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