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
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2021, tree-sitter authors.
// Licensed under either of Apache License, Version 2.0, or MIT license, at your option.
// Please see the LICENSE-APACHE or LICENSE-MIT files in this distribution for license details.
// ------------------------------------------------------------------------------------------------

use std::fmt::Display;
use std::iter::Peekable;
use std::str::Chars;

use regex::Regex;
use thiserror::Error;
use tree_sitter::CaptureQuantifier;
use tree_sitter::CaptureQuantifier::One;
use tree_sitter::CaptureQuantifier::OneOrMore;
use tree_sitter::CaptureQuantifier::Zero;
use tree_sitter::CaptureQuantifier::ZeroOrMore;
use tree_sitter::CaptureQuantifier::ZeroOrOne;
use tree_sitter::Language;
use tree_sitter::Query;
use tree_sitter::QueryError;

use crate::ast;
use crate::Identifier;

pub const FULL_MATCH: &str = "__tsg__full_match";

impl ast::File {
    /// Parses a graph DSL file, returning a new `File` instance.
    pub fn from_str(language: Language, source: &str) -> Result<Self, ParseError> {
        let mut file = ast::File::new(language);
        #[allow(deprecated)]
        file.parse(source)?;
        file.check()?;
        Ok(file)
    }

    /// Parses a graph DSL file, adding its content to an existing `File` instance.
    #[deprecated(
        note = "Parsing multiple times into the same `File` instance is unsound. Use `File::from_str` instead."
    )]
    pub fn parse(&mut self, content: &str) -> Result<(), ParseError> {
        Parser::new(content).parse_into_file(self)
    }
}

/// An error that can occur while parsing a graph DSL file
#[derive(Debug, Error)]
pub enum ParseError {
    #[error("Expected quantifier at {0}")]
    ExpectedQuantifier(Location),
    #[error("Expected '{0}' at {1}")]
    ExpectedToken(&'static str, Location),
    #[error("Expected variable name at {0}")]
    ExpectedVariable(Location),
    #[error("Expected unscoped variable at {0}")]
    ExpectedUnscopedVariable(Location),
    #[error("Invalid regular expression /{0}/ at {1}")]
    InvalidRegex(String, Location),
    #[error("Expected integer constant in regex capture at {0}")]
    InvalidRegexCapture(Location),
    // TODO: The positions in the wrapped QueryError will be incorrect, since they will count the
    // row/column from the start of the query, not from the start of the file.
    #[error("Invalid query pattern: {}", _0.message)]
    QueryError(#[from] QueryError),
    #[error("Unexpected character '{0}' in {1} at {2}")]
    UnexpectedCharacter(char, &'static str, Location),
    #[error("Unexpected end of file at {0}")]
    UnexpectedEOF(Location),
    #[error("Unexpected keyword '{0}' at {1}")]
    UnexpectedKeyword(String, Location),
    #[error("Unexpected literal '#{0}' at {1}")]
    UnexpectedLiteral(String, Location),
    #[error(transparent)]
    Check(#[from] crate::checker::CheckError),
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

impl ParseError {
    /// Wraps an existing [`std::error::Error`][] as an execution error
    pub fn other<E>(err: E) -> ParseError
    where
        E: Into<anyhow::Error>,
    {
        Self::Other(err.into())
    }
}

/// The location of a graph DSL entity within its file
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Location {
    pub row: usize,
    pub column: usize,
}

impl Location {
    fn advance(&mut self, ch: char) {
        if ch == '\n' {
            self.row += 1;
            self.column = 0;
        } else {
            self.column += 1;
        }
    }
}

impl Display for Location {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "({}, {})", self.row + 1, self.column + 1)
    }
}

struct Parser<'a> {
    source: &'a str,
    chars: Peekable<Chars<'a>>,
    offset: usize,
    location: Location,
    query_source: String,
}

fn is_ident_start(c: char) -> bool {
    c == '_' || c.is_alphabetic()
}

fn is_ident(c: char) -> bool {
    c == '_' || c == '-' || c.is_alphanumeric()
}

impl<'a> Parser<'a> {
    fn new(source: &'a str) -> Parser<'a> {
        let chars = source.chars().peekable();
        let query_source = String::with_capacity(source.len());
        Parser {
            source,
            chars,
            offset: 0,
            location: Location::default(),
            query_source,
        }
    }
}

impl<'a> Parser<'a> {
    fn peek(&mut self) -> Result<char, ParseError> {
        self.chars
            .peek()
            .copied()
            .ok_or_else(|| ParseError::UnexpectedEOF(self.location))
    }

    fn try_peek(&mut self) -> Option<char> {
        self.peek().ok()
    }

    fn next(&mut self) -> Result<char, ParseError> {
        let ch = self
            .chars
            .next()
            .ok_or_else(|| ParseError::UnexpectedEOF(self.location))?;
        self.offset += ch.len_utf8();
        self.location.advance(ch);
        Ok(ch)
    }

    fn skip(&mut self) -> Result<(), ParseError> {
        self.next().map(|_| ())
    }

    fn consume_whitespace(&mut self) {
        let mut in_comment = false;
        while let Some(ch) = self.try_peek() {
            if in_comment {
                if ch == '\n' {
                    in_comment = false;
                }
            } else {
                if ch == ';' {
                    in_comment = true;
                } else if !ch.is_whitespace() {
                    return;
                }
            }
            self.skip().unwrap();
        }
    }

    fn consume_while(&mut self, mut f: impl FnMut(char) -> bool) {
        while let Some(ch) = self.try_peek() {
            if !f(ch) {
                return;
            }
            self.skip().unwrap();
        }
    }

    fn consume_n(&mut self, count: usize) -> Result<(), ParseError> {
        for _ in 0..count {
            self.next()?;
        }
        Ok(())
    }

    fn consume_token(&mut self, token: &'static str) -> Result<(), ParseError> {
        if self.source[self.offset..].starts_with(token) {
            self.consume_n(token.len())
        } else {
            Err(ParseError::ExpectedToken(token, self.location))
        }
    }

    fn parse_into_file(&mut self, file: &mut ast::File) -> Result<(), ParseError> {
        self.consume_whitespace();
        while self.try_peek().is_some() {
            if let Ok(_) = self.consume_token("global") {
                self.consume_whitespace();
                let global = self.parse_global()?;
                file.globals.push(global);
            } else if let Ok(_) = self.consume_token("attribute") {
                self.consume_whitespace();
                let shorthand = self.parse_shorthand()?;
                file.shorthands.add(shorthand);
            } else {
                let stanza = self.parse_stanza(file.language)?;
                file.stanzas.push(stanza);
            }
            self.consume_whitespace();
        }
        // we can unwrap here because all queries have already been parsed before
        file.query = Some(Query::new(file.language, &self.query_source).unwrap());
        Ok(())
    }

    fn parse_global(&mut self) -> Result<ast::Global, ParseError> {
        let location = self.location;
        let name = self.parse_identifier("global variable")?;
        let quantifier = self.parse_quantifier()?;
        Ok(ast::Global {
            name,
            quantifier,
            location,
        })
    }

    fn parse_shorthand(&mut self) -> Result<ast::AttributeShorthand, ParseError> {
        let location = self.location;
        let name = self.parse_identifier("shorthand name")?;
        self.consume_whitespace();
        self.consume_token("=")?;
        self.consume_whitespace();
        let variable = self.parse_unscoped_variable()?;
        self.consume_whitespace();
        self.consume_token("=>")?;
        self.consume_whitespace();
        let attributes = self.parse_attributes()?;
        Ok(ast::AttributeShorthand {
            name,
            variable,
            attributes,
            location,
        })
    }

    fn parse_quantifier(&mut self) -> Result<CaptureQuantifier, ParseError> {
        let mut quantifier = One;
        if let Some(c) = self.try_peek() {
            self.skip().unwrap();
            if c == '?' {
                quantifier = ZeroOrOne;
            } else if c == '*' {
                quantifier = ZeroOrMore;
            } else if c == '+' {
                quantifier = OneOrMore;
            } else if !c.is_whitespace() {
                return Err(ParseError::ExpectedQuantifier(self.location));
            }
        }
        Ok(quantifier)
    }

    fn parse_stanza(&mut self, language: Language) -> Result<ast::Stanza, ParseError> {
        let location = self.location;
        let query = self.parse_query(language)?;
        self.consume_whitespace();
        let statements = self.parse_statements()?;
        Ok(ast::Stanza {
            query,
            statements,
            full_match_file_capture_index: usize::MAX, // set in checker
            location,
        })
    }

    fn parse_query(&mut self, language: Language) -> Result<Query, ParseError> {
        let location = self.location;
        let query_start = self.offset;
        self.skip_query()?;
        let query_end = self.offset;
        let query_source = self.source[query_start..query_end].to_owned() + "@" + FULL_MATCH;
        // If tree-sitter allowed us to incrementally add patterns to a query, we wouldn't need
        // the global query_source.
        self.query_source += &query_source;
        self.query_source += "\n";
        let query = Query::new(language, &query_source).map_err(|mut e| {
            e.row += location.row;
            e.offset += query_start;
            e
        })?;
        Ok(query)
    }

    fn skip_query(&mut self) -> Result<(), ParseError> {
        let mut paren_depth = 0;
        let mut in_string = false;
        let mut in_escape = false;
        let mut in_comment = false;
        loop {
            let ch = self.peek()?;
            if in_escape {
                in_escape = false;
            } else if in_string {
                match ch {
                    '\\' => {
                        in_escape = true;
                    }
                    '"' | '\n' => {
                        in_string = false;
                    }
                    _ => {}
                }
            } else if in_comment {
                if ch == '\n' {
                    in_comment = false;
                }
            } else {
                match ch {
                    '"' => in_string = true,
                    '(' => paren_depth += 1,
                    ')' => {
                        if paren_depth > 0 {
                            paren_depth -= 1;
                        }
                    }
                    '{' => return Ok(()),
                    ';' => in_comment = true,
                    _ => {}
                }
            }
            self.skip().unwrap();
        }
    }

    fn parse_statements(&mut self) -> Result<Vec<ast::Statement>, ParseError> {
        self.consume_token("{")?;
        let mut statements = Vec::new();
        self.consume_whitespace();
        while self.peek()? != '}' {
            let statement = self.parse_statement()?;
            statements.push(statement);
            self.consume_whitespace();
        }
        self.consume_token("}")?;
        Ok(statements)
    }

    fn parse_name(&mut self, within: &'static str) -> Result<&'a str, ParseError> {
        let start = self.offset;
        let ch = self.next()?;
        if !is_ident_start(ch) {
            return Err(ParseError::UnexpectedCharacter(ch, within, self.location));
        }
        self.consume_while(is_ident);
        let end = self.offset;
        Ok(&self.source[start..end])
    }

    fn parse_statement(&mut self) -> Result<ast::Statement, ParseError> {
        let keyword_location = self.location;
        let keyword = self.parse_name("keyword")?;
        self.consume_whitespace();
        if keyword == "let" {
            let variable = self.parse_variable()?;
            self.consume_whitespace();
            self.consume_token("=")?;
            self.consume_whitespace();
            let value = self.parse_expression()?;
            Ok(ast::DeclareImmutable {
                variable,
                value,
                location: keyword_location,
            }
            .into())
        } else if keyword == "var" {
            let variable = self.parse_variable()?;
            self.consume_whitespace();
            self.consume_token("=")?;
            self.consume_whitespace();
            let value = self.parse_expression()?;
            Ok(ast::DeclareMutable {
                variable,
                value,
                location: keyword_location,
            }
            .into())
        } else if keyword == "set" {
            let variable = self.parse_variable()?;
            self.consume_whitespace();
            self.consume_token("=")?;
            self.consume_whitespace();
            let value = self.parse_expression()?;
            Ok(ast::Assign {
                variable,
                value,
                location: keyword_location,
            }
            .into())
        } else if keyword == "node" {
            let node = self.parse_variable()?;
            Ok(ast::CreateGraphNode {
                node,
                location: keyword_location,
            }
            .into())
        } else if keyword == "edge" {
            let source = self.parse_expression()?;
            self.consume_whitespace();
            self.consume_token("->")?;
            self.consume_whitespace();
            let sink = self.parse_expression()?;
            Ok(ast::CreateEdge {
                source,
                sink,
                location: keyword_location,
            }
            .into())
        } else if keyword == "attr" {
            self.consume_token("(")?;
            self.consume_whitespace();
            let node_or_source = self.parse_expression()?;
            self.consume_whitespace();

            if self.peek()? == '-' {
                let source = node_or_source;
                self.consume_token("->")?;
                self.consume_whitespace();
                let sink = self.parse_expression()?;
                self.consume_whitespace();
                self.consume_token(")")?;
                self.consume_whitespace();
                let attributes = self.parse_attributes()?;
                Ok(ast::AddEdgeAttribute {
                    source,
                    sink,
                    attributes,
                    location: keyword_location,
                }
                .into())
            } else {
                let node = node_or_source;
                self.consume_whitespace();
                self.consume_token(")")?;
                self.consume_whitespace();
                let attributes = self.parse_attributes()?;
                Ok(ast::AddGraphNodeAttribute {
                    node,
                    attributes,
                    location: keyword_location,
                }
                .into())
            }
        } else if keyword == "print" {
            let mut values = vec![self.parse_expression()?];
            self.consume_whitespace();
            while self.try_peek() == Some(',') {
                self.consume_token(",")?;
                self.consume_whitespace();
                values.push(self.parse_expression()?);
                self.consume_whitespace();
            }
            self.consume_whitespace();
            Ok(ast::Print {
                values,
                location: keyword_location,
            }
            .into())
        } else if keyword == "scan" {
            let value = self.parse_expression()?;
            self.consume_whitespace();
            self.consume_token("{")?;
            self.consume_whitespace();
            let mut arms = Vec::new();
            while self.peek()? != '}' {
                let pattern_location = self.location;
                let pattern = self.parse_string()?;
                let regex = Regex::new(&pattern)
                    .map_err(|_| ParseError::InvalidRegex(pattern.into(), pattern_location))?;
                self.consume_whitespace();
                let statements = self.parse_statements()?;
                arms.push(ast::ScanArm {
                    regex,
                    statements,
                    location: keyword_location,
                });
                self.consume_whitespace();
            }
            self.consume_token("}")?;
            Ok(ast::Scan {
                value,
                arms,
                location: keyword_location,
            }
            .into())
        } else if keyword == "if" {
            let mut arms = Vec::new();

            // if
            let location = keyword_location;
            self.consume_whitespace();
            let conditions = self.parse_conditions()?;
            self.consume_whitespace();
            let statements = self.parse_statements()?;
            self.consume_whitespace();
            arms.push(ast::IfArm {
                conditions,
                statements,
                location,
            });

            // elif
            let mut location = self.location;
            while let Ok(_) = self.consume_token("elif") {
                self.consume_whitespace();
                let conditions = self.parse_conditions()?;
                self.consume_whitespace();
                let statements = self.parse_statements()?;
                self.consume_whitespace();
                arms.push(ast::IfArm {
                    conditions,
                    statements,
                    location,
                });
                self.consume_whitespace();
                location = self.location;
            }

            // else
            let location = self.location;
            if let Ok(_) = self.consume_token("else") {
                let conditions = vec![];
                self.consume_whitespace();
                let statements = self.parse_statements()?;
                self.consume_whitespace();
                arms.push(ast::IfArm {
                    conditions,
                    statements,
                    location,
                });
                self.consume_whitespace();
            }

            Ok(ast::If {
                arms,
                location: keyword_location,
            }
            .into())
        } else if keyword == "for" {
            self.consume_whitespace();
            let variable = self.parse_unscoped_variable()?;
            self.consume_whitespace();
            self.consume_token("in")?;
            self.consume_whitespace();
            let value = self.parse_expression()?;
            self.consume_whitespace();
            let statements = self.parse_statements()?;
            Ok(ast::ForIn {
                variable,
                value,
                statements,
                location: keyword_location,
            }
            .into())
        } else {
            Err(ParseError::UnexpectedKeyword(
                keyword.into(),
                keyword_location,
            ))
        }
    }

    fn parse_conditions(&mut self) -> Result<Vec<ast::Condition>, ParseError> {
        let mut conditions = Vec::new();
        let mut has_next = true;
        while has_next {
            conditions.push(self.parse_condition()?);
            self.consume_whitespace();
            if let Some(',') = self.try_peek() {
                self.consume_token(",")?;
                self.consume_whitespace();
                has_next = true;
            } else {
                has_next = false;
            }
        }
        Ok(conditions)
    }

    fn parse_condition(&mut self) -> Result<ast::Condition, ParseError> {
        let location = self.location;
        let condition = if let Ok(_) = self.consume_token("some") {
            self.consume_whitespace();
            let value = self.parse_expression()?;
            ast::Condition::Some { value, location }
        } else if let Ok(_) = self.consume_token("none") {
            self.consume_whitespace();
            let value = self.parse_expression()?;
            ast::Condition::None { value, location }
        } else if let Ok(value) = self.parse_expression() {
            self.consume_whitespace();
            ast::Condition::Bool { value, location }
        } else {
            return Err(ParseError::ExpectedToken(
                "(some|none)? EXPRESSION",
                location,
            ));
        };
        self.consume_whitespace();
        Ok(condition)
    }

    fn parse_identifier(&mut self, within: &'static str) -> Result<Identifier, ParseError> {
        let content = self.parse_name(within)?;
        Ok(Identifier::from(content))
    }

    fn parse_string(&mut self) -> Result<String, ParseError> {
        self.consume_token("\"")?;
        let mut escape = false;
        let mut value = String::new();
        loop {
            let ch = self.next()?;
            if escape {
                escape = false;
                value.push(match ch {
                    '0' => '\0',
                    'n' => '\n',
                    'r' => '\r',
                    't' => '\t',
                    _ => ch,
                });
            } else {
                match ch {
                    '"' => return Ok(value),
                    '\\' => escape = true,
                    _ => value.push(ch),
                }
            }
        }
    }

    fn parse_expression(&mut self) -> Result<ast::Expression, ParseError> {
        let mut expression = match self.peek()? {
            '#' => self.parse_literal()?,
            '"' => self.parse_string()?.into(),
            '@' => self.parse_capture()?.into(),
            '$' => self.parse_regex_capture()?.into(),
            '(' => self.parse_call()?,
            '[' => self.parse_list()?,
            '{' => self.parse_set()?,
            ch if ch.is_ascii_digit() => self.parse_integer_constant()?,
            ch if is_ident_start(ch) => {
                let location = self.location;
                let name = self.parse_identifier("variable name")?;
                ast::UnscopedVariable { name, location }.into()
            }
            ch => {
                return Err(ParseError::UnexpectedCharacter(
                    ch,
                    "expression",
                    self.location,
                ))
            }
        };
        self.consume_whitespace();
        while self.try_peek() == Some('.') {
            self.skip().unwrap();
            self.consume_whitespace();
            let location = self.location;
            let scope = Box::new(expression);
            let name = self.parse_identifier("scoped variable name")?;
            self.consume_whitespace();
            expression = ast::ScopedVariable {
                scope,
                name,
                location,
            }
            .into();
        }
        Ok(expression)
    }

    fn parse_call(&mut self) -> Result<ast::Expression, ParseError> {
        self.consume_token("(")?;
        self.consume_whitespace();
        let function = self.parse_identifier("function name")?;
        self.consume_whitespace();
        let mut parameters = Vec::new();
        while self.peek()? != ')' {
            parameters.push(self.parse_expression()?);
            self.consume_whitespace();
        }
        self.consume_token(")")?;
        Ok(ast::Call {
            function,
            parameters,
        }
        .into())
    }

    fn parse_sequence(&mut self, end_marker: char) -> Result<Vec<ast::Expression>, ParseError> {
        let mut elements = Vec::new();
        while self.peek()? != end_marker {
            elements.push(self.parse_expression()?);
            self.consume_whitespace();
            if self.peek()? != end_marker {
                self.consume_token(",")?;
                self.consume_whitespace();
            }
        }
        Ok(elements)
    }

    fn parse_list(&mut self) -> Result<ast::Expression, ParseError> {
        let location = self.location;
        self.consume_token("[")?;
        self.consume_whitespace();
        if let Ok(_) = self.consume_token("]") {
            return Ok(ast::ListLiteral { elements: vec![] }.into());
        }
        let first_element = self.parse_expression()?;
        self.consume_whitespace();
        if let Ok(_) = self.consume_token("]") {
            let elements = vec![first_element];
            Ok(ast::ListLiteral { elements }.into())
        } else if let Ok(_) = self.consume_token(",") {
            self.consume_whitespace();
            let mut elements = self.parse_sequence(']')?;
            self.consume_whitespace();
            self.consume_token("]")?;
            elements.insert(0, first_element);
            Ok(ast::ListLiteral { elements }.into())
        } else {
            self.consume_token("for")?;
            self.consume_whitespace();
            let variable = self.parse_unscoped_variable()?;
            self.consume_whitespace();
            self.consume_token("in")?;
            self.consume_whitespace();
            let value = self.parse_expression()?;
            self.consume_whitespace();
            self.consume_token("]")?;
            Ok(ast::ListComprehension {
                element: first_element.into(),
                variable,
                value: value.into(),
                location,
            }
            .into())
        }
    }

    fn parse_set(&mut self) -> Result<ast::Expression, ParseError> {
        let location = self.location;
        self.consume_token("{")?;
        self.consume_whitespace();
        if let Ok(_) = self.consume_token("}") {
            return Ok(ast::SetLiteral { elements: vec![] }.into());
        }
        let first_element = self.parse_expression()?;
        self.consume_whitespace();
        if let Ok(_) = self.consume_token("}") {
            let elements = vec![first_element];
            Ok(ast::SetLiteral { elements }.into())
        } else if let Ok(_) = self.consume_token(",") {
            self.consume_whitespace();
            let mut elements = self.parse_sequence('}')?;
            self.consume_whitespace();
            self.consume_token("}")?;
            elements.insert(0, first_element);
            Ok(ast::SetLiteral { elements }.into())
        } else {
            self.consume_token("for")?;
            self.consume_whitespace();
            let variable = self.parse_unscoped_variable()?;
            self.consume_whitespace();
            self.consume_token("in")?;
            self.consume_whitespace();
            let value = self.parse_expression()?;
            self.consume_whitespace();
            self.consume_token("}")?;
            Ok(ast::SetComprehension {
                element: first_element.into(),
                variable,
                value: value.into(),
                location,
            }
            .into())
        }
    }

    fn parse_capture(&mut self) -> Result<ast::Capture, ParseError> {
        let location = self.location;
        let start = self.offset;
        self.consume_token("@")?;
        let ch = self.next()?;
        if !is_ident_start(ch) {
            return Err(ParseError::UnexpectedCharacter(
                ch,
                "query capture",
                self.location,
            ));
        }
        self.consume_while(is_ident);
        let end = self.offset;
        let name = Identifier::from(&self.source[start + 1..end]);
        Ok(ast::Capture {
            name,
            quantifier: Zero,                 // set in checker
            file_capture_index: usize::MAX,   // set in checker
            stanza_capture_index: usize::MAX, // set in checker
            location,
        }
        .into())
    }

    fn parse_integer_constant(&mut self) -> Result<ast::Expression, ParseError> {
        // We'll have already verified that the next digit is an integer.
        let start = self.offset;
        self.consume_while(|ch| ch.is_ascii_digit());
        let end = self.offset;
        let value = u32::from_str_radix(&self.source[start..end], 10).unwrap();
        Ok(ast::IntegerConstant { value }.into())
    }

    fn parse_literal(&mut self) -> Result<ast::Expression, ParseError> {
        let literal_location = self.location;
        self.consume_token("#")?;
        let literal = self.parse_name("literal")?;
        if literal == "false" {
            return Ok(ast::Expression::FalseLiteral);
        } else if literal == "null" {
            return Ok(ast::Expression::NullLiteral);
        } else if literal == "true" {
            return Ok(ast::Expression::TrueLiteral);
        } else {
            Err(ParseError::UnexpectedLiteral(
                literal.into(),
                literal_location,
            ))
        }
    }

    fn parse_regex_capture(&mut self) -> Result<ast::RegexCapture, ParseError> {
        let regex_capture_location = self.location;
        self.consume_token("$")?;
        let start = self.offset;
        self.consume_while(|ch| ch.is_ascii_digit());
        let end = self.offset;
        if start == end {
            return Err(ParseError::InvalidRegexCapture(regex_capture_location));
        }
        let match_index = usize::from_str_radix(&self.source[start..end], 10).unwrap();
        Ok(ast::RegexCapture { match_index }.into())
    }

    fn parse_attributes(&mut self) -> Result<Vec<ast::Attribute>, ParseError> {
        let mut attributes = vec![self.parse_attribute()?];
        self.consume_whitespace();
        while self.try_peek() == Some(',') {
            self.skip().unwrap();
            self.consume_whitespace();
            attributes.push(self.parse_attribute()?);
            self.consume_whitespace();
        }
        Ok(attributes)
    }

    fn parse_attribute(&mut self) -> Result<ast::Attribute, ParseError> {
        let name = self.parse_identifier("attribute name")?;
        self.consume_whitespace();
        let value = if self.try_peek() == Some('=') {
            self.consume_token("=")?;
            self.consume_whitespace();
            self.parse_expression()?
        } else {
            ast::Expression::TrueLiteral
        };
        Ok(ast::Attribute { name, value })
    }

    fn parse_variable(&mut self) -> Result<ast::Variable, ParseError> {
        let expression_location = self.location;
        match self.parse_expression()? {
            ast::Expression::Variable(variable) => Ok(variable),
            _ => Err(ParseError::ExpectedVariable(expression_location)),
        }
    }

    fn parse_unscoped_variable(&mut self) -> Result<ast::UnscopedVariable, ParseError> {
        match self.parse_variable()? {
            ast::Variable::Unscoped(variable) => Ok(variable),
            ast::Variable::Scoped(variable) => {
                Err(ParseError::ExpectedUnscopedVariable(variable.location))
            }
        }
    }
}