]>
Commit | Line | Data |
---|---|---|
f9f354fc XL |
1 | // ignore-tidy-filelength |
2 | ||
e1599b0c XL |
3 | //! This crate is responsible for the part of name resolution that doesn't require type checker. |
4 | //! | |
5 | //! Module structure of the crate is built here. | |
6 | //! Paths in macros, imports, expressions, types, patterns are resolved here. | |
dfeec247 | 7 | //! Label and lifetime names are resolved here as well. |
e1599b0c | 8 | //! |
cdc7bbd5 | 9 | //! Type-relative name resolution (methods, fields, associated items) happens in `rustc_typeck`. |
e1599b0c | 10 | |
1b1a35ee | 11 | #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] |
5869c6ff | 12 | #![feature(box_patterns)] |
60c5eb7d | 13 | #![feature(bool_to_option)] |
94b46f34 | 14 | #![feature(crate_visibility_modifier)] |
29967ef6 | 15 | #![feature(format_args_capture)] |
cdc7bbd5 | 16 | #![feature(iter_zip)] |
0bf4aa26 | 17 | #![feature(nll)] |
dfeec247 | 18 | #![recursion_limit = "256"] |
cdc7bbd5 | 19 | #![allow(rustdoc::private_intra_doc_links)] |
7cac9316 | 20 | |
dfeec247 | 21 | pub use rustc_hir::def::{Namespace, PerNS}; |
94b46f34 | 22 | |
416331ca | 23 | use Determinacy::*; |
1a4d82fc | 24 | |
29967ef6 | 25 | use rustc_arena::{DroplessArena, TypedArena}; |
f9f354fc | 26 | use rustc_ast::node_id::NodeMap; |
6a06907d | 27 | use rustc_ast::ptr::P; |
74b04a01 | 28 | use rustc_ast::visit::{self, Visitor}; |
6a06907d | 29 | use rustc_ast::{self as ast, NodeId}; |
3dfed10e | 30 | use rustc_ast::{Crate, CRATE_NODE_ID}; |
6a06907d XL |
31 | use rustc_ast::{Expr, ExprKind, LitKind}; |
32 | use rustc_ast::{ItemKind, ModKind, Path}; | |
f035d41b | 33 | use rustc_ast_lowering::ResolverAstLowering; |
74b04a01 | 34 | use rustc_ast_pretty::pprust; |
dfeec247 XL |
35 | use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; |
36 | use rustc_data_structures::ptr_key::PtrKey; | |
37 | use rustc_data_structures::sync::Lrc; | |
38 | use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder}; | |
cdc7bbd5 | 39 | use rustc_expand::base::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind}; |
dfeec247 XL |
40 | use rustc_hir::def::Namespace::*; |
41 | use rustc_hir::def::{self, CtorOf, DefKind, NonMacroAttrKind, PartialRes}; | |
136023e0 | 42 | use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefPathHash, LocalDefId, CRATE_DEF_INDEX}; |
f035d41b | 43 | use rustc_hir::definitions::{DefKey, DefPathData, Definitions}; |
cdc7bbd5 | 44 | use rustc_hir::TraitCandidate; |
f035d41b | 45 | use rustc_index::vec::IndexVec; |
dfeec247 | 46 | use rustc_metadata::creader::{CStore, CrateLoader}; |
ba9703b0 XL |
47 | use rustc_middle::hir::exports::ExportMap; |
48 | use rustc_middle::middle::cstore::{CrateStore, MetadataLoaderDyn}; | |
5869c6ff | 49 | use rustc_middle::span_bug; |
ba9703b0 | 50 | use rustc_middle::ty::query::Providers; |
cdc7bbd5 | 51 | use rustc_middle::ty::{self, DefIdTree, MainDefinition, ResolverOutputs}; |
ba9703b0 | 52 | use rustc_session::lint; |
dfeec247 | 53 | use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer}; |
dfeec247 | 54 | use rustc_session::Session; |
5869c6ff | 55 | use rustc_span::edition::Edition; |
136023e0 XL |
56 | use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext, Transparency}; |
57 | use rustc_span::source_map::{CachingSourceMapView, Spanned}; | |
f9f354fc | 58 | use rustc_span::symbol::{kw, sym, Ident, Symbol}; |
dfeec247 | 59 | use rustc_span::{Span, DUMMY_SP}; |
1a4d82fc | 60 | |
3dfed10e | 61 | use smallvec::{smallvec, SmallVec}; |
1a4d82fc | 62 | use std::cell::{Cell, RefCell}; |
8bb4bdeb | 63 | use std::collections::BTreeSet; |
6a06907d | 64 | use std::ops::ControlFlow; |
dfeec247 | 65 | use std::{cmp, fmt, iter, ptr}; |
3dfed10e | 66 | use tracing::debug; |
85aaf69f | 67 | |
dfeec247 | 68 | use diagnostics::{extend_span_to_previous_binding, find_span_of_binding_until_next_binding}; |
f035d41b | 69 | use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion}; |
74b04a01 | 70 | use imports::{Import, ImportKind, ImportResolver, NameResolution}; |
5869c6ff | 71 | use late::{ConstantItemKind, HasGenericParams, PathSource, Rib, RibKind::*}; |
29967ef6 | 72 | use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; |
c34b1796 | 73 | |
48663c56 XL |
74 | type Res = def::Res<NodeId>; |
75 | ||
dfeec247 XL |
76 | mod build_reduced_graph; |
77 | mod check_unused; | |
60c5eb7d | 78 | mod def_collector; |
54a0048b | 79 | mod diagnostics; |
dfeec247 | 80 | mod imports; |
416331ca | 81 | mod late; |
9e0c209e | 82 | mod macros; |
1a4d82fc | 83 | |
13cf67c4 XL |
84 | enum Weak { |
85 | Yes, | |
86 | No, | |
87 | } | |
88 | ||
416331ca XL |
89 | #[derive(Copy, Clone, PartialEq, Debug)] |
90 | pub enum Determinacy { | |
91 | Determined, | |
92 | Undetermined, | |
93 | } | |
94 | ||
95 | impl Determinacy { | |
96 | fn determined(determined: bool) -> Determinacy { | |
97 | if determined { Determinacy::Determined } else { Determinacy::Undetermined } | |
98 | } | |
99 | } | |
100 | ||
101 | /// A specific scope in which a name can be looked up. | |
102 | /// This enum is currently used only for early resolution (imports and macros), | |
103 | /// but not for late resolution yet. | |
104 | #[derive(Clone, Copy)] | |
105 | enum Scope<'a> { | |
136023e0 | 106 | DeriveHelpers(LocalExpnId), |
60c5eb7d | 107 | DeriveHelpersCompat, |
29967ef6 | 108 | MacroRules(MacroRulesScopeRef<'a>), |
416331ca | 109 | CrateRoot, |
cdc7bbd5 XL |
110 | // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK` |
111 | // lint if it should be reported. | |
112 | Module(Module<'a>, Option<NodeId>), | |
60c5eb7d | 113 | RegisteredAttrs, |
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)] |
416331ca XL |
144 | pub struct ParentScope<'a> { |
145 | module: Module<'a>, | |
136023e0 | 146 | expansion: LocalExpnId, |
29967ef6 | 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. | |
29967ef6 | 154 | pub 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 XL |
170 | #[derive(Eq)] |
171 | struct BindingError { | |
f9f354fc | 172 | name: Symbol, |
8bb4bdeb XL |
173 | origin: BTreeSet<Span>, |
174 | target: BTreeSet<Span>, | |
dfeec247 | 175 | could_be_path: bool, |
0731742a XL |
176 | } |
177 | ||
8bb4bdeb XL |
178 | impl PartialOrd for BindingError { |
179 | fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> { | |
180 | Some(self.cmp(other)) | |
181 | } | |
182 | } | |
183 | ||
184 | impl PartialEq for BindingError { | |
185 | fn eq(&self, other: &BindingError) -> bool { | |
186 | self.name == other.name | |
187 | } | |
188 | } | |
189 | ||
190 | impl Ord for BindingError { | |
191 | fn cmp(&self, other: &BindingError) -> cmp::Ordering { | |
192 | self.name.cmp(&other.name) | |
193 | } | |
194 | } | |
195 | ||
54a0048b | 196 | enum ResolutionError<'a> { |
9fa01778 | 197 | /// Error E0401: can't use type or const parameters from outer function. |
e74abb32 | 198 | GenericParamsFromOuterFunction(Res, HasGenericParams), |
9fa01778 XL |
199 | /// Error E0403: the name is already used for a type or const parameter in this generic |
200 | /// parameter list. | |
f9f354fc | 201 | NameAlreadyUsedInParameterList(Symbol, Span), |
9fa01778 | 202 | /// Error E0407: method is not a member of trait. |
f9f354fc | 203 | MethodNotMemberOfTrait(Symbol, &'a str), |
9fa01778 | 204 | /// Error E0437: type is not a member of trait. |
f9f354fc | 205 | TypeNotMemberOfTrait(Symbol, &'a str), |
9fa01778 | 206 | /// Error E0438: const is not a member of trait. |
f9f354fc | 207 | ConstNotMemberOfTrait(Symbol, &'a str), |
9fa01778 | 208 | /// Error E0408: variable `{}` is not bound in all patterns. |
8bb4bdeb | 209 | VariableNotBoundInPattern(&'a BindingError), |
9fa01778 | 210 | /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm. |
f9f354fc | 211 | VariableBoundWithDifferentMode(Symbol, Span), |
9fa01778 | 212 | /// Error E0415: identifier is bound more than once in this parameter list. |
3dfed10e | 213 | IdentifierBoundMoreThanOnceInParameterList(Symbol), |
9fa01778 | 214 | /// Error E0416: identifier is bound more than once in the same pattern. |
3dfed10e | 215 | IdentifierBoundMoreThanOnceInSamePattern(Symbol), |
9fa01778 | 216 | /// Error E0426: use of undeclared label. |
3dfed10e | 217 | UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> }, |
9fa01778 | 218 | /// Error E0429: `self` imports are only allowed within a `{ }` list. |
f9f354fc | 219 | SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span }, |
9fa01778 | 220 | /// Error E0430: `self` import can only appear once in the list. |
c1a9b12d | 221 | SelfImportCanOnlyAppearOnceInTheList, |
9fa01778 | 222 | /// Error E0431: `self` import can only appear in an import list with a non-empty prefix. |
c1a9b12d | 223 | SelfImportOnlyInImportListWithNonEmptyPrefix, |
9fa01778 | 224 | /// Error E0433: failed to resolve. |
532ac7d7 | 225 | FailedToResolve { label: String, suggestion: Option<Suggestion> }, |
9fa01778 | 226 | /// Error E0434: can't capture dynamic environment in a fn item. |
c1a9b12d | 227 | CannotCaptureDynamicEnvironmentInFnItem, |
9fa01778 | 228 | /// Error E0435: attempt to use a non-constant value in a constant. |
5869c6ff XL |
229 | AttemptToUseNonConstantValueInConstant( |
230 | Ident, | |
231 | /* suggestion */ &'static str, | |
232 | /* current */ &'static str, | |
233 | ), | |
9fa01778 | 234 | /// Error E0530: `X` bindings cannot shadow `Y`s. |
17df50a5 XL |
235 | BindingShadowsSomethingUnacceptable { |
236 | shadowing_binding_descr: &'static str, | |
237 | name: Symbol, | |
238 | participle: &'static str, | |
239 | article: &'static str, | |
240 | shadowed_binding_descr: &'static str, | |
241 | shadowed_binding_span: Span, | |
242 | }, | |
cdc7bbd5 | 243 | /// Error E0128: generic parameters with a default cannot use forward-declared identifiers. |
17df50a5 | 244 | ForwardDeclaredGenericParam, |
3dfed10e XL |
245 | /// ERROR E0770: the type of const parameters must not depend on other generic parameters. |
246 | ParamInTyOfConstParam(Symbol), | |
29967ef6 | 247 | /// generic parameters must not be used inside const evaluations. |
3dfed10e XL |
248 | /// |
249 | /// This error is only emitted when using `min_const_generics`. | |
1b1a35ee | 250 | ParamInNonTrivialAnonConst { name: Symbol, is_type: bool }, |
cdc7bbd5 | 251 | /// Error E0735: generic parameters with a default cannot use `Self` |
136023e0 | 252 | SelfInGenericParamDefault, |
f035d41b | 253 | /// Error E0767: use of unreachable label |
3dfed10e | 254 | UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> }, |
e74abb32 XL |
255 | } |
256 | ||
257 | enum VisResolutionError<'a> { | |
258 | Relative2018(Span, &'a ast::Path), | |
259 | AncestorOnly(Span), | |
260 | FailedToResolve(Span, String, Option<Suggestion>), | |
261 | ExpectedFound(Span, String, Res), | |
262 | Indeterminate(Span), | |
263 | ModuleOnly(Span), | |
9cc50fc6 SL |
264 | } |
265 | ||
f035d41b XL |
266 | /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path |
267 | /// segments' which don't have the rest of an AST or HIR `PathSegment`. | |
13cf67c4 XL |
268 | #[derive(Clone, Copy, Debug)] |
269 | pub struct Segment { | |
270 | ident: Ident, | |
271 | id: Option<NodeId>, | |
f035d41b XL |
272 | /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing |
273 | /// nonsensical suggestions. | |
274 | has_generic_args: bool, | |
13cf67c4 XL |
275 | } |
276 | ||
277 | impl Segment { | |
278 | fn from_path(path: &Path) -> Vec<Segment> { | |
279 | path.segments.iter().map(|s| s.into()).collect() | |
280 | } | |
281 | ||
282 | fn from_ident(ident: Ident) -> Segment { | |
f035d41b | 283 | Segment { ident, id: None, has_generic_args: false } |
13cf67c4 XL |
284 | } |
285 | ||
286 | fn names_to_string(segments: &[Segment]) -> String { | |
dfeec247 | 287 | names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>()) |
13cf67c4 XL |
288 | } |
289 | } | |
290 | ||
291 | impl<'a> From<&'a ast::PathSegment> for Segment { | |
292 | fn from(seg: &'a ast::PathSegment) -> Segment { | |
f035d41b | 293 | Segment { ident: seg.ident, id: Some(seg.id), has_generic_args: seg.args.is_some() } |
13cf67c4 XL |
294 | } |
295 | } | |
296 | ||
f035d41b XL |
297 | struct UsePlacementFinder { |
298 | target_module: NodeId, | |
3b2f2976 XL |
299 | span: Option<Span>, |
300 | found_use: bool, | |
301 | } | |
302 | ||
f035d41b XL |
303 | impl UsePlacementFinder { |
304 | fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, bool) { | |
305 | let mut finder = UsePlacementFinder { target_module, span: None, found_use: false }; | |
6a06907d XL |
306 | if let ControlFlow::Continue(..) = finder.check_mod(&krate.items, CRATE_NODE_ID) { |
307 | visit::walk_crate(&mut finder, krate); | |
308 | } | |
f035d41b | 309 | (finder.span, finder.found_use) |
ff7c6d11 | 310 | } |
ff7c6d11 | 311 | |
6a06907d | 312 | fn check_mod(&mut self, items: &[P<ast::Item>], node_id: NodeId) -> ControlFlow<()> { |
3b2f2976 | 313 | if self.span.is_some() { |
6a06907d | 314 | return ControlFlow::Break(()); |
3b2f2976 | 315 | } |
f035d41b | 316 | if node_id != self.target_module { |
6a06907d | 317 | return ControlFlow::Continue(()); |
3b2f2976 XL |
318 | } |
319 | // find a use statement | |
6a06907d | 320 | for item in items { |
e74abb32 | 321 | match item.kind { |
3b2f2976 XL |
322 | ItemKind::Use(..) => { |
323 | // don't suggest placing a use before the prelude | |
324 | // import or other generated ones | |
e1599b0c | 325 | if !item.span.from_expansion() { |
0531ce1d | 326 | self.span = Some(item.span.shrink_to_lo()); |
3b2f2976 | 327 | self.found_use = true; |
6a06907d | 328 | return ControlFlow::Break(()); |
3b2f2976 | 329 | } |
dfeec247 | 330 | } |
3b2f2976 XL |
331 | // don't place use before extern crate |
332 | ItemKind::ExternCrate(_) => {} | |
333 | // but place them before the first other item | |
dfeec247 | 334 | _ => { |
29967ef6 XL |
335 | if self.span.map_or(true, |span| item.span < span) |
336 | && !item.span.from_expansion() | |
337 | { | |
136023e0 | 338 | self.span = Some(item.span.shrink_to_lo()); |
29967ef6 | 339 | // don't insert between attributes and an item |
136023e0 XL |
340 | // find the first attribute on the item |
341 | // FIXME: This is broken for active attributes. | |
342 | for attr in &item.attrs { | |
343 | if !attr.span.is_dummy() | |
344 | && self.span.map_or(true, |span| attr.span < span) | |
345 | { | |
346 | self.span = Some(attr.span.shrink_to_lo()); | |
3b2f2976 XL |
347 | } |
348 | } | |
349 | } | |
dfeec247 | 350 | } |
3b2f2976 XL |
351 | } |
352 | } | |
6a06907d XL |
353 | ControlFlow::Continue(()) |
354 | } | |
355 | } | |
356 | ||
357 | impl<'tcx> Visitor<'tcx> for UsePlacementFinder { | |
358 | fn visit_item(&mut self, item: &'tcx ast::Item) { | |
359 | if let ItemKind::Mod(_, ModKind::Loaded(items, ..)) = &item.kind { | |
360 | if let ControlFlow::Break(..) = self.check_mod(items, item.id) { | |
361 | return; | |
362 | } | |
363 | } | |
364 | visit::walk_item(self, item); | |
3b2f2976 XL |
365 | } |
366 | } | |
367 | ||
0531ce1d XL |
368 | /// An intermediate resolution result. |
369 | /// | |
48663c56 XL |
370 | /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that |
371 | /// items are visible in their whole block, while `Res`es only from the place they are defined | |
0531ce1d | 372 | /// forward. |
416331ca | 373 | #[derive(Debug)] |
54a0048b SL |
374 | enum LexicalScopeBinding<'a> { |
375 | Item(&'a NameBinding<'a>), | |
48663c56 | 376 | Res(Res), |
54a0048b SL |
377 | } |
378 | ||
379 | impl<'a> LexicalScopeBinding<'a> { | |
48663c56 | 380 | fn res(self) -> Res { |
32a655c1 | 381 | match self { |
48663c56 XL |
382 | LexicalScopeBinding::Item(binding) => binding.res(), |
383 | LexicalScopeBinding::Res(res) => res, | |
32a655c1 SL |
384 | } |
385 | } | |
476ff2be SL |
386 | } |
387 | ||
b7449926 | 388 | #[derive(Copy, Clone, Debug)] |
13cf67c4 | 389 | enum ModuleOrUniformRoot<'a> { |
b7449926 XL |
390 | /// Regular module. |
391 | Module(Module<'a>), | |
392 | ||
13cf67c4 XL |
393 | /// Virtual module that denotes resolution in crate root with fallback to extern prelude. |
394 | CrateRootAndExternPrelude, | |
395 | ||
396 | /// Virtual module that denotes resolution in extern prelude. | |
0731742a | 397 | /// Used for paths starting with `::` on 2018 edition. |
13cf67c4 XL |
398 | ExternPrelude, |
399 | ||
400 | /// Virtual module that denotes resolution in current scope. | |
401 | /// Used only for resolving single-segment imports. The reason it exists is that import paths | |
402 | /// are always split into two parts, the first of which should be some kind of module. | |
403 | CurrentScope, | |
404 | } | |
405 | ||
69743fb6 XL |
406 | impl ModuleOrUniformRoot<'_> { |
407 | fn same_def(lhs: Self, rhs: Self) -> bool { | |
408 | match (lhs, rhs) { | |
dfeec247 XL |
409 | (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => { |
410 | lhs.def_id() == rhs.def_id() | |
411 | } | |
412 | ( | |
413 | ModuleOrUniformRoot::CrateRootAndExternPrelude, | |
414 | ModuleOrUniformRoot::CrateRootAndExternPrelude, | |
415 | ) | |
416 | | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) | |
417 | | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true, | |
13cf67c4 XL |
418 | _ => false, |
419 | } | |
420 | } | |
b7449926 XL |
421 | } |
422 | ||
2c00a5a8 | 423 | #[derive(Clone, Debug)] |
476ff2be | 424 | enum PathResult<'a> { |
b7449926 | 425 | Module(ModuleOrUniformRoot<'a>), |
48663c56 | 426 | NonModule(PartialRes), |
476ff2be | 427 | Indeterminate, |
532ac7d7 XL |
428 | Failed { |
429 | span: Span, | |
430 | label: String, | |
431 | suggestion: Option<Suggestion>, | |
432 | is_error_from_last_segment: bool, | |
433 | }, | |
476ff2be SL |
434 | } |
435 | ||
fc512014 | 436 | #[derive(Debug)] |
9e0c209e | 437 | enum ModuleKind { |
9fa01778 | 438 | /// An anonymous module; e.g., just a block. |
0531ce1d XL |
439 | /// |
440 | /// ``` | |
441 | /// fn main() { | |
442 | /// fn f() {} // (1) | |
443 | /// { // This is an anonymous module | |
444 | /// f(); // This resolves to (2) as we are inside the block. | |
445 | /// fn f() {} // (2) | |
446 | /// } | |
447 | /// f(); // Resolves to (1) | |
448 | /// } | |
449 | /// ``` | |
9e0c209e | 450 | Block(NodeId), |
0531ce1d XL |
451 | /// Any module with a name. |
452 | /// | |
453 | /// This could be: | |
454 | /// | |
5869c6ff XL |
455 | /// * A normal module – either `mod from_file;` or `mod from_block { }` – |
456 | /// or the crate root (which is conceptually a top-level module). | |
457 | /// Note that the crate root's [name][Self::name] will be [`kw::Empty`]. | |
0531ce1d XL |
458 | /// * A trait or an enum (it implicitly contains associated types, methods and variant |
459 | /// constructors). | |
f9f354fc | 460 | Def(DefKind, DefId, Symbol), |
48663c56 XL |
461 | } |
462 | ||
463 | impl ModuleKind { | |
464 | /// Get name of the module. | |
f9f354fc | 465 | pub fn name(&self) -> Option<Symbol> { |
48663c56 XL |
466 | match self { |
467 | ModuleKind::Block(..) => None, | |
468 | ModuleKind::Def(.., name) => Some(*name), | |
469 | } | |
470 | } | |
1a4d82fc JJ |
471 | } |
472 | ||
e74abb32 XL |
473 | /// A key that identifies a binding in a given `Module`. |
474 | /// | |
475 | /// Multiple bindings in the same module can have the same key (in a valid | |
476 | /// program) if all but one of them come from glob imports. | |
3dfed10e | 477 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] |
e74abb32 | 478 | struct BindingKey { |
ba9703b0 | 479 | /// The identifier for the binding, aways the `normalize_to_macros_2_0` version of the |
e74abb32 XL |
480 | /// identifier. |
481 | ident: Ident, | |
482 | ns: Namespace, | |
483 | /// 0 if ident is not `_`, otherwise a value that's unique to the specific | |
484 | /// `_` in the expanded AST that introduced this binding. | |
485 | disambiguator: u32, | |
486 | } | |
487 | ||
488 | type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>; | |
e1599b0c | 489 | |
1a4d82fc | 490 | /// One node in the tree of modules. |
5869c6ff XL |
491 | /// |
492 | /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these: | |
493 | /// | |
494 | /// * `mod` | |
495 | /// * crate root (aka, top-level anonymous module) | |
496 | /// * `enum` | |
497 | /// * `trait` | |
498 | /// * curly-braced block with statements | |
499 | /// | |
500 | /// You can use [`ModuleData::kind`] to determine the kind of module this is. | |
32a655c1 | 501 | pub struct ModuleData<'a> { |
5869c6ff | 502 | /// The direct parent module (it may not be a `mod`, however). |
9e0c209e | 503 | parent: Option<Module<'a>>, |
5869c6ff | 504 | /// What kind of module this is, because this may not be a `mod`. |
9e0c209e SL |
505 | kind: ModuleKind, |
506 | ||
5869c6ff XL |
507 | /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module). |
508 | /// This may be the crate root. | |
509 | nearest_parent_mod: DefId, | |
1a4d82fc | 510 | |
5869c6ff XL |
511 | /// Mapping between names and their (possibly in-progress) resolutions in this module. |
512 | /// Resolutions in modules from other crates are not populated until accessed. | |
e1599b0c | 513 | lazy_resolutions: Resolutions<'a>, |
5869c6ff | 514 | /// True if this is a module from other crate that needs to be populated on access. |
e1599b0c | 515 | populate_on_access: Cell<bool>, |
1a4d82fc | 516 | |
5869c6ff | 517 | /// Macro invocations that can expand into items in this module. |
136023e0 | 518 | unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>, |
1a4d82fc | 519 | |
5869c6ff | 520 | /// Whether `#[no_implicit_prelude]` is active. |
9e0c209e | 521 | no_implicit_prelude: bool, |
1a4d82fc | 522 | |
74b04a01 XL |
523 | glob_importers: RefCell<Vec<&'a Import<'a>>>, |
524 | globs: RefCell<Vec<&'a Import<'a>>>, | |
e9174d1e | 525 | |
5869c6ff | 526 | /// Used to memoize the traits in this module for faster searches through all traits in scope. |
32a655c1 | 527 | traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>, |
e9174d1e | 528 | |
7cac9316 XL |
529 | /// Span of the module itself. Used for error reporting. |
530 | span: Span, | |
531 | ||
416331ca | 532 | expansion: ExpnId, |
1a4d82fc JJ |
533 | } |
534 | ||
3b2f2976 | 535 | type Module<'a> = &'a ModuleData<'a>; |
9cc50fc6 | 536 | |
32a655c1 | 537 | impl<'a> ModuleData<'a> { |
dfeec247 XL |
538 | fn new( |
539 | parent: Option<Module<'a>>, | |
540 | kind: ModuleKind, | |
5869c6ff | 541 | nearest_parent_mod: DefId, |
dfeec247 XL |
542 | expansion: ExpnId, |
543 | span: Span, | |
544 | ) -> Self { | |
32a655c1 | 545 | ModuleData { |
3b2f2976 XL |
546 | parent, |
547 | kind, | |
5869c6ff | 548 | nearest_parent_mod, |
e1599b0c | 549 | lazy_resolutions: Default::default(), |
5869c6ff | 550 | populate_on_access: Cell::new(!nearest_parent_mod.is_local()), |
e1599b0c | 551 | unexpanded_invocations: Default::default(), |
9e0c209e | 552 | no_implicit_prelude: false, |
54a0048b | 553 | glob_importers: RefCell::new(Vec::new()), |
2c00a5a8 | 554 | globs: RefCell::new(Vec::new()), |
54a0048b | 555 | traits: RefCell::new(None), |
3b2f2976 XL |
556 | span, |
557 | expansion, | |
7453a54e SL |
558 | } |
559 | } | |
560 | ||
e1599b0c | 561 | fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F) |
dfeec247 XL |
562 | where |
563 | R: AsMut<Resolver<'a>>, | |
564 | F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>), | |
e1599b0c | 565 | { |
e74abb32 | 566 | for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() { |
f9f354fc XL |
567 | if let Some(binding) = name_resolution.borrow().binding { |
568 | f(resolver, key.ident, key.ns, binding); | |
569 | } | |
3b2f2976 XL |
570 | } |
571 | } | |
572 | ||
3dfed10e XL |
573 | /// This modifies `self` in place. The traits will be stored in `self.traits`. |
574 | fn ensure_traits<R>(&'a self, resolver: &mut R) | |
575 | where | |
576 | R: AsMut<Resolver<'a>>, | |
577 | { | |
578 | let mut traits = self.traits.borrow_mut(); | |
579 | if traits.is_none() { | |
580 | let mut collected_traits = Vec::new(); | |
581 | self.for_each_child(resolver, |_, name, ns, binding| { | |
582 | if ns != TypeNS { | |
583 | return; | |
584 | } | |
1b1a35ee XL |
585 | if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() { |
586 | collected_traits.push((name, binding)) | |
3dfed10e XL |
587 | } |
588 | }); | |
589 | *traits = Some(collected_traits.into_boxed_slice()); | |
590 | } | |
591 | } | |
592 | ||
48663c56 | 593 | fn res(&self) -> Option<Res> { |
9e0c209e | 594 | match self.kind { |
48663c56 XL |
595 | ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)), |
596 | _ => None, | |
597 | } | |
598 | } | |
599 | ||
92a42be0 | 600 | fn def_id(&self) -> Option<DefId> { |
48663c56 XL |
601 | match self.kind { |
602 | ModuleKind::Def(_, def_id, _) => Some(def_id), | |
603 | _ => None, | |
604 | } | |
92a42be0 SL |
605 | } |
606 | ||
a7813a04 | 607 | // `self` resolves to the first module ancestor that `is_normal`. |
7453a54e | 608 | fn is_normal(&self) -> bool { |
29967ef6 | 609 | matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _)) |
1a4d82fc JJ |
610 | } |
611 | ||
7453a54e | 612 | fn is_trait(&self) -> bool { |
29967ef6 | 613 | matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _)) |
e9174d1e | 614 | } |
c30ab7b3 | 615 | |
8bb4bdeb | 616 | fn nearest_item_scope(&'a self) -> Module<'a> { |
e1599b0c | 617 | match self.kind { |
ba9703b0 | 618 | ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => { |
dfeec247 XL |
619 | self.parent.expect("enum or trait module without a parent") |
620 | } | |
e1599b0c XL |
621 | _ => self, |
622 | } | |
8bb4bdeb | 623 | } |
4462d4a0 XL |
624 | |
625 | fn is_ancestor_of(&self, mut other: &Self) -> bool { | |
626 | while !ptr::eq(self, other) { | |
627 | if let Some(parent) = other.parent { | |
628 | other = parent; | |
629 | } else { | |
630 | return false; | |
631 | } | |
632 | } | |
633 | true | |
634 | } | |
1a4d82fc JJ |
635 | } |
636 | ||
32a655c1 | 637 | impl<'a> fmt::Debug for ModuleData<'a> { |
9fa01778 | 638 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
48663c56 | 639 | write!(f, "{:?}", self.res()) |
1a4d82fc JJ |
640 | } |
641 | } | |
642 | ||
83c7162d | 643 | /// Records a possibly-private value, type, or module definition. |
54a0048b | 644 | #[derive(Clone, Debug)] |
7453a54e | 645 | pub struct NameBinding<'a> { |
7453a54e | 646 | kind: NameBindingKind<'a>, |
0731742a | 647 | ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>, |
136023e0 | 648 | expansion: LocalExpnId, |
a7813a04 XL |
649 | span: Span, |
650 | vis: ty::Visibility, | |
1a4d82fc JJ |
651 | } |
652 | ||
5bcae85e | 653 | pub trait ToNameBinding<'a> { |
32a655c1 | 654 | fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>; |
5bcae85e SL |
655 | } |
656 | ||
32a655c1 SL |
657 | impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> { |
658 | fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { | |
5bcae85e SL |
659 | self |
660 | } | |
661 | } | |
662 | ||
54a0048b | 663 | #[derive(Clone, Debug)] |
7453a54e | 664 | enum NameBindingKind<'a> { |
48663c56 | 665 | Res(Res, /* is_macro_export */ bool), |
9cc50fc6 | 666 | Module(Module<'a>), |
74b04a01 | 667 | Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> }, |
1a4d82fc JJ |
668 | } |
669 | ||
9fa01778 XL |
670 | impl<'a> NameBindingKind<'a> { |
671 | /// Is this a name binding of a import? | |
672 | fn is_import(&self) -> bool { | |
29967ef6 | 673 | matches!(*self, NameBindingKind::Import { .. }) |
9fa01778 XL |
674 | } |
675 | } | |
676 | ||
dfeec247 XL |
677 | struct PrivacyError<'a> { |
678 | ident: Ident, | |
679 | binding: &'a NameBinding<'a>, | |
680 | dedup_span: Span, | |
681 | } | |
54a0048b | 682 | |
3b2f2976 XL |
683 | struct UseError<'a> { |
684 | err: DiagnosticBuilder<'a>, | |
f035d41b | 685 | /// Candidates which user could `use` to access the missing type. |
3b2f2976 | 686 | candidates: Vec<ImportSuggestion>, |
f035d41b | 687 | /// The `DefId` of the module to place the use-statements in. |
f9f354fc | 688 | def_id: DefId, |
f035d41b XL |
689 | /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`). |
690 | instead: bool, | |
691 | /// Extra free-form suggestion. | |
dfeec247 | 692 | suggestion: Option<(Span, &'static str, String, Applicability)>, |
3b2f2976 XL |
693 | } |
694 | ||
13cf67c4 XL |
695 | #[derive(Clone, Copy, PartialEq, Debug)] |
696 | enum AmbiguityKind { | |
697 | Import, | |
13cf67c4 XL |
698 | BuiltinAttr, |
699 | DeriveHelper, | |
ba9703b0 | 700 | MacroRulesVsModularized, |
13cf67c4 XL |
701 | GlobVsOuter, |
702 | GlobVsGlob, | |
703 | GlobVsExpanded, | |
704 | MoreExpandedVsOuter, | |
705 | } | |
706 | ||
707 | impl AmbiguityKind { | |
708 | fn descr(self) -> &'static str { | |
709 | match self { | |
dfeec247 XL |
710 | AmbiguityKind::Import => "name vs any other name during import resolution", |
711 | AmbiguityKind::BuiltinAttr => "built-in attribute vs any other name", | |
712 | AmbiguityKind::DeriveHelper => "derive helper attribute vs any other name", | |
ba9703b0 XL |
713 | AmbiguityKind::MacroRulesVsModularized => { |
714 | "`macro_rules` vs non-`macro_rules` from other module" | |
715 | } | |
dfeec247 XL |
716 | AmbiguityKind::GlobVsOuter => { |
717 | "glob import vs any other name from outer scope during import/macro resolution" | |
718 | } | |
719 | AmbiguityKind::GlobVsGlob => "glob import vs glob import in the same module", | |
720 | AmbiguityKind::GlobVsExpanded => { | |
13cf67c4 | 721 | "glob import vs macro-expanded name in the same \ |
dfeec247 XL |
722 | module during import/macro resolution" |
723 | } | |
724 | AmbiguityKind::MoreExpandedVsOuter => { | |
13cf67c4 | 725 | "macro-expanded name vs less macro-expanded name \ |
dfeec247 XL |
726 | from outer scope during import/macro resolution" |
727 | } | |
13cf67c4 XL |
728 | } |
729 | } | |
730 | } | |
731 | ||
732 | /// Miscellaneous bits of metadata for better ambiguity error reporting. | |
733 | #[derive(Clone, Copy, PartialEq)] | |
734 | enum AmbiguityErrorMisc { | |
735 | SuggestCrate, | |
736 | SuggestSelf, | |
737 | FromPrelude, | |
738 | None, | |
739 | } | |
740 | ||
9e0c209e | 741 | struct AmbiguityError<'a> { |
13cf67c4 | 742 | kind: AmbiguityKind, |
b7449926 | 743 | ident: Ident, |
9e0c209e SL |
744 | b1: &'a NameBinding<'a>, |
745 | b2: &'a NameBinding<'a>, | |
13cf67c4 XL |
746 | misc1: AmbiguityErrorMisc, |
747 | misc2: AmbiguityErrorMisc, | |
9e0c209e SL |
748 | } |
749 | ||
7453a54e | 750 | impl<'a> NameBinding<'a> { |
476ff2be | 751 | fn module(&self) -> Option<Module<'a>> { |
7453a54e | 752 | match self.kind { |
476ff2be | 753 | NameBindingKind::Module(module) => Some(module), |
7453a54e | 754 | NameBindingKind::Import { binding, .. } => binding.module(), |
476ff2be | 755 | _ => None, |
1a4d82fc JJ |
756 | } |
757 | } | |
758 | ||
48663c56 | 759 | fn res(&self) -> Res { |
7453a54e | 760 | match self.kind { |
48663c56 XL |
761 | NameBindingKind::Res(res, _) => res, |
762 | NameBindingKind::Module(module) => module.res().unwrap(), | |
763 | NameBindingKind::Import { binding, .. } => binding.res(), | |
1a4d82fc JJ |
764 | } |
765 | } | |
1a4d82fc | 766 | |
0731742a | 767 | fn is_ambiguity(&self) -> bool { |
dfeec247 XL |
768 | self.ambiguity.is_some() |
769 | || match self.kind { | |
770 | NameBindingKind::Import { binding, .. } => binding.is_ambiguity(), | |
771 | _ => false, | |
772 | } | |
476ff2be SL |
773 | } |
774 | ||
f035d41b XL |
775 | fn is_possibly_imported_variant(&self) -> bool { |
776 | match self.kind { | |
777 | NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(), | |
5869c6ff | 778 | NameBindingKind::Res( |
ba9703b0 XL |
779 | Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _), |
780 | _, | |
6a06907d XL |
781 | ) => true, |
782 | NameBindingKind::Res(..) | NameBindingKind::Module(..) => false, | |
783 | } | |
92a42be0 SL |
784 | } |
785 | ||
7453a54e | 786 | fn is_extern_crate(&self) -> bool { |
476ff2be SL |
787 | match self.kind { |
788 | NameBindingKind::Import { | |
74b04a01 | 789 | import: &Import { kind: ImportKind::ExternCrate { .. }, .. }, |
dfeec247 | 790 | .. |
476ff2be | 791 | } => true, |
dfeec247 XL |
792 | NameBindingKind::Module(&ModuleData { |
793 | kind: ModuleKind::Def(DefKind::Mod, def_id, _), | |
794 | .. | |
795 | }) => def_id.index == CRATE_DEF_INDEX, | |
476ff2be SL |
796 | _ => false, |
797 | } | |
92a42be0 | 798 | } |
92a42be0 | 799 | |
7453a54e | 800 | fn is_import(&self) -> bool { |
29967ef6 | 801 | matches!(self.kind, NameBindingKind::Import { .. }) |
c34b1796 | 802 | } |
a7813a04 XL |
803 | |
804 | fn is_glob_import(&self) -> bool { | |
805 | match self.kind { | |
74b04a01 | 806 | NameBindingKind::Import { import, .. } => import.is_glob(), |
a7813a04 XL |
807 | _ => false, |
808 | } | |
809 | } | |
810 | ||
811 | fn is_importable(&self) -> bool { | |
29967ef6 XL |
812 | !matches!( |
813 | self.res(), | |
814 | Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) | |
815 | ) | |
a7813a04 | 816 | } |
7cac9316 XL |
817 | |
818 | fn is_macro_def(&self) -> bool { | |
29967ef6 | 819 | matches!(self.kind, NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _)) |
7cac9316 XL |
820 | } |
821 | ||
b7449926 | 822 | fn macro_kind(&self) -> Option<MacroKind> { |
416331ca | 823 | self.res().macro_kind() |
13cf67c4 XL |
824 | } |
825 | ||
b7449926 XL |
826 | // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding` |
827 | // at some expansion round `max(invoc, binding)` when they both emerged from macros. | |
828 | // Then this function returns `true` if `self` may emerge from a macro *after* that | |
829 | // in some later round and screw up our previously found resolution. | |
830 | // See more detailed explanation in | |
831 | // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049 | |
136023e0 XL |
832 | fn may_appear_after( |
833 | &self, | |
834 | invoc_parent_expansion: LocalExpnId, | |
835 | binding: &NameBinding<'_>, | |
836 | ) -> bool { | |
b7449926 XL |
837 | // self > max(invoc, binding) => !(self <= invoc || self <= binding) |
838 | // Expansions are partially ordered, so "may appear after" is an inversion of | |
839 | // "certainly appears before or simultaneously" and includes unordered cases. | |
840 | let self_parent_expansion = self.expansion; | |
841 | let other_parent_expansion = binding.expansion; | |
842 | let certainly_before_other_or_simultaneously = | |
843 | other_parent_expansion.is_descendant_of(self_parent_expansion); | |
844 | let certainly_before_invoc_or_simultaneously = | |
845 | invoc_parent_expansion.is_descendant_of(self_parent_expansion); | |
846 | !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously) | |
847 | } | |
1a4d82fc JJ |
848 | } |
849 | ||
0731742a | 850 | #[derive(Debug, Default, Clone)] |
0bf4aa26 XL |
851 | pub struct ExternPreludeEntry<'a> { |
852 | extern_crate_item: Option<&'a NameBinding<'a>>, | |
853 | pub introduced_by_item: bool, | |
854 | } | |
855 | ||
1b1a35ee XL |
856 | /// Used for better errors for E0773 |
857 | enum BuiltinMacroState { | |
5869c6ff | 858 | NotYetSeen(SyntaxExtensionKind), |
1b1a35ee XL |
859 | AlreadySeen(Span), |
860 | } | |
861 | ||
cdc7bbd5 XL |
862 | struct DeriveData { |
863 | resolutions: DeriveResolutions, | |
864 | helper_attrs: Vec<(usize, Ident)>, | |
865 | has_derive_copy: bool, | |
866 | } | |
867 | ||
1a4d82fc | 868 | /// The main resolver class. |
0531ce1d XL |
869 | /// |
870 | /// This is the visitor that walks the whole crate. | |
0731742a | 871 | pub struct Resolver<'a> { |
1a4d82fc JJ |
872 | session: &'a Session, |
873 | ||
e74abb32 | 874 | definitions: Definitions, |
1a4d82fc | 875 | |
e74abb32 | 876 | graph_root: Module<'a>, |
1a4d82fc | 877 | |
3157f602 | 878 | prelude: Option<Module<'a>>, |
e74abb32 | 879 | extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>, |
3157f602 | 880 | |
9fa01778 | 881 | /// N.B., this is used only for better diagnostics, not name resolution itself. |
7cac9316 | 882 | has_self: FxHashSet<DefId>, |
1a4d82fc | 883 | |
83c7162d XL |
884 | /// Names of fields of an item `DefId` accessible with dot syntax. |
885 | /// Used for hints during error reporting. | |
f9f354fc | 886 | field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>, |
1a4d82fc | 887 | |
83c7162d | 888 | /// All imports known to succeed or fail. |
74b04a01 | 889 | determined_imports: Vec<&'a Import<'a>>, |
9e0c209e | 890 | |
83c7162d | 891 | /// All non-determined imports. |
74b04a01 | 892 | indeterminate_imports: Vec<&'a Import<'a>>, |
1a4d82fc | 893 | |
0731742a XL |
894 | /// FIXME: Refactor things so that these fields are passed through arguments and not resolver. |
895 | /// We are resolving a last import segment during import validation. | |
13cf67c4 | 896 | last_import_segment: bool, |
0731742a XL |
897 | /// This binding should be ignored during in-module resolution, so that we don't get |
898 | /// "self-confirming" import resolutions during import validation. | |
f035d41b | 899 | unusable_binding: Option<&'a NameBinding<'a>>, |
13cf67c4 | 900 | |
cdc7bbd5 XL |
901 | // Spans for local variables found during pattern resolution. |
902 | // Used for suggestions during error reporting. | |
903 | pat_span_map: NodeMap<Span>, | |
904 | ||
48663c56 XL |
905 | /// Resolutions for nodes that have a single resolution. |
906 | partial_res_map: NodeMap<PartialRes>, | |
907 | /// Resolutions for import nodes, which have multiple resolutions in different namespaces. | |
908 | import_res_map: NodeMap<PerNS<Option<Res>>>, | |
909 | /// Resolutions for labels (node IDs of their corresponding blocks or loops). | |
910 | label_res_map: NodeMap<NodeId>, | |
911 | ||
e74abb32 | 912 | /// `CrateNum` resolutions of `extern crate` items. |
f9f354fc | 913 | extern_crate_map: FxHashMap<LocalDefId, CrateNum>, |
f035d41b | 914 | export_map: ExportMap<LocalDefId>, |
17df50a5 | 915 | trait_map: Option<NodeMap<Vec<TraitCandidate>>>, |
a7813a04 | 916 | |
83c7162d XL |
917 | /// A map from nodes to anonymous modules. |
918 | /// Anonymous modules are pseudo-modules that are implicitly created around items | |
919 | /// contained within blocks. | |
920 | /// | |
921 | /// For example, if we have this: | |
922 | /// | |
923 | /// fn f() { | |
924 | /// fn g() { | |
925 | /// ... | |
926 | /// } | |
927 | /// } | |
928 | /// | |
929 | /// There will be an anonymous module created around `g` with the ID of the | |
930 | /// entry block for `f`. | |
32a655c1 | 931 | block_map: NodeMap<Module<'a>>, |
e1599b0c XL |
932 | /// A fake module that contains no definition and no prelude. Used so that |
933 | /// some AST passes can generate identifiers that only resolve to local or | |
934 | /// language items. | |
935 | empty_module: Module<'a>, | |
ba9703b0 | 936 | module_map: FxHashMap<LocalDefId, Module<'a>>, |
e74abb32 | 937 | extern_module_map: FxHashMap<DefId, Module<'a>>, |
4462d4a0 | 938 | binding_parent_modules: FxHashMap<PtrKey<'a, NameBinding<'a>>, Module<'a>>, |
e74abb32 | 939 | underscore_disambiguator: u32, |
1a4d82fc | 940 | |
9fa01778 | 941 | /// Maps glob imports to the names of items actually imported. |
f9f354fc | 942 | glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>, |
29967ef6 XL |
943 | /// Visibilities in "lowered" form, for all entities that have them. |
944 | visibilities: FxHashMap<LocalDefId, ty::Visibility>, | |
476ff2be | 945 | used_imports: FxHashSet<(NodeId, Namespace)>, |
f9f354fc XL |
946 | maybe_unused_trait_imports: FxHashSet<LocalDefId>, |
947 | maybe_unused_extern_crates: Vec<(LocalDefId, Span)>, | |
e9174d1e | 948 | |
9fa01778 | 949 | /// Privacy errors are delayed until the end in order to deduplicate them. |
54a0048b | 950 | privacy_errors: Vec<PrivacyError<'a>>, |
9fa01778 | 951 | /// Ambiguity errors are delayed for deduplication. |
9e0c209e | 952 | ambiguity_errors: Vec<AmbiguityError<'a>>, |
9fa01778 | 953 | /// `use` injections are delayed for better placement and deduplication. |
3b2f2976 | 954 | use_injections: Vec<UseError<'a>>, |
9fa01778 | 955 | /// Crate-local macro expanded `macro_export` referred to by a module-relative path. |
b7449926 | 956 | macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>, |
9cc50fc6 SL |
957 | |
958 | arenas: &'a ResolverArenas<'a>, | |
9e0c209e | 959 | dummy_binding: &'a NameBinding<'a>, |
9e0c209e | 960 | |
e74abb32 | 961 | crate_loader: CrateLoader<'a>, |
7cac9316 | 962 | macro_names: FxHashSet<Ident>, |
1b1a35ee | 963 | builtin_macros: FxHashMap<Symbol, BuiltinMacroState>, |
60c5eb7d XL |
964 | registered_attrs: FxHashSet<Ident>, |
965 | registered_tools: FxHashSet<Ident>, | |
f9f354fc XL |
966 | macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>, |
967 | all_macros: FxHashMap<Symbol, Res>, | |
0531ce1d | 968 | macro_map: FxHashMap<DefId, Lrc<SyntaxExtension>>, |
416331ca XL |
969 | dummy_ext_bang: Lrc<SyntaxExtension>, |
970 | dummy_ext_derive: Lrc<SyntaxExtension>, | |
dc9dc135 | 971 | non_macro_attrs: [Lrc<SyntaxExtension>; 2], |
f9f354fc | 972 | local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>, |
136023e0 | 973 | ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>, |
f9f354fc XL |
974 | unused_macros: FxHashMap<LocalDefId, (NodeId, Span)>, |
975 | proc_macro_stubs: FxHashSet<LocalDefId>, | |
e1599b0c | 976 | /// Traces collected during macro resolution and validated when it's complete. |
dfeec247 XL |
977 | single_segment_macro_resolutions: |
978 | Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>, | |
979 | multi_segment_macro_resolutions: | |
980 | Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>, | |
e1599b0c | 981 | builtin_attrs: Vec<(Ident, ParentScope<'a>)>, |
60c5eb7d | 982 | /// `derive(Copy)` marks items they are applied to so they are treated specially later. |
416331ca XL |
983 | /// Derive macros cannot modify the item themselves and have to store the markers in the global |
984 | /// context, so they attach the markers to derive container IDs using this resolver table. | |
136023e0 | 985 | containers_deriving_copy: FxHashSet<LocalExpnId>, |
e1599b0c XL |
986 | /// Parent scopes in which the macros were invoked. |
987 | /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere. | |
136023e0 | 988 | invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>, |
ba9703b0 | 989 | /// `macro_rules` scopes *produced* by expanding the macro invocations, |
e1599b0c | 990 | /// include all the `macro_rules` items and other invocations generated by them. |
136023e0 | 991 | output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>, |
60c5eb7d | 992 | /// Helper attributes that are in scope for the given expansion. |
136023e0 | 993 | helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>, |
cdc7bbd5 XL |
994 | /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute |
995 | /// with the given `ExpnId`. | |
136023e0 | 996 | derive_data: FxHashMap<LocalExpnId, DeriveData>, |
476ff2be | 997 | |
83c7162d | 998 | /// Avoid duplicated errors for "name already defined". |
f9f354fc | 999 | name_already_seen: FxHashMap<Symbol, Span>, |
32a655c1 | 1000 | |
74b04a01 | 1001 | potentially_unused_imports: Vec<&'a Import<'a>>, |
8bb4bdeb | 1002 | |
9fa01778 | 1003 | /// Table for mapping struct IDs into struct constructor IDs, |
83c7162d | 1004 | /// it's not used during normal resolution, only for better error reporting. |
1b1a35ee XL |
1005 | /// Also includes of list of each fields visibility |
1006 | struct_constructors: DefIdMap<(Res, ty::Visibility, Vec<ty::Visibility>)>, | |
3b2f2976 | 1007 | |
416331ca | 1008 | /// Features enabled for this crate. |
f9f354fc | 1009 | active_features: FxHashSet<Symbol>, |
e1599b0c | 1010 | |
dfeec247 | 1011 | lint_buffer: LintBuffer, |
60c5eb7d XL |
1012 | |
1013 | next_node_id: NodeId, | |
f035d41b XL |
1014 | |
1015 | def_id_to_span: IndexVec<LocalDefId, Span>, | |
1016 | ||
1017 | node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>, | |
1018 | def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>, | |
1019 | ||
1020 | /// Indices of unnamed struct or variant fields with unresolved attributes. | |
1021 | placeholder_field_indices: FxHashMap<NodeId, usize>, | |
1022 | /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId` | |
6a06907d XL |
1023 | /// we know what parent node that fragment should be attached to thanks to this table, |
1024 | /// and how the `impl Trait` fragments were introduced. | |
136023e0 | 1025 | invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>, |
f035d41b XL |
1026 | |
1027 | next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>, | |
29967ef6 XL |
1028 | /// Some way to know that we are in a *trait* impl in `visit_assoc_item`. |
1029 | /// FIXME: Replace with a more general AST map (together with some other fields). | |
1030 | trait_impl_items: FxHashSet<LocalDefId>, | |
6a06907d XL |
1031 | |
1032 | legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>, | |
cdc7bbd5 XL |
1033 | |
1034 | main_def: Option<MainDefinition>, | |
9cc50fc6 SL |
1035 | } |
1036 | ||
9fa01778 | 1037 | /// Nothing really interesting here; it just provides memory for the rest of the crate. |
0bf4aa26 | 1038 | #[derive(Default)] |
3157f602 | 1039 | pub struct ResolverArenas<'a> { |
f035d41b | 1040 | modules: TypedArena<ModuleData<'a>>, |
a7813a04 | 1041 | local_modules: RefCell<Vec<Module<'a>>>, |
f035d41b XL |
1042 | imports: TypedArena<Import<'a>>, |
1043 | name_resolutions: TypedArena<RefCell<NameResolution<'a>>>, | |
f035d41b | 1044 | ast_paths: TypedArena<ast::Path>, |
29967ef6 | 1045 | dropless: DroplessArena, |
54a0048b SL |
1046 | } |
1047 | ||
1048 | impl<'a> ResolverArenas<'a> { | |
32a655c1 | 1049 | fn alloc_module(&'a self, module: ModuleData<'a>) -> Module<'a> { |
a7813a04 | 1050 | let module = self.modules.alloc(module); |
5869c6ff | 1051 | if module.def_id().map_or(true, |def_id| def_id.is_local()) { |
a7813a04 XL |
1052 | self.local_modules.borrow_mut().push(module); |
1053 | } | |
1054 | module | |
1055 | } | |
9fa01778 | 1056 | fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> { |
a7813a04 | 1057 | self.local_modules.borrow() |
54a0048b SL |
1058 | } |
1059 | fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> { | |
29967ef6 | 1060 | self.dropless.alloc(name_binding) |
54a0048b | 1061 | } |
74b04a01 XL |
1062 | fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> { |
1063 | self.imports.alloc(import) | |
54a0048b SL |
1064 | } |
1065 | fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> { | |
1066 | self.name_resolutions.alloc(Default::default()) | |
1067 | } | |
29967ef6 XL |
1068 | fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> { |
1069 | PtrKey(self.dropless.alloc(Cell::new(scope))) | |
1070 | } | |
ba9703b0 XL |
1071 | fn alloc_macro_rules_binding( |
1072 | &'a self, | |
1073 | binding: MacroRulesBinding<'a>, | |
1074 | ) -> &'a MacroRulesBinding<'a> { | |
29967ef6 | 1075 | self.dropless.alloc(binding) |
c30ab7b3 | 1076 | } |
e1599b0c XL |
1077 | fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] { |
1078 | self.ast_paths.alloc_from_iter(paths.iter().cloned()) | |
1079 | } | |
1b1a35ee | 1080 | fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] { |
29967ef6 | 1081 | self.dropless.alloc_from_iter(spans) |
1b1a35ee | 1082 | } |
e1599b0c XL |
1083 | } |
1084 | ||
1085 | impl<'a> AsMut<Resolver<'a>> for Resolver<'a> { | |
dfeec247 XL |
1086 | fn as_mut(&mut self) -> &mut Resolver<'a> { |
1087 | self | |
1088 | } | |
1a4d82fc JJ |
1089 | } |
1090 | ||
e74abb32 | 1091 | impl<'a, 'b> DefIdTree for &'a Resolver<'b> { |
32a655c1 | 1092 | fn parent(self, id: DefId) -> Option<DefId> { |
ba9703b0 XL |
1093 | match id.as_local() { |
1094 | Some(id) => self.definitions.def_key(id).parent, | |
1095 | None => self.cstore().def_key(id).parent, | |
dfeec247 XL |
1096 | } |
1097 | .map(|index| DefId { index, ..id }) | |
a7813a04 | 1098 | } |
1a4d82fc JJ |
1099 | } |
1100 | ||
0531ce1d XL |
1101 | /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that |
1102 | /// the resolver is no longer needed as all the relevant information is inline. | |
f035d41b | 1103 | impl ResolverAstLowering for Resolver<'_> { |
dfeec247 | 1104 | fn def_key(&mut self, id: DefId) -> DefKey { |
ba9703b0 XL |
1105 | if let Some(id) = id.as_local() { |
1106 | self.definitions().def_key(id) | |
1107 | } else { | |
1108 | self.cstore().def_key(id) | |
1109 | } | |
dfeec247 XL |
1110 | } |
1111 | ||
1112 | fn item_generics_num_lifetimes(&self, def_id: DefId, sess: &Session) -> usize { | |
1113 | self.cstore().item_generics_num_lifetimes(def_id, sess) | |
e74abb32 XL |
1114 | } |
1115 | ||
6a06907d XL |
1116 | fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> { |
1117 | self.legacy_const_generic_args(expr) | |
1118 | } | |
1119 | ||
48663c56 XL |
1120 | fn get_partial_res(&mut self, id: NodeId) -> Option<PartialRes> { |
1121 | self.partial_res_map.get(&id).cloned() | |
1122 | } | |
1123 | ||
1124 | fn get_import_res(&mut self, id: NodeId) -> PerNS<Option<Res>> { | |
1125 | self.import_res_map.get(&id).cloned().unwrap_or_default() | |
2c00a5a8 XL |
1126 | } |
1127 | ||
48663c56 XL |
1128 | fn get_label_res(&mut self, id: NodeId) -> Option<NodeId> { |
1129 | self.label_res_map.get(&id).cloned() | |
94b46f34 XL |
1130 | } |
1131 | ||
2c00a5a8 XL |
1132 | fn definitions(&mut self) -> &mut Definitions { |
1133 | &mut self.definitions | |
416331ca XL |
1134 | } |
1135 | ||
dfeec247 | 1136 | fn lint_buffer(&mut self) -> &mut LintBuffer { |
e74abb32 XL |
1137 | &mut self.lint_buffer |
1138 | } | |
60c5eb7d XL |
1139 | |
1140 | fn next_node_id(&mut self) -> NodeId { | |
1141 | self.next_node_id() | |
1142 | } | |
f035d41b | 1143 | |
17df50a5 XL |
1144 | fn take_trait_map(&mut self) -> NodeMap<Vec<TraitCandidate>> { |
1145 | std::mem::replace(&mut self.trait_map, None).unwrap() | |
f035d41b XL |
1146 | } |
1147 | ||
1148 | fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> { | |
1149 | self.node_id_to_def_id.get(&node).copied() | |
1150 | } | |
1151 | ||
1152 | fn local_def_id(&self, node: NodeId) -> LocalDefId { | |
1153 | self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) | |
1154 | } | |
1155 | ||
136023e0 XL |
1156 | fn def_path_hash(&self, def_id: DefId) -> DefPathHash { |
1157 | match def_id.as_local() { | |
1158 | Some(def_id) => self.definitions.def_path_hash(def_id), | |
1159 | None => self.cstore().def_path_hash(def_id), | |
1160 | } | |
1161 | } | |
1162 | ||
f035d41b XL |
1163 | /// Adds a definition with a parent definition. |
1164 | fn create_def( | |
1165 | &mut self, | |
1166 | parent: LocalDefId, | |
1167 | node_id: ast::NodeId, | |
1168 | data: DefPathData, | |
1169 | expn_id: ExpnId, | |
1170 | span: Span, | |
1171 | ) -> LocalDefId { | |
1172 | assert!( | |
1173 | !self.node_id_to_def_id.contains_key(&node_id), | |
1174 | "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}", | |
1175 | node_id, | |
1176 | data, | |
1177 | self.definitions.def_key(self.node_id_to_def_id[&node_id]), | |
1178 | ); | |
1179 | ||
1180 | // Find the next free disambiguator for this key. | |
1181 | let next_disambiguator = &mut self.next_disambiguator; | |
1182 | let next_disambiguator = |parent, data| { | |
1183 | let next_disamb = next_disambiguator.entry((parent, data)).or_insert(0); | |
1184 | let disambiguator = *next_disamb; | |
1185 | *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow"); | |
1186 | disambiguator | |
1187 | }; | |
1188 | ||
1189 | let def_id = self.definitions.create_def(parent, data, expn_id, next_disambiguator); | |
1190 | ||
1191 | assert_eq!(self.def_id_to_span.push(span), def_id); | |
1192 | ||
1193 | // Some things for which we allocate `LocalDefId`s don't correspond to | |
1194 | // anything in the AST, so they don't have a `NodeId`. For these cases | |
1195 | // we don't need a mapping from `NodeId` to `LocalDefId`. | |
1196 | if node_id != ast::DUMMY_NODE_ID { | |
1197 | debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); | |
1198 | self.node_id_to_def_id.insert(node_id, def_id); | |
1199 | } | |
1200 | assert_eq!(self.def_id_to_node_id.push(node_id), def_id); | |
1201 | ||
1202 | def_id | |
1203 | } | |
a7813a04 XL |
1204 | } |
1205 | ||
136023e0 XL |
1206 | struct ExpandHasher<'a, 'b> { |
1207 | source_map: CachingSourceMapView<'a>, | |
1208 | resolver: &'a Resolver<'b>, | |
1209 | } | |
1210 | ||
1211 | impl<'a, 'b> rustc_span::HashStableContext for ExpandHasher<'a, 'b> { | |
1212 | #[inline] | |
1213 | fn hash_spans(&self) -> bool { | |
1214 | true | |
1215 | } | |
1216 | ||
1217 | #[inline] | |
1218 | fn def_path_hash(&self, def_id: DefId) -> DefPathHash { | |
1219 | self.resolver.def_path_hash(def_id) | |
1220 | } | |
1221 | ||
1222 | #[inline] | |
1223 | fn span_data_to_lines_and_cols( | |
1224 | &mut self, | |
1225 | span: &rustc_span::SpanData, | |
1226 | ) -> Option<(Lrc<rustc_span::SourceFile>, usize, rustc_span::BytePos, usize, rustc_span::BytePos)> | |
1227 | { | |
1228 | self.source_map.span_data_to_lines_and_cols(span) | |
1229 | } | |
1230 | } | |
1231 | ||
0731742a | 1232 | impl<'a> Resolver<'a> { |
dfeec247 XL |
1233 | pub fn new( |
1234 | session: &'a Session, | |
1235 | krate: &Crate, | |
1236 | crate_name: &str, | |
17df50a5 | 1237 | metadata_loader: Box<MetadataLoaderDyn>, |
dfeec247 XL |
1238 | arenas: &'a ResolverArenas<'a>, |
1239 | ) -> Resolver<'a> { | |
29967ef6 XL |
1240 | let root_local_def_id = LocalDefId { local_def_index: CRATE_DEF_INDEX }; |
1241 | let root_def_id = root_local_def_id.to_def_id(); | |
5869c6ff | 1242 | let root_module_kind = ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty); |
32a655c1 | 1243 | let graph_root = arenas.alloc_module(ModuleData { |
3dfed10e | 1244 | no_implicit_prelude: session.contains_name(&krate.attrs, sym::no_implicit_prelude), |
416331ca | 1245 | ..ModuleData::new(None, root_module_kind, root_def_id, ExpnId::root(), krate.span) |
9e0c209e | 1246 | }); |
5869c6ff | 1247 | let empty_module_kind = ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty); |
e1599b0c XL |
1248 | let empty_module = arenas.alloc_module(ModuleData { |
1249 | no_implicit_prelude: true, | |
1250 | ..ModuleData::new( | |
1251 | Some(graph_root), | |
1252 | empty_module_kind, | |
1253 | root_def_id, | |
1254 | ExpnId::root(), | |
1255 | DUMMY_SP, | |
1256 | ) | |
1257 | }); | |
0bf4aa26 | 1258 | let mut module_map = FxHashMap::default(); |
29967ef6 | 1259 | module_map.insert(root_local_def_id, graph_root); |
1a4d82fc | 1260 | |
136023e0 | 1261 | let definitions = Definitions::new(session.local_stable_crate_id()); |
f035d41b XL |
1262 | let root = definitions.get_root_def(); |
1263 | ||
29967ef6 XL |
1264 | let mut visibilities = FxHashMap::default(); |
1265 | visibilities.insert(root_local_def_id, ty::Visibility::Public); | |
1266 | ||
f035d41b XL |
1267 | let mut def_id_to_span = IndexVec::default(); |
1268 | assert_eq!(def_id_to_span.push(rustc_span::DUMMY_SP), root); | |
1269 | let mut def_id_to_node_id = IndexVec::default(); | |
1270 | assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), root); | |
1271 | let mut node_id_to_def_id = FxHashMap::default(); | |
1272 | node_id_to_def_id.insert(CRATE_NODE_ID, root); | |
1273 | ||
1274 | let mut invocation_parents = FxHashMap::default(); | |
136023e0 | 1275 | invocation_parents.insert(LocalExpnId::ROOT, (root, ImplTraitContext::Existential)); |
c30ab7b3 | 1276 | |
dfeec247 XL |
1277 | let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session |
1278 | .opts | |
1279 | .externs | |
1280 | .iter() | |
1281 | .filter(|(_, entry)| entry.add_prelude) | |
1282 | .map(|(name, _)| (Ident::from_str(name), Default::default())) | |
1283 | .collect(); | |
b7449926 | 1284 | |
3dfed10e | 1285 | if !session.contains_name(&krate.attrs, sym::no_core) { |
e1599b0c | 1286 | extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default()); |
3dfed10e | 1287 | if !session.contains_name(&krate.attrs, sym::no_std) { |
e1599b0c | 1288 | extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default()); |
4462d4a0 XL |
1289 | } |
1290 | } | |
94b46f34 | 1291 | |
60c5eb7d XL |
1292 | let (registered_attrs, registered_tools) = |
1293 | macros::registered_attrs_and_tools(session, &krate.attrs); | |
1294 | ||
416331ca XL |
1295 | let features = session.features_untracked(); |
1296 | let non_macro_attr = | |
1297 | |mark_used| Lrc::new(SyntaxExtension::non_macro_attr(mark_used, session.edition())); | |
dc9dc135 | 1298 | |
29967ef6 | 1299 | let mut resolver = Resolver { |
3b2f2976 | 1300 | session, |
1a4d82fc | 1301 | |
3b2f2976 | 1302 | definitions, |
1a4d82fc JJ |
1303 | |
1304 | // The outermost module has def ID 0; this is not reflected in the | |
1305 | // AST. | |
3b2f2976 | 1306 | graph_root, |
3157f602 | 1307 | prelude: None, |
94b46f34 | 1308 | extern_prelude, |
1a4d82fc | 1309 | |
0bf4aa26 XL |
1310 | has_self: FxHashSet::default(), |
1311 | field_names: FxHashMap::default(), | |
1a4d82fc | 1312 | |
9e0c209e SL |
1313 | determined_imports: Vec::new(), |
1314 | indeterminate_imports: Vec::new(), | |
1a4d82fc | 1315 | |
13cf67c4 | 1316 | last_import_segment: false, |
f035d41b | 1317 | unusable_binding: None, |
1a4d82fc | 1318 | |
cdc7bbd5 | 1319 | pat_span_map: Default::default(), |
48663c56 XL |
1320 | partial_res_map: Default::default(), |
1321 | import_res_map: Default::default(), | |
1322 | label_res_map: Default::default(), | |
e74abb32 | 1323 | extern_crate_map: Default::default(), |
0bf4aa26 | 1324 | export_map: FxHashMap::default(), |
17df50a5 | 1325 | trait_map: Some(NodeMap::default()), |
e74abb32 | 1326 | underscore_disambiguator: 0, |
e1599b0c | 1327 | empty_module, |
3b2f2976 | 1328 | module_map, |
a1dfa0c6 | 1329 | block_map: Default::default(), |
0bf4aa26 XL |
1330 | extern_module_map: FxHashMap::default(), |
1331 | binding_parent_modules: FxHashMap::default(), | |
e1599b0c | 1332 | ast_transform_scopes: FxHashMap::default(), |
1a4d82fc | 1333 | |
a1dfa0c6 | 1334 | glob_map: Default::default(), |
29967ef6 | 1335 | visibilities, |
0bf4aa26 | 1336 | used_imports: FxHashSet::default(), |
a1dfa0c6 | 1337 | maybe_unused_trait_imports: Default::default(), |
3b2f2976 | 1338 | maybe_unused_extern_crates: Vec::new(), |
a7813a04 | 1339 | |
54a0048b | 1340 | privacy_errors: Vec::new(), |
9e0c209e | 1341 | ambiguity_errors: Vec::new(), |
3b2f2976 | 1342 | use_injections: Vec::new(), |
b7449926 | 1343 | macro_expanded_macro_export_errors: BTreeSet::new(), |
9cc50fc6 | 1344 | |
3b2f2976 | 1345 | arenas, |
9e0c209e | 1346 | dummy_binding: arenas.alloc_name_binding(NameBinding { |
48663c56 | 1347 | kind: NameBindingKind::Res(Res::Err, false), |
0731742a | 1348 | ambiguity: None, |
136023e0 | 1349 | expansion: LocalExpnId::ROOT, |
9e0c209e SL |
1350 | span: DUMMY_SP, |
1351 | vis: ty::Visibility::Public, | |
1352 | }), | |
32a655c1 | 1353 | |
e74abb32 | 1354 | crate_loader: CrateLoader::new(session, metadata_loader, crate_name), |
0bf4aa26 | 1355 | macro_names: FxHashSet::default(), |
416331ca | 1356 | builtin_macros: Default::default(), |
60c5eb7d XL |
1357 | registered_attrs, |
1358 | registered_tools, | |
0bf4aa26 XL |
1359 | macro_use_prelude: FxHashMap::default(), |
1360 | all_macros: FxHashMap::default(), | |
1361 | macro_map: FxHashMap::default(), | |
416331ca XL |
1362 | dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())), |
1363 | dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())), | |
dc9dc135 | 1364 | non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)], |
29967ef6 | 1365 | invocation_parent_scopes: Default::default(), |
ba9703b0 | 1366 | output_macro_rules_scopes: Default::default(), |
60c5eb7d | 1367 | helper_attrs: Default::default(), |
cdc7bbd5 | 1368 | derive_data: Default::default(), |
0bf4aa26 XL |
1369 | local_macro_def_scopes: FxHashMap::default(), |
1370 | name_already_seen: FxHashMap::default(), | |
32a655c1 | 1371 | potentially_unused_imports: Vec::new(), |
a1dfa0c6 | 1372 | struct_constructors: Default::default(), |
416331ca XL |
1373 | unused_macros: Default::default(), |
1374 | proc_macro_stubs: Default::default(), | |
e1599b0c XL |
1375 | single_segment_macro_resolutions: Default::default(), |
1376 | multi_segment_macro_resolutions: Default::default(), | |
1377 | builtin_attrs: Default::default(), | |
60c5eb7d | 1378 | containers_deriving_copy: Default::default(), |
dfeec247 XL |
1379 | active_features: features |
1380 | .declared_lib_features | |
1381 | .iter() | |
1382 | .map(|(feat, ..)| *feat) | |
1383 | .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat)) | |
1384 | .collect(), | |
dfeec247 | 1385 | lint_buffer: LintBuffer::default(), |
60c5eb7d | 1386 | next_node_id: NodeId::from_u32(1), |
f035d41b XL |
1387 | def_id_to_span, |
1388 | node_id_to_def_id, | |
1389 | def_id_to_node_id, | |
1390 | placeholder_field_indices: Default::default(), | |
1391 | invocation_parents, | |
1392 | next_disambiguator: Default::default(), | |
29967ef6 | 1393 | trait_impl_items: Default::default(), |
6a06907d | 1394 | legacy_const_generic_args: Default::default(), |
cdc7bbd5 | 1395 | main_def: Default::default(), |
29967ef6 XL |
1396 | }; |
1397 | ||
1398 | let root_parent_scope = ParentScope::module(graph_root, &resolver); | |
136023e0 | 1399 | resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope); |
29967ef6 XL |
1400 | |
1401 | resolver | |
9cc50fc6 SL |
1402 | } |
1403 | ||
136023e0 XL |
1404 | fn create_stable_hashing_context(&self) -> ExpandHasher<'_, 'a> { |
1405 | ExpandHasher { | |
1406 | source_map: CachingSourceMapView::new(self.session.source_map()), | |
1407 | resolver: self, | |
1408 | } | |
1409 | } | |
1410 | ||
60c5eb7d | 1411 | pub fn next_node_id(&mut self) -> NodeId { |
dfeec247 XL |
1412 | let next = self |
1413 | .next_node_id | |
1414 | .as_usize() | |
60c5eb7d XL |
1415 | .checked_add(1) |
1416 | .expect("input too large; ran out of NodeIds"); | |
1417 | self.next_node_id = ast::NodeId::from_usize(next); | |
1418 | self.next_node_id | |
1419 | } | |
1420 | ||
dfeec247 | 1421 | pub fn lint_buffer(&mut self) -> &mut LintBuffer { |
e74abb32 XL |
1422 | &mut self.lint_buffer |
1423 | } | |
1424 | ||
3157f602 | 1425 | pub fn arenas() -> ResolverArenas<'a> { |
0bf4aa26 | 1426 | Default::default() |
1a4d82fc JJ |
1427 | } |
1428 | ||
e74abb32 | 1429 | pub fn into_outputs(self) -> ResolverOutputs { |
f9f354fc | 1430 | let definitions = self.definitions; |
29967ef6 | 1431 | let visibilities = self.visibilities; |
f9f354fc | 1432 | let extern_crate_map = self.extern_crate_map; |
f035d41b | 1433 | let export_map = self.export_map; |
f9f354fc XL |
1434 | let maybe_unused_trait_imports = self.maybe_unused_trait_imports; |
1435 | let maybe_unused_extern_crates = self.maybe_unused_extern_crates; | |
1436 | let glob_map = self.glob_map; | |
cdc7bbd5 | 1437 | let main_def = self.main_def; |
e74abb32 | 1438 | ResolverOutputs { |
29967ef6 | 1439 | definitions, |
e74abb32 | 1440 | cstore: Box::new(self.crate_loader.into_cstore()), |
29967ef6 | 1441 | visibilities, |
f9f354fc XL |
1442 | extern_crate_map, |
1443 | export_map, | |
f9f354fc XL |
1444 | glob_map, |
1445 | maybe_unused_trait_imports, | |
1446 | maybe_unused_extern_crates, | |
dfeec247 XL |
1447 | extern_prelude: self |
1448 | .extern_prelude | |
1449 | .iter() | |
1450 | .map(|(ident, entry)| (ident.name, entry.introduced_by_item)) | |
1451 | .collect(), | |
cdc7bbd5 | 1452 | main_def, |
e74abb32 XL |
1453 | } |
1454 | } | |
1455 | ||
1456 | pub fn clone_outputs(&self) -> ResolverOutputs { | |
1457 | ResolverOutputs { | |
1458 | definitions: self.definitions.clone(), | |
1459 | cstore: Box::new(self.cstore().clone()), | |
29967ef6 | 1460 | visibilities: self.visibilities.clone(), |
e74abb32 | 1461 | extern_crate_map: self.extern_crate_map.clone(), |
f035d41b | 1462 | export_map: self.export_map.clone(), |
e74abb32 XL |
1463 | glob_map: self.glob_map.clone(), |
1464 | maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(), | |
1465 | maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(), | |
dfeec247 XL |
1466 | extern_prelude: self |
1467 | .extern_prelude | |
1468 | .iter() | |
1469 | .map(|(ident, entry)| (ident.name, entry.introduced_by_item)) | |
1470 | .collect(), | |
cdc7bbd5 | 1471 | main_def: self.main_def.clone(), |
e74abb32 XL |
1472 | } |
1473 | } | |
1474 | ||
1475 | pub fn cstore(&self) -> &CStore { | |
1476 | self.crate_loader.cstore() | |
1477 | } | |
1478 | ||
dc9dc135 XL |
1479 | fn non_macro_attr(&self, mark_used: bool) -> Lrc<SyntaxExtension> { |
1480 | self.non_macro_attrs[mark_used as usize].clone() | |
1481 | } | |
1482 | ||
416331ca XL |
1483 | fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> { |
1484 | match macro_kind { | |
1485 | MacroKind::Bang => self.dummy_ext_bang.clone(), | |
1486 | MacroKind::Derive => self.dummy_ext_derive.clone(), | |
1487 | MacroKind::Attr => self.non_macro_attr(true), | |
1488 | } | |
1489 | } | |
1490 | ||
0531ce1d | 1491 | /// Runs the function on each namespace. |
83c7162d XL |
1492 | fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) { |
1493 | f(self, TypeNS); | |
1494 | f(self, ValueNS); | |
b7449926 | 1495 | f(self, MacroNS); |
476ff2be | 1496 | } |
c30ab7b3 | 1497 | |
e1599b0c | 1498 | fn is_builtin_macro(&mut self, res: Res) -> bool { |
5869c6ff | 1499 | self.get_macro(res).map_or(false, |ext| ext.builtin_name.is_some()) |
416331ca XL |
1500 | } |
1501 | ||
ff7c6d11 XL |
1502 | fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId { |
1503 | loop { | |
6a06907d | 1504 | match ctxt.outer_expn_data().macro_def_id { |
f9f354fc | 1505 | Some(def_id) => return def_id, |
ff7c6d11 XL |
1506 | None => ctxt.remove_mark(), |
1507 | }; | |
1508 | } | |
1509 | } | |
1510 | ||
476ff2be SL |
1511 | /// Entry point to crate resolution. |
1512 | pub fn resolve_crate(&mut self, krate: &Crate) { | |
5869c6ff XL |
1513 | self.session.time("resolve_crate", || { |
1514 | self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports()); | |
1515 | self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions()); | |
1516 | self.session.time("late_resolve_crate", || self.late_resolve_crate(krate)); | |
cdc7bbd5 | 1517 | self.session.time("resolve_main", || self.resolve_main()); |
5869c6ff XL |
1518 | self.session.time("resolve_check_unused", || self.check_unused(krate)); |
1519 | self.session.time("resolve_report_errors", || self.report_errors(krate)); | |
1520 | self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate)); | |
1521 | }); | |
1522 | } | |
e74abb32 | 1523 | |
5869c6ff XL |
1524 | pub fn traits_in_scope( |
1525 | &mut self, | |
1526 | current_trait: Option<Module<'a>>, | |
1527 | parent_scope: &ParentScope<'a>, | |
1528 | ctxt: SyntaxContext, | |
1529 | assoc_item: Option<(Symbol, Namespace)>, | |
1530 | ) -> Vec<TraitCandidate> { | |
1531 | let mut found_traits = Vec::new(); | |
1532 | ||
1533 | if let Some(module) = current_trait { | |
1534 | if self.trait_may_have_item(Some(module), assoc_item) { | |
1535 | let def_id = module.def_id().unwrap(); | |
1536 | found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] }); | |
1537 | } | |
1538 | } | |
3b2f2976 | 1539 | |
5869c6ff XL |
1540 | self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| { |
1541 | match scope { | |
cdc7bbd5 | 1542 | Scope::Module(module, _) => { |
5869c6ff XL |
1543 | this.traits_in_module(module, assoc_item, &mut found_traits); |
1544 | } | |
1545 | Scope::StdLibPrelude => { | |
1546 | if let Some(module) = this.prelude { | |
1547 | this.traits_in_module(module, assoc_item, &mut found_traits); | |
1548 | } | |
1549 | } | |
1550 | Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {} | |
1551 | _ => unreachable!(), | |
1552 | } | |
1553 | None::<()> | |
1554 | }); | |
3157f602 | 1555 | |
5869c6ff | 1556 | found_traits |
3157f602 XL |
1557 | } |
1558 | ||
5869c6ff | 1559 | fn traits_in_module( |
3dfed10e | 1560 | &mut self, |
3dfed10e | 1561 | module: Module<'a>, |
5869c6ff | 1562 | assoc_item: Option<(Symbol, Namespace)>, |
3dfed10e | 1563 | found_traits: &mut Vec<TraitCandidate>, |
3dfed10e | 1564 | ) { |
3dfed10e XL |
1565 | module.ensure_traits(self); |
1566 | let traits = module.traits.borrow(); | |
5869c6ff XL |
1567 | for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() { |
1568 | if self.trait_may_have_item(trait_binding.module(), assoc_item) { | |
1569 | let def_id = trait_binding.res().def_id(); | |
1570 | let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name); | |
1571 | found_traits.push(TraitCandidate { def_id, import_ids }); | |
1572 | } | |
1573 | } | |
1574 | } | |
3dfed10e | 1575 | |
5869c6ff XL |
1576 | // List of traits in scope is pruned on best effort basis. We reject traits not having an |
1577 | // associated item with the given name and namespace (if specified). This is a conservative | |
1578 | // optimization, proper hygienic type-based resolution of associated items is done in typeck. | |
1579 | // We don't reject trait aliases (`trait_module == None`) because we don't have access to their | |
1580 | // associated items. | |
1581 | fn trait_may_have_item( | |
1582 | &mut self, | |
1583 | trait_module: Option<Module<'a>>, | |
1584 | assoc_item: Option<(Symbol, Namespace)>, | |
1585 | ) -> bool { | |
1586 | match (trait_module, assoc_item) { | |
1587 | (Some(trait_module), Some((name, ns))) => { | |
1588 | self.resolutions(trait_module).borrow().iter().any(|resolution| { | |
1589 | let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution; | |
1590 | assoc_ns == ns && assoc_ident.name == name | |
1591 | }) | |
3dfed10e | 1592 | } |
5869c6ff | 1593 | _ => true, |
3dfed10e XL |
1594 | } |
1595 | } | |
1596 | ||
1597 | fn find_transitive_imports( | |
1598 | &mut self, | |
1599 | mut kind: &NameBindingKind<'_>, | |
1600 | trait_name: Ident, | |
1601 | ) -> SmallVec<[LocalDefId; 1]> { | |
1602 | let mut import_ids = smallvec![]; | |
1603 | while let NameBindingKind::Import { import, binding, .. } = kind { | |
1604 | let id = self.local_def_id(import.id); | |
1605 | self.maybe_unused_trait_imports.insert(id); | |
1606 | self.add_to_glob_map(&import, trait_name); | |
1607 | import_ids.push(id); | |
1608 | kind = &binding.kind; | |
1609 | } | |
1610 | import_ids | |
1611 | } | |
1612 | ||
7cac9316 XL |
1613 | fn new_module( |
1614 | &self, | |
1615 | parent: Module<'a>, | |
1616 | kind: ModuleKind, | |
5869c6ff | 1617 | nearest_parent_mod: DefId, |
416331ca | 1618 | expn_id: ExpnId, |
7cac9316 XL |
1619 | span: Span, |
1620 | ) -> Module<'a> { | |
5869c6ff | 1621 | let module = ModuleData::new(Some(parent), kind, nearest_parent_mod, expn_id, span); |
7cac9316 | 1622 | self.arenas.alloc_module(module) |
7453a54e SL |
1623 | } |
1624 | ||
e74abb32 | 1625 | fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey { |
ba9703b0 | 1626 | let ident = ident.normalize_to_macros_2_0(); |
e74abb32 XL |
1627 | let disambiguator = if ident.name == kw::Underscore { |
1628 | self.underscore_disambiguator += 1; | |
1629 | self.underscore_disambiguator | |
1630 | } else { | |
1631 | 0 | |
1632 | }; | |
1633 | BindingKey { ident, ns, disambiguator } | |
1634 | } | |
1635 | ||
e1599b0c XL |
1636 | fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> { |
1637 | if module.populate_on_access.get() { | |
1638 | module.populate_on_access.set(false); | |
1639 | self.build_reduced_graph_external(module); | |
1640 | } | |
1641 | &module.lazy_resolutions | |
1642 | } | |
1643 | ||
dfeec247 XL |
1644 | fn resolution( |
1645 | &mut self, | |
1646 | module: Module<'a>, | |
1647 | key: BindingKey, | |
1648 | ) -> &'a RefCell<NameResolution<'a>> { | |
1649 | *self | |
1650 | .resolutions(module) | |
1651 | .borrow_mut() | |
1652 | .entry(key) | |
1653 | .or_insert_with(|| self.arenas.alloc_name_resolution()) | |
e1599b0c XL |
1654 | } |
1655 | ||
dfeec247 XL |
1656 | fn record_use( |
1657 | &mut self, | |
1658 | ident: Ident, | |
1659 | ns: Namespace, | |
1660 | used_binding: &'a NameBinding<'a>, | |
1661 | is_lexical_scope: bool, | |
1662 | ) { | |
0731742a XL |
1663 | if let Some((b2, kind)) = used_binding.ambiguity { |
1664 | self.ambiguity_errors.push(AmbiguityError { | |
dfeec247 XL |
1665 | kind, |
1666 | ident, | |
1667 | b1: used_binding, | |
1668 | b2, | |
0731742a XL |
1669 | misc1: AmbiguityErrorMisc::None, |
1670 | misc2: AmbiguityErrorMisc::None, | |
1671 | }); | |
1672 | } | |
74b04a01 | 1673 | if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind { |
0731742a XL |
1674 | // Avoid marking `extern crate` items that refer to a name from extern prelude, |
1675 | // but not introduce it, as used if they are accessed from lexical scope. | |
1676 | if is_lexical_scope { | |
ba9703b0 | 1677 | if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) { |
0731742a XL |
1678 | if let Some(crate_item) = entry.extern_crate_item { |
1679 | if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item { | |
1680 | return; | |
13cf67c4 XL |
1681 | } |
1682 | } | |
1683 | } | |
9e0c209e | 1684 | } |
0731742a | 1685 | used.set(true); |
74b04a01 XL |
1686 | import.used.set(true); |
1687 | self.used_imports.insert((import.id, ns)); | |
1688 | self.add_to_glob_map(&import, ident); | |
0731742a | 1689 | self.record_use(ident, ns, binding, false); |
54a0048b | 1690 | } |
5bcae85e | 1691 | } |
7453a54e | 1692 | |
9fa01778 | 1693 | #[inline] |
74b04a01 XL |
1694 | fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) { |
1695 | if import.is_glob() { | |
f035d41b | 1696 | let def_id = self.local_def_id(import.id); |
f9f354fc | 1697 | self.glob_map.entry(def_id).or_default().insert(ident.name); |
1a4d82fc | 1698 | } |
1a4d82fc JJ |
1699 | } |
1700 | ||
416331ca XL |
1701 | /// A generic scope visitor. |
1702 | /// Visits scopes in order to resolve some identifier in them or perform other actions. | |
1703 | /// If the callback returns `Some` result, we stop visiting scopes and return it. | |
1704 | fn visit_scopes<T>( | |
1705 | &mut self, | |
cdc7bbd5 | 1706 | scope_set: ScopeSet<'a>, |
416331ca | 1707 | parent_scope: &ParentScope<'a>, |
5869c6ff XL |
1708 | ctxt: SyntaxContext, |
1709 | mut visitor: impl FnMut( | |
1710 | &mut Self, | |
1711 | Scope<'a>, | |
1712 | /*use_prelude*/ bool, | |
1713 | SyntaxContext, | |
1714 | ) -> Option<T>, | |
416331ca XL |
1715 | ) -> Option<T> { |
1716 | // General principles: | |
1717 | // 1. Not controlled (user-defined) names should have higher priority than controlled names | |
1718 | // built into the language or standard library. This way we can add new names into the | |
1719 | // language or standard library without breaking user code. | |
1720 | // 2. "Closed set" below means new names cannot appear after the current resolution attempt. | |
1721 | // Places to search (in order of decreasing priority): | |
1722 | // (Type NS) | |
1723 | // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet | |
1724 | // (open set, not controlled). | |
1725 | // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents | |
1726 | // (open, not controlled). | |
1727 | // 3. Extern prelude (open, the open part is from macro expansions, not controlled). | |
1728 | // 4. Tool modules (closed, controlled right now, but not in the future). | |
1729 | // 5. Standard library prelude (de-facto closed, controlled). | |
1730 | // 6. Language prelude (closed, controlled). | |
1731 | // (Value NS) | |
1732 | // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet | |
1733 | // (open set, not controlled). | |
1734 | // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents | |
1735 | // (open, not controlled). | |
1736 | // 3. Standard library prelude (de-facto closed, controlled). | |
1737 | // (Macro NS) | |
1738 | // 1-3. Derive helpers (open, not controlled). All ambiguities with other names | |
1739 | // are currently reported as errors. They should be higher in priority than preludes | |
1740 | // and probably even names in modules according to the "general principles" above. They | |
1741 | // also should be subject to restricted shadowing because are effectively produced by | |
1742 | // derives (you need to resolve the derive first to add helpers into scope), but they | |
1743 | // should be available before the derive is expanded for compatibility. | |
1744 | // It's mess in general, so we are being conservative for now. | |
ba9703b0 | 1745 | // 1-3. `macro_rules` (open, not controlled), loop through `macro_rules` scopes. Have higher |
416331ca XL |
1746 | // priority than prelude macros, but create ambiguities with macros in modules. |
1747 | // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents | |
1748 | // (open, not controlled). Have higher priority than prelude macros, but create | |
1749 | // ambiguities with `macro_rules`. | |
1750 | // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled). | |
1751 | // 4a. User-defined prelude from macro-use | |
1752 | // (open, the open part is from macro expansions, not controlled). | |
1753 | // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled). | |
1754 | // 4c. Standard library prelude (de-facto closed, controlled). | |
1755 | // 6. Language prelude: builtin attributes (closed, controlled). | |
416331ca | 1756 | |
5869c6ff | 1757 | let rust_2015 = ctxt.edition() == Edition::Edition2015; |
60c5eb7d XL |
1758 | let (ns, macro_kind, is_absolute_path) = match scope_set { |
1759 | ScopeSet::All(ns, _) => (ns, None, false), | |
1760 | ScopeSet::AbsolutePath(ns) => (ns, None, true), | |
1761 | ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false), | |
cdc7bbd5 XL |
1762 | ScopeSet::Late(ns, ..) => (ns, None, false), |
1763 | }; | |
1764 | let module = match scope_set { | |
1765 | // Start with the specified module. | |
1766 | ScopeSet::Late(_, module, _) => module, | |
1767 | // Jump out of trait or enum modules, they do not act as scopes. | |
1768 | _ => parent_scope.module.nearest_item_scope(), | |
416331ca XL |
1769 | }; |
1770 | let mut scope = match ns { | |
1771 | _ if is_absolute_path => Scope::CrateRoot, | |
cdc7bbd5 | 1772 | TypeNS | ValueNS => Scope::Module(module, None), |
60c5eb7d | 1773 | MacroNS => Scope::DeriveHelpers(parent_scope.expansion), |
416331ca | 1774 | }; |
5869c6ff | 1775 | let mut ctxt = ctxt.normalize_to_macros_2_0(); |
e1599b0c | 1776 | let mut use_prelude = !module.no_implicit_prelude; |
416331ca XL |
1777 | |
1778 | loop { | |
1779 | let visit = match scope { | |
60c5eb7d | 1780 | // Derive helpers are not in scope when resolving derives in the same container. |
dfeec247 XL |
1781 | Scope::DeriveHelpers(expn_id) => { |
1782 | !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive)) | |
1783 | } | |
60c5eb7d | 1784 | Scope::DeriveHelpersCompat => true, |
fc512014 XL |
1785 | Scope::MacroRules(macro_rules_scope) => { |
1786 | // Use "path compression" on `macro_rules` scope chains. This is an optimization | |
1787 | // used to avoid long scope chains, see the comments on `MacroRulesScopeRef`. | |
1788 | // As another consequence of this optimization visitors never observe invocation | |
1789 | // scopes for macros that were already expanded. | |
1790 | while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() { | |
1791 | if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) { | |
1792 | macro_rules_scope.set(next_scope.get()); | |
1793 | } else { | |
1794 | break; | |
1795 | } | |
1796 | } | |
1797 | true | |
1798 | } | |
416331ca XL |
1799 | Scope::CrateRoot => true, |
1800 | Scope::Module(..) => true, | |
60c5eb7d | 1801 | Scope::RegisteredAttrs => use_prelude, |
416331ca XL |
1802 | Scope::MacroUsePrelude => use_prelude || rust_2015, |
1803 | Scope::BuiltinAttrs => true, | |
416331ca XL |
1804 | Scope::ExternPrelude => use_prelude || is_absolute_path, |
1805 | Scope::ToolPrelude => use_prelude, | |
1806 | Scope::StdLibPrelude => use_prelude || ns == MacroNS, | |
1807 | Scope::BuiltinTypes => true, | |
1808 | }; | |
1809 | ||
1810 | if visit { | |
5869c6ff | 1811 | if let break_result @ Some(..) = visitor(self, scope, use_prelude, ctxt) { |
416331ca XL |
1812 | return break_result; |
1813 | } | |
1814 | } | |
1815 | ||
1816 | scope = match scope { | |
136023e0 XL |
1817 | Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat, |
1818 | Scope::DeriveHelpers(expn_id) => { | |
60c5eb7d XL |
1819 | // Derive helpers are not visible to code generated by bang or derive macros. |
1820 | let expn_data = expn_id.expn_data(); | |
1821 | match expn_data.kind { | |
dfeec247 | 1822 | ExpnKind::Root |
136023e0 XL |
1823 | | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => { |
1824 | Scope::DeriveHelpersCompat | |
1825 | } | |
1826 | _ => Scope::DeriveHelpers(expn_data.parent.expect_local()), | |
60c5eb7d XL |
1827 | } |
1828 | } | |
ba9703b0 | 1829 | Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules), |
29967ef6 | 1830 | Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() { |
ba9703b0 XL |
1831 | MacroRulesScope::Binding(binding) => { |
1832 | Scope::MacroRules(binding.parent_macro_rules_scope) | |
1833 | } | |
fc512014 XL |
1834 | MacroRulesScope::Invocation(invoc_id) => { |
1835 | Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules) | |
1836 | } | |
cdc7bbd5 | 1837 | MacroRulesScope::Empty => Scope::Module(module, None), |
dfeec247 | 1838 | }, |
416331ca XL |
1839 | Scope::CrateRoot => match ns { |
1840 | TypeNS => { | |
5869c6ff | 1841 | ctxt.adjust(ExpnId::root()); |
416331ca XL |
1842 | Scope::ExternPrelude |
1843 | } | |
1844 | ValueNS | MacroNS => break, | |
dfeec247 | 1845 | }, |
cdc7bbd5 | 1846 | Scope::Module(module, prev_lint_id) => { |
416331ca | 1847 | use_prelude = !module.no_implicit_prelude; |
cdc7bbd5 XL |
1848 | let derive_fallback_lint_id = match scope_set { |
1849 | ScopeSet::Late(.., lint_id) => lint_id, | |
1850 | _ => None, | |
1851 | }; | |
1852 | match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) { | |
1853 | Some((parent_module, lint_id)) => { | |
1854 | Scope::Module(parent_module, lint_id.or(prev_lint_id)) | |
1855 | } | |
416331ca | 1856 | None => { |
5869c6ff | 1857 | ctxt.adjust(ExpnId::root()); |
416331ca XL |
1858 | match ns { |
1859 | TypeNS => Scope::ExternPrelude, | |
1860 | ValueNS => Scope::StdLibPrelude, | |
60c5eb7d | 1861 | MacroNS => Scope::RegisteredAttrs, |
416331ca XL |
1862 | } |
1863 | } | |
1864 | } | |
1865 | } | |
60c5eb7d | 1866 | Scope::RegisteredAttrs => Scope::MacroUsePrelude, |
416331ca | 1867 | Scope::MacroUsePrelude => Scope::StdLibPrelude, |
60c5eb7d | 1868 | Scope::BuiltinAttrs => break, // nowhere else to search |
416331ca XL |
1869 | Scope::ExternPrelude if is_absolute_path => break, |
1870 | Scope::ExternPrelude => Scope::ToolPrelude, | |
1871 | Scope::ToolPrelude => Scope::StdLibPrelude, | |
1872 | Scope::StdLibPrelude => match ns { | |
1873 | TypeNS => Scope::BuiltinTypes, | |
1874 | ValueNS => break, // nowhere else to search | |
1875 | MacroNS => Scope::BuiltinAttrs, | |
dfeec247 | 1876 | }, |
416331ca XL |
1877 | Scope::BuiltinTypes => break, // nowhere else to search |
1878 | }; | |
1879 | } | |
1880 | ||
1881 | None | |
1882 | } | |
1883 | ||
54a0048b SL |
1884 | /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope. |
1885 | /// More specifically, we proceed up the hierarchy of scopes and return the binding for | |
1886 | /// `ident` in the first scope that defines it (or None if no scopes define it). | |
1887 | /// | |
1888 | /// A block's items are above its local variables in the scope hierarchy, regardless of where | |
1889 | /// the items are defined in the block. For example, | |
1890 | /// ```rust | |
1891 | /// fn f() { | |
1892 | /// g(); // Since there are no local variables in scope yet, this resolves to the item. | |
1893 | /// let g = || {}; | |
1894 | /// fn g() {} | |
1895 | /// g(); // This resolves to the local variable `g` since it shadows the item. | |
1896 | /// } | |
1897 | /// ``` | |
1898 | /// | |
1a4d82fc JJ |
1899 | /// Invariant: This must only be called during main resolution, not during |
1900 | /// import resolution. | |
dfeec247 XL |
1901 | fn resolve_ident_in_lexical_scope( |
1902 | &mut self, | |
1903 | mut ident: Ident, | |
1904 | ns: Namespace, | |
1905 | parent_scope: &ParentScope<'a>, | |
1906 | record_used_id: Option<NodeId>, | |
1907 | path_span: Span, | |
1908 | ribs: &[Rib<'a>], | |
1909 | ) -> Option<LexicalScopeBinding<'a>> { | |
dc9dc135 | 1910 | assert!(ns == TypeNS || ns == ValueNS); |
cdc7bbd5 | 1911 | let orig_ident = ident; |
5869c6ff | 1912 | if ident.name == kw::Empty { |
48663c56 | 1913 | return Some(LexicalScopeBinding::Res(Res::Err)); |
0731742a | 1914 | } |
ba9703b0 | 1915 | let (general_span, normalized_span) = if ident.name == kw::SelfUpper { |
0731742a | 1916 | // FIXME(jseyfried) improve `Self` hygiene |
e1599b0c | 1917 | let empty_span = ident.span.with_ctxt(SyntaxContext::root()); |
416331ca | 1918 | (empty_span, empty_span) |
0731742a | 1919 | } else if ns == TypeNS { |
ba9703b0 XL |
1920 | let normalized_span = ident.span.normalize_to_macros_2_0(); |
1921 | (normalized_span, normalized_span) | |
8faf50e0 | 1922 | } else { |
ba9703b0 | 1923 | (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0()) |
0731742a | 1924 | }; |
416331ca | 1925 | ident.span = general_span; |
ba9703b0 | 1926 | let normalized_ident = Ident { span: normalized_span, ..ident }; |
54a0048b SL |
1927 | |
1928 | // Walk backwards up the ribs in scope. | |
0731742a | 1929 | let record_used = record_used_id.is_some(); |
7cac9316 | 1930 | let mut module = self.graph_root; |
dfeec247 | 1931 | for i in (0..ribs.len()).rev() { |
416331ca XL |
1932 | debug!("walk rib\n{:?}", ribs[i].bindings); |
1933 | // Use the rib kind to determine whether we are resolving parameters | |
ba9703b0 XL |
1934 | // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene). |
1935 | let rib_ident = if ribs[i].kind.contains_params() { normalized_ident } else { ident }; | |
5869c6ff XL |
1936 | if let Some((original_rib_ident_def, res)) = ribs[i].bindings.get_key_value(&rib_ident) |
1937 | { | |
54a0048b | 1938 | // The ident resolves to a type parameter or local variable. |
dfeec247 XL |
1939 | return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs( |
1940 | i, | |
1941 | rib_ident, | |
5869c6ff | 1942 | *res, |
dfeec247 XL |
1943 | record_used, |
1944 | path_span, | |
5869c6ff | 1945 | *original_rib_ident_def, |
dfeec247 XL |
1946 | ribs, |
1947 | ))); | |
54a0048b SL |
1948 | } |
1949 | ||
416331ca | 1950 | module = match ribs[i].kind { |
7cac9316 | 1951 | ModuleRibKind(module) => module, |
83c7162d | 1952 | MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => { |
7cac9316 XL |
1953 | // If an invocation of this macro created `ident`, give up on `ident` |
1954 | // and switch to `ident`'s source from the macro definition. | |
83c7162d | 1955 | ident.span.remove_mark(); |
dfeec247 | 1956 | continue; |
7453a54e | 1957 | } |
7cac9316 XL |
1958 | _ => continue, |
1959 | }; | |
1a4d82fc | 1960 | |
7cac9316 | 1961 | match module.kind { |
dfeec247 | 1962 | ModuleKind::Block(..) => {} // We can see through blocks |
7cac9316 XL |
1963 | _ => break, |
1964 | } | |
7cac9316 | 1965 | |
cdc7bbd5 | 1966 | let item = self.resolve_ident_in_module_unadjusted( |
b7449926 XL |
1967 | ModuleOrUniformRoot::Module(module), |
1968 | ident, | |
1969 | ns, | |
cdc7bbd5 | 1970 | parent_scope, |
b7449926 XL |
1971 | record_used, |
1972 | path_span, | |
7cac9316 | 1973 | ); |
cdc7bbd5 XL |
1974 | if let Ok(binding) = item { |
1975 | // The ident resolves to an item. | |
60c5eb7d XL |
1976 | return Some(LexicalScopeBinding::Item(binding)); |
1977 | } | |
1978 | } | |
cdc7bbd5 XL |
1979 | self.early_resolve_ident_in_lexical_scope( |
1980 | orig_ident, | |
1981 | ScopeSet::Late(ns, module, record_used_id), | |
1982 | parent_scope, | |
1983 | record_used, | |
1984 | record_used, | |
1985 | path_span, | |
1986 | ) | |
1987 | .ok() | |
1988 | .map(LexicalScopeBinding::Item) | |
7cac9316 XL |
1989 | } |
1990 | ||
dfeec247 XL |
1991 | fn hygienic_lexical_parent( |
1992 | &mut self, | |
1993 | module: Module<'a>, | |
5869c6ff | 1994 | ctxt: &mut SyntaxContext, |
cdc7bbd5 XL |
1995 | derive_fallback_lint_id: Option<NodeId>, |
1996 | ) -> Option<(Module<'a>, Option<NodeId>)> { | |
5869c6ff | 1997 | if !module.expansion.outer_expn_is_descendant_of(*ctxt) { |
cdc7bbd5 | 1998 | return Some((self.macro_def_scope(ctxt.remove_mark()), None)); |
7cac9316 XL |
1999 | } |
2000 | ||
2001 | if let ModuleKind::Block(..) = module.kind { | |
cdc7bbd5 | 2002 | return Some((module.parent.unwrap().nearest_item_scope(), None)); |
8faf50e0 XL |
2003 | } |
2004 | ||
2005 | // We need to support the next case under a deprecation warning | |
2006 | // ``` | |
2007 | // struct MyStruct; | |
2008 | // ---- begin: this comes from a proc macro derive | |
2009 | // mod implementation_details { | |
2010 | // // Note that `MyStruct` is not in scope here. | |
2011 | // impl SomeTrait for MyStruct { ... } | |
2012 | // } | |
2013 | // ---- end | |
2014 | // ``` | |
2015 | // So we have to fall back to the module's parent during lexical resolution in this case. | |
cdc7bbd5 XL |
2016 | if derive_fallback_lint_id.is_some() { |
2017 | if let Some(parent) = module.parent { | |
2018 | // Inner module is inside the macro, parent module is outside of the macro. | |
2019 | if module.expansion != parent.expansion | |
2020 | && module.expansion.is_descendant_of(parent.expansion) | |
2021 | { | |
2022 | // The macro is a proc macro derive | |
2023 | if let Some(def_id) = module.expansion.expn_data().macro_def_id { | |
2024 | let ext = self.get_macro_by_def_id(def_id); | |
2025 | if ext.builtin_name.is_none() | |
2026 | && ext.macro_kind() == MacroKind::Derive | |
2027 | && parent.expansion.outer_expn_is_descendant_of(*ctxt) | |
2028 | { | |
2029 | return Some((parent, derive_fallback_lint_id)); | |
2030 | } | |
8faf50e0 XL |
2031 | } |
2032 | } | |
7cac9316 | 2033 | } |
1a4d82fc | 2034 | } |
54a0048b SL |
2035 | |
2036 | None | |
1a4d82fc JJ |
2037 | } |
2038 | ||
13cf67c4 XL |
2039 | fn resolve_ident_in_module( |
2040 | &mut self, | |
2041 | module: ModuleOrUniformRoot<'a>, | |
2042 | ident: Ident, | |
2043 | ns: Namespace, | |
416331ca | 2044 | parent_scope: &ParentScope<'a>, |
13cf67c4 | 2045 | record_used: bool, |
dfeec247 | 2046 | path_span: Span, |
13cf67c4 | 2047 | ) -> Result<&'a NameBinding<'a>, Determinacy> { |
dfeec247 XL |
2048 | self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, record_used, path_span) |
2049 | .map_err(|(determinacy, _)| determinacy) | |
13cf67c4 XL |
2050 | } |
2051 | ||
2052 | fn resolve_ident_in_module_ext( | |
2053 | &mut self, | |
2054 | module: ModuleOrUniformRoot<'a>, | |
2055 | mut ident: Ident, | |
2056 | ns: Namespace, | |
416331ca | 2057 | parent_scope: &ParentScope<'a>, |
13cf67c4 | 2058 | record_used: bool, |
dfeec247 | 2059 | path_span: Span, |
13cf67c4 | 2060 | ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> { |
416331ca XL |
2061 | let tmp_parent_scope; |
2062 | let mut adjusted_parent_scope = parent_scope; | |
13cf67c4 | 2063 | match module { |
416331ca | 2064 | ModuleOrUniformRoot::Module(m) => { |
ba9703b0 | 2065 | if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) { |
416331ca | 2066 | tmp_parent_scope = |
e1599b0c | 2067 | ParentScope { module: self.macro_def_scope(def), ..*parent_scope }; |
416331ca | 2068 | adjusted_parent_scope = &tmp_parent_scope; |
13cf67c4 XL |
2069 | } |
2070 | } | |
2071 | ModuleOrUniformRoot::ExternPrelude => { | |
ba9703b0 | 2072 | ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root()); |
13cf67c4 | 2073 | } |
dfeec247 | 2074 | ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => { |
13cf67c4 | 2075 | // No adjustments |
b7449926 | 2076 | } |
7cac9316 | 2077 | } |
ba9703b0 | 2078 | self.resolve_ident_in_module_unadjusted_ext( |
dfeec247 XL |
2079 | module, |
2080 | ident, | |
2081 | ns, | |
2082 | adjusted_parent_scope, | |
2083 | false, | |
2084 | record_used, | |
2085 | path_span, | |
ba9703b0 | 2086 | ) |
7cac9316 XL |
2087 | } |
2088 | ||
8faf50e0 | 2089 | fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> { |
3dfed10e | 2090 | debug!("resolve_crate_root({:?})", ident); |
8faf50e0 | 2091 | let mut ctxt = ident.span.ctxt(); |
dc9dc135 | 2092 | let mark = if ident.name == kw::DollarCrate { |
2c00a5a8 XL |
2093 | // When resolving `$crate` from a `macro_rules!` invoked in a `macro`, |
2094 | // we don't want to pretend that the `macro_rules!` definition is in the `macro` | |
ba9703b0 | 2095 | // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks. |
8faf50e0 XL |
2096 | // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!` |
2097 | // definitions actually produced by `macro` and `macro` definitions produced by | |
2098 | // `macro_rules!`, but at least such configurations are not stable yet. | |
ba9703b0 | 2099 | ctxt = ctxt.normalize_to_macro_rules(); |
3dfed10e XL |
2100 | debug!( |
2101 | "resolve_crate_root: marks={:?}", | |
2102 | ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>() | |
2103 | ); | |
8faf50e0 XL |
2104 | let mut iter = ctxt.marks().into_iter().rev().peekable(); |
2105 | let mut result = None; | |
ba9703b0 | 2106 | // Find the last opaque mark from the end if it exists. |
8faf50e0 XL |
2107 | while let Some(&(mark, transparency)) = iter.peek() { |
2108 | if transparency == Transparency::Opaque { | |
2109 | result = Some(mark); | |
2110 | iter.next(); | |
2111 | } else { | |
2112 | break; | |
2113 | } | |
2114 | } | |
3dfed10e XL |
2115 | debug!( |
2116 | "resolve_crate_root: found opaque mark {:?} {:?}", | |
2117 | result, | |
2118 | result.map(|r| r.expn_data()) | |
2119 | ); | |
ba9703b0 | 2120 | // Then find the last semi-transparent mark from the end if it exists. |
8faf50e0 XL |
2121 | for (mark, transparency) in iter { |
2122 | if transparency == Transparency::SemiTransparent { | |
2123 | result = Some(mark); | |
2124 | } else { | |
2125 | break; | |
2126 | } | |
2127 | } | |
3dfed10e XL |
2128 | debug!( |
2129 | "resolve_crate_root: found semi-transparent mark {:?} {:?}", | |
2130 | result, | |
2131 | result.map(|r| r.expn_data()) | |
2132 | ); | |
8faf50e0 | 2133 | result |
2c00a5a8 | 2134 | } else { |
3dfed10e | 2135 | debug!("resolve_crate_root: not DollarCrate"); |
ba9703b0 | 2136 | ctxt = ctxt.normalize_to_macros_2_0(); |
416331ca | 2137 | ctxt.adjust(ExpnId::root()) |
2c00a5a8 XL |
2138 | }; |
2139 | let module = match mark { | |
7cac9316 | 2140 | Some(def) => self.macro_def_scope(def), |
3dfed10e XL |
2141 | None => { |
2142 | debug!( | |
2143 | "resolve_crate_root({:?}): found no mark (ident.span = {:?})", | |
2144 | ident, ident.span | |
2145 | ); | |
2146 | return self.graph_root; | |
2147 | } | |
7cac9316 | 2148 | }; |
5869c6ff | 2149 | let module = self.get_module(DefId { index: CRATE_DEF_INDEX, ..module.nearest_parent_mod }); |
3dfed10e XL |
2150 | debug!( |
2151 | "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})", | |
2152 | ident, | |
2153 | module, | |
2154 | module.kind.name(), | |
2155 | ident.span | |
2156 | ); | |
2157 | module | |
7cac9316 XL |
2158 | } |
2159 | ||
2160 | fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> { | |
5869c6ff | 2161 | let mut module = self.get_module(module.nearest_parent_mod); |
ba9703b0 | 2162 | while module.span.ctxt().normalize_to_macros_2_0() != *ctxt { |
7cac9316 | 2163 | let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark())); |
5869c6ff | 2164 | module = self.get_module(parent.nearest_parent_mod); |
c30ab7b3 | 2165 | } |
7cac9316 | 2166 | module |
c30ab7b3 SL |
2167 | } |
2168 | ||
416331ca XL |
2169 | fn resolve_path( |
2170 | &mut self, | |
2171 | path: &[Segment], | |
2172 | opt_ns: Option<Namespace>, // `None` indicates a module path in import | |
2173 | parent_scope: &ParentScope<'a>, | |
2174 | record_used: bool, | |
2175 | path_span: Span, | |
2176 | crate_lint: CrateLint, | |
2177 | ) -> PathResult<'a> { | |
2178 | self.resolve_path_with_ribs( | |
dfeec247 XL |
2179 | path, |
2180 | opt_ns, | |
2181 | parent_scope, | |
2182 | record_used, | |
2183 | path_span, | |
2184 | crate_lint, | |
2185 | None, | |
416331ca | 2186 | ) |
b7449926 XL |
2187 | } |
2188 | ||
416331ca XL |
2189 | fn resolve_path_with_ribs( |
2190 | &mut self, | |
2191 | path: &[Segment], | |
2192 | opt_ns: Option<Namespace>, // `None` indicates a module path in import | |
2193 | parent_scope: &ParentScope<'a>, | |
2194 | record_used: bool, | |
2195 | path_span: Span, | |
2196 | crate_lint: CrateLint, | |
2197 | ribs: Option<&PerNS<Vec<Rib<'a>>>>, | |
2198 | ) -> PathResult<'a> { | |
2199 | let mut module = None; | |
2200 | let mut allow_super = true; | |
2201 | let mut second_binding = None; | |
13cf67c4 | 2202 | |
416331ca XL |
2203 | debug!( |
2204 | "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \ | |
2205 | path_span={:?}, crate_lint={:?})", | |
dfeec247 | 2206 | path, opt_ns, record_used, path_span, crate_lint, |
416331ca | 2207 | ); |
69743fb6 | 2208 | |
f035d41b | 2209 | for (i, &Segment { ident, id, has_generic_args: _ }) in path.iter().enumerate() { |
416331ca XL |
2210 | debug!("resolve_path ident {} {:?} {:?}", i, ident, id); |
2211 | let record_segment_res = |this: &mut Self, res| { | |
2212 | if record_used { | |
2213 | if let Some(id) = id { | |
2214 | if !this.partial_res_map.contains_key(&id) { | |
2215 | assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id"); | |
2216 | this.record_partial_res(id, PartialRes::new(res)); | |
69743fb6 | 2217 | } |
69743fb6 | 2218 | } |
13cf67c4 | 2219 | } |
416331ca | 2220 | }; |
1a4d82fc | 2221 | |
416331ca XL |
2222 | let is_last = i == path.len() - 1; |
2223 | let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS }; | |
2224 | let name = ident.name; | |
1a4d82fc | 2225 | |
dfeec247 | 2226 | allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super); |
9fa01778 | 2227 | |
416331ca XL |
2228 | if ns == TypeNS { |
2229 | if allow_super && name == kw::Super { | |
ba9703b0 | 2230 | let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); |
416331ca XL |
2231 | let self_module = match i { |
2232 | 0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)), | |
2233 | _ => match module { | |
2234 | Some(ModuleOrUniformRoot::Module(module)) => Some(module), | |
2235 | _ => None, | |
2236 | }, | |
2237 | }; | |
2238 | if let Some(self_module) = self_module { | |
2239 | if let Some(parent) = self_module.parent { | |
2240 | module = Some(ModuleOrUniformRoot::Module( | |
dfeec247 XL |
2241 | self.resolve_self(&mut ctxt, parent), |
2242 | )); | |
416331ca | 2243 | continue; |
9fa01778 | 2244 | } |
ff7c6d11 | 2245 | } |
dfeec247 | 2246 | let msg = "there are too many leading `super` keywords".to_string(); |
416331ca XL |
2247 | return PathResult::Failed { |
2248 | span: ident.span, | |
2249 | label: msg, | |
2250 | suggestion: None, | |
2251 | is_error_from_last_segment: false, | |
2252 | }; | |
2253 | } | |
2254 | if i == 0 { | |
2255 | if name == kw::SelfLower { | |
ba9703b0 | 2256 | let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); |
416331ca | 2257 | module = Some(ModuleOrUniformRoot::Module( |
dfeec247 XL |
2258 | self.resolve_self(&mut ctxt, parent_scope.module), |
2259 | )); | |
416331ca XL |
2260 | continue; |
2261 | } | |
2262 | if name == kw::PathRoot && ident.span.rust_2018() { | |
2263 | module = Some(ModuleOrUniformRoot::ExternPrelude); | |
2264 | continue; | |
2265 | } | |
dfeec247 | 2266 | if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() { |
416331ca XL |
2267 | // `::a::b` from 2015 macro on 2018 global edition |
2268 | module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude); | |
2269 | continue; | |
2270 | } | |
dfeec247 | 2271 | if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate { |
416331ca | 2272 | // `::a::b`, `crate::a::b` or `$crate::a::b` |
dfeec247 | 2273 | module = Some(ModuleOrUniformRoot::Module(self.resolve_crate_root(ident))); |
416331ca XL |
2274 | continue; |
2275 | } | |
b7449926 | 2276 | } |
1a4d82fc JJ |
2277 | } |
2278 | ||
416331ca XL |
2279 | // Report special messages for path segment keywords in wrong positions. |
2280 | if ident.is_path_segment_keyword() && i != 0 { | |
2281 | let name_str = if name == kw::PathRoot { | |
2282 | "crate root".to_string() | |
2283 | } else { | |
2284 | format!("`{}`", name) | |
2285 | }; | |
2286 | let label = if i == 1 && path[0].ident.name == kw::PathRoot { | |
2287 | format!("global paths cannot start with {}", name_str) | |
2288 | } else { | |
2289 | format!("{} in paths can only be used in start position", name_str) | |
2290 | }; | |
2291 | return PathResult::Failed { | |
2292 | span: ident.span, | |
2293 | label, | |
2294 | suggestion: None, | |
2295 | is_error_from_last_segment: false, | |
2296 | }; | |
1a4d82fc | 2297 | } |
1a4d82fc | 2298 | |
f9f354fc XL |
2299 | enum FindBindingResult<'a> { |
2300 | Binding(Result<&'a NameBinding<'a>, Determinacy>), | |
2301 | PathResult(PathResult<'a>), | |
2302 | } | |
2303 | let find_binding_in_ns = |this: &mut Self, ns| { | |
2304 | let binding = if let Some(module) = module { | |
2305 | this.resolve_ident_in_module( | |
2306 | module, | |
2307 | ident, | |
2308 | ns, | |
2309 | parent_scope, | |
2310 | record_used, | |
2311 | path_span, | |
2312 | ) | |
2313 | } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) { | |
2314 | let scopes = ScopeSet::All(ns, opt_ns.is_none()); | |
2315 | this.early_resolve_ident_in_lexical_scope( | |
2316 | ident, | |
2317 | scopes, | |
2318 | parent_scope, | |
2319 | record_used, | |
2320 | record_used, | |
2321 | path_span, | |
2322 | ) | |
2323 | } else { | |
2324 | let record_used_id = if record_used { | |
2325 | crate_lint.node_id().or(Some(CRATE_NODE_ID)) | |
2326 | } else { | |
2327 | None | |
2328 | }; | |
2329 | match this.resolve_ident_in_lexical_scope( | |
2330 | ident, | |
2331 | ns, | |
2332 | parent_scope, | |
2333 | record_used_id, | |
2334 | path_span, | |
2335 | &ribs.unwrap()[ns], | |
2336 | ) { | |
2337 | // we found a locally-imported or available item/module | |
2338 | Some(LexicalScopeBinding::Item(binding)) => Ok(binding), | |
2339 | // we found a local variable or type param | |
2340 | Some(LexicalScopeBinding::Res(res)) | |
2341 | if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => | |
2342 | { | |
2343 | record_segment_res(this, res); | |
2344 | return FindBindingResult::PathResult(PathResult::NonModule( | |
2345 | PartialRes::with_unresolved_segments(res, path.len() - 1), | |
2346 | )); | |
2347 | } | |
2348 | _ => Err(Determinacy::determined(record_used)), | |
9fa01778 | 2349 | } |
f9f354fc XL |
2350 | }; |
2351 | FindBindingResult::Binding(binding) | |
2352 | }; | |
2353 | let binding = match find_binding_in_ns(self, ns) { | |
2354 | FindBindingResult::PathResult(x) => return x, | |
2355 | FindBindingResult::Binding(binding) => binding, | |
416331ca | 2356 | }; |
416331ca XL |
2357 | match binding { |
2358 | Ok(binding) => { | |
2359 | if i == 1 { | |
2360 | second_binding = Some(binding); | |
1a4d82fc | 2361 | } |
416331ca XL |
2362 | let res = binding.res(); |
2363 | let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res); | |
2364 | if let Some(next_module) = binding.module() { | |
2365 | module = Some(ModuleOrUniformRoot::Module(next_module)); | |
2366 | record_segment_res(self, res); | |
2367 | } else if res == Res::ToolMod && i + 1 != path.len() { | |
2368 | if binding.is_import() { | |
dfeec247 XL |
2369 | self.session |
2370 | .struct_span_err( | |
2371 | ident.span, | |
2372 | "cannot use a tool module through an import", | |
2373 | ) | |
2374 | .span_note(binding.span, "the tool module imported here") | |
2375 | .emit(); | |
416331ca XL |
2376 | } |
2377 | let res = Res::NonMacroAttr(NonMacroAttrKind::Tool); | |
2378 | return PathResult::NonModule(PartialRes::new(res)); | |
2379 | } else if res == Res::Err { | |
2380 | return PathResult::NonModule(PartialRes::new(Res::Err)); | |
2381 | } else if opt_ns.is_some() && (is_last || maybe_assoc) { | |
2382 | self.lint_if_path_starts_with_module( | |
2383 | crate_lint, | |
2384 | path, | |
2385 | path_span, | |
2386 | second_binding, | |
2387 | ); | |
2388 | return PathResult::NonModule(PartialRes::with_unresolved_segments( | |
dfeec247 XL |
2389 | res, |
2390 | path.len() - i - 1, | |
416331ca | 2391 | )); |
32a655c1 | 2392 | } else { |
416331ca XL |
2393 | let label = format!( |
2394 | "`{}` is {} {}, not a module", | |
2395 | ident, | |
2396 | res.article(), | |
2397 | res.descr(), | |
2398 | ); | |
92a42be0 | 2399 | |
416331ca XL |
2400 | return PathResult::Failed { |
2401 | span: ident.span, | |
2402 | label, | |
2403 | suggestion: None, | |
2404 | is_error_from_last_segment: is_last, | |
2405 | }; | |
32a655c1 SL |
2406 | } |
2407 | } | |
416331ca XL |
2408 | Err(Undetermined) => return PathResult::Indeterminate, |
2409 | Err(Determined) => { | |
2410 | if let Some(ModuleOrUniformRoot::Module(module)) = module { | |
2411 | if opt_ns.is_some() && !module.is_normal() { | |
2412 | return PathResult::NonModule(PartialRes::with_unresolved_segments( | |
dfeec247 XL |
2413 | module.res().unwrap(), |
2414 | path.len() - i, | |
416331ca | 2415 | )); |
32a655c1 | 2416 | } |
32a655c1 | 2417 | } |
416331ca XL |
2418 | let module_res = match module { |
2419 | Some(ModuleOrUniformRoot::Module(module)) => module.res(), | |
2420 | _ => None, | |
2421 | }; | |
2422 | let (label, suggestion) = if module_res == self.graph_root.res() { | |
29967ef6 | 2423 | let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _)); |
1b1a35ee XL |
2424 | // Don't look up import candidates if this is a speculative resolve |
2425 | let mut candidates = if record_used { | |
2426 | self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod) | |
2427 | } else { | |
2428 | Vec::new() | |
2429 | }; | |
416331ca | 2430 | candidates.sort_by_cached_key(|c| { |
e74abb32 | 2431 | (c.path.segments.len(), pprust::path_to_string(&c.path)) |
416331ca XL |
2432 | }); |
2433 | if let Some(candidate) = candidates.get(0) { | |
2434 | ( | |
2435 | String::from("unresolved import"), | |
2436 | Some(( | |
e74abb32 | 2437 | vec![(ident.span, pprust::path_to_string(&candidate.path))], |
416331ca XL |
2438 | String::from("a similar path exists"), |
2439 | Applicability::MaybeIncorrect, | |
2440 | )), | |
2441 | ) | |
6a06907d | 2442 | } else if self.session.edition() == Edition::Edition2015 { |
ba9703b0 | 2443 | (format!("maybe a missing crate `{}`?", ident), None) |
6a06907d XL |
2444 | } else { |
2445 | (format!("could not find `{}` in the crate root", ident), None) | |
dc9dc135 | 2446 | } |
416331ca | 2447 | } else if i == 0 { |
1b1a35ee XL |
2448 | if ident |
2449 | .name | |
5869c6ff XL |
2450 | .as_str() |
2451 | .chars() | |
2452 | .next() | |
2453 | .map_or(false, |c| c.is_ascii_uppercase()) | |
1b1a35ee | 2454 | { |
cdc7bbd5 XL |
2455 | // Check whether the name refers to an item in the value namespace. |
2456 | let suggestion = if ribs.is_some() { | |
2457 | let match_span = match self.resolve_ident_in_lexical_scope( | |
2458 | ident, | |
2459 | ValueNS, | |
2460 | parent_scope, | |
2461 | None, | |
2462 | path_span, | |
2463 | &ribs.unwrap()[ValueNS], | |
2464 | ) { | |
2465 | // Name matches a local variable. For example: | |
2466 | // ``` | |
2467 | // fn f() { | |
2468 | // let Foo: &str = ""; | |
2469 | // println!("{}", Foo::Bar); // Name refers to local | |
2470 | // // variable `Foo`. | |
2471 | // } | |
2472 | // ``` | |
2473 | Some(LexicalScopeBinding::Res(Res::Local(id))) => { | |
2474 | Some(*self.pat_span_map.get(&id).unwrap()) | |
2475 | } | |
2476 | ||
2477 | // Name matches item from a local name binding | |
2478 | // created by `use` declaration. For example: | |
2479 | // ``` | |
2480 | // pub Foo: &str = ""; | |
2481 | // | |
2482 | // mod submod { | |
2483 | // use super::Foo; | |
2484 | // println!("{}", Foo::Bar); // Name refers to local | |
2485 | // // binding `Foo`. | |
2486 | // } | |
2487 | // ``` | |
2488 | Some(LexicalScopeBinding::Item(name_binding)) => { | |
2489 | Some(name_binding.span) | |
2490 | } | |
2491 | _ => None, | |
2492 | }; | |
2493 | ||
2494 | if let Some(span) = match_span { | |
2495 | Some(( | |
2496 | vec![(span, String::from(""))], | |
2497 | format!("`{}` is defined here, but is not a type", ident), | |
2498 | Applicability::MaybeIncorrect, | |
2499 | )) | |
2500 | } else { | |
2501 | None | |
2502 | } | |
2503 | } else { | |
2504 | None | |
2505 | }; | |
2506 | ||
2507 | (format!("use of undeclared type `{}`", ident), suggestion) | |
1b1a35ee XL |
2508 | } else { |
2509 | (format!("use of undeclared crate or module `{}`", ident), None) | |
2510 | } | |
416331ca | 2511 | } else { |
5869c6ff | 2512 | let parent = path[i - 1].ident.name; |
6a06907d XL |
2513 | let parent = match parent { |
2514 | // ::foo is mounted at the crate root for 2015, and is the extern | |
2515 | // prelude for 2018+ | |
2516 | kw::PathRoot if self.session.edition() > Edition::Edition2015 => { | |
2517 | "the list of imported crates".to_owned() | |
2518 | } | |
2519 | kw::PathRoot | kw::Crate => "the crate root".to_owned(), | |
2520 | _ => { | |
2521 | format!("`{}`", parent) | |
2522 | } | |
5869c6ff XL |
2523 | }; |
2524 | ||
2525 | let mut msg = format!("could not find `{}` in {}", ident, parent); | |
f9f354fc XL |
2526 | if ns == TypeNS || ns == ValueNS { |
2527 | let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS }; | |
2528 | if let FindBindingResult::Binding(Ok(binding)) = | |
2529 | find_binding_in_ns(self, ns_to_try) | |
2530 | { | |
2531 | let mut found = |what| { | |
2532 | msg = format!( | |
5869c6ff | 2533 | "expected {}, found {} `{}` in {}", |
f9f354fc XL |
2534 | ns.descr(), |
2535 | what, | |
2536 | ident, | |
5869c6ff | 2537 | parent |
f9f354fc XL |
2538 | ) |
2539 | }; | |
2540 | if binding.module().is_some() { | |
2541 | found("module") | |
2542 | } else { | |
2543 | match binding.res() { | |
2544 | def::Res::<NodeId>::Def(kind, id) => found(kind.descr(id)), | |
2545 | _ => found(ns_to_try.descr()), | |
2546 | } | |
2547 | } | |
2548 | }; | |
2549 | } | |
2550 | (msg, None) | |
416331ca XL |
2551 | }; |
2552 | return PathResult::Failed { | |
2553 | span: ident.span, | |
2554 | label, | |
2555 | suggestion, | |
2556 | is_error_from_last_segment: is_last, | |
2557 | }; | |
b7449926 | 2558 | } |
32a655c1 | 2559 | } |
8bb4bdeb | 2560 | } |
32a655c1 | 2561 | |
416331ca | 2562 | self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding); |
a7813a04 | 2563 | |
416331ca XL |
2564 | PathResult::Module(match module { |
2565 | Some(module) => module, | |
2566 | None if path.is_empty() => ModuleOrUniformRoot::CurrentScope, | |
2567 | _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path), | |
2568 | }) | |
1a4d82fc JJ |
2569 | } |
2570 | ||
416331ca | 2571 | fn lint_if_path_starts_with_module( |
e74abb32 | 2572 | &mut self, |
416331ca XL |
2573 | crate_lint: CrateLint, |
2574 | path: &[Segment], | |
2575 | path_span: Span, | |
2576 | second_binding: Option<&NameBinding<'_>>, | |
2577 | ) { | |
2578 | let (diag_id, diag_span) = match crate_lint { | |
2579 | CrateLint::No => return, | |
2580 | CrateLint::SimplePath(id) => (id, path_span), | |
2581 | CrateLint::UsePath { root_id, root_span } => (root_id, root_span), | |
2582 | CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span), | |
2583 | }; | |
1a4d82fc | 2584 | |
416331ca XL |
2585 | let first_name = match path.get(0) { |
2586 | // In the 2018 edition this lint is a hard error, so nothing to do | |
2587 | Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name, | |
2588 | _ => return, | |
2589 | }; | |
1a4d82fc | 2590 | |
416331ca XL |
2591 | // We're only interested in `use` paths which should start with |
2592 | // `{{root}}` currently. | |
2593 | if first_name != kw::PathRoot { | |
dfeec247 | 2594 | return; |
54a0048b | 2595 | } |
1a4d82fc | 2596 | |
416331ca XL |
2597 | match path.get(1) { |
2598 | // If this import looks like `crate::...` it's already good | |
2599 | Some(Segment { ident, .. }) if ident.name == kw::Crate => return, | |
2600 | // Otherwise go below to see if it's an extern crate | |
2601 | Some(_) => {} | |
2602 | // If the path has length one (and it's `PathRoot` most likely) | |
2603 | // then we don't know whether we're gonna be importing a crate or an | |
2604 | // item in our crate. Defer this lint to elsewhere | |
2605 | None => return, | |
32a655c1 | 2606 | } |
1a4d82fc | 2607 | |
416331ca XL |
2608 | // If the first element of our path was actually resolved to an |
2609 | // `ExternCrate` (also used for `crate::...`) then no need to issue a | |
2610 | // warning, this looks all good! | |
2611 | if let Some(binding) = second_binding { | |
74b04a01 XL |
2612 | if let NameBindingKind::Import { import, .. } = binding.kind { |
2613 | // Careful: we still want to rewrite paths from renamed extern crates. | |
2614 | if let ImportKind::ExternCrate { source: None, .. } = import.kind { | |
dfeec247 | 2615 | return; |
416331ca | 2616 | } |
1a4d82fc JJ |
2617 | } |
2618 | } | |
2619 | ||
dfeec247 | 2620 | let diag = BuiltinLintDiagnostics::AbsPathWithModule(diag_span); |
e74abb32 | 2621 | self.lint_buffer.buffer_lint_with_diagnostic( |
416331ca | 2622 | lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, |
dfeec247 XL |
2623 | diag_id, |
2624 | diag_span, | |
416331ca | 2625 | "absolute paths must start with `self`, `super`, \ |
dfeec247 XL |
2626 | `crate`, or an external crate name in the 2018 edition", |
2627 | diag, | |
2628 | ); | |
1a4d82fc JJ |
2629 | } |
2630 | ||
416331ca XL |
2631 | // Validate a local resolution (from ribs). |
2632 | fn validate_res_from_ribs( | |
2633 | &mut self, | |
2634 | rib_index: usize, | |
e74abb32 | 2635 | rib_ident: Ident, |
1b1a35ee | 2636 | mut res: Res, |
416331ca XL |
2637 | record_used: bool, |
2638 | span: Span, | |
5869c6ff | 2639 | original_rib_ident_def: Ident, |
416331ca XL |
2640 | all_ribs: &[Rib<'a>], |
2641 | ) -> Res { | |
fc512014 | 2642 | const CG_BUG_STR: &str = "min_const_generics resolve check didn't stop compilation"; |
416331ca XL |
2643 | debug!("validate_res_from_ribs({:?})", res); |
2644 | let ribs = &all_ribs[rib_index + 1..]; | |
2645 | ||
cdc7bbd5 XL |
2646 | // An invalid forward use of a generic parameter from a previous default. |
2647 | if let ForwardGenericParamBanRibKind = all_ribs[rib_index].kind { | |
416331ca | 2648 | if record_used { |
e74abb32 | 2649 | let res_error = if rib_ident.name == kw::SelfUpper { |
136023e0 | 2650 | ResolutionError::SelfInGenericParamDefault |
e74abb32 | 2651 | } else { |
17df50a5 | 2652 | ResolutionError::ForwardDeclaredGenericParam |
e74abb32 XL |
2653 | }; |
2654 | self.report_error(span, res_error); | |
32a655c1 | 2655 | } |
416331ca XL |
2656 | assert_eq!(res, Res::Err); |
2657 | return Res::Err; | |
32a655c1 | 2658 | } |
32a655c1 | 2659 | |
416331ca XL |
2660 | match res { |
2661 | Res::Local(_) => { | |
2662 | use ResolutionError::*; | |
2663 | let mut res_err = None; | |
48663c56 | 2664 | |
416331ca XL |
2665 | for rib in ribs { |
2666 | match rib.kind { | |
dfeec247 | 2667 | NormalRibKind |
f035d41b | 2668 | | ClosureOrAsyncRibKind |
dfeec247 XL |
2669 | | ModuleRibKind(..) |
2670 | | MacroDefinition(..) | |
cdc7bbd5 | 2671 | | ForwardGenericParamBanRibKind => { |
416331ca | 2672 | // Nothing to do. Continue. |
b7449926 | 2673 | } |
e74abb32 | 2674 | ItemRibKind(_) | FnItemRibKind | AssocItemRibKind => { |
416331ca XL |
2675 | // This was an attempt to access an upvar inside a |
2676 | // named function item. This is not allowed, so we | |
2677 | // report an error. | |
2678 | if record_used { | |
2679 | // We don't immediately trigger a resolve error, because | |
2680 | // we want certain other resolution errors (namely those | |
2681 | // emitted for `ConstantItemRibKind` below) to take | |
2682 | // precedence. | |
2683 | res_err = Some(CannotCaptureDynamicEnvironmentInFnItem); | |
2684 | } | |
2685 | } | |
5869c6ff | 2686 | ConstantItemRibKind(_, item) => { |
416331ca XL |
2687 | // Still doesn't deal with upvars |
2688 | if record_used { | |
5869c6ff XL |
2689 | let (span, resolution_error) = |
2690 | if let Some((ident, constant_item_kind)) = item { | |
2691 | let kind_str = match constant_item_kind { | |
2692 | ConstantItemKind::Const => "const", | |
2693 | ConstantItemKind::Static => "static", | |
2694 | }; | |
2695 | ( | |
2696 | span, | |
2697 | AttemptToUseNonConstantValueInConstant( | |
2698 | ident, "let", kind_str, | |
2699 | ), | |
2700 | ) | |
2701 | } else { | |
2702 | ( | |
2703 | rib_ident.span, | |
2704 | AttemptToUseNonConstantValueInConstant( | |
2705 | original_rib_ident_def, | |
2706 | "const", | |
2707 | "let", | |
2708 | ), | |
2709 | ) | |
2710 | }; | |
2711 | self.report_error(span, resolution_error); | |
416331ca XL |
2712 | } |
2713 | return Res::Err; | |
7453a54e | 2714 | } |
3dfed10e XL |
2715 | ConstParamTyRibKind => { |
2716 | if record_used { | |
2717 | self.report_error(span, ParamInTyOfConstParam(rib_ident.name)); | |
2718 | } | |
2719 | return Res::Err; | |
2720 | } | |
7453a54e SL |
2721 | } |
2722 | } | |
416331ca | 2723 | if let Some(res_err) = res_err { |
dfeec247 XL |
2724 | self.report_error(span, res_err); |
2725 | return Res::Err; | |
416331ca XL |
2726 | } |
2727 | } | |
2728 | Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => { | |
2729 | for rib in ribs { | |
cdc7bbd5 | 2730 | let has_generic_params: HasGenericParams = match rib.kind { |
dfeec247 | 2731 | NormalRibKind |
f035d41b | 2732 | | ClosureOrAsyncRibKind |
dfeec247 XL |
2733 | | AssocItemRibKind |
2734 | | ModuleRibKind(..) | |
cdc7bbd5 XL |
2735 | | MacroDefinition(..) |
2736 | | ForwardGenericParamBanRibKind => { | |
416331ca | 2737 | // Nothing to do. Continue. |
e74abb32 | 2738 | continue; |
416331ca | 2739 | } |
3dfed10e | 2740 | |
5869c6ff XL |
2741 | ConstantItemRibKind(trivial, _) => { |
2742 | let features = self.session.features_untracked(); | |
3dfed10e | 2743 | // HACK(min_const_generics): We currently only allow `N` or `{ N }`. |
5869c6ff XL |
2744 | if !(trivial |
2745 | || features.const_generics | |
2746 | || features.lazy_normalization_consts) | |
2747 | { | |
1b1a35ee XL |
2748 | // HACK(min_const_generics): If we encounter `Self` in an anonymous constant |
2749 | // we can't easily tell if it's generic at this stage, so we instead remember | |
2750 | // this and then enforce the self type to be concrete later on. | |
2751 | if let Res::SelfTy(trait_def, Some((impl_def, _))) = res { | |
2752 | res = Res::SelfTy(trait_def, Some((impl_def, true))); | |
2753 | } else { | |
2754 | if record_used { | |
2755 | self.report_error( | |
2756 | span, | |
2757 | ResolutionError::ParamInNonTrivialAnonConst { | |
2758 | name: rib_ident.name, | |
2759 | is_type: true, | |
2760 | }, | |
2761 | ); | |
2762 | } | |
fc512014 XL |
2763 | |
2764 | self.session.delay_span_bug(span, CG_BUG_STR); | |
1b1a35ee | 2765 | return Res::Err; |
3dfed10e | 2766 | } |
3dfed10e XL |
2767 | } |
2768 | ||
cdc7bbd5 | 2769 | continue; |
3dfed10e XL |
2770 | } |
2771 | ||
e74abb32 XL |
2772 | // This was an attempt to use a type parameter outside its scope. |
2773 | ItemRibKind(has_generic_params) => has_generic_params, | |
2774 | FnItemRibKind => HasGenericParams::Yes, | |
3dfed10e XL |
2775 | ConstParamTyRibKind => { |
2776 | if record_used { | |
2777 | self.report_error( | |
2778 | span, | |
2779 | ResolutionError::ParamInTyOfConstParam(rib_ident.name), | |
2780 | ); | |
2781 | } | |
2782 | return Res::Err; | |
2783 | } | |
e74abb32 XL |
2784 | }; |
2785 | ||
2786 | if record_used { | |
dfeec247 XL |
2787 | self.report_error( |
2788 | span, | |
2789 | ResolutionError::GenericParamsFromOuterFunction( | |
2790 | res, | |
2791 | has_generic_params, | |
2792 | ), | |
2793 | ); | |
7453a54e | 2794 | } |
e74abb32 | 2795 | return Res::Err; |
7453a54e | 2796 | } |
b7449926 | 2797 | } |
416331ca XL |
2798 | Res::Def(DefKind::ConstParam, _) => { |
2799 | let mut ribs = ribs.iter().peekable(); | |
2800 | if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() { | |
2801 | // When declaring const parameters inside function signatures, the first rib | |
2802 | // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it | |
2803 | // (spuriously) conflicting with the const param. | |
2804 | ribs.next(); | |
ff7c6d11 | 2805 | } |
3dfed10e | 2806 | |
416331ca | 2807 | for rib in ribs { |
e74abb32 | 2808 | let has_generic_params = match rib.kind { |
3dfed10e XL |
2809 | NormalRibKind |
2810 | | ClosureOrAsyncRibKind | |
2811 | | AssocItemRibKind | |
2812 | | ModuleRibKind(..) | |
cdc7bbd5 XL |
2813 | | MacroDefinition(..) |
2814 | | ForwardGenericParamBanRibKind => continue, | |
3dfed10e | 2815 | |
5869c6ff XL |
2816 | ConstantItemRibKind(trivial, _) => { |
2817 | let features = self.session.features_untracked(); | |
3dfed10e | 2818 | // HACK(min_const_generics): We currently only allow `N` or `{ N }`. |
5869c6ff XL |
2819 | if !(trivial |
2820 | || features.const_generics | |
2821 | || features.lazy_normalization_consts) | |
2822 | { | |
3dfed10e XL |
2823 | if record_used { |
2824 | self.report_error( | |
2825 | span, | |
1b1a35ee XL |
2826 | ResolutionError::ParamInNonTrivialAnonConst { |
2827 | name: rib_ident.name, | |
2828 | is_type: false, | |
2829 | }, | |
3dfed10e XL |
2830 | ); |
2831 | } | |
fc512014 XL |
2832 | |
2833 | self.session.delay_span_bug(span, CG_BUG_STR); | |
3dfed10e XL |
2834 | return Res::Err; |
2835 | } | |
2836 | ||
cdc7bbd5 | 2837 | continue; |
3dfed10e XL |
2838 | } |
2839 | ||
e74abb32 XL |
2840 | ItemRibKind(has_generic_params) => has_generic_params, |
2841 | FnItemRibKind => HasGenericParams::Yes, | |
3dfed10e XL |
2842 | ConstParamTyRibKind => { |
2843 | if record_used { | |
2844 | self.report_error( | |
2845 | span, | |
2846 | ResolutionError::ParamInTyOfConstParam(rib_ident.name), | |
2847 | ); | |
2848 | } | |
2849 | return Res::Err; | |
2850 | } | |
e74abb32 XL |
2851 | }; |
2852 | ||
2853 | // This was an attempt to use a const parameter outside its scope. | |
2854 | if record_used { | |
dfeec247 XL |
2855 | self.report_error( |
2856 | span, | |
2857 | ResolutionError::GenericParamsFromOuterFunction( | |
2858 | res, | |
2859 | has_generic_params, | |
2860 | ), | |
2861 | ); | |
ff7c6d11 | 2862 | } |
e74abb32 | 2863 | return Res::Err; |
ff7c6d11 | 2864 | } |
416331ca XL |
2865 | } |
2866 | _ => {} | |
ff7c6d11 | 2867 | } |
416331ca | 2868 | res |
ff7c6d11 XL |
2869 | } |
2870 | ||
48663c56 XL |
2871 | fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) { |
2872 | debug!("(recording res) recording {:?} for {}", resolution, node_id); | |
2873 | if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) { | |
a7813a04 | 2874 | panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution); |
1a4d82fc JJ |
2875 | } |
2876 | } | |
2877 | ||
cdc7bbd5 XL |
2878 | fn record_pat_span(&mut self, node: NodeId, span: Span) { |
2879 | debug!("(recording pat) recording {:?} for {:?}", node, span); | |
2880 | self.pat_span_map.insert(node, span); | |
2881 | } | |
2882 | ||
9e0c209e | 2883 | fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool { |
5869c6ff | 2884 | vis.is_accessible_from(module.nearest_parent_mod, self) |
54a0048b SL |
2885 | } |
2886 | ||
4462d4a0 XL |
2887 | fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) { |
2888 | if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) { | |
2889 | if !ptr::eq(module, old_module) { | |
2890 | span_bug!(binding.span, "parent module is reset for binding"); | |
2891 | } | |
2892 | } | |
2893 | } | |
2894 | ||
ba9703b0 | 2895 | fn disambiguate_macro_rules_vs_modularized( |
4462d4a0 | 2896 | &self, |
ba9703b0 XL |
2897 | macro_rules: &'a NameBinding<'a>, |
2898 | modularized: &'a NameBinding<'a>, | |
4462d4a0 | 2899 | ) -> bool { |
ba9703b0 | 2900 | // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules" |
4462d4a0 XL |
2901 | // is disambiguated to mitigate regressions from macro modularization. |
2902 | // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general. | |
dfeec247 | 2903 | match ( |
ba9703b0 XL |
2904 | self.binding_parent_modules.get(&PtrKey(macro_rules)), |
2905 | self.binding_parent_modules.get(&PtrKey(modularized)), | |
dfeec247 | 2906 | ) { |
ba9703b0 | 2907 | (Some(macro_rules), Some(modularized)) => { |
5869c6ff | 2908 | macro_rules.nearest_parent_mod == modularized.nearest_parent_mod |
ba9703b0 | 2909 | && modularized.is_ancestor_of(macro_rules) |
dfeec247 | 2910 | } |
4462d4a0 XL |
2911 | _ => false, |
2912 | } | |
2913 | } | |
2914 | ||
b7449926 XL |
2915 | fn report_errors(&mut self, krate: &Crate) { |
2916 | self.report_with_use_injections(krate); | |
b7449926 XL |
2917 | |
2918 | for &(span_use, span_def) in &self.macro_expanded_macro_export_errors { | |
2919 | let msg = "macro-expanded `macro_export` macros from the current crate \ | |
2920 | cannot be referred to by absolute paths"; | |
e74abb32 | 2921 | self.lint_buffer.buffer_lint_with_diagnostic( |
b7449926 | 2922 | lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS, |
dfeec247 XL |
2923 | CRATE_NODE_ID, |
2924 | span_use, | |
2925 | msg, | |
2926 | BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def), | |
b7449926 XL |
2927 | ); |
2928 | } | |
2929 | ||
13cf67c4 XL |
2930 | for ambiguity_error in &self.ambiguity_errors { |
2931 | self.report_ambiguity_error(ambiguity_error); | |
9e0c209e SL |
2932 | } |
2933 | ||
13cf67c4 | 2934 | let mut reported_spans = FxHashSet::default(); |
dfeec247 XL |
2935 | for error in &self.privacy_errors { |
2936 | if reported_spans.insert(error.dedup_span) { | |
2937 | self.report_privacy_error(error); | |
0bf4aa26 | 2938 | } |
54a0048b SL |
2939 | } |
2940 | } | |
2941 | ||
3b2f2976 | 2942 | fn report_with_use_injections(&mut self, krate: &Crate) { |
f035d41b | 2943 | for UseError { mut err, candidates, def_id, instead, suggestion } in |
dfeec247 XL |
2944 | self.use_injections.drain(..) |
2945 | { | |
f035d41b XL |
2946 | let (span, found_use) = if let Some(def_id) = def_id.as_local() { |
2947 | UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id]) | |
2948 | } else { | |
2949 | (None, false) | |
2950 | }; | |
3b2f2976 | 2951 | if !candidates.is_empty() { |
f035d41b | 2952 | diagnostics::show_candidates(&mut err, span, &candidates, instead, found_use); |
ba9703b0 | 2953 | } else if let Some((span, msg, sugg, appl)) = suggestion { |
dfeec247 XL |
2954 | err.span_suggestion(span, msg, sugg, appl); |
2955 | } | |
3b2f2976 XL |
2956 | err.emit(); |
2957 | } | |
2958 | } | |
2959 | ||
dfeec247 XL |
2960 | fn report_conflict<'b>( |
2961 | &mut self, | |
2962 | parent: Module<'_>, | |
2963 | ident: Ident, | |
2964 | ns: Namespace, | |
2965 | new_binding: &NameBinding<'b>, | |
2966 | old_binding: &NameBinding<'b>, | |
2967 | ) { | |
54a0048b | 2968 | // Error on the second of two conflicting names |
ea8adc8c | 2969 | if old_binding.span.lo() > new_binding.span.lo() { |
041b39d2 | 2970 | return self.report_conflict(parent, ident, ns, old_binding, new_binding); |
54a0048b SL |
2971 | } |
2972 | ||
9e0c209e | 2973 | let container = match parent.kind { |
f9f354fc | 2974 | ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id().unwrap()), |
9e0c209e | 2975 | ModuleKind::Block(..) => "block", |
54a0048b SL |
2976 | }; |
2977 | ||
041b39d2 XL |
2978 | let old_noun = match old_binding.is_import() { |
2979 | true => "import", | |
2980 | false => "definition", | |
54a0048b SL |
2981 | }; |
2982 | ||
041b39d2 XL |
2983 | let new_participle = match new_binding.is_import() { |
2984 | true => "imported", | |
2985 | false => "defined", | |
2986 | }; | |
2987 | ||
ba9703b0 XL |
2988 | let (name, span) = |
2989 | (ident.name, self.session.source_map().guess_head_span(new_binding.span)); | |
476ff2be SL |
2990 | |
2991 | if let Some(s) = self.name_already_seen.get(&name) { | |
2992 | if s == &span { | |
2993 | return; | |
2994 | } | |
2995 | } | |
2996 | ||
041b39d2 XL |
2997 | let old_kind = match (ns, old_binding.module()) { |
2998 | (ValueNS, _) => "value", | |
2999 | (MacroNS, _) => "macro", | |
3000 | (TypeNS, _) if old_binding.is_extern_crate() => "extern crate", | |
3001 | (TypeNS, Some(module)) if module.is_normal() => "module", | |
3002 | (TypeNS, Some(module)) if module.is_trait() => "trait", | |
3003 | (TypeNS, _) => "type", | |
54a0048b SL |
3004 | }; |
3005 | ||
041b39d2 XL |
3006 | let msg = format!("the name `{}` is defined multiple times", name); |
3007 | ||
3008 | let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) { | |
32a655c1 | 3009 | (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg), |
041b39d2 | 3010 | (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() { |
32a655c1 SL |
3011 | true => struct_span_err!(self.session, span, E0254, "{}", msg), |
3012 | false => struct_span_err!(self.session, span, E0260, "{}", msg), | |
9e0c209e | 3013 | }, |
041b39d2 | 3014 | _ => match (old_binding.is_import(), new_binding.is_import()) { |
32a655c1 SL |
3015 | (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg), |
3016 | (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg), | |
3017 | _ => struct_span_err!(self.session, span, E0255, "{}", msg), | |
54a0048b SL |
3018 | }, |
3019 | }; | |
3020 | ||
dfeec247 XL |
3021 | err.note(&format!( |
3022 | "`{}` must be defined only once in the {} namespace of this {}", | |
3023 | name, | |
3024 | ns.descr(), | |
3025 | container | |
3026 | )); | |
041b39d2 XL |
3027 | |
3028 | err.span_label(span, format!("`{}` re{} here", name, new_participle)); | |
9fa01778 | 3029 | err.span_label( |
ba9703b0 | 3030 | self.session.source_map().guess_head_span(old_binding.span), |
9fa01778 XL |
3031 | format!("previous {} of the {} `{}` here", old_noun, old_kind, name), |
3032 | ); | |
041b39d2 | 3033 | |
abe05a73 | 3034 | // See https://github.com/rust-lang/rust/issues/32354 |
9fa01778 | 3035 | use NameBindingKind::Import; |
74b04a01 | 3036 | let import = match (&new_binding.kind, &old_binding.kind) { |
9fa01778 XL |
3037 | // If there are two imports where one or both have attributes then prefer removing the |
3038 | // import without attributes. | |
74b04a01 | 3039 | (Import { import: new, .. }, Import { import: old, .. }) |
dfeec247 XL |
3040 | if { |
3041 | !new_binding.span.is_dummy() | |
3042 | && !old_binding.span.is_dummy() | |
3043 | && (new.has_attributes || old.has_attributes) | |
3044 | } => | |
3045 | { | |
9fa01778 XL |
3046 | if old.has_attributes { |
3047 | Some((new, new_binding.span, true)) | |
3048 | } else { | |
3049 | Some((old, old_binding.span, true)) | |
3050 | } | |
dfeec247 | 3051 | } |
9fa01778 | 3052 | // Otherwise prioritize the new binding. |
74b04a01 XL |
3053 | (Import { import, .. }, other) if !new_binding.span.is_dummy() => { |
3054 | Some((import, new_binding.span, other.is_import())) | |
dfeec247 | 3055 | } |
74b04a01 XL |
3056 | (other, Import { import, .. }) if !old_binding.span.is_dummy() => { |
3057 | Some((import, old_binding.span, other.is_import())) | |
dfeec247 | 3058 | } |
0731742a XL |
3059 | _ => None, |
3060 | }; | |
abe05a73 | 3061 | |
9fa01778 | 3062 | // Check if the target of the use for both bindings is the same. |
48663c56 | 3063 | let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id(); |
9fa01778 | 3064 | let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy(); |
dfeec247 | 3065 | let from_item = |
5869c6ff | 3066 | self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item); |
9fa01778 XL |
3067 | // Only suggest removing an import if both bindings are to the same def, if both spans |
3068 | // aren't dummy spans. Further, if both bindings are imports, then the ident must have | |
3069 | // been introduced by a item. | |
dfeec247 XL |
3070 | let should_remove_import = duplicate |
3071 | && !has_dummy_span | |
3072 | && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item); | |
9fa01778 | 3073 | |
74b04a01 XL |
3074 | match import { |
3075 | Some((import, span, true)) if should_remove_import && import.is_nested() => { | |
3076 | self.add_suggestion_for_duplicate_nested_use(&mut err, import, span) | |
dfeec247 | 3077 | } |
74b04a01 | 3078 | Some((import, _, true)) if should_remove_import && !import.is_glob() => { |
9fa01778 XL |
3079 | // Simple case - remove the entire import. Due to the above match arm, this can |
3080 | // only be a single use so just remove it entirely. | |
532ac7d7 | 3081 | err.tool_only_span_suggestion( |
74b04a01 | 3082 | import.use_span_with_attributes, |
9fa01778 XL |
3083 | "remove unnecessary import", |
3084 | String::new(), | |
3085 | Applicability::MaybeIncorrect, | |
3086 | ); | |
dfeec247 | 3087 | } |
74b04a01 XL |
3088 | Some((import, span, _)) => { |
3089 | self.add_suggestion_for_rename_of_use(&mut err, name, import, span) | |
dfeec247 XL |
3090 | } |
3091 | _ => {} | |
9fa01778 XL |
3092 | } |
3093 | ||
3094 | err.emit(); | |
3095 | self.name_already_seen.insert(name, span); | |
3096 | } | |
3097 | ||
3098 | /// This function adds a suggestion to change the binding name of a new import that conflicts | |
3099 | /// with an existing import. | |
3100 | /// | |
f9f354fc | 3101 | /// ```text,ignore (diagnostic) |
9fa01778 XL |
3102 | /// help: you can use `as` to change the binding name of the import |
3103 | /// | | |
3104 | /// LL | use foo::bar as other_bar; | |
3105 | /// | ^^^^^^^^^^^^^^^^^^^^^ | |
3106 | /// ``` | |
3107 | fn add_suggestion_for_rename_of_use( | |
3108 | &self, | |
3109 | err: &mut DiagnosticBuilder<'_>, | |
f9f354fc | 3110 | name: Symbol, |
74b04a01 | 3111 | import: &Import<'_>, |
9fa01778 XL |
3112 | binding_span: Span, |
3113 | ) { | |
3114 | let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() { | |
3115 | format!("Other{}", name) | |
3116 | } else { | |
3117 | format!("other_{}", name) | |
3118 | }; | |
3119 | ||
3120 | let mut suggestion = None; | |
74b04a01 XL |
3121 | match import.kind { |
3122 | ImportKind::Single { type_ns_only: true, .. } => { | |
dfeec247 XL |
3123 | suggestion = Some(format!("self as {}", suggested_name)) |
3124 | } | |
74b04a01 | 3125 | ImportKind::Single { source, .. } => { |
dfeec247 XL |
3126 | if let Some(pos) = |
3127 | source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize) | |
3128 | { | |
3129 | if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) { | |
9fa01778 XL |
3130 | if pos <= snippet.len() { |
3131 | suggestion = Some(format!( | |
3132 | "{} as {}{}", | |
3133 | &snippet[..pos], | |
3134 | suggested_name, | |
74b04a01 | 3135 | if snippet.ends_with(';') { ";" } else { "" } |
9fa01778 | 3136 | )) |
0731742a XL |
3137 | } |
3138 | } | |
3139 | } | |
0731742a | 3140 | } |
74b04a01 | 3141 | ImportKind::ExternCrate { source, target, .. } => { |
9fa01778 XL |
3142 | suggestion = Some(format!( |
3143 | "extern crate {} as {};", | |
3144 | source.unwrap_or(target.name), | |
3145 | suggested_name, | |
dfeec247 XL |
3146 | )) |
3147 | } | |
9fa01778 XL |
3148 | _ => unreachable!(), |
3149 | } | |
3150 | ||
3151 | let rename_msg = "you can use `as` to change the binding name of the import"; | |
3152 | if let Some(suggestion) = suggestion { | |
3153 | err.span_suggestion( | |
3154 | binding_span, | |
3155 | rename_msg, | |
3156 | suggestion, | |
3157 | Applicability::MaybeIncorrect, | |
3158 | ); | |
3159 | } else { | |
3160 | err.span_label(binding_span, rename_msg); | |
3161 | } | |
3162 | } | |
2c00a5a8 | 3163 | |
9fa01778 XL |
3164 | /// This function adds a suggestion to remove a unnecessary binding from an import that is |
3165 | /// nested. In the following example, this function will be invoked to remove the `a` binding | |
3166 | /// in the second use statement: | |
3167 | /// | |
3168 | /// ```ignore (diagnostic) | |
3169 | /// use issue_52891::a; | |
3170 | /// use issue_52891::{d, a, e}; | |
3171 | /// ``` | |
3172 | /// | |
3173 | /// The following suggestion will be added: | |
3174 | /// | |
3175 | /// ```ignore (diagnostic) | |
3176 | /// use issue_52891::{d, a, e}; | |
3177 | /// ^-- help: remove unnecessary import | |
3178 | /// ``` | |
3179 | /// | |
3180 | /// If the nested use contains only one import then the suggestion will remove the entire | |
3181 | /// line. | |
3182 | /// | |
74b04a01 | 3183 | /// It is expected that the provided import is nested - this isn't checked by the |
9fa01778 XL |
3184 | /// function. If this invariant is not upheld, this function's behaviour will be unexpected |
3185 | /// as characters expected by span manipulations won't be present. | |
3186 | fn add_suggestion_for_duplicate_nested_use( | |
3187 | &self, | |
3188 | err: &mut DiagnosticBuilder<'_>, | |
74b04a01 | 3189 | import: &Import<'_>, |
9fa01778 XL |
3190 | binding_span: Span, |
3191 | ) { | |
74b04a01 | 3192 | assert!(import.is_nested()); |
9fa01778 | 3193 | let message = "remove unnecessary import"; |
9fa01778 XL |
3194 | |
3195 | // Two examples will be used to illustrate the span manipulations we're doing: | |
3196 | // | |
3197 | // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is | |
74b04a01 | 3198 | // `a` and `import.use_span` is `issue_52891::{d, a, e};`. |
9fa01778 | 3199 | // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is |
74b04a01 | 3200 | // `a` and `import.use_span` is `issue_52891::{d, e, a};`. |
9fa01778 | 3201 | |
dfeec247 | 3202 | let (found_closing_brace, span) = |
74b04a01 | 3203 | find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span); |
9fa01778 | 3204 | |
9fa01778 XL |
3205 | // If there was a closing brace then identify the span to remove any trailing commas from |
3206 | // previous imports. | |
3207 | if found_closing_brace { | |
48663c56 | 3208 | if let Some(span) = extend_span_to_previous_binding(self.session, span) { |
dfeec247 XL |
3209 | err.tool_only_span_suggestion( |
3210 | span, | |
3211 | message, | |
3212 | String::new(), | |
3213 | Applicability::MaybeIncorrect, | |
3214 | ); | |
48663c56 XL |
3215 | } else { |
3216 | // Remove the entire line if we cannot extend the span back, this indicates a | |
3217 | // `issue_52891::{self}` case. | |
dfeec247 | 3218 | err.span_suggestion( |
74b04a01 | 3219 | import.use_span_with_attributes, |
dfeec247 XL |
3220 | message, |
3221 | String::new(), | |
3222 | Applicability::MaybeIncorrect, | |
3223 | ); | |
abe05a73 | 3224 | } |
48663c56 XL |
3225 | |
3226 | return; | |
abe05a73 XL |
3227 | } |
3228 | ||
9fa01778 | 3229 | err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable); |
54a0048b | 3230 | } |
0bf4aa26 | 3231 | |
dfeec247 XL |
3232 | fn extern_prelude_get( |
3233 | &mut self, | |
3234 | ident: Ident, | |
3235 | speculative: bool, | |
3236 | ) -> Option<&'a NameBinding<'a>> { | |
13cf67c4 XL |
3237 | if ident.is_path_segment_keyword() { |
3238 | // Make sure `self`, `super` etc produce an error when passed to here. | |
3239 | return None; | |
3240 | } | |
ba9703b0 | 3241 | self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| { |
0bf4aa26 | 3242 | if let Some(binding) = entry.extern_crate_item { |
0731742a XL |
3243 | if !speculative && entry.introduced_by_item { |
3244 | self.record_use(ident, TypeNS, binding, false); | |
3245 | } | |
0bf4aa26 XL |
3246 | Some(binding) |
3247 | } else { | |
3248 | let crate_id = if !speculative { | |
3249 | self.crate_loader.process_path_extern(ident.name, ident.span) | |
0bf4aa26 | 3250 | } else { |
3dfed10e | 3251 | self.crate_loader.maybe_process_path_extern(ident.name)? |
0bf4aa26 XL |
3252 | }; |
3253 | let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX }); | |
dfeec247 | 3254 | Some( |
136023e0 | 3255 | (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT) |
dfeec247 XL |
3256 | .to_name_binding(self.arenas), |
3257 | ) | |
0bf4aa26 XL |
3258 | } |
3259 | }) | |
3260 | } | |
c34b1796 | 3261 | |
416331ca XL |
3262 | /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>` |
3263 | /// isn't something that can be returned because it can't be made to live that long, | |
3264 | /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, | |
3265 | /// just that an error occurred. | |
3266 | // FIXME(Manishearth): intra-doc links won't get warned of epoch changes. | |
3267 | pub fn resolve_str_path_error( | |
dfeec247 XL |
3268 | &mut self, |
3269 | span: Span, | |
3270 | path_str: &str, | |
3271 | ns: Namespace, | |
3dfed10e | 3272 | module_id: DefId, |
416331ca XL |
3273 | ) -> Result<(ast::Path, Res), ()> { |
3274 | let path = if path_str.starts_with("::") { | |
3275 | ast::Path { | |
3276 | span, | |
e1599b0c | 3277 | segments: iter::once(Ident::with_dummy_span(kw::PathRoot)) |
ba9703b0 | 3278 | .chain(path_str.split("::").skip(1).map(Ident::from_str)) |
416331ca XL |
3279 | .map(|i| self.new_ast_path_segment(i)) |
3280 | .collect(), | |
1b1a35ee | 3281 | tokens: None, |
416331ca XL |
3282 | } |
3283 | } else { | |
3284 | ast::Path { | |
3285 | span, | |
3286 | segments: path_str | |
3287 | .split("::") | |
3288 | .map(Ident::from_str) | |
3289 | .map(|i| self.new_ast_path_segment(i)) | |
3290 | .collect(), | |
1b1a35ee | 3291 | tokens: None, |
416331ca XL |
3292 | } |
3293 | }; | |
3dfed10e | 3294 | let module = self.get_module(module_id); |
29967ef6 | 3295 | let parent_scope = &ParentScope::module(module, self); |
416331ca XL |
3296 | let res = self.resolve_ast_path(&path, ns, parent_scope).map_err(|_| ())?; |
3297 | Ok((path, res)) | |
3298 | } | |
3299 | ||
3300 | // Resolve a path passed from rustdoc or HIR lowering. | |
3301 | fn resolve_ast_path( | |
3302 | &mut self, | |
3303 | path: &ast::Path, | |
3304 | ns: Namespace, | |
3305 | parent_scope: &ParentScope<'a>, | |
3306 | ) -> Result<Res, (Span, ResolutionError<'a>)> { | |
3307 | match self.resolve_path( | |
dfeec247 XL |
3308 | &Segment::from_path(path), |
3309 | Some(ns), | |
3310 | parent_scope, | |
1b1a35ee | 3311 | false, |
dfeec247 XL |
3312 | path.span, |
3313 | CrateLint::No, | |
416331ca | 3314 | ) { |
dfeec247 XL |
3315 | PathResult::Module(ModuleOrUniformRoot::Module(module)) => Ok(module.res().unwrap()), |
3316 | PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => { | |
3317 | Ok(path_res.base_res()) | |
3318 | } | |
3319 | PathResult::NonModule(..) => Err(( | |
3320 | path.span, | |
3321 | ResolutionError::FailedToResolve { | |
416331ca XL |
3322 | label: String::from("type-relative paths are not supported in this context"), |
3323 | suggestion: None, | |
dfeec247 XL |
3324 | }, |
3325 | )), | |
416331ca XL |
3326 | PathResult::Module(..) | PathResult::Indeterminate => unreachable!(), |
3327 | PathResult::Failed { span, label, suggestion, .. } => { | |
dfeec247 | 3328 | Err((span, ResolutionError::FailedToResolve { label, suggestion })) |
416331ca XL |
3329 | } |
3330 | } | |
3331 | } | |
32a655c1 | 3332 | |
60c5eb7d | 3333 | fn new_ast_path_segment(&mut self, ident: Ident) -> ast::PathSegment { |
416331ca | 3334 | let mut seg = ast::PathSegment::from_ident(ident); |
60c5eb7d | 3335 | seg.id = self.next_node_id(); |
416331ca XL |
3336 | seg |
3337 | } | |
e74abb32 XL |
3338 | |
3339 | // For rustdoc. | |
3340 | pub fn graph_root(&self) -> Module<'a> { | |
3341 | self.graph_root | |
3342 | } | |
3343 | ||
3344 | // For rustdoc. | |
f9f354fc | 3345 | pub fn all_macros(&self) -> &FxHashMap<Symbol, Res> { |
e74abb32 XL |
3346 | &self.all_macros |
3347 | } | |
f035d41b XL |
3348 | |
3349 | /// Retrieves the span of the given `DefId` if `DefId` is in the local crate. | |
3350 | #[inline] | |
3351 | pub fn opt_span(&self, def_id: DefId) -> Option<Span> { | |
3352 | if let Some(def_id) = def_id.as_local() { Some(self.def_id_to_span[def_id]) } else { None } | |
3353 | } | |
6a06907d XL |
3354 | |
3355 | /// Checks if an expression refers to a function marked with | |
3356 | /// `#[rustc_legacy_const_generics]` and returns the argument index list | |
3357 | /// from the attribute. | |
3358 | pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> { | |
3359 | if let ExprKind::Path(None, path) = &expr.kind { | |
3360 | // Don't perform legacy const generics rewriting if the path already | |
3361 | // has generic arguments. | |
3362 | if path.segments.last().unwrap().args.is_some() { | |
3363 | return None; | |
3364 | } | |
3365 | ||
3366 | let partial_res = self.partial_res_map.get(&expr.id)?; | |
3367 | if partial_res.unresolved_segments() != 0 { | |
3368 | return None; | |
3369 | } | |
3370 | ||
3371 | if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() { | |
3372 | // We only support cross-crate argument rewriting. Uses | |
3373 | // within the same crate should be updated to use the new | |
3374 | // const generics style. | |
3375 | if def_id.is_local() { | |
3376 | return None; | |
3377 | } | |
3378 | ||
3379 | if let Some(v) = self.legacy_const_generic_args.get(&def_id) { | |
3380 | return v.clone(); | |
3381 | } | |
3382 | ||
3383 | let parse_attrs = || { | |
3384 | let attrs = self.cstore().item_attrs(def_id, self.session); | |
3385 | let attr = attrs | |
3386 | .iter() | |
3387 | .find(|a| self.session.check_name(a, sym::rustc_legacy_const_generics))?; | |
3388 | let mut ret = vec![]; | |
3389 | for meta in attr.meta_item_list()? { | |
3390 | match meta.literal()?.kind { | |
3391 | LitKind::Int(a, _) => { | |
3392 | ret.push(a as usize); | |
3393 | } | |
3394 | _ => panic!("invalid arg index"), | |
3395 | } | |
3396 | } | |
3397 | Some(ret) | |
3398 | }; | |
3399 | ||
3400 | // Cache the lookup to avoid parsing attributes for an iterm | |
3401 | // multiple times. | |
3402 | let ret = parse_attrs(); | |
3403 | self.legacy_const_generic_args.insert(def_id, ret.clone()); | |
3404 | return ret; | |
3405 | } | |
3406 | } | |
3407 | None | |
3408 | } | |
cdc7bbd5 XL |
3409 | |
3410 | fn resolve_main(&mut self) { | |
3411 | let module = self.graph_root; | |
3412 | let ident = Ident::with_dummy_span(sym::main); | |
3413 | let parent_scope = &ParentScope::module(module, self); | |
3414 | ||
3415 | let name_binding = match self.resolve_ident_in_module( | |
3416 | ModuleOrUniformRoot::Module(module), | |
3417 | ident, | |
3418 | ValueNS, | |
3419 | parent_scope, | |
3420 | false, | |
3421 | DUMMY_SP, | |
3422 | ) { | |
3423 | Ok(name_binding) => name_binding, | |
3424 | _ => return, | |
3425 | }; | |
3426 | ||
3427 | let res = name_binding.res(); | |
3428 | let is_import = name_binding.is_import(); | |
3429 | let span = name_binding.span; | |
3430 | if let Res::Def(DefKind::Fn, _) = res { | |
3431 | self.record_use(ident, ValueNS, name_binding, false); | |
3432 | } | |
3433 | self.main_def = Some(MainDefinition { res, is_import, span }); | |
3434 | } | |
32a655c1 SL |
3435 | } |
3436 | ||
f9f354fc | 3437 | fn names_to_string(names: &[Symbol]) -> String { |
c34b1796 | 3438 | let mut result = String::new(); |
dfeec247 | 3439 | for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() { |
32a655c1 SL |
3440 | if i > 0 { |
3441 | result.push_str("::"); | |
c34b1796 | 3442 | } |
60c5eb7d XL |
3443 | if Ident::with_dummy_span(*name).is_raw_guess() { |
3444 | result.push_str("r#"); | |
3445 | } | |
e1599b0c | 3446 | result.push_str(&name.as_str()); |
92a42be0 | 3447 | } |
c34b1796 AL |
3448 | result |
3449 | } | |
3450 | ||
32a655c1 | 3451 | fn path_names_to_string(path: &Path) -> String { |
60c5eb7d | 3452 | names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>()) |
c34b1796 AL |
3453 | } |
3454 | ||
3455 | /// A somewhat inefficient routine to obtain the name of a module. | |
9fa01778 | 3456 | fn module_to_string(module: Module<'_>) -> Option<String> { |
c34b1796 AL |
3457 | let mut names = Vec::new(); |
3458 | ||
f9f354fc | 3459 | fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) { |
48663c56 | 3460 | if let ModuleKind::Def(.., name) = module.kind { |
9e0c209e | 3461 | if let Some(parent) = module.parent { |
e1599b0c | 3462 | names.push(name); |
9e0c209e | 3463 | collect_mod(names, parent); |
c34b1796 | 3464 | } |
9e0c209e | 3465 | } else { |
f9f354fc | 3466 | names.push(Symbol::intern("<opaque>")); |
c30ab7b3 | 3467 | collect_mod(names, module.parent.unwrap()); |
c34b1796 AL |
3468 | } |
3469 | } | |
3470 | collect_mod(&mut names, module); | |
3471 | ||
9346a6ac | 3472 | if names.is_empty() { |
2c00a5a8 | 3473 | return None; |
c34b1796 | 3474 | } |
e1599b0c XL |
3475 | names.reverse(); |
3476 | Some(names_to_string(&names)) | |
c34b1796 AL |
3477 | } |
3478 | ||
94b46f34 XL |
3479 | #[derive(Copy, Clone, Debug)] |
3480 | enum CrateLint { | |
9fa01778 | 3481 | /// Do not issue the lint. |
94b46f34 XL |
3482 | No, |
3483 | ||
9fa01778 XL |
3484 | /// This lint applies to some arbitrary path; e.g., `impl ::foo::Bar`. |
3485 | /// In this case, we can take the span of that path. | |
94b46f34 XL |
3486 | SimplePath(NodeId), |
3487 | ||
3488 | /// This lint comes from a `use` statement. In this case, what we | |
3489 | /// care about really is the *root* `use` statement; e.g., if we | |
3490 | /// have nested things like `use a::{b, c}`, we care about the | |
3491 | /// `use a` part. | |
3492 | UsePath { root_id: NodeId, root_span: Span }, | |
3493 | ||
3494 | /// This is the "trait item" from a fully qualified path. For example, | |
3495 | /// we might be resolving `X::Y::Z` from a path like `<T as X::Y>::Z`. | |
3496 | /// The `path_span` is the span of the to the trait itself (`X::Y`). | |
3497 | QPathTrait { qpath_id: NodeId, qpath_span: Span }, | |
3498 | } | |
3499 | ||
8faf50e0 XL |
3500 | impl CrateLint { |
3501 | fn node_id(&self) -> Option<NodeId> { | |
3502 | match *self { | |
3503 | CrateLint::No => None, | |
dfeec247 XL |
3504 | CrateLint::SimplePath(id) |
3505 | | CrateLint::UsePath { root_id: id, .. } | |
3506 | | CrateLint::QPathTrait { qpath_id: id, .. } => Some(id), | |
8faf50e0 XL |
3507 | } |
3508 | } | |
3509 | } | |
dfeec247 | 3510 | |
f035d41b | 3511 | pub fn provide(providers: &mut Providers) { |
74b04a01 | 3512 | late::lifetimes::provide(providers); |
dfeec247 | 3513 | } |