3 use crate::parse::{SeqSep, PResult};
4 use crate::parse::token::{self, Nonterminal, DelimToken};
5 use crate::parse::parser::{Parser, TokenType, PathStyle};
6 use crate::tokenstream::{TokenStream, TokenTree};
9 use smallvec::smallvec;
12 enum InnerAttributeParsePolicy<'a> {
14 NotPermitted { reason: &'a str },
17 const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \
18 permitted in this context";
21 /// Parse attributes that appear before an item
22 crate fn parse_outer_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
23 let mut attrs: Vec<ast::Attribute> = Vec::new();
24 let mut just_parsed_doc_comment = false;
26 debug!("parse_outer_attributes: self.token={:?}", self.token);
27 match self.token.kind {
29 let inner_error_reason = if just_parsed_doc_comment {
30 "an inner attribute is not permitted following an outer doc comment"
31 } else if !attrs.is_empty() {
32 "an inner attribute is not permitted following an outer attribute"
34 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
36 let inner_parse_policy =
37 InnerAttributeParsePolicy::NotPermitted { reason: inner_error_reason };
38 attrs.push(self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?);
39 just_parsed_doc_comment = false;
41 token::DocComment(s) => {
42 let attr = attr::mk_sugared_doc_attr(attr::mk_attr_id(), s, self.span);
43 if attr.style != ast::AttrStyle::Outer {
44 let mut err = self.fatal("expected outer doc comment");
45 err.note("inner doc comments like this (starting with \
46 `//!` or `/*!`) can only appear before items");
51 just_parsed_doc_comment = true;
59 /// Matches `attribute = # ! [ meta_item ]`
61 /// If permit_inner is true, then a leading `!` indicates an inner
63 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
64 debug!("parse_attribute: permit_inner={:?} self.token={:?}",
67 let inner_parse_policy = if permit_inner {
68 InnerAttributeParsePolicy::Permitted
70 InnerAttributeParsePolicy::NotPermitted
71 { reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG }
73 self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
76 /// The same as `parse_attribute`, except it takes in an `InnerAttributeParsePolicy`
77 /// that prescribes how to handle inner attributes.
78 fn parse_attribute_with_inner_parse_policy(&mut self,
79 inner_parse_policy: InnerAttributeParsePolicy<'_>)
80 -> PResult<'a, ast::Attribute> {
81 debug!("parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}",
84 let (span, path, tokens, style) = match self.token.kind {
89 if let InnerAttributeParsePolicy::Permitted = inner_parse_policy {
90 self.expected_tokens.push(TokenType::Token(token::Not));
92 let style = if self.token == token::Not {
94 if let InnerAttributeParsePolicy::NotPermitted { reason } = inner_parse_policy
98 .struct_span_err(span, reason)
99 .note("inner attributes, like `#![no_std]`, annotate the item \
100 enclosing them, and are usually found at the beginning of \
101 source files. Outer attributes, like `#[test]`, annotate the \
102 item following them.")
105 ast::AttrStyle::Inner
107 ast::AttrStyle::Outer
110 self.expect(&token::OpenDelim(token::Bracket))?;
111 let (path, tokens) = self.parse_meta_item_unrestricted()?;
112 self.expect(&token::CloseDelim(token::Bracket))?;
113 let hi = self.prev_span;
115 (lo.to(hi), path, tokens, style)
118 let token_str = self.this_token_to_string();
119 return Err(self.fatal(&format!("expected `#`, found `{}`", token_str)));
124 id: attr::mk_attr_id(),
128 is_sugared_doc: false,
133 /// Parse an inner part of attribute - path and following tokens.
134 /// The tokens must be either a delimited token stream, or empty token stream,
135 /// or the "legacy" key-value form.
136 /// PATH `(` TOKEN_STREAM `)`
137 /// PATH `[` TOKEN_STREAM `]`
138 /// PATH `{` TOKEN_STREAM `}`
140 /// PATH `=` TOKEN_TREE
141 /// The delimiters or `=` are still put into the resulting token stream.
142 crate fn parse_meta_item_unrestricted(&mut self) -> PResult<'a, (ast::Path, TokenStream)> {
143 let meta = match self.token.kind {
144 token::Interpolated(ref nt) => match **nt {
145 Nonterminal::NtMeta(ref meta) => Some(meta.clone()),
150 Ok(if let Some(meta) = meta {
152 (meta.path, meta.node.tokens(meta.span))
154 let path = self.parse_path(PathStyle::Mod)?;
155 let tokens = if self.check(&token::OpenDelim(DelimToken::Paren)) ||
156 self.check(&token::OpenDelim(DelimToken::Bracket)) ||
157 self.check(&token::OpenDelim(DelimToken::Brace)) {
158 self.parse_token_tree().into()
159 } else if self.eat(&token::Eq) {
160 let eq = TokenTree::token(self.prev_span, token::Eq);
161 let mut is_interpolated_expr = false;
162 if let token::Interpolated(nt) = &self.token.kind {
163 if let token::NtExpr(..) = **nt {
164 is_interpolated_expr = true;
167 let tokens = if is_interpolated_expr {
168 // We need to accept arbitrary interpolated expressions to continue
169 // supporting things like `doc = $expr` that work on stable.
170 // Non-literal interpolated expressions are rejected after expansion.
171 self.parse_token_tree().into()
173 self.parse_unsuffixed_lit()?.tokens()
175 TokenStream::from_streams(smallvec![eq.into(), tokens])
183 /// Parse attributes that appear after the opening of an item. These should
184 /// be preceded by an exclamation mark, but we accept and warn about one
185 /// terminated by a semicolon.
187 /// matches inner_attrs*
188 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
189 let mut attrs: Vec<ast::Attribute> = vec![];
191 match self.token.kind {
193 // Don't even try to parse if it's not an inner attribute.
194 if !self.look_ahead(1, |t| t == &token::Not) {
198 let attr = self.parse_attribute(true)?;
199 assert_eq!(attr.style, ast::AttrStyle::Inner);
202 token::DocComment(s) => {
203 // we need to get the position of this token before we bump.
204 let attr = attr::mk_sugared_doc_attr(attr::mk_attr_id(), s, self.span);
205 if attr.style == ast::AttrStyle::Inner {
218 fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
219 let lit = self.parse_lit()?;
220 debug!("Checking if {:?} is unusuffixed.", lit);
222 if !lit.node.is_unsuffixed() {
223 let msg = "suffixed literals are not allowed in attributes";
224 self.diagnostic().struct_span_err(lit.span, msg)
225 .help("instead of using a suffixed literal \
226 (1u8, 1.0f32, etc.), use an unsuffixed version \
234 /// Per RFC#1559, matches the following grammar:
236 /// meta_item : IDENT ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
237 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
238 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
239 let nt_meta = match self.token.kind {
240 token::Interpolated(ref nt) => match **nt {
241 token::NtMeta(ref e) => Some(e.clone()),
247 if let Some(meta) = nt_meta {
253 let path = self.parse_path(PathStyle::Mod)?;
254 let node = self.parse_meta_item_kind()?;
255 let span = lo.to(self.prev_span);
256 Ok(ast::MetaItem { path, node, span })
259 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
260 Ok(if self.eat(&token::Eq) {
261 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
262 } else if self.eat(&token::OpenDelim(token::Paren)) {
263 ast::MetaItemKind::List(self.parse_meta_seq()?)
265 ast::MetaItemKind::Word
269 /// matches meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;
270 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
271 match self.parse_unsuffixed_lit() {
273 return Ok(ast::NestedMetaItem::Literal(lit))
275 Err(ref mut err) => self.diagnostic().cancel(err)
278 match self.parse_meta_item() {
280 return Ok(ast::NestedMetaItem::MetaItem(mi))
282 Err(ref mut err) => self.diagnostic().cancel(err)
285 let found = self.this_token_to_string();
286 let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
287 Err(self.diagnostic().struct_span_err(self.span, &msg))
290 /// matches meta_seq = ( COMMASEP(meta_item_inner) )
291 fn parse_meta_seq(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
292 self.parse_seq_to_end(&token::CloseDelim(token::Paren),
293 SeqSep::trailing_allowed(token::Comma),
294 |p: &mut Parser<'a>| p.parse_meta_item_inner())