macros.rs 36.1 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 25
use rustc_middle::ty::RegisteredTools;
use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE, UNUSED_MACROS};
26
use rustc_session::lint::BuiltinLintDiagnostics;
27
use rustc_session::parse::feature_err;
28
use rustc_session::Session;
29
use rustc_span::edition::Edition;
C
Camille GILLOT 已提交
30
use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
31
use rustc_span::hygiene::{AstPass, MacroKind};
32
use rustc_span::symbol::{kw, sym, Ident, Symbol};
33
use rustc_span::{Span, DUMMY_SP};
34
use std::cell::Cell;
35
use std::mem;
36

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

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

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

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

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

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

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

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
// 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
}

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

180 181 182 183
    fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
        self.invocation_parents[&id].0
    }

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

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

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

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

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

239
        let parent_scope =
240
            parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
241
        self.ast_transform_scopes.insert(expn_id, parent_scope);
242

243
        expn_id
244 245
    }

246
    fn resolve_imports(&mut self) {
247
        ImportResolver { r: self }.resolve_imports()
248 249
    }

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

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

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

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

311
        Ok(ext)
312 313
    }

314
    fn check_unused_macros(&mut self) {
315 316 317 318 319 320 321
        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 已提交
322
        }
323
    }
324

C
Camille GILLOT 已提交
325
    fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
326
        self.containers_deriving_copy.contains(&expn_id)
327 328
    }

329 330
    fn resolve_derives(
        &mut self,
C
Camille GILLOT 已提交
331
        expn_id: LocalExpnId,
332
        force: bool,
333
        derive_paths: &dyn Fn() -> DeriveResolutions,
334 335 336 337 338 339 340
    ) -> 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`.
341 342 343 344 345 346 347
        // 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,
        });
348
        let parent_scope = self.invocation_parent_scopes[&expn_id];
349
        for (i, (path, _, opt_ext)) in entry.resolutions.iter_mut().enumerate() {
350 351 352 353 354 355 356 357 358 359 360 361 362 363
            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(
364 365 366
                                    ext.helper_attrs
                                        .iter()
                                        .map(|name| (i, Ident::new(*name, span))),
367 368 369 370 371 372 373 374 375 376 377 378 379 380
                                );
                            }
                            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);
                        }
                    },
                );
            }
381
        }
382 383 384 385
        // 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());
386 387
        // 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)]`.
388
        if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
389 390
            self.containers_deriving_copy.insert(expn_id);
        }
391 392
        assert!(self.derive_data.is_empty());
        self.derive_data = derive_data;
393 394 395
        Ok(())
    }

C
Camille GILLOT 已提交
396
    fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
397
        self.derive_data.remove(&expn_id).map(|data| data.resolutions)
398 399
    }

400 401 402 403
    // 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 已提交
404 405 406 407 408
    fn cfg_accessible(
        &mut self,
        expn_id: LocalExpnId,
        path: &ast::Path,
    ) -> Result<bool, Indeterminate> {
409 410 411 412 413 414
        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() {
415
            match self.maybe_resolve_path(path, Some(ns), &parent_scope) {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
                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)
    }
439 440 441 442

    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)
    }
443 444 445 446

    fn declare_proc_macro(&mut self, id: NodeId) {
        self.proc_macros.push(id)
    }
447 448 449 450

    fn registered_tools(&self) -> &RegisteredTools {
        &self.registered_tools
    }
451 452
}

J
John Kåre Alsaker 已提交
453
impl<'a> Resolver<'a> {
454
    /// Resolve macro path with error reporting and recovery.
455 456
    /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
    /// for better error recovery.
457
    fn smart_resolve_macro_path(
458 459 460
        &mut self,
        path: &ast::Path,
        kind: MacroKind,
461
        supports_macro_expansion: SupportsMacroExpansion,
462
        inner_attr: bool,
463
        parent_scope: &ParentScope<'a>,
464
        node_id: NodeId,
465
        force: bool,
466
        soft_custom_inner_attributes_gate: bool,
467
    ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
M
Mark Rousskov 已提交
468 469
        let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
        {
470 471 472 473 474
            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),
        };
475

476
        // Report errors for the resolved macro.
477 478 479
        for segment in &path.segments {
            if let Some(args) = &segment.args {
                self.session.span_err(args.span(), "generic arguments in macro path");
480
            }
481 482 483 484 485
            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",
                );
486
            }
487
        }
488

489
        match res {
490
            Res::Def(DefKind::Macro(_), def_id) => {
491 492 493
                if let Some(def_id) = def_id.as_local() {
                    self.unused_macros.remove(&def_id);
                    if self.proc_macro_stubs.contains(&def_id) {
494 495 496 497 498
                        self.session.span_err(
                            path.span,
                            "can't use a procedural macro from the same crate that defines it",
                        );
                    }
499
                }
500
            }
501
            Res::NonMacroAttr(..) | Res::Err => {}
502
            _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
503
        };
504

505
        self.check_stability_and_deprecation(&ext, path, node_id);
506

507 508
        let unexpected_res = if ext.macro_kind() != kind {
            Some((kind.article(), kind.descr_expected()))
509 510 511 512 513 514 515 516 517 518 519
        } 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
                    }
                }
            }
520 521 522 523
        } else {
            None
        };
        if let Some((article, expected)) = unexpected_res {
524 525
            let path_str = pprust::path_to_string(path);
            let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
M
Mark Rousskov 已提交
526 527
            self.session
                .struct_span_err(path.span, &msg)
528
                .span_label(path.span, format!("not {} {}", article, expected))
M
Mark Rousskov 已提交
529
                .emit();
530 531 532 533
            return Ok((self.dummy_ext(kind), Res::Err));
        }

        // We are trying to avoid reporting this error if other related errors were reported.
534 535
        if res != Res::Err
            && inner_attr
536 537
            && !self.session.features_untracked().custom_inner_attributes
        {
538 539 540 541 542
            let msg = match res {
                Res::Def(..) => "inner macro attributes are unstable",
                Res::NonMacroAttr(..) => "custom inner attributes are unstable",
                _ => unreachable!(),
            };
543
            if soft_custom_inner_attributes_gate {
544 545 546 547 548
                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();
            }
549 550 551
        }

        Ok((ext, res))
552
    }
553

554
    pub fn resolve_macro_path(
555 556
        &mut self,
        path: &ast::Path,
557
        kind: Option<MacroKind>,
558
        parent_scope: &ParentScope<'a>,
559
        trace: bool,
560
        force: bool,
561
    ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
562
        let path_span = path.span;
N
Nick Cameron 已提交
563
        let mut path = Segment::from_path(path);
564

565
        // Possibly apply the macro helper hack
M
Mark Rousskov 已提交
566 567 568 569
        if kind == Some(MacroKind::Bang)
            && path.len() == 1
            && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
        {
570
            let root = Ident::new(kw::DollarCrate, path[0].ident.span);
N
Nick Cameron 已提交
571
            path.insert(0, Segment::from_ident(root));
572 573
        }

574
        let res = if path.len() > 1 {
575
            let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) {
576
                PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
577
                    Ok(path_res.base_res())
578
                }
579
                PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
580 581 582
                PathResult::NonModule(..)
                | PathResult::Indeterminate
                | PathResult::Failed { .. } => Err(Determinacy::Determined),
583
                PathResult::Module(..) => unreachable!(),
584
            };
585

586
            if trace {
587
                let kind = kind.expect("macro kind must be specified if tracing is enabled");
M
Mark Rousskov 已提交
588 589 590 591 592 593 594
                self.multi_segment_macro_resolutions.push((
                    path,
                    path_span,
                    kind,
                    *parent_scope,
                    res.ok(),
                ));
595
            }
596

597 598
            self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
            res
599
        } else {
600
            let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
601
            let binding = self.early_resolve_ident_in_lexical_scope(
M
Mark Rousskov 已提交
602 603 604
                path[0].ident,
                scope_set,
                parent_scope,
605
                None,
M
Mark Rousskov 已提交
606
                force,
607 608
                false,
                None,
609
            );
610 611
            if let Err(Determinacy::Undetermined) = binding {
                return Err(Determinacy::Undetermined);
612
            }
613

614
            if trace {
615
                let kind = kind.expect("macro kind must be specified if tracing is enabled");
M
Mark Rousskov 已提交
616 617 618 619 620 621
                self.single_segment_macro_resolutions.push((
                    path[0].ident,
                    kind,
                    *parent_scope,
                    binding.ok(),
                ));
622
            }
623

624 625 626
            let res = binding.map(|binding| binding.res());
            self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
            res
627 628 629
        };

        res.map(|res| (self.get_macro(res), res))
630
    }
631

632
    crate fn finalize_macro_resolutions(&mut self) {
M
Mark Rousskov 已提交
633 634 635 636 637 638
        let check_consistency = |this: &mut Self,
                                 path: &[Segment],
                                 span,
                                 kind: MacroKind,
                                 initial_res: Option<Res>,
                                 res: Res| {
639
            if let Some(initial_res) = initial_res {
640
                if res != initial_res {
641 642
                    // Make sure compilation does not succeed if preferred macro resolution
                    // has changed after the macro had been expanded. In theory all such
643 644
                    // situations should be reported as errors, so this is a bug.
                    this.session.delay_span_bug(span, "inconsistent resolution for a macro");
645 646 647 648 649 650 651 652 653 654
                }
            } 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 已提交
655 656 657 658 659
                    let msg = format!(
                        "cannot determine resolution for the {} `{}`",
                        kind.descr(),
                        Segment::names_to_string(path)
                    );
660 661 662 663 664 665
                    let msg_note = "import resolution is stuck, try simplifying macro imports";
                    this.session.struct_span_err(span, &msg).note(msg_note).emit();
                }
            }
        };

666
        let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
667
        for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
668
            // FIXME: Path resolution will ICE if segment IDs present.
M
Mark Rousskov 已提交
669 670 671
            for seg in &mut path {
                seg.id = None;
            }
672
            match self.resolve_path(
M
Mark Rousskov 已提交
673 674 675
                &path,
                Some(MacroNS),
                &parent_scope,
676
                Finalize::SimplePath(ast::CRATE_NODE_ID, path_span),
677
                None,
678
            ) {
679
                PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
680 681
                    let res = path_res.base_res();
                    check_consistency(self, &path, path_span, kind, initial_res, res);
682
                }
683 684 685
                path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
                    let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
                        (span, label)
686
                    } else {
M
Mark Rousskov 已提交
687 688 689 690 691 692 693 694
                        (
                            path_span,
                            format!(
                                "partially resolved path in {} {}",
                                kind.article(),
                                kind.descr()
                            ),
                        )
695
                    };
M
Mark Rousskov 已提交
696 697 698 699
                    self.report_error(
                        span,
                        ResolutionError::FailedToResolve { label, suggestion: None },
                    );
700
                }
701
                PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
702 703 704
            }
        }

705
        let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
706
        for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
M
Mark Rousskov 已提交
707 708 709 710
            match self.early_resolve_ident_in_lexical_scope(
                ident,
                ScopeSet::Macro(kind),
                &parent_scope,
711
                Some(ident.span),
M
Mark Rousskov 已提交
712
                true,
713 714
                false,
                None,
M
Mark Rousskov 已提交
715
            ) {
716
                Ok(binding) => {
717
                    let initial_res = initial_binding.map(|initial_binding| {
718
                        self.record_use(ident, initial_binding, false);
719
                        initial_binding.res()
720
                    });
721
                    let res = binding.res();
V
Vadim Petrochenkov 已提交
722
                    let seg = Segment::from_ident(ident);
723
                    check_consistency(self, &[seg], ident.span, kind, initial_res, res);
724
                    if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
725 726 727 728
                        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]);
729 730
                        self.lint_buffer.buffer_lint_with_diagnostic(
                            LEGACY_DERIVE_HELPERS,
731
                            node_id,
732 733 734 735 736
                            ident.span,
                            "derive helper attribute is used before it is introduced",
                            BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
                        );
                    }
737
                }
738
                Err(..) => {
739
                    let expected = kind.descr_expected();
740
                    let msg = format!("cannot find {} `{}` in this scope", expected, ident);
741
                    let mut err = self.session.struct_span_err(ident.span, &msg);
742
                    self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
743
                    err.emit();
744
                }
745
            }
J
Jeffrey Seyfried 已提交
746
        }
747

748
        let builtin_attrs = mem::take(&mut self.builtin_attrs);
749
        for (ident, parent_scope) in builtin_attrs {
750
            let _ = self.early_resolve_ident_in_lexical_scope(
M
Mark Rousskov 已提交
751 752 753
                ident,
                ScopeSet::Macro(MacroKind::Attr),
                &parent_scope,
754
                Some(ident.span),
M
Mark Rousskov 已提交
755
                true,
756 757
                false,
                None,
758
            );
759
        }
760
    }
761

762 763 764 765 766 767
    fn check_stability_and_deprecation(
        &mut self,
        ext: &SyntaxExtension,
        path: &ast::Path,
        node_id: NodeId,
    ) {
768
        let span = path.span;
769
        if let Some(stability) = &ext.stability {
770
            if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
771 772
                let feature = stability.feature;
                if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
773
                    let lint_buffer = &mut self.lint_buffer;
M
Mark Rousskov 已提交
774 775
                    let soft_handler =
                        |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
776
                    stability::report_unstable(
M
Mark Rousskov 已提交
777 778 779 780
                        self.session,
                        feature,
                        reason,
                        issue,
781
                        None,
M
Mark Rousskov 已提交
782 783 784
                        is_soft,
                        span,
                        soft_handler,
785
                    );
786 787 788 789
                }
            }
        }
        if let Some(depr) = &ext.deprecation {
790
            let path = pprust::path_to_string(&path);
791
            let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
792 793 794 795 796 797
            stability::early_report_deprecation(
                &mut self.lint_buffer,
                &message,
                depr.suggestion,
                lint,
                span,
798
                node_id,
799
            );
800 801 802
        }
    }

M
Mark Rousskov 已提交
803 804 805 806 807 808
    fn prohibit_imported_non_macro_attrs(
        &self,
        binding: Option<&'a NameBinding<'a>>,
        res: Option<Res>,
        span: Span,
    ) {
809
        if let Some(Res::NonMacroAttr(kind)) = res {
810
            if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
V
Vadim Petrochenkov 已提交
811 812
                let msg =
                    format!("cannot use {} {} through an import", kind.article(), kind.descr());
813 814 815 816 817 818 819 820 821
                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();
            }
        }
    }

822 823 824
    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`.
825
        if ident.name == sym::cfg || ident.name == sym::cfg_attr {
826
            let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
827 828
            if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
                self.session.span_err(
M
Mark Rousskov 已提交
829 830
                    ident.span,
                    &format!("name `{}` is reserved in attribute namespace", ident),
831 832 833 834 835
                );
            }
        }
    }

836 837
    /// Compile the macro into a `SyntaxExtension` and possibly replace
    /// its expander to a pre-defined one for built-in macros.
838
    crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
839
        let mut result = compile_declarative_macro(
840
            &self.session,
M
Mark Rousskov 已提交
841 842 843
            self.session.features_untracked(),
            item,
            edition,
844 845
        );

846
        if let Some(builtin_name) = result.builtin_name {
847
            // The macro was marked with `#[rustc_builtin_macro]`.
848
            if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
849 850
                // The macro is a built-in, replace its expander function
                // while still taking everything else from the source code.
851 852
                // 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)) {
853 854 855 856 857 858 859
                    BuiltinMacroState::NotYetSeen(ext) => {
                        result.kind = ext;
                        if item.id != ast::DUMMY_NODE_ID {
                            self.builtin_macro_kinds
                                .insert(self.local_def_id(item.id), result.macro_kind());
                        }
                    }
860 861 862 863 864 865 866 867 868 869 870
                    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();
                    }
                }
871 872 873 874 875 876
            } else {
                let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
                self.session.span_err(item.span, &msg);
            }
        }

877
        result
878
    }
879
}