]>
Commit | Line | Data |
---|---|---|
e1599b0c XL |
1 | //! This crate is responsible for the part of name resolution that doesn't require type checker. |
2 | //! | |
3 | //! Module structure of the crate is built here. | |
4 | //! Paths in macros, imports, expressions, types, patterns are resolved here. | |
dfeec247 | 5 | //! Label and lifetime names are resolved here as well. |
e1599b0c | 6 | //! |
2b03887a | 7 | //! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`. |
e1599b0c | 8 | |
1b1a35ee | 9 | #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] |
f2b60f7d | 10 | #![feature(assert_matches)] |
5869c6ff | 11 | #![feature(box_patterns)] |
c295e0f8 | 12 | #![feature(drain_filter)] |
04454e1e | 13 | #![feature(if_let_guard)] |
064997fb | 14 | #![feature(iter_intersperse)] |
5e7ed085 | 15 | #![feature(let_chains)] |
c295e0f8 | 16 | #![feature(never_type)] |
dfeec247 | 17 | #![recursion_limit = "256"] |
cdc7bbd5 | 18 | #![allow(rustdoc::private_intra_doc_links)] |
5e7ed085 | 19 | #![allow(rustc::potential_query_instability)] |
7cac9316 | 20 | |
c295e0f8 XL |
21 | #[macro_use] |
22 | extern crate tracing; | |
23 | ||
29967ef6 | 24 | use rustc_arena::{DroplessArena, TypedArena}; |
f9f354fc | 25 | use rustc_ast::node_id::NodeMap; |
04454e1e FG |
26 | use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID}; |
27 | use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path}; | |
923072b8 | 28 | use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; |
5099ac24 | 29 | use rustc_data_structures::intern::Interned; |
9ffffee4 FG |
30 | use rustc_data_structures::sync::{Lrc, MappedReadGuard}; |
31 | use rustc_errors::{ | |
32 | Applicability, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, SubdiagnosticMessage, | |
33 | }; | |
cdc7bbd5 | 34 | use rustc_expand::base::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind}; |
9ffffee4 FG |
35 | use rustc_hir::def::Namespace::{self, *}; |
36 | use rustc_hir::def::{self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, PartialRes, PerNS}; | |
923072b8 | 37 | use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId}; |
04454e1e | 38 | use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; |
9ffffee4 | 39 | use rustc_hir::definitions::DefPathData; |
cdc7bbd5 | 40 | use rustc_hir::TraitCandidate; |
f035d41b | 41 | use rustc_index::vec::IndexVec; |
9ffffee4 | 42 | use rustc_macros::fluent_messages; |
dfeec247 | 43 | use rustc_metadata::creader::{CStore, CrateLoader}; |
5099ac24 | 44 | use rustc_middle::metadata::ModChild; |
2b03887a | 45 | use rustc_middle::middle::privacy::EffectiveVisibilities; |
04454e1e | 46 | use rustc_middle::span_bug; |
9ffffee4 | 47 | use rustc_middle::ty::{self, DefIdTree, MainDefinition, RegisteredTools, TyCtxt}; |
2b03887a | 48 | use rustc_middle::ty::{ResolverGlobalCtxt, ResolverOutputs}; |
3c0e092e | 49 | use rustc_query_system::ich::StableHashingContext; |
9ffffee4 | 50 | use rustc_session::cstore::CrateStore; |
04454e1e | 51 | use rustc_session::lint::LintBuffer; |
04454e1e | 52 | use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency}; |
3c0e092e | 53 | use rustc_span::source_map::Spanned; |
f9f354fc | 54 | use rustc_span::symbol::{kw, sym, Ident, Symbol}; |
dfeec247 | 55 | use rustc_span::{Span, DUMMY_SP}; |
1a4d82fc | 56 | |
3dfed10e | 57 | use smallvec::{smallvec, SmallVec}; |
1a4d82fc | 58 | use std::cell::{Cell, RefCell}; |
5099ac24 | 59 | use std::collections::BTreeSet; |
f2b60f7d | 60 | use std::{fmt, ptr}; |
85aaf69f | 61 | |
f035d41b | 62 | use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion}; |
9ffffee4 | 63 | use imports::{Import, ImportKind, NameResolution}; |
064997fb | 64 | use late::{HasGenericParams, PathSource, PatternSource}; |
29967ef6 | 65 | use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; |
c34b1796 | 66 | |
2b03887a | 67 | use crate::effective_visibilities::EffectiveVisibilitiesVisitor; |
5099ac24 | 68 | |
48663c56 XL |
69 | type Res = def::Res<NodeId>; |
70 | ||
dfeec247 XL |
71 | mod build_reduced_graph; |
72 | mod check_unused; | |
60c5eb7d | 73 | mod def_collector; |
54a0048b | 74 | mod diagnostics; |
2b03887a | 75 | mod effective_visibilities; |
487cf647 | 76 | mod errors; |
04454e1e | 77 | mod ident; |
dfeec247 | 78 | mod imports; |
416331ca | 79 | mod late; |
9e0c209e | 80 | mod macros; |
9ffffee4 FG |
81 | pub mod rustdoc; |
82 | ||
83 | fluent_messages! { "../locales/en-US.ftl" } | |
1a4d82fc | 84 | |
13cf67c4 XL |
85 | enum Weak { |
86 | Yes, | |
87 | No, | |
88 | } | |
89 | ||
416331ca | 90 | #[derive(Copy, Clone, PartialEq, Debug)] |
9ffffee4 | 91 | enum Determinacy { |
416331ca XL |
92 | Determined, |
93 | Undetermined, | |
94 | } | |
95 | ||
96 | impl Determinacy { | |
97 | fn determined(determined: bool) -> Determinacy { | |
98 | if determined { Determinacy::Determined } else { Determinacy::Undetermined } | |
99 | } | |
100 | } | |
101 | ||
102 | /// A specific scope in which a name can be looked up. | |
103 | /// This enum is currently used only for early resolution (imports and macros), | |
104 | /// but not for late resolution yet. | |
105 | #[derive(Clone, Copy)] | |
106 | enum Scope<'a> { | |
136023e0 | 107 | DeriveHelpers(LocalExpnId), |
60c5eb7d | 108 | DeriveHelpersCompat, |
29967ef6 | 109 | MacroRules(MacroRulesScopeRef<'a>), |
416331ca | 110 | CrateRoot, |
cdc7bbd5 XL |
111 | // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK` |
112 | // lint if it should be reported. | |
113 | Module(Module<'a>, Option<NodeId>), | |
416331ca XL |
114 | MacroUsePrelude, |
115 | BuiltinAttrs, | |
416331ca XL |
116 | ExternPrelude, |
117 | ToolPrelude, | |
118 | StdLibPrelude, | |
119 | BuiltinTypes, | |
120 | } | |
121 | ||
122 | /// Names from different contexts may want to visit different subsets of all specific scopes | |
123 | /// with different restrictions when looking up the resolution. | |
124 | /// This enum is currently used only for early resolution (imports and macros), | |
125 | /// but not for late resolution yet. | |
cdc7bbd5 XL |
126 | #[derive(Clone, Copy)] |
127 | enum ScopeSet<'a> { | |
416331ca XL |
128 | /// All scopes with the given namespace. |
129 | All(Namespace, /*is_import*/ bool), | |
130 | /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros). | |
13cf67c4 | 131 | AbsolutePath(Namespace), |
416331ca | 132 | /// All scopes with macro namespace and the given macro kind restriction. |
13cf67c4 | 133 | Macro(MacroKind), |
cdc7bbd5 XL |
134 | /// All scopes with the given namespace, used for partially performing late resolution. |
135 | /// The node id enables lints and is used for reporting them. | |
136 | Late(Namespace, Module<'a>, Option<NodeId>), | |
13cf67c4 XL |
137 | } |
138 | ||
416331ca XL |
139 | /// Everything you need to know about a name's location to resolve it. |
140 | /// Serves as a starting point for the scope visitor. | |
141 | /// This struct is currently used only for early resolution (imports and macros), | |
142 | /// but not for late resolution yet. | |
e1599b0c | 143 | #[derive(Clone, Copy, Debug)] |
9ffffee4 FG |
144 | struct ParentScope<'a> { |
145 | module: Module<'a>, | |
136023e0 | 146 | expansion: LocalExpnId, |
9ffffee4 | 147 | macro_rules: MacroRulesScopeRef<'a>, |
e1599b0c XL |
148 | derives: &'a [ast::Path], |
149 | } | |
150 | ||
151 | impl<'a> ParentScope<'a> { | |
152 | /// Creates a parent scope with the passed argument used as the module scope component, | |
153 | /// and other scope components set to default empty values. | |
9ffffee4 | 154 | fn module(module: Module<'a>, resolver: &Resolver<'a, '_>) -> ParentScope<'a> { |
ba9703b0 XL |
155 | ParentScope { |
156 | module, | |
136023e0 | 157 | expansion: LocalExpnId::ROOT, |
29967ef6 | 158 | macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty), |
ba9703b0 XL |
159 | derives: &[], |
160 | } | |
e1599b0c | 161 | } |
7453a54e SL |
162 | } |
163 | ||
6a06907d XL |
164 | #[derive(Copy, Debug, Clone)] |
165 | enum ImplTraitContext { | |
166 | Existential, | |
167 | Universal(LocalDefId), | |
168 | } | |
169 | ||
8bb4bdeb | 170 | struct BindingError { |
f9f354fc | 171 | name: Symbol, |
8bb4bdeb XL |
172 | origin: BTreeSet<Span>, |
173 | target: BTreeSet<Span>, | |
dfeec247 | 174 | could_be_path: bool, |
0731742a XL |
175 | } |
176 | ||
54a0048b | 177 | enum ResolutionError<'a> { |
9fa01778 | 178 | /// Error E0401: can't use type or const parameters from outer function. |
e74abb32 | 179 | GenericParamsFromOuterFunction(Res, HasGenericParams), |
9fa01778 XL |
180 | /// Error E0403: the name is already used for a type or const parameter in this generic |
181 | /// parameter list. | |
f9f354fc | 182 | NameAlreadyUsedInParameterList(Symbol, Span), |
9fa01778 | 183 | /// Error E0407: method is not a member of trait. |
04454e1e | 184 | MethodNotMemberOfTrait(Ident, String, Option<Symbol>), |
9fa01778 | 185 | /// Error E0437: type is not a member of trait. |
04454e1e | 186 | TypeNotMemberOfTrait(Ident, String, Option<Symbol>), |
9fa01778 | 187 | /// Error E0438: const is not a member of trait. |
04454e1e | 188 | ConstNotMemberOfTrait(Ident, String, Option<Symbol>), |
9fa01778 | 189 | /// Error E0408: variable `{}` is not bound in all patterns. |
04454e1e | 190 | VariableNotBoundInPattern(BindingError, ParentScope<'a>), |
9fa01778 | 191 | /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm. |
f9f354fc | 192 | VariableBoundWithDifferentMode(Symbol, Span), |
9fa01778 | 193 | /// Error E0415: identifier is bound more than once in this parameter list. |
3dfed10e | 194 | IdentifierBoundMoreThanOnceInParameterList(Symbol), |
9fa01778 | 195 | /// Error E0416: identifier is bound more than once in the same pattern. |
3dfed10e | 196 | IdentifierBoundMoreThanOnceInSamePattern(Symbol), |
9fa01778 | 197 | /// Error E0426: use of undeclared label. |
3dfed10e | 198 | UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> }, |
9fa01778 | 199 | /// Error E0429: `self` imports are only allowed within a `{ }` list. |
f9f354fc | 200 | SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span }, |
9fa01778 | 201 | /// Error E0430: `self` import can only appear once in the list. |
c1a9b12d | 202 | SelfImportCanOnlyAppearOnceInTheList, |
9fa01778 | 203 | /// Error E0431: `self` import can only appear in an import list with a non-empty prefix. |
c1a9b12d | 204 | SelfImportOnlyInImportListWithNonEmptyPrefix, |
9fa01778 | 205 | /// Error E0433: failed to resolve. |
532ac7d7 | 206 | FailedToResolve { label: String, suggestion: Option<Suggestion> }, |
9fa01778 | 207 | /// Error E0434: can't capture dynamic environment in a fn item. |
c1a9b12d | 208 | CannotCaptureDynamicEnvironmentInFnItem, |
9fa01778 | 209 | /// Error E0435: attempt to use a non-constant value in a constant. |
5869c6ff XL |
210 | AttemptToUseNonConstantValueInConstant( |
211 | Ident, | |
212 | /* suggestion */ &'static str, | |
213 | /* current */ &'static str, | |
214 | ), | |
9fa01778 | 215 | /// Error E0530: `X` bindings cannot shadow `Y`s. |
17df50a5 | 216 | BindingShadowsSomethingUnacceptable { |
064997fb | 217 | shadowing_binding: PatternSource, |
17df50a5 XL |
218 | name: Symbol, |
219 | participle: &'static str, | |
220 | article: &'static str, | |
064997fb | 221 | shadowed_binding: Res, |
17df50a5 XL |
222 | shadowed_binding_span: Span, |
223 | }, | |
cdc7bbd5 | 224 | /// Error E0128: generic parameters with a default cannot use forward-declared identifiers. |
17df50a5 | 225 | ForwardDeclaredGenericParam, |
3dfed10e XL |
226 | /// ERROR E0770: the type of const parameters must not depend on other generic parameters. |
227 | ParamInTyOfConstParam(Symbol), | |
29967ef6 | 228 | /// generic parameters must not be used inside const evaluations. |
3dfed10e XL |
229 | /// |
230 | /// This error is only emitted when using `min_const_generics`. | |
1b1a35ee | 231 | ParamInNonTrivialAnonConst { name: Symbol, is_type: bool }, |
cdc7bbd5 | 232 | /// Error E0735: generic parameters with a default cannot use `Self` |
136023e0 | 233 | SelfInGenericParamDefault, |
f035d41b | 234 | /// Error E0767: use of unreachable label |
3dfed10e | 235 | UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> }, |
5099ac24 FG |
236 | /// Error E0323, E0324, E0325: mismatch between trait item and impl item. |
237 | TraitImplMismatch { | |
238 | name: Symbol, | |
239 | kind: &'static str, | |
240 | trait_path: String, | |
241 | trait_item_span: Span, | |
242 | code: rustc_errors::DiagnosticId, | |
243 | }, | |
2b03887a FG |
244 | /// Error E0201: multiple impl items for the same trait item. |
245 | TraitImplDuplicate { name: Symbol, trait_item_span: Span, old_span: Span }, | |
04454e1e FG |
246 | /// Inline asm `sym` operand must refer to a `fn` or `static`. |
247 | InvalidAsmSym, | |
e74abb32 XL |
248 | } |
249 | ||
250 | enum VisResolutionError<'a> { | |
251 | Relative2018(Span, &'a ast::Path), | |
252 | AncestorOnly(Span), | |
253 | FailedToResolve(Span, String, Option<Suggestion>), | |
254 | ExpectedFound(Span, String, Res), | |
255 | Indeterminate(Span), | |
256 | ModuleOnly(Span), | |
9cc50fc6 SL |
257 | } |
258 | ||
f035d41b XL |
259 | /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path |
260 | /// segments' which don't have the rest of an AST or HIR `PathSegment`. | |
13cf67c4 | 261 | #[derive(Clone, Copy, Debug)] |
9ffffee4 | 262 | struct Segment { |
13cf67c4 XL |
263 | ident: Ident, |
264 | id: Option<NodeId>, | |
f035d41b XL |
265 | /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing |
266 | /// nonsensical suggestions. | |
267 | has_generic_args: bool, | |
04454e1e FG |
268 | /// Signals whether this `PathSegment` has lifetime arguments. |
269 | has_lifetime_args: bool, | |
270 | args_span: Span, | |
13cf67c4 XL |
271 | } |
272 | ||
273 | impl Segment { | |
274 | fn from_path(path: &Path) -> Vec<Segment> { | |
275 | path.segments.iter().map(|s| s.into()).collect() | |
276 | } | |
277 | ||
278 | fn from_ident(ident: Ident) -> Segment { | |
04454e1e FG |
279 | Segment { |
280 | ident, | |
281 | id: None, | |
282 | has_generic_args: false, | |
283 | has_lifetime_args: false, | |
284 | args_span: DUMMY_SP, | |
285 | } | |
286 | } | |
287 | ||
288 | fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment { | |
289 | Segment { | |
290 | ident, | |
291 | id: Some(id), | |
292 | has_generic_args: false, | |
293 | has_lifetime_args: false, | |
294 | args_span: DUMMY_SP, | |
295 | } | |
13cf67c4 XL |
296 | } |
297 | ||
298 | fn names_to_string(segments: &[Segment]) -> String { | |
dfeec247 | 299 | names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>()) |
13cf67c4 XL |
300 | } |
301 | } | |
302 | ||
303 | impl<'a> From<&'a ast::PathSegment> for Segment { | |
304 | fn from(seg: &'a ast::PathSegment) -> Segment { | |
04454e1e FG |
305 | let has_generic_args = seg.args.is_some(); |
306 | let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() { | |
307 | match args { | |
308 | GenericArgs::AngleBracketed(args) => { | |
309 | let found_lifetimes = args | |
310 | .args | |
311 | .iter() | |
312 | .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_)))); | |
313 | (args.span, found_lifetimes) | |
5e7ed085 | 314 | } |
04454e1e | 315 | GenericArgs::Parenthesized(args) => (args.span, true), |
6a06907d | 316 | } |
5e7ed085 | 317 | } else { |
04454e1e FG |
318 | (DUMMY_SP, false) |
319 | }; | |
320 | Segment { | |
321 | ident: seg.ident, | |
322 | id: Some(seg.id), | |
323 | has_generic_args, | |
324 | has_lifetime_args, | |
325 | args_span, | |
6a06907d | 326 | } |
3b2f2976 XL |
327 | } |
328 | } | |
329 | ||
0531ce1d XL |
330 | /// An intermediate resolution result. |
331 | /// | |
48663c56 XL |
332 | /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that |
333 | /// items are visible in their whole block, while `Res`es only from the place they are defined | |
0531ce1d | 334 | /// forward. |
416331ca | 335 | #[derive(Debug)] |
54a0048b SL |
336 | enum LexicalScopeBinding<'a> { |
337 | Item(&'a NameBinding<'a>), | |
48663c56 | 338 | Res(Res), |
54a0048b SL |
339 | } |
340 | ||
341 | impl<'a> LexicalScopeBinding<'a> { | |
48663c56 | 342 | fn res(self) -> Res { |
32a655c1 | 343 | match self { |
48663c56 XL |
344 | LexicalScopeBinding::Item(binding) => binding.res(), |
345 | LexicalScopeBinding::Res(res) => res, | |
32a655c1 SL |
346 | } |
347 | } | |
476ff2be SL |
348 | } |
349 | ||
b7449926 | 350 | #[derive(Copy, Clone, Debug)] |
13cf67c4 | 351 | enum ModuleOrUniformRoot<'a> { |
b7449926 XL |
352 | /// Regular module. |
353 | Module(Module<'a>), | |
354 | ||
13cf67c4 XL |
355 | /// Virtual module that denotes resolution in crate root with fallback to extern prelude. |
356 | CrateRootAndExternPrelude, | |
357 | ||
358 | /// Virtual module that denotes resolution in extern prelude. | |
0731742a | 359 | /// Used for paths starting with `::` on 2018 edition. |
13cf67c4 XL |
360 | ExternPrelude, |
361 | ||
362 | /// Virtual module that denotes resolution in current scope. | |
363 | /// Used only for resolving single-segment imports. The reason it exists is that import paths | |
364 | /// are always split into two parts, the first of which should be some kind of module. | |
365 | CurrentScope, | |
366 | } | |
367 | ||
69743fb6 XL |
368 | impl ModuleOrUniformRoot<'_> { |
369 | fn same_def(lhs: Self, rhs: Self) -> bool { | |
370 | match (lhs, rhs) { | |
dfeec247 | 371 | (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => { |
c295e0f8 | 372 | ptr::eq(lhs, rhs) |
dfeec247 XL |
373 | } |
374 | ( | |
375 | ModuleOrUniformRoot::CrateRootAndExternPrelude, | |
376 | ModuleOrUniformRoot::CrateRootAndExternPrelude, | |
377 | ) | |
378 | | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) | |
379 | | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true, | |
13cf67c4 XL |
380 | _ => false, |
381 | } | |
382 | } | |
b7449926 XL |
383 | } |
384 | ||
9ffffee4 | 385 | #[derive(Debug)] |
476ff2be | 386 | enum PathResult<'a> { |
b7449926 | 387 | Module(ModuleOrUniformRoot<'a>), |
48663c56 | 388 | NonModule(PartialRes), |
476ff2be | 389 | Indeterminate, |
532ac7d7 XL |
390 | Failed { |
391 | span: Span, | |
392 | label: String, | |
393 | suggestion: Option<Suggestion>, | |
394 | is_error_from_last_segment: bool, | |
395 | }, | |
476ff2be SL |
396 | } |
397 | ||
5e7ed085 FG |
398 | impl<'a> PathResult<'a> { |
399 | fn failed( | |
400 | span: Span, | |
401 | is_error_from_last_segment: bool, | |
402 | finalize: bool, | |
403 | label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>), | |
404 | ) -> PathResult<'a> { | |
405 | let (label, suggestion) = | |
406 | if finalize { label_and_suggestion() } else { (String::new(), None) }; | |
407 | PathResult::Failed { span, label, suggestion, is_error_from_last_segment } | |
408 | } | |
409 | } | |
410 | ||
fc512014 | 411 | #[derive(Debug)] |
9e0c209e | 412 | enum ModuleKind { |
9fa01778 | 413 | /// An anonymous module; e.g., just a block. |
0531ce1d XL |
414 | /// |
415 | /// ``` | |
416 | /// fn main() { | |
417 | /// fn f() {} // (1) | |
418 | /// { // This is an anonymous module | |
419 | /// f(); // This resolves to (2) as we are inside the block. | |
420 | /// fn f() {} // (2) | |
421 | /// } | |
422 | /// f(); // Resolves to (1) | |
423 | /// } | |
424 | /// ``` | |
064997fb | 425 | Block, |
0531ce1d XL |
426 | /// Any module with a name. |
427 | /// | |
428 | /// This could be: | |
429 | /// | |
5869c6ff XL |
430 | /// * A normal module – either `mod from_file;` or `mod from_block { }` – |
431 | /// or the crate root (which is conceptually a top-level module). | |
432 | /// Note that the crate root's [name][Self::name] will be [`kw::Empty`]. | |
0531ce1d XL |
433 | /// * A trait or an enum (it implicitly contains associated types, methods and variant |
434 | /// constructors). | |
f9f354fc | 435 | Def(DefKind, DefId, Symbol), |
48663c56 XL |
436 | } |
437 | ||
438 | impl ModuleKind { | |
439 | /// Get name of the module. | |
9ffffee4 | 440 | fn name(&self) -> Option<Symbol> { |
48663c56 | 441 | match self { |
064997fb | 442 | ModuleKind::Block => None, |
48663c56 XL |
443 | ModuleKind::Def(.., name) => Some(*name), |
444 | } | |
445 | } | |
1a4d82fc JJ |
446 | } |
447 | ||
e74abb32 XL |
448 | /// A key that identifies a binding in a given `Module`. |
449 | /// | |
450 | /// Multiple bindings in the same module can have the same key (in a valid | |
451 | /// program) if all but one of them come from glob imports. | |
3dfed10e | 452 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] |
e74abb32 | 453 | struct BindingKey { |
5e7ed085 | 454 | /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the |
e74abb32 XL |
455 | /// identifier. |
456 | ident: Ident, | |
457 | ns: Namespace, | |
458 | /// 0 if ident is not `_`, otherwise a value that's unique to the specific | |
459 | /// `_` in the expanded AST that introduced this binding. | |
460 | disambiguator: u32, | |
461 | } | |
462 | ||
463 | type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>; | |
e1599b0c | 464 | |
1a4d82fc | 465 | /// One node in the tree of modules. |
5869c6ff XL |
466 | /// |
467 | /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these: | |
468 | /// | |
469 | /// * `mod` | |
470 | /// * crate root (aka, top-level anonymous module) | |
471 | /// * `enum` | |
472 | /// * `trait` | |
473 | /// * curly-braced block with statements | |
474 | /// | |
475 | /// You can use [`ModuleData::kind`] to determine the kind of module this is. | |
9ffffee4 | 476 | struct ModuleData<'a> { |
5869c6ff | 477 | /// The direct parent module (it may not be a `mod`, however). |
9e0c209e | 478 | parent: Option<Module<'a>>, |
5869c6ff | 479 | /// What kind of module this is, because this may not be a `mod`. |
9e0c209e SL |
480 | kind: ModuleKind, |
481 | ||
5869c6ff XL |
482 | /// Mapping between names and their (possibly in-progress) resolutions in this module. |
483 | /// Resolutions in modules from other crates are not populated until accessed. | |
e1599b0c | 484 | lazy_resolutions: Resolutions<'a>, |
5869c6ff | 485 | /// True if this is a module from other crate that needs to be populated on access. |
e1599b0c | 486 | populate_on_access: Cell<bool>, |
1a4d82fc | 487 | |
5869c6ff | 488 | /// Macro invocations that can expand into items in this module. |
136023e0 | 489 | unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>, |
1a4d82fc | 490 | |
5869c6ff | 491 | /// Whether `#[no_implicit_prelude]` is active. |
9e0c209e | 492 | no_implicit_prelude: bool, |
1a4d82fc | 493 | |
74b04a01 XL |
494 | glob_importers: RefCell<Vec<&'a Import<'a>>>, |
495 | globs: RefCell<Vec<&'a Import<'a>>>, | |
e9174d1e | 496 | |
5869c6ff | 497 | /// Used to memoize the traits in this module for faster searches through all traits in scope. |
32a655c1 | 498 | traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>, |
e9174d1e | 499 | |
7cac9316 XL |
500 | /// Span of the module itself. Used for error reporting. |
501 | span: Span, | |
502 | ||
416331ca | 503 | expansion: ExpnId, |
1a4d82fc JJ |
504 | } |
505 | ||
3b2f2976 | 506 | type Module<'a> = &'a ModuleData<'a>; |
9cc50fc6 | 507 | |
32a655c1 | 508 | impl<'a> ModuleData<'a> { |
dfeec247 XL |
509 | fn new( |
510 | parent: Option<Module<'a>>, | |
511 | kind: ModuleKind, | |
dfeec247 XL |
512 | expansion: ExpnId, |
513 | span: Span, | |
c295e0f8 | 514 | no_implicit_prelude: bool, |
dfeec247 | 515 | ) -> Self { |
c295e0f8 XL |
516 | let is_foreign = match kind { |
517 | ModuleKind::Def(_, def_id, _) => !def_id.is_local(), | |
064997fb | 518 | ModuleKind::Block => false, |
c295e0f8 | 519 | }; |
32a655c1 | 520 | ModuleData { |
3b2f2976 XL |
521 | parent, |
522 | kind, | |
e1599b0c | 523 | lazy_resolutions: Default::default(), |
c295e0f8 | 524 | populate_on_access: Cell::new(is_foreign), |
e1599b0c | 525 | unexpanded_invocations: Default::default(), |
c295e0f8 | 526 | no_implicit_prelude, |
54a0048b | 527 | glob_importers: RefCell::new(Vec::new()), |
2c00a5a8 | 528 | globs: RefCell::new(Vec::new()), |
54a0048b | 529 | traits: RefCell::new(None), |
3b2f2976 XL |
530 | span, |
531 | expansion, | |
7453a54e SL |
532 | } |
533 | } | |
534 | ||
9ffffee4 | 535 | fn for_each_child<'tcx, R, F>(&'a self, resolver: &mut R, mut f: F) |
dfeec247 | 536 | where |
9ffffee4 | 537 | R: AsMut<Resolver<'a, 'tcx>>, |
dfeec247 | 538 | F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>), |
e1599b0c | 539 | { |
e74abb32 | 540 | for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() { |
f9f354fc XL |
541 | if let Some(binding) = name_resolution.borrow().binding { |
542 | f(resolver, key.ident, key.ns, binding); | |
543 | } | |
3b2f2976 XL |
544 | } |
545 | } | |
546 | ||
3dfed10e | 547 | /// This modifies `self` in place. The traits will be stored in `self.traits`. |
9ffffee4 | 548 | fn ensure_traits<'tcx, R>(&'a self, resolver: &mut R) |
3dfed10e | 549 | where |
9ffffee4 | 550 | R: AsMut<Resolver<'a, 'tcx>>, |
3dfed10e XL |
551 | { |
552 | let mut traits = self.traits.borrow_mut(); | |
553 | if traits.is_none() { | |
554 | let mut collected_traits = Vec::new(); | |
555 | self.for_each_child(resolver, |_, name, ns, binding| { | |
556 | if ns != TypeNS { | |
557 | return; | |
558 | } | |
1b1a35ee XL |
559 | if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() { |
560 | collected_traits.push((name, binding)) | |
3dfed10e XL |
561 | } |
562 | }); | |
563 | *traits = Some(collected_traits.into_boxed_slice()); | |
564 | } | |
565 | } | |
566 | ||
48663c56 | 567 | fn res(&self) -> Option<Res> { |
9e0c209e | 568 | match self.kind { |
48663c56 XL |
569 | ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)), |
570 | _ => None, | |
571 | } | |
572 | } | |
573 | ||
5099ac24 | 574 | // Public for rustdoc. |
9ffffee4 | 575 | fn def_id(&self) -> DefId { |
c295e0f8 XL |
576 | self.opt_def_id().expect("`ModuleData::def_id` is called on a block module") |
577 | } | |
578 | ||
579 | fn opt_def_id(&self) -> Option<DefId> { | |
48663c56 XL |
580 | match self.kind { |
581 | ModuleKind::Def(_, def_id, _) => Some(def_id), | |
582 | _ => None, | |
583 | } | |
92a42be0 SL |
584 | } |
585 | ||
a7813a04 | 586 | // `self` resolves to the first module ancestor that `is_normal`. |
7453a54e | 587 | fn is_normal(&self) -> bool { |
29967ef6 | 588 | matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _)) |
1a4d82fc JJ |
589 | } |
590 | ||
7453a54e | 591 | fn is_trait(&self) -> bool { |
29967ef6 | 592 | matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _)) |
e9174d1e | 593 | } |
c30ab7b3 | 594 | |
8bb4bdeb | 595 | fn nearest_item_scope(&'a self) -> Module<'a> { |
e1599b0c | 596 | match self.kind { |
ba9703b0 | 597 | ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => { |
dfeec247 XL |
598 | self.parent.expect("enum or trait module without a parent") |
599 | } | |
e1599b0c XL |
600 | _ => self, |
601 | } | |
8bb4bdeb | 602 | } |
4462d4a0 | 603 | |
c295e0f8 XL |
604 | /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module). |
605 | /// This may be the crate root. | |
606 | fn nearest_parent_mod(&self) -> DefId { | |
607 | match self.kind { | |
608 | ModuleKind::Def(DefKind::Mod, def_id, _) => def_id, | |
609 | _ => self.parent.expect("non-root module without parent").nearest_parent_mod(), | |
610 | } | |
611 | } | |
612 | ||
4462d4a0 XL |
613 | fn is_ancestor_of(&self, mut other: &Self) -> bool { |
614 | while !ptr::eq(self, other) { | |
615 | if let Some(parent) = other.parent { | |
616 | other = parent; | |
617 | } else { | |
618 | return false; | |
619 | } | |
620 | } | |
621 | true | |
622 | } | |
1a4d82fc JJ |
623 | } |
624 | ||
32a655c1 | 625 | impl<'a> fmt::Debug for ModuleData<'a> { |
9fa01778 | 626 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
48663c56 | 627 | write!(f, "{:?}", self.res()) |
1a4d82fc JJ |
628 | } |
629 | } | |
630 | ||
83c7162d | 631 | /// Records a possibly-private value, type, or module definition. |
54a0048b | 632 | #[derive(Clone, Debug)] |
9ffffee4 | 633 | struct NameBinding<'a> { |
7453a54e | 634 | kind: NameBindingKind<'a>, |
0731742a | 635 | ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>, |
136023e0 | 636 | expansion: LocalExpnId, |
a7813a04 | 637 | span: Span, |
f2b60f7d | 638 | vis: ty::Visibility<DefId>, |
1a4d82fc JJ |
639 | } |
640 | ||
9ffffee4 | 641 | trait ToNameBinding<'a> { |
32a655c1 | 642 | fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>; |
5bcae85e SL |
643 | } |
644 | ||
32a655c1 SL |
645 | impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> { |
646 | fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { | |
5bcae85e SL |
647 | self |
648 | } | |
649 | } | |
650 | ||
54a0048b | 651 | #[derive(Clone, Debug)] |
7453a54e | 652 | enum NameBindingKind<'a> { |
487cf647 | 653 | Res(Res), |
9cc50fc6 | 654 | Module(Module<'a>), |
74b04a01 | 655 | Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> }, |
1a4d82fc JJ |
656 | } |
657 | ||
9fa01778 | 658 | impl<'a> NameBindingKind<'a> { |
94222f64 | 659 | /// Is this a name binding of an import? |
9fa01778 | 660 | fn is_import(&self) -> bool { |
29967ef6 | 661 | matches!(*self, NameBindingKind::Import { .. }) |
9fa01778 XL |
662 | } |
663 | } | |
664 | ||
dfeec247 XL |
665 | struct PrivacyError<'a> { |
666 | ident: Ident, | |
667 | binding: &'a NameBinding<'a>, | |
668 | dedup_span: Span, | |
669 | } | |
54a0048b | 670 | |
3b2f2976 | 671 | struct UseError<'a> { |
5e7ed085 | 672 | err: DiagnosticBuilder<'a, ErrorGuaranteed>, |
f035d41b | 673 | /// Candidates which user could `use` to access the missing type. |
3b2f2976 | 674 | candidates: Vec<ImportSuggestion>, |
f035d41b | 675 | /// The `DefId` of the module to place the use-statements in. |
f9f354fc | 676 | def_id: DefId, |
f035d41b XL |
677 | /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`). |
678 | instead: bool, | |
679 | /// Extra free-form suggestion. | |
dfeec247 | 680 | suggestion: Option<(Span, &'static str, String, Applicability)>, |
04454e1e FG |
681 | /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling |
682 | /// the user to import the item directly. | |
683 | path: Vec<Segment>, | |
2b03887a FG |
684 | /// Whether the expected source is a call |
685 | is_call: bool, | |
3b2f2976 XL |
686 | } |
687 | ||
13cf67c4 XL |
688 | #[derive(Clone, Copy, PartialEq, Debug)] |
689 | enum AmbiguityKind { | |
690 | Import, | |
13cf67c4 XL |
691 | BuiltinAttr, |
692 | DeriveHelper, | |
ba9703b0 | 693 | MacroRulesVsModularized, |
13cf67c4 XL |
694 | GlobVsOuter, |
695 | GlobVsGlob, | |
696 | GlobVsExpanded, | |
697 | MoreExpandedVsOuter, | |
698 | } | |
699 | ||
700 | impl AmbiguityKind { | |
701 | fn descr(self) -> &'static str { | |
702 | match self { | |
3c0e092e XL |
703 | AmbiguityKind::Import => "multiple potential import sources", |
704 | AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute", | |
705 | AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute", | |
ba9703b0 | 706 | AmbiguityKind::MacroRulesVsModularized => { |
3c0e092e | 707 | "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module" |
ba9703b0 | 708 | } |
dfeec247 | 709 | AmbiguityKind::GlobVsOuter => { |
3c0e092e | 710 | "a conflict between a name from a glob import and an outer scope during import or macro resolution" |
dfeec247 | 711 | } |
3c0e092e | 712 | AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module", |
dfeec247 | 713 | AmbiguityKind::GlobVsExpanded => { |
3c0e092e | 714 | "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution" |
dfeec247 XL |
715 | } |
716 | AmbiguityKind::MoreExpandedVsOuter => { | |
3c0e092e | 717 | "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution" |
dfeec247 | 718 | } |
13cf67c4 XL |
719 | } |
720 | } | |
721 | } | |
722 | ||
723 | /// Miscellaneous bits of metadata for better ambiguity error reporting. | |
724 | #[derive(Clone, Copy, PartialEq)] | |
725 | enum AmbiguityErrorMisc { | |
726 | SuggestCrate, | |
727 | SuggestSelf, | |
728 | FromPrelude, | |
729 | None, | |
730 | } | |
731 | ||
9e0c209e | 732 | struct AmbiguityError<'a> { |
13cf67c4 | 733 | kind: AmbiguityKind, |
b7449926 | 734 | ident: Ident, |
9e0c209e SL |
735 | b1: &'a NameBinding<'a>, |
736 | b2: &'a NameBinding<'a>, | |
13cf67c4 XL |
737 | misc1: AmbiguityErrorMisc, |
738 | misc2: AmbiguityErrorMisc, | |
9e0c209e SL |
739 | } |
740 | ||
7453a54e | 741 | impl<'a> NameBinding<'a> { |
476ff2be | 742 | fn module(&self) -> Option<Module<'a>> { |
7453a54e | 743 | match self.kind { |
476ff2be | 744 | NameBindingKind::Module(module) => Some(module), |
7453a54e | 745 | NameBindingKind::Import { binding, .. } => binding.module(), |
476ff2be | 746 | _ => None, |
1a4d82fc JJ |
747 | } |
748 | } | |
749 | ||
48663c56 | 750 | fn res(&self) -> Res { |
7453a54e | 751 | match self.kind { |
487cf647 | 752 | NameBindingKind::Res(res) => res, |
48663c56 XL |
753 | NameBindingKind::Module(module) => module.res().unwrap(), |
754 | NameBindingKind::Import { binding, .. } => binding.res(), | |
1a4d82fc JJ |
755 | } |
756 | } | |
1a4d82fc | 757 | |
0731742a | 758 | fn is_ambiguity(&self) -> bool { |
dfeec247 XL |
759 | self.ambiguity.is_some() |
760 | || match self.kind { | |
761 | NameBindingKind::Import { binding, .. } => binding.is_ambiguity(), | |
762 | _ => false, | |
763 | } | |
476ff2be SL |
764 | } |
765 | ||
f035d41b XL |
766 | fn is_possibly_imported_variant(&self) -> bool { |
767 | match self.kind { | |
768 | NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(), | |
487cf647 FG |
769 | NameBindingKind::Res(Res::Def( |
770 | DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), | |
ba9703b0 | 771 | _, |
487cf647 | 772 | )) => true, |
6a06907d XL |
773 | NameBindingKind::Res(..) | NameBindingKind::Module(..) => false, |
774 | } | |
92a42be0 SL |
775 | } |
776 | ||
7453a54e | 777 | fn is_extern_crate(&self) -> bool { |
476ff2be SL |
778 | match self.kind { |
779 | NameBindingKind::Import { | |
74b04a01 | 780 | import: &Import { kind: ImportKind::ExternCrate { .. }, .. }, |
dfeec247 | 781 | .. |
476ff2be | 782 | } => true, |
dfeec247 XL |
783 | NameBindingKind::Module(&ModuleData { |
784 | kind: ModuleKind::Def(DefKind::Mod, def_id, _), | |
785 | .. | |
04454e1e | 786 | }) => def_id.is_crate_root(), |
476ff2be SL |
787 | _ => false, |
788 | } | |
92a42be0 | 789 | } |
92a42be0 | 790 | |
7453a54e | 791 | fn is_import(&self) -> bool { |
29967ef6 | 792 | matches!(self.kind, NameBindingKind::Import { .. }) |
c34b1796 | 793 | } |
a7813a04 | 794 | |
487cf647 FG |
795 | /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might |
796 | /// not be perceived as such by users, so treat it as a non-import in some diagnostics. | |
797 | fn is_import_user_facing(&self) -> bool { | |
798 | matches!(self.kind, NameBindingKind::Import { import, .. } | |
799 | if !matches!(import.kind, ImportKind::MacroExport)) | |
800 | } | |
801 | ||
a7813a04 XL |
802 | fn is_glob_import(&self) -> bool { |
803 | match self.kind { | |
74b04a01 | 804 | NameBindingKind::Import { import, .. } => import.is_glob(), |
a7813a04 XL |
805 | _ => false, |
806 | } | |
807 | } | |
808 | ||
809 | fn is_importable(&self) -> bool { | |
29967ef6 XL |
810 | !matches!( |
811 | self.res(), | |
812 | Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) | |
813 | ) | |
a7813a04 | 814 | } |
7cac9316 | 815 | |
b7449926 | 816 | fn macro_kind(&self) -> Option<MacroKind> { |
416331ca | 817 | self.res().macro_kind() |
13cf67c4 XL |
818 | } |
819 | ||
b7449926 XL |
820 | // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding` |
821 | // at some expansion round `max(invoc, binding)` when they both emerged from macros. | |
822 | // Then this function returns `true` if `self` may emerge from a macro *after* that | |
823 | // in some later round and screw up our previously found resolution. | |
824 | // See more detailed explanation in | |
825 | // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049 | |
136023e0 XL |
826 | fn may_appear_after( |
827 | &self, | |
828 | invoc_parent_expansion: LocalExpnId, | |
829 | binding: &NameBinding<'_>, | |
830 | ) -> bool { | |
b7449926 XL |
831 | // self > max(invoc, binding) => !(self <= invoc || self <= binding) |
832 | // Expansions are partially ordered, so "may appear after" is an inversion of | |
833 | // "certainly appears before or simultaneously" and includes unordered cases. | |
834 | let self_parent_expansion = self.expansion; | |
835 | let other_parent_expansion = binding.expansion; | |
836 | let certainly_before_other_or_simultaneously = | |
837 | other_parent_expansion.is_descendant_of(self_parent_expansion); | |
838 | let certainly_before_invoc_or_simultaneously = | |
839 | invoc_parent_expansion.is_descendant_of(self_parent_expansion); | |
840 | !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously) | |
841 | } | |
1a4d82fc JJ |
842 | } |
843 | ||
f2b60f7d | 844 | #[derive(Default, Clone)] |
9ffffee4 | 845 | struct ExternPreludeEntry<'a> { |
0bf4aa26 | 846 | extern_crate_item: Option<&'a NameBinding<'a>>, |
9ffffee4 | 847 | introduced_by_item: bool, |
0bf4aa26 XL |
848 | } |
849 | ||
1b1a35ee XL |
850 | /// Used for better errors for E0773 |
851 | enum BuiltinMacroState { | |
5869c6ff | 852 | NotYetSeen(SyntaxExtensionKind), |
1b1a35ee XL |
853 | AlreadySeen(Span), |
854 | } | |
855 | ||
cdc7bbd5 XL |
856 | struct DeriveData { |
857 | resolutions: DeriveResolutions, | |
858 | helper_attrs: Vec<(usize, Ident)>, | |
859 | has_derive_copy: bool, | |
860 | } | |
861 | ||
923072b8 FG |
862 | #[derive(Clone)] |
863 | struct MacroData { | |
864 | ext: Lrc<SyntaxExtension>, | |
865 | macro_rules: bool, | |
866 | } | |
867 | ||
1a4d82fc | 868 | /// The main resolver class. |
0531ce1d XL |
869 | /// |
870 | /// This is the visitor that walks the whole crate. | |
9ffffee4 FG |
871 | pub struct Resolver<'a, 'tcx> { |
872 | tcx: TyCtxt<'tcx>, | |
1a4d82fc | 873 | |
923072b8 FG |
874 | /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`. |
875 | expn_that_defined: FxHashMap<LocalDefId, ExpnId>, | |
1a4d82fc | 876 | |
e74abb32 | 877 | graph_root: Module<'a>, |
1a4d82fc | 878 | |
3157f602 | 879 | prelude: Option<Module<'a>>, |
e74abb32 | 880 | extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>, |
3157f602 | 881 | |
9fa01778 | 882 | /// N.B., this is used only for better diagnostics, not name resolution itself. |
7cac9316 | 883 | has_self: FxHashSet<DefId>, |
1a4d82fc | 884 | |
83c7162d XL |
885 | /// Names of fields of an item `DefId` accessible with dot syntax. |
886 | /// Used for hints during error reporting. | |
f9f354fc | 887 | field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>, |
1a4d82fc | 888 | |
9c376795 FG |
889 | /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax. |
890 | /// Used for hints during error reporting. | |
891 | field_visibility_spans: FxHashMap<DefId, Vec<Span>>, | |
892 | ||
83c7162d | 893 | /// All imports known to succeed or fail. |
74b04a01 | 894 | determined_imports: Vec<&'a Import<'a>>, |
9e0c209e | 895 | |
83c7162d | 896 | /// All non-determined imports. |
74b04a01 | 897 | indeterminate_imports: Vec<&'a Import<'a>>, |
1a4d82fc | 898 | |
cdc7bbd5 XL |
899 | // Spans for local variables found during pattern resolution. |
900 | // Used for suggestions during error reporting. | |
901 | pat_span_map: NodeMap<Span>, | |
902 | ||
48663c56 XL |
903 | /// Resolutions for nodes that have a single resolution. |
904 | partial_res_map: NodeMap<PartialRes>, | |
905 | /// Resolutions for import nodes, which have multiple resolutions in different namespaces. | |
906 | import_res_map: NodeMap<PerNS<Option<Res>>>, | |
907 | /// Resolutions for labels (node IDs of their corresponding blocks or loops). | |
908 | label_res_map: NodeMap<NodeId>, | |
04454e1e FG |
909 | /// Resolutions for lifetimes. |
910 | lifetimes_res_map: NodeMap<LifetimeRes>, | |
911 | /// Lifetime parameters that lowering will have to introduce. | |
912 | extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>, | |
48663c56 | 913 | |
e74abb32 | 914 | /// `CrateNum` resolutions of `extern crate` items. |
f9f354fc | 915 | extern_crate_map: FxHashMap<LocalDefId, CrateNum>, |
5099ac24 | 916 | reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>, |
3c0e092e | 917 | trait_map: NodeMap<Vec<TraitCandidate>>, |
a7813a04 | 918 | |
83c7162d XL |
919 | /// A map from nodes to anonymous modules. |
920 | /// Anonymous modules are pseudo-modules that are implicitly created around items | |
921 | /// contained within blocks. | |
922 | /// | |
923 | /// For example, if we have this: | |
924 | /// | |
925 | /// fn f() { | |
926 | /// fn g() { | |
927 | /// ... | |
928 | /// } | |
929 | /// } | |
930 | /// | |
931 | /// There will be an anonymous module created around `g` with the ID of the | |
932 | /// entry block for `f`. | |
32a655c1 | 933 | block_map: NodeMap<Module<'a>>, |
e1599b0c XL |
934 | /// A fake module that contains no definition and no prelude. Used so that |
935 | /// some AST passes can generate identifiers that only resolve to local or | |
936 | /// language items. | |
937 | empty_module: Module<'a>, | |
c295e0f8 | 938 | module_map: FxHashMap<DefId, Module<'a>>, |
5099ac24 | 939 | binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>, |
e74abb32 | 940 | underscore_disambiguator: u32, |
1a4d82fc | 941 | |
9fa01778 | 942 | /// Maps glob imports to the names of items actually imported. |
f9f354fc | 943 | glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>, |
29967ef6 XL |
944 | /// Visibilities in "lowered" form, for all entities that have them. |
945 | visibilities: FxHashMap<LocalDefId, ty::Visibility>, | |
04454e1e | 946 | has_pub_restricted: bool, |
94222f64 | 947 | used_imports: FxHashSet<NodeId>, |
923072b8 | 948 | maybe_unused_trait_imports: FxIndexSet<LocalDefId>, |
e9174d1e | 949 | |
9fa01778 | 950 | /// Privacy errors are delayed until the end in order to deduplicate them. |
54a0048b | 951 | privacy_errors: Vec<PrivacyError<'a>>, |
9fa01778 | 952 | /// Ambiguity errors are delayed for deduplication. |
9e0c209e | 953 | ambiguity_errors: Vec<AmbiguityError<'a>>, |
9fa01778 | 954 | /// `use` injections are delayed for better placement and deduplication. |
9ffffee4 | 955 | use_injections: Vec<UseError<'tcx>>, |
9fa01778 | 956 | /// Crate-local macro expanded `macro_export` referred to by a module-relative path. |
b7449926 | 957 | macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>, |
9cc50fc6 SL |
958 | |
959 | arenas: &'a ResolverArenas<'a>, | |
9e0c209e | 960 | dummy_binding: &'a NameBinding<'a>, |
9e0c209e | 961 | |
9c376795 | 962 | used_extern_options: FxHashSet<Symbol>, |
7cac9316 | 963 | macro_names: FxHashSet<Ident>, |
1b1a35ee | 964 | builtin_macros: FxHashMap<Symbol, BuiltinMacroState>, |
5e7ed085 FG |
965 | /// A small map keeping true kinds of built-in macros that appear to be fn-like on |
966 | /// the surface (`macro` items in libcore), but are actually attributes or derives. | |
967 | builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>, | |
5099ac24 | 968 | registered_tools: RegisteredTools, |
f9f354fc | 969 | macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>, |
923072b8 | 970 | macro_map: FxHashMap<DefId, MacroData>, |
416331ca XL |
971 | dummy_ext_bang: Lrc<SyntaxExtension>, |
972 | dummy_ext_derive: Lrc<SyntaxExtension>, | |
94222f64 | 973 | non_macro_attr: Lrc<SyntaxExtension>, |
f9f354fc | 974 | local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>, |
136023e0 | 975 | ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>, |
3c0e092e | 976 | unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>, |
04454e1e | 977 | unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>, |
f9f354fc | 978 | proc_macro_stubs: FxHashSet<LocalDefId>, |
e1599b0c | 979 | /// Traces collected during macro resolution and validated when it's complete. |
dfeec247 XL |
980 | single_segment_macro_resolutions: |
981 | Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>, | |
982 | multi_segment_macro_resolutions: | |
983 | Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>, | |
e1599b0c | 984 | builtin_attrs: Vec<(Ident, ParentScope<'a>)>, |
60c5eb7d | 985 | /// `derive(Copy)` marks items they are applied to so they are treated specially later. |
416331ca XL |
986 | /// Derive macros cannot modify the item themselves and have to store the markers in the global |
987 | /// context, so they attach the markers to derive container IDs using this resolver table. | |
136023e0 | 988 | containers_deriving_copy: FxHashSet<LocalExpnId>, |
e1599b0c XL |
989 | /// Parent scopes in which the macros were invoked. |
990 | /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere. | |
136023e0 | 991 | invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>, |
ba9703b0 | 992 | /// `macro_rules` scopes *produced* by expanding the macro invocations, |
e1599b0c | 993 | /// include all the `macro_rules` items and other invocations generated by them. |
136023e0 | 994 | output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>, |
04454e1e FG |
995 | /// `macro_rules` scopes produced by `macro_rules` item definitions. |
996 | macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'a>>, | |
60c5eb7d | 997 | /// Helper attributes that are in scope for the given expansion. |
136023e0 | 998 | helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>, |
cdc7bbd5 XL |
999 | /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute |
1000 | /// with the given `ExpnId`. | |
136023e0 | 1001 | derive_data: FxHashMap<LocalExpnId, DeriveData>, |
476ff2be | 1002 | |
83c7162d | 1003 | /// Avoid duplicated errors for "name already defined". |
f9f354fc | 1004 | name_already_seen: FxHashMap<Symbol, Span>, |
32a655c1 | 1005 | |
74b04a01 | 1006 | potentially_unused_imports: Vec<&'a Import<'a>>, |
8bb4bdeb | 1007 | |
9fa01778 | 1008 | /// Table for mapping struct IDs into struct constructor IDs, |
83c7162d | 1009 | /// it's not used during normal resolution, only for better error reporting. |
1b1a35ee | 1010 | /// Also includes of list of each fields visibility |
f2b60f7d | 1011 | struct_constructors: DefIdMap<(Res, ty::Visibility<DefId>, Vec<ty::Visibility<DefId>>)>, |
3b2f2976 | 1012 | |
416331ca | 1013 | /// Features enabled for this crate. |
f9f354fc | 1014 | active_features: FxHashSet<Symbol>, |
e1599b0c | 1015 | |
dfeec247 | 1016 | lint_buffer: LintBuffer, |
60c5eb7d XL |
1017 | |
1018 | next_node_id: NodeId, | |
f035d41b | 1019 | |
f035d41b XL |
1020 | node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>, |
1021 | def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>, | |
1022 | ||
1023 | /// Indices of unnamed struct or variant fields with unresolved attributes. | |
1024 | placeholder_field_indices: FxHashMap<NodeId, usize>, | |
1025 | /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId` | |
6a06907d XL |
1026 | /// we know what parent node that fragment should be attached to thanks to this table, |
1027 | /// and how the `impl Trait` fragments were introduced. | |
136023e0 | 1028 | invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>, |
f035d41b | 1029 | |
29967ef6 XL |
1030 | /// Some way to know that we are in a *trait* impl in `visit_assoc_item`. |
1031 | /// FIXME: Replace with a more general AST map (together with some other fields). | |
1032 | trait_impl_items: FxHashSet<LocalDefId>, | |
6a06907d XL |
1033 | |
1034 | legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>, | |
94222f64 XL |
1035 | /// Amount of lifetime parameters for each item in the crate. |
1036 | item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>, | |
cdc7bbd5 XL |
1037 | |
1038 | main_def: Option<MainDefinition>, | |
5099ac24 | 1039 | trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>, |
94222f64 XL |
1040 | /// A list of proc macro LocalDefIds, written out in the order in which |
1041 | /// they are declared in the static array generated by proc_macro_harness. | |
1042 | proc_macros: Vec<NodeId>, | |
c295e0f8 | 1043 | confused_type_with_std_module: FxHashMap<Span, Span>, |
487cf647 FG |
1044 | /// Whether lifetime elision was successful. |
1045 | lifetime_elision_allowed: FxHashSet<NodeId>, | |
5099ac24 | 1046 | |
2b03887a | 1047 | effective_visibilities: EffectiveVisibilities, |
9ffffee4 FG |
1048 | doc_link_resolutions: FxHashMap<LocalDefId, DocLinkResMap>, |
1049 | doc_link_traits_in_scope: FxHashMap<LocalDefId, Vec<DefId>>, | |
1050 | all_macro_rules: FxHashMap<Symbol, Res>, | |
9cc50fc6 SL |
1051 | } |
1052 | ||
9fa01778 | 1053 | /// Nothing really interesting here; it just provides memory for the rest of the crate. |
0bf4aa26 | 1054 | #[derive(Default)] |
3157f602 | 1055 | pub struct ResolverArenas<'a> { |
f035d41b | 1056 | modules: TypedArena<ModuleData<'a>>, |
a7813a04 | 1057 | local_modules: RefCell<Vec<Module<'a>>>, |
f035d41b XL |
1058 | imports: TypedArena<Import<'a>>, |
1059 | name_resolutions: TypedArena<RefCell<NameResolution<'a>>>, | |
f035d41b | 1060 | ast_paths: TypedArena<ast::Path>, |
29967ef6 | 1061 | dropless: DroplessArena, |
54a0048b SL |
1062 | } |
1063 | ||
1064 | impl<'a> ResolverArenas<'a> { | |
c295e0f8 XL |
1065 | fn new_module( |
1066 | &'a self, | |
1067 | parent: Option<Module<'a>>, | |
1068 | kind: ModuleKind, | |
1069 | expn_id: ExpnId, | |
1070 | span: Span, | |
1071 | no_implicit_prelude: bool, | |
1072 | module_map: &mut FxHashMap<DefId, Module<'a>>, | |
1073 | ) -> Module<'a> { | |
1074 | let module = | |
1075 | self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude)); | |
1076 | let def_id = module.opt_def_id(); | |
1077 | if def_id.map_or(true, |def_id| def_id.is_local()) { | |
a7813a04 XL |
1078 | self.local_modules.borrow_mut().push(module); |
1079 | } | |
c295e0f8 XL |
1080 | if let Some(def_id) = def_id { |
1081 | module_map.insert(def_id, module); | |
1082 | } | |
a7813a04 XL |
1083 | module |
1084 | } | |
9fa01778 | 1085 | fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> { |
a7813a04 | 1086 | self.local_modules.borrow() |
54a0048b SL |
1087 | } |
1088 | fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> { | |
29967ef6 | 1089 | self.dropless.alloc(name_binding) |
54a0048b | 1090 | } |
74b04a01 XL |
1091 | fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> { |
1092 | self.imports.alloc(import) | |
54a0048b SL |
1093 | } |
1094 | fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> { | |
1095 | self.name_resolutions.alloc(Default::default()) | |
1096 | } | |
29967ef6 | 1097 | fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> { |
5099ac24 | 1098 | Interned::new_unchecked(self.dropless.alloc(Cell::new(scope))) |
29967ef6 | 1099 | } |
ba9703b0 XL |
1100 | fn alloc_macro_rules_binding( |
1101 | &'a self, | |
1102 | binding: MacroRulesBinding<'a>, | |
1103 | ) -> &'a MacroRulesBinding<'a> { | |
29967ef6 | 1104 | self.dropless.alloc(binding) |
c30ab7b3 | 1105 | } |
e1599b0c XL |
1106 | fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] { |
1107 | self.ast_paths.alloc_from_iter(paths.iter().cloned()) | |
1108 | } | |
1b1a35ee | 1109 | fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] { |
29967ef6 | 1110 | self.dropless.alloc_from_iter(spans) |
1b1a35ee | 1111 | } |
e1599b0c XL |
1112 | } |
1113 | ||
9ffffee4 FG |
1114 | impl<'a, 'tcx> AsMut<Resolver<'a, 'tcx>> for Resolver<'a, 'tcx> { |
1115 | fn as_mut(&mut self) -> &mut Resolver<'a, 'tcx> { | |
dfeec247 XL |
1116 | self |
1117 | } | |
1a4d82fc JJ |
1118 | } |
1119 | ||
9ffffee4 | 1120 | impl<'a, 'b, 'tcx> DefIdTree for &'a Resolver<'b, 'tcx> { |
487cf647 FG |
1121 | #[inline] |
1122 | fn opt_parent(self, id: DefId) -> Option<DefId> { | |
9ffffee4 | 1123 | self.tcx.opt_parent(id) |
487cf647 FG |
1124 | } |
1125 | } | |
1126 | ||
9ffffee4 | 1127 | impl<'tcx> Resolver<'_, 'tcx> { |
f035d41b XL |
1128 | fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> { |
1129 | self.node_id_to_def_id.get(&node).copied() | |
1130 | } | |
1131 | ||
9ffffee4 | 1132 | fn local_def_id(&self, node: NodeId) -> LocalDefId { |
f035d41b XL |
1133 | self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) |
1134 | } | |
1135 | ||
1136 | /// Adds a definition with a parent definition. | |
1137 | fn create_def( | |
1138 | &mut self, | |
1139 | parent: LocalDefId, | |
1140 | node_id: ast::NodeId, | |
1141 | data: DefPathData, | |
1142 | expn_id: ExpnId, | |
1143 | span: Span, | |
1144 | ) -> LocalDefId { | |
1145 | assert!( | |
1146 | !self.node_id_to_def_id.contains_key(&node_id), | |
1147 | "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}", | |
1148 | node_id, | |
1149 | data, | |
9ffffee4 | 1150 | self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id]), |
f035d41b XL |
1151 | ); |
1152 | ||
9ffffee4 FG |
1153 | // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()` |
1154 | let def_id = self.tcx.untracked().definitions.write().create_def(parent, data); | |
923072b8 FG |
1155 | |
1156 | // Create the definition. | |
1157 | if expn_id != ExpnId::root() { | |
1158 | self.expn_that_defined.insert(def_id, expn_id); | |
1159 | } | |
1160 | ||
1161 | // A relative span's parent must be an absolute span. | |
1162 | debug_assert_eq!(span.data_untracked().parent, None); | |
9ffffee4 | 1163 | let _id = self.tcx.untracked().source_span.push(span); |
923072b8 | 1164 | debug_assert_eq!(_id, def_id); |
f035d41b XL |
1165 | |
1166 | // Some things for which we allocate `LocalDefId`s don't correspond to | |
1167 | // anything in the AST, so they don't have a `NodeId`. For these cases | |
1168 | // we don't need a mapping from `NodeId` to `LocalDefId`. | |
1169 | if node_id != ast::DUMMY_NODE_ID { | |
1170 | debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); | |
1171 | self.node_id_to_def_id.insert(node_id, def_id); | |
1172 | } | |
1173 | assert_eq!(self.def_id_to_node_id.push(node_id), def_id); | |
1174 | ||
1175 | def_id | |
1176 | } | |
5e7ed085 | 1177 | |
923072b8 FG |
1178 | fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize { |
1179 | if let Some(def_id) = def_id.as_local() { | |
1180 | self.item_generics_num_lifetimes[&def_id] | |
1181 | } else { | |
9ffffee4 | 1182 | self.cstore().item_generics_num_lifetimes(def_id, self.tcx.sess) |
923072b8 | 1183 | } |
5e7ed085 | 1184 | } |
9c376795 | 1185 | |
9ffffee4 FG |
1186 | pub fn tcx(&self) -> TyCtxt<'tcx> { |
1187 | self.tcx | |
9c376795 | 1188 | } |
a7813a04 XL |
1189 | } |
1190 | ||
9ffffee4 | 1191 | impl<'a, 'tcx> Resolver<'a, 'tcx> { |
dfeec247 | 1192 | pub fn new( |
9ffffee4 | 1193 | tcx: TyCtxt<'tcx>, |
dfeec247 | 1194 | krate: &Crate, |
dfeec247 | 1195 | arenas: &'a ResolverArenas<'a>, |
9ffffee4 | 1196 | ) -> Resolver<'a, 'tcx> { |
c295e0f8 | 1197 | let root_def_id = CRATE_DEF_ID.to_def_id(); |
0bf4aa26 | 1198 | let mut module_map = FxHashMap::default(); |
c295e0f8 XL |
1199 | let graph_root = arenas.new_module( |
1200 | None, | |
1201 | ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), | |
1202 | ExpnId::root(), | |
5e7ed085 | 1203 | krate.spans.inner_span, |
9ffffee4 | 1204 | tcx.sess.contains_name(&krate.attrs, sym::no_implicit_prelude), |
c295e0f8 XL |
1205 | &mut module_map, |
1206 | ); | |
1207 | let empty_module = arenas.new_module( | |
1208 | None, | |
1209 | ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), | |
1210 | ExpnId::root(), | |
1211 | DUMMY_SP, | |
1212 | true, | |
1213 | &mut FxHashMap::default(), | |
1214 | ); | |
1a4d82fc | 1215 | |
29967ef6 | 1216 | let mut visibilities = FxHashMap::default(); |
c295e0f8 | 1217 | visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public); |
29967ef6 | 1218 | |
f035d41b | 1219 | let mut def_id_to_node_id = IndexVec::default(); |
04454e1e | 1220 | assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID); |
f035d41b | 1221 | let mut node_id_to_def_id = FxHashMap::default(); |
04454e1e | 1222 | node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID); |
f035d41b XL |
1223 | |
1224 | let mut invocation_parents = FxHashMap::default(); | |
04454e1e | 1225 | invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential)); |
c30ab7b3 | 1226 | |
9ffffee4 FG |
1227 | let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = tcx |
1228 | .sess | |
dfeec247 XL |
1229 | .opts |
1230 | .externs | |
1231 | .iter() | |
1232 | .filter(|(_, entry)| entry.add_prelude) | |
1233 | .map(|(name, _)| (Ident::from_str(name), Default::default())) | |
1234 | .collect(); | |
b7449926 | 1235 | |
9ffffee4 | 1236 | if !tcx.sess.contains_name(&krate.attrs, sym::no_core) { |
e1599b0c | 1237 | extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default()); |
9ffffee4 | 1238 | if !tcx.sess.contains_name(&krate.attrs, sym::no_std) { |
e1599b0c | 1239 | extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default()); |
4462d4a0 XL |
1240 | } |
1241 | } | |
94b46f34 | 1242 | |
9ffffee4 | 1243 | let registered_tools = macros::registered_tools(tcx.sess, &krate.attrs); |
60c5eb7d | 1244 | |
9ffffee4 | 1245 | let features = tcx.sess.features_untracked(); |
dc9dc135 | 1246 | |
29967ef6 | 1247 | let mut resolver = Resolver { |
9ffffee4 | 1248 | tcx, |
1a4d82fc | 1249 | |
923072b8 | 1250 | expn_that_defined: Default::default(), |
1a4d82fc JJ |
1251 | |
1252 | // The outermost module has def ID 0; this is not reflected in the | |
1253 | // AST. | |
3b2f2976 | 1254 | graph_root, |
3157f602 | 1255 | prelude: None, |
94b46f34 | 1256 | extern_prelude, |
1a4d82fc | 1257 | |
0bf4aa26 XL |
1258 | has_self: FxHashSet::default(), |
1259 | field_names: FxHashMap::default(), | |
9c376795 | 1260 | field_visibility_spans: FxHashMap::default(), |
1a4d82fc | 1261 | |
9e0c209e SL |
1262 | determined_imports: Vec::new(), |
1263 | indeterminate_imports: Vec::new(), | |
1a4d82fc | 1264 | |
cdc7bbd5 | 1265 | pat_span_map: Default::default(), |
48663c56 XL |
1266 | partial_res_map: Default::default(), |
1267 | import_res_map: Default::default(), | |
1268 | label_res_map: Default::default(), | |
04454e1e FG |
1269 | lifetimes_res_map: Default::default(), |
1270 | extra_lifetime_params_map: Default::default(), | |
e74abb32 | 1271 | extern_crate_map: Default::default(), |
5099ac24 | 1272 | reexport_map: FxHashMap::default(), |
3c0e092e | 1273 | trait_map: NodeMap::default(), |
e74abb32 | 1274 | underscore_disambiguator: 0, |
e1599b0c | 1275 | empty_module, |
3b2f2976 | 1276 | module_map, |
a1dfa0c6 | 1277 | block_map: Default::default(), |
0bf4aa26 | 1278 | binding_parent_modules: FxHashMap::default(), |
e1599b0c | 1279 | ast_transform_scopes: FxHashMap::default(), |
1a4d82fc | 1280 | |
a1dfa0c6 | 1281 | glob_map: Default::default(), |
29967ef6 | 1282 | visibilities, |
04454e1e | 1283 | has_pub_restricted: false, |
0bf4aa26 | 1284 | used_imports: FxHashSet::default(), |
a1dfa0c6 | 1285 | maybe_unused_trait_imports: Default::default(), |
a7813a04 | 1286 | |
54a0048b | 1287 | privacy_errors: Vec::new(), |
9e0c209e | 1288 | ambiguity_errors: Vec::new(), |
3b2f2976 | 1289 | use_injections: Vec::new(), |
b7449926 | 1290 | macro_expanded_macro_export_errors: BTreeSet::new(), |
9cc50fc6 | 1291 | |
3b2f2976 | 1292 | arenas, |
9e0c209e | 1293 | dummy_binding: arenas.alloc_name_binding(NameBinding { |
487cf647 | 1294 | kind: NameBindingKind::Res(Res::Err), |
0731742a | 1295 | ambiguity: None, |
136023e0 | 1296 | expansion: LocalExpnId::ROOT, |
9e0c209e SL |
1297 | span: DUMMY_SP, |
1298 | vis: ty::Visibility::Public, | |
1299 | }), | |
32a655c1 | 1300 | |
9c376795 | 1301 | used_extern_options: Default::default(), |
0bf4aa26 | 1302 | macro_names: FxHashSet::default(), |
416331ca | 1303 | builtin_macros: Default::default(), |
5e7ed085 | 1304 | builtin_macro_kinds: Default::default(), |
60c5eb7d | 1305 | registered_tools, |
0bf4aa26 | 1306 | macro_use_prelude: FxHashMap::default(), |
0bf4aa26 | 1307 | macro_map: FxHashMap::default(), |
9ffffee4 FG |
1308 | dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(tcx.sess.edition())), |
1309 | dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(tcx.sess.edition())), | |
1310 | non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(tcx.sess.edition())), | |
29967ef6 | 1311 | invocation_parent_scopes: Default::default(), |
ba9703b0 | 1312 | output_macro_rules_scopes: Default::default(), |
04454e1e | 1313 | macro_rules_scopes: Default::default(), |
60c5eb7d | 1314 | helper_attrs: Default::default(), |
cdc7bbd5 | 1315 | derive_data: Default::default(), |
0bf4aa26 XL |
1316 | local_macro_def_scopes: FxHashMap::default(), |
1317 | name_already_seen: FxHashMap::default(), | |
32a655c1 | 1318 | potentially_unused_imports: Vec::new(), |
a1dfa0c6 | 1319 | struct_constructors: Default::default(), |
416331ca | 1320 | unused_macros: Default::default(), |
04454e1e | 1321 | unused_macro_rules: Default::default(), |
416331ca | 1322 | proc_macro_stubs: Default::default(), |
e1599b0c XL |
1323 | single_segment_macro_resolutions: Default::default(), |
1324 | multi_segment_macro_resolutions: Default::default(), | |
1325 | builtin_attrs: Default::default(), | |
60c5eb7d | 1326 | containers_deriving_copy: Default::default(), |
dfeec247 XL |
1327 | active_features: features |
1328 | .declared_lib_features | |
1329 | .iter() | |
1330 | .map(|(feat, ..)| *feat) | |
1331 | .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat)) | |
1332 | .collect(), | |
dfeec247 | 1333 | lint_buffer: LintBuffer::default(), |
a2a8927a | 1334 | next_node_id: CRATE_NODE_ID, |
f035d41b XL |
1335 | node_id_to_def_id, |
1336 | def_id_to_node_id, | |
1337 | placeholder_field_indices: Default::default(), | |
1338 | invocation_parents, | |
29967ef6 | 1339 | trait_impl_items: Default::default(), |
6a06907d | 1340 | legacy_const_generic_args: Default::default(), |
94222f64 | 1341 | item_generics_num_lifetimes: Default::default(), |
cdc7bbd5 | 1342 | main_def: Default::default(), |
94222f64 XL |
1343 | trait_impls: Default::default(), |
1344 | proc_macros: Default::default(), | |
c295e0f8 | 1345 | confused_type_with_std_module: Default::default(), |
487cf647 | 1346 | lifetime_elision_allowed: Default::default(), |
2b03887a | 1347 | effective_visibilities: Default::default(), |
9ffffee4 FG |
1348 | doc_link_resolutions: Default::default(), |
1349 | doc_link_traits_in_scope: Default::default(), | |
1350 | all_macro_rules: Default::default(), | |
29967ef6 XL |
1351 | }; |
1352 | ||
1353 | let root_parent_scope = ParentScope::module(graph_root, &resolver); | |
136023e0 | 1354 | resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope); |
29967ef6 XL |
1355 | |
1356 | resolver | |
9cc50fc6 SL |
1357 | } |
1358 | ||
c295e0f8 XL |
1359 | fn new_module( |
1360 | &mut self, | |
1361 | parent: Option<Module<'a>>, | |
1362 | kind: ModuleKind, | |
1363 | expn_id: ExpnId, | |
1364 | span: Span, | |
1365 | no_implicit_prelude: bool, | |
1366 | ) -> Module<'a> { | |
1367 | let module_map = &mut self.module_map; | |
1368 | self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map) | |
1369 | } | |
1370 | ||
9ffffee4 | 1371 | fn next_node_id(&mut self) -> NodeId { |
04454e1e FG |
1372 | let start = self.next_node_id; |
1373 | let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds"); | |
1374 | self.next_node_id = ast::NodeId::from_u32(next); | |
1375 | start | |
1376 | } | |
1377 | ||
9ffffee4 | 1378 | fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> { |
04454e1e FG |
1379 | let start = self.next_node_id; |
1380 | let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds"); | |
1381 | self.next_node_id = ast::NodeId::from_usize(end); | |
1382 | start..self.next_node_id | |
60c5eb7d XL |
1383 | } |
1384 | ||
dfeec247 | 1385 | pub fn lint_buffer(&mut self) -> &mut LintBuffer { |
e74abb32 XL |
1386 | &mut self.lint_buffer |
1387 | } | |
1388 | ||
3157f602 | 1389 | pub fn arenas() -> ResolverArenas<'a> { |
0bf4aa26 | 1390 | Default::default() |
1a4d82fc JJ |
1391 | } |
1392 | ||
2b03887a | 1393 | pub fn into_outputs(self) -> ResolverOutputs { |
94222f64 | 1394 | let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); |
923072b8 | 1395 | let expn_that_defined = self.expn_that_defined; |
29967ef6 | 1396 | let visibilities = self.visibilities; |
04454e1e | 1397 | let has_pub_restricted = self.has_pub_restricted; |
f9f354fc | 1398 | let extern_crate_map = self.extern_crate_map; |
5099ac24 | 1399 | let reexport_map = self.reexport_map; |
f9f354fc | 1400 | let maybe_unused_trait_imports = self.maybe_unused_trait_imports; |
f9f354fc | 1401 | let glob_map = self.glob_map; |
cdc7bbd5 | 1402 | let main_def = self.main_def; |
c295e0f8 | 1403 | let confused_type_with_std_module = self.confused_type_with_std_module; |
2b03887a FG |
1404 | let effective_visibilities = self.effective_visibilities; |
1405 | let global_ctxt = ResolverGlobalCtxt { | |
923072b8 | 1406 | expn_that_defined, |
29967ef6 | 1407 | visibilities, |
04454e1e | 1408 | has_pub_restricted, |
2b03887a | 1409 | effective_visibilities, |
f9f354fc | 1410 | extern_crate_map, |
5099ac24 | 1411 | reexport_map, |
f9f354fc XL |
1412 | glob_map, |
1413 | maybe_unused_trait_imports, | |
cdc7bbd5 | 1414 | main_def, |
94222f64 XL |
1415 | trait_impls: self.trait_impls, |
1416 | proc_macros, | |
c295e0f8 | 1417 | confused_type_with_std_module, |
5099ac24 | 1418 | registered_tools: self.registered_tools, |
9ffffee4 FG |
1419 | doc_link_resolutions: self.doc_link_resolutions, |
1420 | doc_link_traits_in_scope: self.doc_link_traits_in_scope, | |
1421 | all_macro_rules: self.all_macro_rules, | |
923072b8 | 1422 | }; |
2b03887a | 1423 | let ast_lowering = ty::ResolverAstLowering { |
923072b8 FG |
1424 | legacy_const_generic_args: self.legacy_const_generic_args, |
1425 | partial_res_map: self.partial_res_map, | |
1426 | import_res_map: self.import_res_map, | |
1427 | label_res_map: self.label_res_map, | |
1428 | lifetimes_res_map: self.lifetimes_res_map, | |
1429 | extra_lifetime_params_map: self.extra_lifetime_params_map, | |
1430 | next_node_id: self.next_node_id, | |
1431 | node_id_to_def_id: self.node_id_to_def_id, | |
1432 | def_id_to_node_id: self.def_id_to_node_id, | |
1433 | trait_map: self.trait_map, | |
1434 | builtin_macro_kinds: self.builtin_macro_kinds, | |
487cf647 | 1435 | lifetime_elision_allowed: self.lifetime_elision_allowed, |
923072b8 | 1436 | }; |
9ffffee4 | 1437 | ResolverOutputs { global_ctxt, ast_lowering } |
923072b8 FG |
1438 | } |
1439 | ||
1440 | fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { | |
9ffffee4 | 1441 | StableHashingContext::new(self.tcx.sess, self.tcx.untracked()) |
9c376795 FG |
1442 | } |
1443 | ||
9ffffee4 FG |
1444 | fn crate_loader<T>(&mut self, f: impl FnOnce(&mut CrateLoader<'_, '_>) -> T) -> T { |
1445 | let mut cstore = self.tcx.untracked().cstore.write(); | |
1446 | let cstore = cstore.untracked_as_any().downcast_mut().unwrap(); | |
1447 | f(&mut CrateLoader::new(self.tcx, &mut *cstore, &mut self.used_extern_options)) | |
e74abb32 XL |
1448 | } |
1449 | ||
9ffffee4 FG |
1450 | fn cstore(&self) -> MappedReadGuard<'_, CStore> { |
1451 | CStore::from_tcx(self.tcx) | |
e74abb32 XL |
1452 | } |
1453 | ||
416331ca XL |
1454 | fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> { |
1455 | match macro_kind { | |
1456 | MacroKind::Bang => self.dummy_ext_bang.clone(), | |
1457 | MacroKind::Derive => self.dummy_ext_derive.clone(), | |
94222f64 | 1458 | MacroKind::Attr => self.non_macro_attr.clone(), |
416331ca XL |
1459 | } |
1460 | } | |
1461 | ||
0531ce1d | 1462 | /// Runs the function on each namespace. |
83c7162d XL |
1463 | fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) { |
1464 | f(self, TypeNS); | |
1465 | f(self, ValueNS); | |
b7449926 | 1466 | f(self, MacroNS); |
476ff2be | 1467 | } |
c30ab7b3 | 1468 | |
e1599b0c | 1469 | fn is_builtin_macro(&mut self, res: Res) -> bool { |
923072b8 | 1470 | self.get_macro(res).map_or(false, |macro_data| macro_data.ext.builtin_name.is_some()) |
416331ca XL |
1471 | } |
1472 | ||
ff7c6d11 XL |
1473 | fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId { |
1474 | loop { | |
6a06907d | 1475 | match ctxt.outer_expn_data().macro_def_id { |
f9f354fc | 1476 | Some(def_id) => return def_id, |
ff7c6d11 XL |
1477 | None => ctxt.remove_mark(), |
1478 | }; | |
1479 | } | |
1480 | } | |
1481 | ||
476ff2be SL |
1482 | /// Entry point to crate resolution. |
1483 | pub fn resolve_crate(&mut self, krate: &Crate) { | |
9ffffee4 FG |
1484 | self.tcx.sess.time("resolve_crate", || { |
1485 | self.tcx.sess.time("finalize_imports", || self.finalize_imports()); | |
1486 | self.tcx.sess.time("compute_effective_visibilities", || { | |
2b03887a | 1487 | EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate) |
5099ac24 | 1488 | }); |
9ffffee4 FG |
1489 | self.tcx.sess.time("finalize_macro_resolutions", || self.finalize_macro_resolutions()); |
1490 | self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate)); | |
1491 | self.tcx.sess.time("resolve_main", || self.resolve_main()); | |
1492 | self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate)); | |
1493 | self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate)); | |
1494 | self.tcx | |
1495 | .sess | |
1496 | .time("resolve_postprocess", || self.crate_loader(|c| c.postprocess(krate))); | |
5869c6ff | 1497 | }); |
9ffffee4 FG |
1498 | |
1499 | // Make sure we don't mutate the cstore from here on. | |
1500 | self.tcx.untracked().cstore.leak(); | |
5869c6ff | 1501 | } |
e74abb32 | 1502 | |
9ffffee4 | 1503 | fn traits_in_scope( |
5869c6ff XL |
1504 | &mut self, |
1505 | current_trait: Option<Module<'a>>, | |
1506 | parent_scope: &ParentScope<'a>, | |
1507 | ctxt: SyntaxContext, | |
1508 | assoc_item: Option<(Symbol, Namespace)>, | |
1509 | ) -> Vec<TraitCandidate> { | |
1510 | let mut found_traits = Vec::new(); | |
1511 | ||
1512 | if let Some(module) = current_trait { | |
1513 | if self.trait_may_have_item(Some(module), assoc_item) { | |
c295e0f8 | 1514 | let def_id = module.def_id(); |
5869c6ff XL |
1515 | found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] }); |
1516 | } | |
1517 | } | |
3b2f2976 | 1518 | |
5869c6ff XL |
1519 | self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| { |
1520 | match scope { | |
cdc7bbd5 | 1521 | Scope::Module(module, _) => { |
5869c6ff XL |
1522 | this.traits_in_module(module, assoc_item, &mut found_traits); |
1523 | } | |
1524 | Scope::StdLibPrelude => { | |
1525 | if let Some(module) = this.prelude { | |
1526 | this.traits_in_module(module, assoc_item, &mut found_traits); | |
1527 | } | |
1528 | } | |
1529 | Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {} | |
1530 | _ => unreachable!(), | |
1531 | } | |
1532 | None::<()> | |
1533 | }); | |
3157f602 | 1534 | |
5869c6ff | 1535 | found_traits |
3157f602 XL |
1536 | } |
1537 | ||
5869c6ff | 1538 | fn traits_in_module( |
3dfed10e | 1539 | &mut self, |
3dfed10e | 1540 | module: Module<'a>, |
5869c6ff | 1541 | assoc_item: Option<(Symbol, Namespace)>, |
3dfed10e | 1542 | found_traits: &mut Vec<TraitCandidate>, |
3dfed10e | 1543 | ) { |
3dfed10e XL |
1544 | module.ensure_traits(self); |
1545 | let traits = module.traits.borrow(); | |
5869c6ff XL |
1546 | for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() { |
1547 | if self.trait_may_have_item(trait_binding.module(), assoc_item) { | |
1548 | let def_id = trait_binding.res().def_id(); | |
1549 | let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name); | |
1550 | found_traits.push(TraitCandidate { def_id, import_ids }); | |
1551 | } | |
1552 | } | |
1553 | } | |
3dfed10e | 1554 | |
5869c6ff XL |
1555 | // List of traits in scope is pruned on best effort basis. We reject traits not having an |
1556 | // associated item with the given name and namespace (if specified). This is a conservative | |
1557 | // optimization, proper hygienic type-based resolution of associated items is done in typeck. | |
1558 | // We don't reject trait aliases (`trait_module == None`) because we don't have access to their | |
1559 | // associated items. | |
1560 | fn trait_may_have_item( | |
1561 | &mut self, | |
1562 | trait_module: Option<Module<'a>>, | |
1563 | assoc_item: Option<(Symbol, Namespace)>, | |
1564 | ) -> bool { | |
1565 | match (trait_module, assoc_item) { | |
1566 | (Some(trait_module), Some((name, ns))) => { | |
1567 | self.resolutions(trait_module).borrow().iter().any(|resolution| { | |
1568 | let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution; | |
1569 | assoc_ns == ns && assoc_ident.name == name | |
1570 | }) | |
3dfed10e | 1571 | } |
5869c6ff | 1572 | _ => true, |
3dfed10e XL |
1573 | } |
1574 | } | |
1575 | ||
1576 | fn find_transitive_imports( | |
1577 | &mut self, | |
1578 | mut kind: &NameBindingKind<'_>, | |
1579 | trait_name: Ident, | |
1580 | ) -> SmallVec<[LocalDefId; 1]> { | |
1581 | let mut import_ids = smallvec![]; | |
1582 | while let NameBindingKind::Import { import, binding, .. } = kind { | |
487cf647 FG |
1583 | if let Some(node_id) = import.id() { |
1584 | let def_id = self.local_def_id(node_id); | |
1585 | self.maybe_unused_trait_imports.insert(def_id); | |
1586 | import_ids.push(def_id); | |
1587 | } | |
3dfed10e | 1588 | self.add_to_glob_map(&import, trait_name); |
3dfed10e XL |
1589 | kind = &binding.kind; |
1590 | } | |
1591 | import_ids | |
1592 | } | |
1593 | ||
e74abb32 | 1594 | fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey { |
ba9703b0 | 1595 | let ident = ident.normalize_to_macros_2_0(); |
e74abb32 XL |
1596 | let disambiguator = if ident.name == kw::Underscore { |
1597 | self.underscore_disambiguator += 1; | |
1598 | self.underscore_disambiguator | |
1599 | } else { | |
1600 | 0 | |
1601 | }; | |
1602 | BindingKey { ident, ns, disambiguator } | |
1603 | } | |
1604 | ||
e1599b0c XL |
1605 | fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> { |
1606 | if module.populate_on_access.get() { | |
1607 | module.populate_on_access.set(false); | |
1608 | self.build_reduced_graph_external(module); | |
1609 | } | |
1610 | &module.lazy_resolutions | |
1611 | } | |
1612 | ||
dfeec247 XL |
1613 | fn resolution( |
1614 | &mut self, | |
1615 | module: Module<'a>, | |
1616 | key: BindingKey, | |
1617 | ) -> &'a RefCell<NameResolution<'a>> { | |
1618 | *self | |
1619 | .resolutions(module) | |
1620 | .borrow_mut() | |
1621 | .entry(key) | |
1622 | .or_insert_with(|| self.arenas.alloc_name_resolution()) | |
e1599b0c XL |
1623 | } |
1624 | ||
9c376795 FG |
1625 | /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors |
1626 | fn matches_previous_ambiguity_error(&mut self, ambi: &AmbiguityError<'_>) -> bool { | |
1627 | for ambiguity_error in &self.ambiguity_errors { | |
1628 | // if the span location and ident as well as its span are the same | |
1629 | if ambiguity_error.kind == ambi.kind | |
1630 | && ambiguity_error.ident == ambi.ident | |
1631 | && ambiguity_error.ident.span == ambi.ident.span | |
1632 | && ambiguity_error.b1.span == ambi.b1.span | |
1633 | && ambiguity_error.b2.span == ambi.b2.span | |
1634 | && ambiguity_error.misc1 == ambi.misc1 | |
1635 | && ambiguity_error.misc2 == ambi.misc2 | |
1636 | { | |
1637 | return true; | |
1638 | } | |
1639 | } | |
1640 | false | |
1641 | } | |
1642 | ||
dfeec247 XL |
1643 | fn record_use( |
1644 | &mut self, | |
1645 | ident: Ident, | |
dfeec247 XL |
1646 | used_binding: &'a NameBinding<'a>, |
1647 | is_lexical_scope: bool, | |
1648 | ) { | |
0731742a | 1649 | if let Some((b2, kind)) = used_binding.ambiguity { |
9c376795 | 1650 | let ambiguity_error = AmbiguityError { |
dfeec247 XL |
1651 | kind, |
1652 | ident, | |
1653 | b1: used_binding, | |
1654 | b2, | |
0731742a XL |
1655 | misc1: AmbiguityErrorMisc::None, |
1656 | misc2: AmbiguityErrorMisc::None, | |
9c376795 FG |
1657 | }; |
1658 | if !self.matches_previous_ambiguity_error(&ambiguity_error) { | |
1659 | // avoid dumplicated span information to be emitt out | |
1660 | self.ambiguity_errors.push(ambiguity_error); | |
1661 | } | |
0731742a | 1662 | } |
74b04a01 | 1663 | if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind { |
0731742a XL |
1664 | // Avoid marking `extern crate` items that refer to a name from extern prelude, |
1665 | // but not introduce it, as used if they are accessed from lexical scope. | |
1666 | if is_lexical_scope { | |
ba9703b0 | 1667 | if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) { |
0731742a XL |
1668 | if let Some(crate_item) = entry.extern_crate_item { |
1669 | if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item { | |
1670 | return; | |
13cf67c4 XL |
1671 | } |
1672 | } | |
1673 | } | |
9e0c209e | 1674 | } |
0731742a | 1675 | used.set(true); |
74b04a01 | 1676 | import.used.set(true); |
487cf647 FG |
1677 | if let Some(id) = import.id() { |
1678 | self.used_imports.insert(id); | |
1679 | } | |
74b04a01 | 1680 | self.add_to_glob_map(&import, ident); |
94222f64 | 1681 | self.record_use(ident, binding, false); |
54a0048b | 1682 | } |
5bcae85e | 1683 | } |
7453a54e | 1684 | |
9fa01778 | 1685 | #[inline] |
74b04a01 | 1686 | fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) { |
487cf647 FG |
1687 | if let ImportKind::Glob { id, .. } = import.kind { |
1688 | let def_id = self.local_def_id(id); | |
f9f354fc | 1689 | self.glob_map.entry(def_id).or_default().insert(ident.name); |
1a4d82fc | 1690 | } |
1a4d82fc JJ |
1691 | } |
1692 | ||
8faf50e0 | 1693 | fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> { |
3dfed10e | 1694 | debug!("resolve_crate_root({:?})", ident); |
8faf50e0 | 1695 | let mut ctxt = ident.span.ctxt(); |
dc9dc135 | 1696 | let mark = if ident.name == kw::DollarCrate { |
2c00a5a8 XL |
1697 | // When resolving `$crate` from a `macro_rules!` invoked in a `macro`, |
1698 | // we don't want to pretend that the `macro_rules!` definition is in the `macro` | |
ba9703b0 | 1699 | // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks. |
8faf50e0 XL |
1700 | // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!` |
1701 | // definitions actually produced by `macro` and `macro` definitions produced by | |
1702 | // `macro_rules!`, but at least such configurations are not stable yet. | |
ba9703b0 | 1703 | ctxt = ctxt.normalize_to_macro_rules(); |
3dfed10e XL |
1704 | debug!( |
1705 | "resolve_crate_root: marks={:?}", | |
1706 | ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>() | |
1707 | ); | |
8faf50e0 XL |
1708 | let mut iter = ctxt.marks().into_iter().rev().peekable(); |
1709 | let mut result = None; | |
ba9703b0 | 1710 | // Find the last opaque mark from the end if it exists. |
8faf50e0 XL |
1711 | while let Some(&(mark, transparency)) = iter.peek() { |
1712 | if transparency == Transparency::Opaque { | |
1713 | result = Some(mark); | |
1714 | iter.next(); | |
1715 | } else { | |
1716 | break; | |
1717 | } | |
1718 | } | |
3dfed10e XL |
1719 | debug!( |
1720 | "resolve_crate_root: found opaque mark {:?} {:?}", | |
1721 | result, | |
1722 | result.map(|r| r.expn_data()) | |
1723 | ); | |
ba9703b0 | 1724 | // Then find the last semi-transparent mark from the end if it exists. |
8faf50e0 XL |
1725 | for (mark, transparency) in iter { |
1726 | if transparency == Transparency::SemiTransparent { | |
1727 | result = Some(mark); | |
1728 | } else { | |
1729 | break; | |
1730 | } | |
1731 | } | |
3dfed10e XL |
1732 | debug!( |
1733 | "resolve_crate_root: found semi-transparent mark {:?} {:?}", | |
1734 | result, | |
1735 | result.map(|r| r.expn_data()) | |
1736 | ); | |
8faf50e0 | 1737 | result |
2c00a5a8 | 1738 | } else { |
3dfed10e | 1739 | debug!("resolve_crate_root: not DollarCrate"); |
ba9703b0 | 1740 | ctxt = ctxt.normalize_to_macros_2_0(); |
416331ca | 1741 | ctxt.adjust(ExpnId::root()) |
2c00a5a8 XL |
1742 | }; |
1743 | let module = match mark { | |
c295e0f8 | 1744 | Some(def) => self.expn_def_scope(def), |
3dfed10e XL |
1745 | None => { |
1746 | debug!( | |
1747 | "resolve_crate_root({:?}): found no mark (ident.span = {:?})", | |
1748 | ident, ident.span | |
1749 | ); | |
1750 | return self.graph_root; | |
1751 | } | |
7cac9316 | 1752 | }; |
c295e0f8 XL |
1753 | let module = self.expect_module( |
1754 | module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(), | |
1755 | ); | |
3dfed10e XL |
1756 | debug!( |
1757 | "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})", | |
1758 | ident, | |
1759 | module, | |
1760 | module.kind.name(), | |
1761 | ident.span | |
1762 | ); | |
1763 | module | |
7cac9316 XL |
1764 | } |
1765 | ||
1766 | fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> { | |
c295e0f8 | 1767 | let mut module = self.expect_module(module.nearest_parent_mod()); |
ba9703b0 | 1768 | while module.span.ctxt().normalize_to_macros_2_0() != *ctxt { |
c295e0f8 XL |
1769 | let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark())); |
1770 | module = self.expect_module(parent.nearest_parent_mod()); | |
c30ab7b3 | 1771 | } |
7cac9316 | 1772 | module |
c30ab7b3 SL |
1773 | } |
1774 | ||
48663c56 XL |
1775 | fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) { |
1776 | debug!("(recording res) recording {:?} for {}", resolution, node_id); | |
1777 | if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) { | |
a7813a04 | 1778 | panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution); |
1a4d82fc JJ |
1779 | } |
1780 | } | |
1781 | ||
cdc7bbd5 XL |
1782 | fn record_pat_span(&mut self, node: NodeId, span: Span) { |
1783 | debug!("(recording pat) recording {:?} for {:?}", node, span); | |
1784 | self.pat_span_map.insert(node, span); | |
1785 | } | |
1786 | ||
f2b60f7d FG |
1787 | fn is_accessible_from( |
1788 | &self, | |
1789 | vis: ty::Visibility<impl Into<DefId>>, | |
1790 | module: Module<'a>, | |
1791 | ) -> bool { | |
c295e0f8 | 1792 | vis.is_accessible_from(module.nearest_parent_mod(), self) |
54a0048b SL |
1793 | } |
1794 | ||
4462d4a0 | 1795 | fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) { |
5099ac24 FG |
1796 | if let Some(old_module) = |
1797 | self.binding_parent_modules.insert(Interned::new_unchecked(binding), module) | |
1798 | { | |
4462d4a0 XL |
1799 | if !ptr::eq(module, old_module) { |
1800 | span_bug!(binding.span, "parent module is reset for binding"); | |
1801 | } | |
1802 | } | |
1803 | } | |
1804 | ||
ba9703b0 | 1805 | fn disambiguate_macro_rules_vs_modularized( |
4462d4a0 | 1806 | &self, |
ba9703b0 XL |
1807 | macro_rules: &'a NameBinding<'a>, |
1808 | modularized: &'a NameBinding<'a>, | |
4462d4a0 | 1809 | ) -> bool { |
ba9703b0 | 1810 | // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules" |
4462d4a0 XL |
1811 | // is disambiguated to mitigate regressions from macro modularization. |
1812 | // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general. | |
dfeec247 | 1813 | match ( |
5099ac24 FG |
1814 | self.binding_parent_modules.get(&Interned::new_unchecked(macro_rules)), |
1815 | self.binding_parent_modules.get(&Interned::new_unchecked(modularized)), | |
dfeec247 | 1816 | ) { |
ba9703b0 | 1817 | (Some(macro_rules), Some(modularized)) => { |
c295e0f8 | 1818 | macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod() |
ba9703b0 | 1819 | && modularized.is_ancestor_of(macro_rules) |
dfeec247 | 1820 | } |
4462d4a0 XL |
1821 | _ => false, |
1822 | } | |
1823 | } | |
1824 | ||
5e7ed085 | 1825 | fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> { |
13cf67c4 XL |
1826 | if ident.is_path_segment_keyword() { |
1827 | // Make sure `self`, `super` etc produce an error when passed to here. | |
1828 | return None; | |
1829 | } | |
ba9703b0 | 1830 | self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| { |
0bf4aa26 | 1831 | if let Some(binding) = entry.extern_crate_item { |
5e7ed085 | 1832 | if finalize && entry.introduced_by_item { |
94222f64 | 1833 | self.record_use(ident, binding, false); |
0731742a | 1834 | } |
0bf4aa26 XL |
1835 | Some(binding) |
1836 | } else { | |
5e7ed085 | 1837 | let crate_id = if finalize { |
a2a8927a | 1838 | let Some(crate_id) = |
9ffffee4 | 1839 | self.crate_loader(|c| c.process_path_extern(ident.name, ident.span)) else { return Some(self.dummy_binding); }; |
a2a8927a | 1840 | crate_id |
0bf4aa26 | 1841 | } else { |
9ffffee4 | 1842 | self.crate_loader(|c| c.maybe_process_path_extern(ident.name))? |
0bf4aa26 | 1843 | }; |
c295e0f8 | 1844 | let crate_root = self.expect_module(crate_id.as_def_id()); |
f2b60f7d FG |
1845 | let vis = ty::Visibility::<LocalDefId>::Public; |
1846 | Some((crate_root, vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(self.arenas)) | |
0bf4aa26 XL |
1847 | } |
1848 | }) | |
1849 | } | |
c34b1796 | 1850 | |
5e7ed085 | 1851 | /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>` |
416331ca XL |
1852 | /// isn't something that can be returned because it can't be made to live that long, |
1853 | /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, | |
1854 | /// just that an error occurred. | |
9ffffee4 | 1855 | fn resolve_rustdoc_path( |
dfeec247 | 1856 | &mut self, |
dfeec247 XL |
1857 | path_str: &str, |
1858 | ns: Namespace, | |
04454e1e | 1859 | mut parent_scope: ParentScope<'a>, |
5e7ed085 FG |
1860 | ) -> Option<Res> { |
1861 | let mut segments = | |
1862 | Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident)); | |
04454e1e FG |
1863 | if let Some(segment) = segments.first_mut() { |
1864 | if segment.ident.name == kw::Crate { | |
1865 | // FIXME: `resolve_path` always resolves `crate` to the current crate root, but | |
1866 | // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of | |
1867 | // replacing `crate` with `self` and changing the current module should achieve | |
1868 | // the same effect. | |
1869 | segment.ident.name = kw::SelfLower; | |
1870 | parent_scope.module = | |
1871 | self.expect_module(parent_scope.module.def_id().krate.as_def_id()); | |
1872 | } else if segment.ident.name == kw::Empty { | |
1873 | segment.ident.name = kw::PathRoot; | |
1874 | } | |
5e7ed085 | 1875 | } |
416331ca | 1876 | |
04454e1e | 1877 | match self.maybe_resolve_path(&segments, Some(ns), &parent_scope) { |
5e7ed085 | 1878 | PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()), |
2b03887a FG |
1879 | PathResult::NonModule(path_res) => path_res.full_res(), |
1880 | PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => { | |
1881 | None | |
dfeec247 | 1882 | } |
416331ca | 1883 | PathResult::Module(..) | PathResult::Indeterminate => unreachable!(), |
416331ca XL |
1884 | } |
1885 | } | |
32a655c1 | 1886 | |
f035d41b XL |
1887 | /// Retrieves the span of the given `DefId` if `DefId` is in the local crate. |
1888 | #[inline] | |
9ffffee4 FG |
1889 | fn opt_span(&self, def_id: DefId) -> Option<Span> { |
1890 | def_id.as_local().map(|def_id| self.tcx.source_span(def_id)) | |
f035d41b | 1891 | } |
6a06907d | 1892 | |
f2b60f7d FG |
1893 | /// Retrieves the name of the given `DefId`. |
1894 | #[inline] | |
9ffffee4 | 1895 | fn opt_name(&self, def_id: DefId) -> Option<Symbol> { |
f2b60f7d | 1896 | let def_key = match def_id.as_local() { |
9ffffee4 | 1897 | Some(def_id) => self.tcx.definitions_untracked().def_key(def_id), |
f2b60f7d FG |
1898 | None => self.cstore().def_key(def_id), |
1899 | }; | |
1900 | def_key.get_opt_name() | |
1901 | } | |
1902 | ||
6a06907d XL |
1903 | /// Checks if an expression refers to a function marked with |
1904 | /// `#[rustc_legacy_const_generics]` and returns the argument index list | |
1905 | /// from the attribute. | |
9ffffee4 | 1906 | fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> { |
6a06907d XL |
1907 | if let ExprKind::Path(None, path) = &expr.kind { |
1908 | // Don't perform legacy const generics rewriting if the path already | |
1909 | // has generic arguments. | |
1910 | if path.segments.last().unwrap().args.is_some() { | |
1911 | return None; | |
1912 | } | |
1913 | ||
2b03887a FG |
1914 | let res = self.partial_res_map.get(&expr.id)?.full_res()?; |
1915 | if let Res::Def(def::DefKind::Fn, def_id) = res { | |
6a06907d XL |
1916 | // We only support cross-crate argument rewriting. Uses |
1917 | // within the same crate should be updated to use the new | |
1918 | // const generics style. | |
1919 | if def_id.is_local() { | |
1920 | return None; | |
1921 | } | |
1922 | ||
1923 | if let Some(v) = self.legacy_const_generic_args.get(&def_id) { | |
1924 | return v.clone(); | |
1925 | } | |
1926 | ||
a2a8927a XL |
1927 | let attr = self |
1928 | .cstore() | |
9ffffee4 | 1929 | .item_attrs_untracked(def_id, self.tcx.sess) |
a2a8927a XL |
1930 | .find(|a| a.has_name(sym::rustc_legacy_const_generics))?; |
1931 | let mut ret = Vec::new(); | |
1932 | for meta in attr.meta_item_list()? { | |
487cf647 | 1933 | match meta.lit()?.kind { |
a2a8927a XL |
1934 | LitKind::Int(a, _) => ret.push(a as usize), |
1935 | _ => panic!("invalid arg index"), | |
6a06907d | 1936 | } |
a2a8927a | 1937 | } |
f2b60f7d | 1938 | // Cache the lookup to avoid parsing attributes for an item multiple times. |
a2a8927a XL |
1939 | self.legacy_const_generic_args.insert(def_id, Some(ret.clone())); |
1940 | return Some(ret); | |
6a06907d XL |
1941 | } |
1942 | } | |
1943 | None | |
1944 | } | |
cdc7bbd5 XL |
1945 | |
1946 | fn resolve_main(&mut self) { | |
1947 | let module = self.graph_root; | |
1948 | let ident = Ident::with_dummy_span(sym::main); | |
1949 | let parent_scope = &ParentScope::module(module, self); | |
1950 | ||
04454e1e | 1951 | let Ok(name_binding) = self.maybe_resolve_ident_in_module( |
cdc7bbd5 XL |
1952 | ModuleOrUniformRoot::Module(module), |
1953 | ident, | |
1954 | ValueNS, | |
1955 | parent_scope, | |
5e7ed085 FG |
1956 | ) else { |
1957 | return; | |
cdc7bbd5 XL |
1958 | }; |
1959 | ||
1960 | let res = name_binding.res(); | |
1961 | let is_import = name_binding.is_import(); | |
1962 | let span = name_binding.span; | |
1963 | if let Res::Def(DefKind::Fn, _) = res { | |
94222f64 | 1964 | self.record_use(ident, name_binding, false); |
cdc7bbd5 XL |
1965 | } |
1966 | self.main_def = Some(MainDefinition { res, is_import, span }); | |
1967 | } | |
f2b60f7d FG |
1968 | |
1969 | // Items that go to reexport table encoded to metadata and visible through it to other crates. | |
1970 | fn is_reexport(&self, binding: &NameBinding<'a>) -> Option<def::Res<!>> { | |
487cf647 | 1971 | if binding.is_import() { |
f2b60f7d FG |
1972 | let res = binding.res().expect_non_local(); |
1973 | // Ambiguous imports are treated as errors at this point and are | |
1974 | // not exposed to other crates (see #36837 for more details). | |
1975 | if res != def::Res::Err && !binding.is_ambiguity() { | |
1976 | return Some(res); | |
1977 | } | |
1978 | } | |
1979 | ||
1980 | return None; | |
1981 | } | |
32a655c1 SL |
1982 | } |
1983 | ||
f9f354fc | 1984 | fn names_to_string(names: &[Symbol]) -> String { |
c34b1796 | 1985 | let mut result = String::new(); |
dfeec247 | 1986 | for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() { |
32a655c1 SL |
1987 | if i > 0 { |
1988 | result.push_str("::"); | |
c34b1796 | 1989 | } |
60c5eb7d XL |
1990 | if Ident::with_dummy_span(*name).is_raw_guess() { |
1991 | result.push_str("r#"); | |
1992 | } | |
a2a8927a | 1993 | result.push_str(name.as_str()); |
92a42be0 | 1994 | } |
c34b1796 AL |
1995 | result |
1996 | } | |
1997 | ||
32a655c1 | 1998 | fn path_names_to_string(path: &Path) -> String { |
60c5eb7d | 1999 | names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>()) |
c34b1796 AL |
2000 | } |
2001 | ||
2002 | /// A somewhat inefficient routine to obtain the name of a module. | |
9fa01778 | 2003 | fn module_to_string(module: Module<'_>) -> Option<String> { |
c34b1796 AL |
2004 | let mut names = Vec::new(); |
2005 | ||
f9f354fc | 2006 | fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) { |
48663c56 | 2007 | if let ModuleKind::Def(.., name) = module.kind { |
9e0c209e | 2008 | if let Some(parent) = module.parent { |
e1599b0c | 2009 | names.push(name); |
9e0c209e | 2010 | collect_mod(names, parent); |
c34b1796 | 2011 | } |
9e0c209e | 2012 | } else { |
f9f354fc | 2013 | names.push(Symbol::intern("<opaque>")); |
c30ab7b3 | 2014 | collect_mod(names, module.parent.unwrap()); |
c34b1796 AL |
2015 | } |
2016 | } | |
2017 | collect_mod(&mut names, module); | |
2018 | ||
9346a6ac | 2019 | if names.is_empty() { |
2c00a5a8 | 2020 | return None; |
c34b1796 | 2021 | } |
e1599b0c XL |
2022 | names.reverse(); |
2023 | Some(names_to_string(&names)) | |
c34b1796 AL |
2024 | } |
2025 | ||
94b46f34 | 2026 | #[derive(Copy, Clone, Debug)] |
04454e1e FG |
2027 | struct Finalize { |
2028 | /// Node ID for linting. | |
2029 | node_id: NodeId, | |
2030 | /// Span of the whole path or some its characteristic fragment. | |
2031 | /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths. | |
2032 | path_span: Span, | |
2b03887a | 2033 | /// Span of the path start, suitable for prepending something to it. |
04454e1e FG |
2034 | /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths. |
2035 | root_span: Span, | |
2036 | /// Whether to report privacy errors or silently return "no resolution" for them, | |
2037 | /// similarly to speculative resolution. | |
2038 | report_private: bool, | |
94b46f34 XL |
2039 | } |
2040 | ||
5e7ed085 | 2041 | impl Finalize { |
04454e1e FG |
2042 | fn new(node_id: NodeId, path_span: Span) -> Finalize { |
2043 | Finalize::with_root_span(node_id, path_span, path_span) | |
5e7ed085 FG |
2044 | } |
2045 | ||
04454e1e FG |
2046 | fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize { |
2047 | Finalize { node_id, path_span, root_span, report_private: true } | |
5e7ed085 | 2048 | } |
8faf50e0 | 2049 | } |