macros.rs 55.0 KB
Newer Older
1 2 3
//! A bunch of methods and structures more or less related to resolving macros and
//! interface provided by `Resolver` to macro expander.

4
use crate::imports::ImportResolver;
M
Mark Rousskov 已提交
5
use crate::Namespace::*;
6
use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BuiltinMacroState, Determinacy};
7
use crate::{CrateLint, DeriveData, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Weak};
M
Mark Rousskov 已提交
8
use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment, ToNameBinding};
9
use rustc_ast::{self as ast, Inline, ItemKind, ModKind, 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_data_structures::ptr_key::PtrKey;
15
use rustc_data_structures::sync::Lrc;
16
use rustc_errors::struct_span_err;
17 18
use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand};
use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
19
use rustc_expand::compile_declarative_macro;
20
use rustc_expand::expand::{AstFragment, Invocation, InvocationKind, SupportsMacroExpansion};
21
use rustc_feature::is_builtin_attr_name;
22
use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
23
use rustc_hir::def_id::{CrateNum, LocalDefId};
24
use rustc_hir::PrimTy;
25
use rustc_middle::middle::stability;
26
use rustc_middle::ty;
27 28
use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, PROC_MACRO_DERIVE_RESOLUTION_FALLBACK};
use rustc_session::lint::builtin::{SOFT_UNSTABLE, UNUSED_MACROS};
29
use rustc_session::lint::BuiltinLintDiagnostics;
30
use rustc_session::parse::feature_err;
31
use rustc_session::Session;
32
use rustc_span::edition::Edition;
C
Camille GILLOT 已提交
33
use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
34
use rustc_span::hygiene::{AstPass, MacroKind};
35
use rustc_span::symbol::{kw, sym, Ident, Symbol};
36
use rustc_span::{Span, DUMMY_SP};
37
use std::cell::Cell;
M
Mark Rousskov 已提交
38
use std::{mem, ptr};
39

40
type Res = def::Res<NodeId>;
L
ljedrz 已提交
41

42
/// Binding produced by a `macro_rules` item.
43
/// Not modularized, can shadow previous `macro_rules` bindings, etc.
44
#[derive(Debug)]
45
pub struct MacroRulesBinding<'a> {
46
    crate binding: &'a NameBinding<'a>,
47
    /// `macro_rules` scope into which the `macro_rules` item was planted.
48
    crate parent_macro_rules_scope: MacroRulesScopeRef<'a>,
49
    crate ident: Ident,
50 51
}

A
Alexander Regueiro 已提交
52 53 54
/// The scope introduced by a `macro_rules!` macro.
/// This starts at the macro's definition and ends at the end of the macro's parent
/// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
55
/// Some macro invocations need to introduce `macro_rules` scopes too because they
A
Alexander Regueiro 已提交
56
/// can potentially expand into macro definitions.
57
#[derive(Copy, Clone, Debug)]
58
pub enum MacroRulesScope<'a> {
59
    /// Empty "root" scope at the crate start containing no names.
J
Jeffrey Seyfried 已提交
60
    Empty,
A
Alexander Regueiro 已提交
61
    /// The scope introduced by a `macro_rules!` macro definition.
62
    Binding(&'a MacroRulesBinding<'a>),
A
Alexander Regueiro 已提交
63
    /// The scope introduced by a macro invocation that can potentially
64
    /// create a `macro_rules!` macro definition.
C
Camille GILLOT 已提交
65
    Invocation(LocalExpnId),
66 67
}

68
/// `macro_rules!` scopes are always kept by reference and inside a cell.
69 70
/// The reason is that we update scopes with value `MacroRulesScope::Invocation(invoc_id)`
/// in-place after `invoc_id` gets expanded.
71 72 73 74 75
/// This helps to avoid uncontrollable growth of `macro_rules!` scope chains,
/// which usually grow lineraly with the number of macro invocations
/// in a module (including derives) and hurt performance.
pub(crate) type MacroRulesScopeRef<'a> = PtrKey<'a, Cell<MacroRulesScope<'a>>>;

76 77 78
// Macro namespace is separated into two sub-namespaces, one for bang macros and
// one for attribute-like macros (attributes, derives).
// We ignore resolutions from one sub-namespace when searching names in scope for another.
79
fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
80
    #[derive(PartialEq)]
M
Mark Rousskov 已提交
81 82 83 84
    enum SubNS {
        Bang,
        AttrLike,
    }
85
    let sub_ns = |kind| match kind {
86 87
        MacroKind::Bang => SubNS::Bang,
        MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
88
    };
89 90
    let candidate = candidate.map(sub_ns);
    let requirement = requirement.map(sub_ns);
91
    // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
92
    candidate.is_none() || requirement.is_none() || candidate == requirement
93 94
}

95 96 97
// We don't want to format a path using pretty-printing,
// `format!("{}", path)`, because that tries to insert
// line-breaks and is slow.
98 99
fn fast_print_path(path: &ast::Path) -> Symbol {
    if path.segments.len() == 1 {
100
        path.segments[0].ident.name
101 102 103 104 105 106 107 108 109
    } else {
        let mut path_str = String::with_capacity(64);
        for (i, segment) in path.segments.iter().enumerate() {
            if i != 0 {
                path_str.push_str("::");
            }
            if segment.ident.name != kw::PathRoot {
                path_str.push_str(&segment.ident.as_str())
            }
110
        }
111
        Symbol::intern(&path_str)
112 113 114
    }
}

V
Vadim Petrochenkov 已提交
115
/// The code common between processing `#![register_tool]` and `#![register_attr]`.
116 117 118 119 120 121 122
fn registered_idents(
    sess: &Session,
    attrs: &[ast::Attribute],
    attr_name: Symbol,
    descr: &str,
) -> FxHashSet<Ident> {
    let mut registered = FxHashSet::default();
123
    for attr in sess.filter_by_name(attrs, attr_name) {
124 125
        for nested_meta in attr.meta_item_list().unwrap_or_default() {
            match nested_meta.ident() {
M
Mark Rousskov 已提交
126 127 128 129 130 131 132
                Some(ident) => {
                    if let Some(old_ident) = registered.replace(ident) {
                        let msg = format!("{} `{}` was already registered", descr, ident);
                        sess.struct_span_err(ident.span, &msg)
                            .span_label(old_ident.span, "already registered here")
                            .emit();
                    }
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
                }
                None => {
                    let msg = format!("`{}` only accepts identifiers", attr_name);
                    let span = nested_meta.span();
                    sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
                }
            }
        }
    }
    registered
}

crate fn registered_attrs_and_tools(
    sess: &Session,
    attrs: &[ast::Attribute],
) -> (FxHashSet<Ident>, FxHashSet<Ident>) {
    let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute");
    let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool");
    // We implicitly add `rustfmt` and `clippy` to known tools,
    // but it's not an error to register them explicitly.
    let predefined_tools = [sym::clippy, sym::rustfmt];
    registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
    (registered_attrs, registered_tools)
}

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
// Some feature gates for inner attributes are reported as lints for backward compatibility.
fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool {
    match &path.segments[..] {
        // `#![test]`
        [seg] if seg.ident.name == sym::test => return true,
        // `#![rustfmt::skip]` on out-of-line modules
        [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => {
            if let InvocationKind::Attr { item, .. } = &invoc.kind {
                if let Annotatable::Item(item) = item {
                    if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind {
                        return true;
                    }
                }
            }
        }
        _ => {}
    }
    false
}

178
impl<'a> ResolverExpand for Resolver<'a> {
179
    fn next_node_id(&mut self) -> NodeId {
M
Mark Rousskov 已提交
180
        self.next_node_id()
181 182
    }

183 184 185 186
    fn resolve_dollar_crates(&mut self) {
        hygiene::update_dollar_crate_names(|ctxt| {
            let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
            match self.resolve_crate_root(ident).kind {
J
Joshua Nelson 已提交
187
                ModuleKind::Def(.., name) if name != kw::Empty => name,
188
                _ => kw::Crate,
189
            }
190
        });
191 192
    }

C
Camille GILLOT 已提交
193 194 195 196 197
    fn visit_ast_fragment_with_placeholders(
        &mut self,
        expansion: LocalExpnId,
        fragment: &AstFragment,
    ) {
198
        // Integrate the new AST fragment into all the definition and module structures.
199 200
        // We are inside the `expansion` now, but other parent scope components are still the same.
        let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
201 202
        let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
        self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
203

204
        parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
205 206
    }

207 208
    fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
        if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
M
Mark Rousskov 已提交
209
            self.session
210 211
                .diagnostic()
                .bug(&format!("built-in macro `{}` was already registered", name));
212
        }
213 214
    }

M
Matthew Jasper 已提交
215 216
    // Create a new Expansion with a definition site of the provided module, or
    // a fake empty `#[no_implicit_prelude]` module if no module is provided.
217
    fn expansion_for_ast_pass(
218
        &mut self,
219
        call_site: Span,
220 221 222
        pass: AstPass,
        features: &[Symbol],
        parent_module_id: Option<NodeId>,
C
Camille GILLOT 已提交
223
    ) -> LocalExpnId {
224
        let parent_module = parent_module_id.map(|module_id| self.local_def_id(module_id));
C
Camille GILLOT 已提交
225
        let expn_id = LocalExpnId::fresh(
C
Camille GILLOT 已提交
226 227 228 229 230 231 232 233 234 235
            ExpnData::allow_unstable(
                ExpnKind::AstPass(pass),
                call_site,
                self.session.edition(),
                features.into(),
                None,
                parent_module.map(LocalDefId::to_def_id),
            ),
            self.create_stable_hashing_context(),
        );
236

237 238
        let parent_scope = parent_module
            .map_or(self.empty_module, |parent_def_id| self.module_map[&parent_def_id]);
239
        self.ast_transform_scopes.insert(expn_id, parent_scope);
240

241
        expn_id
242 243
    }

244
    fn resolve_imports(&mut self) {
245
        ImportResolver { r: self }.resolve_imports()
246 247
    }

248
    fn resolve_macro_invocation(
M
Mark Rousskov 已提交
249 250
        &mut self,
        invoc: &Invocation,
C
Camille GILLOT 已提交
251
        eager_expansion_root: LocalExpnId,
M
Mark Rousskov 已提交
252
        force: bool,
253
    ) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
254 255 256 257 258 259 260
        let invoc_id = invoc.expansion_data.id;
        let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
            Some(parent_scope) => *parent_scope,
            None => {
                // If there's no entry in the table, then we are resolving an eagerly expanded
                // macro, which should inherit its parent scope from its eager expansion root -
                // the macro that requested this eager expansion.
M
Mark Rousskov 已提交
261 262 263
                let parent_scope = *self
                    .invocation_parent_scopes
                    .get(&eager_expansion_root)
264 265 266 267 268 269
                    .expect("non-eager expansion without a parent scope");
                self.invocation_parent_scopes.insert(invoc_id, parent_scope);
                parent_scope
            }
        };

270 271
        let (path, kind, inner_attr, derives) = match invoc.kind {
            InvocationKind::Attr { ref attr, ref derives, .. } => (
M
Mark Rousskov 已提交
272 273
                &attr.get_normal_item().path,
                MacroKind::Attr,
274
                attr.style == ast::AttrStyle::Inner,
M
Mark Rousskov 已提交
275 276
                self.arenas.alloc_ast_paths(derives),
            ),
277 278
            InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
            InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
279
        };
280

281
        // Derives are not included when `invocations` are collected, so we have to add them here.
282
        let parent_scope = &ParentScope { derives, ..parent_scope };
283
        let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
284
        let node_id = invoc.expansion_data.lint_node_id;
285 286 287
        let (ext, res) = self.smart_resolve_macro_path(
            path,
            kind,
288
            supports_macro_expansion,
289 290 291 292
            inner_attr,
            parent_scope,
            node_id,
            force,
293
            soft_custom_inner_attributes_gate(path, invoc),
294
        )?;
295

296
        let span = invoc.span();
C
Camille GILLOT 已提交
297 298 299 300 301 302 303 304 305 306 307 308
        invoc_id.set_expn_data(
            ext.expn_data(
                parent_scope.expansion,
                span,
                fast_print_path(path),
                res.opt_def_id(),
                res.opt_def_id().map(|macro_def_id| {
                    self.macro_def_scope_from_def_id(macro_def_id).nearest_parent_mod
                }),
            ),
            self.create_stable_hashing_context(),
        );
309

A
Aaron Hill 已提交
310
        if let Res::Def(_, _) = res {
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
            // Gate macro attributes in `#[derive]` output.
            if !self.session.features_untracked().macro_attributes_in_derive_output
                && kind == MacroKind::Attr
                && ext.builtin_name != Some(sym::derive)
            {
                let mut expn_id = parent_scope.expansion;
                loop {
                    // Helper attr table is a quick way to determine whether the attr is `derive`.
                    if self.helper_attrs.contains_key(&expn_id) {
                        feature_err(
                            &self.session.parse_sess,
                            sym::macro_attributes_in_derive_output,
                            path.span,
                            "macro attributes in `#[derive]` output are unstable",
                        )
                        .emit();
                        break;
                    } else {
                        let expn_data = expn_id.expn_data();
                        match expn_data.kind {
                            ExpnKind::Root
332
                            | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => {
333 334
                                break;
                            }
C
Camille GILLOT 已提交
335
                            _ => expn_id = expn_data.parent.expect_local(),
336 337 338 339
                        }
                    }
                }
            }
340
        }
341

342
        Ok(ext)
343 344
    }

345
    fn check_unused_macros(&mut self) {
346
        for (_, &(node_id, span)) in self.unused_macros.iter() {
347
            self.lint_buffer.buffer_lint(UNUSED_MACROS, node_id, span, "unused macro definition");
E
est31 已提交
348
        }
349
    }
350

C
Camille GILLOT 已提交
351
    fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
352
        self.containers_deriving_copy.contains(&expn_id)
353 354
    }

355 356
    fn resolve_derives(
        &mut self,
C
Camille GILLOT 已提交
357
        expn_id: LocalExpnId,
358
        force: bool,
359
        derive_paths: &dyn Fn() -> DeriveResolutions,
360 361 362 363 364 365 366
    ) -> Result<(), Indeterminate> {
        // Block expansion of the container until we resolve all derives in it.
        // This is required for two reasons:
        // - Derive helper attributes are in scope for the item to which the `#[derive]`
        //   is applied, so they have to be produced by the container's expansion rather
        //   than by individual derives.
        // - Derives in the container need to know whether one of them is a built-in `Copy`.
367 368 369 370 371 372 373
        // Temporarily take the data to avoid borrow checker conflicts.
        let mut derive_data = mem::take(&mut self.derive_data);
        let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
            resolutions: derive_paths(),
            helper_attrs: Vec::new(),
            has_derive_copy: false,
        });
374
        let parent_scope = self.invocation_parent_scopes[&expn_id];
375
        for (i, (path, _, opt_ext)) in entry.resolutions.iter_mut().enumerate() {
376 377 378 379 380 381 382 383 384 385 386 387 388 389
            if opt_ext.is_none() {
                *opt_ext = Some(
                    match self.resolve_macro_path(
                        &path,
                        Some(MacroKind::Derive),
                        &parent_scope,
                        true,
                        force,
                    ) {
                        Ok((Some(ext), _)) => {
                            if !ext.helper_attrs.is_empty() {
                                let last_seg = path.segments.last().unwrap();
                                let span = last_seg.ident.span.normalize_to_macros_2_0();
                                entry.helper_attrs.extend(
390 391 392
                                    ext.helper_attrs
                                        .iter()
                                        .map(|name| (i, Ident::new(*name, span))),
393 394 395 396 397 398 399 400 401 402 403 404 405 406
                                );
                            }
                            entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
                            ext
                        }
                        Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
                        Err(Determinacy::Undetermined) => {
                            assert!(self.derive_data.is_empty());
                            self.derive_data = derive_data;
                            return Err(Indeterminate);
                        }
                    },
                );
            }
407
        }
408 409 410 411
        // Sort helpers in a stable way independent from the derive resolution order.
        entry.helper_attrs.sort_by_key(|(i, _)| *i);
        self.helper_attrs
            .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect());
412 413
        // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
        // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`.
414
        if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
415 416
            self.containers_deriving_copy.insert(expn_id);
        }
417 418
        assert!(self.derive_data.is_empty());
        self.derive_data = derive_data;
419 420 421
        Ok(())
    }

C
Camille GILLOT 已提交
422
    fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
423
        self.derive_data.remove(&expn_id).map(|data| data.resolutions)
424 425
    }

426 427 428 429
    // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
    // Returns true if the path can certainly be resolved in one of three namespaces,
    // returns false if the path certainly cannot be resolved in any of the three namespaces.
    // Returns `Indeterminate` if we cannot give a certain answer yet.
C
Camille GILLOT 已提交
430 431 432 433 434
    fn cfg_accessible(
        &mut self,
        expn_id: LocalExpnId,
        path: &ast::Path,
    ) -> Result<bool, Indeterminate> {
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        let span = path.span;
        let path = &Segment::from_path(path);
        let parent_scope = self.invocation_parent_scopes[&expn_id];

        let mut indeterminate = false;
        for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
            match self.resolve_path(path, Some(ns), &parent_scope, false, span, CrateLint::No) {
                PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
                PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
                    return Ok(true);
                }
                PathResult::Indeterminate => indeterminate = true,
                // FIXME: `resolve_path` is not ready to report partially resolved paths
                // correctly, so we just report an error if the path was reported as unresolved.
                // This needs to be fixed for `cfg_accessible` to be useful.
                PathResult::NonModule(..) | PathResult::Failed { .. } => {}
                PathResult::Module(_) => panic!("unexpected path resolution"),
            }
        }

        if indeterminate {
            return Err(Indeterminate);
        }

        self.session
            .struct_span_err(span, "not sure whether the path is accessible or not")
            .span_note(span, "`cfg_accessible` is not fully implemented")
            .emit();
        Ok(false)
    }
465 466 467 468

    fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
        self.crate_loader.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session)
    }
469 470
}

J
John Kåre Alsaker 已提交
471
impl<'a> Resolver<'a> {
472
    /// Resolve macro path with error reporting and recovery.
473 474
    /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
    /// for better error recovery.
475
    fn smart_resolve_macro_path(
476 477 478
        &mut self,
        path: &ast::Path,
        kind: MacroKind,
479
        supports_macro_expansion: SupportsMacroExpansion,
480
        inner_attr: bool,
481
        parent_scope: &ParentScope<'a>,
482
        node_id: NodeId,
483
        force: bool,
484
        soft_custom_inner_attributes_gate: bool,
485
    ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
M
Mark Rousskov 已提交
486 487
        let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
        {
488 489 490 491 492
            Ok((Some(ext), res)) => (ext, res),
            Ok((None, res)) => (self.dummy_ext(kind), res),
            Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
            Err(Determinacy::Undetermined) => return Err(Indeterminate),
        };
493

494
        // Report errors for the resolved macro.
495 496 497
        for segment in &path.segments {
            if let Some(args) = &segment.args {
                self.session.span_err(args.span(), "generic arguments in macro path");
498
            }
499 500 501 502 503
            if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
                self.session.span_err(
                    segment.ident.span,
                    "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
                );
504
            }
505
        }
506

507
        match res {
508
            Res::Def(DefKind::Macro(_), def_id) => {
509 510 511
                if let Some(def_id) = def_id.as_local() {
                    self.unused_macros.remove(&def_id);
                    if self.proc_macro_stubs.contains(&def_id) {
512 513 514 515 516
                        self.session.span_err(
                            path.span,
                            "can't use a procedural macro from the same crate that defines it",
                        );
                    }
517
                }
518
            }
519
            Res::NonMacroAttr(..) | Res::Err => {}
520
            _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
521
        };
522

523
        self.check_stability_and_deprecation(&ext, path, node_id);
524

525 526
        let unexpected_res = if ext.macro_kind() != kind {
            Some((kind.article(), kind.descr_expected()))
527 528 529 530 531 532 533 534 535 536 537
        } else if matches!(res, Res::Def(..)) {
            match supports_macro_expansion {
                SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
                SupportsMacroExpansion::Yes { supports_inner_attrs } => {
                    if inner_attr && !supports_inner_attrs {
                        Some(("a", "non-macro inner attribute"))
                    } else {
                        None
                    }
                }
            }
538 539 540 541
        } else {
            None
        };
        if let Some((article, expected)) = unexpected_res {
542 543
            let path_str = pprust::path_to_string(path);
            let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
M
Mark Rousskov 已提交
544 545
            self.session
                .struct_span_err(path.span, &msg)
546
                .span_label(path.span, format!("not {} {}", article, expected))
M
Mark Rousskov 已提交
547
                .emit();
548 549 550 551
            return Ok((self.dummy_ext(kind), Res::Err));
        }

        // We are trying to avoid reporting this error if other related errors were reported.
552 553
        if res != Res::Err
            && inner_attr
554 555
            && !self.session.features_untracked().custom_inner_attributes
        {
556 557 558 559 560
            let msg = match res {
                Res::Def(..) => "inner macro attributes are unstable",
                Res::NonMacroAttr(..) => "custom inner attributes are unstable",
                _ => unreachable!(),
            };
561
            if soft_custom_inner_attributes_gate {
562 563 564 565 566
                self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
            } else {
                feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
                    .emit();
            }
567 568 569
        }

        Ok((ext, res))
570
    }
571

572
    pub fn resolve_macro_path(
573 574
        &mut self,
        path: &ast::Path,
575
        kind: Option<MacroKind>,
576
        parent_scope: &ParentScope<'a>,
577
        trace: bool,
578
        force: bool,
579
    ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
580
        let path_span = path.span;
N
Nick Cameron 已提交
581
        let mut path = Segment::from_path(path);
582

583
        // Possibly apply the macro helper hack
M
Mark Rousskov 已提交
584 585 586 587
        if kind == Some(MacroKind::Bang)
            && path.len() == 1
            && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
        {
588
            let root = Ident::new(kw::DollarCrate, path[0].ident.span);
N
Nick Cameron 已提交
589
            path.insert(0, Segment::from_ident(root));
590 591
        }

592
        let res = if path.len() > 1 {
M
Mark Rousskov 已提交
593 594 595 596 597 598 599 600
            let res = match self.resolve_path(
                &path,
                Some(MacroNS),
                parent_scope,
                false,
                path_span,
                CrateLint::No,
            ) {
601
                PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
602
                    Ok(path_res.base_res())
603
                }
604
                PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
605 606 607
                PathResult::NonModule(..)
                | PathResult::Indeterminate
                | PathResult::Failed { .. } => Err(Determinacy::Determined),
608
                PathResult::Module(..) => unreachable!(),
609
            };
610

611
            if trace {
612
                let kind = kind.expect("macro kind must be specified if tracing is enabled");
M
Mark Rousskov 已提交
613 614 615 616 617 618 619
                self.multi_segment_macro_resolutions.push((
                    path,
                    path_span,
                    kind,
                    *parent_scope,
                    res.ok(),
                ));
620
            }
621

622 623
            self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
            res
624
        } else {
625
            let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
626
            let binding = self.early_resolve_ident_in_lexical_scope(
M
Mark Rousskov 已提交
627 628 629 630 631 632
                path[0].ident,
                scope_set,
                parent_scope,
                false,
                force,
                path_span,
633
            );
634 635
            if let Err(Determinacy::Undetermined) = binding {
                return Err(Determinacy::Undetermined);
636
            }
637

638
            if trace {
639
                let kind = kind.expect("macro kind must be specified if tracing is enabled");
M
Mark Rousskov 已提交
640 641 642 643 644 645
                self.single_segment_macro_resolutions.push((
                    path[0].ident,
                    kind,
                    *parent_scope,
                    binding.ok(),
                ));
646
            }
647

648 649 650
            let res = binding.map(|binding| binding.res());
            self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
            res
651 652 653
        };

        res.map(|res| (self.get_macro(res), res))
654
    }
655

656
    // Resolve an identifier in lexical scope.
657 658
    // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
    // expansion and import resolution (perhaps they can be merged in the future).
659
    // The function is used for resolving initial segments of macro paths (e.g., `foo` in
660
    // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
661
    crate fn early_resolve_ident_in_lexical_scope(
662
        &mut self,
663
        orig_ident: Ident,
664
        scope_set: ScopeSet<'a>,
665
        parent_scope: &ParentScope<'a>,
666 667
        record_used: bool,
        force: bool,
668
        path_span: Span,
669
    ) -> Result<&'a NameBinding<'a>, Determinacy> {
T
Taiki Endo 已提交
670
        bitflags::bitflags! {
671
            struct Flags: u8 {
672 673
                const MACRO_RULES          = 1 << 0;
                const MODULE               = 1 << 1;
674 675 676
                const MISC_SUGGEST_CRATE   = 1 << 2;
                const MISC_SUGGEST_SELF    = 1 << 3;
                const MISC_FROM_PRELUDE    = 1 << 4;
677 678
            }
        }
679

V
Vadim Petrochenkov 已提交
680
        assert!(force || !record_used); // `record_used` implies `force`
681

682
        // Make sure `self`, `super` etc produce an error when passed to here.
683
        if orig_ident.is_path_segment_keyword() {
684 685 686
            return Err(Determinacy::Determined);
        }

687
        let (ns, macro_kind, is_import) = match scope_set {
688
            ScopeSet::All(ns, is_import) => (ns, None, is_import),
689 690
            ScopeSet::AbsolutePath(ns) => (ns, None, false),
            ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
691
            ScopeSet::Late(ns, ..) => (ns, None, false),
692 693
        };

694 695 696 697
        // This is *the* result, resolution from the scope closest to the resolved identifier.
        // However, sometimes this result is "weak" because it comes from a glob import or
        // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
        // mod m { ... } // solution in outer scope
698
        // {
699 700
        //     use prefix::*; // imports another `m` - innermost solution
        //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
701 702
        //     m::mac!();
        // }
703 704
        // So we have to save the innermost solution and continue searching in outer scopes
        // to detect potential ambiguities.
T
Taiki Endo 已提交
705
        let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
706
        let mut determinacy = Determinacy::Determined;
707 708

        // Go through all the scopes and try to resolve the name.
M
Mark Rousskov 已提交
709 710 711
        let break_result = self.visit_scopes(
            scope_set,
            parent_scope,
712 713 714
            orig_ident.span.ctxt(),
            |this, scope, use_prelude, ctxt| {
                let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt));
M
Mark Rousskov 已提交
715 716
                let ok = |res, span, arenas| {
                    Ok((
C
Camille GILLOT 已提交
717 718
                        (res, ty::Visibility::Public, span, LocalExpnId::ROOT)
                            .to_name_binding(arenas),
M
Mark Rousskov 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
                        Flags::empty(),
                    ))
                };
                let result = match scope {
                    Scope::DeriveHelpers(expn_id) => {
                        if let Some(attr) = this
                            .helper_attrs
                            .get(&expn_id)
                            .and_then(|attrs| attrs.iter().rfind(|i| ident == **i))
                        {
                            let binding = (
                                Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
                                ty::Visibility::Public,
                                attr.span,
                                expn_id,
                            )
                                .to_name_binding(this.arenas);
                            Ok((binding, Flags::empty()))
                        } else {
                            Err(Determinacy::Determined)
                        }
740
                    }
M
Mark Rousskov 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753
                    Scope::DeriveHelpersCompat => {
                        let mut result = Err(Determinacy::Determined);
                        for derive in parent_scope.derives {
                            let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
                            match this.resolve_macro_path(
                                derive,
                                Some(MacroKind::Derive),
                                parent_scope,
                                true,
                                force,
                            ) {
                                Ok((Some(ext), _)) => {
                                    if ext.helper_attrs.contains(&ident.name) {
754 755
                                        result = ok(
                                            Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
M
Mark Rousskov 已提交
756
                                            derive.span,
757 758
                                            this.arenas,
                                        );
M
Mark Rousskov 已提交
759 760 761 762 763 764 765
                                        break;
                                    }
                                }
                                Ok(_) | Err(Determinacy::Determined) => {}
                                Err(Determinacy::Undetermined) => {
                                    result = Err(Determinacy::Undetermined)
                                }
766 767
                            }
                        }
M
Mark Rousskov 已提交
768
                        result
769
                    }
770
                    Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
771 772 773 774
                        MacroRulesScope::Binding(macro_rules_binding)
                            if ident == macro_rules_binding.ident =>
                        {
                            Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
775
                        }
776
                        MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
M
Mark Rousskov 已提交
777 778 779 780 781 782 783
                        _ => Err(Determinacy::Determined),
                    },
                    Scope::CrateRoot => {
                        let root_ident = Ident::new(kw::PathRoot, ident.span);
                        let root_module = this.resolve_crate_root(root_ident);
                        let binding = this.resolve_ident_in_module_ext(
                            ModuleOrUniformRoot::Module(root_module),
784 785
                            ident,
                            ns,
786
                            parent_scope,
M
Mark Rousskov 已提交
787
                            record_used,
788
                            path_span,
M
Mark Rousskov 已提交
789 790 791 792 793 794 795 796
                        );
                        match binding {
                            Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
                            Err((Determinacy::Undetermined, Weak::No)) => {
                                return Some(Err(Determinacy::determined(force)));
                            }
                            Err((Determinacy::Undetermined, Weak::Yes)) => {
                                Err(Determinacy::Undetermined)
797
                            }
M
Mark Rousskov 已提交
798
                            Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
799 800
                        }
                    }
801
                    Scope::Module(module, derive_fallback_lint_id) => {
M
Mark Rousskov 已提交
802 803 804 805 806 807
                        let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
                        let binding = this.resolve_ident_in_module_unadjusted_ext(
                            ModuleOrUniformRoot::Module(module),
                            ident,
                            ns,
                            adjusted_parent_scope,
808
                            !matches!(scope_set, ScopeSet::Late(..)),
M
Mark Rousskov 已提交
809 810 811 812 813
                            record_used,
                            path_span,
                        );
                        match binding {
                            Ok(binding) => {
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
                                if let Some(lint_id) = derive_fallback_lint_id {
                                    this.lint_buffer.buffer_lint_with_diagnostic(
                                        PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
                                        lint_id,
                                        orig_ident.span,
                                        &format!(
                                            "cannot find {} `{}` in this scope",
                                            ns.descr(),
                                            ident
                                        ),
                                        BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(
                                            orig_ident.span,
                                        ),
                                    );
                                }
M
Mark Rousskov 已提交
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
                                let misc_flags = if ptr::eq(module, this.graph_root) {
                                    Flags::MISC_SUGGEST_CRATE
                                } else if module.is_normal() {
                                    Flags::MISC_SUGGEST_SELF
                                } else {
                                    Flags::empty()
                                };
                                Ok((binding, Flags::MODULE | misc_flags))
                            }
                            Err((Determinacy::Undetermined, Weak::No)) => {
                                return Some(Err(Determinacy::determined(force)));
                            }
                            Err((Determinacy::Undetermined, Weak::Yes)) => {
                                Err(Determinacy::Undetermined)
                            }
                            Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
                        }
                    }
                    Scope::RegisteredAttrs => match this.registered_attrs.get(&ident).cloned() {
                        Some(ident) => ok(
                            Res::NonMacroAttr(NonMacroAttrKind::Registered),
                            ident.span,
                            this.arenas,
                        ),
                        None => Err(Determinacy::Determined),
                    },
                    Scope::MacroUsePrelude => {
                        match this.macro_use_prelude.get(&ident.name).cloned() {
                            Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)),
                            None => Err(Determinacy::determined(
                                this.graph_root.unexpanded_invocations.borrow().is_empty(),
                            )),
                        }
                    }
                    Scope::BuiltinAttrs => {
                        if is_builtin_attr_name(ident.name) {
865 866 867 868 869
                            ok(
                                Res::NonMacroAttr(NonMacroAttrKind::Builtin(ident.name)),
                                DUMMY_SP,
                                this.arenas,
                            )
M
Mark Rousskov 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
                        } else {
                            Err(Determinacy::Determined)
                        }
                    }
                    Scope::ExternPrelude => match this.extern_prelude_get(ident, !record_used) {
                        Some(binding) => Ok((binding, Flags::empty())),
                        None => Err(Determinacy::determined(
                            this.graph_root.unexpanded_invocations.borrow().is_empty(),
                        )),
                    },
                    Scope::ToolPrelude => match this.registered_tools.get(&ident).cloned() {
                        Some(ident) => ok(Res::ToolMod, ident.span, this.arenas),
                        None => Err(Determinacy::Determined),
                    },
                    Scope::StdLibPrelude => {
                        let mut result = Err(Determinacy::Determined);
                        if let Some(prelude) = this.prelude {
                            if let Ok(binding) = this.resolve_ident_in_module_unadjusted(
                                ModuleOrUniformRoot::Module(prelude),
                                ident,
                                ns,
                                parent_scope,
                                false,
                                path_span,
                            ) {
                                if use_prelude || this.is_builtin_macro(binding.res()) {
                                    result = Ok((binding, Flags::MISC_FROM_PRELUDE));
                                }
                            }
                        }
                        result
901
                    }
902 903 904 905
                    Scope::BuiltinTypes => match PrimTy::from_name(ident.name) {
                        Some(prim_ty) => ok(Res::PrimTy(prim_ty), DUMMY_SP, this.arenas),
                        None => Err(Determinacy::Determined),
                    },
M
Mark Rousskov 已提交
906 907 908 909 910 911
                };

                match result {
                    Ok((binding, flags))
                        if sub_namespace_match(binding.macro_kind(), macro_kind) =>
                    {
912
                        if !record_used || matches!(scope_set, ScopeSet::Late(..)) {
M
Mark Rousskov 已提交
913 914 915 916 917 918 919
                            return Some(Ok(binding));
                        }

                        if let Some((innermost_binding, innermost_flags)) = innermost_result {
                            // Found another solution, if the first one was "weak", report an error.
                            let (res, innermost_res) = (binding.res(), innermost_binding.res());
                            if res != innermost_res {
920 921 922
                                let is_builtin = |res| {
                                    matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)))
                                };
923 924
                                let derive_helper =
                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
925 926
                                let derive_helper_compat =
                                    Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
927

M
Mark Rousskov 已提交
928 929
                                let ambiguity_error_kind = if is_import {
                                    Some(AmbiguityKind::Import)
930
                                } else if is_builtin(innermost_res) || is_builtin(res) {
M
Mark Rousskov 已提交
931
                                    Some(AmbiguityKind::BuiltinAttr)
932
                                } else if innermost_res == derive_helper_compat
933
                                    || res == derive_helper_compat && innermost_res != derive_helper
M
Mark Rousskov 已提交
934 935 936 937
                                {
                                    Some(AmbiguityKind::DeriveHelper)
                                } else if innermost_flags.contains(Flags::MACRO_RULES)
                                    && flags.contains(Flags::MODULE)
938 939 940 941
                                    && !this.disambiguate_macro_rules_vs_modularized(
                                        innermost_binding,
                                        binding,
                                    )
M
Mark Rousskov 已提交
942 943
                                    || flags.contains(Flags::MACRO_RULES)
                                        && innermost_flags.contains(Flags::MODULE)
944
                                        && !this.disambiguate_macro_rules_vs_modularized(
M
Mark Rousskov 已提交
945 946 947 948
                                            binding,
                                            innermost_binding,
                                        )
                                {
949
                                    Some(AmbiguityKind::MacroRulesVsModularized)
M
Mark Rousskov 已提交
950 951 952 953 954 955
                                } else if innermost_binding.is_glob_import() {
                                    Some(AmbiguityKind::GlobVsOuter)
                                } else if innermost_binding
                                    .may_appear_after(parent_scope.expansion, binding)
                                {
                                    Some(AmbiguityKind::MoreExpandedVsOuter)
956
                                } else {
M
Mark Rousskov 已提交
957
                                    None
958
                                };
M
Mark Rousskov 已提交
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
                                if let Some(kind) = ambiguity_error_kind {
                                    let misc = |f: Flags| {
                                        if f.contains(Flags::MISC_SUGGEST_CRATE) {
                                            AmbiguityErrorMisc::SuggestCrate
                                        } else if f.contains(Flags::MISC_SUGGEST_SELF) {
                                            AmbiguityErrorMisc::SuggestSelf
                                        } else if f.contains(Flags::MISC_FROM_PRELUDE) {
                                            AmbiguityErrorMisc::FromPrelude
                                        } else {
                                            AmbiguityErrorMisc::None
                                        }
                                    };
                                    this.ambiguity_errors.push(AmbiguityError {
                                        kind,
                                        ident: orig_ident,
                                        b1: innermost_binding,
                                        b2: binding,
                                        misc1: misc(innermost_flags),
                                        misc2: misc(flags),
                                    });
                                    return Some(Ok(innermost_binding));
                                }
981
                            }
M
Mark Rousskov 已提交
982 983 984
                        } else {
                            // Found the first solution.
                            innermost_result = Some((binding, flags));
985
                        }
986
                    }
M
Mark Rousskov 已提交
987 988
                    Ok(..) | Err(Determinacy::Determined) => {}
                    Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
989
                }
990

M
Mark Rousskov 已提交
991 992 993
                None
            },
        );
994

995 996
        if let Some(break_result) = break_result {
            return break_result;
997
        }
998

999
        // The first found solution was the only one, return it.
1000
        if let Some((binding, _)) = innermost_result {
1001
            return Ok(binding);
1002
        }
1003

1004
        Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
1005 1006
    }

1007
    crate fn finalize_macro_resolutions(&mut self) {
M
Mark Rousskov 已提交
1008 1009 1010 1011 1012 1013
        let check_consistency = |this: &mut Self,
                                 path: &[Segment],
                                 span,
                                 kind: MacroKind,
                                 initial_res: Option<Res>,
                                 res: Res| {
1014
            if let Some(initial_res) = initial_res {
1015
                if res != initial_res {
1016 1017
                    // Make sure compilation does not succeed if preferred macro resolution
                    // has changed after the macro had been expanded. In theory all such
1018 1019
                    // situations should be reported as errors, so this is a bug.
                    this.session.delay_span_bug(span, "inconsistent resolution for a macro");
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
                }
            } else {
                // It's possible that the macro was unresolved (indeterminate) and silently
                // expanded into a dummy fragment for recovery during expansion.
                // Now, post-expansion, the resolution may succeed, but we can't change the
                // past and need to report an error.
                // However, non-speculative `resolve_path` can successfully return private items
                // even if speculative `resolve_path` returned nothing previously, so we skip this
                // less informative error if the privacy error is reported elsewhere.
                if this.privacy_errors.is_empty() {
M
Mark Rousskov 已提交
1030 1031 1032 1033 1034
                    let msg = format!(
                        "cannot determine resolution for the {} `{}`",
                        kind.descr(),
                        Segment::names_to_string(path)
                    );
1035 1036 1037 1038 1039 1040
                    let msg_note = "import resolution is stuck, try simplifying macro imports";
                    this.session.struct_span_err(span, &msg).note(msg_note).emit();
                }
            }
        };

1041
        let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
1042
        for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
1043
            // FIXME: Path resolution will ICE if segment IDs present.
M
Mark Rousskov 已提交
1044 1045 1046
            for seg in &mut path {
                seg.id = None;
            }
1047
            match self.resolve_path(
M
Mark Rousskov 已提交
1048 1049 1050 1051 1052 1053
                &path,
                Some(MacroNS),
                &parent_scope,
                true,
                path_span,
                CrateLint::No,
1054
            ) {
1055
                PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
1056 1057
                    let res = path_res.base_res();
                    check_consistency(self, &path, path_span, kind, initial_res, res);
1058
                }
1059 1060 1061
                path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
                    let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
                        (span, label)
1062
                    } else {
M
Mark Rousskov 已提交
1063 1064 1065 1066 1067 1068 1069 1070
                        (
                            path_span,
                            format!(
                                "partially resolved path in {} {}",
                                kind.article(),
                                kind.descr()
                            ),
                        )
1071
                    };
M
Mark Rousskov 已提交
1072 1073 1074 1075
                    self.report_error(
                        span,
                        ResolutionError::FailedToResolve { label, suggestion: None },
                    );
1076
                }
1077
                PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1078 1079 1080
            }
        }

1081
        let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
1082
        for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
M
Mark Rousskov 已提交
1083 1084 1085 1086 1087 1088 1089 1090
            match self.early_resolve_ident_in_lexical_scope(
                ident,
                ScopeSet::Macro(kind),
                &parent_scope,
                true,
                true,
                ident.span,
            ) {
1091
                Ok(binding) => {
1092
                    let initial_res = initial_binding.map(|initial_binding| {
1093
                        self.record_use(ident, initial_binding, false);
1094
                        initial_binding.res()
1095
                    });
1096
                    let res = binding.res();
V
Vadim Petrochenkov 已提交
1097
                    let seg = Segment::from_ident(ident);
1098
                    check_consistency(self, &[seg], ident.span, kind, initial_res, res);
1099
                    if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
1100 1101 1102 1103
                        let node_id = self
                            .invocation_parents
                            .get(&parent_scope.expansion)
                            .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]);
1104 1105
                        self.lint_buffer.buffer_lint_with_diagnostic(
                            LEGACY_DERIVE_HELPERS,
1106
                            node_id,
1107 1108 1109 1110 1111
                            ident.span,
                            "derive helper attribute is used before it is introduced",
                            BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
                        );
                    }
1112
                }
1113
                Err(..) => {
1114
                    let expected = kind.descr_expected();
1115
                    let msg = format!("cannot find {} `{}` in this scope", expected, ident);
1116
                    let mut err = self.session.struct_span_err(ident.span, &msg);
1117
                    self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
1118
                    err.emit();
1119
                }
1120
            }
J
Jeffrey Seyfried 已提交
1121
        }
1122

1123
        let builtin_attrs = mem::take(&mut self.builtin_attrs);
1124
        for (ident, parent_scope) in builtin_attrs {
1125
            let _ = self.early_resolve_ident_in_lexical_scope(
M
Mark Rousskov 已提交
1126 1127 1128 1129 1130 1131
                ident,
                ScopeSet::Macro(MacroKind::Attr),
                &parent_scope,
                true,
                true,
                ident.span,
1132
            );
1133
        }
1134
    }
1135

1136 1137 1138 1139 1140 1141
    fn check_stability_and_deprecation(
        &mut self,
        ext: &SyntaxExtension,
        path: &ast::Path,
        node_id: NodeId,
    ) {
1142
        let span = path.span;
1143
        if let Some(stability) = &ext.stability {
1144
            if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
1145 1146
                let feature = stability.feature;
                if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
1147
                    let lint_buffer = &mut self.lint_buffer;
M
Mark Rousskov 已提交
1148 1149
                    let soft_handler =
                        |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
1150
                    stability::report_unstable(
M
Mark Rousskov 已提交
1151 1152 1153 1154 1155 1156 1157
                        self.session,
                        feature,
                        reason,
                        issue,
                        is_soft,
                        span,
                        soft_handler,
1158
                    );
1159 1160 1161 1162
                }
            }
        }
        if let Some(depr) = &ext.deprecation {
1163
            let path = pprust::path_to_string(&path);
1164
            let (message, lint) = stability::deprecation_message(depr, "macro", &path);
1165 1166 1167 1168 1169 1170
            stability::early_report_deprecation(
                &mut self.lint_buffer,
                &message,
                depr.suggestion,
                lint,
                span,
1171
                node_id,
1172
            );
1173 1174 1175
        }
    }

M
Mark Rousskov 已提交
1176 1177 1178 1179 1180 1181
    fn prohibit_imported_non_macro_attrs(
        &self,
        binding: Option<&'a NameBinding<'a>>,
        res: Option<Res>,
        span: Span,
    ) {
1182
        if let Some(Res::NonMacroAttr(kind)) = res {
1183
            if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
V
Vadim Petrochenkov 已提交
1184 1185
                let msg =
                    format!("cannot use {} {} through an import", kind.article(), kind.descr());
1186 1187 1188 1189 1190 1191 1192 1193 1194
                let mut err = self.session.struct_span_err(span, &msg);
                if let Some(binding) = binding {
                    err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
                }
                err.emit();
            }
        }
    }

1195 1196 1197
    crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
        // Reserve some names that are not quite covered by the general check
        // performed on `Resolver::builtin_attrs`.
1198
        if ident.name == sym::cfg || ident.name == sym::cfg_attr {
1199
            let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
1200 1201
            if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
                self.session.span_err(
M
Mark Rousskov 已提交
1202 1203
                    ident.span,
                    &format!("name `{}` is reserved in attribute namespace", ident),
1204 1205 1206 1207 1208
                );
            }
        }
    }

1209 1210
    /// Compile the macro into a `SyntaxExtension` and possibly replace
    /// its expander to a pre-defined one for built-in macros.
1211
    crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
1212
        let mut result = compile_declarative_macro(
1213
            &self.session,
M
Mark Rousskov 已提交
1214 1215 1216
            self.session.features_untracked(),
            item,
            edition,
1217 1218
        );

1219
        if let Some(builtin_name) = result.builtin_name {
1220
            // The macro was marked with `#[rustc_builtin_macro]`.
1221
            if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
1222 1223
                // The macro is a built-in, replace its expander function
                // while still taking everything else from the source code.
1224 1225
                // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
                match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
1226
                    BuiltinMacroState::NotYetSeen(ext) => result.kind = ext,
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
                    BuiltinMacroState::AlreadySeen(span) => {
                        struct_span_err!(
                            self.session,
                            item.span,
                            E0773,
                            "attempted to define built-in macro more than once"
                        )
                        .span_note(span, "previously defined here")
                        .emit();
                    }
                }
1238 1239 1240 1241 1242 1243
            } else {
                let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
                self.session.span_err(item.span, &msg);
            }
        }

1244
        result
1245
    }
1246
}