1 use crate::ast::{self, Block, Ident, LitKind, NodeId, PatKind, Path};
2 use crate::ast::{MacStmtStyle, StmtKind, ItemKind};
3 use crate::attr::{self, HasAttrs};
4 use crate::source_map::respan;
5 use crate::config::StripUnconfigured;
6 use crate::ext::base::*;
7 use crate::ext::proc_macro::{collect_derives, MarkAttrs};
8 use crate::ext::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
9 use crate::ext::mbe::macro_rules::annotate_err_with_kind;
10 use crate::ext::placeholders::{placeholder, PlaceholderExpander};
11 use crate::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
12 use crate::mut_visit::*;
13 use crate::parse::{DirectoryOwnership, PResult, ParseSess};
14 use crate::parse::token;
15 use crate::parse::parser::Parser;
17 use crate::symbol::{sym, Symbol};
18 use crate::tokenstream::{TokenStream, TokenTree};
19 use crate::visit::{self, Visitor};
20 use crate::util::map_in_place::MapInPlace;
22 use errors::{Applicability, FatalError};
23 use smallvec::{smallvec, SmallVec};
24 use syntax_pos::{Span, DUMMY_SP, FileName};
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_data_structures::sync::Lrc;
28 use std::io::ErrorKind;
29 use std::{iter, mem, slice};
30 use std::ops::DerefMut;
32 use std::path::PathBuf;
34 macro_rules! ast_fragments {
36 $($Kind:ident($AstTy:ty) {
38 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
39 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
43 /// A fragment of AST that can be produced by a single macro expansion.
44 /// Can also serve as an input and intermediate result for macro expansion operations.
45 pub enum AstFragment {
46 OptExpr(Option<P<ast::Expr>>),
50 /// "Discriminant" of an AST fragment.
51 #[derive(Copy, Clone, PartialEq, Eq)]
52 pub enum AstFragmentKind {
57 impl AstFragmentKind {
58 pub fn name(self) -> &'static str {
60 AstFragmentKind::OptExpr => "expression",
61 $(AstFragmentKind::$Kind => $kind_name,)*
65 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
67 AstFragmentKind::OptExpr =>
68 result.make_expr().map(Some).map(AstFragment::OptExpr),
69 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
75 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
77 AstFragment::OptExpr(expr) => expr,
78 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
82 $(pub fn $make_ast(self) -> $AstTy {
84 AstFragment::$Kind(ast) => ast,
85 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
89 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
91 AstFragment::OptExpr(opt_expr) => {
92 visit_clobber(opt_expr, |opt_expr| {
93 if let Some(expr) = opt_expr {
94 vis.filter_map_expr(expr)
100 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
101 $($(AstFragment::$Kind(ast) =>
102 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
106 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
108 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
109 AstFragment::OptExpr(None) => {}
110 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
111 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
112 visitor.$visit_ast_elt(ast_elt);
118 impl<'a> MacResult for crate::ext::mbe::macro_rules::ParserAnyMacro<'a> {
119 $(fn $make_ast(self: Box<crate::ext::mbe::macro_rules::ParserAnyMacro<'a>>)
121 Some(self.make(AstFragmentKind::$Kind).$make_ast())
128 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
129 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
130 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
131 Stmts(SmallVec<[ast::Stmt; 1]>) {
132 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
134 Items(SmallVec<[P<ast::Item>; 1]>) {
135 "item"; many fn flat_map_item; fn visit_item; fn make_items;
137 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
138 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
140 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
141 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
143 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
145 many fn flat_map_foreign_item;
146 fn visit_foreign_item;
147 fn make_foreign_items;
149 Arms(SmallVec<[ast::Arm; 1]>) {
150 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
152 Fields(SmallVec<[ast::Field; 1]>) {
153 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
155 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
157 many fn flat_map_field_pattern;
158 fn visit_field_pattern;
159 fn make_field_patterns;
161 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
163 many fn flat_map_generic_param;
164 fn visit_generic_param;
165 fn make_generic_params;
167 Params(SmallVec<[ast::Param; 1]>) {
168 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
170 StructFields(SmallVec<[ast::StructField; 1]>) {
172 many fn flat_map_struct_field;
173 fn visit_struct_field;
174 fn make_struct_fields;
176 Variants(SmallVec<[ast::Variant; 1]>) {
177 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
181 impl AstFragmentKind {
182 fn dummy(self, span: Span) -> AstFragment {
183 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
186 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
188 let mut items = items.into_iter();
190 AstFragmentKind::Arms =>
191 AstFragment::Arms(items.map(Annotatable::expect_arm).collect()),
192 AstFragmentKind::Fields =>
193 AstFragment::Fields(items.map(Annotatable::expect_field).collect()),
194 AstFragmentKind::FieldPats =>
195 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()),
196 AstFragmentKind::GenericParams =>
197 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()),
198 AstFragmentKind::Params =>
199 AstFragment::Params(items.map(Annotatable::expect_param).collect()),
200 AstFragmentKind::StructFields => AstFragment::StructFields(
201 items.map(Annotatable::expect_struct_field).collect()
203 AstFragmentKind::Variants =>
204 AstFragment::Variants(items.map(Annotatable::expect_variant).collect()),
205 AstFragmentKind::Items =>
206 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
207 AstFragmentKind::ImplItems =>
208 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
209 AstFragmentKind::TraitItems =>
210 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
211 AstFragmentKind::ForeignItems =>
212 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
213 AstFragmentKind::Stmts =>
214 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
215 AstFragmentKind::Expr => AstFragment::Expr(
216 items.next().expect("expected exactly one expression").expect_expr()
218 AstFragmentKind::OptExpr =>
219 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
220 AstFragmentKind::Pat | AstFragmentKind::Ty =>
221 panic!("patterns and types aren't annotatable"),
226 pub struct Invocation {
227 pub kind: InvocationKind,
228 pub fragment_kind: AstFragmentKind,
229 pub expansion_data: ExpansionData,
232 pub enum InvocationKind {
238 attr: ast::Attribute,
240 // Required for resolving derive helper attributes.
242 // We temporarily report errors for attribute macros placed after derives
249 /// "Invocation" that contains all derives from an item,
250 /// broken into multiple `Derive` invocations when expanded.
251 /// FIXME: Find a way to remove it.
259 pub fn span(&self) -> Span {
261 InvocationKind::Bang { span, .. } => *span,
262 InvocationKind::Attr { attr, .. } => attr.span,
263 InvocationKind::Derive { path, .. } => path.span,
264 InvocationKind::DeriveContainer { item, .. } => item.span(),
269 pub struct MacroExpander<'a, 'b> {
270 pub cx: &'a mut ExtCtxt<'b>,
271 monotonic: bool, // cf. `cx.monotonic_expander()`
274 impl<'a, 'b> MacroExpander<'a, 'b> {
275 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
276 MacroExpander { cx, monotonic }
279 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
280 let mut module = ModuleData {
281 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
282 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
283 FileName::Real(path) => path,
284 other => PathBuf::from(other.to_string()),
287 module.directory.pop();
288 self.cx.root_path = module.directory.clone();
289 self.cx.current_expansion.module = Rc::new(module);
291 let orig_mod_span = krate.module.inner;
293 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
296 node: ast::ItemKind::Mod(krate.module),
297 ident: Ident::invalid(),
298 id: ast::DUMMY_NODE_ID,
299 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
303 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
304 Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
306 krate.module = module;
309 // Resolution failed so we return an empty expansion
310 krate.attrs = vec![];
311 krate.module = ast::Mod {
312 inner: orig_mod_span,
319 self.cx.trace_macros_diag();
323 // Recursively expand all macro invocations in this AST fragment.
324 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
325 let orig_expansion_data = self.cx.current_expansion.clone();
326 self.cx.current_expansion.depth = 0;
328 // Collect all macro invocations and replace them with placeholders.
329 let (mut fragment_with_placeholders, mut invocations)
330 = self.collect_invocations(input_fragment, &[]);
332 // Optimization: if we resolve all imports now,
333 // we'll be able to immediately resolve most of imported macros.
334 self.resolve_imports();
336 // Resolve paths in all invocations and produce output expanded fragments for them, but
337 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
338 // The output fragments also go through expansion recursively until no invocations are left.
339 // Unresolved macros produce dummy outputs as a recovery measure.
340 invocations.reverse();
341 let mut expanded_fragments = Vec::new();
342 let mut all_derive_placeholders: FxHashMap<ExpnId, Vec<_>> = FxHashMap::default();
343 let mut undetermined_invocations = Vec::new();
344 let (mut progress, mut force) = (false, !self.monotonic);
346 let invoc = if let Some(invoc) = invocations.pop() {
349 self.resolve_imports();
350 if undetermined_invocations.is_empty() { break }
351 invocations = mem::take(&mut undetermined_invocations);
352 force = !mem::replace(&mut progress, false);
356 let eager_expansion_root =
357 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
358 let res = match self.cx.resolver.resolve_macro_invocation(
359 &invoc, eager_expansion_root, force
362 Err(Indeterminate) => {
363 undetermined_invocations.push(invoc);
369 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
370 self.cx.current_expansion = invoc.expansion_data.clone();
372 // FIXME(jseyfried): Refactor out the following logic
373 let (expanded_fragment, new_invocations) = match res {
374 InvocationRes::Single(ext) => {
375 let fragment = self.expand_invoc(invoc, &ext.kind);
376 self.collect_invocations(fragment, &[])
378 InvocationRes::DeriveContainer(exts) => {
379 let (derives, item) = match invoc.kind {
380 InvocationKind::DeriveContainer { derives, item } => (derives, item),
383 if !item.derive_allowed() {
384 let attr = attr::find_by_name(item.attrs(), sym::derive)
385 .expect("`derive` attribute should exist");
386 let span = attr.span;
387 let mut err = self.cx.mut_span_err(span,
388 "`derive` may only be applied to structs, enums and unions");
389 if let ast::AttrStyle::Inner = attr.style {
390 let trait_list = derives.iter()
391 .map(|t| t.to_string()).collect::<Vec<_>>();
392 let suggestion = format!("#[derive({})]", trait_list.join(", "));
394 span, "try an outer attribute", suggestion,
395 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
396 Applicability::MaybeIncorrect
402 let mut item = self.fully_configure(item);
403 item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
404 let mut helper_attrs = Vec::new();
405 let mut has_copy = false;
407 helper_attrs.extend(&ext.helper_attrs);
408 has_copy |= ext.is_derive_copy;
410 // Mark derive helpers inside this item as known and used.
411 // FIXME: This is a hack, derive helpers should be integrated with regular name
412 // resolution instead. For example, helpers introduced by a derive container
413 // can be in scope for all code produced by that container's expansion.
414 item.visit_with(&mut MarkAttrs(&helper_attrs));
416 self.cx.resolver.add_derives(invoc.expansion_data.id, SpecialDerives::COPY);
419 let derive_placeholders =
420 all_derive_placeholders.entry(invoc.expansion_data.id).or_default();
421 derive_placeholders.reserve(derives.len());
422 invocations.reserve(derives.len());
423 for path in derives {
424 let expn_id = ExpnId::fresh(None);
425 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
426 invocations.push(Invocation {
427 kind: InvocationKind::Derive { path, item: item.clone() },
428 fragment_kind: invoc.fragment_kind,
429 expansion_data: ExpansionData {
431 ..invoc.expansion_data.clone()
435 let fragment = invoc.fragment_kind
436 .expect_from_annotatables(::std::iter::once(item));
437 self.collect_invocations(fragment, derive_placeholders)
441 if expanded_fragments.len() < depth {
442 expanded_fragments.push(Vec::new());
444 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
445 if !self.cx.ecfg.single_step {
446 invocations.extend(new_invocations.into_iter().rev());
450 self.cx.current_expansion = orig_expansion_data;
452 // Finally incorporate all the expanded macros into the input AST fragment.
453 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
454 while let Some(expanded_fragments) = expanded_fragments.pop() {
455 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
456 let derive_placeholders =
457 all_derive_placeholders.remove(&expn_id).unwrap_or_else(Vec::new);
458 placeholder_expander.add(NodeId::placeholder_from_expn_id(expn_id),
459 expanded_fragment, derive_placeholders);
462 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
463 fragment_with_placeholders
466 fn resolve_imports(&mut self) {
468 self.cx.resolver.resolve_imports();
472 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
473 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
474 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
475 /// prepares data for resolving paths of macro invocations.
476 fn collect_invocations(&mut self, mut fragment: AstFragment, extra_placeholders: &[NodeId])
477 -> (AstFragment, Vec<Invocation>) {
478 // Resolve `$crate`s in the fragment for pretty-printing.
479 self.cx.resolver.resolve_dollar_crates();
482 let mut collector = InvocationCollector {
483 cfg: StripUnconfigured {
484 sess: self.cx.parse_sess,
485 features: self.cx.ecfg.features,
488 invocations: Vec::new(),
489 monotonic: self.monotonic,
491 fragment.mut_visit_with(&mut collector);
492 collector.invocations
495 // FIXME: Merge `extra_placeholders` into the `fragment` as regular placeholders.
497 self.cx.resolver.visit_ast_fragment_with_placeholders(
498 self.cx.current_expansion.id, &fragment, extra_placeholders);
501 (fragment, invocations)
504 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
505 let mut cfg = StripUnconfigured {
506 sess: self.cx.parse_sess,
507 features: self.cx.ecfg.features,
509 // Since the item itself has already been configured by the InvocationCollector,
510 // we know that fold result vector will contain exactly one element
512 Annotatable::Item(item) => {
513 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
515 Annotatable::TraitItem(item) => {
516 Annotatable::TraitItem(
517 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
519 Annotatable::ImplItem(item) => {
520 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
522 Annotatable::ForeignItem(item) => {
523 Annotatable::ForeignItem(
524 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
527 Annotatable::Stmt(stmt) => {
528 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
530 Annotatable::Expr(mut expr) => {
531 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
533 Annotatable::Arm(arm) => {
534 Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap())
536 Annotatable::Field(field) => {
537 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
539 Annotatable::FieldPat(fp) => {
540 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
542 Annotatable::GenericParam(param) => {
543 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
545 Annotatable::Param(param) => {
546 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
548 Annotatable::StructField(sf) => {
549 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
551 Annotatable::Variant(v) => {
552 Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap())
557 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
558 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
559 if fragment_kind == AstFragmentKind::ForeignItems && !self.cx.ecfg.macros_in_extern() {
560 if let SyntaxExtensionKind::NonMacroAttr { .. } = ext {} else {
561 emit_feature_err(&self.cx.parse_sess, sym::macros_in_extern,
562 span, GateIssue::Language,
563 "macro invocations in `extern {}` blocks are experimental");
567 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
568 let expn_data = self.cx.current_expansion.id.expn_data();
569 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
570 let mut err = self.cx.struct_span_err(expn_data.call_site,
571 &format!("recursion limit reached while expanding the macro `{}`",
572 expn_data.kind.descr()));
574 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
577 self.cx.trace_macros_diag();
582 InvocationKind::Bang { mac, .. } => match ext {
583 SyntaxExtensionKind::Bang(expander) => {
584 self.gate_proc_macro_expansion_kind(span, fragment_kind);
585 let tok_result = expander.expand(self.cx, span, mac.stream());
587 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span);
588 self.gate_proc_macro_expansion(span, &result);
591 SyntaxExtensionKind::LegacyBang(expander) => {
592 let prev = self.cx.current_expansion.prior_type_ascription;
593 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
594 let tok_result = expander.expand(self.cx, span, mac.stream());
595 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
598 let msg = format!("non-{kind} macro in {kind} position: {path}",
599 kind = fragment_kind.name(), path = mac.path);
600 self.cx.span_err(span, &msg);
601 self.cx.trace_macros_diag();
602 fragment_kind.dummy(span)
604 self.cx.current_expansion.prior_type_ascription = prev;
609 InvocationKind::Attr { attr, mut item, .. } => match ext {
610 SyntaxExtensionKind::Attr(expander) => {
611 self.gate_proc_macro_attr_item(span, &item);
612 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
613 Annotatable::Item(item) => token::NtItem(item),
614 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
615 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
616 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
617 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
618 Annotatable::Expr(expr) => token::NtExpr(expr),
620 | Annotatable::Field(..)
621 | Annotatable::FieldPat(..)
622 | Annotatable::GenericParam(..)
623 | Annotatable::Param(..)
624 | Annotatable::StructField(..)
625 | Annotatable::Variant(..)
626 => panic!("unexpected annotatable"),
627 })), DUMMY_SP).into();
628 let input = self.extract_proc_macro_attr_input(attr.tokens, span);
629 let tok_result = expander.expand(self.cx, span, input, item_tok);
630 let res = self.parse_ast_fragment(tok_result, fragment_kind, &attr.path, span);
631 self.gate_proc_macro_expansion(span, &res);
634 SyntaxExtensionKind::LegacyAttr(expander) => {
635 match attr.parse_meta(self.cx.parse_sess) {
637 let item = expander.expand(self.cx, span, &meta, item);
638 fragment_kind.expect_from_annotatables(item)
642 fragment_kind.dummy(span)
646 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
647 attr::mark_known(&attr);
649 attr::mark_used(&attr);
651 item.visit_attrs(|attrs| attrs.push(attr));
652 fragment_kind.expect_from_annotatables(iter::once(item))
656 InvocationKind::Derive { path, item } => match ext {
657 SyntaxExtensionKind::Derive(expander) |
658 SyntaxExtensionKind::LegacyDerive(expander) => {
659 if !item.derive_allowed() {
660 return fragment_kind.dummy(span);
662 let meta = ast::MetaItem { node: ast::MetaItemKind::Word, span, path };
663 let items = expander.expand(self.cx, span, &meta, item);
664 fragment_kind.expect_from_annotatables(items)
668 InvocationKind::DeriveContainer { .. } => unreachable!()
672 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
673 let mut trees = tokens.trees();
675 Some(TokenTree::Delimited(_, _, tts)) => {
676 if trees.next().is_none() {
680 Some(TokenTree::Token(..)) => {}
681 None => return TokenStream::empty(),
683 self.cx.span_err(span, "custom attribute invocations must be \
684 of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
685 followed by a delimiter token");
689 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
690 let (kind, gate) = match *item {
691 Annotatable::Item(ref item) => {
693 ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
694 ItemKind::Mod(_) => ("modules", sym::proc_macro_hygiene),
698 Annotatable::TraitItem(_) => return,
699 Annotatable::ImplItem(_) => return,
700 Annotatable::ForeignItem(_) => return,
701 Annotatable::Stmt(_) |
702 Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
703 Annotatable::Stmt(_) => ("statements", sym::proc_macro_hygiene),
704 Annotatable::Expr(_) => ("expressions", sym::proc_macro_hygiene),
706 | Annotatable::Field(..)
707 | Annotatable::FieldPat(..)
708 | Annotatable::GenericParam(..)
709 | Annotatable::Param(..)
710 | Annotatable::StructField(..)
711 | Annotatable::Variant(..)
712 => panic!("unexpected annotatable"),
719 &format!("custom attributes cannot be applied to {}", kind),
723 fn gate_proc_macro_expansion(&self, span: Span, fragment: &AstFragment) {
724 if self.cx.ecfg.proc_macro_hygiene() {
728 fragment.visit_with(&mut DisallowMacros {
730 parse_sess: self.cx.parse_sess,
733 struct DisallowMacros<'a> {
735 parse_sess: &'a ParseSess,
738 impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
739 fn visit_item(&mut self, i: &'ast ast::Item) {
740 if let ast::ItemKind::MacroDef(_) = i.node {
743 sym::proc_macro_hygiene,
746 "procedural macros cannot expand to macro definitions",
749 visit::walk_item(self, i);
752 fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
758 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
759 let kind = match kind {
760 AstFragmentKind::Expr => "expressions",
761 AstFragmentKind::OptExpr => "expressions",
762 AstFragmentKind::Pat => "patterns",
763 AstFragmentKind::Ty => "types",
764 AstFragmentKind::Stmts => "statements",
765 AstFragmentKind::Items => return,
766 AstFragmentKind::TraitItems => return,
767 AstFragmentKind::ImplItems => return,
768 AstFragmentKind::ForeignItems => return,
769 AstFragmentKind::Arms
770 | AstFragmentKind::Fields
771 | AstFragmentKind::FieldPats
772 | AstFragmentKind::GenericParams
773 | AstFragmentKind::Params
774 | AstFragmentKind::StructFields
775 | AstFragmentKind::Variants
776 => panic!("unexpected AST fragment kind"),
778 if self.cx.ecfg.proc_macro_hygiene() {
783 sym::proc_macro_hygiene,
786 &format!("procedural macros cannot be expanded to {}", kind),
790 fn parse_ast_fragment(
793 kind: AstFragmentKind,
797 let mut parser = self.cx.new_parser_from_tts(toks);
798 match parser.parse_ast_fragment(kind, false) {
800 parser.ensure_complete_parse(path, kind.name(), span);
805 annotate_err_with_kind(&mut err, kind, span);
807 self.cx.trace_macros_diag();
814 impl<'a> Parser<'a> {
815 pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
816 -> PResult<'a, AstFragment> {
818 AstFragmentKind::Items => {
819 let mut items = SmallVec::new();
820 while let Some(item) = self.parse_item()? {
823 AstFragment::Items(items)
825 AstFragmentKind::TraitItems => {
826 let mut items = SmallVec::new();
827 while self.token != token::Eof {
828 items.push(self.parse_trait_item(&mut false)?);
830 AstFragment::TraitItems(items)
832 AstFragmentKind::ImplItems => {
833 let mut items = SmallVec::new();
834 while self.token != token::Eof {
835 items.push(self.parse_impl_item(&mut false)?);
837 AstFragment::ImplItems(items)
839 AstFragmentKind::ForeignItems => {
840 let mut items = SmallVec::new();
841 while self.token != token::Eof {
842 items.push(self.parse_foreign_item(DUMMY_SP)?);
844 AstFragment::ForeignItems(items)
846 AstFragmentKind::Stmts => {
847 let mut stmts = SmallVec::new();
848 while self.token != token::Eof &&
849 // won't make progress on a `}`
850 self.token != token::CloseDelim(token::Brace) {
851 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
855 AstFragment::Stmts(stmts)
857 AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
858 AstFragmentKind::OptExpr => {
859 if self.token != token::Eof {
860 AstFragment::OptExpr(Some(self.parse_expr()?))
862 AstFragment::OptExpr(None)
865 AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
866 AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat(None)?),
867 AstFragmentKind::Arms
868 | AstFragmentKind::Fields
869 | AstFragmentKind::FieldPats
870 | AstFragmentKind::GenericParams
871 | AstFragmentKind::Params
872 | AstFragmentKind::StructFields
873 | AstFragmentKind::Variants
874 => panic!("unexpected AST fragment kind"),
878 pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
879 if self.token != token::Eof {
880 let msg = format!("macro expansion ignores token `{}` and any following",
881 self.this_token_to_string());
882 // Avoid emitting backtrace info twice.
883 let def_site_span = self.token.span.with_ctxt(SyntaxContext::root());
884 let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
885 err.span_label(span, "caused by the macro expansion here");
887 "the usage of `{}!` is likely invalid in {} context",
892 let semi_span = self.sess.source_map().next_point(span);
894 let semi_full_span = semi_span.to(self.sess.source_map().next_point(semi_span));
895 match self.sess.source_map().span_to_snippet(semi_full_span) {
896 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
899 "you might be missing a semicolon here",
901 Applicability::MaybeIncorrect,
911 struct InvocationCollector<'a, 'b> {
912 cx: &'a mut ExtCtxt<'b>,
913 cfg: StripUnconfigured<'a>,
914 invocations: Vec<Invocation>,
918 impl<'a, 'b> InvocationCollector<'a, 'b> {
919 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
920 // Expansion data for all the collected invocations is set upon their resolution,
921 // with exception of the derive container case which is not resolved and can get
922 // its expansion data immediately.
923 let expn_data = match &kind {
924 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
925 parent: self.cx.current_expansion.id,
927 ExpnKind::Macro(MacroKind::Attr, sym::derive),
928 item.span(), self.cx.parse_sess.edition,
933 let expn_id = ExpnId::fresh(expn_data);
934 self.invocations.push(Invocation {
937 expansion_data: ExpansionData {
939 depth: self.cx.current_expansion.depth + 1,
940 ..self.cx.current_expansion.clone()
943 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
946 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
947 self.collect(kind, InvocationKind::Bang { mac, span })
950 fn collect_attr(&mut self,
951 attr: Option<ast::Attribute>,
954 kind: AstFragmentKind,
957 self.collect(kind, match attr {
958 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
959 None => InvocationKind::DeriveContainer { derives, item },
963 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
964 -> Option<ast::Attribute> {
965 let attr = attrs.iter()
967 if a.path == sym::derive {
968 *after_derive = true;
970 !attr::is_known(a) && !is_builtin_attr(a)
972 .map(|i| attrs.remove(i));
973 if let Some(attr) = &attr {
974 if !self.cx.ecfg.custom_inner_attributes() &&
975 attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
976 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
977 attr.span, GateIssue::Language,
978 "non-builtin inner attributes are unstable");
984 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
985 fn classify_item<T>(&mut self, item: &mut T)
986 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
989 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
991 item.visit_attrs(|mut attrs| {
992 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
993 traits = collect_derives(&mut self.cx, &mut attrs);
996 (attr, traits, after_derive)
999 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
1000 /// to the unused-attributes lint (making it an error on statements and expressions
1001 /// is a breaking change)
1002 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
1003 -> (Option<ast::Attribute>, /* after_derive */ bool) {
1004 let (mut attr, mut after_derive) = (None, false);
1006 nonitem.visit_attrs(|mut attrs| {
1007 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1010 (attr, after_derive)
1013 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1014 self.cfg.configure(node)
1017 // Detect use of feature-gated or invalid attributes on macro invocations
1018 // since they will not be detected after macro expansion.
1019 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1020 let features = self.cx.ecfg.features.unwrap();
1021 for attr in attrs.iter() {
1022 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1024 // macros are expanded before any lint passes so this warning has to be hardcoded
1025 if attr.path == sym::derive {
1026 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1027 .note("this may become a hard error in a future release")
1034 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1035 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1036 self.cfg.configure_expr(expr);
1037 visit_clobber(expr.deref_mut(), |mut expr| {
1038 self.cfg.configure_expr_kind(&mut expr.node);
1040 // ignore derives so they remain unused
1041 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1044 // Collect the invoc regardless of whether or not attributes are permitted here
1045 // expansion will eat the attribute so it won't error later.
1046 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1048 // AstFragmentKind::Expr requires the macro to emit an expression.
1049 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1050 AstFragmentKind::Expr, after_derive)
1055 if let ast::ExprKind::Mac(mac) = expr.node {
1056 self.check_attributes(&expr.attrs);
1057 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1061 noop_visit_expr(&mut expr, self);
1067 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1068 let mut arm = configure!(self, arm);
1070 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1071 if attr.is_some() || !traits.is_empty() {
1072 return self.collect_attr(attr, traits, Annotatable::Arm(arm),
1073 AstFragmentKind::Arms, after_derive)
1077 noop_flat_map_arm(arm, self)
1080 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1081 let mut field = configure!(self, field);
1083 let (attr, traits, after_derive) = self.classify_item(&mut field);
1084 if attr.is_some() || !traits.is_empty() {
1085 return self.collect_attr(attr, traits, Annotatable::Field(field),
1086 AstFragmentKind::Fields, after_derive)
1090 noop_flat_map_field(field, self)
1093 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1094 let mut fp = configure!(self, fp);
1096 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1097 if attr.is_some() || !traits.is_empty() {
1098 return self.collect_attr(attr, traits, Annotatable::FieldPat(fp),
1099 AstFragmentKind::FieldPats, after_derive)
1100 .make_field_patterns();
1103 noop_flat_map_field_pattern(fp, self)
1106 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1107 let mut p = configure!(self, p);
1109 let (attr, traits, after_derive) = self.classify_item(&mut p);
1110 if attr.is_some() || !traits.is_empty() {
1111 return self.collect_attr(attr, traits, Annotatable::Param(p),
1112 AstFragmentKind::Params, after_derive)
1116 noop_flat_map_param(p, self)
1119 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1120 let mut sf = configure!(self, sf);
1122 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1123 if attr.is_some() || !traits.is_empty() {
1124 return self.collect_attr(attr, traits, Annotatable::StructField(sf),
1125 AstFragmentKind::StructFields, after_derive)
1126 .make_struct_fields();
1129 noop_flat_map_struct_field(sf, self)
1132 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1133 let mut variant = configure!(self, variant);
1135 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1136 if attr.is_some() || !traits.is_empty() {
1137 return self.collect_attr(attr, traits, Annotatable::Variant(variant),
1138 AstFragmentKind::Variants, after_derive)
1142 noop_flat_map_variant(variant, self)
1145 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1146 let expr = configure!(self, expr);
1147 expr.filter_map(|mut expr| {
1148 self.cfg.configure_expr_kind(&mut expr.node);
1150 // Ignore derives so they remain unused.
1151 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1154 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1156 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1157 AstFragmentKind::OptExpr, after_derive)
1159 .map(|expr| expr.into_inner())
1162 if let ast::ExprKind::Mac(mac) = expr.node {
1163 self.check_attributes(&expr.attrs);
1164 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1166 .map(|expr| expr.into_inner())
1168 Some({ noop_visit_expr(&mut expr, self); expr })
1173 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1174 self.cfg.configure_pat(pat);
1176 PatKind::Mac(_) => {}
1177 _ => return noop_visit_pat(pat, self),
1180 visit_clobber(pat, |mut pat| {
1181 match mem::replace(&mut pat.node, PatKind::Wild) {
1182 PatKind::Mac(mac) =>
1183 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1184 _ => unreachable!(),
1189 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1190 let mut stmt = configure!(self, stmt);
1192 // we'll expand attributes on expressions separately
1193 if !stmt.is_expr() {
1194 let (attr, derives, after_derive) = if stmt.is_item() {
1195 self.classify_item(&mut stmt)
1197 // ignore derives on non-item statements so it falls through
1198 // to the unused-attributes lint
1199 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1200 (attr, vec![], after_derive)
1203 if attr.is_some() || !derives.is_empty() {
1204 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1205 AstFragmentKind::Stmts, after_derive).make_stmts();
1209 if let StmtKind::Mac(mac) = stmt.node {
1210 let (mac, style, attrs) = mac.into_inner();
1211 self.check_attributes(&attrs);
1212 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1215 // If this is a macro invocation with a semicolon, then apply that
1216 // semicolon to the final statement produced by expansion.
1217 if style == MacStmtStyle::Semicolon {
1218 if let Some(stmt) = placeholder.pop() {
1219 placeholder.push(stmt.add_trailing_semicolon());
1226 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1227 let ast::Stmt { id, node, span } = stmt;
1228 noop_flat_map_stmt_kind(node, self).into_iter().map(|node| {
1229 ast::Stmt { id, node, span }
1234 fn visit_block(&mut self, block: &mut P<Block>) {
1235 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1236 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1237 noop_visit_block(block, self);
1238 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1241 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1242 let mut item = configure!(self, item);
1244 let (attr, traits, after_derive) = self.classify_item(&mut item);
1245 if attr.is_some() || !traits.is_empty() {
1246 return self.collect_attr(attr, traits, Annotatable::Item(item),
1247 AstFragmentKind::Items, after_derive).make_items();
1251 ast::ItemKind::Mac(..) => {
1252 self.check_attributes(&item.attrs);
1253 item.and_then(|item| match item.node {
1254 ItemKind::Mac(mac) => self.collect(
1255 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1257 _ => unreachable!(),
1260 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1261 if item.ident == Ident::invalid() {
1262 return noop_flat_map_item(item, self);
1265 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1266 let mut module = (*self.cx.current_expansion.module).clone();
1267 module.mod_path.push(item.ident);
1269 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1270 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1271 // Thus, if `inner` is the dummy span, we know the module is inline.
1272 let inline_module = item.span.contains(inner) || inner.is_dummy();
1275 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1276 self.cx.current_expansion.directory_ownership =
1277 DirectoryOwnership::Owned { relative: None };
1278 module.directory.push(&*path.as_str());
1280 module.directory.push(&*item.ident.as_str());
1283 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1284 let mut path = match path {
1285 FileName::Real(path) => path,
1286 other => PathBuf::from(other.to_string()),
1288 let directory_ownership = match path.file_name().unwrap().to_str() {
1289 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1290 Some(_) => DirectoryOwnership::Owned {
1291 relative: Some(item.ident),
1293 None => DirectoryOwnership::UnownedViaMod(false),
1296 module.directory = path;
1297 self.cx.current_expansion.directory_ownership = directory_ownership;
1301 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1302 let result = noop_flat_map_item(item, self);
1303 self.cx.current_expansion.module = orig_module;
1304 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1308 _ => noop_flat_map_item(item, self),
1312 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1313 let mut item = configure!(self, item);
1315 let (attr, traits, after_derive) = self.classify_item(&mut item);
1316 if attr.is_some() || !traits.is_empty() {
1317 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1318 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1322 ast::TraitItemKind::Macro(mac) => {
1323 let ast::TraitItem { attrs, span, .. } = item;
1324 self.check_attributes(&attrs);
1325 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1327 _ => noop_flat_map_trait_item(item, self),
1331 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1332 let mut item = configure!(self, item);
1334 let (attr, traits, after_derive) = self.classify_item(&mut item);
1335 if attr.is_some() || !traits.is_empty() {
1336 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1337 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1341 ast::ImplItemKind::Macro(mac) => {
1342 let ast::ImplItem { attrs, span, .. } = item;
1343 self.check_attributes(&attrs);
1344 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1346 _ => noop_flat_map_impl_item(item, self),
1350 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1352 ast::TyKind::Mac(_) => {}
1353 _ => return noop_visit_ty(ty, self),
1356 visit_clobber(ty, |mut ty| {
1357 match mem::replace(&mut ty.node, ast::TyKind::Err) {
1358 ast::TyKind::Mac(mac) =>
1359 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1360 _ => unreachable!(),
1365 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1366 self.cfg.configure_foreign_mod(foreign_mod);
1367 noop_visit_foreign_mod(foreign_mod, self);
1370 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1371 -> SmallVec<[ast::ForeignItem; 1]>
1373 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1375 if attr.is_some() || !traits.is_empty() {
1376 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1377 AstFragmentKind::ForeignItems, after_derive)
1378 .make_foreign_items();
1381 if let ast::ForeignItemKind::Macro(mac) = foreign_item.node {
1382 self.check_attributes(&foreign_item.attrs);
1383 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1384 .make_foreign_items();
1387 noop_flat_map_foreign_item(foreign_item, self)
1390 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1392 ast::ItemKind::MacroDef(..) => {}
1394 self.cfg.configure_item_kind(item);
1395 noop_visit_item_kind(item, self);
1400 fn flat_map_generic_param(
1402 param: ast::GenericParam
1403 ) -> SmallVec<[ast::GenericParam; 1]>
1405 let mut param = configure!(self, param);
1407 let (attr, traits, after_derive) = self.classify_item(&mut param);
1408 if attr.is_some() || !traits.is_empty() {
1409 return self.collect_attr(attr, traits, Annotatable::GenericParam(param),
1410 AstFragmentKind::GenericParams, after_derive)
1411 .make_generic_params();
1414 noop_flat_map_generic_param(param, self)
1417 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1418 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1419 // contents="file contents")]` attributes
1420 if !at.check_name(sym::doc) {
1421 return noop_visit_attribute(at, self);
1424 if let Some(list) = at.meta_item_list() {
1425 if !list.iter().any(|it| it.check_name(sym::include)) {
1426 return noop_visit_attribute(at, self);
1429 let mut items = vec![];
1431 for mut it in list {
1432 if !it.check_name(sym::include) {
1433 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1437 if let Some(file) = it.value_str() {
1438 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1439 self.check_attributes(slice::from_ref(at));
1440 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1441 // avoid loading the file if they haven't enabled the feature
1442 return noop_visit_attribute(at, self);
1445 let filename = self.cx.resolve_path(&*file.as_str(), it.span());
1446 match self.cx.source_map().load_file(&filename) {
1447 Ok(source_file) => {
1448 let src = source_file.src.as_ref()
1449 .expect("freshly loaded file should have a source");
1450 let src_interned = Symbol::intern(src.as_str());
1452 let include_info = vec![
1453 ast::NestedMetaItem::MetaItem(
1454 attr::mk_name_value_item_str(
1455 Ident::with_dummy_span(sym::file),
1460 ast::NestedMetaItem::MetaItem(
1461 attr::mk_name_value_item_str(
1462 Ident::with_dummy_span(sym::contents),
1469 let include_ident = Ident::with_dummy_span(sym::include);
1470 let item = attr::mk_list_item(include_ident, include_info);
1471 items.push(ast::NestedMetaItem::MetaItem(item));
1476 .and_then(|item| item.name_value_literal())
1479 if e.kind() == ErrorKind::InvalidData {
1483 &format!("{} wasn't a utf-8 file", filename.display()),
1485 .span_label(lit.span, "contains invalid utf-8")
1488 let mut err = self.cx.struct_span_err(
1490 &format!("couldn't read {}: {}", filename.display(), e),
1492 err.span_label(lit.span, "couldn't read file");
1499 let mut err = self.cx.struct_span_err(
1501 &format!("expected path to external documentation"),
1504 // Check if the user erroneously used `doc(include(...))` syntax.
1505 let literal = it.meta_item_list().and_then(|list| {
1506 if list.len() == 1 {
1507 list[0].literal().map(|literal| &literal.node)
1513 let (path, applicability) = match &literal {
1514 Some(LitKind::Str(path, ..)) => {
1515 (path.to_string(), Applicability::MachineApplicable)
1517 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1520 err.span_suggestion(
1522 "provide a file path with `=`",
1523 format!("include = \"{}\"", path),
1531 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1532 *at = attr::Attribute {
1537 tokens: meta.node.tokens(meta.span),
1538 is_sugared_doc: false,
1541 noop_visit_attribute(at, self)
1545 fn visit_id(&mut self, id: &mut ast::NodeId) {
1547 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1548 *id = self.cx.resolver.next_node_id()
1552 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1553 self.cfg.configure_fn_decl(&mut fn_decl);
1554 noop_visit_fn_decl(fn_decl, self);
1558 pub struct ExpansionConfig<'feat> {
1559 pub crate_name: String,
1560 pub features: Option<&'feat Features>,
1561 pub recursion_limit: usize,
1562 pub trace_mac: bool,
1563 pub should_test: bool, // If false, strip `#[test]` nodes
1564 pub single_step: bool,
1565 pub keep_macs: bool,
1568 impl<'feat> ExpansionConfig<'feat> {
1569 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1573 recursion_limit: 1024,
1581 fn macros_in_extern(&self) -> bool {
1582 self.features.map_or(false, |features| features.macros_in_extern)
1584 fn proc_macro_hygiene(&self) -> bool {
1585 self.features.map_or(false, |features| features.proc_macro_hygiene)
1587 fn custom_inner_attributes(&self) -> bool {
1588 self.features.map_or(false, |features| features.custom_inner_attributes)