2 use crate::proc_macro::{collect_derives, MarkAttrs};
3 use crate::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
4 use crate::mbe::macro_rules::annotate_err_with_kind;
5 use crate::placeholders::{placeholder, PlaceholderExpander};
7 use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
8 use syntax::ast::{MacStmtStyle, StmtKind, ItemKind};
9 use syntax::attr::{self, HasAttrs};
10 use syntax::source_map::respan;
11 use syntax::configure;
12 use syntax::config::StripUnconfigured;
13 use syntax::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
14 use syntax::mut_visit::*;
15 use syntax::parse::{DirectoryOwnership, PResult};
16 use syntax::parse::token;
17 use syntax::parse::parser::Parser;
18 use syntax::print::pprust;
20 use syntax::sess::ParseSess;
21 use syntax::symbol::{sym, Symbol};
22 use syntax::tokenstream::{TokenStream, TokenTree};
23 use syntax::visit::{self, Visitor};
24 use syntax::util::map_in_place::MapInPlace;
26 use errors::{Applicability, FatalError};
27 use smallvec::{smallvec, SmallVec};
28 use syntax_pos::{Span, DUMMY_SP, FileName};
30 use rustc_data_structures::sync::Lrc;
31 use std::io::ErrorKind;
32 use std::{iter, mem, slice};
33 use std::ops::DerefMut;
35 use std::path::PathBuf;
37 macro_rules! ast_fragments {
39 $($Kind:ident($AstTy:ty) {
41 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
42 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
46 /// A fragment of AST that can be produced by a single macro expansion.
47 /// Can also serve as an input and intermediate result for macro expansion operations.
48 pub enum AstFragment {
49 OptExpr(Option<P<ast::Expr>>),
53 /// "Discriminant" of an AST fragment.
54 #[derive(Copy, Clone, PartialEq, Eq)]
55 pub enum AstFragmentKind {
60 impl AstFragmentKind {
61 pub fn name(self) -> &'static str {
63 AstFragmentKind::OptExpr => "expression",
64 $(AstFragmentKind::$Kind => $kind_name,)*
68 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
70 AstFragmentKind::OptExpr =>
71 result.make_expr().map(Some).map(AstFragment::OptExpr),
72 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
78 pub fn add_placeholders(&mut self, placeholders: &[NodeId]) {
79 if placeholders.is_empty() {
83 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
84 // We are repeating through arguments with `many`, to do that we have to
85 // mention some macro variable from those arguments even if it's not used.
86 #[cfg_attr(bootstrap, allow(unused_macros))]
87 macro _repeating($flat_map_ast_elt) {}
88 placeholder(AstFragmentKind::$Kind, *id).$make_ast()
90 _ => panic!("unexpected AST fragment kind")
94 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
96 AstFragment::OptExpr(expr) => expr,
97 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
101 $(pub fn $make_ast(self) -> $AstTy {
103 AstFragment::$Kind(ast) => ast,
104 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
108 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
110 AstFragment::OptExpr(opt_expr) => {
111 visit_clobber(opt_expr, |opt_expr| {
112 if let Some(expr) = opt_expr {
113 vis.filter_map_expr(expr)
119 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
120 $($(AstFragment::$Kind(ast) =>
121 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
125 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
127 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
128 AstFragment::OptExpr(None) => {}
129 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
130 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
131 visitor.$visit_ast_elt(ast_elt);
137 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
138 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
140 Some(self.make(AstFragmentKind::$Kind).$make_ast())
147 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
148 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
149 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
150 Stmts(SmallVec<[ast::Stmt; 1]>) {
151 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
153 Items(SmallVec<[P<ast::Item>; 1]>) {
154 "item"; many fn flat_map_item; fn visit_item; fn make_items;
156 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
157 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
159 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
160 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
162 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
164 many fn flat_map_foreign_item;
165 fn visit_foreign_item;
166 fn make_foreign_items;
168 Arms(SmallVec<[ast::Arm; 1]>) {
169 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
171 Fields(SmallVec<[ast::Field; 1]>) {
172 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
174 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
176 many fn flat_map_field_pattern;
177 fn visit_field_pattern;
178 fn make_field_patterns;
180 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
182 many fn flat_map_generic_param;
183 fn visit_generic_param;
184 fn make_generic_params;
186 Params(SmallVec<[ast::Param; 1]>) {
187 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
189 StructFields(SmallVec<[ast::StructField; 1]>) {
191 many fn flat_map_struct_field;
192 fn visit_struct_field;
193 fn make_struct_fields;
195 Variants(SmallVec<[ast::Variant; 1]>) {
196 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
200 impl AstFragmentKind {
201 fn dummy(self, span: Span) -> AstFragment {
202 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
205 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
207 let mut items = items.into_iter();
209 AstFragmentKind::Arms =>
210 AstFragment::Arms(items.map(Annotatable::expect_arm).collect()),
211 AstFragmentKind::Fields =>
212 AstFragment::Fields(items.map(Annotatable::expect_field).collect()),
213 AstFragmentKind::FieldPats =>
214 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()),
215 AstFragmentKind::GenericParams =>
216 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()),
217 AstFragmentKind::Params =>
218 AstFragment::Params(items.map(Annotatable::expect_param).collect()),
219 AstFragmentKind::StructFields => AstFragment::StructFields(
220 items.map(Annotatable::expect_struct_field).collect()
222 AstFragmentKind::Variants =>
223 AstFragment::Variants(items.map(Annotatable::expect_variant).collect()),
224 AstFragmentKind::Items =>
225 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
226 AstFragmentKind::ImplItems =>
227 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
228 AstFragmentKind::TraitItems =>
229 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
230 AstFragmentKind::ForeignItems =>
231 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
232 AstFragmentKind::Stmts =>
233 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
234 AstFragmentKind::Expr => AstFragment::Expr(
235 items.next().expect("expected exactly one expression").expect_expr()
237 AstFragmentKind::OptExpr =>
238 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
239 AstFragmentKind::Pat | AstFragmentKind::Ty =>
240 panic!("patterns and types aren't annotatable"),
245 pub struct Invocation {
246 pub kind: InvocationKind,
247 pub fragment_kind: AstFragmentKind,
248 pub expansion_data: ExpansionData,
251 pub enum InvocationKind {
257 attr: ast::Attribute,
259 // Required for resolving derive helper attributes.
261 // We temporarily report errors for attribute macros placed after derives
268 /// "Invocation" that contains all derives from an item,
269 /// broken into multiple `Derive` invocations when expanded.
270 /// FIXME: Find a way to remove it.
278 pub fn span(&self) -> Span {
280 InvocationKind::Bang { span, .. } => *span,
281 InvocationKind::Attr { attr, .. } => attr.span,
282 InvocationKind::Derive { path, .. } => path.span,
283 InvocationKind::DeriveContainer { item, .. } => item.span(),
288 pub struct MacroExpander<'a, 'b> {
289 pub cx: &'a mut ExtCtxt<'b>,
290 monotonic: bool, // cf. `cx.monotonic_expander()`
293 impl<'a, 'b> MacroExpander<'a, 'b> {
294 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
295 MacroExpander { cx, monotonic }
298 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
299 let mut module = ModuleData {
300 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
301 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
302 FileName::Real(path) => path,
303 other => PathBuf::from(other.to_string()),
306 module.directory.pop();
307 self.cx.root_path = module.directory.clone();
308 self.cx.current_expansion.module = Rc::new(module);
310 let orig_mod_span = krate.module.inner;
312 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
315 kind: ast::ItemKind::Mod(krate.module),
316 ident: Ident::invalid(),
317 id: ast::DUMMY_NODE_ID,
318 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
322 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
323 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
325 krate.module = module;
328 // Resolution failed so we return an empty expansion
329 krate.attrs = vec![];
330 krate.module = ast::Mod {
331 inner: orig_mod_span,
338 self.cx.trace_macros_diag();
342 // Recursively expand all macro invocations in this AST fragment.
343 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
344 let orig_expansion_data = self.cx.current_expansion.clone();
345 self.cx.current_expansion.depth = 0;
347 // Collect all macro invocations and replace them with placeholders.
348 let (mut fragment_with_placeholders, mut invocations)
349 = self.collect_invocations(input_fragment, &[]);
351 // Optimization: if we resolve all imports now,
352 // we'll be able to immediately resolve most of imported macros.
353 self.resolve_imports();
355 // Resolve paths in all invocations and produce output expanded fragments for them, but
356 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
357 // The output fragments also go through expansion recursively until no invocations are left.
358 // Unresolved macros produce dummy outputs as a recovery measure.
359 invocations.reverse();
360 let mut expanded_fragments = Vec::new();
361 let mut undetermined_invocations = Vec::new();
362 let (mut progress, mut force) = (false, !self.monotonic);
364 let invoc = if let Some(invoc) = invocations.pop() {
367 self.resolve_imports();
368 if undetermined_invocations.is_empty() { break }
369 invocations = mem::take(&mut undetermined_invocations);
370 force = !mem::replace(&mut progress, false);
374 let eager_expansion_root =
375 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
376 let res = match self.cx.resolver.resolve_macro_invocation(
377 &invoc, eager_expansion_root, force
380 Err(Indeterminate) => {
381 undetermined_invocations.push(invoc);
387 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
388 self.cx.current_expansion = invoc.expansion_data.clone();
390 // FIXME(jseyfried): Refactor out the following logic
391 let (expanded_fragment, new_invocations) = match res {
392 InvocationRes::Single(ext) => {
393 let fragment = self.expand_invoc(invoc, &ext.kind);
394 self.collect_invocations(fragment, &[])
396 InvocationRes::DeriveContainer(exts) => {
397 let (derives, item) = match invoc.kind {
398 InvocationKind::DeriveContainer { derives, item } => (derives, item),
401 if !item.derive_allowed() {
402 let attr = attr::find_by_name(item.attrs(), sym::derive)
403 .expect("`derive` attribute should exist");
404 let span = attr.span;
405 let mut err = self.cx.struct_span_err(span,
406 "`derive` may only be applied to structs, enums and unions");
407 if let ast::AttrStyle::Inner = attr.style {
408 let trait_list = derives.iter()
409 .map(|t| pprust::path_to_string(t))
410 .collect::<Vec<_>>();
411 let suggestion = format!("#[derive({})]", trait_list.join(", "));
413 span, "try an outer attribute", suggestion,
414 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
415 Applicability::MaybeIncorrect
421 let mut item = self.fully_configure(item);
422 item.visit_attrs(|attrs| attrs.retain(|a| !a.has_name(sym::derive)));
423 let mut helper_attrs = Vec::new();
424 let mut has_copy = false;
426 helper_attrs.extend(&ext.helper_attrs);
427 has_copy |= ext.is_derive_copy;
429 // Mark derive helpers inside this item as known and used.
430 // FIXME: This is a hack, derive helpers should be integrated with regular name
431 // resolution instead. For example, helpers introduced by a derive container
432 // can be in scope for all code produced by that container's expansion.
433 item.visit_with(&mut MarkAttrs(&helper_attrs));
435 self.cx.resolver.add_derive_copy(invoc.expansion_data.id);
438 let mut derive_placeholders = Vec::with_capacity(derives.len());
439 invocations.reserve(derives.len());
440 for path in derives {
441 let expn_id = ExpnId::fresh(None);
442 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
443 invocations.push(Invocation {
444 kind: InvocationKind::Derive { path, item: item.clone() },
445 fragment_kind: invoc.fragment_kind,
446 expansion_data: ExpansionData {
448 ..invoc.expansion_data.clone()
452 let fragment = invoc.fragment_kind
453 .expect_from_annotatables(::std::iter::once(item));
454 self.collect_invocations(fragment, &derive_placeholders)
458 if expanded_fragments.len() < depth {
459 expanded_fragments.push(Vec::new());
461 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
462 if !self.cx.ecfg.single_step {
463 invocations.extend(new_invocations.into_iter().rev());
467 self.cx.current_expansion = orig_expansion_data;
469 // Finally incorporate all the expanded macros into the input AST fragment.
470 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
471 while let Some(expanded_fragments) = expanded_fragments.pop() {
472 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
473 placeholder_expander.add(NodeId::placeholder_from_expn_id(expn_id),
477 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
478 fragment_with_placeholders
481 fn resolve_imports(&mut self) {
483 self.cx.resolver.resolve_imports();
487 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
488 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
489 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
490 /// prepares data for resolving paths of macro invocations.
491 fn collect_invocations(&mut self, mut fragment: AstFragment, extra_placeholders: &[NodeId])
492 -> (AstFragment, Vec<Invocation>) {
493 // Resolve `$crate`s in the fragment for pretty-printing.
494 self.cx.resolver.resolve_dollar_crates();
497 let mut collector = InvocationCollector {
498 cfg: StripUnconfigured {
499 sess: self.cx.parse_sess,
500 features: self.cx.ecfg.features,
503 invocations: Vec::new(),
504 monotonic: self.monotonic,
506 fragment.mut_visit_with(&mut collector);
507 fragment.add_placeholders(extra_placeholders);
508 collector.invocations
512 self.cx.resolver.visit_ast_fragment_with_placeholders(
513 self.cx.current_expansion.id, &fragment
517 (fragment, invocations)
520 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
521 let mut cfg = StripUnconfigured {
522 sess: self.cx.parse_sess,
523 features: self.cx.ecfg.features,
525 // Since the item itself has already been configured by the InvocationCollector,
526 // we know that fold result vector will contain exactly one element
528 Annotatable::Item(item) => {
529 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
531 Annotatable::TraitItem(item) => {
532 Annotatable::TraitItem(
533 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
535 Annotatable::ImplItem(item) => {
536 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
538 Annotatable::ForeignItem(item) => {
539 Annotatable::ForeignItem(
540 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
543 Annotatable::Stmt(stmt) => {
544 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
546 Annotatable::Expr(mut expr) => {
547 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
549 Annotatable::Arm(arm) => {
550 Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap())
552 Annotatable::Field(field) => {
553 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
555 Annotatable::FieldPat(fp) => {
556 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
558 Annotatable::GenericParam(param) => {
559 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
561 Annotatable::Param(param) => {
562 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
564 Annotatable::StructField(sf) => {
565 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
567 Annotatable::Variant(v) => {
568 Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap())
573 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
574 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
575 let expn_data = self.cx.current_expansion.id.expn_data();
576 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
577 let mut err = self.cx.struct_span_err(expn_data.call_site,
578 &format!("recursion limit reached while expanding the macro `{}`",
579 expn_data.kind.descr()));
581 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
584 self.cx.trace_macros_diag();
588 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
590 InvocationKind::Bang { mac, .. } => match ext {
591 SyntaxExtensionKind::Bang(expander) => {
592 self.gate_proc_macro_expansion_kind(span, fragment_kind);
593 let tok_result = expander.expand(self.cx, span, mac.stream());
594 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
596 SyntaxExtensionKind::LegacyBang(expander) => {
597 let prev = self.cx.current_expansion.prior_type_ascription;
598 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
599 let tok_result = expander.expand(self.cx, span, mac.stream());
600 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
604 "non-{kind} macro in {kind} position: {path}",
605 kind = fragment_kind.name(),
606 path = pprust::path_to_string(&mac.path),
608 self.cx.span_err(span, &msg);
609 self.cx.trace_macros_diag();
610 fragment_kind.dummy(span)
612 self.cx.current_expansion.prior_type_ascription = prev;
617 InvocationKind::Attr { attr, mut item, .. } => match ext {
618 SyntaxExtensionKind::Attr(expander) => {
619 self.gate_proc_macro_input(&item);
620 self.gate_proc_macro_attr_item(span, &item);
621 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
622 Annotatable::Item(item) => token::NtItem(item),
623 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
624 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
625 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
626 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
627 Annotatable::Expr(expr) => token::NtExpr(expr),
629 | Annotatable::Field(..)
630 | Annotatable::FieldPat(..)
631 | Annotatable::GenericParam(..)
632 | Annotatable::Param(..)
633 | Annotatable::StructField(..)
634 | Annotatable::Variant(..)
635 => panic!("unexpected annotatable"),
636 })), DUMMY_SP).into();
637 let item = attr.unwrap_normal_item();
638 let input = self.extract_proc_macro_attr_input(item.tokens, span);
639 let tok_result = expander.expand(self.cx, span, input, item_tok);
640 self.parse_ast_fragment(tok_result, fragment_kind, &item.path, span)
642 SyntaxExtensionKind::LegacyAttr(expander) => {
643 match attr.parse_meta(self.cx.parse_sess) {
645 let item = expander.expand(self.cx, span, &meta, item);
646 fragment_kind.expect_from_annotatables(item)
650 fragment_kind.dummy(span)
654 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
655 attr::mark_known(&attr);
657 attr::mark_used(&attr);
659 item.visit_attrs(|attrs| attrs.push(attr));
660 fragment_kind.expect_from_annotatables(iter::once(item))
664 InvocationKind::Derive { path, item } => match ext {
665 SyntaxExtensionKind::Derive(expander) |
666 SyntaxExtensionKind::LegacyDerive(expander) => {
667 if !item.derive_allowed() {
668 return fragment_kind.dummy(span);
670 if let SyntaxExtensionKind::Derive(..) = ext {
671 self.gate_proc_macro_input(&item);
673 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
674 let items = expander.expand(self.cx, span, &meta, item);
675 fragment_kind.expect_from_annotatables(items)
679 InvocationKind::DeriveContainer { .. } => unreachable!()
683 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
684 let mut trees = tokens.trees();
686 Some(TokenTree::Delimited(_, _, tts)) => {
687 if trees.next().is_none() {
691 Some(TokenTree::Token(..)) => {}
692 None => return TokenStream::default(),
694 self.cx.span_err(span, "custom attribute invocations must be \
695 of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
696 followed by a delimiter token");
697 TokenStream::default()
700 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
701 let kind = match item {
702 Annotatable::Item(item) => match &item.kind {
703 ItemKind::Mod(m) if m.inline => "modules",
706 Annotatable::TraitItem(_)
707 | Annotatable::ImplItem(_)
708 | Annotatable::ForeignItem(_) => return,
709 Annotatable::Stmt(_) => "statements",
710 Annotatable::Expr(_) => "expressions",
712 | Annotatable::Field(..)
713 | Annotatable::FieldPat(..)
714 | Annotatable::GenericParam(..)
715 | Annotatable::Param(..)
716 | Annotatable::StructField(..)
717 | Annotatable::Variant(..)
718 => panic!("unexpected annotatable"),
720 if self.cx.ecfg.proc_macro_hygiene() {
725 sym::proc_macro_hygiene,
728 &format!("custom attributes cannot be applied to {}", kind),
732 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
733 struct GateProcMacroInput<'a> {
734 parse_sess: &'a ParseSess,
737 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
738 fn visit_item(&mut self, item: &'ast ast::Item) {
740 ast::ItemKind::Mod(module) if !module.inline => {
743 sym::proc_macro_hygiene,
746 "non-inline modules in proc macro input are unstable",
752 visit::walk_item(self, item);
755 fn visit_mac(&mut self, _: &'ast ast::Mac) {}
758 if !self.cx.ecfg.proc_macro_hygiene() {
759 annotatable.visit_with(&mut GateProcMacroInput { parse_sess: self.cx.parse_sess });
763 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
764 let kind = match kind {
765 AstFragmentKind::Expr |
766 AstFragmentKind::OptExpr => "expressions",
767 AstFragmentKind::Pat => "patterns",
768 AstFragmentKind::Stmts => "statements",
769 AstFragmentKind::Ty |
770 AstFragmentKind::Items |
771 AstFragmentKind::TraitItems |
772 AstFragmentKind::ImplItems |
773 AstFragmentKind::ForeignItems => return,
774 AstFragmentKind::Arms
775 | AstFragmentKind::Fields
776 | AstFragmentKind::FieldPats
777 | AstFragmentKind::GenericParams
778 | AstFragmentKind::Params
779 | AstFragmentKind::StructFields
780 | AstFragmentKind::Variants
781 => panic!("unexpected AST fragment kind"),
783 if self.cx.ecfg.proc_macro_hygiene() {
788 sym::proc_macro_hygiene,
791 &format!("procedural macros cannot be expanded to {}", kind),
795 fn parse_ast_fragment(
798 kind: AstFragmentKind,
802 let mut parser = self.cx.new_parser_from_tts(toks);
803 match parse_ast_fragment(&mut parser, kind, false) {
805 ensure_complete_parse(&mut parser, path, kind.name(), span);
810 annotate_err_with_kind(&mut err, kind, span);
812 self.cx.trace_macros_diag();
819 pub fn parse_ast_fragment<'a>(
820 this: &mut Parser<'a>,
821 kind: AstFragmentKind,
822 macro_legacy_warnings: bool,
823 ) -> PResult<'a, AstFragment> {
825 AstFragmentKind::Items => {
826 let mut items = SmallVec::new();
827 while let Some(item) = this.parse_item()? {
830 AstFragment::Items(items)
832 AstFragmentKind::TraitItems => {
833 let mut items = SmallVec::new();
834 while this.token != token::Eof {
835 items.push(this.parse_trait_item(&mut false)?);
837 AstFragment::TraitItems(items)
839 AstFragmentKind::ImplItems => {
840 let mut items = SmallVec::new();
841 while this.token != token::Eof {
842 items.push(this.parse_impl_item(&mut false)?);
844 AstFragment::ImplItems(items)
846 AstFragmentKind::ForeignItems => {
847 let mut items = SmallVec::new();
848 while this.token != token::Eof {
849 items.push(this.parse_foreign_item(DUMMY_SP)?);
851 AstFragment::ForeignItems(items)
853 AstFragmentKind::Stmts => {
854 let mut stmts = SmallVec::new();
855 while this.token != token::Eof &&
856 // won't make progress on a `}`
857 this.token != token::CloseDelim(token::Brace) {
858 if let Some(stmt) = this.parse_full_stmt(macro_legacy_warnings)? {
862 AstFragment::Stmts(stmts)
864 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
865 AstFragmentKind::OptExpr => {
866 if this.token != token::Eof {
867 AstFragment::OptExpr(Some(this.parse_expr()?))
869 AstFragment::OptExpr(None)
872 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
873 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?),
874 AstFragmentKind::Arms
875 | AstFragmentKind::Fields
876 | AstFragmentKind::FieldPats
877 | AstFragmentKind::GenericParams
878 | AstFragmentKind::Params
879 | AstFragmentKind::StructFields
880 | AstFragmentKind::Variants
881 => panic!("unexpected AST fragment kind"),
885 pub fn ensure_complete_parse<'a>(
886 this: &mut Parser<'a>,
891 if this.token != token::Eof {
892 let msg = format!("macro expansion ignores token `{}` and any following",
893 this.this_token_to_string());
894 // Avoid emitting backtrace info twice.
895 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
896 let mut err = this.struct_span_err(def_site_span, &msg);
897 err.span_label(span, "caused by the macro expansion here");
899 "the usage of `{}!` is likely invalid in {} context",
900 pprust::path_to_string(macro_path),
904 let semi_span = this.sess.source_map().next_point(span);
906 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
907 match this.sess.source_map().span_to_snippet(semi_full_span) {
908 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
911 "you might be missing a semicolon here",
913 Applicability::MaybeIncorrect,
922 struct InvocationCollector<'a, 'b> {
923 cx: &'a mut ExtCtxt<'b>,
924 cfg: StripUnconfigured<'a>,
925 invocations: Vec<Invocation>,
929 impl<'a, 'b> InvocationCollector<'a, 'b> {
930 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
931 // Expansion data for all the collected invocations is set upon their resolution,
932 // with exception of the derive container case which is not resolved and can get
933 // its expansion data immediately.
934 let expn_data = match &kind {
935 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
936 parent: self.cx.current_expansion.id,
938 ExpnKind::Macro(MacroKind::Attr, sym::derive),
939 item.span(), self.cx.parse_sess.edition,
944 let expn_id = ExpnId::fresh(expn_data);
945 self.invocations.push(Invocation {
948 expansion_data: ExpansionData {
950 depth: self.cx.current_expansion.depth + 1,
951 ..self.cx.current_expansion.clone()
954 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
957 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
958 self.collect(kind, InvocationKind::Bang { mac, span })
961 fn collect_attr(&mut self,
962 attr: Option<ast::Attribute>,
965 kind: AstFragmentKind,
968 self.collect(kind, match attr {
969 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
970 None => InvocationKind::DeriveContainer { derives, item },
974 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
975 -> Option<ast::Attribute> {
976 let attr = attrs.iter()
978 if a.has_name(sym::derive) {
979 *after_derive = true;
981 !attr::is_known(a) && !is_builtin_attr(a)
983 .map(|i| attrs.remove(i));
984 if let Some(attr) = &attr {
985 if !self.cx.ecfg.custom_inner_attributes() &&
986 attr.style == ast::AttrStyle::Inner && !attr.has_name(sym::test) {
987 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
988 attr.span, GateIssue::Language,
989 "non-builtin inner attributes are unstable");
995 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
996 fn classify_item<T>(&mut self, item: &mut T)
997 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
1000 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
1002 item.visit_attrs(|mut attrs| {
1003 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1004 traits = collect_derives(&mut self.cx, &mut attrs);
1007 (attr, traits, after_derive)
1010 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1011 /// to the unused-attributes lint (making it an error on statements and expressions
1012 /// is a breaking change)
1013 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
1014 -> (Option<ast::Attribute>, /* after_derive */ bool) {
1015 let (mut attr, mut after_derive) = (None, false);
1017 nonitem.visit_attrs(|mut attrs| {
1018 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1021 (attr, after_derive)
1024 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1025 self.cfg.configure(node)
1028 // Detect use of feature-gated or invalid attributes on macro invocations
1029 // since they will not be detected after macro expansion.
1030 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1031 let features = self.cx.ecfg.features.unwrap();
1032 for attr in attrs.iter() {
1033 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1035 // macros are expanded before any lint passes so this warning has to be hardcoded
1036 if attr.has_name(sym::derive) {
1037 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1038 .note("this may become a hard error in a future release")
1045 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1046 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1047 self.cfg.configure_expr(expr);
1048 visit_clobber(expr.deref_mut(), |mut expr| {
1049 self.cfg.configure_expr_kind(&mut expr.kind);
1051 // ignore derives so they remain unused
1052 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1055 // Collect the invoc regardless of whether or not attributes are permitted here
1056 // expansion will eat the attribute so it won't error later.
1057 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1059 // AstFragmentKind::Expr requires the macro to emit an expression.
1060 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1061 AstFragmentKind::Expr, after_derive)
1066 if let ast::ExprKind::Mac(mac) = expr.kind {
1067 self.check_attributes(&expr.attrs);
1068 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1072 noop_visit_expr(&mut expr, self);
1078 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1079 let mut arm = configure!(self, arm);
1081 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1082 if attr.is_some() || !traits.is_empty() {
1083 return self.collect_attr(attr, traits, Annotatable::Arm(arm),
1084 AstFragmentKind::Arms, after_derive)
1088 noop_flat_map_arm(arm, self)
1091 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1092 let mut field = configure!(self, field);
1094 let (attr, traits, after_derive) = self.classify_item(&mut field);
1095 if attr.is_some() || !traits.is_empty() {
1096 return self.collect_attr(attr, traits, Annotatable::Field(field),
1097 AstFragmentKind::Fields, after_derive)
1101 noop_flat_map_field(field, self)
1104 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1105 let mut fp = configure!(self, fp);
1107 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1108 if attr.is_some() || !traits.is_empty() {
1109 return self.collect_attr(attr, traits, Annotatable::FieldPat(fp),
1110 AstFragmentKind::FieldPats, after_derive)
1111 .make_field_patterns();
1114 noop_flat_map_field_pattern(fp, self)
1117 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1118 let mut p = configure!(self, p);
1120 let (attr, traits, after_derive) = self.classify_item(&mut p);
1121 if attr.is_some() || !traits.is_empty() {
1122 return self.collect_attr(attr, traits, Annotatable::Param(p),
1123 AstFragmentKind::Params, after_derive)
1127 noop_flat_map_param(p, self)
1130 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1131 let mut sf = configure!(self, sf);
1133 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1134 if attr.is_some() || !traits.is_empty() {
1135 return self.collect_attr(attr, traits, Annotatable::StructField(sf),
1136 AstFragmentKind::StructFields, after_derive)
1137 .make_struct_fields();
1140 noop_flat_map_struct_field(sf, self)
1143 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1144 let mut variant = configure!(self, variant);
1146 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1147 if attr.is_some() || !traits.is_empty() {
1148 return self.collect_attr(attr, traits, Annotatable::Variant(variant),
1149 AstFragmentKind::Variants, after_derive)
1153 noop_flat_map_variant(variant, self)
1156 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1157 let expr = configure!(self, expr);
1158 expr.filter_map(|mut expr| {
1159 self.cfg.configure_expr_kind(&mut expr.kind);
1161 // Ignore derives so they remain unused.
1162 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1165 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1167 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1168 AstFragmentKind::OptExpr, after_derive)
1170 .map(|expr| expr.into_inner())
1173 if let ast::ExprKind::Mac(mac) = expr.kind {
1174 self.check_attributes(&expr.attrs);
1175 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1177 .map(|expr| expr.into_inner())
1179 Some({ noop_visit_expr(&mut expr, self); expr })
1184 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1185 self.cfg.configure_pat(pat);
1187 PatKind::Mac(_) => {}
1188 _ => return noop_visit_pat(pat, self),
1191 visit_clobber(pat, |mut pat| {
1192 match mem::replace(&mut pat.kind, PatKind::Wild) {
1193 PatKind::Mac(mac) =>
1194 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1195 _ => unreachable!(),
1200 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1201 let mut stmt = configure!(self, stmt);
1203 // we'll expand attributes on expressions separately
1204 if !stmt.is_expr() {
1205 let (attr, derives, after_derive) = if stmt.is_item() {
1206 self.classify_item(&mut stmt)
1208 // ignore derives on non-item statements so it falls through
1209 // to the unused-attributes lint
1210 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1211 (attr, vec![], after_derive)
1214 if attr.is_some() || !derives.is_empty() {
1215 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1216 AstFragmentKind::Stmts, after_derive).make_stmts();
1220 if let StmtKind::Mac(mac) = stmt.kind {
1221 let (mac, style, attrs) = mac.into_inner();
1222 self.check_attributes(&attrs);
1223 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1226 // If this is a macro invocation with a semicolon, then apply that
1227 // semicolon to the final statement produced by expansion.
1228 if style == MacStmtStyle::Semicolon {
1229 if let Some(stmt) = placeholder.pop() {
1230 placeholder.push(stmt.add_trailing_semicolon());
1237 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1238 let ast::Stmt { id, kind, span } = stmt;
1239 noop_flat_map_stmt_kind(kind, self).into_iter().map(|kind| {
1240 ast::Stmt { id, kind, span }
1245 fn visit_block(&mut self, block: &mut P<Block>) {
1246 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1247 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1248 noop_visit_block(block, self);
1249 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1252 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1253 let mut item = configure!(self, item);
1255 let (attr, traits, after_derive) = self.classify_item(&mut item);
1256 if attr.is_some() || !traits.is_empty() {
1257 return self.collect_attr(attr, traits, Annotatable::Item(item),
1258 AstFragmentKind::Items, after_derive).make_items();
1262 ast::ItemKind::Mac(..) => {
1263 self.check_attributes(&item.attrs);
1264 item.and_then(|item| match item.kind {
1265 ItemKind::Mac(mac) => self.collect(
1266 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1268 _ => unreachable!(),
1271 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1272 if item.ident == Ident::invalid() {
1273 return noop_flat_map_item(item, self);
1276 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1277 let mut module = (*self.cx.current_expansion.module).clone();
1278 module.mod_path.push(item.ident);
1280 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1281 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1282 // Thus, if `inner` is the dummy span, we know the module is inline.
1283 let inline_module = item.span.contains(inner) || inner.is_dummy();
1286 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1287 self.cx.current_expansion.directory_ownership =
1288 DirectoryOwnership::Owned { relative: None };
1289 module.directory.push(&*path.as_str());
1291 module.directory.push(&*item.ident.as_str());
1294 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1295 let mut path = match path {
1296 FileName::Real(path) => path,
1297 other => PathBuf::from(other.to_string()),
1299 let directory_ownership = match path.file_name().unwrap().to_str() {
1300 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1301 Some(_) => DirectoryOwnership::Owned {
1302 relative: Some(item.ident),
1304 None => DirectoryOwnership::UnownedViaMod(false),
1307 module.directory = path;
1308 self.cx.current_expansion.directory_ownership = directory_ownership;
1312 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1313 let result = noop_flat_map_item(item, self);
1314 self.cx.current_expansion.module = orig_module;
1315 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1319 _ => noop_flat_map_item(item, self),
1323 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1324 let mut item = configure!(self, item);
1326 let (attr, traits, after_derive) = self.classify_item(&mut item);
1327 if attr.is_some() || !traits.is_empty() {
1328 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1329 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1333 ast::TraitItemKind::Macro(mac) => {
1334 let ast::TraitItem { attrs, span, .. } = item;
1335 self.check_attributes(&attrs);
1336 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1338 _ => noop_flat_map_trait_item(item, self),
1342 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1343 let mut item = configure!(self, item);
1345 let (attr, traits, after_derive) = self.classify_item(&mut item);
1346 if attr.is_some() || !traits.is_empty() {
1347 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1348 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1352 ast::ImplItemKind::Macro(mac) => {
1353 let ast::ImplItem { attrs, span, .. } = item;
1354 self.check_attributes(&attrs);
1355 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1357 _ => noop_flat_map_impl_item(item, self),
1361 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1363 ast::TyKind::Mac(_) => {}
1364 _ => return noop_visit_ty(ty, self),
1367 visit_clobber(ty, |mut ty| {
1368 match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1369 ast::TyKind::Mac(mac) =>
1370 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1371 _ => unreachable!(),
1376 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1377 self.cfg.configure_foreign_mod(foreign_mod);
1378 noop_visit_foreign_mod(foreign_mod, self);
1381 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1382 -> SmallVec<[ast::ForeignItem; 1]>
1384 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1386 if attr.is_some() || !traits.is_empty() {
1387 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1388 AstFragmentKind::ForeignItems, after_derive)
1389 .make_foreign_items();
1392 if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind {
1393 self.check_attributes(&foreign_item.attrs);
1394 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1395 .make_foreign_items();
1398 noop_flat_map_foreign_item(foreign_item, self)
1401 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1403 ast::ItemKind::MacroDef(..) => {}
1405 self.cfg.configure_item_kind(item);
1406 noop_visit_item_kind(item, self);
1411 fn flat_map_generic_param(
1413 param: ast::GenericParam
1414 ) -> SmallVec<[ast::GenericParam; 1]>
1416 let mut param = configure!(self, param);
1418 let (attr, traits, after_derive) = self.classify_item(&mut param);
1419 if attr.is_some() || !traits.is_empty() {
1420 return self.collect_attr(attr, traits, Annotatable::GenericParam(param),
1421 AstFragmentKind::GenericParams, after_derive)
1422 .make_generic_params();
1425 noop_flat_map_generic_param(param, self)
1428 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1429 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1430 // contents="file contents")]` attributes
1431 if !at.check_name(sym::doc) {
1432 return noop_visit_attribute(at, self);
1435 if let Some(list) = at.meta_item_list() {
1436 if !list.iter().any(|it| it.check_name(sym::include)) {
1437 return noop_visit_attribute(at, self);
1440 let mut items = vec![];
1442 for mut it in list {
1443 if !it.check_name(sym::include) {
1444 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1448 if let Some(file) = it.value_str() {
1449 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1450 self.check_attributes(slice::from_ref(at));
1451 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1452 // avoid loading the file if they haven't enabled the feature
1453 return noop_visit_attribute(at, self);
1456 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1457 Ok(filename) => filename,
1464 match self.cx.source_map().load_file(&filename) {
1465 Ok(source_file) => {
1466 let src = source_file.src.as_ref()
1467 .expect("freshly loaded file should have a source");
1468 let src_interned = Symbol::intern(src.as_str());
1470 let include_info = vec![
1471 ast::NestedMetaItem::MetaItem(
1472 attr::mk_name_value_item_str(
1473 Ident::with_dummy_span(sym::file),
1478 ast::NestedMetaItem::MetaItem(
1479 attr::mk_name_value_item_str(
1480 Ident::with_dummy_span(sym::contents),
1487 let include_ident = Ident::with_dummy_span(sym::include);
1488 let item = attr::mk_list_item(include_ident, include_info);
1489 items.push(ast::NestedMetaItem::MetaItem(item));
1494 .and_then(|item| item.name_value_literal())
1497 if e.kind() == ErrorKind::InvalidData {
1501 &format!("{} wasn't a utf-8 file", filename.display()),
1503 .span_label(lit.span, "contains invalid utf-8")
1506 let mut err = self.cx.struct_span_err(
1508 &format!("couldn't read {}: {}", filename.display(), e),
1510 err.span_label(lit.span, "couldn't read file");
1517 let mut err = self.cx.struct_span_err(
1519 &format!("expected path to external documentation"),
1522 // Check if the user erroneously used `doc(include(...))` syntax.
1523 let literal = it.meta_item_list().and_then(|list| {
1524 if list.len() == 1 {
1525 list[0].literal().map(|literal| &literal.kind)
1531 let (path, applicability) = match &literal {
1532 Some(LitKind::Str(path, ..)) => {
1533 (path.to_string(), Applicability::MachineApplicable)
1535 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1538 err.span_suggestion(
1540 "provide a file path with `=`",
1541 format!("include = \"{}\"", path),
1549 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1550 *at = attr::Attribute {
1551 kind: ast::AttrKind::Normal(
1552 AttrItem { path: meta.path, tokens: meta.kind.tokens(meta.span) },
1559 noop_visit_attribute(at, self)
1563 fn visit_id(&mut self, id: &mut ast::NodeId) {
1565 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1566 *id = self.cx.resolver.next_node_id()
1570 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1571 self.cfg.configure_fn_decl(&mut fn_decl);
1572 noop_visit_fn_decl(fn_decl, self);
1576 pub struct ExpansionConfig<'feat> {
1577 pub crate_name: String,
1578 pub features: Option<&'feat Features>,
1579 pub recursion_limit: usize,
1580 pub trace_mac: bool,
1581 pub should_test: bool, // If false, strip `#[test]` nodes
1582 pub single_step: bool,
1583 pub keep_macs: bool,
1586 impl<'feat> ExpansionConfig<'feat> {
1587 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1591 recursion_limit: 1024,
1599 fn proc_macro_hygiene(&self) -> bool {
1600 self.features.map_or(false, |features| features.proc_macro_hygiene)
1602 fn custom_inner_attributes(&self) -> bool {
1603 self.features.map_or(false, |features| features.custom_inner_attributes)