2019-08-13 02:46:42 +03:00
|
|
|
//! A bunch of methods and structures more or less related to resolving macros and
|
|
|
|
//! interface provided by `Resolver` to macro expander.
|
|
|
|
|
2023-06-18 12:15:17 +01:00
|
|
|
use crate::errors::{
|
2023-09-04 00:52:17 +08:00
|
|
|
self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope,
|
|
|
|
MacroExpectedFound, RemoveSurroundingDerive,
|
2023-06-18 12:15:17 +01:00
|
|
|
};
|
2019-02-07 02:15:23 +09:00
|
|
|
use crate::Namespace::*;
|
2022-03-26 20:59:09 +01:00
|
|
|
use crate::{BuiltinMacroState, Determinacy};
|
|
|
|
use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet};
|
2023-08-22 19:14:32 +08:00
|
|
|
use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment, ToNameBinding};
|
2023-03-10 22:39:14 +01:00
|
|
|
use rustc_ast::expand::StrippedCfgItem;
|
2023-06-10 00:06:34 +08:00
|
|
|
use rustc_ast::{self as ast, attr, Crate, Inline, ItemKind, ModKind, NodeId};
|
2020-01-11 17:02:46 +01:00
|
|
|
use rustc_ast_pretty::pprust;
|
2020-07-30 11:27:50 +10:00
|
|
|
use rustc_attr::StabilityLevel;
|
2022-02-04 14:26:29 +11:00
|
|
|
use rustc_data_structures::intern::Interned;
|
2020-11-19 01:49:20 +03:00
|
|
|
use rustc_data_structures::sync::Lrc;
|
2022-10-17 05:54:13 +08:00
|
|
|
use rustc_errors::{struct_span_err, Applicability};
|
2021-03-08 15:05:03 +03:00
|
|
|
use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand};
|
|
|
|
use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
|
2019-12-29 17:23:55 +03:00
|
|
|
use rustc_expand::compile_declarative_macro;
|
2021-03-01 16:02:09 -05:00
|
|
|
use rustc_expand::expand::{AstFragment, Invocation, InvocationKind, SupportsMacroExpansion};
|
2020-01-05 02:37:57 +01:00
|
|
|
use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
|
2023-08-22 19:14:32 +08:00
|
|
|
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
|
2020-03-29 17:19:48 +02:00
|
|
|
use rustc_middle::middle::stability;
|
2022-03-26 20:59:09 +01:00
|
|
|
use rustc_middle::ty::RegisteredTools;
|
2023-08-22 19:14:32 +08:00
|
|
|
use rustc_middle::ty::{TyCtxt, Visibility};
|
2023-04-28 13:04:35 +02:00
|
|
|
use rustc_session::lint::builtin::{
|
2023-06-02 13:55:46 +02:00
|
|
|
LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE, UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES,
|
2023-04-28 13:04:35 +02:00
|
|
|
};
|
2022-04-17 04:01:17 +02:00
|
|
|
use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES};
|
2020-11-14 14:47:14 +03:00
|
|
|
use rustc_session::lint::BuiltinLintDiagnostics;
|
2020-11-19 01:49:20 +03:00
|
|
|
use rustc_session::parse::feature_err;
|
2020-01-01 19:40:49 +01:00
|
|
|
use rustc_span::edition::Edition;
|
2021-06-25 20:43:04 +02:00
|
|
|
use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
|
2020-11-19 01:49:20 +03:00
|
|
|
use rustc_span::hygiene::{AstPass, MacroKind};
|
2020-04-19 13:00:18 +02:00
|
|
|
use rustc_span::symbol::{kw, sym, Ident, Symbol};
|
2019-12-31 20:15:40 +03:00
|
|
|
use rustc_span::{Span, DUMMY_SP};
|
2020-11-06 16:11:21 +03:00
|
|
|
use std::cell::Cell;
|
2022-03-26 20:59:09 +01:00
|
|
|
use std::mem;
|
2017-03-01 08:44:05 +00:00
|
|
|
|
2019-08-17 20:49:00 +03:00
|
|
|
type Res = def::Res<NodeId>;
|
2019-04-03 09:07:45 +02:00
|
|
|
|
2018-08-31 22:53:08 +03:00
|
|
|
/// Binding produced by a `macro_rules` item.
|
2020-03-14 01:06:36 +03:00
|
|
|
/// Not modularized, can shadow previous `macro_rules` bindings, etc.
|
2018-10-22 01:28:59 +03:00
|
|
|
#[derive(Debug)]
|
2023-02-05 23:05:46 +04:00
|
|
|
pub(crate) struct MacroRulesBinding<'a> {
|
2023-07-04 17:28:57 +03:00
|
|
|
pub(crate) binding: NameBinding<'a>,
|
2020-03-14 01:06:36 +03:00
|
|
|
/// `macro_rules` scope into which the `macro_rules` item was planted.
|
2022-05-20 19:51:09 -04:00
|
|
|
pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'a>,
|
|
|
|
pub(crate) ident: Ident,
|
2018-08-29 04:48:02 +03:00
|
|
|
}
|
|
|
|
|
2019-02-08 14:53:55 +01:00
|
|
|
/// 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]`.
|
2020-03-14 01:06:36 +03:00
|
|
|
/// Some macro invocations need to introduce `macro_rules` scopes too because they
|
2019-02-08 14:53:55 +01:00
|
|
|
/// can potentially expand into macro definitions.
|
2018-10-22 01:28:59 +03:00
|
|
|
#[derive(Copy, Clone, Debug)]
|
2023-02-05 23:05:46 +04:00
|
|
|
pub(crate) enum MacroRulesScope<'a> {
|
2018-08-31 22:53:08 +03:00
|
|
|
/// Empty "root" scope at the crate start containing no names.
|
2016-10-06 08:04:30 +00:00
|
|
|
Empty,
|
2019-02-08 14:53:55 +01:00
|
|
|
/// The scope introduced by a `macro_rules!` macro definition.
|
2020-03-14 01:06:36 +03:00
|
|
|
Binding(&'a MacroRulesBinding<'a>),
|
2019-02-08 14:53:55 +01:00
|
|
|
/// The scope introduced by a macro invocation that can potentially
|
2018-08-31 22:53:08 +03:00
|
|
|
/// create a `macro_rules!` macro definition.
|
2021-06-25 20:43:04 +02:00
|
|
|
Invocation(LocalExpnId),
|
2018-08-18 02:38:51 +03:00
|
|
|
}
|
|
|
|
|
2020-11-06 16:11:21 +03:00
|
|
|
/// `macro_rules!` scopes are always kept by reference and inside a cell.
|
2020-11-14 00:05:05 +03:00
|
|
|
/// The reason is that we update scopes with value `MacroRulesScope::Invocation(invoc_id)`
|
|
|
|
/// in-place after `invoc_id` gets expanded.
|
2020-11-06 16:11:21 +03:00
|
|
|
/// This helps to avoid uncontrollable growth of `macro_rules!` scope chains,
|
2022-03-30 15:14:15 -04:00
|
|
|
/// which usually grow linearly with the number of macro invocations
|
2020-11-06 16:11:21 +03:00
|
|
|
/// in a module (including derives) and hurt performance.
|
2022-02-04 14:26:29 +11:00
|
|
|
pub(crate) type MacroRulesScopeRef<'a> = Interned<'a, Cell<MacroRulesScope<'a>>>;
|
2020-11-06 16:11:21 +03:00
|
|
|
|
2022-03-26 20:59:09 +01:00
|
|
|
/// 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.
|
2022-05-20 19:51:09 -04:00
|
|
|
pub(crate) fn sub_namespace_match(
|
|
|
|
candidate: Option<MacroKind>,
|
|
|
|
requirement: Option<MacroKind>,
|
|
|
|
) -> bool {
|
2018-09-08 22:19:53 +03:00
|
|
|
#[derive(PartialEq)]
|
|
|
|
enum SubNS {
|
|
|
|
Bang,
|
|
|
|
AttrLike,
|
|
|
|
}
|
|
|
|
let sub_ns = |kind| match kind {
|
2019-06-18 22:23:13 +03:00
|
|
|
MacroKind::Bang => SubNS::Bang,
|
|
|
|
MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
|
2018-09-08 22:19:53 +03:00
|
|
|
};
|
2019-06-18 22:23:13 +03:00
|
|
|
let candidate = candidate.map(sub_ns);
|
|
|
|
let requirement = requirement.map(sub_ns);
|
2018-09-08 22:19:53 +03:00
|
|
|
// "No specific sub-namespace" means "matches anything" for both requirements and candidates.
|
2018-11-08 00:39:07 +03:00
|
|
|
candidate.is_none() || requirement.is_none() || candidate == requirement
|
2018-09-11 00:28:35 +03:00
|
|
|
}
|
|
|
|
|
2019-06-18 10:48:44 +03:00
|
|
|
// We don't want to format a path using pretty-printing,
|
|
|
|
// `format!("{}", path)`, because that tries to insert
|
|
|
|
// line-breaks and is slow.
|
2019-06-30 15:58:56 +03:00
|
|
|
fn fast_print_path(path: &ast::Path) -> Symbol {
|
|
|
|
if path.segments.len() == 1 {
|
2020-03-20 15:03:11 +01:00
|
|
|
path.segments[0].ident.name
|
2019-06-30 15:58:56 +03:00
|
|
|
} 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 {
|
2021-12-15 16:13:11 +11:00
|
|
|
path_str.push_str(segment.ident.as_str())
|
2019-06-30 15:58:56 +03:00
|
|
|
}
|
2019-06-18 10:48:44 +03:00
|
|
|
}
|
2019-06-30 15:58:56 +03:00
|
|
|
Symbol::intern(&path_str)
|
2019-06-18 10:48:44 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-06 10:56:23 +00:00
|
|
|
pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools {
|
|
|
|
let mut registered_tools = RegisteredTools::default();
|
2023-03-14 16:53:04 +04:00
|
|
|
let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow();
|
|
|
|
for attr in attr::filter_by_name(pre_configured_attrs, sym::register_tool) {
|
2019-11-03 20:28:20 +03:00
|
|
|
for nested_meta in attr.meta_item_list().unwrap_or_default() {
|
|
|
|
match nested_meta.ident() {
|
|
|
|
Some(ident) => {
|
2022-08-28 21:23:23 +09:00
|
|
|
if let Some(old_ident) = registered_tools.replace(ident) {
|
|
|
|
let msg = format!("{} `{}` was already registered", "tool", ident);
|
2023-03-06 10:56:23 +00:00
|
|
|
tcx.sess
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
.struct_span_err(ident.span, msg)
|
2019-11-03 20:28:20 +03:00
|
|
|
.span_label(old_ident.span, "already registered here")
|
|
|
|
.emit();
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2019-11-03 20:28:20 +03:00
|
|
|
}
|
|
|
|
None => {
|
2022-08-28 21:23:23 +09:00
|
|
|
let msg = format!("`{}` only accepts identifiers", sym::register_tool);
|
2019-11-03 20:28:20 +03:00
|
|
|
let span = nested_meta.span();
|
2023-03-06 10:56:23 +00:00
|
|
|
tcx.sess
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
.struct_span_err(span, msg)
|
2023-03-06 10:56:23 +00:00
|
|
|
.span_label(span, "not an identifier")
|
|
|
|
.emit();
|
2019-11-03 20:28:20 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-04-28 13:04:35 +02:00
|
|
|
// We implicitly add `rustfmt`, `clippy`, `diagnostic` to known tools,
|
2019-11-03 20:28:20 +03:00
|
|
|
// but it's not an error to register them explicitly.
|
2023-04-28 13:04:35 +02:00
|
|
|
let predefined_tools = [sym::clippy, sym::rustfmt, sym::diagnostic];
|
2019-11-03 20:28:20 +03:00
|
|
|
registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
|
2022-08-28 21:23:23 +09:00
|
|
|
registered_tools
|
2019-11-03 20:28:20 +03:00
|
|
|
}
|
|
|
|
|
2021-02-21 16:32:38 +03:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2022-12-08 12:59:02 +00:00
|
|
|
impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> {
|
2019-08-17 20:49:00 +03:00
|
|
|
fn next_node_id(&mut self) -> NodeId {
|
2019-11-03 17:38:02 -05:00
|
|
|
self.next_node_id()
|
2016-09-05 00:10:27 +00:00
|
|
|
}
|
|
|
|
|
2021-05-02 21:19:28 +02:00
|
|
|
fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
|
|
|
|
self.invocation_parents[&id].0
|
|
|
|
}
|
|
|
|
|
2019-07-05 03:09:24 +03:00
|
|
|
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 {
|
2020-12-29 20:28:08 -05:00
|
|
|
ModuleKind::Def(.., name) if name != kw::Empty => name,
|
2019-07-05 03:09:24 +03:00
|
|
|
_ => kw::Crate,
|
2018-12-28 00:31:28 +03:00
|
|
|
}
|
2019-07-05 03:09:24 +03:00
|
|
|
});
|
2018-12-28 00:31:28 +03:00
|
|
|
}
|
|
|
|
|
2021-06-25 20:43:04 +02:00
|
|
|
fn visit_ast_fragment_with_placeholders(
|
|
|
|
&mut self,
|
|
|
|
expansion: LocalExpnId,
|
|
|
|
fragment: &AstFragment,
|
|
|
|
) {
|
2019-08-17 19:32:52 +03:00
|
|
|
// Integrate the new AST fragment into all the definition and module structures.
|
2019-08-13 03:34:46 +03:00
|
|
|
// 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] };
|
2020-03-14 01:06:36 +03:00
|
|
|
let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
|
|
|
|
self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
|
2019-08-17 19:32:52 +03:00
|
|
|
|
2019-08-17 20:49:00 +03:00
|
|
|
parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
|
2016-09-07 23:21:59 +00:00
|
|
|
}
|
|
|
|
|
2021-01-10 14:36:30 +03:00
|
|
|
fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
|
|
|
|
if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx
|
|
|
|
.sess
|
2021-01-10 14:36:30 +03:00
|
|
|
.diagnostic()
|
2023-07-25 23:04:01 +02:00
|
|
|
.bug(format!("built-in macro `{name}` was already registered"));
|
2018-09-04 01:14:58 +03:00
|
|
|
}
|
2016-09-07 23:21:59 +00:00
|
|
|
}
|
|
|
|
|
2019-09-05 15:05:58 +01:00
|
|
|
// 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.
|
2019-08-28 12:41:29 +03:00
|
|
|
fn expansion_for_ast_pass(
|
2019-08-25 20:58:03 +01:00
|
|
|
&mut self,
|
2019-08-28 12:41:29 +03:00
|
|
|
call_site: Span,
|
2019-08-25 20:58:03 +01:00
|
|
|
pass: AstPass,
|
|
|
|
features: &[Symbol],
|
|
|
|
parent_module_id: Option<NodeId>,
|
2021-06-25 20:43:04 +02:00
|
|
|
) -> LocalExpnId {
|
2021-09-12 01:59:05 +03:00
|
|
|
let parent_module =
|
|
|
|
parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
|
2021-06-25 20:43:04 +02:00
|
|
|
let expn_id = LocalExpnId::fresh(
|
2021-06-22 19:20:25 +02:00
|
|
|
ExpnData::allow_unstable(
|
|
|
|
ExpnKind::AstPass(pass),
|
|
|
|
call_site,
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx.sess.edition(),
|
2021-06-22 19:20:25 +02:00
|
|
|
features.into(),
|
|
|
|
None,
|
2021-09-12 01:59:05 +03:00
|
|
|
parent_module,
|
2021-06-22 19:20:25 +02:00
|
|
|
),
|
|
|
|
self.create_stable_hashing_context(),
|
|
|
|
);
|
2019-08-28 12:41:29 +03:00
|
|
|
|
2021-09-12 01:59:05 +03:00
|
|
|
let parent_scope =
|
2021-09-12 02:06:27 +03:00
|
|
|
parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
|
2019-08-25 20:58:03 +01:00
|
|
|
self.ast_transform_scopes.insert(expn_id, parent_scope);
|
2021-06-28 19:29:55 +02:00
|
|
|
|
2019-08-28 12:41:29 +03:00
|
|
|
expn_id
|
2019-08-25 20:58:03 +01:00
|
|
|
}
|
|
|
|
|
2016-11-10 10:11:25 +00:00
|
|
|
fn resolve_imports(&mut self) {
|
2023-02-22 21:20:54 +04:00
|
|
|
self.resolve_imports()
|
2016-11-10 10:11:25 +00:00
|
|
|
}
|
|
|
|
|
2019-08-20 00:24:28 +03:00
|
|
|
fn resolve_macro_invocation(
|
|
|
|
&mut self,
|
|
|
|
invoc: &Invocation,
|
2021-06-25 20:43:04 +02:00
|
|
|
eager_expansion_root: LocalExpnId,
|
2019-08-20 00:24:28 +03:00
|
|
|
force: bool,
|
2020-11-14 14:47:14 +03:00
|
|
|
) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
|
2019-08-20 00:24:28 +03:00
|
|
|
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.
|
|
|
|
let parent_scope = *self
|
|
|
|
.invocation_parent_scopes
|
|
|
|
.get(&eager_expansion_root)
|
|
|
|
.expect("non-eager expansion without a parent scope");
|
|
|
|
self.invocation_parent_scopes.insert(invoc_id, parent_scope);
|
|
|
|
parent_scope
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-11-14 14:47:14 +03:00
|
|
|
let (path, kind, inner_attr, derives) = match invoc.kind {
|
|
|
|
InvocationKind::Attr { ref attr, ref derives, .. } => (
|
2019-10-24 06:33:12 +11:00
|
|
|
&attr.get_normal_item().path,
|
2019-10-24 06:40:35 +11:00
|
|
|
MacroKind::Attr,
|
2020-11-19 01:49:20 +03:00
|
|
|
attr.style == ast::AttrStyle::Inner,
|
2019-10-24 06:40:35 +11:00
|
|
|
self.arenas.alloc_ast_paths(derives),
|
2018-08-13 02:57:19 +03:00
|
|
|
),
|
2020-11-14 14:47:14 +03:00
|
|
|
InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
|
|
|
|
InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
|
2017-03-01 23:48:16 +00:00
|
|
|
};
|
2018-08-11 16:40:08 +03:00
|
|
|
|
2019-08-12 23:39:49 +03:00
|
|
|
// Derives are not included when `invocations` are collected, so we have to add them here.
|
2019-08-13 01:39:10 +03:00
|
|
|
let parent_scope = &ParentScope { derives, ..parent_scope };
|
2021-03-01 16:02:09 -05:00
|
|
|
let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
|
2021-07-14 18:24:12 -05:00
|
|
|
let node_id = invoc.expansion_data.lint_node_id;
|
2020-11-19 01:49:20 +03:00
|
|
|
let (ext, res) = self.smart_resolve_macro_path(
|
|
|
|
path,
|
|
|
|
kind,
|
2021-03-01 16:02:09 -05:00
|
|
|
supports_macro_expansion,
|
2020-11-19 01:49:20 +03:00
|
|
|
inner_attr,
|
|
|
|
parent_scope,
|
|
|
|
node_id,
|
|
|
|
force,
|
2021-02-21 16:32:38 +03:00
|
|
|
soft_custom_inner_attributes_gate(path, invoc),
|
2020-11-19 01:49:20 +03:00
|
|
|
)?;
|
2018-08-15 03:51:12 +03:00
|
|
|
|
2019-06-20 22:00:47 +03:00
|
|
|
let span = invoc.span();
|
2021-09-12 01:47:46 +03:00
|
|
|
let def_id = res.opt_def_id();
|
2021-06-22 19:20:25 +02:00
|
|
|
invoc_id.set_expn_data(
|
|
|
|
ext.expn_data(
|
|
|
|
parent_scope.expansion,
|
|
|
|
span,
|
|
|
|
fast_print_path(path),
|
2021-09-12 01:47:46 +03:00
|
|
|
def_id,
|
|
|
|
def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
|
2021-06-22 19:20:25 +02:00
|
|
|
),
|
|
|
|
self.create_stable_hashing_context(),
|
|
|
|
);
|
2019-06-21 01:59:30 +03:00
|
|
|
|
2020-11-14 14:47:14 +03:00
|
|
|
Ok(ext)
|
2017-03-01 23:48:16 +00:00
|
|
|
}
|
|
|
|
|
2022-04-17 04:01:17 +02:00
|
|
|
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));
|
|
|
|
}
|
|
|
|
|
2019-10-25 09:15:33 -04:00
|
|
|
fn check_unused_macros(&mut self) {
|
2021-11-10 12:00:46 +01:00
|
|
|
for (_, &(node_id, ident)) in self.unused_macros.iter() {
|
|
|
|
self.lint_buffer.buffer_lint(
|
|
|
|
UNUSED_MACROS,
|
|
|
|
node_id,
|
|
|
|
ident.span,
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
format!("unused macro definition: `{}`", ident.name),
|
2021-11-10 12:00:46 +01:00
|
|
|
);
|
2017-05-11 10:26:07 +02:00
|
|
|
}
|
2022-04-17 04:01:17 +02:00
|
|
|
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,
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
format!(
|
2022-04-17 04:01:17 +02:00
|
|
|
"{} rule of macro `{}` is never used",
|
|
|
|
crate::diagnostics::ordinalize(arm_i + 1),
|
2022-07-18 14:25:34 +09:00
|
|
|
ident.name
|
2022-04-17 04:01:17 +02:00
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
2017-03-01 23:48:16 +00:00
|
|
|
}
|
2019-08-03 04:22:44 +03:00
|
|
|
|
2021-06-25 20:43:04 +02:00
|
|
|
fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
|
2019-11-04 10:09:58 +01:00
|
|
|
self.containers_deriving_copy.contains(&expn_id)
|
2019-08-03 04:22:44 +03:00
|
|
|
}
|
|
|
|
|
2020-11-14 14:47:14 +03:00
|
|
|
fn resolve_derives(
|
|
|
|
&mut self,
|
2021-06-25 20:43:04 +02:00
|
|
|
expn_id: LocalExpnId,
|
2020-11-14 14:47:14 +03:00
|
|
|
force: bool,
|
2021-03-08 15:05:03 +03:00
|
|
|
derive_paths: &dyn Fn() -> DeriveResolutions,
|
2020-11-14 14:47:14 +03:00
|
|
|
) -> 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`.
|
2021-03-08 15:05:03 +03:00
|
|
|
// 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,
|
|
|
|
});
|
2020-11-14 14:47:14 +03:00
|
|
|
let parent_scope = self.invocation_parent_scopes[&expn_id];
|
2022-09-20 11:55:07 +00:00
|
|
|
for (i, (path, _, opt_ext, _)) in entry.resolutions.iter_mut().enumerate() {
|
2021-03-08 15:05:03 +03:00
|
|
|
if opt_ext.is_none() {
|
|
|
|
*opt_ext = Some(
|
|
|
|
match self.resolve_macro_path(
|
2023-11-21 20:07:32 +01:00
|
|
|
path,
|
2021-03-08 15:05:03 +03:00
|
|
|
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(
|
2021-04-04 17:51:31 +03:00
|
|
|
ext.helper_attrs
|
|
|
|
.iter()
|
|
|
|
.map(|name| (i, Ident::new(*name, span))),
|
2021-03-08 15:05:03 +03:00
|
|
|
);
|
|
|
|
}
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
2020-11-14 14:47:14 +03:00
|
|
|
}
|
2021-04-04 17:51:31 +03:00
|
|
|
// Sort helpers in a stable way independent from the derive resolution order.
|
|
|
|
entry.helper_attrs.sort_by_key(|(i, _)| *i);
|
2023-08-22 19:14:32 +08:00
|
|
|
let helper_attrs = entry
|
|
|
|
.helper_attrs
|
|
|
|
.iter()
|
|
|
|
.map(|(_, ident)| {
|
|
|
|
let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
|
|
|
|
let binding = (res, Visibility::<DefId>::Public, ident.span, expn_id)
|
|
|
|
.to_name_binding(self.arenas);
|
|
|
|
(*ident, binding)
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
self.helper_attrs.insert(expn_id, helper_attrs);
|
2020-11-14 14:47:14 +03:00
|
|
|
// 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)]`.
|
2021-03-08 15:05:03 +03:00
|
|
|
if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
|
2020-11-14 14:47:14 +03:00
|
|
|
self.containers_deriving_copy.insert(expn_id);
|
|
|
|
}
|
2021-03-08 15:05:03 +03:00
|
|
|
assert!(self.derive_data.is_empty());
|
|
|
|
self.derive_data = derive_data;
|
2020-11-14 14:47:14 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-06-25 20:43:04 +02:00
|
|
|
fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
|
2021-03-08 15:05:03 +03:00
|
|
|
self.derive_data.remove(&expn_id).map(|data| data.resolutions)
|
2020-11-14 14:47:14 +03:00
|
|
|
}
|
|
|
|
|
2020-03-10 00:56:20 +03:00
|
|
|
// 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.
|
2021-06-25 20:43:04 +02:00
|
|
|
fn cfg_accessible(
|
|
|
|
&mut self,
|
|
|
|
expn_id: LocalExpnId,
|
|
|
|
path: &ast::Path,
|
|
|
|
) -> Result<bool, Indeterminate> {
|
2020-03-10 00:56:20 +03:00
|
|
|
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() {
|
2022-04-08 22:50:56 +02:00
|
|
|
match self.maybe_resolve_path(path, Some(ns), &parent_scope) {
|
2020-03-10 00:56:20 +03:00
|
|
|
PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
|
|
|
|
PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
|
|
|
|
return Ok(true);
|
|
|
|
}
|
2022-05-25 20:08:27 +02:00
|
|
|
PathResult::NonModule(..) |
|
|
|
|
// HACK(Urgau): This shouldn't be necessary
|
|
|
|
PathResult::Failed { is_error_from_last_segment: false, .. } => {
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx.sess
|
2023-04-10 16:04:14 +01:00
|
|
|
.emit_err(errors::CfgAccessibleUnsure { span });
|
2022-05-20 21:27:34 +02:00
|
|
|
|
|
|
|
// 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);
|
|
|
|
}
|
2020-03-10 00:56:20 +03:00
|
|
|
PathResult::Indeterminate => indeterminate = true,
|
2022-05-20 21:27:34 +02:00
|
|
|
// We can only be sure that a path doesn't exist after having tested all the
|
2022-08-18 10:13:37 +08:00
|
|
|
// possibilities, only at that time we can return false.
|
2022-05-20 21:27:34 +02:00
|
|
|
PathResult::Failed { .. } => {}
|
2020-03-10 00:56:20 +03:00
|
|
|
PathResult::Module(_) => panic!("unexpected path resolution"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if indeterminate {
|
|
|
|
return Err(Indeterminate);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(false)
|
|
|
|
}
|
Implement span quoting for proc-macros
This PR implements span quoting, allowing proc-macros to produce spans
pointing *into their own crate*. This is used by the unstable
`proc_macro::quote!` macro, allowing us to get error messages like this:
```
error[E0412]: cannot find type `MissingType` in this scope
--> $DIR/auxiliary/span-from-proc-macro.rs:37:20
|
LL | pub fn error_from_attribute(_args: TokenStream, _input: TokenStream) -> TokenStream {
| ----------------------------------------------------------------------------------- in this expansion of procedural macro `#[error_from_attribute]`
...
LL | field: MissingType
| ^^^^^^^^^^^ not found in this scope
|
::: $DIR/span-from-proc-macro.rs:8:1
|
LL | #[error_from_attribute]
| ----------------------- in this macro invocation
```
Here, `MissingType` occurs inside the implementation of the proc-macro
`#[error_from_attribute]`. Previosuly, this would always result in a
span pointing at `#[error_from_attribute]`
This will make many proc-macro-related error message much more useful -
when a proc-macro generates code containing an error, users will get an
error message pointing directly at that code (within the macro
definition), instead of always getting a span pointing at the macro
invocation site.
This is implemented as follows:
* When a proc-macro crate is being *compiled*, it causes the `quote!`
macro to get run. This saves all of the sapns in the input to `quote!`
into the metadata of *the proc-macro-crate* (which we are currently
compiling). The `quote!` macro then expands to a call to
`proc_macro::Span::recover_proc_macro_span(id)`, where `id` is an
opaque identifier for the span in the crate metadata.
* When the same proc-macro crate is *run* (e.g. it is loaded from disk
and invoked by some consumer crate), the call to
`proc_macro::Span::recover_proc_macro_span` causes us to load the span
from the proc-macro crate's metadata. The proc-macro then produces a
`TokenStream` containing a `Span` pointing into the proc-macro crate
itself.
The recursive nature of 'quote!' can be difficult to understand at
first. The file `src/test/ui/proc-macro/quote-debug.stdout` shows
the output of the `quote!` macro, which should make this eaier to
understand.
This PR also supports custom quoting spans in custom quote macros (e.g.
the `quote` crate). All span quoting goes through the
`proc_macro::quote_span` method, which can be called by a custom quote
macro to perform span quoting. An example of this usage is provided in
`src/test/ui/proc-macro/auxiliary/custom-quote.rs`
Custom quoting currently has a few limitations:
In order to quote a span, we need to generate a call to
`proc_macro::Span::recover_proc_macro_span`. However, proc-macros
support renaming the `proc_macro` crate, so we can't simply hardcode
this path. Previously, the `quote_span` method used the path
`crate::Span` - however, this only works when it is called by the
builtin `quote!` macro in the same crate. To support being called from
arbitrary crates, we need access to the name of the `proc_macro` crate
to generate a path. This PR adds an additional argument to `quote_span`
to specify the name of the `proc_macro` crate. Howver, this feels kind
of hacky, and we may want to change this before stabilizing anything
quote-related.
Additionally, using `quote_span` currently requires enabling the
`proc_macro_internals` feature. The builtin `quote!` macro
has an `#[allow_internal_unstable]` attribute, but this won't work for
custom quote implementations. This will likely require some additional
tricks to apply `allow_internal_unstable` to the span of
`proc_macro::Span::recover_proc_macro_span`.
2020-08-02 19:52:16 -04:00
|
|
|
|
|
|
|
fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
|
2023-02-20 10:38:48 +00:00
|
|
|
self.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.tcx.sess)
|
Implement span quoting for proc-macros
This PR implements span quoting, allowing proc-macros to produce spans
pointing *into their own crate*. This is used by the unstable
`proc_macro::quote!` macro, allowing us to get error messages like this:
```
error[E0412]: cannot find type `MissingType` in this scope
--> $DIR/auxiliary/span-from-proc-macro.rs:37:20
|
LL | pub fn error_from_attribute(_args: TokenStream, _input: TokenStream) -> TokenStream {
| ----------------------------------------------------------------------------------- in this expansion of procedural macro `#[error_from_attribute]`
...
LL | field: MissingType
| ^^^^^^^^^^^ not found in this scope
|
::: $DIR/span-from-proc-macro.rs:8:1
|
LL | #[error_from_attribute]
| ----------------------- in this macro invocation
```
Here, `MissingType` occurs inside the implementation of the proc-macro
`#[error_from_attribute]`. Previosuly, this would always result in a
span pointing at `#[error_from_attribute]`
This will make many proc-macro-related error message much more useful -
when a proc-macro generates code containing an error, users will get an
error message pointing directly at that code (within the macro
definition), instead of always getting a span pointing at the macro
invocation site.
This is implemented as follows:
* When a proc-macro crate is being *compiled*, it causes the `quote!`
macro to get run. This saves all of the sapns in the input to `quote!`
into the metadata of *the proc-macro-crate* (which we are currently
compiling). The `quote!` macro then expands to a call to
`proc_macro::Span::recover_proc_macro_span(id)`, where `id` is an
opaque identifier for the span in the crate metadata.
* When the same proc-macro crate is *run* (e.g. it is loaded from disk
and invoked by some consumer crate), the call to
`proc_macro::Span::recover_proc_macro_span` causes us to load the span
from the proc-macro crate's metadata. The proc-macro then produces a
`TokenStream` containing a `Span` pointing into the proc-macro crate
itself.
The recursive nature of 'quote!' can be difficult to understand at
first. The file `src/test/ui/proc-macro/quote-debug.stdout` shows
the output of the `quote!` macro, which should make this eaier to
understand.
This PR also supports custom quoting spans in custom quote macros (e.g.
the `quote` crate). All span quoting goes through the
`proc_macro::quote_span` method, which can be called by a custom quote
macro to perform span quoting. An example of this usage is provided in
`src/test/ui/proc-macro/auxiliary/custom-quote.rs`
Custom quoting currently has a few limitations:
In order to quote a span, we need to generate a call to
`proc_macro::Span::recover_proc_macro_span`. However, proc-macros
support renaming the `proc_macro` crate, so we can't simply hardcode
this path. Previously, the `quote_span` method used the path
`crate::Span` - however, this only works when it is called by the
builtin `quote!` macro in the same crate. To support being called from
arbitrary crates, we need access to the name of the `proc_macro` crate
to generate a path. This PR adds an additional argument to `quote_span`
to specify the name of the `proc_macro` crate. Howver, this feels kind
of hacky, and we may want to change this before stabilizing anything
quote-related.
Additionally, using `quote_span` currently requires enabling the
`proc_macro_internals` feature. The builtin `quote!` macro
has an `#[allow_internal_unstable]` attribute, but this won't work for
custom quote implementations. This will likely require some additional
tricks to apply `allow_internal_unstable` to the span of
`proc_macro::Span::recover_proc_macro_span`.
2020-08-02 19:52:16 -04:00
|
|
|
}
|
2021-07-16 22:22:08 +02:00
|
|
|
|
|
|
|
fn declare_proc_macro(&mut self, id: NodeId) {
|
|
|
|
self.proc_macros.push(id)
|
|
|
|
}
|
2021-09-29 01:17:54 +03:00
|
|
|
|
2023-03-10 22:39:14 +01:00
|
|
|
fn append_stripped_cfg_item(&mut self, parent_node: NodeId, name: Ident, cfg: ast::MetaItem) {
|
|
|
|
self.stripped_cfg_items.push(StrippedCfgItem { parent_module: parent_node, name, cfg });
|
|
|
|
}
|
|
|
|
|
2021-09-29 01:17:54 +03:00
|
|
|
fn registered_tools(&self) -> &RegisteredTools {
|
2023-11-21 20:07:32 +01:00
|
|
|
self.registered_tools
|
2021-09-29 01:17:54 +03:00
|
|
|
}
|
2017-03-01 23:48:16 +00:00
|
|
|
}
|
|
|
|
|
2022-12-08 12:59:02 +00:00
|
|
|
impl<'a, 'tcx> Resolver<'a, 'tcx> {
|
2019-07-03 23:59:03 +03:00
|
|
|
/// Resolve macro path with error reporting and recovery.
|
2020-11-19 01:49:20 +03:00
|
|
|
/// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
|
|
|
|
/// for better error recovery.
|
2019-07-03 23:59:03 +03:00
|
|
|
fn smart_resolve_macro_path(
|
2018-09-13 01:41:07 +03:00
|
|
|
&mut self,
|
|
|
|
path: &ast::Path,
|
|
|
|
kind: MacroKind,
|
2021-03-01 16:02:09 -05:00
|
|
|
supports_macro_expansion: SupportsMacroExpansion,
|
2020-11-19 01:49:20 +03:00
|
|
|
inner_attr: bool,
|
2018-09-13 01:41:07 +03:00
|
|
|
parent_scope: &ParentScope<'a>,
|
2020-06-09 20:59:43 +03:00
|
|
|
node_id: NodeId,
|
2018-09-13 01:41:07 +03:00
|
|
|
force: bool,
|
2021-02-21 16:32:38 +03:00
|
|
|
soft_custom_inner_attributes_gate: bool,
|
2019-07-03 23:59:03 +03:00
|
|
|
) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
|
2019-07-16 00:10:34 +03:00
|
|
|
let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
|
|
|
|
{
|
2019-07-03 23:59:03 +03:00
|
|
|
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),
|
|
|
|
};
|
2018-08-15 03:51:12 +03:00
|
|
|
|
2020-03-24 20:41:16 +03:00
|
|
|
// Report errors for the resolved macro.
|
2019-07-03 23:59:03 +03:00
|
|
|
for segment in &path.segments {
|
|
|
|
if let Some(args) = &segment.args {
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx.sess.span_err(args.span(), "generic arguments in macro path");
|
2018-08-15 03:51:12 +03:00
|
|
|
}
|
2020-03-24 20:41:16 +03:00
|
|
|
if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx.sess.span_err(
|
2020-03-24 20:41:16 +03:00
|
|
|
segment.ident.span,
|
|
|
|
"attributes starting with `rustc` are reserved for use by the `rustc` compiler",
|
|
|
|
);
|
2019-07-03 11:44:57 +03:00
|
|
|
}
|
2019-07-03 23:59:03 +03:00
|
|
|
}
|
2018-08-15 03:51:12 +03:00
|
|
|
|
2019-04-20 19:36:05 +03:00
|
|
|
match res {
|
2019-06-18 22:23:13 +03:00
|
|
|
Res::Def(DefKind::Macro(_), def_id) => {
|
2020-05-24 23:39:39 +01:00
|
|
|
if let Some(def_id) = def_id.as_local() {
|
|
|
|
self.unused_macros.remove(&def_id);
|
|
|
|
if self.proc_macro_stubs.contains(&def_id) {
|
2023-04-12 21:45:21 +01:00
|
|
|
self.tcx.sess.emit_err(errors::ProcMacroSameCrate {
|
|
|
|
span: path.span,
|
|
|
|
is_test: self.tcx.sess.is_test_crate(),
|
|
|
|
});
|
2019-07-03 01:44:04 +03:00
|
|
|
}
|
2019-06-20 11:52:31 +03:00
|
|
|
}
|
2019-06-18 22:23:13 +03:00
|
|
|
}
|
2019-07-12 01:00:20 +03:00
|
|
|
Res::NonMacroAttr(..) | Res::Err => {}
|
2019-04-20 19:36:05 +03:00
|
|
|
_ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
|
2019-07-03 11:44:57 +03:00
|
|
|
};
|
2018-08-15 03:51:12 +03:00
|
|
|
|
2020-06-09 20:59:43 +03:00
|
|
|
self.check_stability_and_deprecation(&ext, path, node_id);
|
2019-07-03 23:59:03 +03:00
|
|
|
|
2020-11-19 01:49:20 +03:00
|
|
|
let unexpected_res = if ext.macro_kind() != kind {
|
|
|
|
Some((kind.article(), kind.descr_expected()))
|
2021-03-01 16:02:09 -05:00
|
|
|
} 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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-11-19 01:49:20 +03:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
if let Some((article, expected)) = unexpected_res {
|
2019-10-08 22:17:46 +02:00
|
|
|
let path_str = pprust::path_to_string(path);
|
2023-03-26 15:59:45 +01:00
|
|
|
|
2023-04-07 08:14:48 +01:00
|
|
|
let mut err = MacroExpectedFound {
|
|
|
|
span: path.span,
|
|
|
|
expected,
|
|
|
|
found: res.descr(),
|
|
|
|
macro_path: &path_str,
|
|
|
|
..Default::default() // Subdiagnostics default to None
|
|
|
|
};
|
2023-03-26 15:59:45 +01:00
|
|
|
|
2023-04-07 08:14:48 +01:00
|
|
|
// Suggest moving the macro out of the derive() if the macro isn't Derive
|
2023-04-06 18:02:52 +01:00
|
|
|
if !path.span.from_expansion()
|
|
|
|
&& kind == MacroKind::Derive
|
|
|
|
&& ext.macro_kind() != MacroKind::Derive
|
|
|
|
{
|
2023-04-07 08:14:48 +01:00
|
|
|
err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span });
|
2023-04-07 08:44:19 +01:00
|
|
|
err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
|
2023-03-26 15:59:45 +01:00
|
|
|
}
|
|
|
|
|
2023-04-07 08:14:48 +01:00
|
|
|
let mut err = self.tcx.sess.create_err(err);
|
2023-07-25 23:04:01 +02:00
|
|
|
err.span_label(path.span, format!("not {article} {expected}"));
|
2023-04-07 08:14:48 +01:00
|
|
|
|
2023-03-26 15:59:45 +01:00
|
|
|
err.emit();
|
2023-04-07 08:14:48 +01:00
|
|
|
|
2020-11-19 01:49:20 +03:00
|
|
|
return Ok((self.dummy_ext(kind), Res::Err));
|
|
|
|
}
|
|
|
|
|
|
|
|
// We are trying to avoid reporting this error if other related errors were reported.
|
2023-07-22 15:33:51 +02:00
|
|
|
if res != Res::Err && inner_attr && !self.tcx.features().custom_inner_attributes {
|
2020-11-12 23:42:42 +03:00
|
|
|
let msg = match res {
|
|
|
|
Res::Def(..) => "inner macro attributes are unstable",
|
|
|
|
Res::NonMacroAttr(..) => "custom inner attributes are unstable",
|
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
2021-02-21 16:32:38 +03:00
|
|
|
if soft_custom_inner_attributes_gate {
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx.sess.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
|
2020-11-12 23:42:42 +03:00
|
|
|
} else {
|
2023-02-20 10:38:48 +00:00
|
|
|
feature_err(
|
|
|
|
&self.tcx.sess.parse_sess,
|
|
|
|
sym::custom_inner_attributes,
|
|
|
|
path.span,
|
|
|
|
msg,
|
|
|
|
)
|
|
|
|
.emit();
|
2020-11-12 23:42:42 +03:00
|
|
|
}
|
2020-11-19 01:49:20 +03:00
|
|
|
}
|
|
|
|
|
2023-04-28 13:04:35 +02:00
|
|
|
if res == Res::NonMacroAttr(NonMacroAttrKind::Tool)
|
|
|
|
&& path.segments.len() >= 2
|
|
|
|
&& path.segments[0].ident.name == sym::diagnostic
|
2023-06-02 13:55:46 +02:00
|
|
|
&& path.segments[1].ident.name != sym::on_unimplemented
|
2023-04-28 13:04:35 +02:00
|
|
|
{
|
|
|
|
self.tcx.sess.parse_sess.buffer_lint(
|
2023-06-02 13:55:46 +02:00
|
|
|
UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES,
|
2023-04-28 13:04:35 +02:00
|
|
|
path.segments[1].span(),
|
|
|
|
node_id,
|
|
|
|
"unknown diagnostic attribute",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-11-19 01:49:20 +03:00
|
|
|
Ok((ext, res))
|
2017-07-25 00:33:15 +03:00
|
|
|
}
|
2016-09-07 23:21:59 +00:00
|
|
|
|
2022-02-01 20:30:32 +08:00
|
|
|
pub(crate) fn resolve_macro_path(
|
2018-09-13 01:41:07 +03:00
|
|
|
&mut self,
|
|
|
|
path: &ast::Path,
|
2019-07-16 00:10:34 +03:00
|
|
|
kind: Option<MacroKind>,
|
2018-09-13 01:41:07 +03:00
|
|
|
parent_scope: &ParentScope<'a>,
|
2018-11-14 02:20:59 +03:00
|
|
|
trace: bool,
|
2018-09-13 01:41:07 +03:00
|
|
|
force: bool,
|
2019-07-03 23:59:03 +03:00
|
|
|
) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
|
2018-10-27 20:23:54 +03:00
|
|
|
let path_span = path.span;
|
2018-09-12 15:21:50 +12:00
|
|
|
let mut path = Segment::from_path(path);
|
2016-11-27 10:58:46 +00:00
|
|
|
|
2018-06-11 14:21:36 +03:00
|
|
|
// Possibly apply the macro helper hack
|
2019-07-16 00:10:34 +03:00
|
|
|
if kind == Some(MacroKind::Bang)
|
|
|
|
&& path.len() == 1
|
2019-08-13 23:56:42 +03:00
|
|
|
&& path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
|
|
|
|
{
|
2019-05-11 17:41:37 +03:00
|
|
|
let root = Ident::new(kw::DollarCrate, path[0].ident.span);
|
2018-09-12 15:21:50 +12:00
|
|
|
path.insert(0, Segment::from_ident(root));
|
2018-06-11 14:21:36 +03:00
|
|
|
}
|
|
|
|
|
2019-07-03 23:59:03 +03:00
|
|
|
let res = if path.len() > 1 {
|
2022-04-08 22:50:56 +02:00
|
|
|
let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) {
|
2022-10-10 19:21:35 +04:00
|
|
|
PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
|
2016-11-27 10:58:46 +00:00
|
|
|
PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
|
2019-01-16 15:30:41 -05:00
|
|
|
PathResult::NonModule(..)
|
|
|
|
| PathResult::Indeterminate
|
|
|
|
| PathResult::Failed { .. } => Err(Determinacy::Determined),
|
2018-11-10 18:58:37 +03:00
|
|
|
PathResult::Module(..) => unreachable!(),
|
2016-11-27 10:58:46 +00:00
|
|
|
};
|
2018-09-18 03:19:26 +03:00
|
|
|
|
2018-11-14 02:20:59 +03:00
|
|
|
if trace {
|
2019-07-16 00:10:34 +03:00
|
|
|
let kind = kind.expect("macro kind must be specified if tracing is enabled");
|
2019-08-12 21:52:37 +03:00
|
|
|
self.multi_segment_macro_resolutions.push((
|
2019-08-13 01:39:10 +03:00
|
|
|
path,
|
|
|
|
path_span,
|
|
|
|
kind,
|
|
|
|
*parent_scope,
|
|
|
|
res.ok(),
|
|
|
|
));
|
2018-11-14 02:20:59 +03:00
|
|
|
}
|
2016-11-27 10:58:46 +00:00
|
|
|
|
2019-04-20 19:36:05 +03:00
|
|
|
self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
|
|
|
|
res
|
2017-03-11 10:58:19 +00:00
|
|
|
} else {
|
2023-05-29 23:36:06 +03:00
|
|
|
let scope_set = kind.map_or(ScopeSet::All(MacroNS), ScopeSet::Macro);
|
2018-09-19 01:01:09 +03:00
|
|
|
let binding = self.early_resolve_ident_in_lexical_scope(
|
2019-07-16 00:10:34 +03:00
|
|
|
path[0].ident,
|
|
|
|
scope_set,
|
|
|
|
parent_scope,
|
2022-03-24 00:32:00 +03:00
|
|
|
None,
|
2019-07-16 00:10:34 +03:00
|
|
|
force,
|
2022-04-08 22:50:56 +02:00
|
|
|
None,
|
2018-09-19 01:01:09 +03:00
|
|
|
);
|
2018-12-16 20:23:27 +03:00
|
|
|
if let Err(Determinacy::Undetermined) = binding {
|
|
|
|
return Err(Determinacy::Undetermined);
|
2018-09-19 01:01:09 +03:00
|
|
|
}
|
2016-11-10 10:29:36 +00:00
|
|
|
|
2018-11-14 02:20:59 +03:00
|
|
|
if trace {
|
2019-07-16 00:10:34 +03:00
|
|
|
let kind = kind.expect("macro kind must be specified if tracing is enabled");
|
2019-08-12 21:52:37 +03:00
|
|
|
self.single_segment_macro_resolutions.push((
|
2019-08-13 01:39:10 +03:00
|
|
|
path[0].ident,
|
|
|
|
kind,
|
|
|
|
*parent_scope,
|
|
|
|
binding.ok(),
|
|
|
|
));
|
2018-11-14 02:20:59 +03:00
|
|
|
}
|
2017-02-01 21:03:09 +10:30
|
|
|
|
2019-04-20 19:36:05 +03:00
|
|
|
let res = binding.map(|binding| binding.res());
|
|
|
|
self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
|
|
|
|
res
|
2019-07-03 23:59:03 +03:00
|
|
|
};
|
|
|
|
|
2022-06-15 00:31:21 +09:00
|
|
|
res.map(|res| (self.get_macro(res).map(|macro_data| macro_data.ext), res))
|
2017-02-01 21:03:09 +10:30
|
|
|
}
|
2016-09-26 03:17:05 +00:00
|
|
|
|
2023-06-10 00:06:34 +08:00
|
|
|
pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
|
2018-12-16 20:23:27 +03:00
|
|
|
let check_consistency = |this: &mut Self,
|
|
|
|
path: &[Segment],
|
|
|
|
span,
|
|
|
|
kind: MacroKind,
|
2019-04-20 19:36:05 +03:00
|
|
|
initial_res: Option<Res>,
|
|
|
|
res: Res| {
|
|
|
|
if let Some(initial_res) = initial_res {
|
2020-10-24 21:17:34 +03:00
|
|
|
if res != initial_res {
|
2018-11-10 18:58:37 +03:00
|
|
|
// Make sure compilation does not succeed if preferred macro resolution
|
|
|
|
// has changed after the macro had been expanded. In theory all such
|
2020-10-24 21:17:34 +03:00
|
|
|
// situations should be reported as errors, so this is a bug.
|
2023-02-20 10:38:48 +00:00
|
|
|
this.tcx.sess.delay_span_bug(span, "inconsistent resolution for a macro");
|
2018-11-10 18:58:37 +03:00
|
|
|
}
|
|
|
|
} 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() {
|
2023-09-04 00:52:17 +08:00
|
|
|
this.tcx.sess.emit_err(CannotDetermineMacroResolution {
|
|
|
|
span,
|
|
|
|
kind: kind.descr(),
|
|
|
|
path: Segment::names_to_string(path),
|
|
|
|
});
|
2018-11-10 18:58:37 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-08-12 21:52:37 +03:00
|
|
|
let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
|
2019-04-20 19:36:05 +03:00
|
|
|
for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
|
2018-10-27 20:23:54 +03:00
|
|
|
// FIXME: Path resolution will ICE if segment IDs present.
|
|
|
|
for seg in &mut path {
|
|
|
|
seg.id = None;
|
|
|
|
}
|
2019-08-05 21:18:50 +03:00
|
|
|
match self.resolve_path(
|
|
|
|
&path,
|
|
|
|
Some(MacroNS),
|
|
|
|
&parent_scope,
|
2022-04-30 16:26:36 +03:00
|
|
|
Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
|
2022-04-08 22:50:56 +02:00
|
|
|
None,
|
2019-08-05 21:18:50 +03:00
|
|
|
) {
|
2022-10-10 19:21:35 +04:00
|
|
|
PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
|
|
|
|
check_consistency(self, &path, path_span, kind, initial_res, res)
|
2018-11-10 18:58:37 +03:00
|
|
|
}
|
2023-03-22 15:38:55 +01:00
|
|
|
path_res @ (PathResult::NonModule(..) | PathResult::Failed { .. }) => {
|
2022-10-17 05:54:13 +08:00
|
|
|
let mut suggestion = None;
|
2023-03-10 22:39:14 +01:00
|
|
|
let (span, label, module) =
|
|
|
|
if let PathResult::Failed { span, label, module, .. } = path_res {
|
2022-10-17 05:54:13 +08:00
|
|
|
// try to suggest if it's not a macro, maybe a function
|
2022-10-18 01:58:22 +08:00
|
|
|
if let PathResult::NonModule(partial_res) =
|
|
|
|
self.maybe_resolve_path(&path, Some(ValueNS), &parent_scope)
|
|
|
|
&& partial_res.unresolved_segments() == 0
|
|
|
|
{
|
2023-02-20 10:38:48 +00:00
|
|
|
let sm = self.tcx.sess.source_map();
|
2022-10-18 01:58:22 +08:00
|
|
|
let exclamation_span = sm.next_point(span);
|
|
|
|
suggestion = Some((
|
|
|
|
vec![(exclamation_span, "".to_string())],
|
2022-10-17 05:54:13 +08:00
|
|
|
format!(
|
|
|
|
"{} is not a macro, but a {}, try to remove `!`",
|
|
|
|
Segment::names_to_string(&path),
|
|
|
|
partial_res.base_res().descr()
|
|
|
|
),
|
2022-10-18 01:58:22 +08:00
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
));
|
2022-10-17 05:54:13 +08:00
|
|
|
}
|
2023-03-10 22:39:14 +01:00
|
|
|
(span, label, module)
|
2018-11-10 18:58:37 +03:00
|
|
|
} else {
|
|
|
|
(
|
|
|
|
path_span,
|
|
|
|
format!(
|
|
|
|
"partially resolved path in {} {}",
|
|
|
|
kind.article(),
|
|
|
|
kind.descr()
|
2019-12-22 17:42:04 -05:00
|
|
|
),
|
2023-03-10 22:39:14 +01:00
|
|
|
None,
|
2019-12-22 17:42:04 -05:00
|
|
|
)
|
2018-11-10 18:58:37 +03:00
|
|
|
};
|
2019-08-08 23:32:58 +03:00
|
|
|
self.report_error(
|
|
|
|
span,
|
2023-03-10 22:39:14 +01:00
|
|
|
ResolutionError::FailedToResolve {
|
|
|
|
last_segment: path.last().map(|segment| segment.ident.name),
|
|
|
|
label,
|
|
|
|
suggestion,
|
|
|
|
module,
|
|
|
|
},
|
2019-01-16 15:30:41 -05:00
|
|
|
);
|
2016-11-27 10:58:46 +00:00
|
|
|
}
|
2018-11-10 18:58:37 +03:00
|
|
|
PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
|
2016-11-27 10:58:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-12 21:52:37 +03:00
|
|
|
let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
|
2018-11-10 18:58:37 +03:00
|
|
|
for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
|
2018-11-24 19:14:05 +03:00
|
|
|
match self.early_resolve_ident_in_lexical_scope(
|
|
|
|
ident,
|
|
|
|
ScopeSet::Macro(kind),
|
2018-11-10 18:58:37 +03:00
|
|
|
&parent_scope,
|
2022-04-30 16:57:18 +03:00
|
|
|
Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
|
2018-11-10 18:58:37 +03:00
|
|
|
true,
|
2022-04-08 22:50:56 +02:00
|
|
|
None,
|
2018-11-10 18:58:37 +03:00
|
|
|
) {
|
2018-09-18 03:19:26 +03:00
|
|
|
Ok(binding) => {
|
2019-04-20 19:36:05 +03:00
|
|
|
let initial_res = initial_binding.map(|initial_binding| {
|
2021-08-22 16:50:59 +02:00
|
|
|
self.record_use(ident, initial_binding, false);
|
2019-04-20 19:36:05 +03:00
|
|
|
initial_binding.res()
|
2018-11-10 18:58:37 +03:00
|
|
|
});
|
2019-04-20 19:36:05 +03:00
|
|
|
let res = binding.res();
|
2018-11-18 14:41:06 +03:00
|
|
|
let seg = Segment::from_ident(ident);
|
2019-04-20 19:36:05 +03:00
|
|
|
check_consistency(self, &[seg], ident.span, kind, initial_res, res);
|
2020-11-14 14:47:14 +03:00
|
|
|
if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
|
2021-07-14 18:24:12 -05:00
|
|
|
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]);
|
2020-11-14 14:47:14 +03:00
|
|
|
self.lint_buffer.buffer_lint_with_diagnostic(
|
|
|
|
LEGACY_DERIVE_HELPERS,
|
2021-07-14 18:24:12 -05:00
|
|
|
node_id,
|
2020-11-14 14:47:14 +03:00
|
|
|
ident.span,
|
|
|
|
"derive helper attribute is used before it is introduced",
|
|
|
|
BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
|
|
|
|
);
|
|
|
|
}
|
2018-05-28 22:13:59 +03:00
|
|
|
}
|
2018-09-18 03:19:26 +03:00
|
|
|
Err(..) => {
|
2019-09-15 12:55:18 +03:00
|
|
|
let expected = kind.descr_expected();
|
2023-06-18 12:15:17 +01:00
|
|
|
|
|
|
|
let mut err = self.tcx.sess.create_err(CannotFindIdentInThisScope {
|
|
|
|
span: ident.span,
|
|
|
|
expected,
|
|
|
|
ident,
|
|
|
|
});
|
|
|
|
|
2023-06-10 00:06:34 +08:00
|
|
|
self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident, krate);
|
2017-02-06 22:14:38 +10:30
|
|
|
err.emit();
|
2018-05-28 22:13:59 +03:00
|
|
|
}
|
2018-09-18 03:19:26 +03:00
|
|
|
}
|
2016-10-31 22:17:15 +00:00
|
|
|
}
|
2018-09-03 00:04:54 +03:00
|
|
|
|
2019-08-12 21:52:37 +03:00
|
|
|
let builtin_attrs = mem::take(&mut self.builtin_attrs);
|
2018-09-13 01:41:07 +03:00
|
|
|
for (ident, parent_scope) in builtin_attrs {
|
2018-11-05 01:00:31 +03:00
|
|
|
let _ = self.early_resolve_ident_in_lexical_scope(
|
2018-11-24 19:14:05 +03:00
|
|
|
ident,
|
|
|
|
ScopeSet::Macro(MacroKind::Attr),
|
|
|
|
&parent_scope,
|
2022-04-30 16:57:18 +03:00
|
|
|
Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
|
2018-11-24 19:14:05 +03:00
|
|
|
true,
|
2022-04-08 22:50:56 +02:00
|
|
|
None,
|
2018-09-18 03:19:26 +03:00
|
|
|
);
|
2018-09-03 00:04:54 +03:00
|
|
|
}
|
2016-09-07 23:21:59 +00:00
|
|
|
}
|
2016-09-21 06:25:09 +00:00
|
|
|
|
2020-06-09 20:59:43 +03:00
|
|
|
fn check_stability_and_deprecation(
|
|
|
|
&mut self,
|
|
|
|
ext: &SyntaxExtension,
|
|
|
|
path: &ast::Path,
|
|
|
|
node_id: NodeId,
|
|
|
|
) {
|
2019-07-03 23:59:03 +03:00
|
|
|
let span = path.span;
|
2019-06-22 02:44:45 +03:00
|
|
|
if let Some(stability) = &ext.stability {
|
2022-07-13 13:10:37 +01:00
|
|
|
if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by } = stability.level
|
|
|
|
{
|
2019-06-22 16:18:05 +03:00
|
|
|
let feature = stability.feature;
|
2022-07-13 13:10:37 +01:00
|
|
|
|
|
|
|
let is_allowed = |feature| {
|
2023-10-05 16:20:07 +11:00
|
|
|
self.declared_features.contains(&feature) || span.allows_unstable(feature)
|
2022-07-13 13:10:37 +01:00
|
|
|
};
|
2023-05-24 14:33:43 +00:00
|
|
|
let allowed_by_implication = implied_by.is_some_and(|feature| is_allowed(feature));
|
2022-07-13 13:10:37 +01:00
|
|
|
if !is_allowed(feature) && !allowed_by_implication {
|
2019-10-25 09:15:33 -04:00
|
|
|
let lint_buffer = &mut self.lint_buffer;
|
|
|
|
let soft_handler =
|
Use `Cow` in `{D,Subd}iagnosticMessage`.
Each of `{D,Subd}iagnosticMessage::{Str,Eager}` has a comment:
```
// FIXME(davidtwco): can a `Cow<'static, str>` be used here?
```
This commit answers that question in the affirmative. It's not the most
compelling change ever, but it might be worth merging.
This requires changing the `impl<'a> From<&'a str>` impls to `impl
From<&'static str>`, which involves a bunch of knock-on changes that
require/result in call sites being a little more precise about exactly
what kind of string they use to create errors, and not just `&str`. This
will result in fewer unnecessary allocations, though this will not have
any notable perf effects given that these are error paths.
Note that I was lazy within Clippy, using `to_string` in a few places to
preserve the existing string imprecision. I could have used `impl
Into<{D,Subd}iagnosticMessage>` in various places as is done in the
compiler, but that would have required changes to *many* call sites
(mostly changing `&format("...")` to `format!("...")`) which didn't seem
worthwhile.
2023-05-04 10:55:21 +10:00
|
|
|
|lint, span, msg: String| lint_buffer.buffer_lint(lint, node_id, span, msg);
|
2019-10-10 23:37:41 +03:00
|
|
|
stability::report_unstable(
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx.sess,
|
2019-10-10 23:37:41 +03:00
|
|
|
feature,
|
2022-07-01 18:20:46 +03:00
|
|
|
reason.to_opt_reason(),
|
2019-10-10 23:37:41 +03:00
|
|
|
issue,
|
2021-11-13 16:39:54 +09:00
|
|
|
None,
|
2019-10-10 23:37:41 +03:00
|
|
|
is_soft,
|
|
|
|
span,
|
|
|
|
soft_handler,
|
|
|
|
);
|
2019-06-22 02:44:45 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if let Some(depr) = &ext.deprecation {
|
2023-11-21 20:07:32 +01:00
|
|
|
let path = pprust::path_to_string(path);
|
2021-09-30 15:15:10 +04:00
|
|
|
let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
|
2020-07-20 10:44:43 -04:00
|
|
|
stability::early_report_deprecation(
|
|
|
|
&mut self.lint_buffer,
|
Use `Cow` in `{D,Subd}iagnosticMessage`.
Each of `{D,Subd}iagnosticMessage::{Str,Eager}` has a comment:
```
// FIXME(davidtwco): can a `Cow<'static, str>` be used here?
```
This commit answers that question in the affirmative. It's not the most
compelling change ever, but it might be worth merging.
This requires changing the `impl<'a> From<&'a str>` impls to `impl
From<&'static str>`, which involves a bunch of knock-on changes that
require/result in call sites being a little more precise about exactly
what kind of string they use to create errors, and not just `&str`. This
will result in fewer unnecessary allocations, though this will not have
any notable perf effects given that these are error paths.
Note that I was lazy within Clippy, using `to_string` in a few places to
preserve the existing string imprecision. I could have used `impl
Into<{D,Subd}iagnosticMessage>` in various places as is done in the
compiler, but that would have required changes to *many* call sites
(mostly changing `&format("...")` to `format!("...")`) which didn't seem
worthwhile.
2023-05-04 10:55:21 +10:00
|
|
|
message,
|
2020-07-20 10:44:43 -04:00
|
|
|
depr.suggestion,
|
|
|
|
lint,
|
|
|
|
span,
|
2020-11-12 22:29:52 +03:00
|
|
|
node_id,
|
2020-07-20 10:44:43 -04:00
|
|
|
);
|
2019-06-22 02:44:45 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-12 04:11:46 +03:00
|
|
|
fn prohibit_imported_non_macro_attrs(
|
|
|
|
&self,
|
2023-07-04 17:28:57 +03:00
|
|
|
binding: Option<NameBinding<'a>>,
|
2019-04-20 19:36:05 +03:00
|
|
|
res: Option<Res>,
|
|
|
|
span: Span,
|
|
|
|
) {
|
|
|
|
if let Some(Res::NonMacroAttr(kind)) = res {
|
2018-12-12 04:11:46 +03:00
|
|
|
if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
|
2019-11-04 16:47:03 +03:00
|
|
|
let msg =
|
|
|
|
format!("cannot use {} {} through an import", kind.article(), kind.descr());
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
let mut err = self.tcx.sess.struct_span_err(span, msg);
|
2018-12-12 04:11:46 +03:00
|
|
|
if let Some(binding) = binding {
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
err.span_note(binding.span, format!("the {} imported here", kind.descr()));
|
2018-12-12 04:11:46 +03:00
|
|
|
}
|
|
|
|
err.emit();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-20 19:51:09 -04:00
|
|
|
pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
|
2019-06-30 01:24:34 +03:00
|
|
|
// Reserve some names that are not quite covered by the general check
|
|
|
|
// performed on `Resolver::builtin_attrs`.
|
2020-11-14 14:47:14 +03:00
|
|
|
if ident.name == sym::cfg || ident.name == sym::cfg_attr {
|
2022-06-15 00:31:21 +09:00
|
|
|
let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind());
|
2019-06-30 01:24:34 +03:00
|
|
|
if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx.sess.span_err(
|
2019-06-30 01:24:34 +03:00
|
|
|
ident.span,
|
2023-07-25 23:04:01 +02:00
|
|
|
format!("name `{ident}` is reserved in attribute namespace"),
|
2019-06-30 01:24:34 +03:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-17 04:01:17 +02:00
|
|
|
/// Compile the macro into a `SyntaxExtension` and its rule spans.
|
|
|
|
///
|
|
|
|
/// Possibly replace its expander to a pre-defined one for built-in macros.
|
2022-05-20 19:51:09 -04:00
|
|
|
pub(crate) fn compile_macro(
|
2022-04-17 04:01:17 +02:00
|
|
|
&mut self,
|
|
|
|
item: &ast::Item,
|
|
|
|
edition: Edition,
|
2022-06-09 04:46:51 +02:00
|
|
|
) -> (SyntaxExtension, Vec<(usize, Span)>) {
|
2023-08-09 20:28:00 +08:00
|
|
|
let (mut result, mut rule_spans) =
|
|
|
|
compile_declarative_macro(self.tcx.sess, self.tcx.features(), item, edition);
|
2019-06-20 11:52:31 +03:00
|
|
|
|
2021-01-09 16:48:58 +01:00
|
|
|
if let Some(builtin_name) = result.builtin_name {
|
2019-06-20 11:52:31 +03:00
|
|
|
// The macro was marked with `#[rustc_builtin_macro]`.
|
2021-01-09 16:48:58 +01:00
|
|
|
if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
|
2019-11-22 23:06:56 +03:00
|
|
|
// The macro is a built-in, replace its expander function
|
|
|
|
// while still taking everything else from the source code.
|
2020-08-31 00:04:01 -04:00
|
|
|
// 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)) {
|
2021-12-11 19:52:23 +08:00
|
|
|
BuiltinMacroState::NotYetSeen(ext) => {
|
|
|
|
result.kind = ext;
|
2022-04-17 04:01:17 +02:00
|
|
|
rule_spans = Vec::new();
|
2021-12-11 19:52:23 +08:00
|
|
|
if item.id != ast::DUMMY_NODE_ID {
|
|
|
|
self.builtin_macro_kinds
|
|
|
|
.insert(self.local_def_id(item.id), result.macro_kind());
|
|
|
|
}
|
|
|
|
}
|
2020-08-31 00:04:01 -04:00
|
|
|
BuiltinMacroState::AlreadySeen(span) => {
|
|
|
|
struct_span_err!(
|
2023-02-20 10:38:48 +00:00
|
|
|
self.tcx.sess,
|
2020-08-31 00:04:01 -04:00
|
|
|
item.span,
|
|
|
|
E0773,
|
|
|
|
"attempted to define built-in macro more than once"
|
|
|
|
)
|
|
|
|
.span_note(span, "previously defined here")
|
|
|
|
.emit();
|
|
|
|
}
|
|
|
|
}
|
2019-06-20 11:52:31 +03:00
|
|
|
} else {
|
|
|
|
let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
self.tcx.sess.span_err(item.span, msg);
|
2019-06-20 11:52:31 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-17 04:01:17 +02:00
|
|
|
(result, rule_spans)
|
2019-06-20 11:52:31 +03:00
|
|
|
}
|
2016-09-07 23:21:59 +00:00
|
|
|
}
|