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