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
//! Describes the top-level document structure.
use std::{marker::PhantomData, rc::Rc};
use self_cell::self_cell;
use crate::{
HasSpan, Parser, Span,
attributes::Attrlist,
blocks::{Block, ContentModel, IsBlock, Preamble, parse_utils::parse_blocks_until},
document::{
Author, Catalog, Docinfo, DocinfoLocation, Header, InterpretedValue, TocConfig, TocMode,
},
internal::{debug::DebugSliceReference, opaque_iter::opaque_slice_iter},
parser::{
CatalogResolver, DeferredWarning, InlineSubstitutionRenderer, Origin, ReferenceResolver,
ReferenceWarning, ReferenceWarnings, ResolvedAttributes, SourceMap,
},
strings::CowStr,
warnings::{Warning, WarningType},
};
opaque_slice_iter! {
/// An iterator over a [`Document`]'s parse-time [`Warning`]s, returned by
/// [`Document::warnings`].
pub struct Warnings<'a> yielding Warning<'a>;
}
/// A document represents the top-level block element in AsciiDoc. It consists
/// of an optional document header and either a) one or more sections preceded
/// by an optional preamble or b) a sequence of top-level blocks only.
///
/// The document can be configured using a document header. The header is not a
/// block itself, but contributes metadata to the document, such as the document
/// title and document attributes.
///
/// The `Document` structure is a self-contained package of the original content
/// that was parsed and the data structures that describe that parsed content.
/// The API functions on this struct can be used to understand the parse
/// results.
#[derive(Eq, PartialEq)]
pub struct Document<'src> {
internal: Internal,
_phantom: PhantomData<&'src ()>,
}
/// Internal dependent struct containing the actual data members that reference
/// the owned source.
#[derive(Debug, Eq, PartialEq)]
struct InternalDependent<'src> {
header: Header<'src>,
blocks: Vec<Block<'src>>,
source: Span<'src>,
warnings: Vec<Warning<'src>>,
source_map: SourceMap,
catalog: Catalog,
attributes: ResolvedAttributes,
toc: TocConfig,
docinfo: Docinfo,
}
self_cell! {
/// Internal implementation struct containing the actual data members.
struct Internal {
owner: String,
#[covariant]
dependent: InternalDependent,
}
impl {Debug, Eq, PartialEq}
}
impl<'src> Document<'src> {
pub(crate) fn parse(
source: &str,
source_map: SourceMap,
preprocessor_warnings: Vec<DeferredWarning>,
parser: &mut Parser,
) -> Self {
let owned_source = source.to_string();
// Publish the source map on the parser for the duration of the parse so
// an AsciiDoc table cell can map a position in this (preprocessed)
// source back to the file and line it originally came from – needed to
// report an unresolved `include::` directive inside such a cell against
// the correct cursor. The document keeps its own copy of the map, so
// clear the parser's reference once parsing completes.
let source_map = Rc::new(source_map);
parser.source_map = Some(Rc::clone(&source_map));
let internal = Internal::new(owned_source, |owned_src| {
let source = Span::new(owned_src);
let mi = Header::parse(source, parser);
let after_header = mi.item.after;
parser.sectnumlevels = parser
.attribute_value("sectnumlevels")
.as_maybe_str()
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(3);
let header = mi.item.item;
let mut warnings = mi.warnings;
// Derive the `iconsdir` default from `imagesdir` (`{imagesdir}/icons`)
// now that the header is fully parsed, unless the author set
// `iconsdir` explicitly in the header (in which case it wins).
let iconsdir_set_in_header = header.attributes().any(|a| a.name().data() == "iconsdir");
parser.apply_iconsdir_default(iconsdir_set_in_header);
// Unfreeze any "flexible" attribute (`sectnums`) that was supplied
// *set* through the API, now that the header is parsed, so the body
// may still toggle it. An API-supplied *unset* stays locked. This
// mirrors the timing of Asciidoctor's `finalize_header` (see
// `Parser::unlock_flexible_attributes`).
parser.unlock_flexible_attributes();
let mut maw_blocks = parse_blocks_until(after_header, |_, _| false, parser);
if !maw_blocks.warnings.is_empty() {
warnings.append(&mut maw_blocks.warnings);
}
// A top-level section that skips level 1 (e.g. a `= Document Title`
// followed directly by a level-2 heading) is out of sequence, but
// the section-child boundary check only sees sections nested under
// another section; flag the document-root case here.
//
// Skipped for a title-less document or when `fragment` is set – both
// are treated as section fragments with no level-0 root to sequence
// against – and when `leveloffset` is in effect, since a shifted (or
// clamped) effective level no longer reflects the authored level
// relationship and any degenerate offset is reported on its own.
if header.title_source().is_some()
&& !parser.is_attribute_set("fragment")
&& parser.level_offset() == 0
{
warnings.append(&mut crate::blocks::root_section_sequence_warnings(
&maw_blocks.item.item,
));
}
// Warnings recorded while replacing attribute references (e.g. a
// reference to a missing attribute under `attribute-missing=warn`)
// are collected on the parser, where only owned offsets – not
// borrowed spans – can live. Now that the document's owned source is
// available, turn each one back into a spanned `Warning`.
let root = Span::new(owned_src);
// Warnings raised during preprocessing (e.g. an unresolved include
// directive) are carried the same way and reconstituted here.
for pw in preprocessor_warnings {
warnings.push(Warning {
source: root.slice(pw.offset..pw.offset + pw.len),
warning: pw.warning,
origin: pw.origin,
});
}
for sw in parser.take_substitution_warnings() {
warnings.push(Warning {
source: root.slice(sw.offset..sw.offset + sw.len),
warning: sw.warning,
origin: None,
});
}
let mut blocks = maw_blocks.item.item;
let mut has_content_blocks = false;
let mut preamble_split_index: Option<usize> = None;
// Only look for preamble content if document has a title.
// Asciidoctor only creates a preamble when there's a document title.
if header.title().is_some() {
for (index, block) in blocks.iter().enumerate() {
match block {
Block::DocumentAttribute(_) => (),
Block::Section(_) => {
if has_content_blocks {
preamble_split_index = Some(index);
}
break;
}
_ => {
has_content_blocks = true;
}
}
}
}
if let Some(index) = preamble_split_index {
let mut section_blocks = blocks.split_off(index);
let preamble = Preamble::from_blocks(blocks, after_header);
section_blocks.insert(0, Block::Preamble(preamble));
blocks = section_blocks;
}
// An abstract block is not permitted as a direct child of a book
// document without a doctitle. Asciidoctor's converter excludes
// such a block's content and warns; the parser keeps the block in
// the AST (as Asciidoctor does) and records the warning here, for
// a renderer to act on.
if matches!(
parser.attribute_value("doctype"),
InterpretedValue::Value(ref v) if v == "book"
) && header.title().is_none()
{
for block in &blocks {
if block.declared_style() == Some("abstract")
&& block.resolved_context().as_ref() == "open"
{
warnings.push(Warning {
source: block.span(),
warning: WarningType::AbstractBlockInBookWithoutDoctitle,
origin: None,
});
}
}
}
// Under `doctype: inline`, only the first eligible block is converted,
// as bare inline content, and everything after it is dropped (the
// rendering lives on the embed path). A compound or empty candidate
// has no inline content to emit, so warn here – matching
// Asciidoctor's `Document#convert` – and let the embed path render
// nothing. This runs on the final block list (after any preamble
// split) and uses the same candidate selection as the renderer, so
// the two always agree on which block is the candidate.
if matches!(
parser.attribute_value("doctype"),
InterpretedValue::Value(ref v) if v == "inline"
) && let Some(first) = first_inline_candidate(blocks.iter())
&& matches!(
first.content_model(),
ContentModel::Compound | ContentModel::Empty
)
{
warnings.push(Warning {
source: first.span(),
warning: WarningType::NoInlineDoctypeCandidate,
origin: None,
});
}
// The `toc` family of attributes is header-only, so the resolved
// placement, depth, title, and class are fixed once the header (and
// body) have been processed. Capture them here, while the parser
// still holds the document's resolved attribute state.
let toc = TocConfig::from_parser(parser);
// Capture the parser's fully-resolved attribute state so it can be
// read back through the `Document` (via `attribute_value`,
// `has_attribute`, and `is_attribute_set`) without a `Parser` in
// hand – the embed path a renderer uses for `convert_document`.
let mut attributes = parser.snapshot_attributes();
// Materialize the derived `toc-position` / `toc-placement` /
// `toc-class` document attributes from the resolved placement into
// the snapshot (matching Asciidoctor), so they are queryable via
// `attribute_value` without perturbing the parser's own attribute
// state – a reused parser must not carry this document's derived TOC
// values into the next parse, where they would change what
// `TocMode::from_parser` observes.
attributes.materialize_toc_attributes(toc.mode);
// Resolve docinfo from the final attribute state and the parser's
// configured docinfo file handler (empty when no handler is set).
let docinfo = Docinfo::resolve(parser);
// Warnings are collected in assembly order (header, then blocks, then
// preprocessor, substitution, and post-parse checks), which is not
// source order. Put them into source order now so a host can rely on
// `warnings()` yielding line-ordered diagnostics. See
// `sort_warnings` for the ordering and its determinism.
sort_warnings(&mut warnings);
InternalDependent {
header,
blocks,
source: source.trim_trailing_whitespace(),
warnings,
source_map: (*source_map).clone(),
catalog: parser.take_catalog(),
attributes,
toc,
docinfo,
}
});
// The parse is complete; the document now owns its source map.
parser.source_map = None;
Self {
internal,
_phantom: PhantomData,
}
}
/// Return the document header.
pub fn header(&self) -> &Header<'_> {
&self.internal.borrow_dependent().header
}
/// Return the document's authors.
///
/// Authors may be declared on the [author line] or via the `author` /
/// `author_N` document attributes; this returns the resolved list
/// regardless of which mechanism was used. See [`Header::authors`].
///
/// [author line]: https://docs.asciidoctor.org/asciidoc/latest/document/author-line/
pub fn authors(&self) -> &[Author] {
self.header().authors()
}
/// Return the document title, if there was one.
///
/// The title may be the implicit level-0 `= Title`, or it may be supplied
/// or overridden by a `:doctitle:` or `:title:` [attribute entry],
/// following Asciidoctor's `Document#doctitle` precedence: a `title`
/// attribute entry wins over the section title, which a `:doctitle:`
/// entry may itself supply or override. Consequently this can differ
/// from [`Header::title`] (the section title): given `= Document Title`
/// then `:title: Override`, this returns `Override` while
/// [`Header::title`] returns `Document Title`.
///
/// If the title contains a subtitle, this returns the full, combined title.
/// Use [`Header::main_title`] and [`Header::subtitle`] (via [`header`]) to
/// access the partitioned section title.
///
/// [attribute entry]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes/
/// [`header`]: Self::header
pub fn doctitle(&self) -> Option<&str> {
self.header().doctitle()
}
/// Return the document subtitle, if the document title contained one.
///
/// A subtitle is the text following the final subtitle separator (a colon
/// followed by a space, by default) in the document title. See
/// [`Header::subtitle`].
pub fn subtitle(&self) -> Option<&str> {
self.header().subtitle()
}
/// Returns the resolved interpreted value of the named [document
/// attribute], as of the end of parsing.
///
/// This mirrors [`Parser::attribute_value`] and is the accessor to use on
/// the *embed* path – rendering a [`Document`] you already hold, without a
/// [`Parser`] in hand. The value reflects the document's final attribute
/// state: built-in defaults, values set in the header or body, and the
/// current value of any counter of the same name. An attribute that is not
/// present, or is present but explicitly [unset], resolves to
/// [`InterpretedValue::Unset`].
///
/// [document attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes/
/// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
/// [`Parser::attribute_value`]: crate::Parser::attribute_value
pub fn attribute_value<N: AsRef<str>>(&self, name: N) -> InterpretedValue {
self.internal
.borrow_dependent()
.attributes
.attribute_value(name)
}
/// Returns `true` if the document has a [document attribute] by this name
/// (whether or not it is set), as of the end of parsing.
///
/// This mirrors [`Parser::has_attribute`].
///
/// [document attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes/
/// [`Parser::has_attribute`]: crate::Parser::has_attribute
pub fn has_attribute<N: AsRef<str>>(&self, name: N) -> bool {
self.internal
.borrow_dependent()
.attributes
.has_attribute(name)
}
/// Returns `true` if the document has a [document attribute] by this name
/// which has been set (i.e. is present and not [unset]), as of the end of
/// parsing.
///
/// This mirrors [`Parser::is_attribute_set`].
///
/// [document attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes/
/// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
/// [`Parser::is_attribute_set`]: crate::Parser::is_attribute_set
pub fn is_attribute_set<N: AsRef<str>>(&self, name: N) -> bool {
self.internal
.borrow_dependent()
.attributes
.is_attribute_set(name)
}
/// Return where (and whether) this document's table of contents is
/// generated, resolved from the [`toc` attribute].
///
/// [`toc` attribute]: https://docs.asciidoctor.org/asciidoc/latest/toc/
pub fn toc_mode(&self) -> TocMode {
self.internal.borrow_dependent().toc.mode
}
/// Return the depth of section levels included in this document's table of
/// contents, resolved from the [`toclevels` attribute] (default `2`).
///
/// [`toclevels` attribute]: https://docs.asciidoctor.org/asciidoc/latest/toc/levels/
pub fn toc_levels(&self) -> usize {
self.internal.borrow_dependent().toc.levels
}
/// Return the title of this document's table of contents, resolved from the
/// [`toc-title` attribute] (default _Table of Contents_).
///
/// [`toc-title` attribute]: https://docs.asciidoctor.org/asciidoc/latest/toc/title/
pub fn toc_title(&self) -> &str {
&self.internal.borrow_dependent().toc.title
}
/// Return the CSS class applied to this document's table of contents
/// container, resolved from the [`toc-class` attribute]. An explicit,
/// non-empty `toc-class` is used verbatim; otherwise the default is `toc2`
/// for a `left`/`right` side-column placement (matching Asciidoctor) and
/// `toc` for every other placement.
///
/// [`toc-class` attribute]: https://docs.asciidoctor.org/asciidoc/latest/toc/
pub fn toc_class(&self) -> &str {
&self.internal.borrow_dependent().toc.class
}
/// Return this document's resolved [docinfo] content for `location`.
///
/// [Docinfo] is custom content read from external *docinfo files* and
/// injected into the head, header, or footer of the converted output. The
/// returned string is the concatenation of the applicable shared and
/// private docinfo files (shared first, matching Asciidoctor), with
/// `docinfosubs` substitutions already applied.
///
/// An empty string is returned when no docinfo applies to the location –
/// for example when no [`DocinfoFileHandler`] was configured on the parser,
/// the `docinfo` attribute did not enable that scope/location, or no
/// matching file was found. Docinfo files are resolved through a
/// caller-supplied [`DocinfoFileHandler`], since this crate does not read
/// from the filesystem itself.
///
/// [docinfo]: https://docs.asciidoctor.org/asciidoc/latest/docinfo/
/// [Docinfo]: https://docs.asciidoctor.org/asciidoc/latest/docinfo/
/// [`DocinfoFileHandler`]: crate::parser::DocinfoFileHandler
pub fn docinfo(&self, location: DocinfoLocation) -> &str {
self.internal.borrow_dependent().docinfo.content(location)
}
/// Returns this document's direct (top-level) child blocks.
///
/// This is the internal seed for the
/// [`FindBlocks`](crate::blocks::FindBlocks) traversal; the public
/// accessor is
/// [`FindBlocks::child_blocks`](crate::blocks::FindBlocks::child_blocks).
pub(crate) fn top_level_blocks(&'src self) -> &'src [Block<'src>] {
&self.internal.borrow_dependent().blocks
}
/// Return an iterator over any warnings found during parsing.
///
/// Warnings are yielded in **source order**: by the byte offset of each
/// warning's [`source`](Warning::source) span in the (preprocessed)
/// document, so a host can render a line-ordered gutter or pick the "first"
/// diagnostic without sorting them itself. The order is deterministic;
/// warnings that share an offset keep a stable relative order. Resolving
/// cross-references (via [`resolve_references`](Self::resolve_references))
/// folds its unresolved-reference warnings into this same source order.
pub fn warnings(&self) -> Warnings<'_> {
Warnings::new(&self.internal.borrow_dependent().warnings)
}
/// Return a [`Span`] describing the entire document source.
pub fn span(&self) -> Span<'_> {
self.internal.borrow_dependent().source
}
/// Return the source map that tracks original file locations.
pub fn source_map(&self) -> &SourceMap {
&self.internal.borrow_dependent().source_map
}
/// Translate the start of `span` back to its [`Origin`] in the original
/// input files: the file, line, and (on verbatim lines) column the author
/// actually wrote, together with the [`Fidelity`] of the mapping.
///
/// Because a `Span` covers preprocessed source, its own `line`/`col` are
/// relative to the unified buffer, not any one input file; this resolves
/// them through the document's [`source_map`](Self::source_map). Pass any
/// element's span via [`HasSpan::span`], e.g.
/// `doc.origin_of(block.span())`.
///
/// [`Origin`]: crate::parser::Origin
/// [`Fidelity`]: crate::parser::Fidelity
/// [`HasSpan::span`]: crate::HasSpan::span
pub fn origin_of(&self, span: Span<'_>) -> Origin<'_> {
self.source_map().origin_of(span)
}
/// Return the document catalog for accessing referenceable elements.
pub fn catalog(&self) -> &Catalog {
&self.internal.borrow_dependent().catalog
}
/// Resolve the document's deferred cross-references using a caller-supplied
/// [`ReferenceResolver`] and [`InlineSubstitutionRenderer`].
///
/// This is the entry point for multi-document workflows: parse each
/// document with [`Parser::parse_deferred`], then call this with a
/// resolver that resolves targets against whatever combined index the
/// caller has built (this crate does not merge catalogs). The resolver
/// binds the "from" document, so a single shared resolver can be
/// parametrized per call site.
///
/// Resolution is non-destructive and may be repeated (e.g. for incremental
/// builds or multiple output targets): the original target text is
/// retained, so re-resolving is always possible.
///
/// Each call is a **full, independent resolution sweep**. Every
/// cross-reference is re-resolved against `resolver`, overwriting any
/// result from a previous pass, and the returned [`ReferenceWarning`]s
/// reflect only what *this* `resolver` could not resolve – a prior pass
/// having resolved a target does not suppress a warning here.
/// Consequently, resolving with a resolver that knows fewer targets
/// than an earlier pass (for example, calling this after
/// [`Parser::parse`] has already auto-resolved against the document's
/// own catalog) will re-report those now-unknown targets as unresolved.
/// Multi-document pipelines should therefore start from
/// [`Parser::parse_deferred`], which does not auto-resolve.
///
/// Each unresolved target is also recorded on the document as a
/// [`WarningType::PossibleInvalidReference`] warning, so a host that reads
/// [`warnings()`](Self::warnings) sees it alongside every other parse-time
/// diagnostic. Because each sweep is independent, those warnings replace
/// (rather than accumulate on top of) any left by an earlier sweep.
pub fn resolve_references(
&mut self,
resolver: &dyn ReferenceResolver,
renderer: &dyn InlineSubstitutionRenderer,
) -> Vec<ReferenceWarning> {
self.internal.with_dependent_mut(|_owner, dependent| {
let source = dependent.source;
let mut warnings = ReferenceWarnings::default();
for block in dependent.blocks.iter_mut() {
block.resolve_references(resolver, renderer, &mut warnings);
}
// Section titles are resolved separately, in document order, so
// cross-references between titles (forward and circular) coordinate
// the way Asciidoctor's converts-once-and-caches model does.
crate::document::title_refs::resolve_title_references(
&mut dependent.blocks,
&dependent.catalog,
resolver,
renderer,
&mut warnings,
);
// Footnote text is extracted out of block content, so its
// cross-references are resolved here rather than by the block pass
// above. The host resolver does not alias the catalog, so the
// footnotes can be borrowed mutably in place.
for footnote in dependent.catalog.footnotes.iter_mut() {
footnote.resolve_references(resolver, renderer, &mut warnings, source);
}
replace_reference_warnings(&mut dependent.warnings, &mut warnings.doc);
warnings.host
})
}
/// Resolve the document's deferred cross-references against its own
/// catalog.
///
/// This is the single-document convenience path used by [`Parser::parse`].
pub(crate) fn resolve_against_own_catalog(
&mut self,
renderer: &dyn InlineSubstitutionRenderer,
) -> Vec<ReferenceWarning> {
self.internal.with_dependent_mut(|_owner, dependent| {
let source = dependent.source;
let mut warnings = ReferenceWarnings::default();
// The footnotes are moved out of the catalog so they can be resolved
// mutably while the `CatalogResolver` borrows the (footnote-free)
// catalog. Footnotes are never cross-reference *targets*, so their
// absence does not affect resolution.
let mut footnotes = dependent.catalog.take_footnotes();
let resolver = CatalogResolver::new(&dependent.catalog);
for block in dependent.blocks.iter_mut() {
block.resolve_references(&resolver, renderer, &mut warnings);
}
// Section titles are resolved separately, in document order, so
// cross-references between titles (forward and circular) coordinate
// the way Asciidoctor's converts-once-and-caches model does.
crate::document::title_refs::resolve_title_references(
&mut dependent.blocks,
&dependent.catalog,
&resolver,
renderer,
&mut warnings,
);
// Footnote text is extracted out of block content, so its
// cross-references are resolved here rather than by the block pass
// above.
for footnote in footnotes.iter_mut() {
footnote.resolve_references(&resolver, renderer, &mut warnings, source);
}
dependent.catalog.restore_footnotes(footnotes);
replace_reference_warnings(&mut dependent.warnings, &mut warnings.doc);
warnings.host
})
}
}
/// Folds the document warnings raised by a resolution sweep into the document's
/// own warning list.
///
/// Each sweep is a full, independent pass, so any unresolved-reference warning
/// left by an earlier sweep is discarded first; otherwise resolving a document
/// twice would report every still-unresolved reference twice.
fn replace_reference_warnings<'src>(
document_warnings: &mut Vec<Warning<'src>>,
sweep_warnings: &mut Vec<Warning<'src>>,
) {
document_warnings
.retain(|warning| !matches!(warning.warning, WarningType::PossibleInvalidReference(_)));
document_warnings.append(sweep_warnings);
// A resolution sweep appends its unresolved-reference warnings at the end,
// so restore source order after folding them in – matching the order
// established at the end of the parse.
sort_warnings(document_warnings);
}
/// Stable-sorts `warnings` into source order.
///
/// Warnings are collected in assembly order during the parse (and a reference
/// resolution sweep appends more afterward), which does not match the order the
/// diagnostics appear in the source. The primary key is the byte offset of each
/// warning's [`source`](Warning::source) span in the (preprocessed) document,
/// so a host can render a line-ordered gutter or pick the "first" diagnostic.
///
/// The sort is *stable*, and the tiebreaker is the warning's
/// [`origin`](Warning::origin) line: two warnings anchored to the same document
/// span – several failing `include::` directives inside one AsciiDoc table
/// cell, whose `source` is the enclosing cell's directive line – order by where
/// they actually live, and any remaining ties keep their deterministic assembly
/// order. The result is therefore both source-ordered and stable across runs.
fn sort_warnings(warnings: &mut [Warning<'_>]) {
warnings.sort_by_key(|warning| {
(
warning.source.byte_offset(),
warning.origin.as_ref().map_or(0, |origin| origin.1),
)
});
}
impl<'src> IsBlock<'src> for Document<'src> {
fn content_model(&self) -> ContentModel {
ContentModel::Compound
}
fn raw_context(&self) -> CowStr<'src> {
"document".into()
}
fn title_source(&'src self) -> Option<Span<'src>> {
// Document title is reflected in the Header.
None
}
fn title(&self) -> Option<&str> {
// Document title is reflected in the Header.
None
}
fn id(&'src self) -> Option<&'src str> {
// A document ID is assigned with a block attribute line above the
// document title and is reflected in the Header.
self.internal.borrow_dependent().header.id()
}
fn roles(&'src self) -> Vec<&'src str> {
// Document role(s) are assigned with a block attribute line above the
// document title and are reflected in the Header (the default
// implementation reads `attrlist()`, which a document does not have).
self.internal.borrow_dependent().header.roles()
}
fn anchor(&'src self) -> Option<Span<'src>> {
None
}
fn anchor_reftext(&'src self) -> Option<Span<'src>> {
None
}
fn attrlist(&'src self) -> Option<&'src Attrlist<'src>> {
// Document attributes are reflected in the Header.
None
}
}
impl std::fmt::Debug for Document<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let dependent = self.internal.borrow_dependent();
f.debug_struct("Document")
.field("header", &dependent.header)
.field("blocks", &DebugSliceReference(&dependent.blocks))
.field("source", &dependent.source)
.field("warnings", &DebugSliceReference(&dependent.warnings))
.field("source_map", &dependent.source_map)
.field("catalog", &dependent.catalog)
.finish()
}
}
/// Returns the first block eligible to be the sole rendered block of an
/// `inline` document.
///
/// A document-attribute entry and a comment (either a `[comment]`-styled block
/// or a `////` comment block) produce no output, so they are transparent here
/// and skipped, mirroring how Asciidoctor drops them before taking `blocks[0]`.
/// The returned block is the one an `inline` document renders (when it holds
/// inline content) or reports as having *no inline candidate* (when it is
/// compound or empty).
///
/// Both the parse-time `no inline candidate` check and the embed-path renderer
/// select the candidate through this function so the two never disagree about
/// which block is the candidate.
pub(crate) fn first_inline_candidate<'a, 'src>(
blocks: impl Iterator<Item = &'a Block<'src>>,
) -> Option<&'a Block<'src>>
where
'src: 'a,
{
blocks.into_iter().find(|b| {
!matches!(b, Block::DocumentAttribute(_))
&& b.resolved_context().as_ref() != "comment"
&& b.declared_style() != Some("comment")
})
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use std::{collections::HashMap, ops::Deref};
use crate::{
blocks::{ContentModel, MediaType},
document::RefType,
tests::prelude::*,
};
#[test]
fn empty_source() {
let doc = Parser::default().parse("");
assert_eq!(doc.content_model(), ContentModel::Compound);
assert_eq!(doc.raw_context().deref(), "document");
assert_eq!(doc.resolved_context().deref(), "document");
assert!(doc.declared_style().is_none());
assert!(doc.id().is_none());
assert!(doc.roles().is_empty());
assert!(doc.title_source().is_none());
assert!(doc.title().is_none());
assert!(doc.anchor().is_none());
assert!(doc.anchor_reftext().is_none());
assert!(doc.attrlist().is_none());
assert_eq!(doc.substitution_group(), SubstitutionGroup::Normal);
assert_eq!(
doc,
Document {
header: Header {
title_source: None,
title: None,
attributes: &[],
author_line: None,
revision_line: None,
comments: &[],
source: Span {
data: "",
line: 1,
col: 1,
offset: 0
},
},
source: Span {
data: "",
line: 1,
col: 1,
offset: 0
},
blocks: &[],
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
}
#[test]
fn only_spaces() {
assert_eq!(
Parser::default().parse(" "),
Document {
header: Header {
title_source: None,
title: None,
attributes: &[],
author_line: None,
revision_line: None,
comments: &[],
source: Span {
data: "",
line: 1,
col: 5,
offset: 4
},
},
source: Span {
data: "",
line: 1,
col: 1,
offset: 0
},
blocks: &[],
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
}
#[test]
fn one_simple_block() {
let doc = Parser::default().parse("abc");
assert_eq!(
doc,
Document {
header: Header {
title_source: None,
title: None,
attributes: &[],
author_line: None,
revision_line: None,
comments: &[],
source: Span {
data: "",
line: 1,
col: 1,
offset: 0
},
},
source: Span {
data: "abc",
line: 1,
col: 1,
offset: 0
},
blocks: &[Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "abc",
line: 1,
col: 1,
offset: 0,
},
rendered: "abc",
},
source: Span {
data: "abc",
line: 1,
col: 1,
offset: 0,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
})],
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
assert!(doc.anchor().is_none());
assert!(doc.anchor_reftext().is_none());
}
#[test]
fn two_simple_blocks() {
assert_eq!(
Parser::default().parse("abc\n\ndef"),
Document {
header: Header {
title_source: None,
title: None,
attributes: &[],
author_line: None,
revision_line: None,
comments: &[],
source: Span {
data: "",
line: 1,
col: 1,
offset: 0
},
},
source: Span {
data: "abc\n\ndef",
line: 1,
col: 1,
offset: 0
},
blocks: &[
Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "abc",
line: 1,
col: 1,
offset: 0,
},
rendered: "abc",
},
source: Span {
data: "abc",
line: 1,
col: 1,
offset: 0,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
}),
Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "def",
line: 3,
col: 1,
offset: 5,
},
rendered: "def",
},
source: Span {
data: "def",
line: 3,
col: 1,
offset: 5,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
})
],
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
}
#[test]
fn two_blocks_and_title() {
assert_eq!(
Parser::default().parse("= Example Title\n\nabc\n\ndef"),
Document {
header: Header {
title_source: Some(Span {
data: "Example Title",
line: 1,
col: 3,
offset: 2,
}),
title: Some("Example Title"),
attributes: &[],
author_line: None,
revision_line: None,
comments: &[],
source: Span {
data: "= Example Title",
line: 1,
col: 1,
offset: 0,
}
},
blocks: &[
Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "abc",
line: 3,
col: 1,
offset: 17,
},
rendered: "abc",
},
source: Span {
data: "abc",
line: 3,
col: 1,
offset: 17,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
}),
Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "def",
line: 5,
col: 1,
offset: 22,
},
rendered: "def",
},
source: Span {
data: "def",
line: 5,
col: 1,
offset: 22,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
})
],
source: Span {
data: "= Example Title\n\nabc\n\ndef",
line: 1,
col: 1,
offset: 0
},
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
}
#[test]
fn blank_lines_before_header() {
let doc = Parser::default().parse("\n\n= Example Title\n\nabc\n\ndef");
assert_eq!(
doc,
Document {
header: Header {
title_source: Some(Span {
data: "Example Title",
line: 3,
col: 3,
offset: 4,
},),
title: Some("Example Title",),
attributes: &[],
author_line: None,
revision_line: None,
comments: &[],
source: Span {
data: "= Example Title",
line: 3,
col: 1,
offset: 2,
},
},
blocks: &[
Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "abc",
line: 5,
col: 1,
offset: 19,
},
rendered: "abc",
},
source: Span {
data: "abc",
line: 5,
col: 1,
offset: 19,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
},),
Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "def",
line: 7,
col: 1,
offset: 24,
},
rendered: "def",
},
source: Span {
data: "def",
line: 7,
col: 1,
offset: 24,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
},),
],
source: Span {
data: "\n\n= Example Title\n\nabc\n\ndef",
line: 1,
col: 1,
offset: 0,
},
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
}
#[test]
fn blank_lines_and_comment_before_header() {
let doc =
Parser::default().parse("\n// ignore this comment\n= Example Title\n\nabc\n\ndef");
assert_eq!(
doc,
Document {
header: Header {
title_source: Some(Span {
data: "Example Title",
line: 3,
col: 3,
offset: 26,
},),
title: Some("Example Title",),
attributes: &[],
author_line: None,
revision_line: None,
comments: &[Span {
data: "// ignore this comment",
line: 2,
col: 1,
offset: 1,
},],
source: Span {
data: "// ignore this comment\n= Example Title",
line: 2,
col: 1,
offset: 1,
},
},
blocks: &[
Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "abc",
line: 5,
col: 1,
offset: 41,
},
rendered: "abc",
},
source: Span {
data: "abc",
line: 5,
col: 1,
offset: 41,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
},),
Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "def",
line: 7,
col: 1,
offset: 46,
},
rendered: "def",
},
source: Span {
data: "def",
line: 7,
col: 1,
offset: 46,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
},),
],
source: Span {
data: "\n// ignore this comment\n= Example Title\n\nabc\n\ndef",
line: 1,
col: 1,
offset: 0,
},
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
}
#[test]
fn extra_space_before_title() {
assert_eq!(
Parser::default().parse("= Example Title\n\nabc"),
Document {
header: Header {
title_source: Some(Span {
data: "Example Title",
line: 1,
col: 5,
offset: 4,
}),
title: Some("Example Title"),
attributes: &[],
author_line: None,
revision_line: None,
comments: &[],
source: Span {
data: "= Example Title",
line: 1,
col: 1,
offset: 0,
}
},
blocks: &[Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "abc",
line: 3,
col: 1,
offset: 19,
},
rendered: "abc",
},
source: Span {
data: "abc",
line: 3,
col: 1,
offset: 19,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
})],
source: Span {
data: "= Example Title\n\nabc",
line: 1,
col: 1,
offset: 0
},
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
}
#[test]
fn err_bad_header() {
assert_eq!(
Parser::default().parse(
"= Title\nJane Smith <jane@example.com>\nv1, 2025-09-28\nnot an attribute\n"
),
Document {
header: Header {
title_source: Some(Span {
data: "Title",
line: 1,
col: 3,
offset: 2,
}),
title: Some("Title"),
attributes: &[],
author_line: Some(AuthorLine {
authors: &[Author {
name: "Jane Smith",
firstname: "Jane",
middlename: None,
lastname: Some("Smith"),
email: Some("jane@example.com"),
}],
source: Span {
data: "Jane Smith <jane@example.com>",
line: 2,
col: 1,
offset: 8,
},
}),
revision_line: Some(RevisionLine {
revnumber: Some("1",),
revdate: "2025-09-28",
revremark: None,
source: Span {
data: "v1, 2025-09-28",
line: 3,
col: 1,
offset: 38,
},
},),
comments: &[],
source: Span {
data: "= Title\nJane Smith <jane@example.com>\nv1, 2025-09-28",
line: 1,
col: 1,
offset: 0,
}
},
blocks: &[Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "not an attribute",
line: 4,
col: 1,
offset: 53,
},
rendered: "not an attribute",
},
source: Span {
data: "not an attribute",
line: 4,
col: 1,
offset: 53,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
})],
source: Span {
data: "= Title\nJane Smith <jane@example.com>\nv1, 2025-09-28\nnot an attribute",
line: 1,
col: 1,
offset: 0
},
warnings: &[Warning {
source: Span {
data: "not an attribute",
line: 4,
col: 1,
offset: 53,
},
warning: WarningType::DocumentHeaderNotTerminated,
},],
source_map: SourceMap(&[]),
catalog: Catalog::default(),
}
);
}
#[test]
fn err_bad_header_and_bad_macro() {
let doc = Parser::default().parse("= Title\nJane Smith <jane@example.com>\nv1, 2025-09-28\nnot an attribute\n\n== Section Title\n\nimage::bar[alt=Sunset,width=300,,height=400]");
assert_eq!(
Document {
header: Header {
title_source: Some(Span {
data: "Title",
line: 1,
col: 3,
offset: 2,
}),
title: Some("Title"),
attributes: &[],
author_line: Some(AuthorLine {
authors: &[Author {
name: "Jane Smith",
firstname: "Jane",
middlename: None,
lastname: Some("Smith"),
email: Some("jane@example.com"),
}],
source: Span {
data: "Jane Smith <jane@example.com>",
line: 2,
col: 1,
offset: 8,
},
}),
revision_line: Some(RevisionLine {
revnumber: Some("1"),
revdate: "2025-09-28",
revremark: None,
source: Span {
data: "v1, 2025-09-28",
line: 3,
col: 1,
offset: 38,
},
},),
comments: &[],
source: Span {
data: "= Title\nJane Smith <jane@example.com>\nv1, 2025-09-28",
line: 1,
col: 1,
offset: 0,
}
},
blocks: &[
Block::Preamble(Preamble {
blocks: &[Block::Simple(SimpleBlock {
content: Content {
original: Span {
data: "not an attribute",
line: 4,
col: 1,
offset: 53,
},
rendered: "not an attribute",
},
source: Span {
data: "not an attribute",
line: 4,
col: 1,
offset: 53,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
},),],
source: Span {
data: "not an attribute",
line: 4,
col: 1,
offset: 53,
},
},),
Block::Section(SectionBlock {
level: 1,
section_title: Content {
original: Span {
data: "Section Title",
line: 6,
col: 4,
offset: 74,
},
rendered: "Section Title",
},
blocks: &[Block::Media(MediaBlock {
type_: MediaType::Image,
target: Span {
data: "bar",
line: 8,
col: 8,
offset: 96,
},
macro_attrlist: Attrlist {
attributes: &[
ElementAttribute {
name: Some("alt"),
shorthand_items: &[],
value: "Sunset"
},
ElementAttribute {
name: Some("width"),
shorthand_items: &[],
value: "300"
},
ElementAttribute {
name: Some("height"),
shorthand_items: &[],
value: "400"
},
],
anchor: None,
source: Span {
data: "alt=Sunset,width=300,,height=400",
line: 8,
col: 12,
offset: 100,
},
},
source: Span {
data: "image::bar[alt=Sunset,width=300,,height=400]",
line: 8,
col: 1,
offset: 89,
},
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
},),],
source: Span {
data: "== Section Title\n\nimage::bar[alt=Sunset,width=300,,height=400]",
line: 6,
col: 1,
offset: 71,
},
title_source: None,
title: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
section_type: SectionType::Normal,
section_id: Some("_section_title"),
caption: None,
section_number: None,
},)
],
source: Span {
data: "= Title\nJane Smith <jane@example.com>\nv1, 2025-09-28\nnot an attribute\n\n== Section Title\n\nimage::bar[alt=Sunset,width=300,,height=400]",
line: 1,
col: 1,
offset: 0
},
warnings: &[
Warning {
source: Span {
data: "not an attribute",
line: 4,
col: 1,
offset: 53,
},
warning: WarningType::DocumentHeaderNotTerminated,
},
Warning {
source: Span {
data: "alt=Sunset,width=300,,height=400",
line: 8,
col: 12,
offset: 100,
},
warning: WarningType::EmptyAttributeValue,
},
],
source_map: SourceMap(&[]),
catalog: Catalog {
refs: HashMap::from([(
"_section_title",
RefEntry {
id: "_section_title",
reftext: Some("Section Title",),
ref_type: RefType::Section,
}
),]),
reftext_to_id: HashMap::from([("Section Title", "_section_title"),]),
}
},
doc
);
}
#[test]
fn impl_debug() {
let doc = Parser::default().parse("= Example Title\n\nabc\n\ndef");
assert_eq!(
format!("{doc:#?}"),
r#"Document {
header: Header {
title_source: Some(
Span {
data: "Example Title",
line: 1,
col: 3,
offset: 2,
},
),
title: Some(
"Example Title",
),
doctitle: Some(
"Example Title",
),
main_title: Some(
"Example Title",
),
subtitle: None,
id: None,
roles: [],
attributes: &[],
author_line: None,
authors: [],
revision_line: None,
comments: &[],
source: Span {
data: "= Example Title",
line: 1,
col: 1,
offset: 0,
},
},
blocks: &[
Block::Simple(
SimpleBlock {
content: Content {
original: Span {
data: "abc",
line: 3,
col: 1,
offset: 17,
},
rendered: "abc",
},
source: Span {
data: "abc",
line: 3,
col: 1,
offset: 17,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
},
),
Block::Simple(
SimpleBlock {
content: Content {
original: Span {
data: "def",
line: 5,
col: 1,
offset: 22,
},
rendered: "def",
},
source: Span {
data: "def",
line: 5,
col: 1,
offset: 22,
},
style: SimpleBlockStyle::Paragraph,
title_source: None,
title: None,
caption: None,
number: None,
anchor: None,
anchor_reftext: None,
attrlist: None,
},
),
],
source: Span {
data: "= Example Title\n\nabc\n\ndef",
line: 1,
col: 1,
offset: 0,
},
warnings: &[],
source_map: SourceMap(&[]),
catalog: Catalog {
refs: HashMap::from([]),
reftext_to_id: HashMap::from([]),
footnotes: [],
images: [],
links: [],
includes: HashMap::from([]),
},
}"#
);
}
mod attribute_access {
use crate::{document::InterpretedValue, tests::prelude::*};
#[test]
fn built_in_default() {
// `doctype` is a built-in attribute with a default of `article`; it
// should read back through the `Document` even though the source
// never sets it.
let doc = Parser::default().parse("Hello.");
assert!(doc.has_attribute("doctype"));
assert!(doc.is_attribute_set("doctype"));
assert_eq!(
doc.attribute_value("doctype"),
InterpretedValue::Value("article".to_string())
);
}
#[test]
fn header_set_attribute() {
let doc = Parser::default().parse("= Title\n:lang: fr\n\nBonjour.");
assert!(doc.has_attribute("lang"));
assert!(doc.is_attribute_set("lang"));
assert_eq!(
doc.attribute_value("lang"),
InterpretedValue::Value("fr".to_string())
);
}
#[test]
fn body_set_attribute() {
// An attribute set in the document body (not the header) is part of
// the final resolved state and must be visible on the `Document`.
let doc = Parser::default().parse("First paragraph.\n\n:foo: bar\n\nSecond paragraph.");
assert!(doc.has_attribute("foo"));
assert!(doc.is_attribute_set("foo"));
assert_eq!(
doc.attribute_value("foo"),
InterpretedValue::Value("bar".to_string())
);
}
#[test]
fn set_flag_attribute() {
// A bare `:sectnums:` turns the attribute on; its resolved value is
// the built-in default `all`.
let doc = Parser::default().parse("= Title\n:sectnums:\n\nBody.");
assert!(doc.has_attribute("sectnums"));
assert!(doc.is_attribute_set("sectnums"));
assert_eq!(
doc.attribute_value("sectnums"),
InterpretedValue::Value("all".to_string())
);
}
#[test]
fn unset_attribute() {
// `sectnums` exists in the built-in table but is unset by default.
let doc = Parser::default().parse("Hello.");
assert!(doc.has_attribute("sectnums"));
assert!(!doc.is_attribute_set("sectnums"));
assert_eq!(doc.attribute_value("sectnums"), InterpretedValue::Unset);
}
#[test]
fn explicitly_unset_attribute() {
// `:!sectnums:` explicitly unsets an otherwise-set attribute: it is
// present but not set.
let doc = Parser::default().parse("= Title\n:sectnums:\n:!sectnums:\n\nBody.");
assert!(doc.has_attribute("sectnums"));
assert!(!doc.is_attribute_set("sectnums"));
assert_eq!(doc.attribute_value("sectnums"), InterpretedValue::Unset);
}
#[test]
fn absent_attribute() {
let doc = Parser::default().parse("Hello.");
assert!(!doc.has_attribute("no-such-attribute"));
assert!(!doc.is_attribute_set("no-such-attribute"));
assert_eq!(
doc.attribute_value("no-such-attribute"),
InterpretedValue::Unset
);
}
#[test]
fn matches_parser_state() {
// The values read back through the `Document` must equal what the
// `Parser` itself reports after `parse`.
let mut parser = Parser::default();
let doc = parser.parse("= Title\n:lang: de\n:sectnums:\n\nBody.");
for name in [
"lang",
"sectnums",
"doctype",
"notitle",
"no-such-attribute",
] {
assert_eq!(doc.attribute_value(name), parser.attribute_value(name));
assert_eq!(doc.has_attribute(name), parser.has_attribute(name));
assert_eq!(doc.is_attribute_set(name), parser.is_attribute_set(name));
}
}
#[test]
fn matches_parser_state_for_masked_docdir_and_docfile() {
// Under `SafeMode::Server` the `Document` snapshot must report the
// same masked `docdir` / `docfile` the parser does, so the host path
// never leaks through the public `Document::attribute_value` (#735).
let mut parser = Parser::default()
.with_safe_mode(SafeMode::Server)
.with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
.with_intrinsic_attribute(
"docfile",
"/some/dir/sample.adoc",
ModificationContext::ApiOnly,
);
let doc = parser.parse("Body.");
for name in ["docdir", "docfile"] {
assert_eq!(doc.attribute_value(name), parser.attribute_value(name));
assert_eq!(doc.has_attribute(name), parser.has_attribute(name));
assert_eq!(doc.is_attribute_set(name), parser.is_attribute_set(name));
}
assert_eq!(
doc.attribute_value("docdir"),
InterpretedValue::Value(String::new())
);
assert_eq!(
doc.attribute_value("docfile"),
InterpretedValue::Value("sample.adoc".to_string())
);
}
#[test]
fn counter_value() {
// A counter's current value is part of the resolved attribute state
// and supersedes any like-named attribute.
let doc = Parser::default().parse("{counter:my-counter}\n\n{counter:my-counter}");
assert!(doc.has_attribute("my-counter"));
assert!(doc.is_attribute_set("my-counter"));
assert_eq!(
doc.attribute_value("my-counter"),
InterpretedValue::Value("2".to_string())
);
}
}
}