2 use crate::proc_macro::{collect_derives, MarkAttrs};
3 use crate::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
4 use crate::mbe::macro_rules::annotate_err_with_kind;
5 use crate::placeholders::{placeholder, PlaceholderExpander};
7 use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
8 use syntax::ast::{MacStmtStyle, StmtKind, ItemKind};
9 use syntax::attr::{self, HasAttrs};
10 use syntax::source_map::respan;
11 use syntax::configure;
12 use syntax::config::StripUnconfigured;
13 use syntax::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
14 use syntax::mut_visit::*;
15 use syntax::parse::{DirectoryOwnership, PResult};
16 use syntax::parse::token;
17 use syntax::parse::parser::Parser;
18 use syntax::print::pprust;
20 use syntax::symbol::{sym, Symbol};
21 use syntax::tokenstream::{TokenStream, TokenTree};
22 use syntax::visit::Visitor;
23 use syntax::util::map_in_place::MapInPlace;
25 use errors::{Applicability, FatalError};
26 use smallvec::{smallvec, SmallVec};
27 use syntax_pos::{Span, DUMMY_SP, FileName};
29 use rustc_data_structures::fx::FxHashMap;
30 use rustc_data_structures::sync::Lrc;
31 use std::io::ErrorKind;
32 use std::{iter, mem, slice};
33 use std::ops::DerefMut;
35 use std::path::PathBuf;
37 macro_rules! ast_fragments {
39 $($Kind:ident($AstTy:ty) {
41 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
42 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
46 /// A fragment of AST that can be produced by a single macro expansion.
47 /// Can also serve as an input and intermediate result for macro expansion operations.
48 pub enum AstFragment {
49 OptExpr(Option<P<ast::Expr>>),
53 /// "Discriminant" of an AST fragment.
54 #[derive(Copy, Clone, PartialEq, Eq)]
55 pub enum AstFragmentKind {
60 impl AstFragmentKind {
61 pub fn name(self) -> &'static str {
63 AstFragmentKind::OptExpr => "expression",
64 $(AstFragmentKind::$Kind => $kind_name,)*
68 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
70 AstFragmentKind::OptExpr =>
71 result.make_expr().map(Some).map(AstFragment::OptExpr),
72 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
78 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
80 AstFragment::OptExpr(expr) => expr,
81 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
85 $(pub fn $make_ast(self) -> $AstTy {
87 AstFragment::$Kind(ast) => ast,
88 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
92 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
94 AstFragment::OptExpr(opt_expr) => {
95 visit_clobber(opt_expr, |opt_expr| {
96 if let Some(expr) = opt_expr {
97 vis.filter_map_expr(expr)
103 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
104 $($(AstFragment::$Kind(ast) =>
105 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
109 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
111 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
112 AstFragment::OptExpr(None) => {}
113 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
114 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
115 visitor.$visit_ast_elt(ast_elt);
121 impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
122 $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
124 Some(self.make(AstFragmentKind::$Kind).$make_ast())
131 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
132 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
133 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
134 Stmts(SmallVec<[ast::Stmt; 1]>) {
135 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
137 Items(SmallVec<[P<ast::Item>; 1]>) {
138 "item"; many fn flat_map_item; fn visit_item; fn make_items;
140 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
141 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
143 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
144 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
146 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
148 many fn flat_map_foreign_item;
149 fn visit_foreign_item;
150 fn make_foreign_items;
152 Arms(SmallVec<[ast::Arm; 1]>) {
153 "match arm"; many fn flat_map_arm; fn visit_arm; fn make_arms;
155 Fields(SmallVec<[ast::Field; 1]>) {
156 "field expression"; many fn flat_map_field; fn visit_field; fn make_fields;
158 FieldPats(SmallVec<[ast::FieldPat; 1]>) {
160 many fn flat_map_field_pattern;
161 fn visit_field_pattern;
162 fn make_field_patterns;
164 GenericParams(SmallVec<[ast::GenericParam; 1]>) {
166 many fn flat_map_generic_param;
167 fn visit_generic_param;
168 fn make_generic_params;
170 Params(SmallVec<[ast::Param; 1]>) {
171 "function parameter"; many fn flat_map_param; fn visit_param; fn make_params;
173 StructFields(SmallVec<[ast::StructField; 1]>) {
175 many fn flat_map_struct_field;
176 fn visit_struct_field;
177 fn make_struct_fields;
179 Variants(SmallVec<[ast::Variant; 1]>) {
180 "variant"; many fn flat_map_variant; fn visit_variant; fn make_variants;
184 impl AstFragmentKind {
185 fn dummy(self, span: Span) -> AstFragment {
186 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
189 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
191 let mut items = items.into_iter();
193 AstFragmentKind::Arms =>
194 AstFragment::Arms(items.map(Annotatable::expect_arm).collect()),
195 AstFragmentKind::Fields =>
196 AstFragment::Fields(items.map(Annotatable::expect_field).collect()),
197 AstFragmentKind::FieldPats =>
198 AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()),
199 AstFragmentKind::GenericParams =>
200 AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()),
201 AstFragmentKind::Params =>
202 AstFragment::Params(items.map(Annotatable::expect_param).collect()),
203 AstFragmentKind::StructFields => AstFragment::StructFields(
204 items.map(Annotatable::expect_struct_field).collect()
206 AstFragmentKind::Variants =>
207 AstFragment::Variants(items.map(Annotatable::expect_variant).collect()),
208 AstFragmentKind::Items =>
209 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
210 AstFragmentKind::ImplItems =>
211 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
212 AstFragmentKind::TraitItems =>
213 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
214 AstFragmentKind::ForeignItems =>
215 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
216 AstFragmentKind::Stmts =>
217 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
218 AstFragmentKind::Expr => AstFragment::Expr(
219 items.next().expect("expected exactly one expression").expect_expr()
221 AstFragmentKind::OptExpr =>
222 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
223 AstFragmentKind::Pat | AstFragmentKind::Ty =>
224 panic!("patterns and types aren't annotatable"),
229 pub struct Invocation {
230 pub kind: InvocationKind,
231 pub fragment_kind: AstFragmentKind,
232 pub expansion_data: ExpansionData,
235 pub enum InvocationKind {
241 attr: ast::Attribute,
243 // Required for resolving derive helper attributes.
245 // We temporarily report errors for attribute macros placed after derives
252 /// "Invocation" that contains all derives from an item,
253 /// broken into multiple `Derive` invocations when expanded.
254 /// FIXME: Find a way to remove it.
262 pub fn span(&self) -> Span {
264 InvocationKind::Bang { span, .. } => *span,
265 InvocationKind::Attr { attr, .. } => attr.span,
266 InvocationKind::Derive { path, .. } => path.span,
267 InvocationKind::DeriveContainer { item, .. } => item.span(),
272 pub struct MacroExpander<'a, 'b> {
273 pub cx: &'a mut ExtCtxt<'b>,
274 monotonic: bool, // cf. `cx.monotonic_expander()`
277 impl<'a, 'b> MacroExpander<'a, 'b> {
278 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
279 MacroExpander { cx, monotonic }
282 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
283 let mut module = ModuleData {
284 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
285 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
286 FileName::Real(path) => path,
287 other => PathBuf::from(other.to_string()),
290 module.directory.pop();
291 self.cx.root_path = module.directory.clone();
292 self.cx.current_expansion.module = Rc::new(module);
294 let orig_mod_span = krate.module.inner;
296 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
299 kind: ast::ItemKind::Mod(krate.module),
300 ident: Ident::invalid(),
301 id: ast::DUMMY_NODE_ID,
302 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
306 match self.fully_expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
307 Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => {
309 krate.module = module;
312 // Resolution failed so we return an empty expansion
313 krate.attrs = vec![];
314 krate.module = ast::Mod {
315 inner: orig_mod_span,
322 self.cx.trace_macros_diag();
326 // Recursively expand all macro invocations in this AST fragment.
327 pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
328 let orig_expansion_data = self.cx.current_expansion.clone();
329 self.cx.current_expansion.depth = 0;
331 // Collect all macro invocations and replace them with placeholders.
332 let (mut fragment_with_placeholders, mut invocations)
333 = self.collect_invocations(input_fragment, &[]);
335 // Optimization: if we resolve all imports now,
336 // we'll be able to immediately resolve most of imported macros.
337 self.resolve_imports();
339 // Resolve paths in all invocations and produce output expanded fragments for them, but
340 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
341 // The output fragments also go through expansion recursively until no invocations are left.
342 // Unresolved macros produce dummy outputs as a recovery measure.
343 invocations.reverse();
344 let mut expanded_fragments = Vec::new();
345 let mut all_derive_placeholders: FxHashMap<ExpnId, Vec<_>> = FxHashMap::default();
346 let mut undetermined_invocations = Vec::new();
347 let (mut progress, mut force) = (false, !self.monotonic);
349 let invoc = if let Some(invoc) = invocations.pop() {
352 self.resolve_imports();
353 if undetermined_invocations.is_empty() { break }
354 invocations = mem::take(&mut undetermined_invocations);
355 force = !mem::replace(&mut progress, false);
359 let eager_expansion_root =
360 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
361 let res = match self.cx.resolver.resolve_macro_invocation(
362 &invoc, eager_expansion_root, force
365 Err(Indeterminate) => {
366 undetermined_invocations.push(invoc);
372 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
373 self.cx.current_expansion = invoc.expansion_data.clone();
375 // FIXME(jseyfried): Refactor out the following logic
376 let (expanded_fragment, new_invocations) = match res {
377 InvocationRes::Single(ext) => {
378 let fragment = self.expand_invoc(invoc, &ext.kind);
379 self.collect_invocations(fragment, &[])
381 InvocationRes::DeriveContainer(exts) => {
382 let (derives, item) = match invoc.kind {
383 InvocationKind::DeriveContainer { derives, item } => (derives, item),
386 if !item.derive_allowed() {
387 let attr = attr::find_by_name(item.attrs(), sym::derive)
388 .expect("`derive` attribute should exist");
389 let span = attr.span;
390 let mut err = self.cx.struct_span_err(span,
391 "`derive` may only be applied to structs, enums and unions");
392 if let ast::AttrStyle::Inner = attr.style {
393 let trait_list = derives.iter()
394 .map(|t| pprust::path_to_string(t))
395 .collect::<Vec<_>>();
396 let suggestion = format!("#[derive({})]", trait_list.join(", "));
398 span, "try an outer attribute", suggestion,
399 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
400 Applicability::MaybeIncorrect
406 let mut item = self.fully_configure(item);
407 item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
408 let mut helper_attrs = Vec::new();
409 let mut has_copy = false;
411 helper_attrs.extend(&ext.helper_attrs);
412 has_copy |= ext.is_derive_copy;
414 // Mark derive helpers inside this item as known and used.
415 // FIXME: This is a hack, derive helpers should be integrated with regular name
416 // resolution instead. For example, helpers introduced by a derive container
417 // can be in scope for all code produced by that container's expansion.
418 item.visit_with(&mut MarkAttrs(&helper_attrs));
420 self.cx.resolver.add_derives(invoc.expansion_data.id, SpecialDerives::COPY);
423 let derive_placeholders =
424 all_derive_placeholders.entry(invoc.expansion_data.id).or_default();
425 derive_placeholders.reserve(derives.len());
426 invocations.reserve(derives.len());
427 for path in derives {
428 let expn_id = ExpnId::fresh(None);
429 derive_placeholders.push(NodeId::placeholder_from_expn_id(expn_id));
430 invocations.push(Invocation {
431 kind: InvocationKind::Derive { path, item: item.clone() },
432 fragment_kind: invoc.fragment_kind,
433 expansion_data: ExpansionData {
435 ..invoc.expansion_data.clone()
439 let fragment = invoc.fragment_kind
440 .expect_from_annotatables(::std::iter::once(item));
441 self.collect_invocations(fragment, derive_placeholders)
445 if expanded_fragments.len() < depth {
446 expanded_fragments.push(Vec::new());
448 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
449 if !self.cx.ecfg.single_step {
450 invocations.extend(new_invocations.into_iter().rev());
454 self.cx.current_expansion = orig_expansion_data;
456 // Finally incorporate all the expanded macros into the input AST fragment.
457 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
458 while let Some(expanded_fragments) = expanded_fragments.pop() {
459 for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
460 let derive_placeholders =
461 all_derive_placeholders.remove(&expn_id).unwrap_or_else(Vec::new);
462 placeholder_expander.add(NodeId::placeholder_from_expn_id(expn_id),
463 expanded_fragment, derive_placeholders);
466 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
467 fragment_with_placeholders
470 fn resolve_imports(&mut self) {
472 self.cx.resolver.resolve_imports();
476 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
477 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
478 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
479 /// prepares data for resolving paths of macro invocations.
480 fn collect_invocations(&mut self, mut fragment: AstFragment, extra_placeholders: &[NodeId])
481 -> (AstFragment, Vec<Invocation>) {
482 // Resolve `$crate`s in the fragment for pretty-printing.
483 self.cx.resolver.resolve_dollar_crates();
486 let mut collector = InvocationCollector {
487 cfg: StripUnconfigured {
488 sess: self.cx.parse_sess,
489 features: self.cx.ecfg.features,
492 invocations: Vec::new(),
493 monotonic: self.monotonic,
495 fragment.mut_visit_with(&mut collector);
496 collector.invocations
499 // FIXME: Merge `extra_placeholders` into the `fragment` as regular placeholders.
501 self.cx.resolver.visit_ast_fragment_with_placeholders(
502 self.cx.current_expansion.id, &fragment, extra_placeholders);
505 (fragment, invocations)
508 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
509 let mut cfg = StripUnconfigured {
510 sess: self.cx.parse_sess,
511 features: self.cx.ecfg.features,
513 // Since the item itself has already been configured by the InvocationCollector,
514 // we know that fold result vector will contain exactly one element
516 Annotatable::Item(item) => {
517 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
519 Annotatable::TraitItem(item) => {
520 Annotatable::TraitItem(
521 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
523 Annotatable::ImplItem(item) => {
524 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
526 Annotatable::ForeignItem(item) => {
527 Annotatable::ForeignItem(
528 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
531 Annotatable::Stmt(stmt) => {
532 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
534 Annotatable::Expr(mut expr) => {
535 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
537 Annotatable::Arm(arm) => {
538 Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap())
540 Annotatable::Field(field) => {
541 Annotatable::Field(cfg.flat_map_field(field).pop().unwrap())
543 Annotatable::FieldPat(fp) => {
544 Annotatable::FieldPat(cfg.flat_map_field_pattern(fp).pop().unwrap())
546 Annotatable::GenericParam(param) => {
547 Annotatable::GenericParam(cfg.flat_map_generic_param(param).pop().unwrap())
549 Annotatable::Param(param) => {
550 Annotatable::Param(cfg.flat_map_param(param).pop().unwrap())
552 Annotatable::StructField(sf) => {
553 Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap())
555 Annotatable::Variant(v) => {
556 Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap())
561 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
562 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
563 let expn_data = self.cx.current_expansion.id.expn_data();
564 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
565 let mut err = self.cx.struct_span_err(expn_data.call_site,
566 &format!("recursion limit reached while expanding the macro `{}`",
567 expn_data.kind.descr()));
569 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
572 self.cx.trace_macros_diag();
576 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
578 InvocationKind::Bang { mac, .. } => match ext {
579 SyntaxExtensionKind::Bang(expander) => {
580 self.gate_proc_macro_expansion_kind(span, fragment_kind);
581 let tok_result = expander.expand(self.cx, span, mac.stream());
582 self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
584 SyntaxExtensionKind::LegacyBang(expander) => {
585 let prev = self.cx.current_expansion.prior_type_ascription;
586 self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
587 let tok_result = expander.expand(self.cx, span, mac.stream());
588 let result = if let Some(result) = fragment_kind.make_from(tok_result) {
592 "non-{kind} macro in {kind} position: {path}",
593 kind = fragment_kind.name(),
594 path = pprust::path_to_string(&mac.path),
596 self.cx.span_err(span, &msg);
597 self.cx.trace_macros_diag();
598 fragment_kind.dummy(span)
600 self.cx.current_expansion.prior_type_ascription = prev;
605 InvocationKind::Attr { attr, mut item, .. } => match ext {
606 SyntaxExtensionKind::Attr(expander) => {
607 self.gate_proc_macro_attr_item(span, &item);
608 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
609 Annotatable::Item(item) => token::NtItem(item),
610 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
611 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
612 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
613 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
614 Annotatable::Expr(expr) => token::NtExpr(expr),
616 | Annotatable::Field(..)
617 | Annotatable::FieldPat(..)
618 | Annotatable::GenericParam(..)
619 | Annotatable::Param(..)
620 | Annotatable::StructField(..)
621 | Annotatable::Variant(..)
622 => panic!("unexpected annotatable"),
623 })), DUMMY_SP).into();
624 let input = self.extract_proc_macro_attr_input(attr.item.tokens, span);
625 let tok_result = expander.expand(self.cx, span, input, item_tok);
626 self.parse_ast_fragment(tok_result, fragment_kind, &attr.item.path, span)
628 SyntaxExtensionKind::LegacyAttr(expander) => {
629 match attr.parse_meta(self.cx.parse_sess) {
631 let item = expander.expand(self.cx, span, &meta, item);
632 fragment_kind.expect_from_annotatables(item)
636 fragment_kind.dummy(span)
640 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
641 attr::mark_known(&attr);
643 attr::mark_used(&attr);
645 item.visit_attrs(|attrs| attrs.push(attr));
646 fragment_kind.expect_from_annotatables(iter::once(item))
650 InvocationKind::Derive { path, item } => match ext {
651 SyntaxExtensionKind::Derive(expander) |
652 SyntaxExtensionKind::LegacyDerive(expander) => {
653 if !item.derive_allowed() {
654 return fragment_kind.dummy(span);
656 let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
657 let items = expander.expand(self.cx, span, &meta, item);
658 fragment_kind.expect_from_annotatables(items)
662 InvocationKind::DeriveContainer { .. } => unreachable!()
666 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
667 let mut trees = tokens.trees();
669 Some(TokenTree::Delimited(_, _, tts)) => {
670 if trees.next().is_none() {
674 Some(TokenTree::Token(..)) => {}
675 None => return TokenStream::default(),
677 self.cx.span_err(span, "custom attribute invocations must be \
678 of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
679 followed by a delimiter token");
680 TokenStream::default()
683 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
684 let (kind, gate) = match *item {
685 Annotatable::Item(ref item) => {
687 ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
688 ItemKind::Mod(_) => ("modules", sym::proc_macro_hygiene),
692 Annotatable::TraitItem(_) => return,
693 Annotatable::ImplItem(_) => return,
694 Annotatable::ForeignItem(_) => return,
695 Annotatable::Stmt(_) |
696 Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
697 Annotatable::Stmt(_) => ("statements", sym::proc_macro_hygiene),
698 Annotatable::Expr(_) => ("expressions", sym::proc_macro_hygiene),
700 | Annotatable::Field(..)
701 | Annotatable::FieldPat(..)
702 | Annotatable::GenericParam(..)
703 | Annotatable::Param(..)
704 | Annotatable::StructField(..)
705 | Annotatable::Variant(..)
706 => panic!("unexpected annotatable"),
713 &format!("custom attributes cannot be applied to {}", kind),
717 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
718 let kind = match kind {
719 AstFragmentKind::Expr |
720 AstFragmentKind::OptExpr => "expressions",
721 AstFragmentKind::Pat => "patterns",
722 AstFragmentKind::Stmts => "statements",
723 AstFragmentKind::Ty |
724 AstFragmentKind::Items |
725 AstFragmentKind::TraitItems |
726 AstFragmentKind::ImplItems |
727 AstFragmentKind::ForeignItems => return,
728 AstFragmentKind::Arms
729 | AstFragmentKind::Fields
730 | AstFragmentKind::FieldPats
731 | AstFragmentKind::GenericParams
732 | AstFragmentKind::Params
733 | AstFragmentKind::StructFields
734 | AstFragmentKind::Variants
735 => panic!("unexpected AST fragment kind"),
737 if self.cx.ecfg.proc_macro_hygiene() {
742 sym::proc_macro_hygiene,
745 &format!("procedural macros cannot be expanded to {}", kind),
749 fn parse_ast_fragment(
752 kind: AstFragmentKind,
756 let mut parser = self.cx.new_parser_from_tts(toks);
757 match parse_ast_fragment(&mut parser, kind, false) {
759 ensure_complete_parse(&mut parser, path, kind.name(), span);
764 annotate_err_with_kind(&mut err, kind, span);
766 self.cx.trace_macros_diag();
773 pub fn parse_ast_fragment<'a>(
774 this: &mut Parser<'a>,
775 kind: AstFragmentKind,
776 macro_legacy_warnings: bool,
777 ) -> PResult<'a, AstFragment> {
779 AstFragmentKind::Items => {
780 let mut items = SmallVec::new();
781 while let Some(item) = this.parse_item()? {
784 AstFragment::Items(items)
786 AstFragmentKind::TraitItems => {
787 let mut items = SmallVec::new();
788 while this.token != token::Eof {
789 items.push(this.parse_trait_item(&mut false)?);
791 AstFragment::TraitItems(items)
793 AstFragmentKind::ImplItems => {
794 let mut items = SmallVec::new();
795 while this.token != token::Eof {
796 items.push(this.parse_impl_item(&mut false)?);
798 AstFragment::ImplItems(items)
800 AstFragmentKind::ForeignItems => {
801 let mut items = SmallVec::new();
802 while this.token != token::Eof {
803 items.push(this.parse_foreign_item(DUMMY_SP)?);
805 AstFragment::ForeignItems(items)
807 AstFragmentKind::Stmts => {
808 let mut stmts = SmallVec::new();
809 while this.token != token::Eof &&
810 // won't make progress on a `}`
811 this.token != token::CloseDelim(token::Brace) {
812 if let Some(stmt) = this.parse_full_stmt(macro_legacy_warnings)? {
816 AstFragment::Stmts(stmts)
818 AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
819 AstFragmentKind::OptExpr => {
820 if this.token != token::Eof {
821 AstFragment::OptExpr(Some(this.parse_expr()?))
823 AstFragment::OptExpr(None)
826 AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
827 AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?),
828 AstFragmentKind::Arms
829 | AstFragmentKind::Fields
830 | AstFragmentKind::FieldPats
831 | AstFragmentKind::GenericParams
832 | AstFragmentKind::Params
833 | AstFragmentKind::StructFields
834 | AstFragmentKind::Variants
835 => panic!("unexpected AST fragment kind"),
839 pub fn ensure_complete_parse<'a>(
840 this: &mut Parser<'a>,
845 if this.token != token::Eof {
846 let msg = format!("macro expansion ignores token `{}` and any following",
847 this.this_token_to_string());
848 // Avoid emitting backtrace info twice.
849 let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
850 let mut err = this.struct_span_err(def_site_span, &msg);
851 err.span_label(span, "caused by the macro expansion here");
853 "the usage of `{}!` is likely invalid in {} context",
854 pprust::path_to_string(macro_path),
858 let semi_span = this.sess.source_map().next_point(span);
860 let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
861 match this.sess.source_map().span_to_snippet(semi_full_span) {
862 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
865 "you might be missing a semicolon here",
867 Applicability::MaybeIncorrect,
876 struct InvocationCollector<'a, 'b> {
877 cx: &'a mut ExtCtxt<'b>,
878 cfg: StripUnconfigured<'a>,
879 invocations: Vec<Invocation>,
883 impl<'a, 'b> InvocationCollector<'a, 'b> {
884 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
885 // Expansion data for all the collected invocations is set upon their resolution,
886 // with exception of the derive container case which is not resolved and can get
887 // its expansion data immediately.
888 let expn_data = match &kind {
889 InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
890 parent: self.cx.current_expansion.id,
892 ExpnKind::Macro(MacroKind::Attr, sym::derive),
893 item.span(), self.cx.parse_sess.edition,
898 let expn_id = ExpnId::fresh(expn_data);
899 self.invocations.push(Invocation {
902 expansion_data: ExpansionData {
904 depth: self.cx.current_expansion.depth + 1,
905 ..self.cx.current_expansion.clone()
908 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
911 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
912 self.collect(kind, InvocationKind::Bang { mac, span })
915 fn collect_attr(&mut self,
916 attr: Option<ast::Attribute>,
919 kind: AstFragmentKind,
922 self.collect(kind, match attr {
923 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
924 None => InvocationKind::DeriveContainer { derives, item },
928 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
929 -> Option<ast::Attribute> {
930 let attr = attrs.iter()
932 if a.path == sym::derive {
933 *after_derive = true;
935 !attr::is_known(a) && !is_builtin_attr(a)
937 .map(|i| attrs.remove(i));
938 if let Some(attr) = &attr {
939 if !self.cx.ecfg.custom_inner_attributes() &&
940 attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
941 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
942 attr.span, GateIssue::Language,
943 "non-builtin inner attributes are unstable");
949 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
950 fn classify_item<T>(&mut self, item: &mut T)
951 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
954 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
956 item.visit_attrs(|mut attrs| {
957 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
958 traits = collect_derives(&mut self.cx, &mut attrs);
961 (attr, traits, after_derive)
964 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
965 /// to the unused-attributes lint (making it an error on statements and expressions
966 /// is a breaking change)
967 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
968 -> (Option<ast::Attribute>, /* after_derive */ bool) {
969 let (mut attr, mut after_derive) = (None, false);
971 nonitem.visit_attrs(|mut attrs| {
972 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
978 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
979 self.cfg.configure(node)
982 // Detect use of feature-gated or invalid attributes on macro invocations
983 // since they will not be detected after macro expansion.
984 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
985 let features = self.cx.ecfg.features.unwrap();
986 for attr in attrs.iter() {
987 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
989 // macros are expanded before any lint passes so this warning has to be hardcoded
990 if attr.path == sym::derive {
991 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
992 .note("this may become a hard error in a future release")
999 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1000 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1001 self.cfg.configure_expr(expr);
1002 visit_clobber(expr.deref_mut(), |mut expr| {
1003 self.cfg.configure_expr_kind(&mut expr.kind);
1005 // ignore derives so they remain unused
1006 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1009 // Collect the invoc regardless of whether or not attributes are permitted here
1010 // expansion will eat the attribute so it won't error later.
1011 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1013 // AstFragmentKind::Expr requires the macro to emit an expression.
1014 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1015 AstFragmentKind::Expr, after_derive)
1020 if let ast::ExprKind::Mac(mac) = expr.kind {
1021 self.check_attributes(&expr.attrs);
1022 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1026 noop_visit_expr(&mut expr, self);
1032 fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1033 let mut arm = configure!(self, arm);
1035 let (attr, traits, after_derive) = self.classify_item(&mut arm);
1036 if attr.is_some() || !traits.is_empty() {
1037 return self.collect_attr(attr, traits, Annotatable::Arm(arm),
1038 AstFragmentKind::Arms, after_derive)
1042 noop_flat_map_arm(arm, self)
1045 fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1046 let mut field = configure!(self, field);
1048 let (attr, traits, after_derive) = self.classify_item(&mut field);
1049 if attr.is_some() || !traits.is_empty() {
1050 return self.collect_attr(attr, traits, Annotatable::Field(field),
1051 AstFragmentKind::Fields, after_derive)
1055 noop_flat_map_field(field, self)
1058 fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1059 let mut fp = configure!(self, fp);
1061 let (attr, traits, after_derive) = self.classify_item(&mut fp);
1062 if attr.is_some() || !traits.is_empty() {
1063 return self.collect_attr(attr, traits, Annotatable::FieldPat(fp),
1064 AstFragmentKind::FieldPats, after_derive)
1065 .make_field_patterns();
1068 noop_flat_map_field_pattern(fp, self)
1071 fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1072 let mut p = configure!(self, p);
1074 let (attr, traits, after_derive) = self.classify_item(&mut p);
1075 if attr.is_some() || !traits.is_empty() {
1076 return self.collect_attr(attr, traits, Annotatable::Param(p),
1077 AstFragmentKind::Params, after_derive)
1081 noop_flat_map_param(p, self)
1084 fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1085 let mut sf = configure!(self, sf);
1087 let (attr, traits, after_derive) = self.classify_item(&mut sf);
1088 if attr.is_some() || !traits.is_empty() {
1089 return self.collect_attr(attr, traits, Annotatable::StructField(sf),
1090 AstFragmentKind::StructFields, after_derive)
1091 .make_struct_fields();
1094 noop_flat_map_struct_field(sf, self)
1097 fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1098 let mut variant = configure!(self, variant);
1100 let (attr, traits, after_derive) = self.classify_item(&mut variant);
1101 if attr.is_some() || !traits.is_empty() {
1102 return self.collect_attr(attr, traits, Annotatable::Variant(variant),
1103 AstFragmentKind::Variants, after_derive)
1107 noop_flat_map_variant(variant, self)
1110 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1111 let expr = configure!(self, expr);
1112 expr.filter_map(|mut expr| {
1113 self.cfg.configure_expr_kind(&mut expr.kind);
1115 // Ignore derives so they remain unused.
1116 let (attr, after_derive) = self.classify_nonitem(&mut expr);
1119 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1121 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1122 AstFragmentKind::OptExpr, after_derive)
1124 .map(|expr| expr.into_inner())
1127 if let ast::ExprKind::Mac(mac) = expr.kind {
1128 self.check_attributes(&expr.attrs);
1129 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1131 .map(|expr| expr.into_inner())
1133 Some({ noop_visit_expr(&mut expr, self); expr })
1138 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1139 self.cfg.configure_pat(pat);
1141 PatKind::Mac(_) => {}
1142 _ => return noop_visit_pat(pat, self),
1145 visit_clobber(pat, |mut pat| {
1146 match mem::replace(&mut pat.kind, PatKind::Wild) {
1147 PatKind::Mac(mac) =>
1148 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1149 _ => unreachable!(),
1154 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1155 let mut stmt = configure!(self, stmt);
1157 // we'll expand attributes on expressions separately
1158 if !stmt.is_expr() {
1159 let (attr, derives, after_derive) = if stmt.is_item() {
1160 self.classify_item(&mut stmt)
1162 // ignore derives on non-item statements so it falls through
1163 // to the unused-attributes lint
1164 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1165 (attr, vec![], after_derive)
1168 if attr.is_some() || !derives.is_empty() {
1169 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1170 AstFragmentKind::Stmts, after_derive).make_stmts();
1174 if let StmtKind::Mac(mac) = stmt.kind {
1175 let (mac, style, attrs) = mac.into_inner();
1176 self.check_attributes(&attrs);
1177 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1180 // If this is a macro invocation with a semicolon, then apply that
1181 // semicolon to the final statement produced by expansion.
1182 if style == MacStmtStyle::Semicolon {
1183 if let Some(stmt) = placeholder.pop() {
1184 placeholder.push(stmt.add_trailing_semicolon());
1191 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1192 let ast::Stmt { id, kind, span } = stmt;
1193 noop_flat_map_stmt_kind(kind, self).into_iter().map(|kind| {
1194 ast::Stmt { id, kind, span }
1199 fn visit_block(&mut self, block: &mut P<Block>) {
1200 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1201 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1202 noop_visit_block(block, self);
1203 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1206 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1207 let mut item = configure!(self, item);
1209 let (attr, traits, after_derive) = self.classify_item(&mut item);
1210 if attr.is_some() || !traits.is_empty() {
1211 return self.collect_attr(attr, traits, Annotatable::Item(item),
1212 AstFragmentKind::Items, after_derive).make_items();
1216 ast::ItemKind::Mac(..) => {
1217 self.check_attributes(&item.attrs);
1218 item.and_then(|item| match item.kind {
1219 ItemKind::Mac(mac) => self.collect(
1220 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1222 _ => unreachable!(),
1225 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1226 if item.ident == Ident::invalid() {
1227 return noop_flat_map_item(item, self);
1230 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1231 let mut module = (*self.cx.current_expansion.module).clone();
1232 module.mod_path.push(item.ident);
1234 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1235 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1236 // Thus, if `inner` is the dummy span, we know the module is inline.
1237 let inline_module = item.span.contains(inner) || inner.is_dummy();
1240 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1241 self.cx.current_expansion.directory_ownership =
1242 DirectoryOwnership::Owned { relative: None };
1243 module.directory.push(&*path.as_str());
1245 module.directory.push(&*item.ident.as_str());
1248 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1249 let mut path = match path {
1250 FileName::Real(path) => path,
1251 other => PathBuf::from(other.to_string()),
1253 let directory_ownership = match path.file_name().unwrap().to_str() {
1254 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1255 Some(_) => DirectoryOwnership::Owned {
1256 relative: Some(item.ident),
1258 None => DirectoryOwnership::UnownedViaMod(false),
1261 module.directory = path;
1262 self.cx.current_expansion.directory_ownership = directory_ownership;
1266 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1267 let result = noop_flat_map_item(item, self);
1268 self.cx.current_expansion.module = orig_module;
1269 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1273 _ => noop_flat_map_item(item, self),
1277 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1278 let mut item = configure!(self, item);
1280 let (attr, traits, after_derive) = self.classify_item(&mut item);
1281 if attr.is_some() || !traits.is_empty() {
1282 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1283 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1287 ast::TraitItemKind::Macro(mac) => {
1288 let ast::TraitItem { attrs, span, .. } = item;
1289 self.check_attributes(&attrs);
1290 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1292 _ => noop_flat_map_trait_item(item, self),
1296 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1297 let mut item = configure!(self, item);
1299 let (attr, traits, after_derive) = self.classify_item(&mut item);
1300 if attr.is_some() || !traits.is_empty() {
1301 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1302 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1306 ast::ImplItemKind::Macro(mac) => {
1307 let ast::ImplItem { attrs, span, .. } = item;
1308 self.check_attributes(&attrs);
1309 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1311 _ => noop_flat_map_impl_item(item, self),
1315 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1317 ast::TyKind::Mac(_) => {}
1318 _ => return noop_visit_ty(ty, self),
1321 visit_clobber(ty, |mut ty| {
1322 match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1323 ast::TyKind::Mac(mac) =>
1324 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1325 _ => unreachable!(),
1330 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1331 self.cfg.configure_foreign_mod(foreign_mod);
1332 noop_visit_foreign_mod(foreign_mod, self);
1335 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1336 -> SmallVec<[ast::ForeignItem; 1]>
1338 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1340 if attr.is_some() || !traits.is_empty() {
1341 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1342 AstFragmentKind::ForeignItems, after_derive)
1343 .make_foreign_items();
1346 if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind {
1347 self.check_attributes(&foreign_item.attrs);
1348 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1349 .make_foreign_items();
1352 noop_flat_map_foreign_item(foreign_item, self)
1355 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1357 ast::ItemKind::MacroDef(..) => {}
1359 self.cfg.configure_item_kind(item);
1360 noop_visit_item_kind(item, self);
1365 fn flat_map_generic_param(
1367 param: ast::GenericParam
1368 ) -> SmallVec<[ast::GenericParam; 1]>
1370 let mut param = configure!(self, param);
1372 let (attr, traits, after_derive) = self.classify_item(&mut param);
1373 if attr.is_some() || !traits.is_empty() {
1374 return self.collect_attr(attr, traits, Annotatable::GenericParam(param),
1375 AstFragmentKind::GenericParams, after_derive)
1376 .make_generic_params();
1379 noop_flat_map_generic_param(param, self)
1382 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1383 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1384 // contents="file contents")]` attributes
1385 if !at.check_name(sym::doc) {
1386 return noop_visit_attribute(at, self);
1389 if let Some(list) = at.meta_item_list() {
1390 if !list.iter().any(|it| it.check_name(sym::include)) {
1391 return noop_visit_attribute(at, self);
1394 let mut items = vec![];
1396 for mut it in list {
1397 if !it.check_name(sym::include) {
1398 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1402 if let Some(file) = it.value_str() {
1403 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1404 self.check_attributes(slice::from_ref(at));
1405 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1406 // avoid loading the file if they haven't enabled the feature
1407 return noop_visit_attribute(at, self);
1410 let filename = self.cx.resolve_path(&*file.as_str(), it.span());
1411 match self.cx.source_map().load_file(&filename) {
1412 Ok(source_file) => {
1413 let src = source_file.src.as_ref()
1414 .expect("freshly loaded file should have a source");
1415 let src_interned = Symbol::intern(src.as_str());
1417 let include_info = vec![
1418 ast::NestedMetaItem::MetaItem(
1419 attr::mk_name_value_item_str(
1420 Ident::with_dummy_span(sym::file),
1425 ast::NestedMetaItem::MetaItem(
1426 attr::mk_name_value_item_str(
1427 Ident::with_dummy_span(sym::contents),
1434 let include_ident = Ident::with_dummy_span(sym::include);
1435 let item = attr::mk_list_item(include_ident, include_info);
1436 items.push(ast::NestedMetaItem::MetaItem(item));
1441 .and_then(|item| item.name_value_literal())
1444 if e.kind() == ErrorKind::InvalidData {
1448 &format!("{} wasn't a utf-8 file", filename.display()),
1450 .span_label(lit.span, "contains invalid utf-8")
1453 let mut err = self.cx.struct_span_err(
1455 &format!("couldn't read {}: {}", filename.display(), e),
1457 err.span_label(lit.span, "couldn't read file");
1464 let mut err = self.cx.struct_span_err(
1466 &format!("expected path to external documentation"),
1469 // Check if the user erroneously used `doc(include(...))` syntax.
1470 let literal = it.meta_item_list().and_then(|list| {
1471 if list.len() == 1 {
1472 list[0].literal().map(|literal| &literal.kind)
1478 let (path, applicability) = match &literal {
1479 Some(LitKind::Str(path, ..)) => {
1480 (path.to_string(), Applicability::MachineApplicable)
1482 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1485 err.span_suggestion(
1487 "provide a file path with `=`",
1488 format!("include = \"{}\"", path),
1496 let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1497 *at = attr::Attribute {
1498 item: AttrItem { path: meta.path, tokens: meta.kind.tokens(meta.span) },
1502 is_sugared_doc: false,
1505 noop_visit_attribute(at, self)
1509 fn visit_id(&mut self, id: &mut ast::NodeId) {
1511 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1512 *id = self.cx.resolver.next_node_id()
1516 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1517 self.cfg.configure_fn_decl(&mut fn_decl);
1518 noop_visit_fn_decl(fn_decl, self);
1522 pub struct ExpansionConfig<'feat> {
1523 pub crate_name: String,
1524 pub features: Option<&'feat Features>,
1525 pub recursion_limit: usize,
1526 pub trace_mac: bool,
1527 pub should_test: bool, // If false, strip `#[test]` nodes
1528 pub single_step: bool,
1529 pub keep_macs: bool,
1532 impl<'feat> ExpansionConfig<'feat> {
1533 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1537 recursion_limit: 1024,
1545 fn proc_macro_hygiene(&self) -> bool {
1546 self.features.map_or(false, |features| features.proc_macro_hygiene)
1548 fn custom_inner_attributes(&self) -> bool {
1549 self.features.map_or(false, |features| features.custom_inner_attributes)