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