1 use crate::ast::{self, Block, Ident, LitKind, NodeId, PatKind, Path};
2 use crate::ast::{MacStmtStyle, StmtKind, ItemKind};
3 use crate::attr::{self, HasAttrs};
4 use crate::source_map::{dummy_spanned, respan};
5 use crate::config::StripUnconfigured;
6 use crate::ext::base::*;
7 use crate::ext::derive::{add_derived_markers, collect_derives};
8 use crate::ext::hygiene::{Mark, SyntaxContext};
9 use crate::ext::placeholders::{placeholder, PlaceholderExpander};
10 use crate::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
11 use crate::mut_visit::*;
12 use crate::parse::{DirectoryOwnership, PResult, ParseSess};
13 use crate::parse::token;
14 use crate::parse::parser::Parser;
16 use crate::symbol::Symbol;
17 use crate::symbol::{kw, sym};
18 use crate::tokenstream::{TokenStream, TokenTree};
19 use crate::visit::{self, Visitor};
20 use crate::util::map_in_place::MapInPlace;
22 use errors::{Applicability, FatalError};
23 use smallvec::{smallvec, SmallVec};
24 use syntax_pos::{Span, DUMMY_SP, FileName};
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_data_structures::sync::Lrc;
29 use std::io::ErrorKind;
31 use std::ops::DerefMut;
33 use std::path::PathBuf;
35 macro_rules! ast_fragments {
37 $($Kind:ident($AstTy:ty) {
39 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
40 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
44 /// A fragment of AST that can be produced by a single macro expansion.
45 /// Can also serve as an input and intermediate result for macro expansion operations.
46 pub enum AstFragment {
47 OptExpr(Option<P<ast::Expr>>),
51 /// "Discriminant" of an AST fragment.
52 #[derive(Copy, Clone, PartialEq, Eq)]
53 pub enum AstFragmentKind {
58 impl AstFragmentKind {
59 pub fn name(self) -> &'static str {
61 AstFragmentKind::OptExpr => "expression",
62 $(AstFragmentKind::$Kind => $kind_name,)*
66 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
68 AstFragmentKind::OptExpr =>
69 result.make_expr().map(Some).map(AstFragment::OptExpr),
70 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
76 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
78 AstFragment::OptExpr(expr) => expr,
79 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
83 $(pub fn $make_ast(self) -> $AstTy {
85 AstFragment::$Kind(ast) => ast,
86 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
90 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
92 AstFragment::OptExpr(opt_expr) => {
93 visit_clobber(opt_expr, |opt_expr| {
94 if let Some(expr) = opt_expr {
95 vis.filter_map_expr(expr)
101 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
102 $($(AstFragment::$Kind(ast) =>
103 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
107 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
109 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
110 AstFragment::OptExpr(None) => {}
111 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
112 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
113 visitor.$visit_ast_elt(ast_elt);
119 impl<'a, 'b> MutVisitor for MacroExpander<'a, 'b> {
120 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
121 self.expand_fragment(AstFragment::OptExpr(Some(expr))).make_opt_expr()
123 $($(fn $mut_visit_ast(&mut self, ast: &mut $AstTy) {
124 visit_clobber(ast, |ast| self.expand_fragment(AstFragment::$Kind(ast)).$make_ast());
126 $($(fn $flat_map_ast_elt(&mut self, ast_elt: <$AstTy as IntoIterator>::Item) -> $AstTy {
127 self.expand_fragment(AstFragment::$Kind(smallvec![ast_elt])).$make_ast()
131 impl<'a> MacResult for crate::ext::tt::macro_rules::ParserAnyMacro<'a> {
132 $(fn $make_ast(self: Box<crate::ext::tt::macro_rules::ParserAnyMacro<'a>>)
134 Some(self.make(AstFragmentKind::$Kind).$make_ast())
141 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
142 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
143 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
144 Stmts(SmallVec<[ast::Stmt; 1]>) {
145 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
147 Items(SmallVec<[P<ast::Item>; 1]>) {
148 "item"; many fn flat_map_item; fn visit_item; fn make_items;
150 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
151 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
153 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
154 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
156 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
157 "foreign item"; many fn flat_map_foreign_item; fn visit_foreign_item; fn make_foreign_items;
161 impl AstFragmentKind {
162 fn dummy(self, span: Span) -> Option<AstFragment> {
163 self.make_from(DummyResult::any(span))
166 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
168 let mut items = items.into_iter();
170 AstFragmentKind::Items =>
171 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
172 AstFragmentKind::ImplItems =>
173 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
174 AstFragmentKind::TraitItems =>
175 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
176 AstFragmentKind::ForeignItems =>
177 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
178 AstFragmentKind::Stmts =>
179 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
180 AstFragmentKind::Expr => AstFragment::Expr(
181 items.next().expect("expected exactly one expression").expect_expr()
183 AstFragmentKind::OptExpr =>
184 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
185 AstFragmentKind::Pat | AstFragmentKind::Ty =>
186 panic!("patterns and types aren't annotatable"),
191 pub struct Invocation {
192 pub kind: InvocationKind,
193 fragment_kind: AstFragmentKind,
194 pub expansion_data: ExpansionData,
197 pub enum InvocationKind {
200 ident: Option<Ident>,
204 attr: Option<ast::Attribute>,
207 // We temporarily report errors for attribute macros placed after derives
217 pub fn span(&self) -> Span {
219 InvocationKind::Bang { span, .. } => span,
220 InvocationKind::Attr { attr: Some(ref attr), .. } => attr.span,
221 InvocationKind::Attr { attr: None, .. } => DUMMY_SP,
222 InvocationKind::Derive { ref path, .. } => path.span,
227 pub struct MacroExpander<'a, 'b> {
228 pub cx: &'a mut ExtCtxt<'b>,
229 monotonic: bool, // cf. `cx.monotonic_expander()`
232 impl<'a, 'b> MacroExpander<'a, 'b> {
233 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
234 MacroExpander { cx, monotonic }
237 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
238 let mut module = ModuleData {
239 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
240 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
241 FileName::Real(path) => path,
242 other => PathBuf::from(other.to_string()),
245 module.directory.pop();
246 self.cx.root_path = module.directory.clone();
247 self.cx.current_expansion.module = Rc::new(module);
248 self.cx.current_expansion.crate_span = Some(krate.span);
250 let orig_mod_span = krate.module.inner;
252 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
255 node: ast::ItemKind::Mod(krate.module),
256 ident: Ident::invalid(),
257 id: ast::DUMMY_NODE_ID,
258 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
262 match self.expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
263 Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
265 krate.module = module;
268 // Resolution failed so we return an empty expansion
269 krate.attrs = vec![];
270 krate.module = ast::Mod {
271 inner: orig_mod_span,
278 self.cx.trace_macros_diag();
282 // Fully expand all macro invocations in this AST fragment.
283 fn expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
284 let orig_expansion_data = self.cx.current_expansion.clone();
285 self.cx.current_expansion.depth = 0;
287 // Collect all macro invocations and replace them with placeholders.
288 let (mut fragment_with_placeholders, mut invocations)
289 = self.collect_invocations(input_fragment, &[]);
291 // Optimization: if we resolve all imports now,
292 // we'll be able to immediately resolve most of imported macros.
293 self.resolve_imports();
295 // Resolve paths in all invocations and produce output expanded fragments for them, but
296 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
297 // The output fragments also go through expansion recursively until no invocations are left.
298 // Unresolved macros produce dummy outputs as a recovery measure.
299 invocations.reverse();
300 let mut expanded_fragments = Vec::new();
301 let mut derives: FxHashMap<Mark, Vec<_>> = FxHashMap::default();
302 let mut undetermined_invocations = Vec::new();
303 let (mut progress, mut force) = (false, !self.monotonic);
305 let invoc = if let Some(invoc) = invocations.pop() {
308 self.resolve_imports();
309 if undetermined_invocations.is_empty() { break }
310 invocations = mem::replace(&mut undetermined_invocations, Vec::new());
311 force = !mem::replace(&mut progress, false);
316 if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark };
317 let ext = match self.cx.resolver.resolve_macro_invocation(&invoc, scope, force) {
318 Ok(ext) => Some(ext),
319 Err(Determinacy::Determined) => None,
320 Err(Determinacy::Undetermined) => {
321 undetermined_invocations.push(invoc);
327 let ExpansionData { depth, mark, .. } = invoc.expansion_data;
328 self.cx.current_expansion = invoc.expansion_data.clone();
330 self.cx.current_expansion.mark = scope;
331 // FIXME(jseyfried): Refactor out the following logic
332 let (expanded_fragment, new_invocations) = if let Some(ext) = ext {
333 if let Some(ext) = ext {
334 let (invoc_fragment_kind, invoc_span) = (invoc.fragment_kind, invoc.span());
335 let fragment = self.expand_invoc(invoc, &*ext).unwrap_or_else(|| {
336 invoc_fragment_kind.dummy(invoc_span).unwrap()
338 self.collect_invocations(fragment, &[])
339 } else if let InvocationKind::Attr { attr: None, traits, item, .. } = invoc.kind {
340 if !item.derive_allowed() {
341 let attr = attr::find_by_name(item.attrs(), sym::derive)
342 .expect("`derive` attribute should exist");
343 let span = attr.span;
344 let mut err = self.cx.mut_span_err(span,
345 "`derive` may only be applied to \
346 structs, enums and unions");
347 if let ast::AttrStyle::Inner = attr.style {
348 let trait_list = traits.iter()
349 .map(|t| t.to_string()).collect::<Vec<_>>();
350 let suggestion = format!("#[derive({})]", trait_list.join(", "));
352 span, "try an outer attribute", suggestion,
353 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
354 Applicability::MaybeIncorrect
360 let mut item = self.fully_configure(item);
361 item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
362 let mut item_with_markers = item.clone();
363 add_derived_markers(&mut self.cx, item.span(), &traits, &mut item_with_markers);
364 let derives = derives.entry(invoc.expansion_data.mark).or_default();
366 derives.reserve(traits.len());
367 invocations.reserve(traits.len());
368 for path in &traits {
369 let mark = Mark::fresh(self.cx.current_expansion.mark);
371 let item = match self.cx.resolver.resolve_macro_path(
372 path, MacroKind::Derive, Mark::root(), Vec::new(), false) {
373 Ok(ext) => match ext.kind {
374 SyntaxExtensionKind::LegacyDerive(..) => item_with_markers.clone(),
379 invocations.push(Invocation {
380 kind: InvocationKind::Derive { path: path.clone(), item },
381 fragment_kind: invoc.fragment_kind,
382 expansion_data: ExpansionData {
384 ..invoc.expansion_data.clone()
388 let fragment = invoc.fragment_kind
389 .expect_from_annotatables(::std::iter::once(item_with_markers));
390 self.collect_invocations(fragment, derives)
395 self.collect_invocations(invoc.fragment_kind.dummy(invoc.span()).unwrap(), &[])
398 if expanded_fragments.len() < depth {
399 expanded_fragments.push(Vec::new());
401 expanded_fragments[depth - 1].push((mark, expanded_fragment));
402 if !self.cx.ecfg.single_step {
403 invocations.extend(new_invocations.into_iter().rev());
407 self.cx.current_expansion = orig_expansion_data;
409 // Finally incorporate all the expanded macros into the input AST fragment.
410 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
411 while let Some(expanded_fragments) = expanded_fragments.pop() {
412 for (mark, expanded_fragment) in expanded_fragments.into_iter().rev() {
413 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
414 placeholder_expander.add(NodeId::placeholder_from_mark(mark),
415 expanded_fragment, derives);
418 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
419 fragment_with_placeholders
422 fn resolve_imports(&mut self) {
424 self.cx.resolver.resolve_imports();
428 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
429 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
430 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
431 /// prepares data for resolving paths of macro invocations.
432 fn collect_invocations(&mut self, mut fragment: AstFragment, derives: &[Mark])
433 -> (AstFragment, Vec<Invocation>) {
434 // Resolve `$crate`s in the fragment for pretty-printing.
435 self.cx.resolver.resolve_dollar_crates(&fragment);
438 let mut collector = InvocationCollector {
439 cfg: StripUnconfigured {
440 sess: self.cx.parse_sess,
441 features: self.cx.ecfg.features,
444 invocations: Vec::new(),
445 monotonic: self.monotonic,
447 fragment.mut_visit_with(&mut collector);
448 collector.invocations
452 self.cx.resolver.visit_ast_fragment_with_placeholders(
453 self.cx.current_expansion.mark, &fragment, derives);
456 (fragment, invocations)
459 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
460 let mut cfg = StripUnconfigured {
461 sess: self.cx.parse_sess,
462 features: self.cx.ecfg.features,
464 // Since the item itself has already been configured by the InvocationCollector,
465 // we know that fold result vector will contain exactly one element
467 Annotatable::Item(item) => {
468 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
470 Annotatable::TraitItem(item) => {
471 Annotatable::TraitItem(
472 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
474 Annotatable::ImplItem(item) => {
475 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
477 Annotatable::ForeignItem(item) => {
478 Annotatable::ForeignItem(
479 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
482 Annotatable::Stmt(stmt) => {
483 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
485 Annotatable::Expr(mut expr) => {
486 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
491 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtension) -> Option<AstFragment> {
492 if invoc.fragment_kind == AstFragmentKind::ForeignItems &&
493 !self.cx.ecfg.macros_in_extern_enabled() {
494 if let SyntaxExtensionKind::NonMacroAttr { .. } = ext.kind {} else {
495 emit_feature_err(&self.cx.parse_sess, sym::macros_in_extern,
496 invoc.span(), GateIssue::Language,
497 "macro invocations in `extern {}` blocks are experimental");
501 let result = match invoc.kind {
502 InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext)?,
503 InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext)?,
504 InvocationKind::Derive { .. } => self.expand_derive_invoc(invoc, ext)?,
507 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
508 let info = self.cx.current_expansion.mark.expn_info().unwrap();
509 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
510 let mut err = self.cx.struct_span_err(info.call_site,
511 &format!("recursion limit reached while expanding the macro `{}`",
512 info.format.name()));
514 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
517 self.cx.trace_macros_diag();
524 fn expand_attr_invoc(&mut self,
526 ext: &SyntaxExtension)
527 -> Option<AstFragment> {
528 let (attr, mut item) = match invoc.kind {
529 InvocationKind::Attr { attr, item, .. } => (attr?, item),
534 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
535 attr::mark_known(&attr);
537 attr::mark_used(&attr);
539 item.visit_attrs(|attrs| attrs.push(attr));
540 Some(invoc.fragment_kind.expect_from_annotatables(iter::once(item)))
542 SyntaxExtensionKind::LegacyAttr(expander) => {
543 let meta = attr.parse_meta(self.cx.parse_sess)
544 .map_err(|mut e| { e.emit(); }).ok()?;
545 let item = expander.expand(self.cx, attr.span, &meta, item);
546 Some(invoc.fragment_kind.expect_from_annotatables(item))
548 SyntaxExtensionKind::Attr(expander) => {
549 self.gate_proc_macro_attr_item(attr.span, &item);
550 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
551 Annotatable::Item(item) => token::NtItem(item),
552 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
553 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
554 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
555 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
556 Annotatable::Expr(expr) => token::NtExpr(expr),
557 })), DUMMY_SP).into();
558 let input = self.extract_proc_macro_attr_input(attr.tokens, attr.span);
559 let tok_result = expander.expand(self.cx, attr.span, input, item_tok);
560 let res = self.parse_ast_fragment(tok_result, invoc.fragment_kind,
561 &attr.path, attr.span);
562 self.gate_proc_macro_expansion(attr.span, &res);
565 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
566 self.cx.span_err(attr.span, &format!("`{}` is a derive macro", attr.path));
567 self.cx.trace_macros_diag();
568 invoc.fragment_kind.dummy(attr.span)
571 let msg = &format!("macro `{}` may not be used in attributes", attr.path);
572 self.cx.span_err(attr.span, msg);
573 self.cx.trace_macros_diag();
574 invoc.fragment_kind.dummy(attr.span)
579 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
580 let mut trees = tokens.trees();
582 Some(TokenTree::Delimited(_, _, tts)) => {
583 if trees.next().is_none() {
587 Some(TokenTree::Token(..)) => {}
588 None => return TokenStream::empty(),
590 self.cx.span_err(span, "custom attribute invocations must be \
591 of the form #[foo] or #[foo(..)], the macro name must only be \
592 followed by a delimiter token");
596 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
597 let (kind, gate) = match *item {
598 Annotatable::Item(ref item) => {
600 ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
601 ItemKind::Mod(_) => ("modules", sym::proc_macro_hygiene),
605 Annotatable::TraitItem(_) => return,
606 Annotatable::ImplItem(_) => return,
607 Annotatable::ForeignItem(_) => return,
608 Annotatable::Stmt(_) |
609 Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
610 Annotatable::Stmt(_) => ("statements", sym::proc_macro_hygiene),
611 Annotatable::Expr(_) => ("expressions", sym::proc_macro_hygiene),
618 &format!("custom attributes cannot be applied to {}", kind),
622 fn gate_proc_macro_expansion(&self, span: Span, fragment: &Option<AstFragment>) {
623 if self.cx.ecfg.proc_macro_hygiene() {
626 let fragment = match fragment {
627 Some(fragment) => fragment,
631 fragment.visit_with(&mut DisallowMacros {
633 parse_sess: self.cx.parse_sess,
636 struct DisallowMacros<'a> {
638 parse_sess: &'a ParseSess,
641 impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
642 fn visit_item(&mut self, i: &'ast ast::Item) {
643 if let ast::ItemKind::MacroDef(_) = i.node {
646 sym::proc_macro_hygiene,
649 "procedural macros cannot expand to macro definitions",
652 visit::walk_item(self, i);
655 fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
661 /// Expand a macro invocation. Returns the resulting expanded AST fragment.
662 fn expand_bang_invoc(&mut self,
664 ext: &SyntaxExtension)
665 -> Option<AstFragment> {
666 let kind = invoc.fragment_kind;
667 let (mac, ident, span) = match invoc.kind {
668 InvocationKind::Bang { mac, ident, span } => (mac, ident, span),
671 let path = &mac.node.path;
673 let ident = ident.unwrap_or_else(|| Ident::invalid());
674 let validate = |this: &mut Self| {
675 // feature-gate the macro invocation
676 if let Some((feature, issue)) = ext.unstable_feature {
677 let crate_span = this.cx.current_expansion.crate_span.unwrap();
678 // don't stability-check macros in the same crate
679 // (the only time this is null is for syntax extensions registered as macros)
680 if ext.def_info.map_or(false, |(_, def_span)| !crate_span.contains(def_span))
681 && !span.allows_unstable(feature)
682 && this.cx.ecfg.features.map_or(true, |feats| {
683 // macro features will count as lib features
684 !feats.declared_lib_features.iter().any(|&(feat, _)| feat == feature)
686 let explain = format!("macro {}! is unstable", path);
687 emit_feature_err(this.cx.parse_sess, feature, span,
688 GateIssue::Library(Some(issue)), &explain);
689 this.cx.trace_macros_diag();
693 if ident.name != kw::Invalid {
694 let msg = format!("macro {}! expects no ident argument, given '{}'", path, ident);
695 this.cx.span_err(path.span, &msg);
696 this.cx.trace_macros_diag();
697 return Err(kind.dummy(span));
702 let opt_expanded = match &ext.kind {
703 SyntaxExtensionKind::LegacyBang(expander) => {
704 if let Err(dummy_span) = validate(self) {
707 kind.make_from(expander.expand(
711 ext.def_info.map(|(_, s)| s),
716 SyntaxExtensionKind::Attr(..) |
717 SyntaxExtensionKind::LegacyAttr(..) |
718 SyntaxExtensionKind::NonMacroAttr { .. } => {
719 self.cx.span_err(path.span,
720 &format!("`{}` can only be used in attributes", path));
721 self.cx.trace_macros_diag();
725 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
726 self.cx.span_err(path.span, &format!("`{}` is a derive macro", path));
727 self.cx.trace_macros_diag();
731 SyntaxExtensionKind::Bang(expander) => {
732 if ident.name != kw::Invalid {
734 format!("macro {}! expects no ident argument, given '{}'", path, ident);
735 self.cx.span_err(path.span, &msg);
736 self.cx.trace_macros_diag();
739 self.gate_proc_macro_expansion_kind(span, kind);
740 let tok_result = expander.expand(self.cx, span, mac.node.stream());
741 let result = self.parse_ast_fragment(tok_result, kind, path, span);
742 self.gate_proc_macro_expansion(span, &result);
748 if opt_expanded.is_some() {
751 let msg = format!("non-{kind} macro in {kind} position: {name}",
752 name = path.segments[0].ident.name, kind = kind.name());
753 self.cx.span_err(path.span, &msg);
754 self.cx.trace_macros_diag();
759 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
760 let kind = match kind {
761 AstFragmentKind::Expr => "expressions",
762 AstFragmentKind::OptExpr => "expressions",
763 AstFragmentKind::Pat => "patterns",
764 AstFragmentKind::Ty => "types",
765 AstFragmentKind::Stmts => "statements",
766 AstFragmentKind::Items => return,
767 AstFragmentKind::TraitItems => return,
768 AstFragmentKind::ImplItems => return,
769 AstFragmentKind::ForeignItems => return,
771 if self.cx.ecfg.proc_macro_hygiene() {
776 sym::proc_macro_hygiene,
779 &format!("procedural macros cannot be expanded to {}", kind),
783 /// Expand a derive invocation. Returns the resulting expanded AST fragment.
784 fn expand_derive_invoc(&mut self,
786 ext: &SyntaxExtension)
787 -> Option<AstFragment> {
788 let (path, item) = match invoc.kind {
789 InvocationKind::Derive { path, item } => (path, item),
792 if !item.derive_allowed() {
797 SyntaxExtensionKind::Derive(expander) |
798 SyntaxExtensionKind::LegacyDerive(expander) => {
799 let meta = ast::MetaItem { node: ast::MetaItemKind::Word, span: path.span, path };
800 let span = meta.span.with_ctxt(self.cx.backtrace());
801 let items = expander.expand(self.cx, span, &meta, item);
802 Some(invoc.fragment_kind.expect_from_annotatables(items))
805 let msg = &format!("macro `{}` may not be used for derive attributes", path);
806 self.cx.span_err(path.span, msg);
807 self.cx.trace_macros_diag();
808 invoc.fragment_kind.dummy(path.span)
813 fn parse_ast_fragment(&mut self,
815 kind: AstFragmentKind,
818 -> Option<AstFragment> {
819 let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
820 match parser.parse_ast_fragment(kind, false) {
822 parser.ensure_complete_parse(path, kind.name(), span);
828 self.cx.trace_macros_diag();
835 impl<'a> Parser<'a> {
836 pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
837 -> PResult<'a, AstFragment> {
839 AstFragmentKind::Items => {
840 let mut items = SmallVec::new();
841 while let Some(item) = self.parse_item()? {
844 AstFragment::Items(items)
846 AstFragmentKind::TraitItems => {
847 let mut items = SmallVec::new();
848 while self.token != token::Eof {
849 items.push(self.parse_trait_item(&mut false)?);
851 AstFragment::TraitItems(items)
853 AstFragmentKind::ImplItems => {
854 let mut items = SmallVec::new();
855 while self.token != token::Eof {
856 items.push(self.parse_impl_item(&mut false)?);
858 AstFragment::ImplItems(items)
860 AstFragmentKind::ForeignItems => {
861 let mut items = SmallVec::new();
862 while self.token != token::Eof {
863 items.push(self.parse_foreign_item()?);
865 AstFragment::ForeignItems(items)
867 AstFragmentKind::Stmts => {
868 let mut stmts = SmallVec::new();
869 while self.token != token::Eof &&
870 // won't make progress on a `}`
871 self.token != token::CloseDelim(token::Brace) {
872 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
876 AstFragment::Stmts(stmts)
878 AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
879 AstFragmentKind::OptExpr => {
880 if self.token != token::Eof {
881 AstFragment::OptExpr(Some(self.parse_expr()?))
883 AstFragment::OptExpr(None)
886 AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
887 AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat(None)?),
891 pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
892 if self.token != token::Eof {
893 let msg = format!("macro expansion ignores token `{}` and any following",
894 self.this_token_to_string());
895 // Avoid emitting backtrace info twice.
896 let def_site_span = self.token.span.with_ctxt(SyntaxContext::empty());
897 let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
898 err.span_label(span, "caused by the macro expansion here");
900 "the usage of `{}!` is likely invalid in {} context",
905 let semi_span = self.sess.source_map().next_point(span);
907 let semi_full_span = semi_span.to(self.sess.source_map().next_point(semi_span));
908 match self.sess.source_map().span_to_snippet(semi_full_span) {
909 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
912 "you might be missing a semicolon here",
914 Applicability::MaybeIncorrect,
924 struct InvocationCollector<'a, 'b> {
925 cx: &'a mut ExtCtxt<'b>,
926 cfg: StripUnconfigured<'a>,
927 invocations: Vec<Invocation>,
931 impl<'a, 'b> InvocationCollector<'a, 'b> {
932 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
933 let mark = Mark::fresh(self.cx.current_expansion.mark);
934 self.invocations.push(Invocation {
937 expansion_data: ExpansionData {
939 depth: self.cx.current_expansion.depth + 1,
940 ..self.cx.current_expansion.clone()
943 placeholder(fragment_kind, NodeId::placeholder_from_mark(mark))
946 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
947 self.collect(kind, InvocationKind::Bang { mac, ident: None, span })
950 fn collect_attr(&mut self,
951 attr: Option<ast::Attribute>,
954 kind: AstFragmentKind,
957 self.collect(kind, InvocationKind::Attr { attr, traits, item, after_derive })
960 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
961 -> Option<ast::Attribute> {
962 let attr = attrs.iter()
964 if a.path == sym::derive {
965 *after_derive = true;
967 !attr::is_known(a) && !is_builtin_attr(a)
969 .map(|i| attrs.remove(i));
970 if let Some(attr) = &attr {
971 if !self.cx.ecfg.enable_custom_inner_attributes() &&
972 attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
973 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
974 attr.span, GateIssue::Language,
975 "non-builtin inner attributes are unstable");
981 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
982 fn classify_item<T>(&mut self, item: &mut T)
983 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
986 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
988 item.visit_attrs(|mut attrs| {
989 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
990 traits = collect_derives(&mut self.cx, &mut attrs);
993 (attr, traits, after_derive)
996 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
997 /// to the unused-attributes lint (making it an error on statements and expressions
998 /// is a breaking change)
999 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
1000 -> (Option<ast::Attribute>, /* after_derive */ bool) {
1001 let (mut attr, mut after_derive) = (None, false);
1003 nonitem.visit_attrs(|mut attrs| {
1004 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1007 (attr, after_derive)
1010 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1011 self.cfg.configure(node)
1014 // Detect use of feature-gated or invalid attributes on macro invocations
1015 // since they will not be detected after macro expansion.
1016 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1017 let features = self.cx.ecfg.features.unwrap();
1018 for attr in attrs.iter() {
1019 self.check_attribute_inner(attr, features);
1021 // macros are expanded before any lint passes so this warning has to be hardcoded
1022 if attr.path == sym::derive {
1023 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1024 .note("this may become a hard error in a future release")
1030 fn check_attribute(&mut self, at: &ast::Attribute) {
1031 let features = self.cx.ecfg.features.unwrap();
1032 self.check_attribute_inner(at, features);
1035 fn check_attribute_inner(&mut self, at: &ast::Attribute, features: &Features) {
1036 feature_gate::check_attribute(at, self.cx.parse_sess, features);
1040 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1041 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1042 self.cfg.configure_expr(expr);
1043 visit_clobber(expr.deref_mut(), |mut expr| {
1044 self.cfg.configure_expr_kind(&mut expr.node);
1046 // ignore derives so they remain unused
1047 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1050 // Collect the invoc regardless of whether or not attributes are permitted here
1051 // expansion will eat the attribute so it won't error later.
1052 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1054 // AstFragmentKind::Expr requires the macro to emit an expression.
1055 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1056 AstFragmentKind::Expr, after_derive)
1061 if let ast::ExprKind::Mac(mac) = expr.node {
1062 self.check_attributes(&expr.attrs);
1063 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1067 noop_visit_expr(&mut expr, self);
1073 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1074 let expr = configure!(self, expr);
1075 expr.filter_map(|mut expr| {
1076 self.cfg.configure_expr_kind(&mut expr.node);
1078 // Ignore derives so they remain unused.
1079 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1082 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1084 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1085 AstFragmentKind::OptExpr, after_derive)
1087 .map(|expr| expr.into_inner())
1090 if let ast::ExprKind::Mac(mac) = expr.node {
1091 self.check_attributes(&expr.attrs);
1092 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1094 .map(|expr| expr.into_inner())
1096 Some({ noop_visit_expr(&mut expr, self); expr })
1101 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1102 self.cfg.configure_pat(pat);
1104 PatKind::Mac(_) => {}
1105 _ => return noop_visit_pat(pat, self),
1108 visit_clobber(pat, |mut pat| {
1109 match mem::replace(&mut pat.node, PatKind::Wild) {
1110 PatKind::Mac(mac) =>
1111 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1112 _ => unreachable!(),
1117 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1118 let mut stmt = configure!(self, stmt);
1120 // we'll expand attributes on expressions separately
1121 if !stmt.is_expr() {
1122 let (attr, derives, after_derive) = if stmt.is_item() {
1123 self.classify_item(&mut stmt)
1125 // ignore derives on non-item statements so it falls through
1126 // to the unused-attributes lint
1127 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1128 (attr, vec![], after_derive)
1131 if attr.is_some() || !derives.is_empty() {
1132 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1133 AstFragmentKind::Stmts, after_derive).make_stmts();
1137 if let StmtKind::Mac(mac) = stmt.node {
1138 let (mac, style, attrs) = mac.into_inner();
1139 self.check_attributes(&attrs);
1140 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1143 // If this is a macro invocation with a semicolon, then apply that
1144 // semicolon to the final statement produced by expansion.
1145 if style == MacStmtStyle::Semicolon {
1146 if let Some(stmt) = placeholder.pop() {
1147 placeholder.push(stmt.add_trailing_semicolon());
1154 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1155 let ast::Stmt { id, node, span } = stmt;
1156 noop_flat_map_stmt_kind(node, self).into_iter().map(|node| {
1157 ast::Stmt { id, node, span }
1162 fn visit_block(&mut self, block: &mut P<Block>) {
1163 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1164 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1165 noop_visit_block(block, self);
1166 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1169 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1170 let mut item = configure!(self, item);
1172 let (attr, traits, after_derive) = self.classify_item(&mut item);
1173 if attr.is_some() || !traits.is_empty() {
1174 return self.collect_attr(attr, traits, Annotatable::Item(item),
1175 AstFragmentKind::Items, after_derive).make_items();
1179 ast::ItemKind::Mac(..) => {
1180 self.check_attributes(&item.attrs);
1181 item.and_then(|item| match item.node {
1182 ItemKind::Mac(mac) => {
1183 self.collect(AstFragmentKind::Items, InvocationKind::Bang {
1185 ident: Some(item.ident),
1189 _ => unreachable!(),
1192 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1193 if item.ident == Ident::invalid() {
1194 return noop_flat_map_item(item, self);
1197 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1198 let mut module = (*self.cx.current_expansion.module).clone();
1199 module.mod_path.push(item.ident);
1201 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1202 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1203 // Thus, if `inner` is the dummy span, we know the module is inline.
1204 let inline_module = item.span.contains(inner) || inner.is_dummy();
1207 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1208 self.cx.current_expansion.directory_ownership =
1209 DirectoryOwnership::Owned { relative: None };
1210 module.directory.push(&*path.as_str());
1212 module.directory.push(&*item.ident.as_str());
1215 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1216 let mut path = match path {
1217 FileName::Real(path) => path,
1218 other => PathBuf::from(other.to_string()),
1220 let directory_ownership = match path.file_name().unwrap().to_str() {
1221 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1222 Some(_) => DirectoryOwnership::Owned {
1223 relative: Some(item.ident),
1225 None => DirectoryOwnership::UnownedViaMod(false),
1228 module.directory = path;
1229 self.cx.current_expansion.directory_ownership = directory_ownership;
1233 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1234 let result = noop_flat_map_item(item, self);
1235 self.cx.current_expansion.module = orig_module;
1236 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1240 _ => noop_flat_map_item(item, self),
1244 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1245 let mut item = configure!(self, item);
1247 let (attr, traits, after_derive) = self.classify_item(&mut item);
1248 if attr.is_some() || !traits.is_empty() {
1249 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1250 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1254 ast::TraitItemKind::Macro(mac) => {
1255 let ast::TraitItem { attrs, span, .. } = item;
1256 self.check_attributes(&attrs);
1257 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1259 _ => noop_flat_map_trait_item(item, self),
1263 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1264 let mut item = configure!(self, item);
1266 let (attr, traits, after_derive) = self.classify_item(&mut item);
1267 if attr.is_some() || !traits.is_empty() {
1268 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1269 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1273 ast::ImplItemKind::Macro(mac) => {
1274 let ast::ImplItem { attrs, span, .. } = item;
1275 self.check_attributes(&attrs);
1276 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1278 _ => noop_flat_map_impl_item(item, self),
1282 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1284 ast::TyKind::Mac(_) => {}
1285 _ => return noop_visit_ty(ty, self),
1288 visit_clobber(ty, |mut ty| {
1289 match mem::replace(&mut ty.node, ast::TyKind::Err) {
1290 ast::TyKind::Mac(mac) =>
1291 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1292 _ => unreachable!(),
1297 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1298 self.cfg.configure_foreign_mod(foreign_mod);
1299 noop_visit_foreign_mod(foreign_mod, self);
1302 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1303 -> SmallVec<[ast::ForeignItem; 1]>
1305 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1307 if attr.is_some() || !traits.is_empty() {
1308 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1309 AstFragmentKind::ForeignItems, after_derive)
1310 .make_foreign_items();
1313 if let ast::ForeignItemKind::Macro(mac) = foreign_item.node {
1314 self.check_attributes(&foreign_item.attrs);
1315 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1316 .make_foreign_items();
1319 noop_flat_map_foreign_item(foreign_item, self)
1322 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1324 ast::ItemKind::MacroDef(..) => {}
1326 self.cfg.configure_item_kind(item);
1327 noop_visit_item_kind(item, self);
1332 fn visit_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
1333 self.cfg.configure_generic_params(params);
1334 noop_visit_generic_params(params, self);
1337 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1338 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1339 // contents="file contents")]` attributes
1340 if !at.check_name(sym::doc) {
1341 return noop_visit_attribute(at, self);
1344 if let Some(list) = at.meta_item_list() {
1345 if !list.iter().any(|it| it.check_name(sym::include)) {
1346 return noop_visit_attribute(at, self);
1349 let mut items = vec![];
1351 for mut it in list {
1352 if !it.check_name(sym::include) {
1353 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1357 if let Some(file) = it.value_str() {
1358 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1359 self.check_attribute(&at);
1360 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1361 // avoid loading the file if they haven't enabled the feature
1362 return noop_visit_attribute(at, self);
1365 let filename = self.cx.root_path.join(file.to_string());
1366 match fs::read_to_string(&filename) {
1368 let src_interned = Symbol::intern(&src);
1370 // Add this input file to the code map to make it available as
1371 // dependency information
1372 self.cx.source_map().new_source_file(filename.into(), src);
1374 let include_info = vec![
1375 ast::NestedMetaItem::MetaItem(
1376 attr::mk_name_value_item_str(
1377 Ident::with_empty_ctxt(sym::file),
1378 dummy_spanned(file),
1381 ast::NestedMetaItem::MetaItem(
1382 attr::mk_name_value_item_str(
1383 Ident::with_empty_ctxt(sym::contents),
1384 dummy_spanned(src_interned),
1389 let include_ident = Ident::with_empty_ctxt(sym::include);
1390 let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info);
1391 items.push(ast::NestedMetaItem::MetaItem(item));
1396 .and_then(|item| item.name_value_literal())
1399 if e.kind() == ErrorKind::InvalidData {
1403 &format!("{} wasn't a utf-8 file", filename.display()),
1405 .span_label(lit.span, "contains invalid utf-8")
1408 let mut err = self.cx.struct_span_err(
1410 &format!("couldn't read {}: {}", filename.display(), e),
1412 err.span_label(lit.span, "couldn't read file");
1414 if e.kind() == ErrorKind::NotFound {
1415 err.help("external doc paths are relative to the crate root");
1423 let mut err = self.cx.struct_span_err(
1425 &format!("expected path to external documentation"),
1428 // Check if the user erroneously used `doc(include(...))` syntax.
1429 let literal = it.meta_item_list().and_then(|list| {
1430 if list.len() == 1 {
1431 list[0].literal().map(|literal| &literal.node)
1437 let (path, applicability) = match &literal {
1438 Some(LitKind::Str(path, ..)) => {
1439 (path.to_string(), Applicability::MachineApplicable)
1441 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1444 err.span_suggestion(
1446 "provide a file path with `=`",
1447 format!("include = \"{}\"", path),
1455 let meta = attr::mk_list_item(DUMMY_SP, Ident::with_empty_ctxt(sym::doc), items);
1457 ast::AttrStyle::Inner => *at = attr::mk_spanned_attr_inner(at.span, at.id, meta),
1458 ast::AttrStyle::Outer => *at = attr::mk_spanned_attr_outer(at.span, at.id, meta),
1461 noop_visit_attribute(at, self)
1465 fn visit_id(&mut self, id: &mut ast::NodeId) {
1467 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1468 *id = self.cx.resolver.next_node_id()
1472 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1473 self.cfg.configure_fn_decl(&mut fn_decl);
1474 noop_visit_fn_decl(fn_decl, self);
1478 pub struct ExpansionConfig<'feat> {
1479 pub crate_name: String,
1480 pub features: Option<&'feat Features>,
1481 pub recursion_limit: usize,
1482 pub trace_mac: bool,
1483 pub should_test: bool, // If false, strip `#[test]` nodes
1484 pub single_step: bool,
1485 pub keep_macs: bool,
1488 macro_rules! feature_tests {
1489 ($( fn $getter:ident = $field:ident, )*) => {
1491 pub fn $getter(&self) -> bool {
1492 match self.features {
1493 Some(&Features { $field: true, .. }) => true,
1501 impl<'feat> ExpansionConfig<'feat> {
1502 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1506 recursion_limit: 1024,
1515 fn enable_asm = asm,
1516 fn enable_custom_test_frameworks = custom_test_frameworks,
1517 fn enable_global_asm = global_asm,
1518 fn enable_log_syntax = log_syntax,
1519 fn enable_concat_idents = concat_idents,
1520 fn enable_trace_macros = trace_macros,
1521 fn enable_allow_internal_unstable = allow_internal_unstable,
1522 fn enable_format_args_nl = format_args_nl,
1523 fn macros_in_extern_enabled = macros_in_extern,
1524 fn proc_macro_hygiene = proc_macro_hygiene,
1527 fn enable_custom_inner_attributes(&self) -> bool {
1528 self.features.map_or(false, |features| {
1529 features.custom_inner_attributes || features.custom_attribute || features.rustc_attrs
1534 // A Marker adds the given mark to the syntax context.
1536 pub struct Marker(pub Mark);
1538 impl MutVisitor for Marker {
1539 fn visit_span(&mut self, span: &mut Span) {
1540 *span = span.apply_mark(self.0)
1543 fn visit_mac(&mut self, mac: &mut ast::Mac) {
1544 noop_visit_mac(mac, self)