Skip to main content

sway_parse/
parser.rs

1use crate::{Parse, ParseToEnd, Peek};
2use core::marker::PhantomData;
3use std::cell::RefCell;
4use sway_ast::keywords::Keyword;
5use sway_ast::literal::Literal;
6use sway_ast::token::{
7    DocComment, GenericTokenTree, Group, Punct, Spacing, TokenStream, TokenTree,
8};
9use sway_ast::PubToken;
10use sway_error::error::CompileError;
11use sway_error::handler::{ErrorEmitted, Handler};
12use sway_error::parser_error::{ParseError, ParseErrorKind};
13use sway_features::ExperimentalFeatures;
14use sway_types::{
15    ast::{Delimiter, PunctKind},
16    Ident, Span, Spanned,
17};
18
19pub struct Parser<'a, 'e> {
20    token_trees: &'a [TokenTree],
21    full_span: Span,
22    handler: &'e Handler,
23    pub check_double_underscore: bool,
24    pub experimental: ExperimentalFeatures,
25}
26
27impl<'a, 'e> Parser<'a, 'e> {
28    pub fn new(
29        handler: &'e Handler,
30        token_stream: &'a TokenStream,
31        experimental: ExperimentalFeatures,
32    ) -> Parser<'a, 'e> {
33        Parser {
34            token_trees: token_stream.token_trees(),
35            full_span: token_stream.span(),
36            handler,
37            check_double_underscore: true,
38            experimental,
39        }
40    }
41
42    pub fn emit_error(&mut self, kind: ParseErrorKind) -> ErrorEmitted {
43        let span = match self.token_trees {
44            [token_tree, ..] => token_tree.span(),
45            _ => {
46                // Create a new span that points to _just_ after the last parsed item or 1
47                // character before that if the last parsed item is the last item in the full span.
48                let num_trailing_spaces =
49                    self.full_span.as_str().len() - self.full_span.as_str().trim_end().len();
50                let trim_offset = if num_trailing_spaces == 0 {
51                    1
52                } else {
53                    num_trailing_spaces
54                };
55                Span::new(
56                    self.full_span.src().clone(),
57                    self.full_span.end().saturating_sub(trim_offset),
58                    (self.full_span.end() + 1).saturating_sub(trim_offset),
59                    self.full_span.source_id().cloned(),
60                )
61                .unwrap_or(Span::dummy())
62            }
63        };
64        self.emit_error_with_span(kind, span)
65    }
66
67    pub fn emit_error_with_span(&mut self, kind: ParseErrorKind, span: Span) -> ErrorEmitted {
68        let error = ParseError { span, kind };
69        self.handler.emit_err(CompileError::Parse { error })
70    }
71
72    /// Eats a `P` in its canonical way by peeking.
73    ///
74    /// Unlike [`Parser::peek`], this method advances the parser on success, but not on failure.
75    pub fn take<P: Peek>(&mut self) -> Option<P> {
76        let (value, tokens) = Peeker::with(self.token_trees)?;
77        self.token_trees = tokens;
78        Some(value)
79    }
80
81    /// Tries to peek a `P` in its canonical way.
82    ///
83    /// Either way, on success or failure, the parser is not advanced.
84    pub fn peek<P: Peek>(&self) -> Option<P> {
85        Peeker::with(self.token_trees).map(|(v, _)| v)
86    }
87
88    /// Tries to peek a `P` as the second token in its canonical way.
89    ///
90    /// Either way, on success or failure, the parser is not advanced.
91    pub fn peek_next<P: Peek>(&self) -> Option<P> {
92        Peeker::with(&self.token_trees[1..]).map(|(v, _)| v)
93    }
94
95    /// This function will fork the current parse, and call the parsing function.
96    /// If it succeeds it will sync the original parser with the forked one;
97    ///
98    /// If it fails it will return a `Recoverer` together with the `ErrorEmitted`.
99    ///
100    /// This recoverer can be used to put the forked parsed back in track and then
101    /// sync the original parser to allow the parsing to continue.
102    pub fn call_parsing_function_with_recovery<
103        'original,
104        T,
105        F: FnOnce(&mut Parser<'a, '_>) -> ParseResult<T>,
106    >(
107        &'original mut self,
108        parsing_function: F,
109    ) -> Result<T, ParseRecoveryStrategies<'original, 'a, 'e>> {
110        let handler = Handler::default();
111        let mut fork = Parser {
112            token_trees: self.token_trees,
113            full_span: self.full_span.clone(),
114            handler: &handler,
115            check_double_underscore: self.check_double_underscore,
116            experimental: self.experimental,
117        };
118
119        match parsing_function(&mut fork) {
120            Ok(result) => {
121                self.token_trees = fork.token_trees;
122                self.handler.append(handler);
123                Ok(result)
124            }
125            Err(error) => {
126                let Parser {
127                    token_trees,
128                    full_span,
129                    ..
130                } = fork;
131                Err(ParseRecoveryStrategies {
132                    original: RefCell::new(self),
133                    handler,
134                    fork_token_trees: token_trees,
135                    fork_full_span: full_span,
136                    error,
137                })
138            }
139        }
140    }
141
142    /// This function will fork the current parse, and try to parse
143    /// T using the fork. If it succeeds it will sync the original parser with the forked one;
144    ///
145    /// If it fails it will return a `Recoverer` together with the `ErrorEmitted`.
146    ///
147    /// This recoverer can be used to put the forked parsed back in track and then
148    /// sync the original parser to allow the parsing to continue.
149    pub fn parse_with_recovery<'original, T: Parse>(
150        &'original mut self,
151    ) -> Result<T, ParseRecoveryStrategies<'original, 'a, 'e>> {
152        self.call_parsing_function_with_recovery(|p| p.parse())
153    }
154
155    /// This function does three things
156    /// 1 - it peeks P;
157    /// 2 - it forks the current parser and tries to parse
158    /// T using this fork. If it succeeds it syncs the original
159    /// parser with the forked one;
160    /// 3 - if it fails it will return a `Recoverer` together with the `ErrorEmitted`.
161    ///
162    /// This recoverer can be used to put the forked parsed back in track and then
163    /// sync the original parser to allow the parsing to continue.
164    pub fn guarded_parse_with_recovery<'original, P: Peek, T: Parse>(
165        &'original mut self,
166    ) -> Result<Option<T>, ParseRecoveryStrategies<'original, 'a, 'e>> {
167        if self.peek::<P>().is_none() {
168            return Ok(None);
169        }
170
171        let handler = Handler::default();
172        let mut fork = Parser {
173            token_trees: self.token_trees,
174            full_span: self.full_span.clone(),
175            handler: &handler,
176            check_double_underscore: self.check_double_underscore,
177            experimental: self.experimental,
178        };
179
180        match fork.parse() {
181            Ok(result) => {
182                self.token_trees = fork.token_trees;
183                self.handler.append(handler);
184                Ok(Some(result))
185            }
186            Err(error) => {
187                let Parser {
188                    token_trees,
189                    full_span,
190                    ..
191                } = fork;
192                Err(ParseRecoveryStrategies {
193                    original: RefCell::new(self),
194                    handler,
195                    fork_token_trees: token_trees,
196                    fork_full_span: full_span,
197                    error,
198                })
199            }
200        }
201    }
202
203    /// Parses a `T` in its canonical way.
204    /// Do not advance the parser on failure
205    pub fn try_parse<T: Parse>(&mut self, append_diagnostics: bool) -> ParseResult<T> {
206        let handler = Handler::default();
207        let mut fork = Parser {
208            token_trees: self.token_trees,
209            full_span: self.full_span.clone(),
210            handler: &handler,
211            check_double_underscore: self.check_double_underscore,
212            experimental: self.experimental,
213        };
214        let r = match T::parse(&mut fork) {
215            Ok(result) => {
216                self.token_trees = fork.token_trees;
217                Ok(result)
218            }
219            Err(err) => Err(err),
220        };
221        if append_diagnostics {
222            self.handler.append(handler);
223        }
224        r
225    }
226
227    /// This method is useful if `T` does not impl `ParseToEnd`
228    pub fn try_parse_and_check_empty<T: Parse>(
229        mut self,
230        append_diagnostics: bool,
231    ) -> ParseResult<Option<(T, ParserConsumed<'a>)>> {
232        let value = self.try_parse(append_diagnostics)?;
233        match self.check_empty() {
234            Some(consumed) => Ok(Some((value, consumed))),
235            None => Ok(None),
236        }
237    }
238
239    /// Parses a `T` in its canonical way.
240    pub fn parse<T: Parse>(&mut self) -> ParseResult<T> {
241        T::parse(self)
242    }
243
244    /// Parses `T` given that the guard `G` was successfully peeked.
245    ///
246    /// Useful to parse e.g., `$keyword $stuff` as a unit where `$keyword` is your guard.
247    pub fn guarded_parse<G: Peek, T: Parse>(&mut self) -> ParseResult<Option<T>> {
248        self.peek::<G>().map(|_| self.parse()).transpose()
249    }
250
251    pub fn parse_to_end<T: ParseToEnd>(self) -> ParseResult<(T, ParserConsumed<'a>)> {
252        T::parse_to_end(self)
253    }
254
255    /// Do not advance the parser on failure
256    pub fn try_parse_to_end<T: ParseToEnd>(
257        &mut self,
258        append_diagnostics: bool,
259    ) -> ParseResult<(T, ParserConsumed<'a>)> {
260        let handler = Handler::default();
261        let fork = Parser {
262            token_trees: self.token_trees,
263            full_span: self.full_span.clone(),
264            handler: &handler,
265            check_double_underscore: self.check_double_underscore,
266            experimental: self.experimental,
267        };
268        let r = T::parse_to_end(fork);
269        if append_diagnostics {
270            self.handler.append(handler);
271        }
272        r
273    }
274
275    pub fn enter_delimited(
276        &mut self,
277        expected_delimiter: Delimiter,
278    ) -> Option<(Parser<'_, '_>, Span)> {
279        match self.token_trees {
280            [TokenTree::Group(Group {
281                delimiter,
282                token_stream,
283                span,
284            }), rest @ ..]
285                if *delimiter == expected_delimiter =>
286            {
287                self.token_trees = rest;
288                let parser = Parser {
289                    token_trees: token_stream.token_trees(),
290                    full_span: token_stream.span(),
291                    handler: self.handler,
292                    check_double_underscore: self.check_double_underscore,
293                    experimental: self.experimental,
294                };
295                Some((parser, span.clone()))
296            }
297            _ => None,
298        }
299    }
300
301    pub fn is_empty(&self) -> bool {
302        self.token_trees.is_empty()
303    }
304
305    pub fn check_empty(&self) -> Option<ParserConsumed<'a>> {
306        self.is_empty()
307            .then_some(ParserConsumed { _priv: PhantomData })
308    }
309
310    pub fn debug_tokens(&self) -> &[TokenTree] {
311        let len = std::cmp::min(5, self.token_trees.len());
312        &self.token_trees[..len]
313    }
314
315    /// Errors given `Some(PubToken)`.
316    pub fn ban_visibility_qualifier(&mut self, vis: &Option<PubToken>) -> ParseResult<()> {
317        if let Some(token) = vis {
318            return Err(self.emit_error_with_span(
319                ParseErrorKind::UnnecessaryVisibilityQualifier {
320                    visibility: token.ident(),
321                },
322                token.span(),
323            ));
324        }
325        Ok(())
326    }
327
328    pub fn full_span(&self) -> &Span {
329        &self.full_span
330    }
331    /// Consume tokens while its line equals to `line`.
332    ///
333    /// # Warning
334    ///
335    /// To calculate lines the original source code needs to be transversed.
336    pub fn consume_while_line_equals(&mut self, line: usize) {
337        while let Some(current_token) = self.token_trees.first() {
338            let current_span = current_token.span();
339            let current_span_line = current_span.start_line_col_one_index().line;
340
341            if current_span_line != line {
342                break;
343            } else {
344                self.token_trees = &self.token_trees[1..];
345            }
346        }
347    }
348
349    pub fn has_errors(&self) -> bool {
350        self.handler.has_errors()
351    }
352
353    pub fn has_warnings(&self) -> bool {
354        self.handler.has_warnings()
355    }
356}
357
358pub struct Peeker<'a> {
359    pub token_trees: &'a [TokenTree],
360    num_tokens: &'a mut usize,
361}
362
363impl<'a> Peeker<'a> {
364    /// Peek a `P` in `token_trees`, if any, and return the `P` + the remainder of the token trees.
365    pub fn with<P: Peek>(token_trees: &'a [TokenTree]) -> Option<(P, &'a [TokenTree])> {
366        let mut num_tokens = 0;
367        let peeker = Peeker {
368            token_trees,
369            num_tokens: &mut num_tokens,
370        };
371        let value = P::peek(peeker)?;
372        Some((value, &token_trees[num_tokens..]))
373    }
374
375    pub fn peek_ident(self) -> Result<&'a Ident, Self> {
376        match self.token_trees {
377            [TokenTree::Ident(ident), ..] => {
378                *self.num_tokens = 1;
379                Ok(ident)
380            }
381            _ => Err(self),
382        }
383    }
384
385    pub fn peek_literal(self) -> Result<&'a Literal, Self> {
386        match self.token_trees {
387            [TokenTree::Literal(literal), ..] => {
388                *self.num_tokens = 1;
389                Ok(literal)
390            }
391            _ => Err(self),
392        }
393    }
394
395    pub fn peek_punct_kinds(
396        self,
397        punct_kinds: &[PunctKind],
398        not_followed_by: &[PunctKind],
399    ) -> Result<Span, Self> {
400        let (last_punct_kind, first_punct_kinds) = punct_kinds
401            .split_last()
402            .unwrap_or_else(|| panic!("peek_punct_kinds called with empty slice"));
403        if self.token_trees.len() < punct_kinds.len() {
404            return Err(self);
405        }
406        for (punct_kind, tt) in first_punct_kinds.iter().zip(self.token_trees.iter()) {
407            match tt {
408                TokenTree::Punct(Punct {
409                    kind,
410                    spacing: Spacing::Joint,
411                    ..
412                }) if *kind == *punct_kind => {}
413                _ => return Err(self),
414            }
415        }
416        let span_end = match &self.token_trees[punct_kinds.len() - 1] {
417            TokenTree::Punct(Punct {
418                kind,
419                spacing,
420                span,
421            }) if *kind == *last_punct_kind => match spacing {
422                Spacing::Alone => span,
423                Spacing::Joint => match &self.token_trees.get(punct_kinds.len()) {
424                    Some(TokenTree::Punct(Punct { kind, .. })) => {
425                        if not_followed_by.contains(kind) {
426                            return Err(self);
427                        }
428                        span
429                    }
430                    _ => span,
431                },
432            },
433            _ => return Err(self),
434        };
435        let span_start = match &self.token_trees[0] {
436            TokenTree::Punct(Punct { span, .. }) => span,
437            _ => unreachable!(),
438        };
439        let span = Span::join(span_start.clone(), span_end);
440        *self.num_tokens = punct_kinds.len();
441        Ok(span)
442    }
443
444    pub fn peek_delimiter(self) -> Result<Delimiter, Self> {
445        match self.token_trees {
446            [TokenTree::Group(Group { delimiter, .. }), ..] => {
447                *self.num_tokens = 1;
448                Ok(*delimiter)
449            }
450            _ => Err(self),
451        }
452    }
453
454    pub fn peek_doc_comment(self) -> Result<&'a DocComment, Self> {
455        match self.token_trees {
456            [TokenTree::DocComment(doc_comment), ..] => {
457                *self.num_tokens = 1;
458                Ok(doc_comment)
459            }
460            _ => Err(self),
461        }
462    }
463}
464
465/// This struct is returned by some parser methods that allow
466/// parser recovery.
467///
468/// It implements some standardized recovery strategies or it allows
469/// custom strategies using the `start` method.
470pub struct ParseRecoveryStrategies<'original, 'a, 'e> {
471    original: RefCell<&'original mut Parser<'a, 'e>>,
472    handler: Handler,
473    fork_token_trees: &'a [TokenTree],
474    fork_full_span: Span,
475    error: ErrorEmitted,
476}
477
478impl<'a> ParseRecoveryStrategies<'_, 'a, '_> {
479    /// This strategy consumes everything at the current line and emits the fallback error
480    /// if the forked parser does not contain any error.
481    pub fn recover_at_next_line_with_fallback_error(
482        &self,
483        kind: ParseErrorKind,
484    ) -> (Box<[Span]>, ErrorEmitted) {
485        let line = if self.fork_token_trees.is_empty() {
486            None
487        } else {
488            self.last_consumed_token()
489                .map(|x| x.span())
490                .or_else(|| self.fork_token_trees.first().map(|x| x.span()))
491                .map(|x| x.start_line_col_one_index().line)
492        };
493
494        self.start(|p| {
495            if let Some(line) = line {
496                p.consume_while_line_equals(line);
497            }
498            if !p.has_errors() {
499                p.emit_error_with_span(kind, self.diff_span(p));
500            }
501        })
502    }
503
504    /// Starts the parser recovery process calling the callback with the forked parser.
505    /// All the changes to this forked parser will be imposed into the original parser,
506    /// including diagnostics.
507    pub fn start<'this>(
508        &'this self,
509        f: impl FnOnce(&mut Parser<'a, 'this>),
510    ) -> (Box<[Span]>, ErrorEmitted) {
511        let mut p = {
512            let original = self.original.borrow();
513            Parser {
514                token_trees: self.fork_token_trees,
515                full_span: self.fork_full_span.clone(),
516                handler: &self.handler,
517                check_double_underscore: original.check_double_underscore,
518                experimental: original.experimental,
519            }
520        };
521        f(&mut p);
522        self.finish(p)
523    }
524
525    /// This is the token before the whole tentative parser started.
526    pub fn starting_token(&self) -> &GenericTokenTree<TokenStream> {
527        let original = self.original.borrow();
528        &original.token_trees[0]
529    }
530
531    /// This is the last consumed token of the forked parser. This the token
532    /// immediately before the forked parser head.
533    pub fn last_consumed_token(&self) -> Option<&GenericTokenTree<TokenStream>> {
534        let fork_head_span = self.fork_token_trees.first()?.span();
535
536        // find the last token consumed by the fork
537        let original = self.original.borrow();
538        let fork_pos = original
539            .token_trees
540            .iter()
541            .position(|x| x.span() == fork_head_span)?;
542
543        let before_fork_pos = fork_pos.checked_sub(1)?;
544        original.token_trees.get(before_fork_pos)
545    }
546
547    /// This return a span encopassing all tokens that were consumed by the `p` since the start
548    /// of the tentative parsing
549    ///
550    /// This is useful to show one single error for all the consumed tokens.
551    pub fn diff_span<'this>(&self, p: &Parser<'a, 'this>) -> Span {
552        let original = self.original.borrow_mut();
553
554        // collect all tokens trees that were consumed by the fork
555        let qty = if let Some(first_fork_tt) = p.token_trees.first() {
556            original
557                .token_trees
558                .iter()
559                .position(|tt| tt.span() == first_fork_tt.span())
560                .expect("not finding fork head")
561        } else {
562            original.token_trees.len()
563        };
564
565        let garbage: Vec<_> = original
566            .token_trees
567            .iter()
568            .take(qty)
569            .map(|x| x.span())
570            .collect();
571
572        Span::join_all(garbage)
573    }
574
575    fn finish(&self, p: Parser<'a, '_>) -> (Box<[Span]>, ErrorEmitted) {
576        let mut original = self.original.borrow_mut();
577
578        // collect all tokens trees that were consumed by the fork
579        let qty = if let Some(first_fork_tt) = p.token_trees.first() {
580            original
581                .token_trees
582                .iter()
583                .position(|tt| tt.span() == first_fork_tt.span())
584                .expect("not finding fork head")
585        } else {
586            original.token_trees.len()
587        };
588
589        let garbage: Vec<_> = original
590            .token_trees
591            .iter()
592            .take(qty)
593            .map(|x| x.span())
594            .collect();
595
596        original.token_trees = p.token_trees;
597        original.handler.append(self.handler.clone());
598
599        (garbage.into_boxed_slice(), self.error)
600    }
601}
602
603pub struct ParserConsumed<'a> {
604    _priv: PhantomData<fn(&'a ()) -> &'a ()>,
605}
606
607pub type ParseResult<T> = Result<T, ErrorEmitted>;