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