]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/macros.rs
builtin_macros: Add attribute macro `#[cfg_accessible(path)]`
[rust.git] / src / librustc_resolve / macros.rs
1 //! A bunch of methods and structures more or less related to resolving macros and
2 //! interface provided by `Resolver` to macro expander.
3
4 use crate::imports::ImportResolver;
5 use crate::Namespace::*;
6 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, Determinacy};
7 use crate::{CrateLint, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Weak};
8 use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment, ToNameBinding};
9 use rustc::middle::stability;
10 use rustc::session::parse::feature_err;
11 use rustc::session::Session;
12 use rustc::{lint, span_bug, ty};
13 use rustc_ast::ast::{self, Ident, NodeId};
14 use rustc_ast_pretty::pprust;
15 use rustc_attr::{self as attr, StabilityLevel};
16 use rustc_data_structures::fx::FxHashSet;
17 use rustc_expand::base::SyntaxExtension;
18 use rustc_expand::base::{self, Indeterminate, InvocationRes};
19 use rustc_expand::compile_declarative_macro;
20 use rustc_expand::expand::{AstFragment, AstFragmentKind, Invocation, InvocationKind};
21 use rustc_feature::is_builtin_attr_name;
22 use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
23 use rustc_hir::def_id;
24 use rustc_span::edition::Edition;
25 use rustc_span::hygiene::{self, ExpnData, ExpnId, ExpnKind};
26 use rustc_span::symbol::{kw, sym, Symbol};
27 use rustc_span::{Span, DUMMY_SP};
28
29 use rustc_data_structures::sync::Lrc;
30 use rustc_span::hygiene::{AstPass, MacroKind};
31 use std::{mem, ptr};
32
33 type Res = def::Res<NodeId>;
34
35 /// Binding produced by a `macro_rules` item.
36 /// Not modularized, can shadow previous legacy bindings, etc.
37 #[derive(Debug)]
38 pub struct LegacyBinding<'a> {
39     crate binding: &'a NameBinding<'a>,
40     /// Legacy scope into which the `macro_rules` item was planted.
41     crate parent_legacy_scope: LegacyScope<'a>,
42     crate ident: Ident,
43 }
44
45 /// The scope introduced by a `macro_rules!` macro.
46 /// This starts at the macro's definition and ends at the end of the macro's parent
47 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
48 /// Some macro invocations need to introduce legacy scopes too because they
49 /// can potentially expand into macro definitions.
50 #[derive(Copy, Clone, Debug)]
51 pub enum LegacyScope<'a> {
52     /// Empty "root" scope at the crate start containing no names.
53     Empty,
54     /// The scope introduced by a `macro_rules!` macro definition.
55     Binding(&'a LegacyBinding<'a>),
56     /// The scope introduced by a macro invocation that can potentially
57     /// create a `macro_rules!` macro definition.
58     Invocation(ExpnId),
59 }
60
61 // Macro namespace is separated into two sub-namespaces, one for bang macros and
62 // one for attribute-like macros (attributes, derives).
63 // We ignore resolutions from one sub-namespace when searching names in scope for another.
64 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
65     #[derive(PartialEq)]
66     enum SubNS {
67         Bang,
68         AttrLike,
69     }
70     let sub_ns = |kind| match kind {
71         MacroKind::Bang => SubNS::Bang,
72         MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
73     };
74     let candidate = candidate.map(sub_ns);
75     let requirement = requirement.map(sub_ns);
76     // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
77     candidate.is_none() || requirement.is_none() || candidate == requirement
78 }
79
80 // We don't want to format a path using pretty-printing,
81 // `format!("{}", path)`, because that tries to insert
82 // line-breaks and is slow.
83 fn fast_print_path(path: &ast::Path) -> Symbol {
84     if path.segments.len() == 1 {
85         return path.segments[0].ident.name;
86     } else {
87         let mut path_str = String::with_capacity(64);
88         for (i, segment) in path.segments.iter().enumerate() {
89             if i != 0 {
90                 path_str.push_str("::");
91             }
92             if segment.ident.name != kw::PathRoot {
93                 path_str.push_str(&segment.ident.as_str())
94             }
95         }
96         Symbol::intern(&path_str)
97     }
98 }
99
100 /// The code common between processing `#![register_tool]` and `#![register_attr]`.
101 fn registered_idents(
102     sess: &Session,
103     attrs: &[ast::Attribute],
104     attr_name: Symbol,
105     descr: &str,
106 ) -> FxHashSet<Ident> {
107     let mut registered = FxHashSet::default();
108     for attr in attr::filter_by_name(attrs, attr_name) {
109         for nested_meta in attr.meta_item_list().unwrap_or_default() {
110             match nested_meta.ident() {
111                 Some(ident) => {
112                     if let Some(old_ident) = registered.replace(ident) {
113                         let msg = format!("{} `{}` was already registered", descr, ident);
114                         sess.struct_span_err(ident.span, &msg)
115                             .span_label(old_ident.span, "already registered here")
116                             .emit();
117                     }
118                 }
119                 None => {
120                     let msg = format!("`{}` only accepts identifiers", attr_name);
121                     let span = nested_meta.span();
122                     sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
123                 }
124             }
125         }
126     }
127     registered
128 }
129
130 crate fn registered_attrs_and_tools(
131     sess: &Session,
132     attrs: &[ast::Attribute],
133 ) -> (FxHashSet<Ident>, FxHashSet<Ident>) {
134     let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute");
135     let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool");
136     // We implicitly add `rustfmt` and `clippy` to known tools,
137     // but it's not an error to register them explicitly.
138     let predefined_tools = [sym::clippy, sym::rustfmt];
139     registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
140     (registered_attrs, registered_tools)
141 }
142
143 impl<'a> base::Resolver for Resolver<'a> {
144     fn next_node_id(&mut self) -> NodeId {
145         self.next_node_id()
146     }
147
148     fn resolve_dollar_crates(&mut self) {
149         hygiene::update_dollar_crate_names(|ctxt| {
150             let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
151             match self.resolve_crate_root(ident).kind {
152                 ModuleKind::Def(.., name) if name != kw::Invalid => name,
153                 _ => kw::Crate,
154             }
155         });
156     }
157
158     fn visit_ast_fragment_with_placeholders(&mut self, expansion: ExpnId, fragment: &AstFragment) {
159         // Integrate the new AST fragment into all the definition and module structures.
160         // We are inside the `expansion` now, but other parent scope components are still the same.
161         let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
162         let output_legacy_scope = self.build_reduced_graph(fragment, parent_scope);
163         self.output_legacy_scopes.insert(expansion, output_legacy_scope);
164
165         parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
166     }
167
168     fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension) {
169         if self.builtin_macros.insert(ident.name, ext).is_some() {
170             self.session
171                 .span_err(ident.span, &format!("built-in macro `{}` was already defined", ident));
172         }
173     }
174
175     // Create a new Expansion with a definition site of the provided module, or
176     // a fake empty `#[no_implicit_prelude]` module if no module is provided.
177     fn expansion_for_ast_pass(
178         &mut self,
179         call_site: Span,
180         pass: AstPass,
181         features: &[Symbol],
182         parent_module_id: Option<NodeId>,
183     ) -> ExpnId {
184         let expn_id = ExpnId::fresh(Some(ExpnData::allow_unstable(
185             ExpnKind::AstPass(pass),
186             call_site,
187             self.session.edition(),
188             features.into(),
189         )));
190
191         let parent_scope = if let Some(module_id) = parent_module_id {
192             let parent_def_id = self.definitions.local_def_id(module_id);
193             self.definitions.add_parent_module_of_macro_def(expn_id, parent_def_id);
194             self.module_map[&parent_def_id]
195         } else {
196             self.definitions.add_parent_module_of_macro_def(
197                 expn_id,
198                 def_id::DefId::local(def_id::CRATE_DEF_INDEX),
199             );
200             self.empty_module
201         };
202         self.ast_transform_scopes.insert(expn_id, parent_scope);
203         expn_id
204     }
205
206     fn resolve_imports(&mut self) {
207         ImportResolver { r: self }.resolve_imports()
208     }
209
210     fn resolve_macro_invocation(
211         &mut self,
212         invoc: &Invocation,
213         eager_expansion_root: ExpnId,
214         force: bool,
215     ) -> Result<InvocationRes, Indeterminate> {
216         let invoc_id = invoc.expansion_data.id;
217         let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
218             Some(parent_scope) => *parent_scope,
219             None => {
220                 // If there's no entry in the table, then we are resolving an eagerly expanded
221                 // macro, which should inherit its parent scope from its eager expansion root -
222                 // the macro that requested this eager expansion.
223                 let parent_scope = *self
224                     .invocation_parent_scopes
225                     .get(&eager_expansion_root)
226                     .expect("non-eager expansion without a parent scope");
227                 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
228                 parent_scope
229             }
230         };
231
232         let (path, kind, derives, after_derive) = match invoc.kind {
233             InvocationKind::Attr { ref attr, ref derives, after_derive, .. } => (
234                 &attr.get_normal_item().path,
235                 MacroKind::Attr,
236                 self.arenas.alloc_ast_paths(derives),
237                 after_derive,
238             ),
239             InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, &[][..], false),
240             InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, &[][..], false),
241             InvocationKind::DeriveContainer { ref derives, .. } => {
242                 // Block expansion of the container until we resolve all derives in it.
243                 // This is required for two reasons:
244                 // - Derive helper attributes are in scope for the item to which the `#[derive]`
245                 //   is applied, so they have to be produced by the container's expansion rather
246                 //   than by individual derives.
247                 // - Derives in the container need to know whether one of them is a built-in `Copy`.
248                 // FIXME: Try to avoid repeated resolutions for derives here and in expansion.
249                 let mut exts = Vec::new();
250                 let mut helper_attrs = Vec::new();
251                 for path in derives {
252                     exts.push(
253                         match self.resolve_macro_path(
254                             path,
255                             Some(MacroKind::Derive),
256                             &parent_scope,
257                             true,
258                             force,
259                         ) {
260                             Ok((Some(ext), _)) => {
261                                 let span = path.segments.last().unwrap().ident.span.modern();
262                                 helper_attrs.extend(
263                                     ext.helper_attrs.iter().map(|name| Ident::new(*name, span)),
264                                 );
265                                 if ext.is_derive_copy {
266                                     self.add_derive_copy(invoc_id);
267                                 }
268                                 ext
269                             }
270                             Ok(_) | Err(Determinacy::Determined) => {
271                                 self.dummy_ext(MacroKind::Derive)
272                             }
273                             Err(Determinacy::Undetermined) => return Err(Indeterminate),
274                         },
275                     )
276                 }
277                 self.helper_attrs.insert(invoc_id, helper_attrs);
278                 return Ok(InvocationRes::DeriveContainer(exts));
279             }
280         };
281
282         // Derives are not included when `invocations` are collected, so we have to add them here.
283         let parent_scope = &ParentScope { derives, ..parent_scope };
284         let (ext, res) = self.smart_resolve_macro_path(path, kind, parent_scope, force)?;
285
286         let span = invoc.span();
287         invoc_id.set_expn_data(ext.expn_data(parent_scope.expansion, span, fast_print_path(path)));
288
289         if let Res::Def(_, def_id) = res {
290             if after_derive {
291                 self.session.span_err(span, "macro attributes must be placed before `#[derive]`");
292             }
293             self.macro_defs.insert(invoc_id, def_id);
294             let normal_module_def_id = self.macro_def_scope(invoc_id).normal_ancestor_id;
295             self.definitions.add_parent_module_of_macro_def(invoc_id, normal_module_def_id);
296         }
297
298         match invoc.fragment_kind {
299             AstFragmentKind::Arms
300             | AstFragmentKind::Fields
301             | AstFragmentKind::FieldPats
302             | AstFragmentKind::GenericParams
303             | AstFragmentKind::Params
304             | AstFragmentKind::StructFields
305             | AstFragmentKind::Variants => {
306                 if let Res::Def(..) = res {
307                     self.session.span_err(
308                         span,
309                         &format!(
310                             "expected an inert attribute, found {} {}",
311                             res.article(),
312                             res.descr()
313                         ),
314                     );
315                     return Ok(InvocationRes::Single(self.dummy_ext(kind)));
316                 }
317             }
318             _ => {}
319         }
320
321         Ok(InvocationRes::Single(ext))
322     }
323
324     fn check_unused_macros(&mut self) {
325         for (&node_id, &span) in self.unused_macros.iter() {
326             self.lint_buffer.buffer_lint(
327                 lint::builtin::UNUSED_MACROS,
328                 node_id,
329                 span,
330                 "unused macro definition",
331             );
332         }
333     }
334
335     fn has_derive_copy(&self, expn_id: ExpnId) -> bool {
336         self.containers_deriving_copy.contains(&expn_id)
337     }
338
339     fn add_derive_copy(&mut self, expn_id: ExpnId) {
340         self.containers_deriving_copy.insert(expn_id);
341     }
342
343     // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
344     // Returns true if the path can certainly be resolved in one of three namespaces,
345     // returns false if the path certainly cannot be resolved in any of the three namespaces.
346     // Returns `Indeterminate` if we cannot give a certain answer yet.
347     fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate> {
348         let span = path.span;
349         let path = &Segment::from_path(path);
350         let parent_scope = self.invocation_parent_scopes[&expn_id];
351
352         let mut indeterminate = false;
353         for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
354             match self.resolve_path(path, Some(ns), &parent_scope, false, span, CrateLint::No) {
355                 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
356                 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
357                     return Ok(true);
358                 }
359                 PathResult::Indeterminate => indeterminate = true,
360                 // FIXME: `resolve_path` is not ready to report partially resolved paths
361                 // correctly, so we just report an error if the path was reported as unresolved.
362                 // This needs to be fixed for `cfg_accessible` to be useful.
363                 PathResult::NonModule(..) | PathResult::Failed { .. } => {}
364                 PathResult::Module(_) => panic!("unexpected path resolution"),
365             }
366         }
367
368         if indeterminate {
369             return Err(Indeterminate);
370         }
371
372         self.session
373             .struct_span_err(span, "not sure whether the path is accessible or not")
374             .span_note(span, "`cfg_accessible` is not fully implemented")
375             .emit();
376         Ok(false)
377     }
378 }
379
380 impl<'a> Resolver<'a> {
381     /// Resolve macro path with error reporting and recovery.
382     fn smart_resolve_macro_path(
383         &mut self,
384         path: &ast::Path,
385         kind: MacroKind,
386         parent_scope: &ParentScope<'a>,
387         force: bool,
388     ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
389         let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
390         {
391             Ok((Some(ext), res)) => (ext, res),
392             // Use dummy syntax extensions for unresolved macros for better recovery.
393             Ok((None, res)) => (self.dummy_ext(kind), res),
394             Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
395             Err(Determinacy::Undetermined) => return Err(Indeterminate),
396         };
397
398         // Report errors and enforce feature gates for the resolved macro.
399         let features = self.session.features_untracked();
400         for segment in &path.segments {
401             if let Some(args) = &segment.args {
402                 self.session.span_err(args.span(), "generic arguments in macro path");
403             }
404             if kind == MacroKind::Attr
405                 && !features.rustc_attrs
406                 && segment.ident.as_str().starts_with("rustc")
407             {
408                 let msg =
409                     "attributes starting with `rustc` are reserved for use by the `rustc` compiler";
410                 feature_err(&self.session.parse_sess, sym::rustc_attrs, segment.ident.span, msg)
411                     .emit();
412             }
413         }
414
415         match res {
416             Res::Def(DefKind::Macro(_), def_id) => {
417                 if let Some(node_id) = self.definitions.as_local_node_id(def_id) {
418                     self.unused_macros.remove(&node_id);
419                     if self.proc_macro_stubs.contains(&node_id) {
420                         self.session.span_err(
421                             path.span,
422                             "can't use a procedural macro from the same crate that defines it",
423                         );
424                     }
425                 }
426             }
427             Res::NonMacroAttr(..) | Res::Err => {}
428             _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
429         };
430
431         self.check_stability_and_deprecation(&ext, path);
432
433         Ok(if ext.macro_kind() != kind {
434             let expected = kind.descr_expected();
435             let path_str = pprust::path_to_string(path);
436             let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
437             self.session
438                 .struct_span_err(path.span, &msg)
439                 .span_label(path.span, format!("not {} {}", kind.article(), expected))
440                 .emit();
441             // Use dummy syntax extensions for unexpected macro kinds for better recovery.
442             (self.dummy_ext(kind), Res::Err)
443         } else {
444             (ext, res)
445         })
446     }
447
448     pub fn resolve_macro_path(
449         &mut self,
450         path: &ast::Path,
451         kind: Option<MacroKind>,
452         parent_scope: &ParentScope<'a>,
453         trace: bool,
454         force: bool,
455     ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
456         let path_span = path.span;
457         let mut path = Segment::from_path(path);
458
459         // Possibly apply the macro helper hack
460         if kind == Some(MacroKind::Bang)
461             && path.len() == 1
462             && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
463         {
464             let root = Ident::new(kw::DollarCrate, path[0].ident.span);
465             path.insert(0, Segment::from_ident(root));
466         }
467
468         let res = if path.len() > 1 {
469             let res = match self.resolve_path(
470                 &path,
471                 Some(MacroNS),
472                 parent_scope,
473                 false,
474                 path_span,
475                 CrateLint::No,
476             ) {
477                 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
478                     Ok(path_res.base_res())
479                 }
480                 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
481                 PathResult::NonModule(..)
482                 | PathResult::Indeterminate
483                 | PathResult::Failed { .. } => Err(Determinacy::Determined),
484                 PathResult::Module(..) => unreachable!(),
485             };
486
487             if trace {
488                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
489                 self.multi_segment_macro_resolutions.push((
490                     path,
491                     path_span,
492                     kind,
493                     *parent_scope,
494                     res.ok(),
495                 ));
496             }
497
498             self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
499             res
500         } else {
501             let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
502             let binding = self.early_resolve_ident_in_lexical_scope(
503                 path[0].ident,
504                 scope_set,
505                 parent_scope,
506                 false,
507                 force,
508                 path_span,
509             );
510             if let Err(Determinacy::Undetermined) = binding {
511                 return Err(Determinacy::Undetermined);
512             }
513
514             if trace {
515                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
516                 self.single_segment_macro_resolutions.push((
517                     path[0].ident,
518                     kind,
519                     *parent_scope,
520                     binding.ok(),
521                 ));
522             }
523
524             let res = binding.map(|binding| binding.res());
525             self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
526             res
527         };
528
529         res.map(|res| (self.get_macro(res), res))
530     }
531
532     // Resolve an identifier in lexical scope.
533     // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
534     // expansion and import resolution (perhaps they can be merged in the future).
535     // The function is used for resolving initial segments of macro paths (e.g., `foo` in
536     // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
537     crate fn early_resolve_ident_in_lexical_scope(
538         &mut self,
539         orig_ident: Ident,
540         scope_set: ScopeSet,
541         parent_scope: &ParentScope<'a>,
542         record_used: bool,
543         force: bool,
544         path_span: Span,
545     ) -> Result<&'a NameBinding<'a>, Determinacy> {
546         bitflags::bitflags! {
547             struct Flags: u8 {
548                 const MACRO_RULES          = 1 << 0;
549                 const MODULE               = 1 << 1;
550                 const DERIVE_HELPER_COMPAT = 1 << 2;
551                 const MISC_SUGGEST_CRATE   = 1 << 3;
552                 const MISC_SUGGEST_SELF    = 1 << 4;
553                 const MISC_FROM_PRELUDE    = 1 << 5;
554             }
555         }
556
557         assert!(force || !record_used); // `record_used` implies `force`
558
559         // Make sure `self`, `super` etc produce an error when passed to here.
560         if orig_ident.is_path_segment_keyword() {
561             return Err(Determinacy::Determined);
562         }
563
564         let (ns, macro_kind, is_import) = match scope_set {
565             ScopeSet::All(ns, is_import) => (ns, None, is_import),
566             ScopeSet::AbsolutePath(ns) => (ns, None, false),
567             ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
568         };
569
570         // This is *the* result, resolution from the scope closest to the resolved identifier.
571         // However, sometimes this result is "weak" because it comes from a glob import or
572         // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
573         // mod m { ... } // solution in outer scope
574         // {
575         //     use prefix::*; // imports another `m` - innermost solution
576         //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
577         //     m::mac!();
578         // }
579         // So we have to save the innermost solution and continue searching in outer scopes
580         // to detect potential ambiguities.
581         let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
582         let mut determinacy = Determinacy::Determined;
583
584         // Go through all the scopes and try to resolve the name.
585         let break_result = self.visit_scopes(
586             scope_set,
587             parent_scope,
588             orig_ident,
589             |this, scope, use_prelude, ident| {
590                 let ok = |res, span, arenas| {
591                     Ok((
592                         (res, ty::Visibility::Public, span, ExpnId::root()).to_name_binding(arenas),
593                         Flags::empty(),
594                     ))
595                 };
596                 let result = match scope {
597                     Scope::DeriveHelpers(expn_id) => {
598                         if let Some(attr) = this
599                             .helper_attrs
600                             .get(&expn_id)
601                             .and_then(|attrs| attrs.iter().rfind(|i| ident == **i))
602                         {
603                             let binding = (
604                                 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
605                                 ty::Visibility::Public,
606                                 attr.span,
607                                 expn_id,
608                             )
609                                 .to_name_binding(this.arenas);
610                             Ok((binding, Flags::empty()))
611                         } else {
612                             Err(Determinacy::Determined)
613                         }
614                     }
615                     Scope::DeriveHelpersCompat => {
616                         let mut result = Err(Determinacy::Determined);
617                         for derive in parent_scope.derives {
618                             let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
619                             match this.resolve_macro_path(
620                                 derive,
621                                 Some(MacroKind::Derive),
622                                 parent_scope,
623                                 true,
624                                 force,
625                             ) {
626                                 Ok((Some(ext), _)) => {
627                                     if ext.helper_attrs.contains(&ident.name) {
628                                         let binding = (
629                                             Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
630                                             ty::Visibility::Public,
631                                             derive.span,
632                                             ExpnId::root(),
633                                         )
634                                             .to_name_binding(this.arenas);
635                                         result = Ok((binding, Flags::DERIVE_HELPER_COMPAT));
636                                         break;
637                                     }
638                                 }
639                                 Ok(_) | Err(Determinacy::Determined) => {}
640                                 Err(Determinacy::Undetermined) => {
641                                     result = Err(Determinacy::Undetermined)
642                                 }
643                             }
644                         }
645                         result
646                     }
647                     Scope::MacroRules(legacy_scope) => match legacy_scope {
648                         LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident => {
649                             Ok((legacy_binding.binding, Flags::MACRO_RULES))
650                         }
651                         LegacyScope::Invocation(invoc_id)
652                             if !this.output_legacy_scopes.contains_key(&invoc_id) =>
653                         {
654                             Err(Determinacy::Undetermined)
655                         }
656                         _ => Err(Determinacy::Determined),
657                     },
658                     Scope::CrateRoot => {
659                         let root_ident = Ident::new(kw::PathRoot, ident.span);
660                         let root_module = this.resolve_crate_root(root_ident);
661                         let binding = this.resolve_ident_in_module_ext(
662                             ModuleOrUniformRoot::Module(root_module),
663                             ident,
664                             ns,
665                             parent_scope,
666                             record_used,
667                             path_span,
668                         );
669                         match binding {
670                             Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
671                             Err((Determinacy::Undetermined, Weak::No)) => {
672                                 return Some(Err(Determinacy::determined(force)));
673                             }
674                             Err((Determinacy::Undetermined, Weak::Yes)) => {
675                                 Err(Determinacy::Undetermined)
676                             }
677                             Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
678                         }
679                     }
680                     Scope::Module(module) => {
681                         let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
682                         let binding = this.resolve_ident_in_module_unadjusted_ext(
683                             ModuleOrUniformRoot::Module(module),
684                             ident,
685                             ns,
686                             adjusted_parent_scope,
687                             true,
688                             record_used,
689                             path_span,
690                         );
691                         match binding {
692                             Ok(binding) => {
693                                 let misc_flags = if ptr::eq(module, this.graph_root) {
694                                     Flags::MISC_SUGGEST_CRATE
695                                 } else if module.is_normal() {
696                                     Flags::MISC_SUGGEST_SELF
697                                 } else {
698                                     Flags::empty()
699                                 };
700                                 Ok((binding, Flags::MODULE | misc_flags))
701                             }
702                             Err((Determinacy::Undetermined, Weak::No)) => {
703                                 return Some(Err(Determinacy::determined(force)));
704                             }
705                             Err((Determinacy::Undetermined, Weak::Yes)) => {
706                                 Err(Determinacy::Undetermined)
707                             }
708                             Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
709                         }
710                     }
711                     Scope::RegisteredAttrs => match this.registered_attrs.get(&ident).cloned() {
712                         Some(ident) => ok(
713                             Res::NonMacroAttr(NonMacroAttrKind::Registered),
714                             ident.span,
715                             this.arenas,
716                         ),
717                         None => Err(Determinacy::Determined),
718                     },
719                     Scope::MacroUsePrelude => {
720                         match this.macro_use_prelude.get(&ident.name).cloned() {
721                             Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)),
722                             None => Err(Determinacy::determined(
723                                 this.graph_root.unexpanded_invocations.borrow().is_empty(),
724                             )),
725                         }
726                     }
727                     Scope::BuiltinAttrs => {
728                         if is_builtin_attr_name(ident.name) {
729                             ok(Res::NonMacroAttr(NonMacroAttrKind::Builtin), DUMMY_SP, this.arenas)
730                         } else {
731                             Err(Determinacy::Determined)
732                         }
733                     }
734                     Scope::ExternPrelude => match this.extern_prelude_get(ident, !record_used) {
735                         Some(binding) => Ok((binding, Flags::empty())),
736                         None => Err(Determinacy::determined(
737                             this.graph_root.unexpanded_invocations.borrow().is_empty(),
738                         )),
739                     },
740                     Scope::ToolPrelude => match this.registered_tools.get(&ident).cloned() {
741                         Some(ident) => ok(Res::ToolMod, ident.span, this.arenas),
742                         None => Err(Determinacy::Determined),
743                     },
744                     Scope::StdLibPrelude => {
745                         let mut result = Err(Determinacy::Determined);
746                         if let Some(prelude) = this.prelude {
747                             if let Ok(binding) = this.resolve_ident_in_module_unadjusted(
748                                 ModuleOrUniformRoot::Module(prelude),
749                                 ident,
750                                 ns,
751                                 parent_scope,
752                                 false,
753                                 path_span,
754                             ) {
755                                 if use_prelude || this.is_builtin_macro(binding.res()) {
756                                     result = Ok((binding, Flags::MISC_FROM_PRELUDE));
757                                 }
758                             }
759                         }
760                         result
761                     }
762                     Scope::BuiltinTypes => {
763                         match this.primitive_type_table.primitive_types.get(&ident.name).cloned() {
764                             Some(prim_ty) => ok(Res::PrimTy(prim_ty), DUMMY_SP, this.arenas),
765                             None => Err(Determinacy::Determined),
766                         }
767                     }
768                 };
769
770                 match result {
771                     Ok((binding, flags))
772                         if sub_namespace_match(binding.macro_kind(), macro_kind) =>
773                     {
774                         if !record_used {
775                             return Some(Ok(binding));
776                         }
777
778                         if let Some((innermost_binding, innermost_flags)) = innermost_result {
779                             // Found another solution, if the first one was "weak", report an error.
780                             let (res, innermost_res) = (binding.res(), innermost_binding.res());
781                             if res != innermost_res {
782                                 let builtin = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
783                                 let is_derive_helper_compat = |res, flags: Flags| {
784                                     res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper)
785                                         && flags.contains(Flags::DERIVE_HELPER_COMPAT)
786                                 };
787
788                                 let ambiguity_error_kind = if is_import {
789                                     Some(AmbiguityKind::Import)
790                                 } else if innermost_res == builtin || res == builtin {
791                                     Some(AmbiguityKind::BuiltinAttr)
792                                 } else if is_derive_helper_compat(innermost_res, innermost_flags)
793                                     || is_derive_helper_compat(res, flags)
794                                 {
795                                     Some(AmbiguityKind::DeriveHelper)
796                                 } else if innermost_flags.contains(Flags::MACRO_RULES)
797                                     && flags.contains(Flags::MODULE)
798                                     && !this
799                                         .disambiguate_legacy_vs_modern(innermost_binding, binding)
800                                     || flags.contains(Flags::MACRO_RULES)
801                                         && innermost_flags.contains(Flags::MODULE)
802                                         && !this.disambiguate_legacy_vs_modern(
803                                             binding,
804                                             innermost_binding,
805                                         )
806                                 {
807                                     Some(AmbiguityKind::LegacyVsModern)
808                                 } else if innermost_binding.is_glob_import() {
809                                     Some(AmbiguityKind::GlobVsOuter)
810                                 } else if innermost_binding
811                                     .may_appear_after(parent_scope.expansion, binding)
812                                 {
813                                     Some(AmbiguityKind::MoreExpandedVsOuter)
814                                 } else {
815                                     None
816                                 };
817                                 if let Some(kind) = ambiguity_error_kind {
818                                     let misc = |f: Flags| {
819                                         if f.contains(Flags::MISC_SUGGEST_CRATE) {
820                                             AmbiguityErrorMisc::SuggestCrate
821                                         } else if f.contains(Flags::MISC_SUGGEST_SELF) {
822                                             AmbiguityErrorMisc::SuggestSelf
823                                         } else if f.contains(Flags::MISC_FROM_PRELUDE) {
824                                             AmbiguityErrorMisc::FromPrelude
825                                         } else {
826                                             AmbiguityErrorMisc::None
827                                         }
828                                     };
829                                     this.ambiguity_errors.push(AmbiguityError {
830                                         kind,
831                                         ident: orig_ident,
832                                         b1: innermost_binding,
833                                         b2: binding,
834                                         misc1: misc(innermost_flags),
835                                         misc2: misc(flags),
836                                     });
837                                     return Some(Ok(innermost_binding));
838                                 }
839                             }
840                         } else {
841                             // Found the first solution.
842                             innermost_result = Some((binding, flags));
843                         }
844                     }
845                     Ok(..) | Err(Determinacy::Determined) => {}
846                     Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
847                 }
848
849                 None
850             },
851         );
852
853         if let Some(break_result) = break_result {
854             return break_result;
855         }
856
857         // The first found solution was the only one, return it.
858         if let Some((binding, _)) = innermost_result {
859             return Ok(binding);
860         }
861
862         Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
863     }
864
865     crate fn finalize_macro_resolutions(&mut self) {
866         let check_consistency = |this: &mut Self,
867                                  path: &[Segment],
868                                  span,
869                                  kind: MacroKind,
870                                  initial_res: Option<Res>,
871                                  res: Res| {
872             if let Some(initial_res) = initial_res {
873                 if res != initial_res && res != Res::Err && this.ambiguity_errors.is_empty() {
874                     // Make sure compilation does not succeed if preferred macro resolution
875                     // has changed after the macro had been expanded. In theory all such
876                     // situations should be reported as ambiguity errors, so this is a bug.
877                     span_bug!(span, "inconsistent resolution for a macro");
878                 }
879             } else {
880                 // It's possible that the macro was unresolved (indeterminate) and silently
881                 // expanded into a dummy fragment for recovery during expansion.
882                 // Now, post-expansion, the resolution may succeed, but we can't change the
883                 // past and need to report an error.
884                 // However, non-speculative `resolve_path` can successfully return private items
885                 // even if speculative `resolve_path` returned nothing previously, so we skip this
886                 // less informative error if the privacy error is reported elsewhere.
887                 if this.privacy_errors.is_empty() {
888                     let msg = format!(
889                         "cannot determine resolution for the {} `{}`",
890                         kind.descr(),
891                         Segment::names_to_string(path)
892                     );
893                     let msg_note = "import resolution is stuck, try simplifying macro imports";
894                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
895                 }
896             }
897         };
898
899         let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
900         for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
901             // FIXME: Path resolution will ICE if segment IDs present.
902             for seg in &mut path {
903                 seg.id = None;
904             }
905             match self.resolve_path(
906                 &path,
907                 Some(MacroNS),
908                 &parent_scope,
909                 true,
910                 path_span,
911                 CrateLint::No,
912             ) {
913                 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
914                     let res = path_res.base_res();
915                     check_consistency(self, &path, path_span, kind, initial_res, res);
916                 }
917                 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
918                     let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
919                         (span, label)
920                     } else {
921                         (
922                             path_span,
923                             format!(
924                                 "partially resolved path in {} {}",
925                                 kind.article(),
926                                 kind.descr()
927                             ),
928                         )
929                     };
930                     self.report_error(
931                         span,
932                         ResolutionError::FailedToResolve { label, suggestion: None },
933                     );
934                 }
935                 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
936             }
937         }
938
939         let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
940         for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
941             match self.early_resolve_ident_in_lexical_scope(
942                 ident,
943                 ScopeSet::Macro(kind),
944                 &parent_scope,
945                 true,
946                 true,
947                 ident.span,
948             ) {
949                 Ok(binding) => {
950                     let initial_res = initial_binding.map(|initial_binding| {
951                         self.record_use(ident, MacroNS, initial_binding, false);
952                         initial_binding.res()
953                     });
954                     let res = binding.res();
955                     let seg = Segment::from_ident(ident);
956                     check_consistency(self, &[seg], ident.span, kind, initial_res, res);
957                 }
958                 Err(..) => {
959                     let expected = kind.descr_expected();
960                     let msg = format!("cannot find {} `{}` in this scope", expected, ident);
961                     let mut err = self.session.struct_span_err(ident.span, &msg);
962                     self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
963                     err.emit();
964                 }
965             }
966         }
967
968         let builtin_attrs = mem::take(&mut self.builtin_attrs);
969         for (ident, parent_scope) in builtin_attrs {
970             let _ = self.early_resolve_ident_in_lexical_scope(
971                 ident,
972                 ScopeSet::Macro(MacroKind::Attr),
973                 &parent_scope,
974                 true,
975                 true,
976                 ident.span,
977             );
978         }
979     }
980
981     fn check_stability_and_deprecation(&mut self, ext: &SyntaxExtension, path: &ast::Path) {
982         let span = path.span;
983         if let Some(stability) = &ext.stability {
984             if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
985                 let feature = stability.feature;
986                 if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
987                     let node_id = ast::CRATE_NODE_ID;
988                     let lint_buffer = &mut self.lint_buffer;
989                     let soft_handler =
990                         |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
991                     stability::report_unstable(
992                         self.session,
993                         feature,
994                         reason,
995                         issue,
996                         is_soft,
997                         span,
998                         soft_handler,
999                     );
1000                 }
1001             }
1002             if let Some(depr) = &stability.rustc_depr {
1003                 let path = pprust::path_to_string(path);
1004                 let (message, lint) = stability::rustc_deprecation_message(depr, &path);
1005                 stability::early_report_deprecation(
1006                     &mut self.lint_buffer,
1007                     &message,
1008                     depr.suggestion,
1009                     lint,
1010                     span,
1011                 );
1012             }
1013         }
1014         if let Some(depr) = &ext.deprecation {
1015             let path = pprust::path_to_string(&path);
1016             let (message, lint) = stability::deprecation_message(depr, &path);
1017             stability::early_report_deprecation(&mut self.lint_buffer, &message, None, lint, span);
1018         }
1019     }
1020
1021     fn prohibit_imported_non_macro_attrs(
1022         &self,
1023         binding: Option<&'a NameBinding<'a>>,
1024         res: Option<Res>,
1025         span: Span,
1026     ) {
1027         if let Some(Res::NonMacroAttr(kind)) = res {
1028             if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
1029                 let msg =
1030                     format!("cannot use {} {} through an import", kind.article(), kind.descr());
1031                 let mut err = self.session.struct_span_err(span, &msg);
1032                 if let Some(binding) = binding {
1033                     err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
1034                 }
1035                 err.emit();
1036             }
1037         }
1038     }
1039
1040     crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
1041         // Reserve some names that are not quite covered by the general check
1042         // performed on `Resolver::builtin_attrs`.
1043         if ident.name == sym::cfg || ident.name == sym::cfg_attr || ident.name == sym::derive {
1044             let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
1045             if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
1046                 self.session.span_err(
1047                     ident.span,
1048                     &format!("name `{}` is reserved in attribute namespace", ident),
1049                 );
1050             }
1051         }
1052     }
1053
1054     /// Compile the macro into a `SyntaxExtension` and possibly replace
1055     /// its expander to a pre-defined one for built-in macros.
1056     crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
1057         let mut result = compile_declarative_macro(
1058             &self.session.parse_sess,
1059             self.session.features_untracked(),
1060             item,
1061             edition,
1062         );
1063
1064         if result.is_builtin {
1065             // The macro was marked with `#[rustc_builtin_macro]`.
1066             if let Some(ext) = self.builtin_macros.remove(&item.ident.name) {
1067                 // The macro is a built-in, replace its expander function
1068                 // while still taking everything else from the source code.
1069                 result.kind = ext.kind;
1070             } else {
1071                 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
1072                 self.session.span_err(item.span, &msg);
1073             }
1074         }
1075
1076         result
1077     }
1078 }