2 use crate::config::StripUnconfigured;
4 use crate::hygiene::{ExpnData, ExpnId, ExpnKind, SyntaxContext};
5 use crate::mbe::macro_rules::annotate_err_with_kind;
6 use crate::module::{parse_external_mod, push_directory, Directory, DirectoryOwnership};
7 use crate::placeholders::{placeholder, PlaceholderExpander};
8 use crate::proc_macro::collect_derives;
10 use rustc_ast::ast::{self, AttrItem, Block, LitKind, NodeId, PatKind, Path};
11 use rustc_ast::ast::{ItemKind, MacArgs, MacStmtStyle, StmtKind};
12 use rustc_ast::mut_visit::*;
13 use rustc_ast::ptr::P;
15 use rustc_ast::tokenstream::TokenStream;
16 use rustc_ast::visit::{self, AssocCtxt, Visitor};
17 use rustc_ast_pretty::pprust;
18 use rustc_attr::{self as attr, is_builtin_attr, HasAttrs};
19 use rustc_data_structures::map_in_place::MapInPlace;
20 use rustc_errors::{Applicability, PResult};
21 use rustc_feature::Features;
22 use rustc_parse::parser::Parser;
23 use rustc_parse::validate_attr;
24 use rustc_session::lint::builtin::UNUSED_DOC_COMMENTS;
25 use rustc_session::lint::BuiltinLintDiagnostics;
26 use rustc_session::parse::{feature_err, ParseSess};
27 use rustc_span::source_map::respan;
28 use rustc_span::symbol::{sym, Ident, Symbol};
29 use rustc_span::{FileName, Span, DUMMY_SP};
31 use smallvec::{smallvec, SmallVec};
32 use std::io::ErrorKind;
33 use std::ops::DerefMut;
34 use std::path::PathBuf;
36 use std::{iter, mem, slice};
38 macro_rules! ast_fragments {
40 $($Kind:ident($AstTy:ty) {
42 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
43 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident($($args:tt)*);)?
47 /// A fragment of AST that can be produced by a single macro expansion.
48 /// Can also serve as an input and intermediate result for macro expansion operations.
49 pub enum AstFragment {
50 OptExpr(Option<P<ast::Expr>>),
54 /// "Discriminant" of an AST fragment.
55 #[derive(Copy, Clone, PartialEq, Eq)]
56 pub enum AstFragmentKind {
61 impl AstFragmentKind {
62 pub fn name(self) -> &'static str {
64 AstFragmentKind::OptExpr => "expression",
65 $(AstFragmentKind::$Kind => $kind_name,)*
69 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
71 AstFragmentKind::OptExpr =>
72 result.make_expr().map(Some).map(AstFragment::OptExpr),
73 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
79 pub fn add_placeholders(&mut self, placeholders: &[NodeId]) {
80 if placeholders.is_empty() {
84 $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
85 // We are repeating through arguments with `many`, to do that we have to
86 // mention some macro variable from those arguments even if it's not used.
87 macro _repeating($flat_map_ast_elt) {}
88 placeholder(AstFragmentKind::$Kind, *id, None).$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, $($args)*);
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<[P<ast::AssocItem>; 1]>) {
158 many fn flat_map_trait_item;
159 fn visit_assoc_item(AssocCtxt::Trait);
162 ImplItems(SmallVec<[P<ast::AssocItem>; 1]>) {
164 many fn flat_map_impl_item;
165 fn visit_assoc_item(AssocCtxt::Impl);
168 ForeignItems(SmallVec<[P<ast::ForeignItem>; 1]>) {
170 many fn flat_map_foreign_item;
171 fn visit_foreign_item();
172 fn make_foreign_items;
174 Arms(SmallVec<[ast::Arm; 1]>) {
175 "match arm"; many fn flat_map_arm; fn visit_arm(); fn make_arms;
177 Fields(SmallVec<[ast::Field; 1]>) {
178 "field expression"; many fn flat_map_field; fn visit_field(); fn make_fields;
180 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
182 many fn flat_map_field_pattern;
183 fn visit_field_pattern();
184 fn make_field_patterns;
186 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
188 many fn flat_map_generic_param;
189 fn visit_generic_param();
190 fn make_generic_params;
192 Params(SmallVec<[ast::Param; 1]>) {
193 "function parameter"; many fn flat_map_param; fn visit_param(); fn make_params;
195 StructFields(SmallVec<[ast::StructField; 1]>) {
197 many fn flat_map_struct_field;
198 fn visit_struct_field();
199 fn make_struct_fields;
201 Variants(SmallVec<[ast::Variant; 1]>) {
202 "variant"; many fn flat_map_variant; fn visit_variant(); fn make_variants;
206 impl AstFragmentKind {
207 crate fn dummy(self, span: Span) -> AstFragment {
208 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
211 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(
215 let mut items = items.into_iter();
217 AstFragmentKind::Arms => {
218 AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
220 AstFragmentKind::Fields => {
221 AstFragment::Fields(items.map(Annotatable::expect_field).collect())
223 AstFragmentKind::FieldPats => {
224 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect())
226 AstFragmentKind::GenericParams => {
227 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
229 AstFragmentKind::Params => {
230 AstFragment::Params(items.map(Annotatable::expect_param).collect())
232 AstFragmentKind::StructFields => {
233 AstFragment::StructFields(items.map(Annotatable::expect_struct_field).collect())
235 AstFragmentKind::Variants => {
236 AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
238 AstFragmentKind::Items => {
239 AstFragment::Items(items.map(Annotatable::expect_item).collect())
241 AstFragmentKind::ImplItems => {
242 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
244 AstFragmentKind::TraitItems => {
245 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
247 AstFragmentKind::ForeignItems => {
248 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
250 AstFragmentKind::Stmts => {
251 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
253 AstFragmentKind::Expr => AstFragment::Expr(
254 items.next().expect("expected exactly one expression").expect_expr(),
256 AstFragmentKind::OptExpr => {
257 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
259 AstFragmentKind::Pat | AstFragmentKind::Ty => {
260 panic!("patterns and types aren't annotatable")
266 pub struct Invocation {
267 pub kind: InvocationKind,
268 pub fragment_kind: AstFragmentKind,
269 pub expansion_data: ExpansionData,
272 pub enum InvocationKind {
278 attr: ast::Attribute,
280 // Required for resolving derive helper attributes.
282 // We temporarily report errors for attribute macros placed after derives
289 /// "Invocation" that contains all derives from an item,
290 /// broken into multiple `Derive` invocations when expanded.
291 /// FIXME: Find a way to remove it.
298 impl InvocationKind {
299 fn placeholder_visibility(&self) -> Option<ast::Visibility> {
300 // HACK: For unnamed fields placeholders should have the same visibility as the actual
301 // fields because for tuple structs/variants resolve determines visibilities of their
302 // constructor using these field visibilities before attributes on them are are expanded.
303 // The assumption is that the attribute expansion cannot change field visibilities,
304 // and it holds because only inert attributes are supported in this position.
306 InvocationKind::Attr { item: Annotatable::StructField(field), .. }
307 | InvocationKind::Derive { item: Annotatable::StructField(field), .. }
308 | InvocationKind::DeriveContainer { item: Annotatable::StructField(field), .. }
309 if field.ident.is_none() =>
311 Some(field.vis.clone())
319 pub fn span(&self) -> Span {
321 InvocationKind::Bang { span, .. } => *span,
322 InvocationKind::Attr { attr, .. } => attr.span,
323 InvocationKind::Derive { path, .. } => path.span,
324 InvocationKind::DeriveContainer { item, .. } => item.span(),
329 pub struct MacroExpander<'a, 'b> {
330 pub cx: &'a mut ExtCtxt<'b>,
331 monotonic: bool, // cf. `cx.monotonic_expander()`
334 impl<'a, 'b> MacroExpander<'a, 'b> {
335 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
336 MacroExpander { cx, monotonic }
339 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
340 let mut module = ModuleData {
341 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
342 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
343 FileName::Real(path) => path,
344 other => PathBuf::from(other.to_string()),
347 module.directory.pop();
348 self.cx.root_path = module.directory.clone();
349 self.cx.current_expansion.module = Rc::new(module);
351 let orig_mod_span = krate.module.inner;
353 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
356 kind: ast::ItemKind::Mod(krate.module),
357 ident: Ident::invalid(),
358 id: ast::DUMMY_NODE_ID,
359 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
363 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
364 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
366 krate.module = module;
369 // Resolution failed so we return an empty expansion
370 krate.attrs = vec![];
371 krate.module = ast::Mod { inner: orig_mod_span, items: vec![], inline: true };
373 Some(ast::Item { span, kind, .. }) => {
374 krate.attrs = vec![];
375 krate.module = ast::Mod { inner: orig_mod_span, items: vec![], inline: true };
379 "expected crate top-level item to be a module after macro expansion, found {} {}",
380 kind.article(), kind.descr()
385 self.cx.trace_macros_diag();
389 // Recursively expand all macro invocations in this AST fragment.
390 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
391 let orig_expansion_data = self.cx.current_expansion.clone();
392 self.cx.current_expansion.depth = 0;
394 // Collect all macro invocations and replace them with placeholders.
395 let (mut fragment_with_placeholders, mut invocations) =
396 self.collect_invocations(input_fragment, &[]);
398 // Optimization: if we resolve all imports now,
399 // we'll be able to immediately resolve most of imported macros.
400 self.resolve_imports();
402 // Resolve paths in all invocations and produce output expanded fragments for them, but
403 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
404 // The output fragments also go through expansion recursively until no invocations are left.
405 // Unresolved macros produce dummy outputs as a recovery measure.
406 invocations.reverse();
407 let mut expanded_fragments = Vec::new();
408 let mut undetermined_invocations = Vec::new();
409 let (mut progress, mut force) = (false, !self.monotonic);
411 let (invoc, res) = if let Some(invoc) = invocations.pop() {
414 self.resolve_imports();
415 if undetermined_invocations.is_empty() {
418 invocations = mem::take(&mut undetermined_invocations);
419 force = !mem::replace(&mut progress, false);
423 let res = match res {
426 let eager_expansion_root = if self.monotonic {
427 invoc.expansion_data.id
429 orig_expansion_data.id
431 match self.cx.resolver.resolve_macro_invocation(
433 eager_expansion_root,
437 Err(Indeterminate) => {
438 // Cannot resolve, will retry this invocation later.
439 undetermined_invocations.push((invoc, None));
446 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
447 self.cx.current_expansion = invoc.expansion_data.clone();
449 // FIXME(jseyfried): Refactor out the following logic
450 let (expanded_fragment, new_invocations) = match res {
451 InvocationRes::Single(ext) => match self.expand_invoc(invoc, &ext.kind) {
452 ExpandResult::Ready(fragment) => self.collect_invocations(fragment, &[]),
453 ExpandResult::Retry(invoc, explanation) => {
455 // We are stuck, stop retrying and produce a dummy fragment.
456 let span = invoc.span();
457 self.cx.span_err(span, &explanation);
458 let fragment = invoc.fragment_kind.dummy(span);
459 self.collect_invocations(fragment, &[])
461 // Cannot expand, will retry this invocation later.
462 undetermined_invocations
463 .push((invoc, Some(InvocationRes::Single(ext))));
468 InvocationRes::DeriveContainer(_exts) => {
469 // FIXME: Consider using the derive resolutions (`_exts`) immediately,
470 // instead of enqueuing the derives to be resolved again later.
471 let (derives, item) = match invoc.kind {
472 InvocationKind::DeriveContainer { derives, item } => (derives, item),
475 if !item.derive_allowed() {
476 self.error_derive_forbidden_on_non_adt(&derives, &item);
479 let mut item = self.fully_configure(item);
480 item.visit_attrs(|attrs| attrs.retain(|a| !a.has_name(sym::derive)));
482 let mut derive_placeholders = Vec::with_capacity(derives.len());
483 invocations.reserve(derives.len());
484 for path in derives {
485 let expn_id = ExpnId::fresh(None);
486 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
489 kind: InvocationKind::Derive { path, item: item.clone() },
490 fragment_kind: invoc.fragment_kind,
491 expansion_data: ExpansionData {
493 ..invoc.expansion_data.clone()
500 invoc.fragment_kind.expect_from_annotatables(::std::iter::once(item));
501 self.collect_invocations(fragment, &derive_placeholders)
506 if expanded_fragments.len() < depth {
507 expanded_fragments.push(Vec::new());
509 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
510 invocations.extend(new_invocations.into_iter().rev());
513 self.cx.current_expansion = orig_expansion_data;
515 // Finally incorporate all the expanded macros into the input AST fragment.
516 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
517 while let Some(expanded_fragments) = expanded_fragments.pop() {
518 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
520 .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
523 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
524 fragment_with_placeholders
527 fn error_derive_forbidden_on_non_adt(&self, derives: &[Path], item: &Annotatable) {
528 let attr = attr::find_by_name(item.attrs(), sym::derive);
529 let span = attr.map_or(item.span(), |attr| attr.span);
532 .struct_span_err(span, "`derive` may only be applied to structs, enums and unions");
533 if let Some(ast::Attribute { style: ast::AttrStyle::Inner, .. }) = attr {
534 let trait_list = derives.iter().map(|t| pprust::path_to_string(t)).collect::<Vec<_>>();
535 let suggestion = format!("#[derive({})]", trait_list.join(", "));
538 "try an outer attribute",
540 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
541 Applicability::MaybeIncorrect,
547 fn resolve_imports(&mut self) {
549 self.cx.resolver.resolve_imports();
553 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
554 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
555 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
556 /// prepares data for resolving paths of macro invocations.
557 fn collect_invocations(
559 mut fragment: AstFragment,
560 extra_placeholders: &[NodeId],
561 ) -> (AstFragment, Vec<(Invocation, Option<InvocationRes>)>) {
562 // Resolve `$crate`s in the fragment for pretty-printing.
563 self.cx.resolver.resolve_dollar_crates();
566 let mut collector = InvocationCollector {
567 cfg: StripUnconfigured {
568 sess: self.cx.parse_sess,
569 features: self.cx.ecfg.features,
572 invocations: Vec::new(),
573 monotonic: self.monotonic,
575 fragment.mut_visit_with(&mut collector);
576 fragment.add_placeholders(extra_placeholders);
577 collector.invocations
583 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
586 (fragment, invocations)
589 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
591 StripUnconfigured { sess: self.cx.parse_sess, features: self.cx.ecfg.features };
592 // Since the item itself has already been configured by the InvocationCollector,
593 // we know that fold result vector will contain exactly one element
595 Annotatable::Item(item) => Annotatable::Item(cfg.flat_map_item(item).pop().unwrap()),
596 Annotatable::TraitItem(item) => {
597 Annotatable::TraitItem(cfg.flat_map_trait_item(item).pop().unwrap())
599 Annotatable::ImplItem(item) => {
600 Annotatable::ImplItem(cfg.flat_map_impl_item(item).pop().unwrap())
602 Annotatable::ForeignItem(item) => {
603 Annotatable::ForeignItem(cfg.flat_map_foreign_item(item).pop().unwrap())
605 Annotatable::Stmt(stmt) => {
606 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
608 Annotatable::Expr(mut expr) => Annotatable::Expr({
609 cfg.visit_expr(&mut expr);
612 Annotatable::Arm(arm) => Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap()),
613 Annotatable::Field(field) => {
614 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
616 Annotatable::FieldPat(fp) => {
617 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
619 Annotatable::GenericParam(param) => {
620 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
622 Annotatable::Param(param) => {
623 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
625 Annotatable::StructField(sf) => {
626 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
628 Annotatable::Variant(v) => Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap()),
632 fn error_recursion_limit_reached(&mut self) {
633 let expn_data = self.cx.current_expansion.id.expn_data();
634 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
638 &format!("recursion limit reached while expanding `{}`", expn_data.kind.descr()),
641 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
642 suggested_limit, self.cx.ecfg.crate_name,
645 self.cx.trace_macros_diag();
648 /// A macro's expansion does not fit in this fragment kind.
649 /// For example, a non-type macro in a type position.
650 fn error_wrong_fragment_kind(&mut self, kind: AstFragmentKind, mac: &ast::MacCall, span: Span) {
652 "non-{kind} macro in {kind} position: {path}",
654 path = pprust::path_to_string(&mac.path),
656 self.cx.span_err(span, &msg);
657 self.cx.trace_macros_diag();
663 ext: &SyntaxExtensionKind,
664 ) -> ExpandResult<AstFragment, Invocation> {
665 let recursion_limit =
666 self.cx.reduced_recursion_limit.unwrap_or(self.cx.ecfg.recursion_limit);
667 if self.cx.current_expansion.depth > recursion_limit {
668 if self.cx.reduced_recursion_limit.is_none() {
669 self.error_recursion_limit_reached();
672 // Reduce the recursion limit by half each time it triggers.
673 self.cx.reduced_recursion_limit = Some(recursion_limit / 2);
675 return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span()));
678 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
679 ExpandResult::Ready(match invoc.kind {
680 InvocationKind::Bang { mac, .. } => match ext {
681 SyntaxExtensionKind::Bang(expander) => {
682 let tok_result = match expander.expand(self.cx, span, mac.args.inner_tokens()) {
683 Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)),
686 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
688 SyntaxExtensionKind::LegacyBang(expander) => {
689 let prev = self.cx.current_expansion.prior_type_ascription;
690 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
691 let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
692 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
695 self.error_wrong_fragment_kind(fragment_kind, &mac, span);
696 fragment_kind.dummy(span)
698 self.cx.current_expansion.prior_type_ascription = prev;
703 InvocationKind::Attr { attr, mut item, derives, after_derive } => match ext {
704 SyntaxExtensionKind::Attr(expander) => {
705 self.gate_proc_macro_input(&item);
706 self.gate_proc_macro_attr_item(span, &item);
707 let tokens = item.into_tokens();
708 let attr_item = attr.unwrap_normal_item();
709 if let MacArgs::Eq(..) = attr_item.args {
710 self.cx.span_err(span, "key-value macro attributes are not supported");
712 let inner_tokens = attr_item.args.inner_tokens();
713 let tok_result = match expander.expand(self.cx, span, inner_tokens, tokens) {
714 Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)),
717 self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span)
719 SyntaxExtensionKind::LegacyAttr(expander) => {
720 match validate_attr::parse_meta(self.cx.parse_sess, &attr) {
722 let items = match expander.expand(self.cx, span, &meta, item) {
723 ExpandResult::Ready(items) => items,
724 ExpandResult::Retry(item, explanation) => {
725 // Reassemble the original invocation for retrying.
726 return ExpandResult::Retry(
728 kind: InvocationKind::Attr {
740 fragment_kind.expect_from_annotatables(items)
744 fragment_kind.dummy(span)
748 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
749 attr::mark_known(&attr);
751 attr::mark_used(&attr);
753 item.visit_attrs(|attrs| attrs.push(attr));
754 fragment_kind.expect_from_annotatables(iter::once(item))
758 InvocationKind::Derive { path, item } => match ext {
759 SyntaxExtensionKind::Derive(expander)
760 | SyntaxExtensionKind::LegacyDerive(expander) => {
761 if !item.derive_allowed() {
762 return ExpandResult::Ready(fragment_kind.dummy(span));
764 if let SyntaxExtensionKind::Derive(..) = ext {
765 self.gate_proc_macro_input(&item);
767 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
768 let items = match expander.expand(self.cx, span, &meta, item) {
769 ExpandResult::Ready(items) => items,
770 ExpandResult::Retry(item, explanation) => {
771 // Reassemble the original invocation for retrying.
772 return ExpandResult::Retry(
774 kind: InvocationKind::Derive { path: meta.path, item },
781 fragment_kind.expect_from_annotatables(items)
785 InvocationKind::DeriveContainer { .. } => unreachable!(),
789 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
790 let kind = match item {
792 | Annotatable::TraitItem(_)
793 | Annotatable::ImplItem(_)
794 | Annotatable::ForeignItem(_) => return,
795 Annotatable::Stmt(_) => "statements",
796 Annotatable::Expr(_) => "expressions",
798 | Annotatable::Field(..)
799 | Annotatable::FieldPat(..)
800 | Annotatable::GenericParam(..)
801 | Annotatable::Param(..)
802 | Annotatable::StructField(..)
803 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
805 if self.cx.ecfg.proc_macro_hygiene() {
810 sym::proc_macro_hygiene,
812 &format!("custom attributes cannot be applied to {}", kind),
817 fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
818 struct GateProcMacroInput<'a> {
819 parse_sess: &'a ParseSess,
822 impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
823 fn visit_item(&mut self, item: &'ast ast::Item) {
825 ast::ItemKind::Mod(module) if !module.inline => {
828 sym::proc_macro_hygiene,
830 "non-inline modules in proc macro input are unstable",
837 visit::walk_item(self, item);
840 fn visit_mac(&mut self, _: &'ast ast::MacCall) {}
843 if !self.cx.ecfg.proc_macro_hygiene() {
844 annotatable.visit_with(&mut GateProcMacroInput { parse_sess: self.cx.parse_sess });
848 fn parse_ast_fragment(
851 kind: AstFragmentKind,
855 let mut parser = self.cx.new_parser_from_tts(toks);
856 match parse_ast_fragment(&mut parser, kind) {
858 ensure_complete_parse(&mut parser, path, kind.name(), span);
863 annotate_err_with_kind(&mut err, kind, span);
865 self.cx.trace_macros_diag();
872 pub fn parse_ast_fragment<'a>(
873 this: &mut Parser<'a>,
874 kind: AstFragmentKind,
875 ) -> PResult<'a, AstFragment> {
877 AstFragmentKind::Items => {
878 let mut items = SmallVec::new();
879 while let Some(item) = this.parse_item()? {
882 AstFragment::Items(items)
884 AstFragmentKind::TraitItems => {
885 let mut items = SmallVec::new();
886 while let Some(item) = this.parse_trait_item()? {
889 AstFragment::TraitItems(items)
891 AstFragmentKind::ImplItems => {
892 let mut items = SmallVec::new();
893 while let Some(item) = this.parse_impl_item()? {
896 AstFragment::ImplItems(items)
898 AstFragmentKind::ForeignItems => {
899 let mut items = SmallVec::new();
900 while let Some(item) = this.parse_foreign_item()? {
903 AstFragment::ForeignItems(items)
905 AstFragmentKind::Stmts => {
906 let mut stmts = SmallVec::new();
907 // Won't make progress on a `}`.
908 while this.token != token::Eof && this.token != token::CloseDelim(token::Brace) {
909 if let Some(stmt) = this.parse_full_stmt()? {
913 AstFragment::Stmts(stmts)
915 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
916 AstFragmentKind::OptExpr => {
917 if this.token != token::Eof {
918 AstFragment::OptExpr(Some(this.parse_expr()?))
920 AstFragment::OptExpr(None)
923 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
924 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?),
925 AstFragmentKind::Arms
926 | AstFragmentKind::Fields
927 | AstFragmentKind::FieldPats
928 | AstFragmentKind::GenericParams
929 | AstFragmentKind::Params
930 | AstFragmentKind::StructFields
931 | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
935 pub fn ensure_complete_parse<'a>(
936 this: &mut Parser<'a>,
941 if this.token != token::Eof {
942 let token = pprust::token_to_string(&this.token);
943 let msg = format!("macro expansion ignores token `{}` and any following", token);
944 // Avoid emitting backtrace info twice.
945 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
946 let mut err = this.struct_span_err(def_site_span, &msg);
947 err.span_label(span, "caused by the macro expansion here");
949 "the usage of `{}!` is likely invalid in {} context",
950 pprust::path_to_string(macro_path),
954 let semi_span = this.sess.source_map().next_point(span);
956 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
957 match this.sess.source_map().span_to_snippet(semi_full_span) {
958 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
961 "you might be missing a semicolon here",
963 Applicability::MaybeIncorrect,
972 struct InvocationCollector<'a, 'b> {
973 cx: &'a mut ExtCtxt<'b>,
974 cfg: StripUnconfigured<'a>,
975 invocations: Vec<(Invocation, Option<InvocationRes>)>,
979 impl<'a, 'b> InvocationCollector<'a, 'b> {
980 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
981 // Expansion data for all the collected invocations is set upon their resolution,
982 // with exception of the derive container case which is not resolved and can get
983 // its expansion data immediately.
984 let expn_data = match &kind {
985 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
986 parent: self.cx.current_expansion.id,
988 ExpnKind::Macro(MacroKind::Attr, sym::derive),
990 self.cx.parse_sess.edition,
996 let expn_id = ExpnId::fresh(expn_data);
997 let vis = kind.placeholder_visibility();
998 self.invocations.push((
1002 expansion_data: ExpansionData {
1004 depth: self.cx.current_expansion.depth + 1,
1005 ..self.cx.current_expansion.clone()
1010 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
1017 kind: AstFragmentKind,
1019 self.collect(kind, InvocationKind::Bang { mac, span })
1024 attr: Option<ast::Attribute>,
1027 kind: AstFragmentKind,
1033 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
1034 None => InvocationKind::DeriveContainer { derives, item },
1041 attrs: &mut Vec<ast::Attribute>,
1042 after_derive: &mut bool,
1043 ) -> Option<ast::Attribute> {
1047 if a.has_name(sym::derive) {
1048 *after_derive = true;
1050 !attr::is_known(a) && !is_builtin_attr(a)
1052 .map(|i| attrs.remove(i));
1053 if let Some(attr) = &attr {
1054 if !self.cx.ecfg.custom_inner_attributes()
1055 && attr.style == ast::AttrStyle::Inner
1056 && !attr.has_name(sym::test)
1059 &self.cx.parse_sess,
1060 sym::custom_inner_attributes,
1062 "non-builtin inner attributes are unstable",
1070 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
1073 item: &mut impl HasAttrs,
1074 ) -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool) {
1075 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
1077 item.visit_attrs(|mut attrs| {
1078 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1079 traits = collect_derives(&mut self.cx, &mut attrs);
1082 (attr, traits, after_derive)
1085 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1086 /// to the unused-attributes lint (making it an error on statements and expressions
1087 /// is a breaking change)
1088 fn classify_nonitem(
1090 nonitem: &mut impl HasAttrs,
1091 ) -> (Option<ast::Attribute>, /* after_derive */ bool) {
1092 let (mut attr, mut after_derive) = (None, false);
1094 nonitem.visit_attrs(|mut attrs| {
1095 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1098 (attr, after_derive)
1101 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1102 self.cfg.configure(node)
1105 // Detect use of feature-gated or invalid attributes on macro invocations
1106 // since they will not be detected after macro expansion.
1107 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1108 let features = self.cx.ecfg.features.unwrap();
1109 for attr in attrs.iter() {
1110 rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1111 validate_attr::check_meta(self.cx.parse_sess, attr);
1113 // macros are expanded before any lint passes so this warning has to be hardcoded
1114 if attr.has_name(sym::derive) {
1118 .struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1119 .note("this may become a hard error in a future release")
1123 if attr.doc_str().is_some() {
1124 self.cx.parse_sess.buffer_lint_with_diagnostic(
1125 &UNUSED_DOC_COMMENTS,
1128 "unused doc comment",
1129 BuiltinLintDiagnostics::UnusedDocComment(attr.span),
1136 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1137 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1138 self.cfg.configure_expr(expr);
1139 visit_clobber(expr.deref_mut(), |mut expr| {
1140 self.cfg.configure_expr_kind(&mut expr.kind);
1142 // ignore derives so they remain unused
1143 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1145 if let Some(ref attr_value) = attr {
1146 // Collect the invoc regardless of whether or not attributes are permitted here
1147 // expansion will eat the attribute so it won't error later.
1148 self.cfg.maybe_emit_expr_attr_err(attr_value);
1150 // AstFragmentKind::Expr requires the macro to emit an expression.
1155 Annotatable::Expr(P(expr)),
1156 AstFragmentKind::Expr,
1163 if let ast::ExprKind::MacCall(mac) = expr.kind {
1164 self.check_attributes(&expr.attrs);
1165 self.collect_bang(mac, expr.span, AstFragmentKind::Expr).make_expr().into_inner()
1167 noop_visit_expr(&mut expr, self);
1173 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1174 let mut arm = configure!(self, arm);
1176 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1177 if attr.is_some() || !traits.is_empty() {
1182 Annotatable::Arm(arm),
1183 AstFragmentKind::Arms,
1189 noop_flat_map_arm(arm, self)
1192 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1193 let mut field = configure!(self, field);
1195 let (attr, traits, after_derive) = self.classify_item(&mut field);
1196 if attr.is_some() || !traits.is_empty() {
1201 Annotatable::Field(field),
1202 AstFragmentKind::Fields,
1208 noop_flat_map_field(field, self)
1211 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1212 let mut fp = configure!(self, fp);
1214 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1215 if attr.is_some() || !traits.is_empty() {
1220 Annotatable::FieldPat(fp),
1221 AstFragmentKind::FieldPats,
1224 .make_field_patterns();
1227 noop_flat_map_field_pattern(fp, self)
1230 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1231 let mut p = configure!(self, p);
1233 let (attr, traits, after_derive) = self.classify_item(&mut p);
1234 if attr.is_some() || !traits.is_empty() {
1239 Annotatable::Param(p),
1240 AstFragmentKind::Params,
1246 noop_flat_map_param(p, self)
1249 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1250 let mut sf = configure!(self, sf);
1252 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1253 if attr.is_some() || !traits.is_empty() {
1258 Annotatable::StructField(sf),
1259 AstFragmentKind::StructFields,
1262 .make_struct_fields();
1265 noop_flat_map_struct_field(sf, self)
1268 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1269 let mut variant = configure!(self, variant);
1271 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1272 if attr.is_some() || !traits.is_empty() {
1277 Annotatable::Variant(variant),
1278 AstFragmentKind::Variants,
1284 noop_flat_map_variant(variant, self)
1287 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1288 let expr = configure!(self, expr);
1289 expr.filter_map(|mut expr| {
1290 self.cfg.configure_expr_kind(&mut expr.kind);
1292 // Ignore derives so they remain unused.
1293 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1295 if let Some(ref attr_value) = attr {
1296 self.cfg.maybe_emit_expr_attr_err(attr_value);
1302 Annotatable::Expr(P(expr)),
1303 AstFragmentKind::OptExpr,
1307 .map(|expr| expr.into_inner());
1310 if let ast::ExprKind::MacCall(mac) = expr.kind {
1311 self.check_attributes(&expr.attrs);
1312 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1314 .map(|expr| expr.into_inner())
1317 noop_visit_expr(&mut expr, self);
1324 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1325 self.cfg.configure_pat(pat);
1327 PatKind::MacCall(_) => {}
1328 _ => return noop_visit_pat(pat, self),
1331 visit_clobber(pat, |mut pat| match mem::replace(&mut pat.kind, PatKind::Wild) {
1332 PatKind::MacCall(mac) => {
1333 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat()
1335 _ => unreachable!(),
1339 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1340 let mut stmt = configure!(self, stmt);
1342 // we'll expand attributes on expressions separately
1343 if !stmt.is_expr() {
1344 let (attr, derives, after_derive) = if stmt.is_item() {
1345 self.classify_item(&mut stmt)
1347 // ignore derives on non-item statements so it falls through
1348 // to the unused-attributes lint
1349 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1350 (attr, vec![], after_derive)
1353 if attr.is_some() || !derives.is_empty() {
1358 Annotatable::Stmt(P(stmt)),
1359 AstFragmentKind::Stmts,
1366 if let StmtKind::MacCall(mac) = stmt.kind {
1367 let (mac, style, attrs) = mac.into_inner();
1368 self.check_attributes(&attrs);
1369 let mut placeholder =
1370 self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts).make_stmts();
1372 // If this is a macro invocation with a semicolon, then apply that
1373 // semicolon to the final statement produced by expansion.
1374 if style == MacStmtStyle::Semicolon {
1375 if let Some(stmt) = placeholder.pop() {
1376 placeholder.push(stmt.add_trailing_semicolon());
1383 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1384 let ast::Stmt { id, kind, span } = stmt;
1385 noop_flat_map_stmt_kind(kind, self)
1387 .map(|kind| ast::Stmt { id, kind, span })
1391 fn visit_block(&mut self, block: &mut P<Block>) {
1392 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1393 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1394 noop_visit_block(block, self);
1395 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1398 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1399 let mut item = configure!(self, item);
1401 let (attr, traits, after_derive) = self.classify_item(&mut item);
1402 if attr.is_some() || !traits.is_empty() {
1407 Annotatable::Item(item),
1408 AstFragmentKind::Items,
1414 let mut attrs = mem::take(&mut item.attrs); // We do this to please borrowck.
1415 let ident = item.ident;
1416 let span = item.span;
1419 ast::ItemKind::MacCall(..) => {
1421 self.check_attributes(&item.attrs);
1422 item.and_then(|item| match item.kind {
1423 ItemKind::MacCall(mac) => self
1424 .collect(AstFragmentKind::Items, InvocationKind::Bang { mac, span })
1426 _ => unreachable!(),
1429 ast::ItemKind::Mod(ref mut old_mod @ ast::Mod { .. }) if ident != Ident::invalid() => {
1430 let sess = self.cx.parse_sess;
1431 let orig_ownership = self.cx.current_expansion.directory_ownership;
1432 let mut module = (*self.cx.current_expansion.module).clone();
1434 let pushed = &mut false; // Record `parse_external_mod` pushing so we can pop.
1435 let dir = Directory { ownership: orig_ownership, path: module.directory };
1436 let Directory { ownership, path } = if old_mod.inline {
1437 // Inline `mod foo { ... }`, but we still need to push directories.
1439 push_directory(ident, &item.attrs, dir)
1441 // We have an outline `mod foo;` so we need to parse the file.
1442 let (new_mod, dir) =
1443 parse_external_mod(sess, ident, span, dir, &mut attrs, pushed);
1445 let krate = ast::Crate {
1446 span: new_mod.inner,
1449 proc_macros: vec![],
1451 if let Some(extern_mod_loaded) = self.cx.extern_mod_loaded {
1452 extern_mod_loaded(&krate);
1455 *old_mod = krate.module;
1456 item.attrs = krate.attrs;
1457 // File can have inline attributes, e.g., `#![cfg(...)]` & co. => Reconfigure.
1458 item = match self.configure(item) {
1462 sess.included_mod_stack.borrow_mut().pop();
1464 return Default::default();
1470 // Set the module info before we flat map.
1471 self.cx.current_expansion.directory_ownership = ownership;
1472 module.directory = path;
1473 module.mod_path.push(ident);
1475 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1477 let result = noop_flat_map_item(item, self);
1479 // Restore the module info.
1480 self.cx.current_expansion.module = orig_module;
1481 self.cx.current_expansion.directory_ownership = orig_ownership;
1483 sess.included_mod_stack.borrow_mut().pop();
1489 noop_flat_map_item(item, self)
1494 fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1495 let mut item = configure!(self, item);
1497 let (attr, traits, after_derive) = self.classify_item(&mut item);
1498 if attr.is_some() || !traits.is_empty() {
1503 Annotatable::TraitItem(item),
1504 AstFragmentKind::TraitItems,
1507 .make_trait_items();
1511 ast::AssocItemKind::MacCall(..) => {
1512 self.check_attributes(&item.attrs);
1513 item.and_then(|item| match item.kind {
1514 ast::AssocItemKind::MacCall(mac) => self
1515 .collect_bang(mac, item.span, AstFragmentKind::TraitItems)
1516 .make_trait_items(),
1517 _ => unreachable!(),
1520 _ => noop_flat_map_assoc_item(item, self),
1524 fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1525 let mut item = configure!(self, item);
1527 let (attr, traits, after_derive) = self.classify_item(&mut item);
1528 if attr.is_some() || !traits.is_empty() {
1533 Annotatable::ImplItem(item),
1534 AstFragmentKind::ImplItems,
1541 ast::AssocItemKind::MacCall(..) => {
1542 self.check_attributes(&item.attrs);
1543 item.and_then(|item| match item.kind {
1544 ast::AssocItemKind::MacCall(mac) => self
1545 .collect_bang(mac, item.span, AstFragmentKind::ImplItems)
1547 _ => unreachable!(),
1550 _ => noop_flat_map_assoc_item(item, self),
1554 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1556 ast::TyKind::MacCall(_) => {}
1557 _ => return noop_visit_ty(ty, self),
1560 visit_clobber(ty, |mut ty| match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1561 ast::TyKind::MacCall(mac) => {
1562 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty()
1564 _ => unreachable!(),
1568 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1569 self.cfg.configure_foreign_mod(foreign_mod);
1570 noop_visit_foreign_mod(foreign_mod, self);
1573 fn flat_map_foreign_item(
1575 mut foreign_item: P<ast::ForeignItem>,
1576 ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
1577 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1579 if attr.is_some() || !traits.is_empty() {
1584 Annotatable::ForeignItem(foreign_item),
1585 AstFragmentKind::ForeignItems,
1588 .make_foreign_items();
1591 match foreign_item.kind {
1592 ast::ForeignItemKind::MacCall(..) => {
1593 self.check_attributes(&foreign_item.attrs);
1594 foreign_item.and_then(|item| match item.kind {
1595 ast::ForeignItemKind::MacCall(mac) => self
1596 .collect_bang(mac, item.span, AstFragmentKind::ForeignItems)
1597 .make_foreign_items(),
1598 _ => unreachable!(),
1601 _ => noop_flat_map_foreign_item(foreign_item, self),
1605 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1607 ast::ItemKind::MacroDef(..) => {}
1609 self.cfg.configure_item_kind(item);
1610 noop_visit_item_kind(item, self);
1615 fn flat_map_generic_param(
1617 param: ast::GenericParam,
1618 ) -> SmallVec<[ast::GenericParam; 1]> {
1619 let mut param = configure!(self, param);
1621 let (attr, traits, after_derive) = self.classify_item(&mut param);
1622 if attr.is_some() || !traits.is_empty() {
1627 Annotatable::GenericParam(param),
1628 AstFragmentKind::GenericParams,
1631 .make_generic_params();
1634 noop_flat_map_generic_param(param, self)
1637 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1638 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1639 // contents="file contents")]` attributes
1640 if !at.check_name(sym::doc) {
1641 return noop_visit_attribute(at, self);
1644 if let Some(list) = at.meta_item_list() {
1645 if !list.iter().any(|it| it.check_name(sym::include)) {
1646 return noop_visit_attribute(at, self);
1649 let mut items = vec![];
1651 for mut it in list {
1652 if !it.check_name(sym::include) {
1654 noop_visit_meta_list_item(&mut it, self);
1660 if let Some(file) = it.value_str() {
1661 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1662 self.check_attributes(slice::from_ref(at));
1663 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1664 // avoid loading the file if they haven't enabled the feature
1665 return noop_visit_attribute(at, self);
1668 let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1669 Ok(filename) => filename,
1676 match self.cx.source_map().load_file(&filename) {
1677 Ok(source_file) => {
1678 let src = source_file
1681 .expect("freshly loaded file should have a source");
1682 let src_interned = Symbol::intern(src.as_str());
1684 let include_info = vec![
1685 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1686 Ident::with_dummy_span(sym::file),
1690 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1691 Ident::with_dummy_span(sym::contents),
1697 let include_ident = Ident::with_dummy_span(sym::include);
1698 let item = attr::mk_list_item(include_ident, include_info);
1699 items.push(ast::NestedMetaItem::MetaItem(item));
1703 it.meta_item().and_then(|item| item.name_value_literal()).unwrap();
1705 if e.kind() == ErrorKind::InvalidData {
1709 &format!("{} wasn't a utf-8 file", filename.display()),
1711 .span_label(lit.span, "contains invalid utf-8")
1714 let mut err = self.cx.struct_span_err(
1716 &format!("couldn't read {}: {}", filename.display(), e),
1718 err.span_label(lit.span, "couldn't read file");
1727 .struct_span_err(it.span(), "expected path to external documentation");
1729 // Check if the user erroneously used `doc(include(...))` syntax.
1730 let literal = it.meta_item_list().and_then(|list| {
1731 if list.len() == 1 {
1732 list[0].literal().map(|literal| &literal.kind)
1738 let (path, applicability) = match &literal {
1739 Some(LitKind::Str(path, ..)) => {
1740 (path.to_string(), Applicability::MachineApplicable)
1742 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1745 err.span_suggestion(
1747 "provide a file path with `=`",
1748 format!("include = \"{}\"", path),
1756 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1757 *at = ast::Attribute {
1758 kind: ast::AttrKind::Normal(AttrItem {
1760 args: meta.kind.mac_args(meta.span),
1767 noop_visit_attribute(at, self)
1771 fn visit_id(&mut self, id: &mut ast::NodeId) {
1773 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1774 *id = self.cx.resolver.next_node_id()
1778 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1779 self.cfg.configure_fn_decl(&mut fn_decl);
1780 noop_visit_fn_decl(fn_decl, self);
1784 pub struct ExpansionConfig<'feat> {
1785 pub crate_name: String,
1786 pub features: Option<&'feat Features>,
1787 pub recursion_limit: usize,
1788 pub trace_mac: bool,
1789 pub should_test: bool, // If false, strip `#[test]` nodes
1790 pub keep_macs: bool,
1793 impl<'feat> ExpansionConfig<'feat> {
1794 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1798 recursion_limit: 1024,
1805 fn proc_macro_hygiene(&self) -> bool {
1806 self.features.map_or(false, |features| features.proc_macro_hygiene)
1808 fn custom_inner_attributes(&self) -> bool {
1809 self.features.map_or(false, |features| features.custom_inner_attributes)