rustc_attr_parsing/
parser.rs

1//! This is in essence an (improved) duplicate of `rustc_ast/attr/mod.rs`.
2//! That module is intended to be deleted in its entirety.
3//!
4//! FIXME(jdonszelmann): delete `rustc_ast/attr/mod.rs`
5
6use std::fmt::{Debug, Display};
7use std::iter::Peekable;
8
9use rustc_ast::token::{self, Delimiter, Token};
10use rustc_ast::tokenstream::{TokenStreamIter, TokenTree};
11use rustc_ast::{AttrArgs, DelimArgs, Expr, ExprKind, LitKind, MetaItemLit, NormalAttr, Path};
12use rustc_ast_pretty::pprust;
13use rustc_errors::DiagCtxtHandle;
14use rustc_hir::{self as hir, AttrPath};
15use rustc_span::symbol::{Ident, kw, sym};
16use rustc_span::{ErrorGuaranteed, Span, Symbol};
17
18pub struct SegmentIterator<'a> {
19    offset: usize,
20    path: &'a PathParser<'a>,
21}
22
23impl<'a> Iterator for SegmentIterator<'a> {
24    type Item = &'a Ident;
25
26    fn next(&mut self) -> Option<Self::Item> {
27        if self.offset >= self.path.len() {
28            return None;
29        }
30
31        let res = match self.path {
32            PathParser::Ast(ast_path) => &ast_path.segments[self.offset].ident,
33            PathParser::Attr(attr_path) => &attr_path.segments[self.offset],
34        };
35
36        self.offset += 1;
37        Some(res)
38    }
39}
40
41#[derive(Clone, Debug)]
42pub enum PathParser<'a> {
43    Ast(&'a Path),
44    Attr(AttrPath),
45}
46
47impl<'a> PathParser<'a> {
48    pub fn get_attribute_path(&self) -> hir::AttrPath {
49        AttrPath {
50            segments: self.segments().copied().collect::<Vec<_>>().into_boxed_slice(),
51            span: self.span(),
52        }
53    }
54
55    pub fn segments(&'a self) -> impl Iterator<Item = &'a Ident> {
56        SegmentIterator { offset: 0, path: self }
57    }
58
59    pub fn span(&self) -> Span {
60        match self {
61            PathParser::Ast(path) => path.span,
62            PathParser::Attr(attr_path) => attr_path.span,
63        }
64    }
65
66    pub fn len(&self) -> usize {
67        match self {
68            PathParser::Ast(path) => path.segments.len(),
69            PathParser::Attr(attr_path) => attr_path.segments.len(),
70        }
71    }
72
73    pub fn segments_is(&self, segments: &[Symbol]) -> bool {
74        self.len() == segments.len() && self.segments().zip(segments).all(|(a, b)| a.name == *b)
75    }
76
77    pub fn word(&self) -> Option<Ident> {
78        (self.len() == 1).then(|| **self.segments().next().as_ref().unwrap())
79    }
80
81    pub fn word_sym(&self) -> Option<Symbol> {
82        self.word().map(|ident| ident.name)
83    }
84
85    /// Asserts that this MetaItem is some specific word.
86    ///
87    /// See [`word`](Self::word) for examples of what a word is.
88    pub fn word_is(&self, sym: Symbol) -> bool {
89        self.word().map(|i| i.name == sym).unwrap_or(false)
90    }
91}
92
93impl Display for PathParser<'_> {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        match self {
96            PathParser::Ast(path) => write!(f, "{}", pprust::path_to_string(path)),
97            PathParser::Attr(attr_path) => write!(f, "{attr_path}"),
98        }
99    }
100}
101
102#[derive(Clone, Debug)]
103#[must_use]
104pub enum ArgParser<'a> {
105    NoArgs,
106    List(MetaItemListParser<'a>),
107    NameValue(NameValueParser),
108}
109
110impl<'a> ArgParser<'a> {
111    pub fn span(&self) -> Option<Span> {
112        match self {
113            Self::NoArgs => None,
114            Self::List(l) => Some(l.span),
115            Self::NameValue(n) => Some(n.value_span.with_lo(n.eq_span.lo())),
116        }
117    }
118
119    pub fn from_attr_args(value: &'a AttrArgs, dcx: DiagCtxtHandle<'a>) -> Self {
120        match value {
121            AttrArgs::Empty => Self::NoArgs,
122            AttrArgs::Delimited(args) if args.delim == Delimiter::Parenthesis => {
123                Self::List(MetaItemListParser::new(args, dcx))
124            }
125            AttrArgs::Delimited(args) => {
126                Self::List(MetaItemListParser { sub_parsers: vec![], span: args.dspan.entire() })
127            }
128            AttrArgs::Eq { eq_span, expr } => Self::NameValue(NameValueParser {
129                eq_span: *eq_span,
130                value: expr_to_lit(dcx, &expr, *eq_span),
131                value_span: expr.span,
132            }),
133        }
134    }
135
136    /// Asserts that this MetaItem is a list
137    ///
138    /// Some examples:
139    ///
140    /// - `#[allow(clippy::complexity)]`: `(clippy::complexity)` is a list
141    /// - `#[rustfmt::skip::macros(target_macro_name)]`: `(target_macro_name)` is a list
142    pub fn list(&self) -> Option<&MetaItemListParser<'a>> {
143        match self {
144            Self::List(l) => Some(l),
145            Self::NameValue(_) | Self::NoArgs => None,
146        }
147    }
148
149    /// Asserts that this MetaItem is a name-value pair.
150    ///
151    /// Some examples:
152    ///
153    /// - `#[clippy::cyclomatic_complexity = "100"]`: `clippy::cyclomatic_complexity = "100"` is a name value pair,
154    ///   where the name is a path (`clippy::cyclomatic_complexity`). You already checked the path
155    ///   to get an `ArgParser`, so this method will effectively only assert that the `= "100"` is
156    ///   there
157    /// - `#[doc = "hello"]`: `doc = "hello`  is also a name value pair
158    pub fn name_value(&self) -> Option<&NameValueParser> {
159        match self {
160            Self::NameValue(n) => Some(n),
161            Self::List(_) | Self::NoArgs => None,
162        }
163    }
164
165    /// Asserts that there are no arguments
166    pub fn no_args(&self) -> bool {
167        matches!(self, Self::NoArgs)
168    }
169}
170
171/// Inside lists, values could be either literals, or more deeply nested meta items.
172/// This enum represents that.
173///
174/// Choose which one you want using the provided methods.
175#[derive(Debug, Clone)]
176pub enum MetaItemOrLitParser<'a> {
177    MetaItemParser(MetaItemParser<'a>),
178    Lit(MetaItemLit),
179    Err(Span, ErrorGuaranteed),
180}
181
182impl<'a> MetaItemOrLitParser<'a> {
183    pub fn span(&self) -> Span {
184        match self {
185            MetaItemOrLitParser::MetaItemParser(generic_meta_item_parser) => {
186                generic_meta_item_parser.span()
187            }
188            MetaItemOrLitParser::Lit(meta_item_lit) => meta_item_lit.span,
189            MetaItemOrLitParser::Err(span, _) => *span,
190        }
191    }
192
193    pub fn lit(&self) -> Option<&MetaItemLit> {
194        match self {
195            MetaItemOrLitParser::Lit(meta_item_lit) => Some(meta_item_lit),
196            _ => None,
197        }
198    }
199
200    pub fn meta_item(&self) -> Option<&MetaItemParser<'a>> {
201        match self {
202            MetaItemOrLitParser::MetaItemParser(parser) => Some(parser),
203            _ => None,
204        }
205    }
206}
207
208/// Utility that deconstructs a MetaItem into usable parts.
209///
210/// MetaItems are syntactically extremely flexible, but specific attributes want to parse
211/// them in custom, more restricted ways. This can be done using this struct.
212///
213/// MetaItems consist of some path, and some args. The args could be empty. In other words:
214///
215/// - `name` -> args are empty
216/// - `name(...)` -> args are a [`list`](ArgParser::list), which is the bit between the parentheses
217/// - `name = value`-> arg is [`name_value`](ArgParser::name_value), where the argument is the
218///   `= value` part
219///
220/// The syntax of MetaItems can be found at <https://doc.rust-lang.org/reference/attributes.html>
221#[derive(Clone)]
222pub struct MetaItemParser<'a> {
223    path: PathParser<'a>,
224    args: ArgParser<'a>,
225}
226
227impl<'a> Debug for MetaItemParser<'a> {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        f.debug_struct("MetaItemParser")
230            .field("path", &self.path)
231            .field("args", &self.args)
232            .finish()
233    }
234}
235
236impl<'a> MetaItemParser<'a> {
237    /// Create a new parser from a [`NormalAttr`], which is stored inside of any
238    /// [`ast::Attribute`](rustc_ast::Attribute)
239    pub fn from_attr(attr: &'a NormalAttr, dcx: DiagCtxtHandle<'a>) -> Self {
240        Self {
241            path: PathParser::Ast(&attr.item.path),
242            args: ArgParser::from_attr_args(&attr.item.args, dcx),
243        }
244    }
245}
246
247impl<'a> MetaItemParser<'a> {
248    pub fn span(&self) -> Span {
249        if let Some(other) = self.args.span() {
250            self.path.span().with_hi(other.hi())
251        } else {
252            self.path.span()
253        }
254    }
255
256    /// Gets just the path, without the args.
257    pub fn path_without_args(&self) -> PathParser<'a> {
258        self.path.clone()
259    }
260
261    /// Gets just the args parser, without caring about the path.
262    pub fn args(&self) -> &ArgParser<'a> {
263        &self.args
264    }
265
266    pub fn deconstruct(&self) -> (PathParser<'a>, &ArgParser<'a>) {
267        (self.path_without_args(), self.args())
268    }
269
270    /// Asserts that this MetaItem starts with a path. Some examples:
271    ///
272    /// - `#[rustfmt::skip]`: `rustfmt::skip` is a path
273    /// - `#[allow(clippy::complexity)]`: `clippy::complexity` is a path
274    /// - `#[inline]`: `inline` is a single segment path
275    pub fn path(&self) -> (PathParser<'a>, &ArgParser<'a>) {
276        self.deconstruct()
277    }
278
279    /// Asserts that this MetaItem starts with a word, or single segment path.
280    /// Doesn't return the args parser.
281    ///
282    /// For examples. see [`Self::word`]
283    pub fn word_without_args(&self) -> Option<Ident> {
284        Some(self.word()?.0)
285    }
286
287    /// Asserts that this MetaItem starts with a word, or single segment path.
288    ///
289    /// Some examples:
290    /// - `#[inline]`: `inline` is a word
291    /// - `#[rustfmt::skip]`: `rustfmt::skip` is a path,
292    ///   and not a word and should instead be parsed using [`path`](Self::path)
293    pub fn word(&self) -> Option<(Ident, &ArgParser<'a>)> {
294        let (path, args) = self.deconstruct();
295        Some((path.word()?, args))
296    }
297
298    /// Asserts that this MetaItem starts with some specific word.
299    ///
300    /// See [`word`](Self::word) for examples of what a word is.
301    pub fn word_is(&self, sym: Symbol) -> Option<&ArgParser<'a>> {
302        self.path_without_args().word_is(sym).then(|| self.args())
303    }
304
305    /// Asserts that this MetaItem starts with some specific path.
306    ///
307    /// See [`word`](Self::path) for examples of what a word is.
308    pub fn path_is(&self, segments: &[Symbol]) -> Option<&ArgParser<'a>> {
309        self.path_without_args().segments_is(segments).then(|| self.args())
310    }
311}
312
313#[derive(Clone)]
314pub struct NameValueParser {
315    pub eq_span: Span,
316    value: MetaItemLit,
317    pub value_span: Span,
318}
319
320impl Debug for NameValueParser {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        f.debug_struct("NameValueParser")
323            .field("eq_span", &self.eq_span)
324            .field("value", &self.value)
325            .field("value_span", &self.value_span)
326            .finish()
327    }
328}
329
330impl NameValueParser {
331    pub fn value_as_lit(&self) -> &MetaItemLit {
332        &self.value
333    }
334
335    pub fn value_as_str(&self) -> Option<Symbol> {
336        self.value_as_lit().kind.str()
337    }
338}
339
340fn expr_to_lit(dcx: DiagCtxtHandle<'_>, expr: &Expr, span: Span) -> MetaItemLit {
341    // In valid code the value always ends up as a single literal. Otherwise, a dummy
342    // literal suffices because the error is handled elsewhere.
343    if let ExprKind::Lit(token_lit) = expr.kind
344        && let Ok(lit) = MetaItemLit::from_token_lit(token_lit, expr.span)
345    {
346        lit
347    } else {
348        let guar = dcx.span_delayed_bug(
349            span,
350            "expr in place where literal is expected (builtin attr parsing)",
351        );
352        MetaItemLit { symbol: sym::dummy, suffix: None, kind: LitKind::Err(guar), span }
353    }
354}
355
356struct MetaItemListParserContext<'a> {
357    // the tokens inside the delimiters, so `#[some::attr(a b c)]` would have `a b c` inside
358    inside_delimiters: Peekable<TokenStreamIter<'a>>,
359    dcx: DiagCtxtHandle<'a>,
360}
361
362impl<'a> MetaItemListParserContext<'a> {
363    fn done(&mut self) -> bool {
364        self.inside_delimiters.peek().is_none()
365    }
366
367    fn next_path(&mut self) -> Option<AttrPath> {
368        // FIXME: Share code with `parse_path`.
369        let tt = self.inside_delimiters.next().map(|tt| TokenTree::uninterpolate(tt));
370
371        match tt.as_deref()? {
372            &TokenTree::Token(
373                Token { kind: ref kind @ (token::Ident(..) | token::PathSep), span },
374                _,
375            ) => {
376                // here we have either an ident or pathsep `::`.
377
378                let mut segments = if let &token::Ident(name, _) = kind {
379                    // when we lookahead another pathsep, more path's coming
380                    if let Some(TokenTree::Token(Token { kind: token::PathSep, .. }, _)) =
381                        self.inside_delimiters.peek()
382                    {
383                        self.inside_delimiters.next();
384                        vec![Ident::new(name, span)]
385                    } else {
386                        // else we have a single identifier path, that's all
387                        return Some(AttrPath {
388                            segments: vec![Ident::new(name, span)].into_boxed_slice(),
389                            span,
390                        });
391                    }
392                } else {
393                    // if `::` is all we get, we just got a path root
394                    vec![Ident::new(kw::PathRoot, span)]
395                };
396
397                // one segment accepted. accept n more
398                loop {
399                    // another ident?
400                    if let Some(&TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
401                        self.inside_delimiters
402                            .next()
403                            .map(|tt| TokenTree::uninterpolate(tt))
404                            .as_deref()
405                    {
406                        segments.push(Ident::new(name, span));
407                    } else {
408                        return None;
409                    }
410                    // stop unless we see another `::`
411                    if let Some(TokenTree::Token(Token { kind: token::PathSep, .. }, _)) =
412                        self.inside_delimiters.peek()
413                    {
414                        self.inside_delimiters.next();
415                    } else {
416                        break;
417                    }
418                }
419                let span = span.with_hi(segments.last().unwrap().span.hi());
420                Some(AttrPath { segments: segments.into_boxed_slice(), span })
421            }
422            TokenTree::Token(Token { kind, .. }, _) if kind.is_delim() => None,
423            _ => {
424                // malformed attributes can get here. We can't crash, but somewhere else should've
425                // already warned for this.
426                None
427            }
428        }
429    }
430
431    fn value(&mut self) -> Option<MetaItemLit> {
432        match self.inside_delimiters.next() {
433            Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => {
434                MetaItemListParserContext {
435                    inside_delimiters: inner_tokens.iter().peekable(),
436                    dcx: self.dcx,
437                }
438                .value()
439            }
440            Some(TokenTree::Token(token, _)) => MetaItemLit::from_token(token),
441            _ => None,
442        }
443    }
444
445    /// parses one element on the inside of a list attribute like `#[my_attr( <insides> )]`
446    ///
447    /// parses a path followed be either:
448    /// 1. nothing (a word attr)
449    /// 2. a parenthesized list
450    /// 3. an equals sign and a literal (name-value)
451    ///
452    /// Can also parse *just* a literal. This is for cases like as `#[my_attr("literal")]`
453    /// where no path is given before the literal
454    ///
455    /// Some exceptions too for interpolated attributes which are already pre-processed
456    fn next(&mut self) -> Option<MetaItemOrLitParser<'a>> {
457        // a list element is either a literal
458        if let Some(TokenTree::Token(token, _)) = self.inside_delimiters.peek()
459            && let Some(lit) = MetaItemLit::from_token(token)
460        {
461            self.inside_delimiters.next();
462            return Some(MetaItemOrLitParser::Lit(lit));
463        } else if let Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) =
464            self.inside_delimiters.peek()
465        {
466            self.inside_delimiters.next();
467            return MetaItemListParserContext {
468                inside_delimiters: inner_tokens.iter().peekable(),
469                dcx: self.dcx,
470            }
471            .next();
472        }
473
474        // or a path.
475        let path = self.next_path()?;
476
477        // Paths can be followed by:
478        // - `(more meta items)` (another list)
479        // - `= lit` (a name-value)
480        // - nothing
481        Some(MetaItemOrLitParser::MetaItemParser(match self.inside_delimiters.peek() {
482            Some(TokenTree::Delimited(dspan, _, Delimiter::Parenthesis, inner_tokens)) => {
483                self.inside_delimiters.next();
484
485                MetaItemParser {
486                    path: PathParser::Attr(path),
487                    args: ArgParser::List(MetaItemListParser::new_tts(
488                        inner_tokens.iter(),
489                        dspan.entire(),
490                        self.dcx,
491                    )),
492                }
493            }
494            Some(TokenTree::Delimited(_, ..)) => {
495                self.inside_delimiters.next();
496                // self.dcx.span_delayed_bug(span.entire(), "wrong delimiters");
497                return None;
498            }
499            Some(TokenTree::Token(Token { kind: token::Eq, span }, _)) => {
500                self.inside_delimiters.next();
501                let value = self.value()?;
502                MetaItemParser {
503                    path: PathParser::Attr(path),
504                    args: ArgParser::NameValue(NameValueParser {
505                        eq_span: *span,
506                        value_span: value.span,
507                        value,
508                    }),
509                }
510            }
511            _ => MetaItemParser { path: PathParser::Attr(path), args: ArgParser::NoArgs },
512        }))
513    }
514
515    fn parse(mut self, span: Span) -> MetaItemListParser<'a> {
516        let mut sub_parsers = Vec::new();
517
518        while !self.done() {
519            let Some(n) = self.next() else {
520                continue;
521            };
522            sub_parsers.push(n);
523
524            match self.inside_delimiters.peek() {
525                None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {
526                    self.inside_delimiters.next();
527                }
528                Some(_) => {}
529            }
530        }
531
532        MetaItemListParser { sub_parsers, span }
533    }
534}
535
536#[derive(Debug, Clone)]
537pub struct MetaItemListParser<'a> {
538    sub_parsers: Vec<MetaItemOrLitParser<'a>>,
539    pub span: Span,
540}
541
542impl<'a> MetaItemListParser<'a> {
543    fn new(delim: &'a DelimArgs, dcx: DiagCtxtHandle<'a>) -> MetaItemListParser<'a> {
544        MetaItemListParser::new_tts(delim.tokens.iter(), delim.dspan.entire(), dcx)
545    }
546
547    fn new_tts(tts: TokenStreamIter<'a>, span: Span, dcx: DiagCtxtHandle<'a>) -> Self {
548        MetaItemListParserContext { inside_delimiters: tts.peekable(), dcx }.parse(span)
549    }
550
551    /// Lets you pick and choose as what you want to parse each element in the list
552    pub fn mixed<'s>(&'s self) -> impl Iterator<Item = &'s MetaItemOrLitParser<'a>> + 's {
553        self.sub_parsers.iter()
554    }
555
556    pub fn len(&self) -> usize {
557        self.sub_parsers.len()
558    }
559
560    pub fn is_empty(&self) -> bool {
561        self.len() == 0
562    }
563
564    /// Asserts that every item in the list is another list starting with a word.
565    ///
566    /// See [`MetaItemParser::word`] for examples of words.
567    pub fn all_word_list<'s>(&'s self) -> Option<Vec<(Ident, &'s ArgParser<'a>)>> {
568        self.mixed().map(|i| i.meta_item()?.word()).collect()
569    }
570
571    /// Asserts that every item in the list is another list starting with a full path.
572    ///
573    /// See [`MetaItemParser::path`] for examples of paths.
574    pub fn all_path_list<'s>(&'s self) -> Option<Vec<(PathParser<'a>, &'s ArgParser<'a>)>> {
575        self.mixed().map(|i| Some(i.meta_item()?.path())).collect()
576    }
577
578    /// Returns Some if the list contains only a single element.
579    ///
580    /// Inside the Some is the parser to parse this single element.
581    pub fn single(&self) -> Option<&MetaItemOrLitParser<'a>> {
582        let mut iter = self.mixed();
583        iter.next().filter(|_| iter.next().is_none())
584    }
585}