ssi-json-ld 0.1.0

Implementation of JSON-LD algorithms for the ssi library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
//! [JSON-LD](https://www.w3.org/TR/json-ld11/) functionality

use std::collections::{BTreeMap as Map, HashMap};
use std::convert::TryFrom;
use std::fmt::Write;
use std::str::FromStr;
use std::sync::Arc;

pub mod error;
pub mod rdf;
pub mod urdna2015;

pub use crate::error::Error;
use crate::rdf::{
    BlankNodeLabel, DataSet, Graph, GraphLabel, IRIOrBlankNodeIdentifier, IRIRef, Lang, Literal,
    Object, Predicate, StringLiteral, Subject, Triple, LANG_STRING_IRI_STR,
};

use async_std::sync::RwLock;
use futures::future::{BoxFuture, FutureExt};
use iref::{Iri, IriBuf};
use json::{array, JsonValue};
use json_ld::{util::AsJson, Document, JsonContext, Loader, ProcessingMode, RemoteDocument};

#[derive(Debug, Clone)]
pub enum RdfDirection {
    I18nDatatype,
    CompoundLiteral,
}

/// <https://w3c.github.io/json-ld-api/#the-jsonldoptions-type>
// Options implemented as needed
#[derive(Debug, Clone)]
pub struct JsonLdOptions {
    /// <https://w3c.github.io/json-ld-api/#dom-jsonldoptions-base>
    pub base: Option<String>,
    /// <https://w3c.github.io/json-ld-api/#dom-jsonldoptions-expandcontext>
    pub expand_context: Option<String>,
    /// <https://w3c.github.io/json-ld-api/#dom-jsonldoptions-ordered>
    pub ordered: bool,
    /// <https://w3c.github.io/json-ld-api/#dom-jsonldoptions-processingmode>
    pub processing_mode: ProcessingMode,
    /// <https://w3c.github.io/json-ld-api/#dom-jsonldoptions-producegeneralizedrdf>
    pub produce_generalized_rdf: Option<bool>,
    /// <https://w3c.github.io/json-ld-api/#dom-jsonldoptions-rdfdirection>
    pub rdf_direction: Option<RdfDirection>,
}

pub const DEFAULT_JSON_LD_OPTIONS: JsonLdOptions = JsonLdOptions {
    base: None,
    expand_context: None,
    ordered: false,
    processing_mode: ProcessingMode::JsonLd1_1,
    produce_generalized_rdf: None,
    rdf_direction: None,
};

impl Default for JsonLdOptions {
    fn default() -> Self {
        DEFAULT_JSON_LD_OPTIONS.clone()
    }
}

/// <https://www.w3.org/TR/json-ld11/#keywords>
pub const AT_BASE: &str = "@base";
pub const AT_CONTAINER: &str = "@container";
pub const AT_CONTEXT: &str = "@context";
pub const AT_DEFAULT: &str = "@default";
pub const AT_DIRECTION: &str = "@direction";
pub const AT_GRAPH: &str = "@graph";
pub const AT_ID: &str = "@id";
pub const AT_IMPORT: &str = "@import";
pub const AT_INCLUDED: &str = "@included";
pub const AT_INDEX: &str = "@index";
pub const AT_JSON: &str = "@json";
pub const AT_LANGUAGE: &str = "@language";
pub const AT_LIST: &str = "@list";
pub const AT_NEST: &str = "@nest";
pub const AT_NONE: &str = "@none";
pub const AT_PREFIX: &str = "@prefix";
pub const AT_PROPAGATE: &str = "@propagate";
pub const AT_PROTECTED: &str = "@protected";
pub const AT_REVERSE: &str = "@reverse";
pub const AT_SET: &str = "@set";
pub const AT_TYPE: &str = "@type";
pub const AT_VALUE: &str = "@value";
pub const AT_VERSION: &str = "@version";
pub const AT_VOCAB: &str = "@vocab";

pub fn is_keyword(string: &str) -> bool {
    matches!(
        string,
        AT_BASE
            | AT_CONTAINER
            | AT_CONTEXT
            | AT_DIRECTION
            | AT_GRAPH
            | AT_ID
            | AT_IMPORT
            | AT_INCLUDED
            | AT_INDEX
            | AT_JSON
            | AT_LANGUAGE
            | AT_LIST
            | AT_NEST
            | AT_NONE
            | AT_PREFIX
            | AT_PROPAGATE
            | AT_PROTECTED
            | AT_REVERSE
            | AT_SET
            | AT_TYPE
            | AT_VALUE
            | AT_VERSION
            | AT_VOCAB
    )
}

pub fn is_iri(string: &str) -> bool {
    IriBuf::new(string).is_ok()
}

pub const CREDENTIALS_V1_CONTEXT: &str = "https://www.w3.org/2018/credentials/v1";
pub const CREDENTIALS_EXAMPLES_V1_CONTEXT: &str = "https://www.w3.org/2018/credentials/examples/v1";
pub const ODRL_CONTEXT: &str = "https://www.w3.org/ns/odrl.jsonld";
pub const SECURITY_V1_CONTEXT: &str = "https://w3id.org/security/v1";
pub const SECURITY_V2_CONTEXT: &str = "https://w3id.org/security/v2";
pub const SCHEMA_ORG_CONTEXT: &str = "https://schema.org/";
pub const DID_V1_CONTEXT: &str = "https://www.w3.org/ns/did/v1";
pub const DID_V1_CONTEXT_NO_WWW: &str = "https://w3.org/ns/did/v1";
pub const W3ID_DID_V1_CONTEXT: &str = "https://w3id.org/did/v1";
pub const DID_RESOLUTION_V1_CONTEXT: &str = "https://w3id.org/did-resolution/v1";
pub const DIF_ESRS2020_CONTEXT: &str = "https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld";
#[deprecated(note = "Use W3ID_ESRS2020_V2_CONTEXT instead")]
pub const ESRS2020_EXTRA_CONTEXT: &str =
    "https://demo.spruceid.com/EcdsaSecp256k1RecoverySignature2020/esrs2020-extra-0.0.jsonld";
pub const W3ID_ESRS2020_V2_CONTEXT: &str =
    "https://w3id.org/security/suites/secp256k1recovery-2020/v2";
pub const LDS_JWS2020_V1_CONTEXT: &str =
    "https://w3c-ccg.github.io/lds-jws2020/contexts/lds-jws2020-v1.json";
pub const W3ID_JWS2020_V1_CONTEXT: &str = "https://w3id.org/security/suites/jws-2020/v1";
pub const W3ID_ED2020_V1_CONTEXT: &str = "https://w3id.org/security/suites/ed25519-2020/v1";
pub const BLOCKCHAIN2021_V1_CONTEXT: &str = "https://w3id.org/security/suites/blockchain-2021/v1";
pub const CITIZENSHIP_V1_CONTEXT: &str = "https://w3id.org/citizenship/v1";
pub const VACCINATION_V1_CONTEXT: &str = "https://w3id.org/vaccination/v1";
pub const TRACEABILITY_CONTEXT: &str = "https://w3id.org/traceability/v1";
pub const REVOCATION_LIST_2020_V1_CONTEXT: &str = "https://w3id.org/vc-revocation-list-2020/v1";
pub const BBS_V1_CONTEXT: &str = "https://w3id.org/security/bbs/v1";
pub const STATUS_LIST_2021_V1_CONTEXT: &str = "https://w3id.org/vc/status-list/2021/v1";
pub const EIP712SIG_V0_1_CONTEXT: &str = "https://demo.spruceid.com/ld/eip712sig-2021/v0.1.jsonld";
pub const EIP712SIG_V1_CONTEXT: &str = "https://w3id.org/security/suites/eip712sig-2021/v1";
pub const PRESENTATION_SUBMISSION_V1_CONTEXT: &str =
    "https://identity.foundation/presentation-exchange/submission/v1";
pub const VDL_V1_CONTEXT: &str = "https://w3id.org/vdl/v1";
pub const WALLET_V1_CONTEXT: &str = "https://w3id.org/wallet/v1";
pub const ZCAP_V1_CONTEXT: &str = "https://w3id.org/zcap/v1";
pub const CACAO_ZCAP_V1_CONTEXT: &str = "https://demo.didkit.dev/2022/cacao-zcap/contexts/v1.json";
pub const JFF_VC_EDU_PLUGFEST_2022_CONTEXT: &str =
    "https://w3c-ccg.github.io/vc-ed/plugfest-1-2022/jff-vc-edu-plugfest-1-context.json";
pub const DID_CONFIGURATION_V0_0_CONTEXT: &str =
    "https://identity.foundation/.well-known/contexts/did-configuration-v0.0.jsonld";
pub const JFF_VC_EDU_PLUGFEST_2022_2_CONTEXT: &str =
    "https://purl.imsglobal.org/spec/ob/v3p0/context.json";

lazy_static::lazy_static! {
    pub static ref CREDENTIALS_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::CREDENTIALS_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(CREDENTIALS_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref CREDENTIALS_EXAMPLES_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::CREDENTIALS_EXAMPLES_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(CREDENTIALS_EXAMPLES_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref ODRL_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::ODRL;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(ODRL_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref SCHEMA_ORG_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::SCHEMA_ORG;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(SCHEMA_ORG_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref SECURITY_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::SECURITY_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(SECURITY_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref SECURITY_V2_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::SECURITY_V2;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(SECURITY_V2_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref DID_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::DID_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(DID_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref DID_RESOLUTION_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::DID_RESOLUTION_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(DID_RESOLUTION_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    /// Deprecated in favor of W3ID_ESRS2020_V2_CONTEXT_DOCUMENT
    pub static ref DIF_ESRS2020_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        #[allow(deprecated)]
        let jsonld = ssi_contexts::DIF_ESRS2020;
        let doc = json::parse(jsonld).unwrap();
        #[allow(deprecated)]
        let iri = Iri::new(DIF_ESRS2020_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref W3ID_ESRS2020_V2_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::W3ID_ESRS2020_V2;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(W3ID_ESRS2020_V2_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    /// Deprecated in favor of W3ID_ESRS2020_V2_CONTEXT_DOCUMENT
    pub static ref ESRS2020_EXTRA_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        #[allow(deprecated)]
        let jsonld = ssi_contexts::ESRS2020_EXTRA;
        let doc = json::parse(jsonld).unwrap();
        #[allow(deprecated)]
        let iri = Iri::new(ESRS2020_EXTRA_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref LDS_JWS2020_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::LDS_JWS2020_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(LDS_JWS2020_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref W3ID_JWS2020_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::W3ID_JWS2020_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(W3ID_JWS2020_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref W3ID_ED2020_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::W3ID_ED2020_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(W3ID_ED2020_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref BLOCKCHAIN2021_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::BLOCKCHAIN2021_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(BLOCKCHAIN2021_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref CITIZENSHIP_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::CITIZENSHIP_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(CITIZENSHIP_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref VACCINATION_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::VACCINATION_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(VACCINATION_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref TRACEABILITY_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::TRACEABILITY_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(TRACEABILITY_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref REVOCATION_LIST_2020_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::REVOCATION_LIST_2020_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(REVOCATION_LIST_2020_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref STATUS_LIST_2021_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::STATUS_LIST_2021_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(STATUS_LIST_2021_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref EIP712SIG_V0_1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::EIP712SIG_V0_1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(EIP712SIG_V0_1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref BBS_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::BBS_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(BBS_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref EIP712SIG_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::EIP712SIG_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(EIP712SIG_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref PRESENTATION_SUBMISSION_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::PRESENTATION_SUBMISSION_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(PRESENTATION_SUBMISSION_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref VDL_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::VDL_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(VDL_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref WALLET_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::WALLET_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(WALLET_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref ZCAP_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::ZCAP_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(ZCAP_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref CACAO_ZCAP_V1_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::CACAO_ZCAP_V1;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(CACAO_ZCAP_V1_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref JFF_VC_EDU_PLUGFEST_2022_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::JFF_VC_EDU_PLUGFEST_2022;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(JFF_VC_EDU_PLUGFEST_2022_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref DID_CONFIGURATION_V0_0_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::DID_CONFIGURATION_V0_0;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(DID_CONFIGURATION_V0_0_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
    pub static ref JFF_VC_EDU_PLUGFEST_2022_2_CONTEXT_DOCUMENT: RemoteDocument<JsonValue> = {
        let jsonld = ssi_contexts::JFF_VC_EDU_PLUGFEST_2022_2;
        let doc = json::parse(jsonld).unwrap();
        let iri = Iri::new(JFF_VC_EDU_PLUGFEST_2022_2_CONTEXT).unwrap();
        RemoteDocument::new(doc, iri)
    };
}

#[derive(Clone)]
pub struct StaticLoader;

impl Loader for StaticLoader {
    type Document = JsonValue;
    fn load<'a>(
        &'a mut self,
        url: Iri<'_>,
    ) -> BoxFuture<'a, Result<RemoteDocument<Self::Document>, json_ld::Error>> {
        let url: IriBuf = url.into();
        async move {
            match url.as_str() {
                CREDENTIALS_V1_CONTEXT => Ok(CREDENTIALS_V1_CONTEXT_DOCUMENT.clone()),
                CREDENTIALS_EXAMPLES_V1_CONTEXT => {
                    Ok(CREDENTIALS_EXAMPLES_V1_CONTEXT_DOCUMENT.clone())
                }
                ODRL_CONTEXT => Ok(ODRL_CONTEXT_DOCUMENT.clone()),
                SECURITY_V1_CONTEXT => Ok(SECURITY_V1_CONTEXT_DOCUMENT.clone()),
                SECURITY_V2_CONTEXT => Ok(SECURITY_V2_CONTEXT_DOCUMENT.clone()),
                SCHEMA_ORG_CONTEXT => Ok(SCHEMA_ORG_CONTEXT_DOCUMENT.clone()),
                DID_V1_CONTEXT | DID_V1_CONTEXT_NO_WWW | W3ID_DID_V1_CONTEXT => {
                    Ok(DID_V1_CONTEXT_DOCUMENT.clone())
                }
                DID_RESOLUTION_V1_CONTEXT => Ok(DID_RESOLUTION_V1_CONTEXT_DOCUMENT.clone()),
                #[allow(deprecated)]
                DIF_ESRS2020_CONTEXT => Ok(DIF_ESRS2020_CONTEXT_DOCUMENT.clone()),
                W3ID_ESRS2020_V2_CONTEXT => Ok(W3ID_ESRS2020_V2_CONTEXT_DOCUMENT.clone()),
                #[allow(deprecated)]
                ESRS2020_EXTRA_CONTEXT => Ok(ESRS2020_EXTRA_CONTEXT_DOCUMENT.clone()),
                LDS_JWS2020_V1_CONTEXT => Ok(LDS_JWS2020_V1_CONTEXT_DOCUMENT.clone()),
                W3ID_JWS2020_V1_CONTEXT => Ok(W3ID_JWS2020_V1_CONTEXT_DOCUMENT.clone()),
                W3ID_ED2020_V1_CONTEXT => Ok(W3ID_ED2020_V1_CONTEXT_DOCUMENT.clone()),
                BLOCKCHAIN2021_V1_CONTEXT => Ok(BLOCKCHAIN2021_V1_CONTEXT_DOCUMENT.clone()),
                CITIZENSHIP_V1_CONTEXT => Ok(CITIZENSHIP_V1_CONTEXT_DOCUMENT.clone()),
                VACCINATION_V1_CONTEXT => Ok(VACCINATION_V1_CONTEXT_DOCUMENT.clone()),
                TRACEABILITY_CONTEXT => Ok(TRACEABILITY_CONTEXT_DOCUMENT.clone()),
                REVOCATION_LIST_2020_V1_CONTEXT => {
                    Ok(REVOCATION_LIST_2020_V1_CONTEXT_DOCUMENT.clone())
                }
                STATUS_LIST_2021_V1_CONTEXT => Ok(STATUS_LIST_2021_V1_CONTEXT_DOCUMENT.clone()),
                EIP712SIG_V0_1_CONTEXT => Ok(EIP712SIG_V0_1_CONTEXT_DOCUMENT.clone()),
                BBS_V1_CONTEXT => Ok(BBS_V1_CONTEXT_DOCUMENT.clone()),
                EIP712SIG_V1_CONTEXT => Ok(EIP712SIG_V1_CONTEXT_DOCUMENT.clone()),
                PRESENTATION_SUBMISSION_V1_CONTEXT => {
                    Ok(PRESENTATION_SUBMISSION_V1_CONTEXT_DOCUMENT.clone())
                }
                VDL_V1_CONTEXT => Ok(VDL_V1_CONTEXT_DOCUMENT.clone()),
                WALLET_V1_CONTEXT => Ok(WALLET_V1_CONTEXT_DOCUMENT.clone()),
                ZCAP_V1_CONTEXT => Ok(ZCAP_V1_CONTEXT_DOCUMENT.clone()),
                CACAO_ZCAP_V1_CONTEXT => Ok(CACAO_ZCAP_V1_CONTEXT_DOCUMENT.clone()),
                JFF_VC_EDU_PLUGFEST_2022_CONTEXT => {
                    Ok(JFF_VC_EDU_PLUGFEST_2022_CONTEXT_DOCUMENT.clone())
                }
                DID_CONFIGURATION_V0_0_CONTEXT => {
                    Ok(DID_CONFIGURATION_V0_0_CONTEXT_DOCUMENT.clone())
                }
                JFF_VC_EDU_PLUGFEST_2022_2_CONTEXT => {
                    Ok(JFF_VC_EDU_PLUGFEST_2022_2_CONTEXT_DOCUMENT.clone())
                }
                _ => Err(json_ld::ErrorCode::LoadingDocumentFailed.into()),
            }
        }
        .boxed()
    }
}

pub type ContextMap = HashMap<String, RemoteDocument<JsonValue>>;

#[derive(Clone)]
pub struct ContextLoader {
    // Specifies if StaticLoader is meant to be checked first.
    static_loader: Option<StaticLoader>,
    // This map holds the optional, additional context objects.  This is where any app-specific context
    // objects would go.  The Arc<RwLock<_>> is necessary because json_ld::Loader trait unfortunately
    // has a method that uses `&mut self`.
    context_map: Option<Arc<RwLock<ContextMap>>>,
}

impl std::fmt::Debug for ContextLoader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("ContextLoader").finish_non_exhaustive()
    }
}

impl ContextLoader {
    /// Constructs an "empty" ContextLoader.
    pub fn empty() -> Self {
        Self {
            static_loader: None,
            context_map: None,
        }
    }
    /// Using the builder pattern, the StaticLoader can be enabled so that contexts are checked
    /// against it before being checked against context_map.
    pub fn with_static_loader(mut self) -> Self {
        self.static_loader = Some(StaticLoader);
        self
    }
    /// Using the builder pattern, the map of additional contexts can be set.  These context objects
    /// will be checked after StaticLoader (if it's specified).  preparsed_context_map should map
    /// the context URLs to their JSON content.
    pub fn with_context_map_from(
        mut self,
        preparsed_context_map: HashMap<String, String>,
    ) -> Result<Self, Error> {
        let context_map = preparsed_context_map
            .iter()
            .map(
                |(url, jsonld)| -> Result<(String, RemoteDocument<JsonValue>), Error> {
                    let doc = json::parse(jsonld)?;
                    let iri = Iri::new(url)?;
                    Ok((url.clone(), RemoteDocument::new(doc, iri)))
                },
            )
            .collect::<Result<HashMap<String, RemoteDocument<JsonValue>>, Error>>()?;
        self.context_map = Some(Arc::new(RwLock::new(context_map)));
        Ok(self)
    }
}

/// The default ContextLoader only uses StaticLoader.
impl std::default::Default for ContextLoader {
    fn default() -> Self {
        Self {
            static_loader: Some(StaticLoader),
            context_map: None,
        }
    }
}

impl Loader for ContextLoader {
    type Document = JsonValue;
    fn load<'a>(
        &'a mut self,
        url: Iri<'_>,
    ) -> BoxFuture<'a, Result<RemoteDocument<Self::Document>, json_ld::Error>> {
        let url_buf: IriBuf = url.into();
        async move {
            if let Some(static_loader) = &mut self.static_loader {
                match static_loader.load(url_buf.as_iri()).await {
                    Ok(x) => {
                        // The url was present in StaticLoader.
                        return Ok(x);
                    }
                    Err(e) => {
                        if e.code() == json_ld::ErrorCode::LoadingDocumentFailed {
                            // This is ok, the url just wasn't found in StaticLoader.  Fall through
                            // to self.context_map.
                        } else {
                            // Any other error is a legit error.
                            return Err(e);
                        }
                    }
                }
            }
            // If we fell through, then try self.context_map.
            if let Some(context_map) = &mut self.context_map {
                context_map
                    .read()
                    .await
                    .get(url_buf.as_str())
                    .cloned()
                    .ok_or_else(|| json_ld::ErrorCode::LoadingDocumentFailed.into())
            } else {
                Err(json_ld::ErrorCode::LoadingDocumentFailed.into())
            }
        }
        .boxed()
    }
}

impl FromStr for RdfDirection {
    type Err = Error;
    fn from_str(purpose: &str) -> Result<Self, Self::Err> {
        match purpose {
            "i18n-datatype" => Ok(Self::I18nDatatype),
            "compound-literal" => Ok(Self::CompoundLiteral),
            _ => Err(Error::UnknownRdfDirection(purpose.to_owned())),
        }
    }
}

impl From<&JsonLdOptions> for json_ld::expansion::Options {
    fn from(options: &JsonLdOptions) -> Self {
        Self {
            ordered: options.ordered,
            processing_mode: options.processing_mode,
            ..Self::default()
        }
    }
}

impl From<&JsonLdOptions> for json_ld::context::ProcessingOptions {
    fn from(options: &JsonLdOptions) -> Self {
        Self {
            processing_mode: options.processing_mode,
            ..Self::default()
        }
    }
}

pub enum JsonValuesIter<'a> {
    Multiple(std::slice::Iter<'a, JsonValue>),
    Single(Option<&'a JsonValue>),
}

impl<'a> Iterator for JsonValuesIter<'a> {
    type Item = &'a JsonValue;
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Multiple(iter) => iter.next(),
            Self::Single(option) => option.take(),
        }
    }
}

impl<'a> From<&'a JsonValue> for JsonValuesIter<'a> {
    fn from(value: &'a JsonValue) -> Self {
        match value {
            JsonValue::Array(array) => Self::Multiple(array.iter()),
            JsonValue::Null => Self::Single(None),
            value => Self::Single(Some(value)),
        }
    }
}

type NodeMap = Map<String, Map<String, JsonValue>>;

pub fn is_blank_node_identifier(value: &JsonValue) -> bool {
    let value_str = match value.as_str() {
        Some(value_str) => value_str,
        None => return false,
    };
    value_str.starts_with("_:")
}

#[derive(Debug, Clone, Default)]
pub struct BlankNodeIdentifierGenerator {
    pub identifier_map: Map<String, JsonValue>,
    pub counter: u64,
}

impl BlankNodeIdentifierGenerator {
    /// <https://w3c.github.io/json-ld-api/#generate-blank-node-identifier>
    pub fn generate(&mut self, identifier: &JsonValue) -> Result<JsonValue, Error> {
        let identifier_str = if identifier.is_null() {
            None
        } else {
            match identifier.as_str() {
                Some(id) => Some(id),
                None => return Err(Error::ExpectedString),
            }
        };
        // 1
        if let Some(identifier_str) = identifier_str {
            if let Some(id) = self.identifier_map.get(identifier_str) {
                return Ok(id.clone());
            }
        }
        // 2
        // Generate new blank unique node identifier
        let blank_node_id_prefix = "_:b";
        let new_id = blank_node_id_prefix.to_string() + &self.counter.to_string();
        self.counter += 1;
        let id = JsonValue::String(new_id);
        // 3
        if let Some(old_id) = identifier_str {
            self.identifier_map.insert(old_id.to_string(), id.clone());
        }
        // 4
        Ok(id)
    }
}

/// <https://w3c.github.io/json-ld-api/#node-map-generation>
pub fn generate_node_map(
    element: JsonValue,
    node_map: &mut NodeMap,
    active_graph: Option<&str>,
    active_subject: Option<&JsonValue>,
    active_property: Option<&str>,
    list: Option<&mut JsonValue>,
    blank_node_id_generator: &mut BlankNodeIdentifierGenerator,
) -> Result<(), Error> {
    let mut null: JsonValue = JsonValue::Null;
    let list = list.unwrap_or(&mut null);
    let mut element_obj = match element {
        JsonValue::Array(array) => {
            // 1
            for item in array.into_iter() {
                // 1.1
                generate_node_map(
                    item,
                    node_map,
                    active_graph,
                    active_subject,
                    active_property,
                    Some(list),
                    blank_node_id_generator,
                )?;
            }
            return Ok(());
        }
        JsonValue::Object(object) => object,
        _ => return Err(Error::ExpectedObject),
    };
    let active_graph = active_graph.unwrap_or(AT_DEFAULT);
    // 2
    let graph = node_map
        .entry(active_graph.to_string())
        .or_insert_with(Map::new);
    let subject_node = match active_subject {
        Some(active_subject) => match active_subject.as_str() {
            Some(subject) => graph.get_mut(subject),
            // On reverse, active subject is a map.
            None => None,
            // https://github.com/w3c/json-ld-api/issues/519
            // None => return Err(Error::ExpectedString),
        },
        None => None,
    };
    // 3
    if let Some(types) = match element_obj.remove(AT_TYPE) {
        Some(JsonValue::Array(items)) => Some(JsonValue::Array(
            items
                .into_iter()
                .map(|item| {
                    // 3.1
                    if is_blank_node_identifier(&item) {
                        blank_node_id_generator.generate(&item)
                    } else {
                        Ok(item)
                    }
                })
                .collect::<Result<Vec<JsonValue>, Error>>()?,
        )),
        Some(item) => {
            // 3.1
            if is_blank_node_identifier(&item) {
                Some(blank_node_id_generator.generate(&item)?)
            } else {
                Some(item)
            }
        }
        None => None,
    } {
        element_obj.insert(AT_TYPE, types);
    }
    // 4
    if element_obj.get(AT_VALUE).is_some() {
        // Reconstruct element since it was partially moved.
        let element = JsonValue::Object(element_obj);
        if let Some(ref mut list) = match list {
            JsonValue::Object(list) => Some(list),
            JsonValue::Null => None,
            _ => return Err(Error::ExpectedObject),
        } {
            // 4.2
            let array = match list.get_mut(AT_LIST) {
                Some(JsonValue::Array(vec)) => vec,
                _ => return Err(Error::ExpectedArrayList),
            };
            array.push(element);
        } else {
            // 4.1
            let subject_node = match subject_node {
                Some(JsonValue::Object(object)) => object,
                _ => return Err(Error::ExpectedObject),
            };
            let active_property = match active_property {
                Some(active_property) => active_property,
                None => return Err(Error::MissingActiveProperty),
            };
            if let Some(entry) = subject_node.get_mut(active_property) {
                // 4.1.2
                let array = match entry {
                    JsonValue::Array(array) => array,
                    _ => return Err(Error::ExpectedArray),
                };
                if !array.contains(&element) {
                    array.push(element);
                }
            } else {
                // 4.1.1
                let entry = array![element];
                subject_node.insert(active_property, entry);
            }
        }
    // 5
    } else if let Some(element_list) = element_obj.remove(AT_LIST) {
        // 5.1
        let mut result: JsonValue = JsonValue::new_object();
        result.insert(AT_LIST, JsonValue::new_array())?;
        // 5.2
        generate_node_map(
            element_list,
            node_map,
            Some(active_graph),
            active_subject,
            active_property,
            Some(&mut result),
            blank_node_id_generator,
        )?;
        if list.is_null() {
            // 5.3
            // Get graph again to avoid multiple mutable borrows
            let graph = match node_map.get_mut(active_graph) {
                Some(graph) => graph,
                None => return Err(Error::MissingGraph),
            };
            let subject_node = match active_subject {
                Some(active_subject) => match active_subject.as_str() {
                    Some(active_subject_str) => graph.get_mut(active_subject_str),
                    None => return Err(Error::ExpectedString),
                },
                None => None,
            };
            let subject_node = match subject_node {
                Some(JsonValue::Object(object)) => object,
                _ => return Err(Error::ExpectedObject),
            };
            let active_property = match active_property {
                Some(active_property) => active_property,
                None => return Err(Error::MissingActiveProperty),
            };
            let entry = match subject_node.get_mut(active_property) {
                Some(JsonValue::Array(array)) => array,
                None => return Err(Error::MissingActivePropertyEntry),
                _ => return Err(Error::ExpectedArray),
            };
            entry.push(result);
        } else {
            // 5.4
            let list = match list {
                JsonValue::Object(list) => list,
                _ => return Err(Error::ExpectedObject),
            };
            let list_entry_of_list = match list.get_mut(AT_LIST) {
                Some(JsonValue::Array(list)) => list,
                _ => return Err(Error::ExpectedArrayList),
            };
            list_entry_of_list.push(result);
        };
    // 6
    } else {
        // 6.1
        let id = match element_obj.remove(AT_ID) {
            Some(id) => {
                if is_blank_node_identifier(&id) {
                    blank_node_id_generator.generate(&id)?
                } else {
                    id
                }
            }
            // 6.2
            None => blank_node_id_generator.generate(&JsonValue::Null)?,
        };
        let id_string = match id.as_str() {
            Some(id) => id,
            None => return Err(Error::ExpectedString),
        };
        // 6.3
        if !graph.contains_key(id_string) {
            let mut object = json::object::Object::new();
            object.insert(AT_ID, id.clone());
            let entry = JsonValue::Object(object);
            graph.insert(id_string.to_string(), entry);
        };
        // 6.4
        let node = match graph.get_mut(id_string) {
            Some(JsonValue::Object(node)) => node,
            _ => return Err(Error::ExpectedObject),
        };
        // 6.5
        if let Some(JsonValue::Object(_)) = active_subject {
            if let Some(active_subject) = active_subject {
                let active_property = match active_property {
                    Some(active_property) => active_property,
                    None => return Err(Error::MissingActiveProperty),
                };
                if let Some(entry) = node.get_mut(active_property) {
                    // 6.5.2
                    let array = match entry {
                        JsonValue::Array(vec) => vec,
                        _ => return Err(Error::ExpectedArray),
                    };
                    if !array.contains(active_subject) {
                        array.push(active_subject.clone());
                    }
                } else {
                    // 6.5.1
                    let entry = array![active_subject.clone()];
                    node.insert(active_property, entry);
                }
            }
        } else {
            // 6.6
            if let Some(active_property) = active_property {
                // 6.6.1
                let mut reference_object = json::object::Object::new();
                reference_object.insert(AT_ID, id.clone());
                let reference = JsonValue::Object(reference_object);
                if list.is_null() {
                    // 6.6.2
                    let subject_node = match active_subject {
                        Some(value) => match value.as_str() {
                            Some(subject) => graph.get_mut(subject),
                            None => return Err(Error::ExpectedString),
                        },
                        None => None,
                    };
                    let subject_node = match subject_node {
                        Some(JsonValue::Object(object)) => object,
                        _ => return Err(Error::ExpectedObject),
                    };
                    if let Some(entry) = subject_node.get_mut(active_property) {
                        // 6.6.2.2
                        let array = match entry {
                            JsonValue::Array(array) => array,
                            _ => return Err(Error::ExpectedArray),
                        };
                        if !array.contains(&reference) {
                            array.push(reference);
                        }
                    } else {
                        // 6.6.2.1
                        let entry = array![reference];
                        subject_node.insert(active_property, entry);
                    }
                } else {
                    // 6.6.3
                    let list = match list {
                        JsonValue::Object(list) => list,
                        _ => return Err(Error::ExpectedObject),
                    };
                    let list_entry_of_list = match list.get_mut(AT_LIST) {
                        Some(JsonValue::Array(list)) => list,
                        _ => return Err(Error::ExpectedArrayList),
                    };
                    list_entry_of_list.push(reference);
                }
            }
        }
        // 6.7
        // Get graph/node again to avoid multiple mutable borrows
        let node = match graph.get_mut(id_string) {
            Some(JsonValue::Object(node)) => node,
            _ => return Err(Error::ExpectedObject),
        };
        if let Some(element_type) = element_obj.remove(AT_TYPE) {
            let element_type_array = match element_type {
                JsonValue::Array(array) => array,
                _ => return Err(Error::ExpectedArray),
            };
            if let Some(node_type) = node.get_mut(AT_TYPE) {
                let node_type_array = match node_type {
                    JsonValue::Array(array) => array,
                    _ => return Err(Error::ExpectedArray),
                };
                for type_ in element_type_array.into_iter() {
                    if !node_type_array.contains(&type_) {
                        node_type_array.push(type_);
                    }
                }
            } else {
                node.insert("type", JsonValue::Array(element_type_array));
            }
        }
        // 6.8
        if let Some(element_index) = element_obj.remove(AT_INDEX) {
            if let Some(node_index) = node.get(AT_INDEX) {
                if node_index != &element_index {
                    return Err(Error::ConflictingIndexes);
                }
            } else {
                node.insert("index", element_index);
            }
        }
        // 6.9, 6.9.2, 6.9.4
        if let Some(reverse_map) = element_obj.remove(AT_REVERSE) {
            // 6.9.1
            let mut object = json::object::Object::new();
            object.insert(AT_ID, id.clone());
            let referenced_node = JsonValue::Object(object);
            // 6.9.3
            let reverse_map_object = match reverse_map {
                JsonValue::Object(object) => object,
                _ => return Err(Error::ExpectedObject),
            };
            // Clone since Object does not have a consuming iterator.
            // https://github.com/maciejhirsz/json-rust/pull/190
            for (property, value) in reverse_map_object.iter() {
                let values = match value {
                    JsonValue::Array(array) => array.to_vec(),
                    value => vec![value.clone()],
                };
                // 6.9.3.1
                for value in values.into_iter() {
                    // 6.9.3.1.1
                    generate_node_map(
                        value,
                        node_map,
                        Some(active_graph),
                        Some(&referenced_node),
                        Some(property),
                        None,
                        blank_node_id_generator,
                    )?;
                }
            }
        }
        // 6.10
        if let Some(graph) = element_obj.remove(AT_GRAPH) {
            let id_string = match id.as_str() {
                Some(id) => id,
                None => return Err(Error::ExpectedString),
            };
            generate_node_map(
                graph,
                node_map,
                Some(id_string),
                None,
                None,
                None,
                blank_node_id_generator,
            )?;
        }
        // 6.11
        if let Some(included) = element_obj.remove(AT_INCLUDED) {
            generate_node_map(
                included,
                node_map,
                Some(active_graph),
                None,
                None,
                None,
                blank_node_id_generator,
            )?;
        }
        // 6.12
        let mut element_property_values: Vec<(String, JsonValue)> = element_obj
            .iter()
            .map(|(prop, value)| (prop.to_owned(), value.to_owned()))
            .collect();
        element_property_values.sort_by(|(property1, _), (property2, _)| property1.cmp(property2));
        for (property_str, value) in element_property_values {
            // 6.12.1
            let mut property = JsonValue::String(property_str.to_string());
            if is_blank_node_identifier(&property) {
                property = blank_node_id_generator.generate(&property)?;
            }
            let property_str = match property.as_str() {
                Some(property) => property,
                None => return Err(Error::ExpectedString),
            };
            // 6.12.2
            // Get graph/node again to avoid multiple mutable borrows
            let graph = match node_map.get_mut(active_graph) {
                Some(graph) => graph,
                None => return Err(Error::MissingGraph),
            };
            let node = match graph.get_mut(id_string) {
                Some(JsonValue::Object(node)) => node,
                _ => return Err(Error::ExpectedObject),
            };
            if node.get(property_str).is_none() {
                node.insert(property_str, JsonValue::new_array());
            }
            // 6.12.3
            generate_node_map(
                value,
                node_map,
                Some(active_graph),
                Some(&id),
                Some(property_str),
                None,
                blank_node_id_generator,
            )?;
        }
    }
    Ok(())
}

/// <https://w3c.github.io/json-ld-api/#deserialize-json-ld-to-rdf-algorithm>
pub fn json_ld_to_rdf(
    node_map: &NodeMap,
    dataset: &mut DataSet,
    options: Option<&JsonLdOptions>,
    blank_node_id_generator: &mut BlankNodeIdentifierGenerator,
) -> Result<(), Error> {
    let options = options.unwrap_or(&DEFAULT_JSON_LD_OPTIONS);
    // 1
    let mut graphs: Vec<(&String, &Map<String, JsonValue>)> = node_map.iter().collect();
    graphs.sort_by(|(name1, _), (name2, _)| name1.cmp(name2));
    for (graph_name, graph) in graphs {
        // 1.1
        // 1.2
        let triples = if graph_name == AT_DEFAULT {
            &mut dataset.default_graph
        } else {
            let graph_name = match GraphLabel::try_from(graph_name.to_string()) {
                Ok(name) => name,
                Err(_) => continue,
            };
            dataset
                .named_graphs
                .entry(graph_name)
                .or_insert_with(Graph::default)
        };
        // 1.3
        let mut nodes: Vec<(&String, &JsonValue)> = graph.iter().collect();
        nodes.sort_by(|(subject1, _), (subject2, _)| subject1.cmp(subject2));
        for (subject, node) in nodes {
            // 1.3.1
            let subject = match Subject::try_from(subject.to_string()) {
                Ok(subject) => subject,
                Err(_) => continue,
            };
            let node_object = match node {
                JsonValue::Object(object) => object,
                _ => return Err(Error::ExpectedObject),
            };
            let mut property_values: Vec<(&str, &JsonValue)> = node_object.iter().collect();
            property_values.sort_by(|(property1, _), (property2, _)| property1.cmp(property2));
            // 1.3.2
            for (property, values) in property_values {
                // 1.3.2.1
                #[allow(clippy::if_same_then_else)]
                if property == AT_TYPE
                // TODO: find out why type is not getting turned into @type here
                || property == "type"
                {
                    for type_ in JsonValuesIter::from(values) {
                        let type_ = match Object::try_from(type_.to_string()) {
                            Ok(type_) => type_,
                            Err(_) => continue,
                        };
                        let triple = Triple {
                            subject: subject.clone(),
                            predicate: Predicate::IRIRef(IRIRef(
                                "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
                            )),
                            object: type_,
                        };
                        triples.add(triple);
                    }
                } else if is_keyword(property) {
                    // 1.3.2.2
                    continue;
                } else if is_blank_node_identifier(&JsonValue::String(property.to_string()))
                    && options.produce_generalized_rdf != Some(true)
                {
                    // 1.3.2.3
                    continue;
                } else {
                    // 1.3.2.4
                    let property = match IRIOrBlankNodeIdentifier::try_from(property.to_string()) {
                        Ok(property) => property,
                        Err(_) => continue,
                    };
                    let predicate = Predicate::try_from(property)?;
                    // 1.3.2.5
                    // property is an IRI or blank node identifier
                    for item in JsonValuesIter::from(values) {
                        // 1.3.2.5.1
                        let mut list_triples = vec![];
                        // 1.3.2.5.2
                        let item = ItemObject::try_from(item)?;
                        if let Some(object) = object_to_rdf(
                            item,
                            &mut list_triples,
                            Some(options),
                            blank_node_id_generator,
                        )? {
                            let triple = Triple {
                                subject: subject.clone(),
                                predicate: predicate.clone(),
                                object,
                            };
                            triples.add(triple);
                        }
                        // 1.3.2.5.3
                        triples.triples.append(&mut list_triples);
                    }
                }
            }
        }
    }
    Ok(())
}

#[derive(Debug, Clone)]
pub enum ItemObject {
    Value(ValueObject),
    List(ListObject),
    Node(NodeObject),
}

/// <https://www.w3.org/TR/json-ld11/#dfn-value-object>
#[derive(Debug, Clone)]
pub struct NodeObject {
    pub id: Option<String>,
    pub entries: json::object::Object,
}

/// <https://www.w3.org/TR/json-ld11/#dfn-list-object>
#[derive(Debug, Clone)]
pub struct ListObject {
    pub list: JsonValue,
    pub index: Option<JsonValue>,
    pub more_properties: json::object::Object,
}

/// <https://www.w3.org/TR/json-ld11/#value-objects>
#[derive(Debug, Clone)]
pub struct ValueObject {
    pub value: JsonValue,
    pub type_: Option<JsonValue>,
    pub language: Option<JsonValue>,
    pub direction: Option<JsonValue>,
    pub index: Option<JsonValue>,
    pub context: Option<JsonValue>,
    pub more_properties: json::object::Object,
}

impl TryFrom<&JsonValue> for ValueObject {
    type Error = Error;
    fn try_from(object: &JsonValue) -> Result<Self, Self::Error> {
        let mut object = match object {
            JsonValue::Object(object) => object,
            _ => return Err(Error::ExpectedObject),
        }
        .clone();
        let value = match object.remove(AT_VALUE) {
            Some(value) => value,
            None => return Err(Error::ExpectedValue),
        };
        let type_ = object.remove(AT_TYPE);
        let type_str = match type_ {
            Some(ref type_) => match type_.as_str() {
                Some(type_str) => Some(type_str),
                None => return Err(Error::ExpectedString),
            },
            None => None,
        };
        // TODO:
        // - The value associated with the @type key MUST be a term, an IRI, a compact IRI, a string which can be turned into an IRI using the vocabulary mapping, @json, or null.
        // - The value associated with the @language key MUST have the lexical form described in [BCP47], or be null.
        if (value.is_array() || value.is_object()) && type_str != Some(AT_JSON) {
            return Err(Error::ExpectedValueTypeJson);
        }
        let language = object.remove(AT_LANGUAGE);
        let direction = object.remove(AT_DIRECTION);
        if let Some(ref direction) = direction {
            if !direction.is_null() {
                match direction.as_str() {
                    Some("ltr") | Some("rtl") => {}
                    _ => return Err(Error::UnrecognizedDirection),
                }
            }
        }
        let index = object.remove(AT_INDEX);
        if let Some(ref index) = index {
            if !index.is_string() {
                return Err(Error::ExpectedStringIndex);
            }
        }
        let context = object.remove(AT_CONTEXT);
        if type_.is_some() && (language.is_some() || direction.is_some()) {
            return Err(Error::ValueObjectLanguageType);
        }
        for (key, _) in object.iter() {
            if is_keyword(key) {
                return Err(Error::UnexpectedKeyword);
            }
            if is_iri(key) {
                return Err(Error::UnexpectedIRI);
            }
        }
        Ok(Self {
            value,
            type_,
            language,
            direction,
            index,
            context,
            more_properties: object,
        })
    }
}

// https://www.w3.org/TR/json-ld11/#node-objects
impl TryFrom<&JsonValue> for NodeObject {
    type Error = Error;
    fn try_from(object: &JsonValue) -> Result<Self, Self::Error> {
        let object = match object {
            JsonValue::Object(object) => object,
            _ => return Err(Error::ExpectedObject),
        };
        if object.get(AT_VALUE).is_some() {
            return Err(Error::UnexpectedValue);
        }
        if object.get(AT_LIST).is_some() {
            return Err(Error::UnexpectedList);
        }
        if object.get(AT_SET).is_some() {
            return Err(Error::UnexpectedSet);
        }
        let mut object = object.clone();
        // TODO:
        // - it is not the top-most map in the JSON-LD document consisting of no other entries than @graph and @context,
        // - it is not a graph object.
        // - All keys which are not IRIs, compact IRIs, terms valid in the active context, or one of the following keywords (or alias of such a keyword) MUST be ignored when processed: @context, @id, @included, @graph, @nest, @type, @reverse, or @index
        // - Keys in a node object that are not keywords MAY expand to an IRI using the active context. The values associated with keys that expand to an IRI MUST be one of the following: string, number, true, false, null, node object, graph object, value object, list object, set object, an array of zero or more of any of the possibilities above, a language map, an index map, an included block an id map, or a type map
        if let Some(_context) = object.get(AT_CONTEXT) {
            // TODO
        }
        let id = match object.remove(AT_ID) {
            None => None,
            Some(value) => {
                let id_str = match value.as_str() {
                    Some(id_str) => id_str,
                    None => return Err(Error::ExpectedString),
                };
                // TODO: MUST be an IRI reference, or a compact IRI (including blank node identifiers
                Some(id_str.to_owned())
            }
        };
        if let Some(_graph) = object.get(AT_GRAPH) {
            // TODO
        }
        if let Some(_type_) = object.get(AT_TYPE) {
            // TODO
        }
        if let Some(_reverse) = object.get(AT_REVERSE) {
            // TODO
        }
        if let Some(_included) = object.get(AT_INCLUDED) {
            // TODO
        }
        if let Some(index) = object.get(AT_INDEX) {
            if !index.is_string() {
                return Err(Error::ExpectedString);
            }
        }
        if let Some(_nest) = object.get(AT_NEST) {
            // TODO
        }

        Ok(Self {
            id,
            entries: object,
        })
    }
}

// https://www.w3.org/TR/json-ld11/#lists-and-sets
impl TryFrom<&JsonValue> for ListObject {
    type Error = Error;
    fn try_from(object: &JsonValue) -> Result<Self, Self::Error> {
        let mut object = match object {
            JsonValue::Object(object) => object,
            _ => return Err(Error::ExpectedObject),
        }
        .clone();
        let list = match object.remove(AT_LIST) {
            Some(value) => value,
            None => return Err(Error::ExpectedList),
        };
        let index = object.remove(AT_INDEX);
        for (key, _) in object.iter() {
            if is_keyword(key) {
                return Err(Error::UnexpectedKeyword);
            }
            if is_iri(key) {
                return Err(Error::UnexpectedIRI);
            }
        }
        for item in JsonValuesIter::from(&list) {
            match item {
                JsonValue::String(_)
                | JsonValue::Number(_)
                | JsonValue::Short(_)
                | JsonValue::Boolean(_)
                | JsonValue::Null => {}
                JsonValue::Array(_) => {
                    return Err(Error::UnexpectedNestedArray);
                }
                JsonValue::Object(_) => {
                    ItemObject::try_from(item)?;
                }
            }
        }
        Ok(Self {
            list,
            index,
            more_properties: object,
        })
    }
}

impl TryFrom<&JsonValue> for ItemObject {
    type Error = Error;
    fn try_from(value: &JsonValue) -> Result<Self, Self::Error> {
        Ok(if value.has_key(AT_LIST) {
            Self::List(ListObject::try_from(value)?)
        } else if value.has_key(AT_VALUE) {
            Self::Value(ValueObject::try_from(value)?)
        } else {
            Self::Node(NodeObject::try_from(value)?)
        })
    }
}

/// <https://w3c.github.io/json-ld-api/#object-to-rdf-conversion>
pub fn object_to_rdf(
    item: ItemObject,
    list_triples: &mut Vec<Triple>,
    options: Option<&JsonLdOptions>,
    blank_node_id_generator: &mut BlankNodeIdentifierGenerator,
) -> Result<Option<Object>, Error> {
    let options = options.unwrap_or(&DEFAULT_JSON_LD_OPTIONS);
    let item = match item {
        ItemObject::Node(node) => {
            // 1
            let id = match match node.id {
                Some(id) => IRIOrBlankNodeIdentifier::try_from(id).ok(),
                None => None,
            } {
                Some(id) => id,
                None => return Ok(None),
            };
            // 2
            return Ok(Some(Object::from(id)));
        }
        ItemObject::List(list) => {
            // 3
            return Ok(Some(list_to_rdf(
                list.list,
                list_triples,
                Some(options),
                blank_node_id_generator,
            )?));
        }
        ItemObject::Value(value) => value,
    };
    // 4
    let mut value = item.value;
    // 5
    let datatype = item.type_.unwrap_or(JsonValue::Null);
    // 6
    let mut datatype = if datatype.is_null() {
        None
    } else {
        let datatype = match datatype.as_str() {
            Some(datatype) => datatype,
            None => return Ok(None),
        };
        // TODO: use IRI here rather than IRIRef
        if datatype != AT_JSON && IRIRef::try_from(datatype.to_string()).is_err() {
            return Ok(None);
        }
        Some(datatype)
    };
    // 7
    if let Some(ref language) = item.language {
        let language_str = match language.as_str() {
            Some(language_str) => language_str,
            None => return Ok(None),
        };
        if Lang::from_str(language_str).is_err() {
            return Ok(None);
        }
    }
    // 8
    if datatype == Some(AT_JSON) {
        value = JsonValue::String(canonicalize_json(&value));
        datatype = Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#JSON");
    }
    // 9
    if let Some(value_bool) = match value {
        JsonValue::Boolean(true) => Some("true"),
        JsonValue::Boolean(false) => Some("false"),
        _ => None,
    } {
        value = JsonValue::String(value_bool.to_string());
        if datatype.is_none() {
            datatype = Some("http://www.w3.org/2001/XMLSchema#boolean");
        }
    } else if let Some(num) = value.as_number() {
        let num_f64 = f64::from(num);
        if num_f64 % 1f64 != 0f64
            || num_f64 >= 1e21
            || datatype == Some("http://www.w3.org/2001/XMLSchema#double")
        {
            // 10
            // https://w3c.github.io/json-ld-api/#data-round-tripping
            // https://www.w3.org/TR/xmlschema11-2/#f-doubleCanmap
            let num = format!("{:.15E}", num_f64);
            // Replace (\d)0*E with $1E
            // TODO: optimize
            let mut num_vec: Vec<char> = num.chars().collect();
            let mut i = match num_vec.iter().position(|x| *x == 'E') {
                Some(i) => i - 1,
                None => return Err(Error::SerializeDouble),
            };
            while i > 1 && num_vec.get(i) == Some(&'0') && num_vec.get(i - 1) != Some(&'.') {
                num_vec.remove(i);
                i -= 1;
            }
            let num: String = num_vec.iter().collect();
            value = JsonValue::String(num);
            if datatype.is_none() {
                datatype = Some("http://www.w3.org/2001/XMLSchema#double");
            }
        } else {
            // 11
            let num = if num_f64 == -0.0 {
                "0".to_string()
            } else {
                format!("{:.0}", num_f64)
            };
            value = JsonValue::String(num);
            if datatype.is_none() {
                datatype = Some("http://www.w3.org/2001/XMLSchema#integer");
            }
        }
    } else if datatype.is_none() {
        // 12
        datatype = Some(match item.language.is_some() {
            true => "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString",
            false => "http://www.w3.org/2001/XMLSchema#string",
        });
    }
    // 13
    let value_string = match value.as_str() {
        Some(val) => val.to_string(),
        None => return Err(Error::ExpectedString),
    };
    let language = match item.language {
        Some(language) => language
            .as_str()
            .map(|language_str| language_str.to_string()),
        None => None,
    };
    let literal;
    if let (Some(direction), Some(rdf_direction)) = (item.direction, options.rdf_direction.as_ref())
    {
        // 13.1
        let language = language.unwrap_or_default();
        let direction = match direction.as_str() {
            Some(direction) => direction,
            None => return Err(Error::ExpectedString),
        };
        match rdf_direction {
            // 13.2
            RdfDirection::I18nDatatype => {
                let datatype_string =
                    "https://www.w3.org/ns/i18n#".to_string() + &language + "_" + direction;
                literal = Literal::Typed {
                    string: StringLiteral(value_string),
                    type_: IRIRef(datatype_string),
                };
            }
            // 13.3
            RdfDirection::CompoundLiteral => {
                // 13.3.1
                let literal_value = blank_node_id_generator.generate(&JsonValue::Null)?;
                let literal_string = match literal_value.as_str() {
                    Some(value) => value.to_string(),
                    None => return Err(Error::ExpectedString),
                };
                literal = Literal::String {
                    string: StringLiteral(literal_string.clone()),
                };
                // 13.3.2
                list_triples.push(Triple {
                    subject: Subject::BlankNodeLabel(BlankNodeLabel(literal_string.clone())),
                    predicate: Predicate::IRIRef(IRIRef(
                        "http://www.w3.org/1999/02/22-rdf-syntax-ns#value".to_string(),
                    )),
                    // TODO: what type is value supposed to be?
                    object: Object::try_from(value.to_string())?,
                });
                // 13.3.3
                if !language.is_empty() {
                    list_triples.push(Triple {
                        subject: Subject::BlankNodeLabel(BlankNodeLabel(literal_string.clone())),
                        predicate: Predicate::IRIRef(IRIRef(
                            "http://www.w3.org/1999/02/22-rdf-syntax-ns#language".to_string(),
                        )),
                        // TODO: is language a literal?
                        object: Object::try_from(language)?,
                    });
                }
                // 13.3.4
                list_triples.push(Triple {
                    subject: Subject::BlankNodeLabel(BlankNodeLabel(literal_string)),
                    predicate: Predicate::IRIRef(IRIRef(
                        "http://www.w3.org/1999/02/22-rdf-syntax-ns#direction".to_string(),
                    )),
                    // TODO: is direction a literal?
                    object: Object::try_from(direction.to_string())?,
                });
            }
        }
    } else {
        let datatype_string = match datatype {
            Some(val) => val.to_string(),
            None => return Err(Error::ExpectedString),
        };
        // 14
        literal = if let Some(language) = language {
            if datatype.is_some() && datatype != Some(LANG_STRING_IRI_STR) {
                return Err(Error::ExpectedLangStringType);
            }
            let lang = Lang::from_str(language.as_str())?;
            Literal::LangTagged {
                string: StringLiteral(value_string),
                lang,
            }
        } else if datatype == Some("http://www.w3.org/2001/XMLSchema#string") {
            Literal::String {
                string: StringLiteral(value_string),
            }
        } else {
            Literal::Typed {
                string: StringLiteral(value_string),
                type_: IRIRef(datatype_string),
            }
        };
    }
    // 15
    Ok(Some(Object::Literal(literal)))
}

/// <https://w3c.github.io/json-ld-api/#dfn-canonical-lexical-form>
pub fn canonicalize_json(value: &JsonValue) -> String {
    // TODO: make sure it follows RFC 8785 (JCS)
    // Converting to serde Value loses the order of keys, and serde_jcs does not provide from_str
    // functions. So we just use serde_jcs for the number serialization.
    match value {
        JsonValue::Null => "null".to_string(),
        JsonValue::Boolean(true) => "true".to_string(),
        JsonValue::Boolean(false) => "false".to_string(),
        JsonValue::Short(short) => canonicalize_json_string(short.as_str()),
        JsonValue::String(string) => canonicalize_json_string(string),
        JsonValue::Number(_) => canonicalize_json_number(value),
        JsonValue::Array(array) => {
            let mut string = "[".to_string();
            let mut first = true;
            for value in array {
                if first {
                    first = false;
                } else {
                    string.push(',');
                }
                string += &canonicalize_json(value);
            }
            string + "]"
        }
        JsonValue::Object(object) => {
            let mut entries = object.iter().collect::<Vec<(&str, &JsonValue)>>();
            entries.sort_by_cached_key(|(key, _)| key.encode_utf16().collect::<Vec<u16>>());
            let mut string = "{".to_string();
            let mut first = true;
            for (key, value) in entries {
                if first {
                    first = false;
                } else {
                    string.push(',');
                }
                string.push_str(&canonicalize_json_string(key));
                string.push(':');
                string.push_str(&canonicalize_json(value));
            }
            string.push('}');
            string
        }
    }
}

/// <https://www.w3.org/TR/json-ld11/#the-rdf-json-datatype>
pub fn canonicalize_json_string(string: &str) -> String {
    let mut out = String::with_capacity(string.len() + 6);
    out.push('"');
    for c in string.chars() {
        match c {
            '\t' => out.push_str("\\t"),
            '\x08' => out.push_str("\\b"),
            '\x0c' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\x00'..='\x1f' => {
                let bytes: u32 = c.into();
                let _ = write!(out, "\\u{:04x}", bytes);
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

pub fn canonicalize_json_number(num: &JsonValue) -> String {
    // This way seems to involve less of precision that converting to f64 first.
    let num_str = num.dump();
    if let Ok(value) = serde_json::from_str::<serde_json::Value>(&num_str) {
        if let Ok(out) = serde_jcs::to_string(&value) {
            return out;
        }
    }
    num_str
}

/// <https://w3c.github.io/json-ld-api/#list-to-rdf-conversion>
pub fn list_to_rdf(
    list: JsonValue,
    list_triples: &mut Vec<Triple>,
    options: Option<&JsonLdOptions>,
    blank_node_id_generator: &mut BlankNodeIdentifierGenerator,
) -> Result<Object, Error> {
    let list = match list {
        JsonValue::Array(array) => array,
        _ => return Err(Error::ExpectedArray),
    };
    if list.is_empty() {
        // 1
        return Ok(Object::IRIRef(IRIRef(
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil".to_string(),
        )));
    }
    // 2
    let bnodes = list
        .iter()
        .map(|_| blank_node_id_generator.generate(&JsonValue::Null))
        .collect::<Result<Vec<JsonValue>, Error>>()?;
    // 3
    let mut bnodes_iter = bnodes.iter().peekable();
    let mut list_iter = list.iter();
    while let (Some(subject), Some(item)) = (bnodes_iter.next(), list_iter.next()) {
        let subject = Subject::try_from(subject.to_string())?;
        // 3.1
        let mut embedded_triples = vec![];
        // 3.2
        let item = ItemObject::try_from(item)?;
        let object = object_to_rdf(
            item,
            &mut embedded_triples,
            options,
            blank_node_id_generator,
        )?;
        // 3.3
        if let Some(object) = object {
            let triple = Triple {
                subject: subject.clone(),
                predicate: Predicate::IRIRef(IRIRef(
                    "http://www.w3.org/1999/02/22-rdf-syntax-ns#first".to_string(),
                )),
                object,
            };
            list_triples.push(triple);
        }
        // 3.4
        let rest = match bnodes_iter.peek() {
            Some(rest) => Object::try_from(rest.to_string())?,
            None => Object::IRIRef(IRIRef(
                "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil".to_string(),
            )),
        };
        list_triples.push(Triple {
            subject: subject.clone(),
            predicate: Predicate::IRIRef(IRIRef(
                "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest".to_string(),
            )),
            object: rest,
        });
        // 3.5
        list_triples.append(&mut embedded_triples);
    }
    // 4
    let first = match bnodes.first() {
        Some(first) => Object::try_from(first.to_string())?,
        None => Object::IRIRef(IRIRef(
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil".to_string(),
        )),
    };
    Ok(first)
}

pub async fn expand_json<T>(
    json: &str,
    more_contexts_json: Option<&String>,
    lax: bool,
    options: Option<&JsonLdOptions>,
    loader: &mut T,
) -> Result<Vec<JsonValue>, Error>
where
    T: Loader<Document = JsonValue> + std::marker::Send + Sync,
{
    let options = options.unwrap_or(&DEFAULT_JSON_LD_OPTIONS);
    let base = match options.base {
        Some(ref iri) => Some(iref::Iri::new(iri)?),
        None => None,
    };
    let mut context: JsonContext = JsonContext::new(base);
    if let Some(ref url) = options.expand_context {
        use json_ld::context::Loader;
        use json_ld::context::Local;
        let iri = IriBuf::new(url).unwrap();
        let local_context = loader.load_context(iri.as_iri()).await?.into_context();
        context = local_context
            .process_with(&context, loader, base, options.into())
            .await?
            .into_inner();
    }
    let mut doc = json::parse(json)?;
    if let Some(more_contexts_json) = more_contexts_json {
        let more_contexts = json::parse(more_contexts_json)?;
        // Merge additional contexts into document. This is needed for serializing proofs, since
        // they typically inherit the context of the parent credential/presentation rather than
        // including their own.
        // TODO: handle this with the expandContext option instead
        let doc_object = match doc {
            JsonValue::Object(ref mut object) => object,
            _ => return Err(Error::ExpectedObject),
        };
        let mut contexts_merged = Vec::new();
        if let Some(doc_contexts) = doc_object.remove(AT_CONTEXT) {
            for item in JsonValuesIter::from(&doc_contexts) {
                contexts_merged.push(item.clone());
            }
        }
        for item in JsonValuesIter::from(&more_contexts) {
            contexts_merged.push(item.clone());
        }
        doc_object.insert(AT_CONTEXT, JsonValue::Array(contexts_merged));
    }
    let mut expansion_options = json_ld::expansion::Options::from(options);
    use json_ld::expansion::Policy;
    expansion_options.policy = if lax {
        // RDF Deserialization tests expect standard behavior of dropping
        // properties
        Policy::Standard
    } else {
        // VC HTTP API Test Suite expect properties to not be silently dropped.
        // More info: https://github.com/timothee-haudebourg/json-ld/issues/13
        Policy::Strict
    };
    expansion_options.ordered = false;
    let expanding = doc.expand_with(base, &context, loader, expansion_options);
    let expanded_doc = expanding.await?;

    let documents = expanded_doc.iter().map(|item| item.as_json()).collect();

    Ok(documents)
}

/// <https://w3c.github.io/json-ld-api/#dom-jsonldprocessor-tordf>
pub async fn json_to_dataset<T>(
    json: &str,
    more_contexts_json: Option<&String>,
    lax: bool,
    options: Option<&JsonLdOptions>,
    loader: &mut T,
) -> Result<DataSet, Error>
where
    T: Loader<Document = JsonValue> + std::marker::Send + Sync,
{
    let options = options.unwrap_or(&DEFAULT_JSON_LD_OPTIONS);
    let expanded_doc = expand_json(json, more_contexts_json, lax, Some(options), loader).await?;
    let mut node_map = Map::new();
    node_map.insert(AT_DEFAULT.to_string(), Map::new());
    let mut blank_node_id_generator = BlankNodeIdentifierGenerator::default();
    for object in expanded_doc {
        generate_node_map(
            object,
            &mut node_map,
            None,
            None,
            None,
            None,
            &mut blank_node_id_generator,
        )?;
    }
    let mut dataset = DataSet::default();
    json_ld_to_rdf(
        &node_map,
        &mut dataset,
        Some(options),
        &mut blank_node_id_generator,
    )?;
    Ok(dataset)
}

#[cfg(test)]
mod tests {
    use super::*;
    use json_ld::FsLoader;

    async fn test_to_rdf(obj: &json::object::Object) -> Result<(), Error> {
        use std::fs;
        use std::path::PathBuf;
        let base1 = "https://w3c.github.io/json-ld-api/tests/".to_string();
        let base = "json-ld-api/tests/";
        let input = obj.get("input").unwrap().as_str().unwrap();
        let input = base.to_string() + input;
        let mut base_iri = "https://w3c.github.io/".to_string() + &input;
        let input_path = PathBuf::from("../".to_string() + &input);
        let in_str = fs::read_to_string(&input_path).unwrap();
        let mut loader = FsLoader::new();
        loader.mount(
            Iri::new("https://w3c.github.io/json-ld-api").unwrap(),
            "../json-ld-api",
        );
        let mut ld_options = DEFAULT_JSON_LD_OPTIONS.clone();
        if let Some(JsonValue::Object(options)) = obj.get("option") {
            if let Some(mode) = options.get("processingMode") {
                let mode_str = match mode.as_str() {
                    Some(mode_str) => mode_str,
                    None => return Err(Error::ExpectedString),
                };
                ld_options.processing_mode = ProcessingMode::try_from(mode_str)
                    .map_err(|_| Error::UnknownProcessingMode(mode_str.to_owned()))?;
            }
            if let Some(mode) = options.get("rdfDirection") {
                ld_options.rdf_direction = Some(RdfDirection::from_str(mode.as_str().unwrap())?);
            }
            if let Some(base) = options.get("base") {
                base_iri = base.as_str().unwrap().to_owned();
            }
            if let Some(ctx) = options.get("expandContext") {
                use iref::IriRef;
                let ctx = ctx.as_str().unwrap();
                let iri_ref = IriRef::new(ctx).unwrap();
                let base1 = Iri::new(&base1).unwrap();
                ld_options.expand_context = Some(iri_ref.resolved(base1).to_string());
            }
        }
        ld_options.base = Some(base_iri);
        // Normalize input and input for comparison
        let result = json_to_dataset(&in_str, None, true, Some(&ld_options), &mut loader)
            .await
            .and_then(|dataset| urdna2015::normalize(&dataset))
            .and_then(|dataset| dataset.to_nquads());
        if let Some(output) = obj.get("expect") {
            let output = output.as_str().unwrap();
            let output_path = PathBuf::from("../".to_string() + base + output);
            let output_string = fs::read_to_string(&output_path).unwrap();
            let output_dataset = DataSet::from_str(&output_string)?;
            let output_dataset_normalized = urdna2015::normalize(&output_dataset)?;
            let output_string_normalized = output_dataset_normalized.to_nquads()?;
            let nquads = result?;
            if &nquads != &output_string_normalized {
                return Err(Error::ExpectedOutput(output_string_normalized, nquads));
            }
        } else if obj.get("expectErrorCode").is_some() {
            if result.is_ok() {
                return Err(Error::ExpectedFailure);
            }
        } else {
            result?;
        }
        Ok(())
    }

    #[async_std::test]
    /// <https://w3c.github.io/json-ld-api/tests/toRdf-manifest.html>
    async fn to_rdf_test_suite() {
        let manifest_str = include_str!("../../json-ld-api/tests/toRdf-manifest.jsonld");
        let manifest = json::parse(manifest_str).unwrap();
        let manifest_obj = match manifest {
            JsonValue::Object(obj) => Ok(obj),
            _ => Err(Error::ExpectedObject),
        }
        .unwrap();
        let case = std::env::args().nth(2);
        let sequence = manifest_obj.get("sequence").unwrap();
        let mut passed = 0;
        let mut total = 0;
        for test in sequence.members() {
            let obj = match test {
                JsonValue::Object(obj) => obj,
                _ => panic!("expected object"),
            };
            let id = obj.get(AT_ID).unwrap().as_str().unwrap();
            if let Some(ref case) = case {
                if case != id {
                    continue;
                }
            }
            // Explanation of skipped tests:
            // https://github.com/timothee-haudebourg/json-ld/issues/8#issuecomment-916490211
            let skip = match id {
                "#tli12" => {
                    // "Tests list elements expanded to IRIs with a bad @base.",
                    // Relevant issue: https://github.com/w3c/json-ld-api/issues/533
                    true
                }
                "#te122" => {
                    // "Processors SHOULD generate a warning and MUST ignore IRIs having the form of a keyword."
                    // Relevant issue: https://github.com/w3c/json-ld-api/issues/480
                    true
                }
                _ => false,
            };
            if skip {
                eprintln!("test {}: skipping", id);
                continue;
            }
            if let Some(requires) = obj.get("requires") {
                if requires.as_str() == Some("GeneralizedRdf") {
                    eprintln!("test {}: skipping: requires Generalized RDF", id);
                    continue;
                }
            }
            if let Some(JsonValue::Object(options)) = obj.get("option") {
                if options.get("normative") == Some(&JsonValue::Boolean(false)) {
                    eprintln!("test {}: skipping: non-normative", id);
                    continue;
                }
                if let Some(spec_version) = options.get("specVersion") {
                    let spec_version = spec_version.as_str().unwrap();
                    if spec_version != "json-ld-1.1" {
                        eprintln!("test {}: skipping: spec version '{}'", id, spec_version);
                        continue;
                    }
                }
            }
            total += 1;
            if let Err(err) = test_to_rdf(obj).await {
                if let Error::ExpectedOutput(expected, found) = err {
                    let changes = difference::Changeset::new(&found, &expected, "\n");
                    eprintln!("test {}: failed. diff:\n{}", id, changes);
                } else {
                    eprintln!("test {}: failed: {:?}", id, err);
                }
            } else {
                passed += 1;
            }
        }
        assert!(total > 0);
        assert_eq!(passed, total);
    }
}