Skip to main content

xur_parser/parser/
mod.rs

1//! Recursive-descent parser producing the AST, modelled on `rustc_parse`.
2//!
3//! - The parser walks the token list keeping `token` (current) and
4//!   `prev_token`; a node's span is `lo.to(self.prev_token.span)`.
5//! - `check`, `eat` and `expect` record what would have been accepted at the
6//!   current position, so errors read "expected one of `,` or `)`, found `;`".
7//! - Parsing functions return [`PResult`]. Recovery points (items and
8//!   statements) report the error, skip ahead and carry on, leaving an `Err`
9//!   node in the tree.
10
11mod expected;
12mod expr;
13mod item;
14mod lit;
15mod pat;
16mod path;
17mod stmt;
18mod ty;
19
20#[cfg(test)]
21mod tests;
22
23use xur_ast::{Item, Module, NodeId, NodeIdGen};
24use xur_errors::Diag;
25use xur_span::{Ident, SourceFile, Span, Symbol};
26
27use self::expected::Expected;
28use crate::lexer::Lexer;
29use crate::token::{Keyword, Token, TokenKind};
30
31pub use self::path::PathStyle;
32
33/// Lexes and parses a whole source file, returning the module (complete
34/// even if there were errors, with `Err` nodes where parsing failed) and
35/// every diagnostic. Node ids are taken from `ids`.
36pub fn parse_file(file: &SourceFile, ids: &mut NodeIdGen) -> (Module, Vec<Diag>) {
37    let mut parser = Parser::for_file(file);
38    parser.ids = std::mem::take(ids);
39    let module = parser.parse_module();
40    *ids = std::mem::take(&mut parser.ids);
41    (module, parser.finish())
42}
43
44/// Parses `source` as module-level items. A synthetic file is added to
45/// `source_map` so that diagnostics can point into the generated code.
46pub fn parse_items(
47    source: &str,
48    source_map: &mut xur_span::SourceMap,
49    ids: &mut NodeIdGen,
50) -> (Vec<Item>, Vec<Diag>) {
51    let file = source_map.add_file("<macro expansion>".to_owned(), source.to_owned());
52    let mut parser = Parser::for_file(&file);
53    parser.ids = std::mem::take(ids);
54    let module = parser.parse_module();
55    *ids = std::mem::take(&mut parser.ids);
56    (module.items, parser.finish())
57}
58
59/// The result of a parsing function. The error has not been reported yet:
60/// the caller either reports it or propagates it to a recovery point.
61pub type PResult<T> = Result<T, Diag>;
62
63pub struct Parser<'src> {
64    src: &'src str,
65    /// Global position of the start of `src`.
66    offset: usize,
67    /// Always ends with `Eof`.
68    tokens: Vec<Token<'src>>,
69    /// Index of `token` in `tokens`.
70    pos: usize,
71    /// The current token.
72    token: Token<'src>,
73    /// The previously consumed token; its span ends the node being parsed.
74    prev_token: Token<'src>,
75    /// Everything checked for since the last `bump`.
76    expected: Vec<Expected>,
77    diags: Vec<Diag>,
78    restrictions: Restrictions,
79    ids: NodeIdGen,
80}
81
82/// Context that changes how an expression is parsed (rustc's
83/// `Restrictions`).
84#[derive(Debug, Clone, Copy, Default)]
85struct Restrictions {
86    /// Parsing an expression statement: a block-like expression such as `if`
87    /// ends the statement, so `if c {} -1` is two statements, not a
88    /// subtraction.
89    stmt_expr: bool,
90    /// Parsing the head of an `if`, `while`, `match` or `for`, where a `{`
91    /// begins the body: `for i in 0.. {}` is an open-ended range.
92    before_block: bool,
93}
94
95impl<'src> Parser<'src> {
96    /// Lexes a standalone string and prepares to parse it; spans start at
97    /// position 0. Lex errors are kept and returned by [`Parser::finish`]
98    /// along with any parse errors.
99    pub fn new(src: &'src str) -> Self {
100        Self::from_lexer(src, 0, Lexer::new(src))
101    }
102
103    /// Like [`Parser::new`], for a file from the source map.
104    pub fn for_file(file: &'src SourceFile) -> Self {
105        Self::from_lexer(&file.src, file.start, Lexer::for_file(file))
106    }
107
108    fn from_lexer(src: &'src str, offset: usize, lexer: Lexer<'src>) -> Self {
109        let (tokens, lex_errors) = lexer.tokenise();
110        let token = tokens[0];
111        Self {
112            src,
113            offset,
114            tokens,
115            pos: 0,
116            token,
117            // A placeholder until the first `bump`; see `token_starts_line`.
118            prev_token: Token::new(TokenKind::Eof, Span::new(offset, offset)),
119            expected: Vec::new(),
120            diags: lex_errors.into_iter().map(Diag::from).collect(),
121            restrictions: Restrictions::default(),
122            ids: NodeIdGen::default(),
123        }
124    }
125
126    /// Returns every diagnostic reported while lexing and parsing.
127    pub fn finish(self) -> Vec<Diag> {
128        self.diags
129    }
130
131    /// Whether all input has been consumed.
132    pub fn is_at_end(&self) -> bool {
133        self.token.kind == TokenKind::Eof
134    }
135
136    /// Errors unless all input has been consumed.
137    pub fn expect_end(&mut self) -> PResult<()> {
138        self.expect(TokenKind::Eof)
139    }
140
141    fn next_id(&mut self) -> NodeId {
142        self.ids.next_id()
143    }
144
145    fn report(&mut self, diag: Diag) {
146        self.diags.push(diag);
147    }
148
149    /// Advances to the next token. `Eof` is never advanced past.
150    fn bump(&mut self) {
151        self.prev_token = self.token;
152        self.pos = (self.pos + 1).min(self.tokens.len() - 1);
153        self.token = self.tokens[self.pos];
154        self.expected.clear();
155    }
156
157    /// The kind of the token `n` places after the current one.
158    fn look_ahead(&self, n: usize) -> TokenKind<'src> {
159        let index = (self.pos + n).min(self.tokens.len() - 1);
160        self.tokens[index].kind
161    }
162
163    /// Runs `parse` with `restrictions` in effect.
164    fn with_res<T>(&mut self, restrictions: Restrictions, parse: impl FnOnce(&mut Self) -> T) -> T {
165        let saved = std::mem::replace(&mut self.restrictions, restrictions);
166        let result = parse(self);
167        self.restrictions = saved;
168        result
169    }
170
171    /// Whether the current token is `kind`; if not, `kind` is recorded as
172    /// expected.
173    fn check(&mut self, kind: TokenKind<'static>) -> bool {
174        let found = self.token.kind == kind;
175        if !found {
176            self.expected.push(Expected::Token(kind));
177        }
178        found
179    }
180
181    /// Consumes the current token if it is `kind`.
182    fn eat(&mut self, kind: TokenKind<'static>) -> bool {
183        let found = self.check(kind);
184        if found {
185            self.bump();
186        }
187        found
188    }
189
190    fn expect(&mut self, kind: TokenKind<'static>) -> PResult<()> {
191        if self.eat(kind) {
192            Ok(())
193        } else {
194            Err(self.unexpected())
195        }
196    }
197
198    fn eat_keyword(&mut self, keyword: Keyword) -> bool {
199        self.eat(TokenKind::Keyword(keyword))
200    }
201
202    /// Consumes the current token if it is `kind`, without recording it as
203    /// expected. Used for tokens that begin a category already named in the
204    /// error, so it reads "expected type" rather than listing `(`, `_`, ...
205    fn eat_noexpect(&mut self, kind: TokenKind<'static>) -> bool {
206        let found = self.token.kind == kind;
207        if found {
208            self.bump();
209        }
210        found
211    }
212
213    /// Records that a whole category of syntax would have been accepted here.
214    fn expected(&mut self, expected: Expected) {
215        self.expected.push(expected);
216    }
217
218    fn parse_ident(&mut self) -> PResult<Ident> {
219        match self.token.kind {
220            TokenKind::Ident(name) => {
221                let ident = Ident::new(Symbol::intern(name), self.token.span);
222                self.bump();
223                Ok(ident)
224            }
225            _ => {
226                self.expected(Expected::Ident);
227                Err(self.unexpected())
228            }
229        }
230    }
231
232    /// Parses `item (, item)* ,? close`, the opening delimiter having already
233    /// been consumed. Also returns whether there was a trailing comma, which
234    /// distinguishes `(a)` from the one-element tuple `(a,)`.
235    fn parse_comma_seq<T>(
236        &mut self,
237        close: TokenKind<'static>,
238        mut parse: impl FnMut(&mut Self) -> PResult<T>,
239    ) -> PResult<(Vec<T>, bool)> {
240        let mut items = Vec::new();
241        let mut trailing_comma = false;
242        while !self.eat(close) {
243            items.push(parse(self)?);
244            trailing_comma = self.eat(TokenKind::Comma);
245            if !trailing_comma {
246                self.expect(close)?;
247                break;
248            }
249        }
250        Ok((items, trailing_comma))
251    }
252
253    /// Like [`Self::parse_comma_seq`], when trailing commas don't matter.
254    fn parse_delimited<T>(
255        &mut self,
256        close: TokenKind<'static>,
257        parse: impl FnMut(&mut Self) -> PResult<T>,
258    ) -> PResult<Vec<T>> {
259        self.parse_comma_seq(close, parse).map(|(items, _)| items)
260    }
261
262    /// Builds an "expected ..., found ..." error for the current token from
263    /// everything checked for since the last `bump`.
264    fn unexpected(&self) -> Diag {
265        let alternatives = expected::alternatives(&self.expected);
266        let expected = expected::join(&alternatives);
267        let found = self.describe_token(self.token);
268        let (message, label) = match alternatives.len() {
269            0 => (format!("unexpected {found}"), "unexpected token".to_owned()),
270            1 => (
271                format!("expected {expected}, found {found}"),
272                format!("expected {expected}"),
273            ),
274            n => (
275                format!("expected {expected}, found {found}"),
276                format!("expected one of {n} possible tokens"),
277            ),
278        };
279
280        // As in rustc: if the unexpected token starts a new line, the problem
281        // is most likely something missing at the end of the previous one.
282        if self.token_starts_line() {
283            let missing = self.prev_token.span.shrink_to_hi();
284            Diag::error(message, missing)
285                .with_label(missing, label)
286                .with_label(self.token.span, "unexpected token")
287        } else {
288            Diag::error(message, self.token.span).with_label(self.token.span, label)
289        }
290    }
291
292    /// Whether a line break separates the current token from the previous
293    /// one. Always false for the first token, which has no previous one.
294    fn token_starts_line(&self) -> bool {
295        let has_prev = self.prev_token.kind != TokenKind::Eof;
296        has_prev
297            && self
298                .text(self.prev_token.span.end, self.token.span.start)
299                .contains('\n')
300    }
301
302    /// The source text between global positions `start` and `end`.
303    fn text(&self, start: usize, end: usize) -> &'src str {
304        &self.src[start - self.offset..end - self.offset]
305    }
306
307    /// Expects a `;`. As in rustc, a `;` missing at the end of a line is
308    /// reported but otherwise treated as present, so parsing continues with
309    /// the next line instead of skipping it.
310    fn expect_semi(&mut self) -> PResult<()> {
311        if self.eat(TokenKind::Semi) {
312            return Ok(());
313        }
314        let diag = self.unexpected();
315        if self.token_starts_line() {
316            self.report(diag);
317            Ok(())
318        } else {
319            Err(diag)
320        }
321    }
322
323    /// How a token is named in "found ..." messages.
324    fn describe_token(&self, token: Token<'_>) -> String {
325        match token.kind {
326            TokenKind::Eof => "end of file".to_owned(),
327            TokenKind::Keyword(keyword) => format!("keyword `{keyword}`"),
328            _ => format!("`{}`", self.text(token.span.start, token.span.end)),
329        }
330    }
331}