macros.rs 37.6 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 7 8
use crate::{BuiltinMacroState, Determinacy};
use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet};
use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment};
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::intern::Interned;
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_hir::def::{self, DefKind, NonMacroAttrKind};
22
use rustc_hir::def_id::{CrateNum, LocalDefId};
23
use rustc_middle::middle::stability;
24
use rustc_middle::ty::RegisteredTools;
E
est31 已提交
25 26
use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE};
use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES};
27
use rustc_session::lint::BuiltinLintDiagnostics;
28
use rustc_session::parse::feature_err;
29
use rustc_session::Session;
30
use rustc_span::edition::Edition;
C
Camille GILLOT 已提交
31
use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
32
use rustc_span::hygiene::{AstPass, MacroKind};
33
use rustc_span::symbol::{kw, sym, Ident, Symbol};
34
use rustc_span::{Span, DUMMY_SP};
35
use std::cell::Cell;
36
use std::mem;
37

38
type Res = def::Res<NodeId>;
L
ljedrz 已提交
39

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

A
Alexander Regueiro 已提交
50 51 52
/// 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]`.
53
/// Some macro invocations need to introduce `macro_rules` scopes too because they
A
Alexander Regueiro 已提交
54
/// can potentially expand into macro definitions.
55
#[derive(Copy, Clone, Debug)]
56
pub enum MacroRulesScope<'a> {
57
    /// Empty "root" scope at the crate start containing no names.
J
Jeffrey Seyfried 已提交
58
    Empty,
A
Alexander Regueiro 已提交
59
    /// The scope introduced by a `macro_rules!` macro definition.
60
    Binding(&'a MacroRulesBinding<'a>),
A
Alexander Regueiro 已提交
61
    /// The scope introduced by a macro invocation that can potentially
62
    /// create a `macro_rules!` macro definition.
C
Camille GILLOT 已提交
63
    Invocation(LocalExpnId),
64 65
}

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

74 75 76
/// 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.
77 78 79 80
pub(crate) fn sub_namespace_match(
    candidate: Option<MacroKind>,
    requirement: Option<MacroKind>,
) -> bool {
81
    #[derive(PartialEq)]
M
Mark Rousskov 已提交
82 83 84 85
    enum SubNS {
        Bang,
        AttrLike,
    }
86
    let sub_ns = |kind| match kind {
87 88
        MacroKind::Bang => SubNS::Bang,
        MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
89
    };
90 91
    let candidate = candidate.map(sub_ns);
    let requirement = requirement.map(sub_ns);
92
    // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
93
    candidate.is_none() || requirement.is_none() || candidate == requirement
94 95
}

96 97 98
// We don't want to format a path using pretty-printing,
// `format!("{}", path)`, because that tries to insert
// line-breaks and is slow.
99 100
fn fast_print_path(path: &ast::Path) -> Symbol {
    if path.segments.len() == 1 {
101
        path.segments[0].ident.name
102 103 104 105 106 107 108
    } 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 {
109
                path_str.push_str(segment.ident.as_str())
110
            }
111
        }
112
        Symbol::intern(&path_str)
113 114 115
    }
}

V
Vadim Petrochenkov 已提交
116
/// The code common between processing `#![register_tool]` and `#![register_attr]`.
117 118 119 120 121 122 123
fn registered_idents(
    sess: &Session,
    attrs: &[ast::Attribute],
    attr_name: Symbol,
    descr: &str,
) -> FxHashSet<Ident> {
    let mut registered = FxHashSet::default();
124
    for attr in sess.filter_by_name(attrs, attr_name) {
125 126
        for nested_meta in attr.meta_item_list().unwrap_or_default() {
            match nested_meta.ident() {
M
Mark Rousskov 已提交
127 128 129 130 131 132 133
                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();
                    }
134 135 136 137 138 139 140 141 142 143 144 145
                }
                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
}

146
pub(crate) fn registered_attrs_and_tools(
147 148 149 150 151 152 153 154 155 156 157 158
    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)
}

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
// 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
}

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

184 185 186 187
    fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
        self.invocation_parents[&id].0
    }

188 189 190 191
    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 已提交
192
                ModuleKind::Def(.., name) if name != kw::Empty => name,
193
                _ => kw::Crate,
194
            }
195
        });
196 197
    }

C
Camille GILLOT 已提交
198 199 200 201 202
    fn visit_ast_fragment_with_placeholders(
        &mut self,
        expansion: LocalExpnId,
        fragment: &AstFragment,
    ) {
203
        // Integrate the new AST fragment into all the definition and module structures.
204 205
        // 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] };
206 207
        let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
        self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
208

209
        parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
210 211
    }

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

M
Matthew Jasper 已提交
220 221
    // 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.
222
    fn expansion_for_ast_pass(
223
        &mut self,
224
        call_site: Span,
225 226 227
        pass: AstPass,
        features: &[Symbol],
        parent_module_id: Option<NodeId>,
C
Camille GILLOT 已提交
228
    ) -> LocalExpnId {
229 230
        let parent_module =
            parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
C
Camille GILLOT 已提交
231
        let expn_id = LocalExpnId::fresh(
C
Camille GILLOT 已提交
232 233 234 235 236 237
            ExpnData::allow_unstable(
                ExpnKind::AstPass(pass),
                call_site,
                self.session.edition(),
                features.into(),
                None,
238
                parent_module,
C
Camille GILLOT 已提交
239 240 241
            ),
            self.create_stable_hashing_context(),
        );
242

243
        let parent_scope =
244
            parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
245
        self.ast_transform_scopes.insert(expn_id, parent_scope);
246

247
        expn_id
248 249
    }

250
    fn resolve_imports(&mut self) {
251
        ImportResolver { r: self }.resolve_imports()
252 253
    }

254
    fn resolve_macro_invocation(
M
Mark Rousskov 已提交
255 256
        &mut self,
        invoc: &Invocation,
C
Camille GILLOT 已提交
257
        eager_expansion_root: LocalExpnId,
M
Mark Rousskov 已提交
258
        force: bool,
259
    ) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
260 261 262 263 264 265 266
        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 已提交
267 268 269
                let parent_scope = *self
                    .invocation_parent_scopes
                    .get(&eager_expansion_root)
270 271 272 273 274 275
                    .expect("non-eager expansion without a parent scope");
                self.invocation_parent_scopes.insert(invoc_id, parent_scope);
                parent_scope
            }
        };

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

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

302
        let span = invoc.span();
303
        let def_id = res.opt_def_id();
C
Camille GILLOT 已提交
304 305 306 307 308
        invoc_id.set_expn_data(
            ext.expn_data(
                parent_scope.expansion,
                span,
                fast_print_path(path),
309 310
                def_id,
                def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
C
Camille GILLOT 已提交
311 312 313
            ),
            self.create_stable_hashing_context(),
        );
314

315
        Ok(ext)
316 317
    }

E
est31 已提交
318 319 320 321 322
    fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
        let did = self.local_def_id(id);
        self.unused_macro_rules.remove(&(did, rule_i));
    }

323
    fn check_unused_macros(&mut self) {
324 325 326 327 328 329 330
        for (_, &(node_id, ident)) in self.unused_macros.iter() {
            self.lint_buffer.buffer_lint(
                UNUSED_MACROS,
                node_id,
                ident.span,
                &format!("unused macro definition: `{}`", ident.as_str()),
            );
E
est31 已提交
331
        }
E
est31 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        for (&(def_id, arm_i), &(ident, rule_span)) in self.unused_macro_rules.iter() {
            if self.unused_macros.contains_key(&def_id) {
                // We already lint the entire macro as unused
                continue;
            }
            let node_id = self.def_id_to_node_id[def_id];
            self.lint_buffer.buffer_lint(
                UNUSED_MACRO_RULES,
                node_id,
                rule_span,
                &format!(
                    "{} rule of macro `{}` is never used",
                    crate::diagnostics::ordinalize(arm_i + 1),
                    ident.as_str()
                ),
            );
        }
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
        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() {
441
            match self.maybe_resolve_path(path, Some(ns), &parent_scope) {
442 443 444 445
                PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
                PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
                    return Ok(true);
                }
446 447 448
                PathResult::NonModule(..) |
                // HACK(Urgau): This shouldn't be necessary
                PathResult::Failed { is_error_from_last_segment: false, .. } => {
U
Urgau 已提交
449 450 451 452 453 454 455 456 457
                    self.session
                        .struct_span_err(span, "not sure whether the path is accessible or not")
                        .note("the type may have associated items, but we are currently not checking them")
                        .emit();

                    // If we get a partially resolved NonModule in one namespace, we should get the
                    // same result in any other namespaces, so we can return early.
                    return Ok(false);
                }
458
                PathResult::Indeterminate => indeterminate = true,
U
Urgau 已提交
459 460 461
                // We can only be sure that a path doesn't exist after having tested all the
                // posibilities, only at that time we can return false.
                PathResult::Failed { .. } => {}
462 463 464 465 466 467 468 469 470 471
                PathResult::Module(_) => panic!("unexpected path resolution"),
            }
        }

        if indeterminate {
            return Err(Indeterminate);
        }

        Ok(false)
    }
472 473 474 475

    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)
    }
476 477 478 479

    fn declare_proc_macro(&mut self, id: NodeId) {
        self.proc_macros.push(id)
    }
480 481 482 483

    fn registered_tools(&self) -> &RegisteredTools {
        &self.registered_tools
    }
484 485
}

J
John Kåre Alsaker 已提交
486
impl<'a> Resolver<'a> {
487
    /// Resolve macro path with error reporting and recovery.
488 489
    /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
    /// for better error recovery.
490
    fn smart_resolve_macro_path(
491 492 493
        &mut self,
        path: &ast::Path,
        kind: MacroKind,
494
        supports_macro_expansion: SupportsMacroExpansion,
495
        inner_attr: bool,
496
        parent_scope: &ParentScope<'a>,
497
        node_id: NodeId,
498
        force: bool,
499
        soft_custom_inner_attributes_gate: bool,
500
    ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
M
Mark Rousskov 已提交
501 502
        let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
        {
503 504 505 506 507
            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),
        };
508

509
        // Report errors for the resolved macro.
510 511 512
        for segment in &path.segments {
            if let Some(args) = &segment.args {
                self.session.span_err(args.span(), "generic arguments in macro path");
513
            }
514 515 516 517 518
            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",
                );
519
            }
520
        }
521

522
        match res {
523
            Res::Def(DefKind::Macro(_), def_id) => {
524 525 526
                if let Some(def_id) = def_id.as_local() {
                    self.unused_macros.remove(&def_id);
                    if self.proc_macro_stubs.contains(&def_id) {
527 528 529 530 531
                        self.session.span_err(
                            path.span,
                            "can't use a procedural macro from the same crate that defines it",
                        );
                    }
532
                }
533
            }
534
            Res::NonMacroAttr(..) | Res::Err => {}
535
            _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
536
        };
537

538
        self.check_stability_and_deprecation(&ext, path, node_id);
539

540 541
        let unexpected_res = if ext.macro_kind() != kind {
            Some((kind.article(), kind.descr_expected()))
542 543 544 545 546 547 548 549 550 551 552
        } 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
                    }
                }
            }
553 554 555 556
        } else {
            None
        };
        if let Some((article, expected)) = unexpected_res {
557 558
            let path_str = pprust::path_to_string(path);
            let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
M
Mark Rousskov 已提交
559 560
            self.session
                .struct_span_err(path.span, &msg)
561
                .span_label(path.span, format!("not {} {}", article, expected))
M
Mark Rousskov 已提交
562
                .emit();
563 564 565 566
            return Ok((self.dummy_ext(kind), Res::Err));
        }

        // We are trying to avoid reporting this error if other related errors were reported.
567 568
        if res != Res::Err
            && inner_attr
569 570
            && !self.session.features_untracked().custom_inner_attributes
        {
571 572 573 574 575
            let msg = match res {
                Res::Def(..) => "inner macro attributes are unstable",
                Res::NonMacroAttr(..) => "custom inner attributes are unstable",
                _ => unreachable!(),
            };
576
            if soft_custom_inner_attributes_gate {
577 578 579 580 581
                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();
            }
582 583 584
        }

        Ok((ext, res))
585
    }
586

587
    pub fn resolve_macro_path(
588 589
        &mut self,
        path: &ast::Path,
590
        kind: Option<MacroKind>,
591
        parent_scope: &ParentScope<'a>,
592
        trace: bool,
593
        force: bool,
594
    ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
595
        let path_span = path.span;
N
Nick Cameron 已提交
596
        let mut path = Segment::from_path(path);
597

598
        // Possibly apply the macro helper hack
M
Mark Rousskov 已提交
599 600 601 602
        if kind == Some(MacroKind::Bang)
            && path.len() == 1
            && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
        {
603
            let root = Ident::new(kw::DollarCrate, path[0].ident.span);
N
Nick Cameron 已提交
604
            path.insert(0, Segment::from_ident(root));
605 606
        }

607
        let res = if path.len() > 1 {
608
            let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) {
609
                PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
610
                    Ok(path_res.base_res())
611
                }
612
                PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
613 614 615
                PathResult::NonModule(..)
                | PathResult::Indeterminate
                | PathResult::Failed { .. } => Err(Determinacy::Determined),
616
                PathResult::Module(..) => unreachable!(),
617
            };
618

619
            if trace {
620
                let kind = kind.expect("macro kind must be specified if tracing is enabled");
M
Mark Rousskov 已提交
621 622 623 624 625 626 627
                self.multi_segment_macro_resolutions.push((
                    path,
                    path_span,
                    kind,
                    *parent_scope,
                    res.ok(),
                ));
628
            }
629

630 631
            self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
            res
632
        } else {
633
            let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
634
            let binding = self.early_resolve_ident_in_lexical_scope(
M
Mark Rousskov 已提交
635 636 637
                path[0].ident,
                scope_set,
                parent_scope,
638
                None,
M
Mark Rousskov 已提交
639
                force,
640
                None,
641
            );
642 643
            if let Err(Determinacy::Undetermined) = binding {
                return Err(Determinacy::Undetermined);
644
            }
645

646
            if trace {
647
                let kind = kind.expect("macro kind must be specified if tracing is enabled");
M
Mark Rousskov 已提交
648 649 650 651 652 653
                self.single_segment_macro_resolutions.push((
                    path[0].ident,
                    kind,
                    *parent_scope,
                    binding.ok(),
                ));
654
            }
655

656 657 658
            let res = binding.map(|binding| binding.res());
            self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
            res
659 660
        };

T
Takayuki Maeda 已提交
661
        res.map(|res| (self.get_macro(res).map(|macro_data| macro_data.ext), res))
662
    }
663

664
    pub(crate) fn finalize_macro_resolutions(&mut self) {
M
Mark Rousskov 已提交
665 666 667 668 669 670
        let check_consistency = |this: &mut Self,
                                 path: &[Segment],
                                 span,
                                 kind: MacroKind,
                                 initial_res: Option<Res>,
                                 res: Res| {
671
            if let Some(initial_res) = initial_res {
672
                if res != initial_res {
673 674
                    // Make sure compilation does not succeed if preferred macro resolution
                    // has changed after the macro had been expanded. In theory all such
675 676
                    // situations should be reported as errors, so this is a bug.
                    this.session.delay_span_bug(span, "inconsistent resolution for a macro");
677 678 679 680 681 682 683 684 685 686
                }
            } 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 已提交
687 688 689 690 691
                    let msg = format!(
                        "cannot determine resolution for the {} `{}`",
                        kind.descr(),
                        Segment::names_to_string(path)
                    );
692 693 694 695 696 697
                    let msg_note = "import resolution is stuck, try simplifying macro imports";
                    this.session.struct_span_err(span, &msg).note(msg_note).emit();
                }
            }
        };

698
        let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
699
        for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
700
            // FIXME: Path resolution will ICE if segment IDs present.
M
Mark Rousskov 已提交
701 702 703
            for seg in &mut path {
                seg.id = None;
            }
704
            match self.resolve_path(
M
Mark Rousskov 已提交
705 706 707
                &path,
                Some(MacroNS),
                &parent_scope,
708
                Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
709
                None,
710
            ) {
711
                PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
712 713
                    let res = path_res.base_res();
                    check_consistency(self, &path, path_span, kind, initial_res, res);
714
                }
715 716 717
                path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
                    let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
                        (span, label)
718
                    } else {
M
Mark Rousskov 已提交
719 720 721 722 723 724 725 726
                        (
                            path_span,
                            format!(
                                "partially resolved path in {} {}",
                                kind.article(),
                                kind.descr()
                            ),
                        )
727
                    };
M
Mark Rousskov 已提交
728 729 730 731
                    self.report_error(
                        span,
                        ResolutionError::FailedToResolve { label, suggestion: None },
                    );
732
                }
733
                PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
734 735 736
            }
        }

737
        let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
738
        for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
M
Mark Rousskov 已提交
739 740 741 742
            match self.early_resolve_ident_in_lexical_scope(
                ident,
                ScopeSet::Macro(kind),
                &parent_scope,
743
                Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
M
Mark Rousskov 已提交
744
                true,
745
                None,
M
Mark Rousskov 已提交
746
            ) {
747
                Ok(binding) => {
748
                    let initial_res = initial_binding.map(|initial_binding| {
749
                        self.record_use(ident, initial_binding, false);
750
                        initial_binding.res()
751
                    });
752
                    let res = binding.res();
V
Vadim Petrochenkov 已提交
753
                    let seg = Segment::from_ident(ident);
754
                    check_consistency(self, &[seg], ident.span, kind, initial_res, res);
755
                    if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
756 757 758 759
                        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]);
760 761
                        self.lint_buffer.buffer_lint_with_diagnostic(
                            LEGACY_DERIVE_HELPERS,
762
                            node_id,
763 764 765 766 767
                            ident.span,
                            "derive helper attribute is used before it is introduced",
                            BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
                        );
                    }
768
                }
769
                Err(..) => {
770
                    let expected = kind.descr_expected();
771
                    let msg = format!("cannot find {} `{}` in this scope", expected, ident);
772
                    let mut err = self.session.struct_span_err(ident.span, &msg);
773
                    self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
774
                    err.emit();
775
                }
776
            }
J
Jeffrey Seyfried 已提交
777
        }
778

779
        let builtin_attrs = mem::take(&mut self.builtin_attrs);
780
        for (ident, parent_scope) in builtin_attrs {
781
            let _ = self.early_resolve_ident_in_lexical_scope(
M
Mark Rousskov 已提交
782 783 784
                ident,
                ScopeSet::Macro(MacroKind::Attr),
                &parent_scope,
785
                Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
M
Mark Rousskov 已提交
786
                true,
787
                None,
788
            );
789
        }
790
    }
791

792 793 794 795 796 797
    fn check_stability_and_deprecation(
        &mut self,
        ext: &SyntaxExtension,
        path: &ast::Path,
        node_id: NodeId,
    ) {
798
        let span = path.span;
799
        if let Some(stability) = &ext.stability {
800
            if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
801 802
                let feature = stability.feature;
                if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
803
                    let lint_buffer = &mut self.lint_buffer;
M
Mark Rousskov 已提交
804 805
                    let soft_handler =
                        |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
806
                    stability::report_unstable(
M
Mark Rousskov 已提交
807 808 809 810
                        self.session,
                        feature,
                        reason,
                        issue,
811
                        None,
M
Mark Rousskov 已提交
812 813 814
                        is_soft,
                        span,
                        soft_handler,
815
                    );
816 817 818 819
                }
            }
        }
        if let Some(depr) = &ext.deprecation {
820
            let path = pprust::path_to_string(&path);
821
            let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
822 823 824 825 826 827
            stability::early_report_deprecation(
                &mut self.lint_buffer,
                &message,
                depr.suggestion,
                lint,
                span,
828
                node_id,
829
            );
830 831 832
        }
    }

M
Mark Rousskov 已提交
833 834 835 836 837 838
    fn prohibit_imported_non_macro_attrs(
        &self,
        binding: Option<&'a NameBinding<'a>>,
        res: Option<Res>,
        span: Span,
    ) {
839
        if let Some(Res::NonMacroAttr(kind)) = res {
840
            if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
V
Vadim Petrochenkov 已提交
841 842
                let msg =
                    format!("cannot use {} {} through an import", kind.article(), kind.descr());
843 844 845 846 847 848 849 850 851
                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();
            }
        }
    }

852
    pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
853 854
        // Reserve some names that are not quite covered by the general check
        // performed on `Resolver::builtin_attrs`.
855
        if ident.name == sym::cfg || ident.name == sym::cfg_attr {
T
Takayuki Maeda 已提交
856
            let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind());
857 858
            if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
                self.session.span_err(
M
Mark Rousskov 已提交
859 860
                    ident.span,
                    &format!("name `{}` is reserved in attribute namespace", ident),
861 862 863 864 865
                );
            }
        }
    }

E
est31 已提交
866 867 868
    /// Compile the macro into a `SyntaxExtension` and its rule spans.
    ///
    /// Possibly replace its expander to a pre-defined one for built-in macros.
869
    pub(crate) fn compile_macro(
E
est31 已提交
870 871 872
        &mut self,
        item: &ast::Item,
        edition: Edition,
873
    ) -> (SyntaxExtension, Vec<(usize, Span)>) {
E
est31 已提交
874
        let (mut result, mut rule_spans) = compile_declarative_macro(
875
            &self.session,
M
Mark Rousskov 已提交
876 877 878
            self.session.features_untracked(),
            item,
            edition,
879 880
        );

881
        if let Some(builtin_name) = result.builtin_name {
882
            // The macro was marked with `#[rustc_builtin_macro]`.
883
            if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
884 885
                // The macro is a built-in, replace its expander function
                // while still taking everything else from the source code.
886 887
                // 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)) {
888 889
                    BuiltinMacroState::NotYetSeen(ext) => {
                        result.kind = ext;
E
est31 已提交
890
                        rule_spans = Vec::new();
891 892 893 894 895
                        if item.id != ast::DUMMY_NODE_ID {
                            self.builtin_macro_kinds
                                .insert(self.local_def_id(item.id), result.macro_kind());
                        }
                    }
896 897 898 899 900 901 902 903 904 905 906
                    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();
                    }
                }
907 908 909 910 911 912
            } else {
                let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
                self.session.span_err(item.span, &msg);
            }
        }

E
est31 已提交
913
        (result, rule_spans)
914
    }
915
}