Skip to main content

xur_parser/parser/
path.rs

1use xur_ast::{GenericArgs, Path, PathSegment};
2
3use super::{PResult, Parser};
4use crate::token::TokenKind;
5
6/// Where a path appears, which decides how generic arguments are written
7/// (rustc's `PathStyle`).
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum PathStyle {
10    /// In expressions and patterns, generic arguments need the turbofish,
11    /// `type_name::<T>`, since a bare `<` would be a comparison.
12    Expr,
13    /// In types, generic arguments follow directly: `Result<u32, E>`.
14    Type,
15    /// In `use` and attributes: no generic arguments at all.
16    Mod,
17}
18
19impl Parser<'_> {
20    pub fn parse_path(&mut self, style: PathStyle) -> PResult<Path> {
21        let lo = self.token.span;
22        let mut segments = Vec::new();
23        loop {
24            let ident = self.parse_ident()?;
25            let args = self.parse_opt_generic_args(style)?;
26            segments.push(PathSegment { ident, args });
27            if !self.eat(TokenKind::ColonColon) {
28                break;
29            }
30        }
31        Ok(Path {
32            id: self.next_id(),
33            segments,
34            span: lo.to(self.prev_token.span),
35        })
36    }
37
38    pub(super) fn parse_opt_generic_args(
39        &mut self,
40        style: PathStyle,
41    ) -> PResult<Option<GenericArgs>> {
42        let has_args = match style {
43            PathStyle::Type => self.check(TokenKind::Lt),
44            PathStyle::Expr => {
45                let turbofish =
46                    self.token.kind == TokenKind::ColonColon && self.look_ahead(1) == TokenKind::Lt;
47                if turbofish {
48                    self.bump(); // `::`
49                }
50                turbofish
51            }
52            PathStyle::Mod => false,
53        };
54        if !has_args {
55            return Ok(None);
56        }
57
58        let lo = self.token.span;
59        self.expect(TokenKind::Lt)?;
60        let args = self.parse_delimited(TokenKind::Gt, Self::parse_ty)?;
61        Ok(Some(GenericArgs {
62            args,
63            span: lo.to(self.prev_token.span),
64        }))
65    }
66}