wdl-grammar 0.25.0

A parse tree for Workflow Description Language (WDL) documents
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
//! Module for the parser implementation.
//!
//! The parser consumes a token stream from a lexer and produces
//! a list of parser events that can be used to construct a CST.
//!
//! The design of this is very much based on `rust-analyzer`.

use std::fmt;
use std::ops::Deref;
use std::ops::DerefMut;

use indexmap::IndexSet;
use logos::Logos;
#[cfg(feature = "unstable-python")]
pub use python::PyEvent;

use super::Diagnostic;
use super::Span;
use super::SupportedVersion;
use super::lexer::Lexer;
use super::lexer::LexerResult;
use super::lexer::TokenSet;
use super::tree::SyntaxKind;

/// Represents an event produced by the parser.
///
/// The parser produces a stream of events that can be used to construct
/// a CST.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
    /// A new node has started.
    NodeStarted {
        /// The kind of the node.
        kind: SyntaxKind,
        /// For left-recursive syntactic constructs, the parser produces
        /// a child node before it sees a parent. `forward_parent`
        /// saves the position of current event's parent.
        forward_parent: Option<usize>,
    },

    /// A node has finished.
    NodeFinished,

    /// A token was encountered.
    Token {
        /// The syntax kind of the token.
        kind: SyntaxKind,
        /// The source span of the token.
        span: Span,
    },
}

impl Event {
    /// Gets an start node event for an abandoned node.
    pub fn abandoned() -> Self {
        Self::NodeStarted {
            kind: SyntaxKind::Abandoned,
            forward_parent: None,
        }
    }
}

/// Utility type for displaying "expected" items in a parser expectation
/// diagnostic.
struct Expected<'a> {
    /// The set of expected items.
    items: &'a [&'a str],
}

impl<'a> Expected<'a> {
    /// Constructs a new `Expected`.
    fn new(items: &'a [&'a str]) -> Self {
        Self { items }
    }
}

impl fmt::Display for Expected<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let count = self.items.len();
        for (i, item) in self.items.iter().enumerate() {
            if i > 0 {
                if count == 2 {
                    write!(f, " or ")?;
                } else if i == count - 1 {
                    write!(f, ", or ")?;
                } else {
                    write!(f, ", ")?;
                }
            }

            write!(f, "{item}")?;
        }

        Ok(())
    }
}

/// [`Diagnostic`] wrapper with [`Parser`]-specific metadata.
#[derive(Debug)]
#[must_use]
pub struct ParseDiagnostic {
    /// The actual diagnostic.
    inner: Diagnostic,
    /// Whether the diagnostic was caused by reaching the end of the input.
    ///
    /// This is used in [`Parser::diagnostic()`] to guard against emitting
    /// multiple EOF errors in nested structures.
    eof: bool,
}

impl From<Diagnostic> for ParseDiagnostic {
    fn from(diagnostic: Diagnostic) -> Self {
        Self {
            inner: diagnostic,
            eof: false,
        }
    }
}

impl From<ParseDiagnostic> for Diagnostic {
    fn from(diagnostic: ParseDiagnostic) -> Self {
        diagnostic.inner
    }
}

impl ParseDiagnostic {
    /// Set the end-of-file flag.
    fn with_eof(mut self, eof: bool) -> Self {
        self.eof = eof;
        self
    }
}

/// Creates an "unterminated string" diagnostic error.
pub(crate) fn unterminated_string(span: Span) -> ParseDiagnostic {
    Diagnostic::error("an unterminated string was encountered")
        .with_label("this quote is not matched", span)
        .into()
}

/// Creates an "unterminated heredoc" diagnostic error.
pub(crate) fn unterminated_heredoc(opening: &str, span: Span, command: bool) -> ParseDiagnostic {
    Diagnostic::error(format!(
        "an unterminated {kind} was encountered",
        kind = if command {
            "heredoc command"
        } else {
            "multi-line string"
        }
    ))
    .with_label(format!("this {opening} is not matched"), span)
    .into()
}

/// Creates an "unterminated braced command" diagnostic error.
pub(crate) fn unterminated_braced_command(opening: &str, span: Span) -> ParseDiagnostic {
    Diagnostic::error("an unterminated braced command was encountered")
        .with_label(format!("this {opening} is not matched"), span)
        .into()
}

/// A trait implemented by parser tokens.
pub trait ParserToken<'a>: Eq + Copy + Logos<'a, Source = str, Error = (), Extras = ()> {
    /// Converts the token into its syntax representation.
    fn into_syntax(self) -> SyntaxKind;

    /// Converts the token into its "raw" representation.
    fn into_raw(self) -> u8;

    /// Converts from a raw token into the parser token.
    fn from_raw(token: u8) -> Self;

    /// Describes a raw token.
    fn describe(self) -> &'static str;

    /// Determines if the token is trivia that should be skipped over
    /// by the parser.
    ///
    /// Trivia tokens are still added to the concrete syntax tree.
    fn is_trivia(self) -> bool;

    /// A helper for recovering at an interpolation point.
    #[allow(unused_variables)]
    fn recover_interpolation(self, start: Span, parser: &mut Parser<'a, Self>) -> bool {
        false
    }
}

/// Marks the start of a node in the event list.
///
/// # Panics
///
/// Markers must either be completed or abandoned before being dropped;
/// otherwise, a panic will occur.
#[derive(Debug)]
pub struct Marker(usize);

impl Marker {
    /// Constructs a new `Marker`.
    fn new(pos: usize) -> Marker {
        Self(pos)
    }

    /// Completes the syntax tree node.
    pub fn complete<'a, T>(self, parser: &mut Parser<'a, T>, kind: SyntaxKind) -> CompletedMarker
    where
        T: ParserToken<'a>,
    {
        // Update the node kind and push a finished event
        match &mut parser.events[self.0] {
            Event::NodeStarted { kind: existing, .. } => {
                *existing = kind;
            }
            _ => unreachable!(),
        }

        parser.events.push(Event::NodeFinished);
        let m = CompletedMarker::new(self.0, kind);
        std::mem::forget(self);
        m
    }

    /// Abandons the node due to an error.
    pub fn abandon<'a, T>(self, parser: &mut Parser<'a, T>)
    where
        T: ParserToken<'a>,
    {
        // If the current node has no children, just pop it from the event list
        if self.0 == parser.events.len() - 1 {
            match parser.events.pop() {
                Some(Event::NodeStarted {
                    kind: SyntaxKind::Abandoned,
                    forward_parent: None,
                }) => (),
                _ => unreachable!(),
            }
        }

        std::mem::forget(self);
    }
}

impl Drop for Marker {
    fn drop(&mut self) {
        if !std::thread::panicking() {
            panic!("marker was dropped without it being completed or abandoned");
        }
    }
}

/// Represents a marker for a node that has been completed.
#[derive(Debug, Clone, Copy)]
pub struct CompletedMarker {
    /// Marks the position in the event list where the node was started.
    pos: usize,
    /// The kind of the completed node.
    kind: SyntaxKind,
}

impl CompletedMarker {
    /// Constructs a new completed marker with the given start position and
    /// syntax kind.
    fn new(pos: usize, kind: SyntaxKind) -> Self {
        CompletedMarker { pos, kind }
    }

    /// Creates a new node that precedes the completed node.
    pub fn precede<'a, T>(self, parser: &mut Parser<'a, T>) -> Marker
    where
        T: ParserToken<'a>,
    {
        let new_pos = parser.start();
        match &mut parser.events[self.pos] {
            Event::NodeStarted { forward_parent, .. } => {
                *forward_parent = Some(new_pos.0 - self.pos);
            }
            _ => unreachable!(),
        }
        new_pos
    }

    /// Extends the completed marker to the left up to `marker`.
    pub fn extend_to<'a, T>(self, parser: &mut Parser<'a, T>, marker: Marker) -> CompletedMarker
    where
        T: ParserToken<'a>,
    {
        let pos = marker.0;
        std::mem::forget(marker);
        match &mut parser.events[pos] {
            Event::NodeStarted { forward_parent, .. } => {
                *forward_parent = Some(self.pos - pos);
            }
            _ => unreachable!(),
        }
        self
    }

    /// Gets the kind of the completed marker.
    pub fn kind(&self) -> SyntaxKind {
        self.kind
    }
}

/// A utility type used during string interpolation.
///
/// See the [Parser::interpolate] method.
#[allow(missing_debug_implementations)]
pub struct Interpolator<'a, T>
where
    T: Logos<'a, Extras = ()>,
{
    /// The version of the document being parsed.
    version: SupportedVersion,
    /// The lexer to use for the interpolation.
    lexer: Lexer<'a, T>,
    /// The parser events.
    events: Vec<Event>,
    /// The recovery token set stack.
    recovery: Vec<TokenSet>,
    /// The context for diagnostics produced by the parser.
    diagnostic_context: DiagnosticContext,
    /// The buffered events from a peek operation.
    buffered: Vec<Event>,
    /// The current expression depth of the parser.
    expr_depth: usize,
}

impl<'a, T> Interpolator<'a, T>
where
    T: Logos<'a, Source = str, Error = (), Extras = ()> + Copy,
{
    /// Adds an event to the parser event list.
    pub fn event(&mut self, event: Event) {
        self.events.push(event);
    }

    /// Adds a diagnostic to the parser error list.
    pub fn diagnostic(&mut self, diagnostic: ParseDiagnostic) {
        if diagnostic.eof {
            if self.diagnostic_context.eof {
                return;
            }
            self.diagnostic_context.eof = true;
        }

        self.diagnostic_context.diagnostics.insert(diagnostic.inner);
    }

    /// Starts a new node event.
    pub fn start(&mut self) -> Marker {
        // Append any buffered trivia before we start this node
        if !self.buffered.is_empty() {
            self.events.append(&mut self.buffered);
        }

        let pos = self.events.len();
        self.events.push(Event::NodeStarted {
            kind: SyntaxKind::Abandoned,
            forward_parent: None,
        });
        Marker::new(pos)
    }

    /// Gets the current span of the interpolator.
    pub fn span(&self) -> Span {
        self.lexer.span()
    }

    /// Consumes the interpolator and returns a parser.
    pub fn into_parser<T2>(self) -> Parser<'a, T2>
    where
        T2: ParserToken<'a>,
        T::Extras: Into<T2::Extras>,
    {
        Parser {
            version: self.version,
            lexer: Some(self.lexer.morph()),
            events: self.events,
            recovery: self.recovery,
            diagnostic_context: self.diagnostic_context,
            buffered: Default::default(),
            expr_depth: self.expr_depth,
        }
    }
}

impl<'a, T> Iterator for Interpolator<'a, T>
where
    T: Logos<'a, Error = (), Extras = ()> + Copy,
{
    type Item = (LexerResult<T>, Span);

    fn next(&mut self) -> Option<Self::Item> {
        self.lexer.next()
    }
}

/// The output of a parse.
#[allow(missing_debug_implementations)]
pub struct Output<'a, T>
where
    T: ParserToken<'a>,
{
    /// The parser's lexer.
    pub lexer: Lexer<'a, T>,
    /// The parser events.
    pub events: Vec<Event>,
    /// The parser diagnostics.
    pub diagnostics: Vec<Diagnostic>,
}

/// Represents the result of a `peek2` operation.
///
/// See [Parser::peek2].
#[derive(Debug, Copy, Clone)]
pub struct Peek2<T> {
    /// The first peeked token.
    pub first: (T, Span),
    /// The second peeked token.
    pub second: (T, Span),
}

/// Context for managing parse diagnostics.
#[derive(Default, Debug)]
struct DiagnosticContext {
    /// The diagnostics encountered so far.
    diagnostics: IndexSet<Diagnostic>,
    /// Whether the parser has reached the end of the input.
    eof: bool,
    /// Whether the parser has encountered a fatal error.
    halt: bool,
}

/// Implements a WDL parser.
///
/// The parser produces a list of events that can be used to
/// construct a CST.
#[allow(missing_debug_implementations)]
pub struct Parser<'a, T>
where
    T: ParserToken<'a>,
{
    /// The version of the document being parsed.
    version: SupportedVersion,
    /// The lexer that returns a stream of tokens for the parser.
    ///
    /// This may temporarily be `None` during string interpolation.
    ///
    /// See the [interpolate][Self::interpolate] method.
    lexer: Option<Lexer<'a, T>>,
    /// The events produced by the parser.
    events: Vec<Event>,
    /// The recovery token set stack.
    recovery: Vec<TokenSet>,
    /// The context for diagnostics produced by the parser.
    diagnostic_context: DiagnosticContext,
    /// The buffered events from a peek operation.
    buffered: Vec<Event>,
    /// The current expression depth.
    expr_depth: usize,
}

/// The maximum recursion depth for nested expressions.
const MAX_DEPTH: usize = 128;

/// Guard for limiting the depth of recursive expression parsing.
#[allow(missing_debug_implementations)]
pub struct RecursionGuard<'a, 'b, T>
where
    T: ParserToken<'a>,
{
    /// The parser that is being guarded.
    parser: &'b mut Parser<'a, T>,
}

impl<'a, 'b, T> Drop for RecursionGuard<'a, 'b, T>
where
    T: ParserToken<'a>,
{
    fn drop(&mut self) {
        self.parser.expr_depth -= 1;
    }
}

impl<'a, 'b, T> Deref for RecursionGuard<'a, 'b, T>
where
    T: ParserToken<'a>,
{
    type Target = Parser<'a, T>;

    fn deref(&self) -> &Self::Target {
        self.parser
    }
}

impl<'a, 'b, T> DerefMut for RecursionGuard<'a, 'b, T>
where
    T: ParserToken<'a>,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.parser
    }
}

impl<'a, T> Parser<'a, T>
where
    T: ParserToken<'a>,
{
    /// Construct a new parser from the given lexer.
    pub fn new(lexer: Lexer<'a, T>) -> Self {
        Self {
            version: Default::default(),
            lexer: Some(lexer),
            events: Default::default(),
            recovery: Default::default(),
            diagnostic_context: Default::default(),
            buffered: Default::default(),
            expr_depth: 0,
        }
    }

    /// Increase the current expression depth by 1.
    pub(super) fn recurse(&mut self) -> Result<RecursionGuard<'a, '_, T>, ParseDiagnostic> {
        self.expr_depth += 1;
        if self.expr_depth > MAX_DEPTH {
            self.diagnostic_context.halt = true;
            return Err(Diagnostic::error("expression nested too deep")
                .with_label("this exceeds the parser's nesting limit", self.span())
                .into());
        }
        Ok(RecursionGuard { parser: self })
    }

    /// Get the version of the document.
    pub fn version(&self) -> SupportedVersion {
        self.version
    }

    /// Set the version of the document.
    pub fn set_version(&mut self, version: SupportedVersion) {
        self.version = version;
    }

    /// Gets the current span of the parser.
    pub fn span(&self) -> Span {
        self.lexer.as_ref().expect("expected a lexer").span()
    }

    /// Gets the source being parsed at the given span.
    pub fn source(&self, span: Span) -> &'a str {
        self.lexer.as_ref().expect("expected a lexer").source(span)
    }

    /// Peeks at the next token (i.e. lookahead 1) from the lexer without
    /// consuming it.
    ///
    /// The token is not added to the event list.
    ///
    /// # Note
    ///
    /// Note that peeking may cause parser events to be buffered.
    ///
    /// If `peek` returns `None`, ensure all buffered events are added to the
    /// event list by calling `next` on the parser; otherwise, calling `finish`
    /// may panic.
    pub fn peek(&mut self) -> Option<(T, Span)> {
        while let Some((res, span)) = self.lexer.as_mut()?.peek() {
            if let Some(t) = self.consume_trivia(res, span, true) {
                return Some(t);
            }
        }

        None
    }

    /// Peeks at the next and next-next tokens (i.e. lookahead 2) from the lexer
    /// without consuming either token.
    ///
    /// The returned tokens are not added to the event list.
    pub fn peek2(&mut self) -> Option<Peek2<T>> {
        let first = self.peek()?;

        // We have to clone the lexer here since it only supports a single lookahead.
        // The clone is cheap, but it does mean we'll re-tokenize this second lookahead
        // eventually.
        let mut lexer = self
            .lexer
            .as_ref()
            .expect("there should be a lexer")
            .clone();
        lexer
            .next()
            .unwrap()
            .0
            .expect("should have peeked at a valid token");
        while let Some((Ok(token), span)) = lexer.next() {
            if token.is_trivia() {
                // Ignore trivia
                continue;
            }

            return Some(Peek2 {
                first,
                second: (token, span),
            });
        }

        None
    }

    /// Consumes the next token only if it matches the given token.
    ///
    /// Returns `true` if the token was consumed, `false` if otherwise.
    pub fn next_if(&mut self, token: T) -> bool {
        match self.peek() {
            Some((t, _)) if t == token => {
                self.next();
                true
            }
            _ => false,
        }
    }

    /// Parses a matching token pair that surrounds an item.
    ///
    /// This method parses the open token, calls the callback to parse the item,
    /// and then parses the close token.
    pub fn matching<F>(
        &mut self,
        open: T,
        close: T,
        allow_empty: bool,
        cb: F,
    ) -> Result<(), ParseDiagnostic>
    where
        F: FnOnce(&mut Self, Span) -> Result<(), ParseDiagnostic>,
    {
        let open_span = self.expect(open)?;

        // Check to see if the close token is immediately following the opening
        if allow_empty {
            match self.peek() {
                Some((t, _)) if t == close => {
                    self.next();
                    return Ok(());
                }
                _ => {}
            }
        }

        cb(self, open_span)?;

        match self.next() {
            Some((token, _)) if token == close => Ok(()),
            found => Err(self.unmatched(open.describe(), open_span, close.describe(), found)),
        }
    }

    /// Parses a matching token pair that surround a delimited list of items.
    ///
    /// This method parses the open token, calls the callback for each delimited
    /// item, and then parses the close token.
    ///
    /// The provided recovery token set is used to recover within the delimited
    /// item list. The provided termination token set, in addition to `close`,
    /// causes the loop to stop early; on early stop, [`consume_close_token`]
    /// synthesizes a zero-width close token and emits an "unmatched" diagnostic
    /// so the surrounding caller can continue parsing.
    ///
    /// [`consume_close_token`]: Self::consume_close_token
    pub fn matching_delimited<F>(
        &mut self,
        open: T,
        close: T,
        delimiter: Option<T>,
        termination: TokenSet,
        recovery: TokenSet,
        cb: F,
    ) -> Result<(), ParseDiagnostic>
    where
        F: FnMut(&mut Self, Marker) -> Result<(), (Marker, ParseDiagnostic)>,
    {
        let open_span = self.expect(open)?;
        self.delimited(close, termination, delimiter, recovery, cb);
        self.consume_close_token(open, open_span, close);
        Ok(())
    }

    /// Consumes a close token if it is the next token to be parsed.
    ///
    /// Otherwise, emits an "unmatched" diagnostic and synthesizes the close
    /// token into the parser's list of events.
    pub fn consume_close_token(&mut self, open: T, open_span: Span, close: T) {
        if self.next_if(close) {
            return;
        }

        let found = self.peek();
        let diagnostic = self.unmatched(open.describe(), open_span, close.describe(), found);
        self.diagnostic(diagnostic);

        // Synthesize a close token event of zero width
        let span = found.map(|(_, s)| s).unwrap_or_else(|| self.span());
        self.events.push(Event::Token {
            kind: close.into_syntax(),
            span: Span::new(span.start(), 0),
        });
    }

    /// Parses a delimited list of items until the given `until` token.
    ///
    /// The provided recovery token set is used to recover within the delimited
    /// item list. Any token in the termination set additionally ends the loop
    /// after a successfully-parsed item.
    ///
    /// Neither `until` nor any termination token is consumed by this method.
    pub fn delimited<F>(
        &mut self,
        until: T,
        termination: TokenSet,
        delimiter: Option<T>,
        recovery: TokenSet,
        mut cb: F,
    ) where
        F: FnMut(&mut Self, Marker) -> Result<(), (Marker, ParseDiagnostic)>,
    {
        let recovery = if let Some(delimiter) = delimiter {
            recovery
                .union(termination)
                .union(TokenSet::new(&[until.into_raw(), delimiter.into_raw()]))
        } else {
            recovery
                .union(termination)
                .union(TokenSet::new(&[until.into_raw()]))
        };

        let parent = self.recovery.last().copied();
        self.recovery.push(recovery);

        let mut next: Option<(T, Span)> = self.peek();
        while let Some((token, _)) = next {
            if token == until || self.diagnostic_context.halt {
                break;
            }

            let mut lexer = self.lexer.clone();
            let marker = self.start();
            if let Err((marker, e)) = cb(self, marker) {
                if let Some((Ok(token), _)) = lexer.as_mut().expect("should have a lexer").peek()
                    && !recovery.contains(token.into_raw())
                {
                    // Determine if the token is recoverable in the parent recovery set
                    // If so, we'll restart where we first attempted to parse this item
                    if let Some(parent) = &parent
                        && parent.contains(token.into_raw())
                    {
                        // Truncate the event list and abandon the marker
                        self.events.truncate(marker.0);
                        marker.abandon(self);

                        // Clear any buffered events and reset the lexer
                        self.buffered.clear();
                        self.lexer = lexer;
                        break;
                    }
                }

                self.recover(e);
                marker.abandon(self);

                if self.diagnostic_context.halt {
                    break;
                }
            }

            next = self.peek();

            if let Some(delimiter) = delimiter
                && let Some((token, _)) = next
            {
                if token == until || termination.contains(token.into_raw()) {
                    break;
                }

                if let Err(mut e) = self.expect(delimiter) {
                    // Attach a label to the diagnostic hinting at where we expected the
                    // delimiter to be; to do this, look back at the last non-trivia token event
                    // in the parser events and use its span for the label.
                    let span = self.events.iter().rev().find_map(|e| match e {
                        Event::Token { kind, span }
                            if *kind != SyntaxKind::Whitespace && *kind != SyntaxKind::Comment =>
                        {
                            Some(*span)
                        }
                        _ => None,
                    });

                    let e = if let Some(span) = span {
                        e.inner = e.inner.with_label(
                            format!(
                                "consider adding a {desc} after this",
                                desc = delimiter.describe()
                            ),
                            Span::new(span.end() - 1, 1),
                        );
                        e
                    } else {
                        e
                    };

                    self.recover(e);
                    self.next_if(delimiter);
                }

                next = self.peek();
            }
        }

        self.recovery.pop();
    }

    /// Adds a diagnostic to the parser output.
    pub fn diagnostic(&mut self, diagnostic: ParseDiagnostic) {
        if diagnostic.eof {
            if self.diagnostic_context.eof {
                return;
            }
            self.diagnostic_context.eof = true;
        }

        self.diagnostic_context.diagnostics.insert(diagnostic.inner);
    }

    /// Pushes a token set to the parser's recovery token set stack.
    pub fn push_recovery_set(&mut self, tokens: TokenSet) {
        self.recovery.push(tokens);
    }

    /// Pops a token set from the parser's recovery token set stack.
    ///
    /// # Panics
    ///
    /// Panics if the parser's recovery set is empty.
    pub fn pop_recovery_set(&mut self) {
        self.recovery.pop().expect("should pop");
    }

    /// Recovers from an error by consuming all tokens not in the top-most
    /// recovery set.
    ///
    /// # Panics
    ///
    /// Panics if a recovery set was not pushed with [Self::push_recovery_set].
    pub fn recover(&mut self, mut diagnostic: ParseDiagnostic) {
        let tokens = *self.recovery.last().expect("expected a top recovery set");

        while let Some((token, span)) = self.peek() {
            if tokens.contains(token.into_raw()) {
                break;
            }

            self.next().unwrap();

            // If the token starts an interpolation, then we need
            // to move past the entire set of tokens that are part
            // of the interpolation
            if T::recover_interpolation(token, span, self) {
                // If the diagnostic label started at this token, we need to extend its length
                // to cover the interpolation
                for label in diagnostic.inner.labels_mut() {
                    let label_span = label.span();
                    if label_span.start() != span.start() {
                        continue;
                    }

                    // The label should include everything up to the current start
                    label.set_span(Span::new(
                        label_span.start(),
                        self.lexer
                            .as_ref()
                            .expect("should have a lexer")
                            .span()
                            .end()
                            - label_span.end()
                            + 1,
                    ));
                }
            }
        }

        self.diagnostic(diagnostic);
    }

    /// Performs recovery with the given recovery token set.
    pub fn recover_with_set(&mut self, diagnostic: ParseDiagnostic, recovery: TokenSet) {
        self.recovery.push(recovery);
        self.recover(diagnostic);
        self.recovery.pop();
    }

    /// Starts a new node event.
    pub fn start(&mut self) -> Marker {
        // Peek before starting the node so that any trivia appears as siblings to this
        // node
        if !self.events.is_empty() {
            self.peek();

            // Append any buffered trivia before we start this node
            if !self.buffered.is_empty() {
                self.events.append(&mut self.buffered);
            }
        }

        let pos = self.events.len();
        self.events.push(Event::NodeStarted {
            kind: SyntaxKind::Abandoned,
            forward_parent: None,
        });
        Marker::new(pos)
    }

    /// Requires that the current token is the given token.
    ///
    /// Panics if the token is not the given token.
    pub fn require(&mut self, token: T) -> Span {
        match self.next() {
            Some((t, span)) if t == token => span,
            _ => panic!(
                "lexer not at required token {token}",
                token = token.describe()
            ),
        }
    }

    /// Requires that the current token is in the given token set.
    ///
    /// # Panics
    ///
    /// Panics if the token is not in the token set.
    pub fn require_in(&mut self, tokens: TokenSet) {
        match self.next() {
            Some((t, _)) if tokens.contains(t.into_raw()) => {}
            found => {
                let found = found.map(|(t, _)| t.describe());
                panic!(
                    "unexpected token {found}",
                    found = found.unwrap_or("end of input")
                );
            }
        }
    }

    /// Determines if the `found` token is EOF, which is used by
    /// [`Self::diagnostic()`] for deduplication.
    fn maybe_eof_diagnostic(
        &mut self,
        found: Option<(T, Span)>,
    ) -> (Option<&'static str>, Span, bool) {
        let (found, span) = found
            .map(|(t, s)| (Some(t.describe()), s))
            .unwrap_or_else(|| (None, self.span()));

        let eof = found.is_none();
        (found, span, eof)
    }

    /// Creates an "expected, but found" diagnostic error.
    pub(crate) fn unexpected(
        &mut self,
        expected: &str,
        found: Option<(T, Span)>,
    ) -> ParseDiagnostic {
        let (found, span, eof) = self.maybe_eof_diagnostic(found);

        let found = found.unwrap_or("end of input");
        let diagnostic: ParseDiagnostic =
            Diagnostic::error(format!("expected {expected}, but found {found}"))
                .with_label(format!("unexpected {found}"), span)
                .into();

        diagnostic.with_eof(eof)
    }

    /// Creates an "expected one of, but found" diagnostic error.
    pub(crate) fn unexpected_many(
        &mut self,
        expected: &[&str],
        found: Option<(T, Span)>,
    ) -> ParseDiagnostic {
        let (found, span, eof) = self.maybe_eof_diagnostic(found);

        let found = found.unwrap_or("end of input");
        let diagnostic: ParseDiagnostic = Diagnostic::error(format!(
            "expected {expected}, but found {found}",
            expected = Expected::new(expected)
        ))
        .with_label(format!("unexpected {found}"), span)
        .into();

        diagnostic.with_eof(eof)
    }

    /// Creates an "unmatched token" diagnostic error.
    pub(crate) fn unmatched(
        &mut self,
        open: &str,
        open_span: Span,
        close: &str,
        found: Option<(T, Span)>,
    ) -> ParseDiagnostic {
        let mut diagnostic = self.unexpected(close, found);
        diagnostic.inner = diagnostic
            .inner
            .with_label(format!("this {open} is not matched"), open_span);

        diagnostic
    }

    /// Expects the next token to be the given token.
    ///
    /// Returns an error if the token is not the given token.
    pub fn expect(&mut self, token: T) -> Result<Span, ParseDiagnostic> {
        match self.peek() {
            Some((t, span)) if t == token => {
                self.next();
                Ok(span)
            }
            found => Err(self.unexpected(token.describe(), found)),
        }
    }

    /// Expects the next token to be the given token, but uses
    /// the provided name in the error.
    ///
    /// Returns an error if the token is not the given token.
    pub fn expect_with_name(
        &mut self,
        token: T,
        name: &'static str,
    ) -> Result<Span, ParseDiagnostic> {
        match self.peek() {
            Some((t, span)) if t == token => {
                self.next();
                Ok(span)
            }
            found => Err(self.unexpected(name, found)),
        }
    }

    /// Expects the next token to be in the given token set.
    ///
    /// Returns an error if the token is not the given set.
    pub fn expect_in(
        &mut self,
        tokens: TokenSet,
        expected: &[&str],
    ) -> Result<(T, Span), ParseDiagnostic> {
        match self.peek() {
            Some((t, span)) if tokens.contains(t.into_raw()) => {
                self.next();
                Ok((t, span))
            }
            found => Err(self.unexpected_many(expected, found)),
        }
    }

    /// Used to interpolate strings with a different string interpolation token.
    ///
    /// The provided callback receives a [Interpolator].
    ///
    /// The callback should use [Interpolator::into_parser] for the return
    /// value.
    pub fn interpolate<T2, F, R>(&mut self, cb: F) -> R
    where
        T2: Logos<'a, Source = str, Error = (), Extras = ()> + Copy,
        F: FnOnce(Interpolator<'a, T2>) -> (Parser<'a, T>, R),
    {
        let input = Interpolator {
            version: self.version,
            lexer: std::mem::take(&mut self.lexer)
                .expect("lexer should exist")
                .morph(),
            recovery: std::mem::take(&mut self.recovery),
            events: std::mem::take(&mut self.events),
            diagnostic_context: std::mem::take(&mut self.diagnostic_context),
            buffered: std::mem::take(&mut self.buffered),
            expr_depth: self.expr_depth,
        };
        let (p, result) = cb(input);
        *self = p;
        result
    }

    /// Morph this parser into a parser for a new token type.
    ///
    /// The returned parser continues to point at the same span
    /// as the current parser.
    pub fn morph<T2>(self) -> Parser<'a, T2>
    where
        T2: ParserToken<'a>,
        T::Extras: Into<T2::Extras>,
    {
        Parser {
            version: self.version,
            lexer: self.lexer.map(|l| l.morph()),
            events: self.events,
            recovery: self.recovery,
            diagnostic_context: self.diagnostic_context,
            buffered: self.buffered,
            expr_depth: self.expr_depth,
        }
    }

    /// Consumes the parser and returns an interpolator.
    pub fn into_interpolator<T2>(self) -> Interpolator<'a, T2>
    where
        T2: Logos<'a, Source = str, Error = (), Extras = ()> + Copy,
    {
        Interpolator {
            version: self.version,
            lexer: self.lexer.expect("lexer should be present").morph(),
            events: self.events,
            recovery: self.recovery,
            diagnostic_context: self.diagnostic_context,
            buffered: self.buffered,
            expr_depth: self.expr_depth,
        }
    }

    /// Consumes the parser and returns the output.
    ///
    /// # Panics
    ///
    /// This method panics if buffered events remain in the parser.
    ///
    /// To ensure that no buffered events remain, call `next()` on the parser
    /// and verify it returns `None` before calling this method.
    pub fn finish(self) -> Output<'a, T> {
        assert!(
            self.buffered.is_empty(),
            "buffered events remain; ensure `next` was called after an unsuccessful peek"
        );

        Output {
            lexer: self.lexer.expect("lexer should be present"),
            events: self.events,
            diagnostics: self.diagnostic_context.diagnostics.into_iter().collect(),
        }
    }

    /// Updates the syntax kind of the last token event.
    ///
    /// # Panics
    ///
    /// Panics if the last event was not a token.
    pub fn update_last_token_kind(&mut self, new_kind: SyntaxKind) {
        let last = self.events.last_mut().expect("expected a last event");
        match last {
            Event::Token { kind, .. } => *kind = new_kind,
            _ => panic!("the last event is not a token"),
        }
    }

    /// Consumes the remainder of the unparsed source into a special
    /// "unparsed" token.
    ///
    /// This occurs when a source file is missing a version statement or
    /// if the version specified is unsupported.
    pub fn consume_remainder(&mut self) {
        if !self.buffered.is_empty() {
            self.events.append(&mut self.buffered);
        }

        if let Some(span) = self
            .lexer
            .as_mut()
            .expect("there should be a lexer")
            .consume_remainder()
        {
            self.events.push(Event::Token {
                kind: SyntaxKind::Unparsed,
                span,
            });
        }
    }

    /// Consumes any trivia tokens by adding them to the event list.
    fn consume_trivia(
        &mut self,
        res: LexerResult<T>,
        span: Span,
        peeked: bool,
    ) -> Option<(T, Span)> {
        // If not peeked and there are buffered events, append them now
        if !peeked && !self.buffered.is_empty() {
            self.events.append(&mut self.buffered);
        }

        let event = match res {
            Ok(token) => {
                if !token.is_trivia() {
                    return Some((token, span));
                }

                if peeked {
                    self.lexer.as_mut().expect("should have a lexer").next();
                }

                Event::Token {
                    kind: token.into_syntax(),
                    span,
                }
            }
            Err(_) => {
                let mut unknown_span = span;
                let lexer = self.lexer.as_mut().expect("should have a lexer");

                if peeked {
                    lexer.next();
                }

                // Consecutive unknown tokens of the same type get condensed into a single
                // diagnostic and event
                while let Some((Err(_), peeked_span)) = lexer.peek() {
                    unknown_span = Span::new(
                        unknown_span.start(),
                        peeked_span.end() - unknown_span.start(),
                    );
                    lexer.next();
                }

                self.diagnostic(
                    Diagnostic::error("an unknown token was encountered")
                        .with_label(
                            Self::unsupported_token_text(self.source(span)),
                            unknown_span,
                        )
                        .into(),
                );

                Event::Token {
                    kind: SyntaxKind::Unknown,
                    span: unknown_span,
                }
            }
        };

        if peeked {
            self.buffered.push(event);
        } else {
            self.events.push(event);
        }

        None
    }

    /// A helper for unsupported token error span text.
    fn unsupported_token_text(token: &str) -> &'static str {
        match token {
            "&" => "did you mean to use `&&` here?",
            "|" => "did you mean to use `||` here?",
            _ => "this is not a supported WDL token",
        }
    }
}

impl<'a, T> Iterator for Parser<'a, T>
where
    T: ParserToken<'a>,
{
    type Item = (T, Span);

    fn next(&mut self) -> Option<(T, Span)> {
        while let Some((res, span)) = self.lexer.as_mut()?.next() {
            if let Some((token, span)) = self.consume_trivia(res, span, false) {
                self.events.push(Event::Token {
                    kind: token.into_syntax(),
                    span,
                });
                return Some((token, span));
            }
        }

        if !self.buffered.is_empty() {
            self.events.append(&mut self.buffered);
        }

        None
    }
}

/// Python-specific APIs.
#[cfg(feature = "unstable-python")]
mod python {
    use pyo3::IntoPyObjectExt;
    use pyo3::prelude::*;
    use pyo3::types::PyType;

    use crate::Span;
    use crate::SyntaxKind;
    use crate::parser::Event;

    /// Represents an event produced by the parser.
    ///
    /// The parser produces a stream of events that can be used to construct
    /// a CST.
    #[pyclass(module = "sprocket_bio.grammar.parser", name = "Event", eq)]
    #[derive(PartialEq)]
    #[expect(missing_debug_implementations)]
    pub enum PyEvent {
        /// A new node has started.
        NodeStarted {
            /// The kind of the node.
            kind: SyntaxKind,
            /// For left-recursive syntactic constructs, the parser produces
            /// a child node before it sees a parent. `forward_parent`
            /// saves the position of current event's parent.
            forward_parent: Option<usize>,
        },

        /// A node has finished.
        NodeFinished(),

        /// A token was encountered.
        Token {
            /// The syntax kind of the token.
            kind: SyntaxKind,
            /// The source span of the token.
            span: Span,
        },
    }

    #[pymethods]
    impl PyEvent {
        /// Gets an start node event for an abandoned node.
        #[classmethod]
        fn abandoned(_cls: &Bound<'_, PyType>) -> Self {
            Self::from_event(Event::abandoned())
        }

        /// Returns a printable representation of this object.
        fn __repr__(&self, py: Python<'_>) -> PyResult<String> {
            match self {
                Self::NodeStarted {
                    kind,
                    forward_parent,
                } => Ok(format!(
                    "Event.NodeStarted({}, {})",
                    // Equivalent to `repr(SyntaxKind)`.
                    kind.into_bound_py_any(py)?.repr()?.to_str()?,
                    // If `forward_parent` is `Some` write the plain integer, else write "None".
                    match forward_parent {
                        Some(x) => x.to_string(),
                        None => "None".to_owned(),
                    },
                )),
                Self::NodeFinished() => Ok("Event.NodeFinished()".to_owned()),
                Self::Token { kind, span } => Ok(format!(
                    "Event.Token({}, {})",
                    // Equivalent to `repr(SyntaxKind)`.
                    kind.into_bound_py_any(py)?.repr()?.to_str()?,
                    span.__repr__(),
                )),
            }
        }
    }

    /// Internal utilities not exposed to Python.
    impl PyEvent {
        /// Converts an [`Event`] into a [`PyEvent`].
        pub(crate) fn from_event(event: Event) -> Self {
            match event {
                Event::NodeStarted {
                    kind,
                    forward_parent,
                } => Self::NodeStarted {
                    kind,
                    forward_parent,
                },
                Event::NodeFinished => Self::NodeFinished(),
                Event::Token { kind, span } => Self::Token { kind, span },
            }
        }
    }
}

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

    #[test]
    fn expression_depth_limit() {
        let ok_map_literal = format!(
            "{} : {}",
            "{".repeat(MAX_DEPTH - 1),
            "}".repeat(MAX_DEPTH - 1)
        );
        let source = format!(
            r#"task foo {{
            command <<<>>>

            Map[String, Int] woah = {ok_map_literal}
        }}"#
        );
        let mut parser = Parser::new(Lexer::new(&source));
        crate::grammar::v1::items(&mut parser);
        assert!(!parser.diagnostic_context.halt);

        let bad_map_literal = format!("{} : {}", "{".repeat(MAX_DEPTH), "}".repeat(MAX_DEPTH));
        let source = format!(
            r#"task foo {{
            command <<<>>>

            Map[String, Int] woah = {bad_map_literal}
        }}"#
        );
        let mut parser = Parser::new(Lexer::new(&source));
        crate::grammar::v1::items(&mut parser);
        assert!(parser.diagnostic_context.halt);
    }
}