Repository navigation
Expand file tree
/
Copy pathparser.rs
More file actions
2400 lines (2009 loc) · 67.9 KB
/
Copy pathparser.rs
File metadata and controls
2400 lines (2009 loc) · 67.9 KB
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
use std::{
borrow::Cow,
fmt::{Formatter, LowerHex, Write},
hash::Hash,
};
use anyhow::{Context, bail};
use indexmap::{IndexMap, map::Entry};
use ruff_db::system::{SystemPath, SystemPathBuf};
use rustc_hash::{FxBuildHasher, FxHashMap};
use ruff_index::{IndexVec, newtype_index};
use ruff_python_ast::PySourceType;
use ruff_python_trivia::Cursor;
use ruff_source_file::{LineIndex, LineRanges, OneIndexed};
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use rustc_stable_hash::{FromStableHash, SipHasher128Hash, StableSipHasher128};
use serde::Deserialize;
/// Parse the Markdown `source` as a test suite with given `title`.
///
/// `validate_config` is invoked once for every literally-declared `toml` config block
/// (after deserialization, before it replaces the section's inherited config) so callers
/// can enforce invariants that mdtest itself shouldn't know about.
pub fn parse<'s, C>(
title: &'s str,
source: &'s str,
validate_config: impl FnMut(&C) -> anyhow::Result<()>,
) -> anyhow::Result<MarkdownTestSuite<'s, C>>
where
C: Clone + Default + for<'de> Deserialize<'de>,
{
let parser = Parser::new(title, source, validate_config);
parser.parse()
}
/// A parsed markdown file containing tests.
///
/// Borrows from the source string and filepath it was created from.
#[derive(Debug)]
pub struct MarkdownTestSuite<'s, C> {
/// Header sections.
sections: IndexVec<SectionId, Section<'s, C>>,
/// Test files embedded within the Markdown file.
files: IndexVec<EmbeddedFileId, EmbeddedFile<'s>>,
}
impl<'s, C> MarkdownTestSuite<'s, C> {
pub(crate) fn tests(&self) -> MarkdownTestIterator<'_, 's, C> {
MarkdownTestIterator {
suite: self,
current_file_index: 0,
}
}
}
struct Hash128([u64; 2]);
impl FromStableHash for Hash128 {
type Hash = SipHasher128Hash;
fn from(SipHasher128Hash(hash): SipHasher128Hash) -> Hash128 {
Hash128(hash)
}
}
impl LowerHex for Hash128 {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let Self(hash) = self;
// Only write the first half for concision
write!(f, "{:x}", hash[0])
}
}
/// A single test inside a [`MarkdownTestSuite`].
///
/// A test is a single header section (or the implicit root section, if there are no Markdown
/// headers in the file), containing one or more embedded Python files as fenced code blocks, and
/// containing no nested header subsections.
#[derive(Debug)]
pub struct MarkdownTest<'m, 's, C> {
suite: &'m MarkdownTestSuite<'s, C>,
section: &'m Section<'s, C>,
files: &'m [EmbeddedFile<'s>],
}
impl<'m, 's, C> MarkdownTest<'m, 's, C> {
const MAX_TITLE_LENGTH: usize = 20;
const ELLIPSIS: char = '\u{2026}';
fn contracted_title(title: &str) -> String {
if title.len() <= Self::MAX_TITLE_LENGTH {
return (*title).to_string();
}
format!(
"{}{}",
title
.chars()
.take(Self::MAX_TITLE_LENGTH)
.collect::<String>(),
Self::ELLIPSIS
)
}
fn joined_name(&self, contracted: bool) -> String {
let mut name_fragments = vec![];
let mut parent_id = self.section.parent_id;
while let Some(next_id) = parent_id {
let parent = &self.suite.sections[next_id];
name_fragments.insert(0, parent.title);
parent_id = parent.parent_id;
}
name_fragments.push(self.section.title);
let full_name = name_fragments.join(" - ");
if !contracted {
return full_name;
}
let mut contracted_name = name_fragments
.iter()
.map(|fragment| Self::contracted_title(fragment))
.collect::<Vec<_>>()
.join(" - ");
let mut hasher = StableSipHasher128::new();
full_name.hash(&mut hasher);
let _ = write!(contracted_name, " ({:x})", hasher.finish::<Hash128>());
contracted_name
}
pub(crate) fn uncontracted_name(&self) -> String {
self.joined_name(false)
}
pub(crate) fn name(&self) -> String {
self.joined_name(true)
}
pub fn files(&self) -> impl Iterator<Item = &'m EmbeddedFile<'s>> {
self.files.iter()
}
pub fn configuration(&self) -> &C {
&self.section.config
}
pub(crate) fn should_snapshot_diagnostics(&self) -> bool {
self.section
.directives
.has_directive_set(MdtestDirective::SnapshotDiagnostics)
}
#[expect(clippy::result_unit_err)]
pub fn should_expect_panic(&self) -> Result<Option<&str>, ()> {
self.section.directives.get(MdtestDirective::ExpectPanic)
}
pub fn should_skip_pulling_types(&self) -> bool {
self.section
.directives
.has_directive_set(MdtestDirective::PullTypesSkip)
}
}
/// Iterator yielding all [`MarkdownTest`]s in a [`MarkdownTestSuite`].
#[derive(Debug)]
pub struct MarkdownTestIterator<'m, 's, C> {
suite: &'m MarkdownTestSuite<'s, C>,
current_file_index: usize,
}
impl<'m, 's, C> Iterator for MarkdownTestIterator<'m, 's, C> {
type Item = MarkdownTest<'m, 's, C>;
fn next(&mut self) -> Option<Self::Item> {
let mut current_file_index = self.current_file_index;
let mut file = self.suite.files.get(current_file_index.into());
let section_id = file?.section;
while file.is_some_and(|file| file.section == section_id) {
current_file_index += 1;
file = self.suite.files.get(current_file_index.into());
}
let files = &self.suite.files[EmbeddedFileId::from_usize(self.current_file_index)
..EmbeddedFileId::from_usize(current_file_index)];
self.current_file_index = current_file_index;
Some(MarkdownTest {
suite: self.suite,
section: &self.suite.sections[section_id],
files,
})
}
}
#[newtype_index]
struct SectionId;
/// A single header section of a [`MarkdownTestSuite`], or the implicit root "section".
///
/// A header section is the part of a Markdown file beginning with a `#`-prefixed header line, and
/// extending until the next header line at the same or higher outline level (that is, with the
/// same number or fewer `#` characters).
///
/// A header section may either contain one or more embedded Python files (making it a
/// [`MarkdownTest`]), or it may contain nested sections (headers with more `#` characters), but
/// not both.
#[derive(Debug)]
pub struct Section<'s, C> {
title: &'s str,
level: u8,
parent_id: Option<SectionId>,
config: C,
directives: MdtestDirectives,
}
#[newtype_index]
struct EmbeddedFileId;
/// Holds information about the start and the end of a code block in a Markdown file.
///
/// The start is the offset of the first triple-backtick in the code block, and the end is the
/// offset immediately after the closing triple-backtick.
#[derive(Debug, Copy, Clone)]
pub struct BacktickOffsets(TextRange);
impl Ranged for BacktickOffsets {
fn range(&self) -> TextRange {
self.0
}
}
#[derive(Debug, Clone)]
pub(crate) struct InlineSnapshotBlock<'s> {
/// The expected snapshot content.
pub(crate) expected: &'s str,
/// The range of the inline snapshot block, including both fences.
pub(crate) range: BacktickOffsets,
}
impl Ranged for InlineSnapshotBlock<'_> {
fn range(&self) -> TextRange {
self.range.0
}
}
/// Holds information about the position and length of all code blocks that are part of
/// a single embedded file in a Markdown file. This is used to reconstruct absolute line
/// numbers (in the Markdown file) from relative line numbers (in the embedded file).
///
/// If we have a Markdown section with multiple code blocks like this:
///
/// 01 # Test
/// 02
/// 03 Part 1:
/// 04
/// 05 ```py
/// 06 a = 1 # Relative line number: 1
/// 07 b = 2 # Relative line number: 2
/// 08 ```
/// 09
/// 10 Part 2:
/// 11
/// 12 ```py
/// 13 c = 3 # Relative line number: 3
/// 14 ```
///
/// We want to reconstruct the absolute line number (left) from relative
/// line numbers. The information we have is the start line and the line
/// count of each code block:
///
/// - Block 1: (start = 5, count = 2)
/// - Block 2: (start = 12, count = 1)
///
/// For example, if we see a relative line number of 3, we see that it is
/// larger than the line count of the first block, so we subtract the line
/// count of the first block, and then add the new relative line number (1)
/// to the absolute start line of the second block (12), resulting in an
/// absolute line number of 13.
pub(crate) struct EmbeddedFileSourceMap {
start_line_and_line_count: Vec<(usize, usize)>,
}
impl EmbeddedFileSourceMap {
pub(crate) fn new(
md_index: &LineIndex,
dimensions: impl IntoIterator<Item = BacktickOffsets>,
) -> EmbeddedFileSourceMap {
EmbeddedFileSourceMap {
start_line_and_line_count: dimensions
.into_iter()
.map(|d| {
let start_line = md_index.line_index(d.start()).get();
let end_line = md_index.line_index(d.end()).get();
let code_line_count = (end_line - start_line) - 1;
(start_line, code_line_count)
})
.collect(),
}
}
/// Returns the absolute line number in the markdown file for a given line number
/// relative to the concatenated code blocks.
///
/// Returns an `Err` if the relative line number is out of bounds where
/// the returned value is the absolute line number of the last code block.
///
/// # Panics
/// If called when the markdown file has no code blocks.
pub(crate) fn to_absolute_line_number(
&self,
relative_line_number: OneIndexed,
) -> std::result::Result<OneIndexed, OneIndexed> {
let mut relative_line_number = relative_line_number.get();
for (start_line, line_count) in &self.start_line_and_line_count {
if relative_line_number > *line_count {
relative_line_number -= *line_count;
} else {
let absolute_line_number = start_line + relative_line_number;
return Ok(OneIndexed::new(absolute_line_number)
.expect("absolute line number must be >= 1"));
}
}
let last_line_number = self
.start_line_and_line_count
.last()
.and_then(|(start_line, line_count)| OneIndexed::new(start_line + line_count));
Err(last_line_number.expect("markdown file to have at least one code block"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum EmbeddedFilePath<'s> {
Autogenerated(PySourceType),
Explicit(&'s str),
}
impl EmbeddedFilePath<'_> {
fn as_str(&self) -> &str {
match self {
EmbeddedFilePath::Autogenerated(PySourceType::Python) => "mdtest_snippet.py",
EmbeddedFilePath::Autogenerated(PySourceType::Stub) => "mdtest_snippet.pyi",
EmbeddedFilePath::Autogenerated(PySourceType::Ipynb) => "mdtest_snippet.ipynb",
EmbeddedFilePath::Explicit(path) => path,
}
}
fn is_explicit(&self) -> bool {
matches!(self, EmbeddedFilePath::Explicit(_))
}
fn is_allowed_explicit_path(path: &str) -> bool {
[
PySourceType::Python,
PySourceType::Stub,
PySourceType::Ipynb,
]
.iter()
.all(|source_type| path != EmbeddedFilePath::Autogenerated(*source_type).as_str())
}
}
/// A single file embedded in a [`Section`] as a fenced code block.
///
/// Currently must be a Python file (`py` language), a type stub (`pyi`), a Jupyter notebook
/// (`ipynb`), an explicitly named TOML file, or a [typeshed `VERSIONS`] file.
///
/// Unnamed TOML blocks configure the test and are not stored as `EmbeddedFile`s. In the future we
/// plan to support `pth` files as well.
///
/// A checkable embedded file makes its containing [`Section`] into a [`MarkdownTest`] and is
/// searched for inline-comment assertions to match against diagnostics.
///
/// [typeshed `VERSIONS`]: https://github.com/python/typeshed/blob/c546278aae47de0b2b664973da4edb613400f6ce/stdlib/VERSIONS#L1-L18
#[derive(Debug)]
pub struct EmbeddedFile<'s> {
section: SectionId,
path: EmbeddedFilePath<'s>,
pub lang: &'s str,
pub code: Cow<'s, str>,
/// The checkable code blocks
pub code_blocks: Vec<CodeBlock<'s>>,
}
impl EmbeddedFile<'_> {
fn append_code(&mut self, backtick_offsets: BacktickOffsets, new_code: &str) {
// Treat empty code blocks as non-existent, instead of creating
// an additional empty line:
if new_code.is_empty() {
return;
}
let existing_code = self.code.to_mut();
existing_code.push('\n');
let start_offset = existing_code.text_len();
existing_code.push_str(new_code);
self.code_blocks.push(CodeBlock {
backticks: backtick_offsets,
embedded_start_offset: start_offset,
inline_snapshot_block: None,
});
}
pub(crate) fn relative_path(&self) -> &str {
self.path.as_str()
}
/// Returns the full path using unix file-path convention.
pub fn full_path(&self, project_root: &SystemPath) -> SystemPathBuf {
// Don't use `SystemPath::absolute` here because it's platform dependent
// and we want to use unix file-path convention.
let relative_path = self.relative_path();
if relative_path.starts_with('/') {
SystemPathBuf::from(relative_path)
} else {
project_root.join(relative_path)
}
}
fn is_checkable(&self) -> bool {
matches!(self.lang, "py" | "python" | "pyi" | "ipynb" | "toml")
}
}
#[derive(Debug, Clone)]
pub struct CodeBlock<'s> {
/// The offsets of the code block's code fences in the markdown source.
backticks: BacktickOffsets,
/// The offset in the concatenated file source at which this code block starts.
embedded_start_offset: TextSize,
/// The code block's associated inline snapshot block (capture the expected rendered diagnostics output).
inline_snapshot_block: Option<InlineSnapshotBlock<'s>>,
}
impl<'s> CodeBlock<'s> {
pub(crate) fn backtick_offsets(&self) -> BacktickOffsets {
self.backticks
}
pub(crate) fn embedded_start_offset(&self) -> TextSize {
self.embedded_start_offset
}
pub(crate) fn inline_snapshot_block(&self) -> Option<&InlineSnapshotBlock<'s>> {
self.inline_snapshot_block.as_ref()
}
}
#[derive(Debug)]
struct SectionStack(Vec<SectionId>);
impl SectionStack {
fn new(root_section_id: SectionId) -> Self {
Self(vec![root_section_id])
}
fn push(&mut self, section_id: SectionId) {
self.0.push(section_id);
}
fn pop(&mut self) -> Option<SectionId> {
let popped = self.0.pop();
debug_assert_ne!(popped, None, "Should never pop the implicit root section");
debug_assert!(
!self.0.is_empty(),
"Should never pop the implicit root section"
);
popped
}
fn top(&mut self) -> SectionId {
*self
.0
.last()
.expect("Should never pop the implicit root section")
}
}
/// Parse the source of a Markdown file into a [`MarkdownTestSuite`].
struct Parser<'s, C, F> {
/// [`Section`]s of the final [`MarkdownTestSuite`].
sections: IndexVec<SectionId, Section<'s, C>>,
/// [`EmbeddedFile`]s of the final [`MarkdownTestSuite`].
files: IndexVec<EmbeddedFileId, EmbeddedFile<'s>>,
/// The unparsed remainder of the Markdown source.
cursor: Cursor<'s>,
// Number of consecutive empty lines.
preceding_blank_lines: usize,
// Explicitly specified path for the upcoming code block.
explicit_path: Option<&'s str>,
source: &'s str,
/// Stack of ancestor sections.
stack: SectionStack,
/// Names of embedded files in current active section.
current_section_files: IndexMap<EmbeddedFilePath<'s>, EmbeddedFileId, FxBuildHasher>,
/// Whether or not the current section has a config block.
current_section_has_config: bool,
/// Callback to validate config blocks
validate_config: F,
}
impl<'s, C, F> Parser<'s, C, F>
where
C: Clone + Default + for<'de> Deserialize<'de>,
F: FnMut(&C) -> anyhow::Result<()>,
{
fn new(title: &'s str, source: &'s str, validate_config: F) -> Self {
let mut sections = IndexVec::default();
let root_section_id = sections.push(Section {
title,
level: 0,
parent_id: None,
config: C::default(),
directives: MdtestDirectives::default(),
});
Self {
sections,
source,
files: IndexVec::default(),
cursor: Cursor::new(source),
preceding_blank_lines: 0,
explicit_path: None,
stack: SectionStack::new(root_section_id),
current_section_files: IndexMap::default(),
current_section_has_config: false,
validate_config,
}
}
fn parse(mut self) -> anyhow::Result<MarkdownTestSuite<'s, C>> {
self.parse_impl()?;
Ok(self.finish())
}
fn finish(mut self) -> MarkdownTestSuite<'s, C> {
self.sections.shrink_to_fit();
self.files.shrink_to_fit();
MarkdownTestSuite {
sections: self.sections,
files: self.files,
}
}
fn skip_non_newline_whitespace(&mut self) {
self.cursor.eat_while(|c| c.is_whitespace() && c != '\n');
}
fn skip_to_beginning_of_next_line(&mut self) -> bool {
if let Some(position) = memchr::memchr(b'\n', self.cursor.as_bytes()) {
self.cursor.skip_bytes(position + 1);
true
} else {
false
}
}
fn consume_until(&mut self, mut end_predicate: impl FnMut(char) -> bool) -> Option<&'s str> {
let start = self.cursor.offset().to_usize();
while !self.cursor.is_eof() {
if end_predicate(self.cursor.first()) {
return Some(&self.source[start..self.cursor.offset().to_usize()]);
}
self.cursor.bump();
}
None
}
fn parse_impl(&mut self) -> anyhow::Result<()> {
const SECTION_CONFIG_SNAPSHOT: &str = "snapshot-diagnostics";
const SECTION_CONFIG_PULLTYPES: &str = "pull-types:skip";
const SECTION_CONFIG_EXPECT_PANIC: &str = "expect-panic";
const HTML_COMMENT_ALLOWLIST: &[&str] = &["fmt:on", "fmt:off"];
const CODE_BLOCK_END: &[u8] = b"```";
const HTML_COMMENT_END: &[u8] = b"-->";
while let Some(first) = self.cursor.bump() {
match first {
'<' if self.cursor.eat_char3('!', '-', '-') => {
if let Some(position) =
memchr::memmem::find(self.cursor.as_bytes(), HTML_COMMENT_END)
{
let html_comment = self.cursor.as_str()[..position].trim();
let (directive, value) = match html_comment.split_once(':') {
Some((directive, value)) => {
(directive.trim(), Some(value.trim().to_string()))
}
None => (html_comment, None),
};
match directive {
SECTION_CONFIG_SNAPSHOT => {
anyhow::ensure!(
value.is_none(),
"The `{SECTION_CONFIG_SNAPSHOT}` directive \
does not take a value."
);
self.process_mdtest_directive(
MdtestDirective::SnapshotDiagnostics,
None,
)?;
}
SECTION_CONFIG_PULLTYPES => {
anyhow::ensure!(
value.is_none(),
"The `{SECTION_CONFIG_PULLTYPES}` directive \
does not take a value."
);
self.process_mdtest_directive(
MdtestDirective::PullTypesSkip,
None,
)?;
}
SECTION_CONFIG_EXPECT_PANIC => {
self.process_mdtest_directive(MdtestDirective::ExpectPanic, value)?;
}
_ => {
if !HTML_COMMENT_ALLOWLIST.contains(&html_comment) {
bail!(
"Unknown HTML comment `{html_comment}` -- \
possibly a typo? (Add to `HTML_COMMENT_ALLOWLIST` \
if this is a false positive)"
);
}
}
}
self.cursor.skip_bytes(position + HTML_COMMENT_END.len());
} else {
bail!("Unterminated HTML comment.");
}
}
'#' => {
self.explicit_path = None;
self.preceding_blank_lines = 0;
// Determine header level (number of '#' characters)
let mut header_level = 1;
while self.cursor.eat_char('#') {
header_level += 1;
}
// Parse header title
if let Some(title) = self.consume_until(|c| c == '\n') {
let title = title.trim();
if !title.is_empty() {
self.process_header(header_level, title)?;
}
}
}
'`' => {
if self.cursor.eat_char2('`', '`') {
// We saw the triple-backtick beginning of a code block.
let backtick_offset_start = self.cursor.offset() - "```".text_len();
if self.preceding_blank_lines < 1 && self.explicit_path.is_none() {
bail!(
"Code blocks must start on a new line \
and be preceded by at least one blank line."
);
}
self.skip_non_newline_whitespace();
// Parse the code block language specifier
let lang = self
.consume_until(|c| matches!(c, ' ' | '\n'))
.unwrap_or_default();
self.skip_non_newline_whitespace();
let metadata = self.consume_until(|c| c == '\n').unwrap_or_default().trim();
if !self.cursor.eat_char('\n') {
bail!(
"Trailing code-block metadata is not supported. \
Only the code block language can be specified."
);
}
let ignore = if metadata.is_empty() {
false
} else if let Some(attributes) = metadata
.strip_prefix('{')
.and_then(|metadata| metadata.strip_suffix('}'))
{
attributes
.split_ascii_whitespace()
.any(|attribute| attribute == r#"data-mdtest="ignore""#)
} else {
bail!(
"Trailing code-block metadata must use the `{{...}}` \
attribute-list syntax."
);
};
if let Some(position) =
memchr::memmem::find(self.cursor.as_bytes(), CODE_BLOCK_END)
{
let mut code = &self.cursor.as_str()[..position];
self.cursor.skip_bytes(position + CODE_BLOCK_END.len());
if code.ends_with('\n') {
code = &code[..code.len() - '\n'.len_utf8()];
}
let backtick_offset_end = self.cursor.offset();
self.process_code_block(
lang,
code,
ignore,
BacktickOffsets(TextRange::new(
backtick_offset_start,
backtick_offset_end,
)),
)?;
} else {
let code_block_start = self.cursor.token_len();
let line = self.source.count_lines(TextRange::up_to(code_block_start));
bail!("Unterminated code block on line {line}.");
}
self.explicit_path = None;
} else if self.preceding_blank_lines > 0 {
// This could be a line that specifies an explicit path for a Markdown code block (`module.py`:)
self.explicit_path = None;
if let Some(path) = self.consume_until(|c| matches!(c, '`' | '\n')) {
if self.cursor.eat_char('`') {
self.skip_non_newline_whitespace();
if self.cursor.eat_char(':') {
self.explicit_path = Some(path);
}
}
}
}
self.preceding_blank_lines = 0;
}
'\n' => {
self.preceding_blank_lines += 1;
continue;
}
c => {
self.preceding_blank_lines = 0;
self.explicit_path = None;
if c.is_whitespace() {
self.skip_non_newline_whitespace();
if self.cursor.eat_char('`')
&& self.cursor.eat_char('`')
&& self.cursor.eat_char('`')
{
bail!("Indented code blocks are not supported.");
}
}
}
}
if !self.skip_to_beginning_of_next_line() {
break;
}
}
Ok(())
}
fn process_header(&mut self, header_level: usize, title: &'s str) -> anyhow::Result<()> {
self.pop_sections_to_level(header_level);
let parent = self.stack.top();
let section = Section {
title,
level: header_level.try_into()?,
parent_id: Some(parent),
config: self.sections[parent].config.clone(),
directives: self.sections[parent].directives.clone(),
};
if !self.current_section_files.is_empty() {
bail!(
"Header '{}' not valid inside a test case; parent '{}' has code files.",
section.title,
self.sections[parent].title,
);
}
let section_id = self.sections.push(section);
self.stack.push(section_id);
self.current_section_files.clear();
self.current_section_has_config = false;
Ok(())
}
fn process_code_block(
&mut self,
lang: &'s str,
code: &'s str,
ignore: bool,
backtick_offsets: BacktickOffsets,
) -> anyhow::Result<()> {
// We never pop the implicit root section.
let section = self.stack.top();
let test_name = self.sections[section].title;
if ignore {
return Ok(());
}
if lang == "toml" && self.explicit_path.is_none() {
return self.process_config_block(code);
}
if matches!(lang, "ignore" | "pycon") {
return Ok(());
}
if lang == "snapshot" {
return self.process_inline_snapshot(code, backtick_offsets);
}
if let Some(explicit_path) = self.explicit_path {
let expected_extension = if lang == "python" { "py" } else { lang };
if !expected_extension.is_empty()
&& lang != "text"
&& !SystemPath::new(explicit_path)
.extension()
.is_none_or(|extension| extension.eq_ignore_ascii_case(expected_extension))
{
let backtick_start = self.line_number(backtick_offsets.start());
bail!(
"File extension of test file path `{explicit_path}` \
in test `{test_name}` does not match language specified `{lang}` \
of code block on line `{backtick_start}`"
);
}
}
let path = match self.explicit_path {
Some(path) => {
if !EmbeddedFilePath::is_allowed_explicit_path(path) {
bail!(
"The file name `{path}` in test `{test_name}` must not be used explicitly.",
);
}
EmbeddedFilePath::Explicit(path)
}
None => match lang {
"py" | "python" => EmbeddedFilePath::Autogenerated(PySourceType::Python),
"pyi" => EmbeddedFilePath::Autogenerated(PySourceType::Stub),
"ipynb" => EmbeddedFilePath::Autogenerated(PySourceType::Ipynb),
"" => {
bail!(
"Cannot auto-generate file name for code block \
with empty language specifier in test `{test_name}`"
);
}
_ => {
bail!(
"Cannot auto-generate file name for code block \
with language `{lang}` in test `{test_name}`"
);
}
},
};
let has_merged_snippets = self.current_section_has_merged_snippets();
let has_explicit_file_paths = self.current_section_has_explicit_file_paths();
match self.current_section_files.entry(path.clone()) {
Entry::Vacant(entry) => {
if has_merged_snippets {
bail!(
"Merged snippets in test `{test_name}` are not allowed \
in the presence of other files."
);
}
let index = self.files.push(EmbeddedFile {
path: path.clone(),
section,
lang,
code: Cow::Borrowed(code),
code_blocks: vec![CodeBlock {
backticks: backtick_offsets,
embedded_start_offset: TextSize::new(0),
inline_snapshot_block: None,
}],
});
entry.insert(index);
}
Entry::Occupied(entry) => {
if path.is_explicit() {
bail!(
"Test `{test_name}` has duplicate files named `{}`.",
path.as_str(),
);
}
if has_explicit_file_paths {
bail!(
"Merged snippets in test `{test_name}` are not allowed \
in the presence of other files."
);
}
let index = *entry.get();
self.files[index].append_code(backtick_offsets, code);
}
}
Ok(())
}
fn current_section_has_explicit_file_paths(&self) -> bool {
self.current_section_files
.iter()
.any(|(path, _)| path.is_explicit())
}
fn current_section_has_merged_snippets(&self) -> bool {
self.current_section_files
.values()
.any(|id| self.files[*id].code_blocks.len() > 1)
}
fn process_config_block(&mut self, code: &str) -> anyhow::Result<()> {
if self.current_section_has_config {
bail!("Multiple TOML configuration blocks in the same section are not allowed.");
}
let config: C = toml::from_str(code).context("Error while parsing Markdown TOML config")?;
(self.validate_config)(&config)?;
let current_section = &mut self.sections[self.stack.top()];
current_section.config = config;
self.current_section_has_config = true;
Ok(())
}
fn process_inline_snapshot(
&mut self,
code: &'s str,
offsets: BacktickOffsets,
) -> anyhow::Result<()> {
let Some((_, current_file)) = self.current_section_files.last() else {
let backtick_start = line_number(offsets.start(), self.source);
bail!(
"`snapshot` code block on line {backtick_start} \
must follow a checkable code block, but section has no files."
);
};
let file = &mut self.files[*current_file];
if !file.is_checkable() {
let backtick_start = line_number(offsets.start(), self.source);
bail!(
"`snapshot` code block on line {backtick_start} \
must follow a checkable code block in the same section \
but it follows a `{}` block.",
file.lang
);