]>
Commit | Line | Data |
---|---|---|
e1599b0c XL |
1 | //! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros. |
2 | //! It runs when the crate is fully expanded and its module structure is fully built. | |
3 | //! So it just walks through the crate and resolves all the expressions, types, etc. | |
4 | //! | |
5 | //! If you wonder why there's no `early.rs`, that's because it's split into three files - | |
dfeec247 | 6 | //! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`. |
e1599b0c | 7 | |
416331ca XL |
8 | use RibKind::*; |
9 | ||
10 | use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding}; | |
3dfed10e | 11 | use crate::{Module, ModuleOrUniformRoot, ParentScope, PathResult}; |
416331ca XL |
12 | use crate::{ResolutionError, Resolver, Segment, UseError}; |
13 | ||
74b04a01 | 14 | use rustc_ast::ptr::P; |
74b04a01 | 15 | use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; |
3dfed10e | 16 | use rustc_ast::*; |
f035d41b | 17 | use rustc_ast_lowering::ResolverAstLowering; |
dfeec247 XL |
18 | use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
19 | use rustc_errors::DiagnosticId; | |
20 | use rustc_hir::def::Namespace::{self, *}; | |
21 | use rustc_hir::def::{self, CtorKind, DefKind, PartialRes, PerNS}; | |
22 | use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX}; | |
6a06907d | 23 | use rustc_hir::{PrimTy, TraitCandidate}; |
ba9703b0 XL |
24 | use rustc_middle::{bug, span_bug}; |
25 | use rustc_session::lint; | |
f9f354fc | 26 | use rustc_span::symbol::{kw, sym, Ident, Symbol}; |
dfeec247 | 27 | use rustc_span::Span; |
416331ca | 28 | use smallvec::{smallvec, SmallVec}; |
416331ca | 29 | |
f035d41b | 30 | use rustc_span::source_map::{respan, Spanned}; |
fc512014 | 31 | use std::collections::{hash_map::Entry, BTreeSet}; |
f035d41b | 32 | use std::mem::{replace, take}; |
3dfed10e | 33 | use tracing::debug; |
416331ca XL |
34 | |
35 | mod diagnostics; | |
74b04a01 | 36 | crate mod lifetimes; |
416331ca XL |
37 | |
38 | type Res = def::Res<NodeId>; | |
39 | ||
e1599b0c XL |
40 | type IdentMap<T> = FxHashMap<Ident, T>; |
41 | ||
416331ca | 42 | /// Map from the name in a pattern to its binding mode. |
e1599b0c | 43 | type BindingMap = IdentMap<BindingInfo>; |
416331ca XL |
44 | |
45 | #[derive(Copy, Clone, Debug)] | |
46 | struct BindingInfo { | |
47 | span: Span, | |
48 | binding_mode: BindingMode, | |
49 | } | |
50 | ||
416331ca XL |
51 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] |
52 | enum PatternSource { | |
53 | Match, | |
54 | Let, | |
55 | For, | |
56 | FnParam, | |
57 | } | |
58 | ||
29967ef6 XL |
59 | #[derive(Copy, Clone, Debug, PartialEq, Eq)] |
60 | enum IsRepeatExpr { | |
61 | No, | |
62 | Yes, | |
63 | } | |
64 | ||
416331ca XL |
65 | impl PatternSource { |
66 | fn descr(self) -> &'static str { | |
67 | match self { | |
68 | PatternSource::Match => "match binding", | |
69 | PatternSource::Let => "let binding", | |
70 | PatternSource::For => "for binding", | |
71 | PatternSource::FnParam => "function parameter", | |
72 | } | |
73 | } | |
74 | } | |
75 | ||
e1599b0c XL |
76 | /// Denotes whether the context for the set of already bound bindings is a `Product` |
77 | /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`. | |
78 | /// See those functions for more information. | |
60c5eb7d | 79 | #[derive(PartialEq)] |
e1599b0c XL |
80 | enum PatBoundCtx { |
81 | /// A product pattern context, e.g., `Variant(a, b)`. | |
82 | Product, | |
83 | /// An or-pattern context, e.g., `p_0 | ... | p_n`. | |
84 | Or, | |
85 | } | |
86 | ||
e74abb32 XL |
87 | /// Does this the item (from the item rib scope) allow generic parameters? |
88 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] | |
dfeec247 XL |
89 | crate enum HasGenericParams { |
90 | Yes, | |
91 | No, | |
92 | } | |
e74abb32 | 93 | |
5869c6ff XL |
94 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
95 | crate enum ConstantItemKind { | |
96 | Const, | |
97 | Static, | |
98 | } | |
99 | ||
416331ca XL |
100 | /// The rib kind restricts certain accesses, |
101 | /// e.g. to a `Res::Local` of an outer item. | |
102 | #[derive(Copy, Clone, Debug)] | |
103 | crate enum RibKind<'a> { | |
104 | /// No restriction needs to be applied. | |
105 | NormalRibKind, | |
106 | ||
107 | /// We passed through an impl or trait and are now in one of its | |
108 | /// methods or associated types. Allow references to ty params that impl or trait | |
109 | /// binds. Disallow any other upvars (including other ty params that are | |
110 | /// upvars). | |
111 | AssocItemRibKind, | |
112 | ||
f035d41b XL |
113 | /// We passed through a closure. Disallow labels. |
114 | ClosureOrAsyncRibKind, | |
115 | ||
416331ca XL |
116 | /// We passed through a function definition. Disallow upvars. |
117 | /// Permit only those const parameters that are specified in the function's generics. | |
118 | FnItemRibKind, | |
119 | ||
120 | /// We passed through an item scope. Disallow upvars. | |
e74abb32 | 121 | ItemRibKind(HasGenericParams), |
416331ca XL |
122 | |
123 | /// We're in a constant item. Can't refer to dynamic stuff. | |
1b1a35ee XL |
124 | /// |
125 | /// The `bool` indicates if this constant may reference generic parameters | |
126 | /// and is used to only allow generic parameters to be used in trivial constant expressions. | |
5869c6ff | 127 | ConstantItemRibKind(bool, Option<(Ident, ConstantItemKind)>), |
416331ca XL |
128 | |
129 | /// We passed through a module. | |
130 | ModuleRibKind(Module<'a>), | |
131 | ||
132 | /// We passed through a `macro_rules!` statement | |
133 | MacroDefinition(DefId), | |
134 | ||
cdc7bbd5 XL |
135 | /// All bindings in this rib are generic parameters that can't be used |
136 | /// from the default of a generic parameter because they're not declared | |
137 | /// before said generic parameter. Also see the `visit_generics` override. | |
138 | ForwardGenericParamBanRibKind, | |
3dfed10e XL |
139 | |
140 | /// We are inside of the type of a const parameter. Can't refer to any | |
141 | /// parameters. | |
142 | ConstParamTyRibKind, | |
416331ca XL |
143 | } |
144 | ||
e1599b0c | 145 | impl RibKind<'_> { |
f035d41b XL |
146 | /// Whether this rib kind contains generic parameters, as opposed to local |
147 | /// variables. | |
e1599b0c XL |
148 | crate fn contains_params(&self) -> bool { |
149 | match self { | |
f035d41b XL |
150 | NormalRibKind |
151 | | ClosureOrAsyncRibKind | |
152 | | FnItemRibKind | |
5869c6ff | 153 | | ConstantItemRibKind(..) |
f035d41b | 154 | | ModuleRibKind(_) |
3dfed10e XL |
155 | | MacroDefinition(_) |
156 | | ConstParamTyRibKind => false, | |
cdc7bbd5 | 157 | AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true, |
e1599b0c XL |
158 | } |
159 | } | |
160 | } | |
161 | ||
416331ca XL |
162 | /// A single local scope. |
163 | /// | |
164 | /// A rib represents a scope names can live in. Note that these appear in many places, not just | |
165 | /// around braces. At any place where the list of accessible names (of the given namespace) | |
166 | /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a | |
167 | /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro, | |
168 | /// etc. | |
169 | /// | |
170 | /// Different [rib kinds](enum.RibKind) are transparent for different names. | |
171 | /// | |
172 | /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When | |
173 | /// resolving, the name is looked up from inside out. | |
174 | #[derive(Debug)] | |
175 | crate struct Rib<'a, R = Res> { | |
e1599b0c | 176 | pub bindings: IdentMap<R>, |
416331ca XL |
177 | pub kind: RibKind<'a>, |
178 | } | |
179 | ||
180 | impl<'a, R> Rib<'a, R> { | |
181 | fn new(kind: RibKind<'a>) -> Rib<'a, R> { | |
dfeec247 | 182 | Rib { bindings: Default::default(), kind } |
416331ca XL |
183 | } |
184 | } | |
185 | ||
186 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
187 | crate enum AliasPossibility { | |
188 | No, | |
189 | Maybe, | |
190 | } | |
191 | ||
192 | #[derive(Copy, Clone, Debug)] | |
193 | crate enum PathSource<'a> { | |
194 | // Type paths `Path`. | |
195 | Type, | |
196 | // Trait paths in bounds or impls. | |
197 | Trait(AliasPossibility), | |
198 | // Expression paths `path`, with optional parent context. | |
199 | Expr(Option<&'a Expr>), | |
200 | // Paths in path patterns `Path`. | |
201 | Pat, | |
202 | // Paths in struct expressions and patterns `Path { .. }`. | |
203 | Struct, | |
204 | // Paths in tuple struct patterns `Path(..)`. | |
1b1a35ee | 205 | TupleStruct(Span, &'a [Span]), |
416331ca XL |
206 | // `m::A::B` in `<T as m::A>::B::C`. |
207 | TraitItem(Namespace), | |
208 | } | |
209 | ||
210 | impl<'a> PathSource<'a> { | |
211 | fn namespace(self) -> Namespace { | |
212 | match self { | |
213 | PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS, | |
1b1a35ee | 214 | PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS, |
416331ca XL |
215 | PathSource::TraitItem(ns) => ns, |
216 | } | |
217 | } | |
218 | ||
219 | fn defer_to_typeck(self) -> bool { | |
220 | match self { | |
dfeec247 XL |
221 | PathSource::Type |
222 | | PathSource::Expr(..) | |
223 | | PathSource::Pat | |
224 | | PathSource::Struct | |
1b1a35ee | 225 | | PathSource::TupleStruct(..) => true, |
416331ca XL |
226 | PathSource::Trait(_) | PathSource::TraitItem(..) => false, |
227 | } | |
228 | } | |
229 | ||
230 | fn descr_expected(self) -> &'static str { | |
e74abb32 | 231 | match &self { |
416331ca XL |
232 | PathSource::Type => "type", |
233 | PathSource::Trait(_) => "trait", | |
e74abb32 | 234 | PathSource::Pat => "unit struct, unit variant or constant", |
416331ca | 235 | PathSource::Struct => "struct, variant or union type", |
1b1a35ee | 236 | PathSource::TupleStruct(..) => "tuple struct or tuple variant", |
416331ca XL |
237 | PathSource::TraitItem(ns) => match ns { |
238 | TypeNS => "associated type", | |
239 | ValueNS => "method or associated constant", | |
240 | MacroNS => bug!("associated macro"), | |
241 | }, | |
3dfed10e | 242 | PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) { |
416331ca XL |
243 | // "function" here means "anything callable" rather than `DefKind::Fn`, |
244 | // this is not precise but usually more helpful than just "value". | |
dfeec247 | 245 | Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind { |
5869c6ff XL |
246 | // the case of `::some_crate()` |
247 | ExprKind::Path(_, path) | |
248 | if path.segments.len() == 2 | |
249 | && path.segments[0].ident.name == kw::PathRoot => | |
250 | { | |
251 | "external crate" | |
252 | } | |
dfeec247 XL |
253 | ExprKind::Path(_, path) => { |
254 | let mut msg = "function"; | |
255 | if let Some(segment) = path.segments.iter().last() { | |
256 | if let Some(c) = segment.ident.to_string().chars().next() { | |
257 | if c.is_uppercase() { | |
258 | msg = "function, tuple struct or tuple variant"; | |
e74abb32 XL |
259 | } |
260 | } | |
e74abb32 | 261 | } |
dfeec247 | 262 | msg |
e74abb32 | 263 | } |
dfeec247 XL |
264 | _ => "function", |
265 | }, | |
416331ca XL |
266 | _ => "value", |
267 | }, | |
268 | } | |
269 | } | |
270 | ||
f035d41b | 271 | fn is_call(self) -> bool { |
29967ef6 | 272 | matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. }))) |
f035d41b XL |
273 | } |
274 | ||
416331ca XL |
275 | crate fn is_expected(self, res: Res) -> bool { |
276 | match self { | |
5869c6ff XL |
277 | PathSource::Type => matches!( |
278 | res, | |
279 | Res::Def( | |
ba9703b0 | 280 | DefKind::Struct |
5869c6ff XL |
281 | | DefKind::Union |
282 | | DefKind::Enum | |
283 | | DefKind::Trait | |
284 | | DefKind::TraitAlias | |
285 | | DefKind::TyAlias | |
286 | | DefKind::AssocTy | |
287 | | DefKind::TyParam | |
288 | | DefKind::OpaqueTy | |
289 | | DefKind::ForeignTy, | |
ba9703b0 | 290 | _, |
5869c6ff XL |
291 | ) | Res::PrimTy(..) |
292 | | Res::SelfTy(..) | |
293 | ), | |
29967ef6 XL |
294 | PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)), |
295 | PathSource::Trait(AliasPossibility::Maybe) => { | |
296 | matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) | |
297 | } | |
5869c6ff XL |
298 | PathSource::Expr(..) => matches!( |
299 | res, | |
300 | Res::Def( | |
ba9703b0 | 301 | DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn) |
5869c6ff XL |
302 | | DefKind::Const |
303 | | DefKind::Static | |
304 | | DefKind::Fn | |
305 | | DefKind::AssocFn | |
306 | | DefKind::AssocConst | |
307 | | DefKind::ConstParam, | |
ba9703b0 | 308 | _, |
5869c6ff XL |
309 | ) | Res::Local(..) |
310 | | Res::SelfCtor(..) | |
311 | ), | |
312 | PathSource::Pat => matches!( | |
313 | res, | |
314 | Res::Def( | |
ba9703b0 XL |
315 | DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst, |
316 | _, | |
5869c6ff XL |
317 | ) | Res::SelfCtor(..) |
318 | ), | |
29967ef6 | 319 | PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(), |
5869c6ff XL |
320 | PathSource::Struct => matches!( |
321 | res, | |
322 | Res::Def( | |
ba9703b0 | 323 | DefKind::Struct |
5869c6ff XL |
324 | | DefKind::Union |
325 | | DefKind::Variant | |
326 | | DefKind::TyAlias | |
327 | | DefKind::AssocTy, | |
ba9703b0 | 328 | _, |
5869c6ff XL |
329 | ) | Res::SelfTy(..) |
330 | ), | |
416331ca | 331 | PathSource::TraitItem(ns) => match res { |
ba9703b0 | 332 | Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true, |
416331ca XL |
333 | Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true, |
334 | _ => false, | |
335 | }, | |
336 | } | |
337 | } | |
338 | ||
dfeec247 XL |
339 | fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId { |
340 | use rustc_errors::error_code; | |
416331ca | 341 | match (self, has_unexpected_resolution) { |
dfeec247 XL |
342 | (PathSource::Trait(_), true) => error_code!(E0404), |
343 | (PathSource::Trait(_), false) => error_code!(E0405), | |
344 | (PathSource::Type, true) => error_code!(E0573), | |
345 | (PathSource::Type, false) => error_code!(E0412), | |
346 | (PathSource::Struct, true) => error_code!(E0574), | |
347 | (PathSource::Struct, false) => error_code!(E0422), | |
348 | (PathSource::Expr(..), true) => error_code!(E0423), | |
349 | (PathSource::Expr(..), false) => error_code!(E0425), | |
1b1a35ee XL |
350 | (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532), |
351 | (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531), | |
dfeec247 XL |
352 | (PathSource::TraitItem(..), true) => error_code!(E0575), |
353 | (PathSource::TraitItem(..), false) => error_code!(E0576), | |
416331ca XL |
354 | } |
355 | } | |
356 | } | |
357 | ||
e74abb32 | 358 | #[derive(Default)] |
dfeec247 | 359 | struct DiagnosticMetadata<'ast> { |
29967ef6 XL |
360 | /// The current trait's associated items' ident, used for diagnostic suggestions. |
361 | current_trait_assoc_items: Option<&'ast [P<AssocItem>]>, | |
e74abb32 XL |
362 | |
363 | /// The current self type if inside an impl (used for better errors). | |
364 | current_self_type: Option<Ty>, | |
365 | ||
366 | /// The current self item if inside an ADT (used for better errors). | |
367 | current_self_item: Option<NodeId>, | |
368 | ||
dfeec247 XL |
369 | /// The current trait (used to suggest). |
370 | current_item: Option<&'ast Item>, | |
371 | ||
372 | /// When processing generics and encountering a type not found, suggest introducing a type | |
373 | /// param. | |
374 | currently_processing_generics: bool, | |
375 | ||
29967ef6 | 376 | /// The current enclosing (non-closure) function (used for better errors). |
f9f354fc | 377 | current_function: Option<(FnKind<'ast>, Span)>, |
e74abb32 XL |
378 | |
379 | /// A list of labels as of yet unused. Labels will be removed from this map when | |
380 | /// they are used (in a `break` or `continue` statement) | |
381 | unused_labels: FxHashMap<NodeId, Span>, | |
382 | ||
383 | /// Only used for better errors on `fn(): fn()`. | |
384 | current_type_ascription: Vec<Span>, | |
385 | ||
386 | /// Only used for better errors on `let <pat>: <expr, not type>;`. | |
387 | current_let_binding: Option<(Span, Option<Span>, Option<Span>)>, | |
1b1a35ee XL |
388 | |
389 | /// Used to detect possible `if let` written without `let` and to provide structured suggestion. | |
390 | in_if_condition: Option<&'ast Expr>, | |
29967ef6 XL |
391 | |
392 | /// If we are currently in a trait object definition. Used to point at the bounds when | |
393 | /// encountering a struct or enum. | |
394 | current_trait_object: Option<&'ast [ast::GenericBound]>, | |
395 | ||
396 | /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`. | |
397 | current_where_predicate: Option<&'ast WherePredicate>, | |
e74abb32 XL |
398 | } |
399 | ||
dfeec247 | 400 | struct LateResolutionVisitor<'a, 'b, 'ast> { |
416331ca XL |
401 | r: &'b mut Resolver<'a>, |
402 | ||
403 | /// The module that represents the current item scope. | |
404 | parent_scope: ParentScope<'a>, | |
405 | ||
406 | /// The current set of local scopes for types and values. | |
407 | /// FIXME #4948: Reuse ribs to avoid allocation. | |
408 | ribs: PerNS<Vec<Rib<'a>>>, | |
409 | ||
410 | /// The current set of local scopes, for labels. | |
411 | label_ribs: Vec<Rib<'a, NodeId>>, | |
412 | ||
413 | /// The trait that the current context can refer to. | |
414 | current_trait_ref: Option<(Module<'a>, TraitRef)>, | |
415 | ||
e74abb32 | 416 | /// Fields used to add information to diagnostic errors. |
dfeec247 | 417 | diagnostic_metadata: DiagnosticMetadata<'ast>, |
3dfed10e XL |
418 | |
419 | /// State used to know whether to ignore resolution errors for function bodies. | |
420 | /// | |
421 | /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items. | |
422 | /// In most cases this will be `None`, in which case errors will always be reported. | |
1b1a35ee | 423 | /// If it is `true`, then it will be updated when entering a nested function or trait body. |
3dfed10e | 424 | in_func_body: bool, |
416331ca XL |
425 | } |
426 | ||
427 | /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes. | |
1b1a35ee | 428 | impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> { |
dfeec247 XL |
429 | fn visit_item(&mut self, item: &'ast Item) { |
430 | let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item)); | |
3dfed10e XL |
431 | // Always report errors in items we just entered. |
432 | let old_ignore = replace(&mut self.in_func_body, false); | |
416331ca | 433 | self.resolve_item(item); |
3dfed10e | 434 | self.in_func_body = old_ignore; |
dfeec247 | 435 | self.diagnostic_metadata.current_item = prev; |
416331ca | 436 | } |
dfeec247 | 437 | fn visit_arm(&mut self, arm: &'ast Arm) { |
416331ca XL |
438 | self.resolve_arm(arm); |
439 | } | |
dfeec247 | 440 | fn visit_block(&mut self, block: &'ast Block) { |
416331ca XL |
441 | self.resolve_block(block); |
442 | } | |
dfeec247 | 443 | fn visit_anon_const(&mut self, constant: &'ast AnonConst) { |
29967ef6 XL |
444 | // We deal with repeat expressions explicitly in `resolve_expr`. |
445 | self.resolve_anon_const(constant, IsRepeatExpr::No); | |
416331ca | 446 | } |
dfeec247 | 447 | fn visit_expr(&mut self, expr: &'ast Expr) { |
416331ca XL |
448 | self.resolve_expr(expr, None); |
449 | } | |
dfeec247 | 450 | fn visit_local(&mut self, local: &'ast Local) { |
e74abb32 XL |
451 | let local_spans = match local.pat.kind { |
452 | // We check for this to avoid tuple struct fields. | |
453 | PatKind::Wild => None, | |
454 | _ => Some(( | |
455 | local.pat.span, | |
456 | local.ty.as_ref().map(|ty| ty.span), | |
457 | local.init.as_ref().map(|init| init.span), | |
458 | )), | |
459 | }; | |
460 | let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans); | |
416331ca | 461 | self.resolve_local(local); |
e74abb32 | 462 | self.diagnostic_metadata.current_let_binding = original; |
416331ca | 463 | } |
dfeec247 | 464 | fn visit_ty(&mut self, ty: &'ast Ty) { |
29967ef6 | 465 | let prev = self.diagnostic_metadata.current_trait_object; |
e74abb32 | 466 | match ty.kind { |
416331ca XL |
467 | TyKind::Path(ref qself, ref path) => { |
468 | self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type); | |
469 | } | |
470 | TyKind::ImplicitSelf => { | |
e1599b0c | 471 | let self_ty = Ident::with_dummy_span(kw::SelfUpper); |
dfeec247 XL |
472 | let res = self |
473 | .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span) | |
474 | .map_or(Res::Err, |d| d.res()); | |
416331ca XL |
475 | self.r.record_partial_res(ty.id, PartialRes::new(res)); |
476 | } | |
29967ef6 XL |
477 | TyKind::TraitObject(ref bounds, ..) => { |
478 | self.diagnostic_metadata.current_trait_object = Some(&bounds[..]); | |
479 | } | |
416331ca XL |
480 | _ => (), |
481 | } | |
482 | visit::walk_ty(self, ty); | |
29967ef6 | 483 | self.diagnostic_metadata.current_trait_object = prev; |
416331ca | 484 | } |
dfeec247 XL |
485 | fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) { |
486 | self.smart_resolve_path( | |
487 | tref.trait_ref.ref_id, | |
488 | None, | |
489 | &tref.trait_ref.path, | |
490 | PathSource::Trait(AliasPossibility::Maybe), | |
491 | ); | |
416331ca XL |
492 | visit::walk_poly_trait_ref(self, tref, m); |
493 | } | |
dfeec247 | 494 | fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) { |
e74abb32 | 495 | match foreign_item.kind { |
5869c6ff XL |
496 | ForeignItemKind::Fn(box FnKind(_, _, ref generics, _)) |
497 | | ForeignItemKind::TyAlias(box TyAliasKind(_, ref generics, ..)) => { | |
e74abb32 XL |
498 | self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { |
499 | visit::walk_foreign_item(this, foreign_item); | |
500 | }); | |
416331ca | 501 | } |
e74abb32 XL |
502 | ForeignItemKind::Static(..) => { |
503 | self.with_item_rib(HasGenericParams::No, |this| { | |
504 | visit::walk_foreign_item(this, foreign_item); | |
505 | }); | |
506 | } | |
ba9703b0 | 507 | ForeignItemKind::MacCall(..) => { |
e74abb32 XL |
508 | visit::walk_foreign_item(self, foreign_item); |
509 | } | |
510 | } | |
416331ca | 511 | } |
74b04a01 | 512 | fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) { |
e1599b0c | 513 | let rib_kind = match fn_kind { |
74b04a01 XL |
514 | // Bail if there's no body. |
515 | FnKind::Fn(.., None) => return visit::walk_fn(self, fn_kind, sp), | |
ba9703b0 | 516 | FnKind::Fn(FnCtxt::Free | FnCtxt::Foreign, ..) => FnItemRibKind, |
f035d41b XL |
517 | FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind, |
518 | FnKind::Closure(..) => ClosureOrAsyncRibKind, | |
416331ca | 519 | }; |
29967ef6 XL |
520 | let previous_value = self.diagnostic_metadata.current_function; |
521 | if matches!(fn_kind, FnKind::Fn(..)) { | |
522 | self.diagnostic_metadata.current_function = Some((fn_kind, sp)); | |
523 | } | |
74b04a01 XL |
524 | debug!("(resolving function) entering function"); |
525 | let declaration = fn_kind.decl(); | |
416331ca XL |
526 | |
527 | // Create a value rib for the function. | |
e1599b0c XL |
528 | self.with_rib(ValueNS, rib_kind, |this| { |
529 | // Create a label rib for the function. | |
530 | this.with_label_rib(rib_kind, |this| { | |
531 | // Add each argument to the rib. | |
532 | this.resolve_params(&declaration.inputs); | |
533 | ||
534 | visit::walk_fn_ret_ty(this, &declaration.output); | |
535 | ||
3dfed10e XL |
536 | // Ignore errors in function bodies if this is rustdoc |
537 | // Be sure not to set this until the function signature has been resolved. | |
538 | let previous_state = replace(&mut this.in_func_body, true); | |
e1599b0c XL |
539 | // Resolve the function body, potentially inside the body of an async closure |
540 | match fn_kind { | |
74b04a01 XL |
541 | FnKind::Fn(.., body) => walk_list!(this, visit_block, body), |
542 | FnKind::Closure(_, body) => this.visit_expr(body), | |
e1599b0c XL |
543 | }; |
544 | ||
545 | debug!("(resolving function) leaving function"); | |
3dfed10e | 546 | this.in_func_body = previous_state; |
e1599b0c XL |
547 | }) |
548 | }); | |
e74abb32 | 549 | self.diagnostic_metadata.current_function = previous_value; |
416331ca XL |
550 | } |
551 | ||
dfeec247 | 552 | fn visit_generics(&mut self, generics: &'ast Generics) { |
416331ca XL |
553 | // For type parameter defaults, we have to ban access |
554 | // to following type parameters, as the InternalSubsts can only | |
555 | // provide previous type parameters as they're built. We | |
556 | // put all the parameters on the ban list and then remove | |
557 | // them one by one as they are processed and become available. | |
cdc7bbd5 XL |
558 | let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind); |
559 | let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind); | |
560 | for param in generics.params.iter() { | |
561 | match param.kind { | |
562 | GenericParamKind::Type { .. } => { | |
563 | forward_ty_ban_rib | |
564 | .bindings | |
565 | .insert(Ident::with_dummy_span(param.ident.name), Res::Err); | |
416331ca | 566 | } |
cdc7bbd5 XL |
567 | GenericParamKind::Const { .. } => { |
568 | forward_const_ban_rib | |
569 | .bindings | |
570 | .insert(Ident::with_dummy_span(param.ident.name), Res::Err); | |
571 | } | |
572 | GenericParamKind::Lifetime => {} | |
573 | } | |
574 | } | |
416331ca | 575 | |
e74abb32 XL |
576 | // rust-lang/rust#61631: The type `Self` is essentially |
577 | // another type parameter. For ADTs, we consider it | |
578 | // well-defined only after all of the ADT type parameters have | |
579 | // been provided. Therefore, we do not allow use of `Self` | |
580 | // anywhere in ADT type parameter defaults. | |
581 | // | |
582 | // (We however cannot ban `Self` for defaults on *all* generic | |
583 | // lists; e.g. trait generics can usefully refer to `Self`, | |
584 | // such as in the case of `trait Add<Rhs = Self>`.) | |
585 | if self.diagnostic_metadata.current_self_item.is_some() { | |
586 | // (`Some` if + only if we are in ADT's generics.) | |
cdc7bbd5 | 587 | forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err); |
e74abb32 | 588 | } |
416331ca XL |
589 | |
590 | for param in &generics.params { | |
591 | match param.kind { | |
f035d41b XL |
592 | GenericParamKind::Lifetime => self.visit_generic_param(param), |
593 | GenericParamKind::Type { ref default } => { | |
416331ca XL |
594 | for bound in ¶m.bounds { |
595 | self.visit_param_bound(bound); | |
596 | } | |
597 | ||
598 | if let Some(ref ty) = default { | |
cdc7bbd5 XL |
599 | self.ribs[TypeNS].push(forward_ty_ban_rib); |
600 | self.ribs[ValueNS].push(forward_const_ban_rib); | |
601 | self.visit_ty(ty); | |
602 | forward_const_ban_rib = self.ribs[ValueNS].pop().unwrap(); | |
603 | forward_ty_ban_rib = self.ribs[TypeNS].pop().unwrap(); | |
416331ca XL |
604 | } |
605 | ||
606 | // Allow all following defaults to refer to this type parameter. | |
cdc7bbd5 | 607 | forward_ty_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name)); |
416331ca | 608 | } |
cdc7bbd5 XL |
609 | GenericParamKind::Const { ref ty, kw_span: _, ref default } => { |
610 | // Const parameters can't have param bounds. | |
611 | assert!(param.bounds.is_empty()); | |
612 | ||
3dfed10e XL |
613 | self.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind)); |
614 | self.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind)); | |
416331ca | 615 | self.visit_ty(ty); |
3dfed10e XL |
616 | self.ribs[TypeNS].pop().unwrap(); |
617 | self.ribs[ValueNS].pop().unwrap(); | |
cdc7bbd5 XL |
618 | |
619 | if let Some(ref expr) = default { | |
620 | self.ribs[TypeNS].push(forward_ty_ban_rib); | |
621 | self.ribs[ValueNS].push(forward_const_ban_rib); | |
622 | self.visit_anon_const(expr); | |
623 | forward_const_ban_rib = self.ribs[ValueNS].pop().unwrap(); | |
624 | forward_ty_ban_rib = self.ribs[TypeNS].pop().unwrap(); | |
625 | } | |
626 | ||
627 | // Allow all following defaults to refer to this const parameter. | |
628 | forward_const_ban_rib | |
629 | .bindings | |
630 | .remove(&Ident::with_dummy_span(param.ident.name)); | |
416331ca XL |
631 | } |
632 | } | |
633 | } | |
634 | for p in &generics.where_clause.predicates { | |
635 | self.visit_where_predicate(p); | |
636 | } | |
637 | } | |
60c5eb7d | 638 | |
dfeec247 | 639 | fn visit_generic_arg(&mut self, arg: &'ast GenericArg) { |
60c5eb7d | 640 | debug!("visit_generic_arg({:?})", arg); |
dfeec247 | 641 | let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true); |
60c5eb7d XL |
642 | match arg { |
643 | GenericArg::Type(ref ty) => { | |
74b04a01 | 644 | // We parse const arguments as path types as we cannot distinguish them during |
60c5eb7d XL |
645 | // parsing. We try to resolve that ambiguity by attempting resolution the type |
646 | // namespace first, and if that fails we try again in the value namespace. If | |
647 | // resolution in the value namespace succeeds, we have an generic const argument on | |
648 | // our hands. | |
649 | if let TyKind::Path(ref qself, ref path) = ty.kind { | |
650 | // We cannot disambiguate multi-segment paths right now as that requires type | |
651 | // checking. | |
652 | if path.segments.len() == 1 && path.segments[0].args.is_none() { | |
dfeec247 XL |
653 | let mut check_ns = |ns| { |
654 | self.resolve_ident_in_lexical_scope( | |
655 | path.segments[0].ident, | |
656 | ns, | |
657 | None, | |
658 | path.span, | |
659 | ) | |
660 | .is_some() | |
661 | }; | |
60c5eb7d XL |
662 | if !check_ns(TypeNS) && check_ns(ValueNS) { |
663 | // This must be equivalent to `visit_anon_const`, but we cannot call it | |
664 | // directly due to visitor lifetimes so we have to copy-paste some code. | |
29967ef6 XL |
665 | // |
666 | // Note that we might not be inside of an repeat expression here, | |
667 | // but considering that `IsRepeatExpr` is only relevant for | |
668 | // non-trivial constants this is doesn't matter. | |
5869c6ff | 669 | self.with_constant_rib(IsRepeatExpr::No, true, None, |this| { |
60c5eb7d XL |
670 | this.smart_resolve_path( |
671 | ty.id, | |
672 | qself.as_ref(), | |
673 | path, | |
dfeec247 | 674 | PathSource::Expr(None), |
60c5eb7d XL |
675 | ); |
676 | ||
677 | if let Some(ref qself) = *qself { | |
678 | this.visit_ty(&qself.ty); | |
679 | } | |
680 | this.visit_path(path, ty.id); | |
681 | }); | |
682 | ||
dfeec247 | 683 | self.diagnostic_metadata.currently_processing_generics = prev; |
60c5eb7d XL |
684 | return; |
685 | } | |
686 | } | |
687 | } | |
688 | ||
689 | self.visit_ty(ty); | |
690 | } | |
691 | GenericArg::Lifetime(lt) => self.visit_lifetime(lt), | |
692 | GenericArg::Const(ct) => self.visit_anon_const(ct), | |
693 | } | |
dfeec247 | 694 | self.diagnostic_metadata.currently_processing_generics = prev; |
60c5eb7d | 695 | } |
29967ef6 XL |
696 | |
697 | fn visit_where_predicate(&mut self, p: &'ast WherePredicate) { | |
698 | debug!("visit_where_predicate {:?}", p); | |
699 | let previous_value = | |
700 | replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p)); | |
701 | visit::walk_where_predicate(self, p); | |
702 | self.diagnostic_metadata.current_where_predicate = previous_value; | |
703 | } | |
416331ca XL |
704 | } |
705 | ||
1b1a35ee | 706 | impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { |
dfeec247 | 707 | fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> { |
416331ca XL |
708 | // During late resolution we only track the module component of the parent scope, |
709 | // although it may be useful to track other components as well for diagnostics. | |
416331ca | 710 | let graph_root = resolver.graph_root; |
29967ef6 | 711 | let parent_scope = ParentScope::module(graph_root, resolver); |
e1599b0c | 712 | let start_rib_kind = ModuleRibKind(graph_root); |
416331ca XL |
713 | LateResolutionVisitor { |
714 | r: resolver, | |
715 | parent_scope, | |
716 | ribs: PerNS { | |
e1599b0c XL |
717 | value_ns: vec![Rib::new(start_rib_kind)], |
718 | type_ns: vec![Rib::new(start_rib_kind)], | |
719 | macro_ns: vec![Rib::new(start_rib_kind)], | |
416331ca XL |
720 | }, |
721 | label_ribs: Vec::new(), | |
722 | current_trait_ref: None, | |
e74abb32 | 723 | diagnostic_metadata: DiagnosticMetadata::default(), |
3dfed10e XL |
724 | // errors at module scope should always be reported |
725 | in_func_body: false, | |
416331ca XL |
726 | } |
727 | } | |
728 | ||
dfeec247 XL |
729 | fn resolve_ident_in_lexical_scope( |
730 | &mut self, | |
731 | ident: Ident, | |
732 | ns: Namespace, | |
733 | record_used_id: Option<NodeId>, | |
734 | path_span: Span, | |
735 | ) -> Option<LexicalScopeBinding<'a>> { | |
416331ca | 736 | self.r.resolve_ident_in_lexical_scope( |
dfeec247 XL |
737 | ident, |
738 | ns, | |
739 | &self.parent_scope, | |
740 | record_used_id, | |
741 | path_span, | |
742 | &self.ribs[ns], | |
416331ca XL |
743 | ) |
744 | } | |
745 | ||
746 | fn resolve_path( | |
747 | &mut self, | |
748 | path: &[Segment], | |
749 | opt_ns: Option<Namespace>, // `None` indicates a module path in import | |
750 | record_used: bool, | |
751 | path_span: Span, | |
752 | crate_lint: CrateLint, | |
753 | ) -> PathResult<'a> { | |
754 | self.r.resolve_path_with_ribs( | |
dfeec247 XL |
755 | path, |
756 | opt_ns, | |
757 | &self.parent_scope, | |
758 | record_used, | |
759 | path_span, | |
760 | crate_lint, | |
761 | Some(&self.ribs), | |
416331ca XL |
762 | ) |
763 | } | |
764 | ||
765 | // AST resolution | |
766 | // | |
767 | // We maintain a list of value ribs and type ribs. | |
768 | // | |
769 | // Simultaneously, we keep track of the current position in the module | |
770 | // graph in the `parent_scope.module` pointer. When we go to resolve a name in | |
771 | // the value or type namespaces, we first look through all the ribs and | |
772 | // then query the module graph. When we resolve a name in the module | |
773 | // namespace, we can skip all the ribs (since nested modules are not | |
774 | // allowed within blocks in Rust) and jump straight to the current module | |
775 | // graph node. | |
776 | // | |
777 | // Named implementations are handled separately. When we find a method | |
778 | // call, we consult the module node to find all of the implementations in | |
779 | // scope. This information is lazily cached in the module node. We then | |
780 | // generate a fake "implementation scope" containing all the | |
781 | // implementations thus found, for compatibility with old resolve pass. | |
782 | ||
e1599b0c XL |
783 | /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`). |
784 | fn with_rib<T>( | |
785 | &mut self, | |
786 | ns: Namespace, | |
787 | kind: RibKind<'a>, | |
788 | work: impl FnOnce(&mut Self) -> T, | |
789 | ) -> T { | |
790 | self.ribs[ns].push(Rib::new(kind)); | |
791 | let ret = work(self); | |
792 | self.ribs[ns].pop(); | |
793 | ret | |
794 | } | |
795 | ||
796 | fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { | |
f035d41b | 797 | let id = self.r.local_def_id(id); |
416331ca XL |
798 | let module = self.r.module_map.get(&id).cloned(); // clones a reference |
799 | if let Some(module) = module { | |
800 | // Move down in the graph. | |
801 | let orig_module = replace(&mut self.parent_scope.module, module); | |
e1599b0c XL |
802 | self.with_rib(ValueNS, ModuleRibKind(module), |this| { |
803 | this.with_rib(TypeNS, ModuleRibKind(module), |this| { | |
804 | let ret = f(this); | |
805 | this.parent_scope.module = orig_module; | |
806 | ret | |
807 | }) | |
808 | }) | |
416331ca XL |
809 | } else { |
810 | f(self) | |
811 | } | |
812 | } | |
813 | ||
f035d41b XL |
814 | /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved |
815 | /// label and reports an error if the label is not found or is unreachable. | |
816 | fn resolve_label(&self, mut label: Ident) -> Option<NodeId> { | |
817 | let mut suggestion = None; | |
818 | ||
819 | // Preserve the original span so that errors contain "in this macro invocation" | |
820 | // information. | |
821 | let original_span = label.span; | |
822 | ||
823 | for i in (0..self.label_ribs.len()).rev() { | |
824 | let rib = &self.label_ribs[i]; | |
825 | ||
826 | if let MacroDefinition(def) = rib.kind { | |
416331ca XL |
827 | // If an invocation of this macro created `ident`, give up on `ident` |
828 | // and switch to `ident`'s source from the macro definition. | |
f035d41b XL |
829 | if def == self.r.macro_def(label.span.ctxt()) { |
830 | label.span.remove_mark(); | |
416331ca XL |
831 | } |
832 | } | |
f035d41b XL |
833 | |
834 | let ident = label.normalize_to_macro_rules(); | |
835 | if let Some((ident, id)) = rib.bindings.get_key_value(&ident) { | |
836 | return if self.is_label_valid_from_rib(i) { | |
837 | Some(*id) | |
838 | } else { | |
3dfed10e | 839 | self.report_error( |
f035d41b XL |
840 | original_span, |
841 | ResolutionError::UnreachableLabel { | |
3dfed10e | 842 | name: label.name, |
f035d41b XL |
843 | definition_span: ident.span, |
844 | suggestion, | |
845 | }, | |
846 | ); | |
847 | ||
848 | None | |
849 | }; | |
416331ca | 850 | } |
f035d41b XL |
851 | |
852 | // Diagnostics: Check if this rib contains a label with a similar name, keep track of | |
853 | // the first such label that is encountered. | |
854 | suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label)); | |
416331ca | 855 | } |
f035d41b | 856 | |
3dfed10e | 857 | self.report_error( |
f035d41b | 858 | original_span, |
3dfed10e | 859 | ResolutionError::UndeclaredLabel { name: label.name, suggestion }, |
f035d41b | 860 | ); |
416331ca XL |
861 | None |
862 | } | |
863 | ||
f035d41b XL |
864 | /// Determine whether or not a label from the `rib_index`th label rib is reachable. |
865 | fn is_label_valid_from_rib(&self, rib_index: usize) -> bool { | |
866 | let ribs = &self.label_ribs[rib_index + 1..]; | |
867 | ||
868 | for rib in ribs { | |
869 | match rib.kind { | |
870 | NormalRibKind | MacroDefinition(..) => { | |
871 | // Nothing to do. Continue. | |
872 | } | |
873 | ||
874 | AssocItemRibKind | |
875 | | ClosureOrAsyncRibKind | |
876 | | FnItemRibKind | |
877 | | ItemRibKind(..) | |
5869c6ff | 878 | | ConstantItemRibKind(..) |
f035d41b | 879 | | ModuleRibKind(..) |
cdc7bbd5 | 880 | | ForwardGenericParamBanRibKind |
3dfed10e | 881 | | ConstParamTyRibKind => { |
f035d41b XL |
882 | return false; |
883 | } | |
884 | } | |
885 | } | |
886 | ||
887 | true | |
888 | } | |
889 | ||
dfeec247 | 890 | fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) { |
416331ca XL |
891 | debug!("resolve_adt"); |
892 | self.with_current_self_item(item, |this| { | |
e74abb32 | 893 | this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { |
f035d41b | 894 | let item_def_id = this.r.local_def_id(item.id).to_def_id(); |
1b1a35ee | 895 | this.with_self_rib(Res::SelfTy(None, Some((item_def_id, false))), |this| { |
416331ca XL |
896 | visit::walk_item(this, item); |
897 | }); | |
898 | }); | |
899 | }); | |
900 | } | |
901 | ||
902 | fn future_proof_import(&mut self, use_tree: &UseTree) { | |
903 | let segments = &use_tree.prefix.segments; | |
904 | if !segments.is_empty() { | |
905 | let ident = segments[0].ident; | |
906 | if ident.is_path_segment_keyword() || ident.span.rust_2015() { | |
907 | return; | |
908 | } | |
909 | ||
910 | let nss = match use_tree.kind { | |
911 | UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..], | |
912 | _ => &[TypeNS], | |
913 | }; | |
914 | let report_error = |this: &Self, ns| { | |
915 | let what = if ns == TypeNS { "type parameters" } else { "local variables" }; | |
3dfed10e XL |
916 | if this.should_report_errs() { |
917 | this.r | |
918 | .session | |
919 | .span_err(ident.span, &format!("imports cannot refer to {}", what)); | |
920 | } | |
416331ca XL |
921 | }; |
922 | ||
923 | for &ns in nss { | |
924 | match self.resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) { | |
925 | Some(LexicalScopeBinding::Res(..)) => { | |
926 | report_error(self, ns); | |
927 | } | |
928 | Some(LexicalScopeBinding::Item(binding)) => { | |
f035d41b XL |
929 | let orig_unusable_binding = |
930 | replace(&mut self.r.unusable_binding, Some(binding)); | |
dfeec247 XL |
931 | if let Some(LexicalScopeBinding::Res(..)) = self |
932 | .resolve_ident_in_lexical_scope(ident, ns, None, use_tree.prefix.span) | |
933 | { | |
416331ca XL |
934 | report_error(self, ns); |
935 | } | |
f035d41b | 936 | self.r.unusable_binding = orig_unusable_binding; |
416331ca XL |
937 | } |
938 | None => {} | |
939 | } | |
940 | } | |
941 | } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind { | |
942 | for (use_tree, _) in use_trees { | |
943 | self.future_proof_import(use_tree); | |
944 | } | |
945 | } | |
946 | } | |
947 | ||
dfeec247 | 948 | fn resolve_item(&mut self, item: &'ast Item) { |
416331ca | 949 | let name = item.ident.name; |
e74abb32 | 950 | debug!("(resolving item) resolving {} ({:?})", name, item.kind); |
416331ca | 951 | |
e74abb32 | 952 | match item.kind { |
5869c6ff XL |
953 | ItemKind::TyAlias(box TyAliasKind(_, ref generics, _, _)) |
954 | | ItemKind::Fn(box FnKind(_, _, ref generics, _)) => { | |
dfeec247 XL |
955 | self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { |
956 | visit::walk_item(this, item) | |
957 | }); | |
416331ca XL |
958 | } |
959 | ||
dfeec247 XL |
960 | ItemKind::Enum(_, ref generics) |
961 | | ItemKind::Struct(_, ref generics) | |
962 | | ItemKind::Union(_, ref generics) => { | |
416331ca XL |
963 | self.resolve_adt(item, generics); |
964 | } | |
965 | ||
5869c6ff | 966 | ItemKind::Impl(box ImplKind { |
dfeec247 XL |
967 | ref generics, |
968 | ref of_trait, | |
969 | ref self_ty, | |
970 | items: ref impl_items, | |
971 | .. | |
5869c6ff | 972 | }) => { |
dfeec247 XL |
973 | self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items); |
974 | } | |
416331ca | 975 | |
5869c6ff | 976 | ItemKind::Trait(box TraitKind(.., ref generics, ref bounds, ref trait_items)) => { |
416331ca | 977 | // Create a new rib for the trait-wide type parameters. |
e74abb32 | 978 | self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { |
f035d41b | 979 | let local_def_id = this.r.local_def_id(item.id).to_def_id(); |
416331ca XL |
980 | this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| { |
981 | this.visit_generics(generics); | |
982 | walk_list!(this, visit_param_bound, bounds); | |
983 | ||
74b04a01 XL |
984 | let walk_assoc_item = |this: &mut Self, generics, item| { |
985 | this.with_generic_param_rib(generics, AssocItemRibKind, |this| { | |
986 | visit::walk_assoc_item(this, item, AssocCtxt::Trait) | |
987 | }); | |
988 | }; | |
989 | ||
fc512014 XL |
990 | this.with_trait_items(trait_items, |this| { |
991 | for item in trait_items { | |
74b04a01 XL |
992 | match &item.kind { |
993 | AssocItemKind::Const(_, ty, default) => { | |
994 | this.visit_ty(ty); | |
995 | // Only impose the restrictions of `ConstRibKind` for an | |
996 | // actual constant expression in a provided default. | |
997 | if let Some(expr) = default { | |
3dfed10e XL |
998 | // We allow arbitrary const expressions inside of associated consts, |
999 | // even if they are potentially not const evaluatable. | |
1000 | // | |
1001 | // Type parameters can already be used and as associated consts are | |
1002 | // not used as part of the type system, this is far less surprising. | |
29967ef6 XL |
1003 | this.with_constant_rib( |
1004 | IsRepeatExpr::No, | |
1005 | true, | |
5869c6ff | 1006 | None, |
29967ef6 XL |
1007 | |this| this.visit_expr(expr), |
1008 | ); | |
74b04a01 XL |
1009 | } |
1010 | } | |
5869c6ff | 1011 | AssocItemKind::Fn(box FnKind(_, _, generics, _)) => { |
74b04a01 XL |
1012 | walk_assoc_item(this, generics, item); |
1013 | } | |
5869c6ff | 1014 | AssocItemKind::TyAlias(box TyAliasKind(_, generics, _, _)) => { |
74b04a01 XL |
1015 | walk_assoc_item(this, generics, item); |
1016 | } | |
ba9703b0 | 1017 | AssocItemKind::MacCall(_) => { |
74b04a01 XL |
1018 | panic!("unexpanded macro in resolve!") |
1019 | } | |
1020 | }; | |
fc512014 XL |
1021 | } |
1022 | }); | |
416331ca XL |
1023 | }); |
1024 | }); | |
1025 | } | |
1026 | ||
1027 | ItemKind::TraitAlias(ref generics, ref bounds) => { | |
1028 | // Create a new rib for the trait-wide type parameters. | |
e74abb32 | 1029 | self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { |
f035d41b | 1030 | let local_def_id = this.r.local_def_id(item.id).to_def_id(); |
416331ca XL |
1031 | this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| { |
1032 | this.visit_generics(generics); | |
1033 | walk_list!(this, visit_param_bound, bounds); | |
1034 | }); | |
1035 | }); | |
1036 | } | |
1037 | ||
6a06907d | 1038 | ItemKind::Mod(..) | ItemKind::ForeignMod(_) => { |
416331ca XL |
1039 | self.with_scope(item.id, |this| { |
1040 | visit::walk_item(this, item); | |
1041 | }); | |
1042 | } | |
1043 | ||
74b04a01 | 1044 | ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => { |
e74abb32 | 1045 | self.with_item_rib(HasGenericParams::No, |this| { |
416331ca | 1046 | this.visit_ty(ty); |
74b04a01 | 1047 | if let Some(expr) = expr { |
5869c6ff XL |
1048 | let constant_item_kind = match item.kind { |
1049 | ItemKind::Const(..) => ConstantItemKind::Const, | |
1050 | ItemKind::Static(..) => ConstantItemKind::Static, | |
1051 | _ => unreachable!(), | |
1052 | }; | |
29967ef6 XL |
1053 | // We already forbid generic params because of the above item rib, |
1054 | // so it doesn't matter whether this is a trivial constant. | |
5869c6ff XL |
1055 | this.with_constant_rib( |
1056 | IsRepeatExpr::No, | |
1057 | true, | |
1058 | Some((item.ident, constant_item_kind)), | |
1059 | |this| this.visit_expr(expr), | |
1060 | ); | |
74b04a01 | 1061 | } |
416331ca XL |
1062 | }); |
1063 | } | |
1064 | ||
1065 | ItemKind::Use(ref use_tree) => { | |
1066 | self.future_proof_import(use_tree); | |
1067 | } | |
1068 | ||
dfeec247 | 1069 | ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) | ItemKind::GlobalAsm(..) => { |
416331ca XL |
1070 | // do nothing, these are just around to be encoded |
1071 | } | |
1072 | ||
ba9703b0 | 1073 | ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"), |
416331ca XL |
1074 | } |
1075 | } | |
1076 | ||
e74abb32 | 1077 | fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F) |
dfeec247 XL |
1078 | where |
1079 | F: FnOnce(&mut Self), | |
416331ca XL |
1080 | { |
1081 | debug!("with_generic_param_rib"); | |
e74abb32 XL |
1082 | let mut function_type_rib = Rib::new(kind); |
1083 | let mut function_value_rib = Rib::new(kind); | |
1084 | let mut seen_bindings = FxHashMap::default(); | |
1085 | ||
1086 | // We also can't shadow bindings from the parent item | |
1087 | if let AssocItemRibKind = kind { | |
1088 | let mut add_bindings_for_ns = |ns| { | |
dfeec247 XL |
1089 | let parent_rib = self.ribs[ns] |
1090 | .iter() | |
1b1a35ee | 1091 | .rfind(|r| matches!(r.kind, ItemRibKind(_))) |
e74abb32 | 1092 | .expect("associated item outside of an item"); |
dfeec247 XL |
1093 | seen_bindings |
1094 | .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span))); | |
e74abb32 XL |
1095 | }; |
1096 | add_bindings_for_ns(ValueNS); | |
1097 | add_bindings_for_ns(TypeNS); | |
1098 | } | |
1099 | ||
1100 | for param in &generics.params { | |
1101 | if let GenericParamKind::Lifetime { .. } = param.kind { | |
1102 | continue; | |
416331ca XL |
1103 | } |
1104 | ||
ba9703b0 | 1105 | let ident = param.ident.normalize_to_macros_2_0(); |
e74abb32 XL |
1106 | debug!("with_generic_param_rib: {}", param.id); |
1107 | ||
fc512014 XL |
1108 | match seen_bindings.entry(ident) { |
1109 | Entry::Occupied(entry) => { | |
1110 | let span = *entry.get(); | |
1111 | let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span); | |
1112 | self.report_error(param.ident.span, err); | |
1113 | } | |
1114 | Entry::Vacant(entry) => { | |
1115 | entry.insert(param.ident.span); | |
1116 | } | |
e74abb32 | 1117 | } |
e74abb32 XL |
1118 | |
1119 | // Plain insert (no renaming). | |
fc512014 XL |
1120 | let (rib, def_kind) = match param.kind { |
1121 | GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam), | |
1122 | GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam), | |
e74abb32 | 1123 | _ => unreachable!(), |
fc512014 XL |
1124 | }; |
1125 | let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id()); | |
1126 | self.r.record_partial_res(param.id, PartialRes::new(res)); | |
1127 | rib.bindings.insert(ident, res); | |
416331ca XL |
1128 | } |
1129 | ||
e74abb32 XL |
1130 | self.ribs[ValueNS].push(function_value_rib); |
1131 | self.ribs[TypeNS].push(function_type_rib); | |
1132 | ||
416331ca XL |
1133 | f(self); |
1134 | ||
e74abb32 XL |
1135 | self.ribs[TypeNS].pop(); |
1136 | self.ribs[ValueNS].pop(); | |
416331ca XL |
1137 | } |
1138 | ||
e1599b0c XL |
1139 | fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) { |
1140 | self.label_ribs.push(Rib::new(kind)); | |
416331ca XL |
1141 | f(self); |
1142 | self.label_ribs.pop(); | |
1143 | } | |
1144 | ||
e74abb32 XL |
1145 | fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) { |
1146 | let kind = ItemRibKind(has_generic_params); | |
1147 | self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f)) | |
416331ca XL |
1148 | } |
1149 | ||
29967ef6 XL |
1150 | // HACK(min_const_generics,const_evaluatable_unchecked): We |
1151 | // want to keep allowing `[0; std::mem::size_of::<*mut T>()]` | |
1152 | // with a future compat lint for now. We do this by adding an | |
1153 | // additional special case for repeat expressions. | |
1154 | // | |
1155 | // Note that we intentionally still forbid `[0; N + 1]` during | |
1156 | // name resolution so that we don't extend the future | |
1157 | // compat lint to new cases. | |
1158 | fn with_constant_rib( | |
1159 | &mut self, | |
1160 | is_repeat: IsRepeatExpr, | |
1161 | is_trivial: bool, | |
5869c6ff | 1162 | item: Option<(Ident, ConstantItemKind)>, |
29967ef6 XL |
1163 | f: impl FnOnce(&mut Self), |
1164 | ) { | |
1165 | debug!("with_constant_rib: is_repeat={:?} is_trivial={}", is_repeat, is_trivial); | |
5869c6ff | 1166 | self.with_rib(ValueNS, ConstantItemRibKind(is_trivial, item), |this| { |
29967ef6 XL |
1167 | this.with_rib( |
1168 | TypeNS, | |
5869c6ff | 1169 | ConstantItemRibKind(is_repeat == IsRepeatExpr::Yes || is_trivial, item), |
29967ef6 | 1170 | |this| { |
5869c6ff | 1171 | this.with_label_rib(ConstantItemRibKind(is_trivial, item), f); |
29967ef6 XL |
1172 | }, |
1173 | ) | |
e1599b0c | 1174 | }); |
416331ca XL |
1175 | } |
1176 | ||
e1599b0c | 1177 | fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T { |
416331ca | 1178 | // Handle nested impls (inside fn bodies) |
dfeec247 XL |
1179 | let previous_value = |
1180 | replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone())); | |
416331ca | 1181 | let result = f(self); |
e74abb32 | 1182 | self.diagnostic_metadata.current_self_type = previous_value; |
416331ca XL |
1183 | result |
1184 | } | |
1185 | ||
e1599b0c | 1186 | fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T { |
dfeec247 XL |
1187 | let previous_value = |
1188 | replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id)); | |
416331ca | 1189 | let result = f(self); |
e74abb32 | 1190 | self.diagnostic_metadata.current_self_item = previous_value; |
416331ca XL |
1191 | result |
1192 | } | |
1193 | ||
29967ef6 | 1194 | /// When evaluating a `trait` use its associated types' idents for suggestions in E0412. |
e1599b0c XL |
1195 | fn with_trait_items<T>( |
1196 | &mut self, | |
5869c6ff | 1197 | trait_items: &'ast [P<AssocItem>], |
e1599b0c XL |
1198 | f: impl FnOnce(&mut Self) -> T, |
1199 | ) -> T { | |
5869c6ff XL |
1200 | let trait_assoc_items = |
1201 | replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items)); | |
416331ca | 1202 | let result = f(self); |
29967ef6 | 1203 | self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items; |
416331ca XL |
1204 | result |
1205 | } | |
1206 | ||
1207 | /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`). | |
e1599b0c XL |
1208 | fn with_optional_trait_ref<T>( |
1209 | &mut self, | |
1210 | opt_trait_ref: Option<&TraitRef>, | |
dfeec247 | 1211 | f: impl FnOnce(&mut Self, Option<DefId>) -> T, |
e1599b0c | 1212 | ) -> T { |
416331ca XL |
1213 | let mut new_val = None; |
1214 | let mut new_id = None; | |
1215 | if let Some(trait_ref) = opt_trait_ref { | |
1216 | let path: Vec<_> = Segment::from_path(&trait_ref.path); | |
1217 | let res = self.smart_resolve_path_fragment( | |
1218 | trait_ref.ref_id, | |
1219 | None, | |
1220 | &path, | |
1221 | trait_ref.path.span, | |
1222 | PathSource::Trait(AliasPossibility::No), | |
1223 | CrateLint::SimplePath(trait_ref.ref_id), | |
dfeec247 XL |
1224 | ); |
1225 | let res = res.base_res(); | |
416331ca XL |
1226 | if res != Res::Err { |
1227 | new_id = Some(res.def_id()); | |
1228 | let span = trait_ref.path.span; | |
dfeec247 XL |
1229 | if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path( |
1230 | &path, | |
1231 | Some(TypeNS), | |
1232 | false, | |
1233 | span, | |
1234 | CrateLint::SimplePath(trait_ref.ref_id), | |
1235 | ) { | |
416331ca XL |
1236 | new_val = Some((module, trait_ref.clone())); |
1237 | } | |
1238 | } | |
1239 | } | |
1240 | let original_trait_ref = replace(&mut self.current_trait_ref, new_val); | |
1241 | let result = f(self, new_id); | |
1242 | self.current_trait_ref = original_trait_ref; | |
1243 | result | |
1244 | } | |
1245 | ||
e1599b0c | 1246 | fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) { |
416331ca XL |
1247 | let mut self_type_rib = Rib::new(NormalRibKind); |
1248 | ||
1249 | // Plain insert (no renaming, since types are not currently hygienic) | |
e1599b0c XL |
1250 | self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res); |
1251 | self.ribs[ns].push(self_type_rib); | |
416331ca | 1252 | f(self); |
e1599b0c | 1253 | self.ribs[ns].pop(); |
416331ca XL |
1254 | } |
1255 | ||
e1599b0c XL |
1256 | fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) { |
1257 | self.with_self_rib_ns(TypeNS, self_res, f) | |
416331ca XL |
1258 | } |
1259 | ||
dfeec247 XL |
1260 | fn resolve_implementation( |
1261 | &mut self, | |
1262 | generics: &'ast Generics, | |
1263 | opt_trait_reference: &'ast Option<TraitRef>, | |
1264 | self_type: &'ast Ty, | |
1265 | item_id: NodeId, | |
74b04a01 | 1266 | impl_items: &'ast [P<AssocItem>], |
dfeec247 | 1267 | ) { |
416331ca XL |
1268 | debug!("resolve_implementation"); |
1269 | // If applicable, create a rib for the type parameters. | |
e74abb32 | 1270 | self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { |
416331ca XL |
1271 | // Dummy self type for better errors if `Self` is used in the trait path. |
1272 | this.with_self_rib(Res::SelfTy(None, None), |this| { | |
1273 | // Resolve the trait reference, if necessary. | |
1274 | this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| { | |
f035d41b | 1275 | let item_def_id = this.r.local_def_id(item_id).to_def_id(); |
1b1a35ee | 1276 | this.with_self_rib(Res::SelfTy(trait_id, Some((item_def_id, false))), |this| { |
416331ca XL |
1277 | if let Some(trait_ref) = opt_trait_reference.as_ref() { |
1278 | // Resolve type arguments in the trait path. | |
1279 | visit::walk_trait_ref(this, trait_ref); | |
1280 | } | |
1281 | // Resolve the self type. | |
1282 | this.visit_ty(self_type); | |
1283 | // Resolve the generic parameters. | |
1284 | this.visit_generics(generics); | |
1285 | // Resolve the items within the impl. | |
1286 | this.with_current_self_type(self_type, |this| { | |
e1599b0c XL |
1287 | this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| { |
1288 | debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)"); | |
74b04a01 XL |
1289 | for item in impl_items { |
1290 | use crate::ResolutionError::*; | |
1291 | match &item.kind { | |
3dfed10e | 1292 | AssocItemKind::Const(_default, _ty, _expr) => { |
74b04a01 XL |
1293 | debug!("resolve_implementation AssocItemKind::Const",); |
1294 | // If this is a trait impl, ensure the const | |
1295 | // exists in trait | |
1296 | this.check_trait_item( | |
1297 | item.ident, | |
1298 | ValueNS, | |
1299 | item.span, | |
1300 | |n, s| ConstNotMemberOfTrait(n, s), | |
1301 | ); | |
1302 | ||
3dfed10e XL |
1303 | // We allow arbitrary const expressions inside of associated consts, |
1304 | // even if they are potentially not const evaluatable. | |
1305 | // | |
1306 | // Type parameters can already be used and as associated consts are | |
1307 | // not used as part of the type system, this is far less surprising. | |
29967ef6 XL |
1308 | this.with_constant_rib( |
1309 | IsRepeatExpr::No, | |
1310 | true, | |
5869c6ff | 1311 | None, |
29967ef6 XL |
1312 | |this| { |
1313 | visit::walk_assoc_item( | |
1314 | this, | |
1315 | item, | |
1316 | AssocCtxt::Impl, | |
1317 | ) | |
1318 | }, | |
1319 | ); | |
74b04a01 | 1320 | } |
5869c6ff | 1321 | AssocItemKind::Fn(box FnKind(.., generics, _)) => { |
74b04a01 XL |
1322 | // We also need a new scope for the impl item type parameters. |
1323 | this.with_generic_param_rib( | |
1324 | generics, | |
1325 | AssocItemRibKind, | |
1326 | |this| { | |
1327 | // If this is a trait impl, ensure the method | |
1328 | // exists in trait | |
1329 | this.check_trait_item( | |
1330 | item.ident, | |
1331 | ValueNS, | |
1332 | item.span, | |
1333 | |n, s| MethodNotMemberOfTrait(n, s), | |
1334 | ); | |
1335 | ||
1336 | visit::walk_assoc_item( | |
1337 | this, | |
1338 | item, | |
1339 | AssocCtxt::Impl, | |
1340 | ) | |
1341 | }, | |
1342 | ); | |
1343 | } | |
5869c6ff XL |
1344 | AssocItemKind::TyAlias(box TyAliasKind( |
1345 | _, | |
1346 | generics, | |
1347 | _, | |
1348 | _, | |
1349 | )) => { | |
74b04a01 XL |
1350 | // We also need a new scope for the impl item type parameters. |
1351 | this.with_generic_param_rib( | |
1352 | generics, | |
1353 | AssocItemRibKind, | |
1354 | |this| { | |
1355 | // If this is a trait impl, ensure the type | |
1356 | // exists in trait | |
1357 | this.check_trait_item( | |
1358 | item.ident, | |
1359 | TypeNS, | |
1360 | item.span, | |
1361 | |n, s| TypeNotMemberOfTrait(n, s), | |
1362 | ); | |
1363 | ||
1364 | visit::walk_assoc_item( | |
1365 | this, | |
1366 | item, | |
1367 | AssocCtxt::Impl, | |
1368 | ) | |
1369 | }, | |
1370 | ); | |
1371 | } | |
ba9703b0 | 1372 | AssocItemKind::MacCall(_) => { |
74b04a01 | 1373 | panic!("unexpanded macro in resolve!") |
416331ca | 1374 | } |
74b04a01 | 1375 | } |
416331ca XL |
1376 | } |
1377 | }); | |
1378 | }); | |
1379 | }); | |
1380 | }); | |
1381 | }); | |
1382 | }); | |
1383 | } | |
1384 | ||
1385 | fn check_trait_item<F>(&mut self, ident: Ident, ns: Namespace, span: Span, err: F) | |
dfeec247 | 1386 | where |
f9f354fc | 1387 | F: FnOnce(Symbol, &str) -> ResolutionError<'_>, |
416331ca XL |
1388 | { |
1389 | // If there is a TraitRef in scope for an impl, then the method must be in the | |
1390 | // trait. | |
1391 | if let Some((module, _)) = self.current_trait_ref { | |
dfeec247 XL |
1392 | if self |
1393 | .r | |
1394 | .resolve_ident_in_module( | |
1395 | ModuleOrUniformRoot::Module(module), | |
1396 | ident, | |
1397 | ns, | |
1398 | &self.parent_scope, | |
1399 | false, | |
1400 | span, | |
1401 | ) | |
1402 | .is_err() | |
1403 | { | |
416331ca | 1404 | let path = &self.current_trait_ref.as_ref().unwrap().1.path; |
3dfed10e | 1405 | self.report_error(span, err(ident.name, &path_names_to_string(path))); |
416331ca XL |
1406 | } |
1407 | } | |
1408 | } | |
1409 | ||
dfeec247 | 1410 | fn resolve_params(&mut self, params: &'ast [Param]) { |
e1599b0c XL |
1411 | let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; |
1412 | for Param { pat, ty, .. } in params { | |
1413 | self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings); | |
1414 | self.visit_ty(ty); | |
1415 | debug!("(resolving function / closure) recorded parameter"); | |
1416 | } | |
1417 | } | |
1418 | ||
dfeec247 | 1419 | fn resolve_local(&mut self, local: &'ast Local) { |
3dfed10e | 1420 | debug!("resolving local ({:?})", local); |
416331ca XL |
1421 | // Resolve the type. |
1422 | walk_list!(self, visit_ty, &local.ty); | |
1423 | ||
1424 | // Resolve the initializer. | |
1425 | walk_list!(self, visit_expr, &local.init); | |
1426 | ||
1427 | // Resolve the pattern. | |
e1599b0c | 1428 | self.resolve_pattern_top(&local.pat, PatternSource::Let); |
416331ca XL |
1429 | } |
1430 | ||
e1599b0c XL |
1431 | /// build a map from pattern identifiers to binding-info's. |
1432 | /// this is done hygienically. This could arise for a macro | |
1433 | /// that expands into an or-pattern where one 'x' was from the | |
1434 | /// user and one 'x' came from the macro. | |
416331ca XL |
1435 | fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap { |
1436 | let mut binding_map = FxHashMap::default(); | |
1437 | ||
1438 | pat.walk(&mut |pat| { | |
e74abb32 | 1439 | match pat.kind { |
e1599b0c XL |
1440 | PatKind::Ident(binding_mode, ident, ref sub_pat) |
1441 | if sub_pat.is_some() || self.is_base_res_local(pat.id) => | |
1442 | { | |
1443 | binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode }); | |
416331ca | 1444 | } |
e1599b0c XL |
1445 | PatKind::Or(ref ps) => { |
1446 | // Check the consistency of this or-pattern and | |
1447 | // then add all bindings to the larger map. | |
1448 | for bm in self.check_consistent_bindings(ps) { | |
1449 | binding_map.extend(bm); | |
1450 | } | |
1451 | return false; | |
1452 | } | |
1453 | _ => {} | |
416331ca | 1454 | } |
e1599b0c | 1455 | |
416331ca XL |
1456 | true |
1457 | }); | |
1458 | ||
1459 | binding_map | |
1460 | } | |
1461 | ||
e1599b0c | 1462 | fn is_base_res_local(&self, nid: NodeId) -> bool { |
29967ef6 | 1463 | matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..))) |
e1599b0c XL |
1464 | } |
1465 | ||
1466 | /// Checks that all of the arms in an or-pattern have exactly the | |
1467 | /// same set of bindings, with the same binding modes for each. | |
1468 | fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> { | |
416331ca XL |
1469 | let mut missing_vars = FxHashMap::default(); |
1470 | let mut inconsistent_vars = FxHashMap::default(); | |
1471 | ||
e1599b0c | 1472 | // 1) Compute the binding maps of all arms. |
dfeec247 | 1473 | let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>(); |
e1599b0c XL |
1474 | |
1475 | // 2) Record any missing bindings or binding mode inconsistencies. | |
1476 | for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) { | |
1477 | // Check against all arms except for the same pattern which is always self-consistent. | |
dfeec247 XL |
1478 | let inners = pats |
1479 | .iter() | |
1480 | .enumerate() | |
e1599b0c XL |
1481 | .filter(|(_, pat)| pat.id != pat_outer.id) |
1482 | .flat_map(|(idx, _)| maps[idx].iter()) | |
1483 | .map(|(key, binding)| (key.name, map_outer.get(&key), binding)); | |
1484 | ||
1485 | for (name, info, &binding_inner) in inners { | |
1486 | match info { | |
dfeec247 XL |
1487 | None => { |
1488 | // The inner binding is missing in the outer. | |
1489 | let binding_error = | |
1490 | missing_vars.entry(name).or_insert_with(|| BindingError { | |
e1599b0c XL |
1491 | name, |
1492 | origin: BTreeSet::new(), | |
1493 | target: BTreeSet::new(), | |
1494 | could_be_path: name.as_str().starts_with(char::is_uppercase), | |
1495 | }); | |
1496 | binding_error.origin.insert(binding_inner.span); | |
1497 | binding_error.target.insert(pat_outer.span); | |
1498 | } | |
1499 | Some(binding_outer) => { | |
1500 | if binding_outer.binding_mode != binding_inner.binding_mode { | |
1501 | // The binding modes in the outer and inner bindings differ. | |
1502 | inconsistent_vars | |
1503 | .entry(name) | |
1504 | .or_insert((binding_inner.span, binding_outer.span)); | |
416331ca XL |
1505 | } |
1506 | } | |
1507 | } | |
1508 | } | |
1509 | } | |
1510 | ||
e1599b0c | 1511 | // 3) Report all missing variables we found. |
416331ca | 1512 | let mut missing_vars = missing_vars.iter_mut().collect::<Vec<_>>(); |
f035d41b XL |
1513 | missing_vars.sort_by_key(|(sym, _err)| sym.as_str()); |
1514 | ||
416331ca XL |
1515 | for (name, mut v) in missing_vars { |
1516 | if inconsistent_vars.contains_key(name) { | |
1517 | v.could_be_path = false; | |
1518 | } | |
3dfed10e | 1519 | self.report_error( |
416331ca | 1520 | *v.origin.iter().next().unwrap(), |
dfeec247 XL |
1521 | ResolutionError::VariableNotBoundInPattern(v), |
1522 | ); | |
416331ca XL |
1523 | } |
1524 | ||
e1599b0c | 1525 | // 4) Report all inconsistencies in binding modes we found. |
416331ca XL |
1526 | let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>(); |
1527 | inconsistent_vars.sort(); | |
1528 | for (name, v) in inconsistent_vars { | |
3dfed10e | 1529 | self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1)); |
416331ca | 1530 | } |
416331ca | 1531 | |
e1599b0c XL |
1532 | // 5) Finally bubble up all the binding maps. |
1533 | maps | |
416331ca XL |
1534 | } |
1535 | ||
e1599b0c | 1536 | /// Check the consistency of the outermost or-patterns. |
dfeec247 | 1537 | fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) { |
e74abb32 | 1538 | pat.walk(&mut |pat| match pat.kind { |
e1599b0c XL |
1539 | PatKind::Or(ref ps) => { |
1540 | self.check_consistent_bindings(ps); | |
1541 | false | |
dfeec247 | 1542 | } |
e1599b0c XL |
1543 | _ => true, |
1544 | }) | |
416331ca XL |
1545 | } |
1546 | ||
dfeec247 | 1547 | fn resolve_arm(&mut self, arm: &'ast Arm) { |
e1599b0c XL |
1548 | self.with_rib(ValueNS, NormalRibKind, |this| { |
1549 | this.resolve_pattern_top(&arm.pat, PatternSource::Match); | |
1550 | walk_list!(this, visit_expr, &arm.guard); | |
1551 | this.visit_expr(&arm.body); | |
1552 | }); | |
416331ca XL |
1553 | } |
1554 | ||
e1599b0c | 1555 | /// Arising from `source`, resolve a top level pattern. |
dfeec247 | 1556 | fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) { |
e1599b0c XL |
1557 | let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; |
1558 | self.resolve_pattern(pat, pat_src, &mut bindings); | |
1559 | } | |
416331ca | 1560 | |
e1599b0c XL |
1561 | fn resolve_pattern( |
1562 | &mut self, | |
dfeec247 | 1563 | pat: &'ast Pat, |
e1599b0c XL |
1564 | pat_src: PatternSource, |
1565 | bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>, | |
1566 | ) { | |
1567 | self.resolve_pattern_inner(pat, pat_src, bindings); | |
1568 | // This has to happen *after* we determine which pat_idents are variants: | |
1569 | self.check_consistent_bindings_top(pat); | |
1570 | visit::walk_pat(self, pat); | |
416331ca XL |
1571 | } |
1572 | ||
e1599b0c XL |
1573 | /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`. |
1574 | /// | |
1575 | /// ### `bindings` | |
1576 | /// | |
1577 | /// A stack of sets of bindings accumulated. | |
1578 | /// | |
1579 | /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should | |
1580 | /// be interpreted as re-binding an already bound binding. This results in an error. | |
1581 | /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result | |
1582 | /// in reusing this binding rather than creating a fresh one. | |
1583 | /// | |
1584 | /// When called at the top level, the stack must have a single element | |
1585 | /// with `PatBound::Product`. Otherwise, pushing to the stack happens as | |
1586 | /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs | |
1587 | /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`. | |
1588 | /// When each `p_i` has been dealt with, the top set is merged with its parent. | |
1589 | /// When a whole or-pattern has been dealt with, the thing happens. | |
1590 | /// | |
1591 | /// See the implementation and `fresh_binding` for more details. | |
1592 | fn resolve_pattern_inner( | |
1593 | &mut self, | |
1594 | pat: &Pat, | |
1595 | pat_src: PatternSource, | |
1596 | bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>, | |
1597 | ) { | |
416331ca | 1598 | // Visit all direct subpatterns of this pattern. |
416331ca | 1599 | pat.walk(&mut |pat| { |
e74abb32 XL |
1600 | debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind); |
1601 | match pat.kind { | |
e1599b0c XL |
1602 | PatKind::Ident(bmode, ident, ref sub) => { |
1603 | // First try to resolve the identifier as some existing entity, | |
1604 | // then fall back to a fresh binding. | |
1605 | let has_sub = sub.is_some(); | |
dfeec247 XL |
1606 | let res = self |
1607 | .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub) | |
e1599b0c | 1608 | .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings)); |
416331ca | 1609 | self.r.record_partial_res(pat.id, PartialRes::new(res)); |
cdc7bbd5 | 1610 | self.r.record_pat_span(pat.id, pat.span); |
416331ca | 1611 | } |
1b1a35ee XL |
1612 | PatKind::TupleStruct(ref path, ref sub_patterns) => { |
1613 | self.smart_resolve_path( | |
1614 | pat.id, | |
1615 | None, | |
1616 | path, | |
1617 | PathSource::TupleStruct( | |
1618 | pat.span, | |
1619 | self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)), | |
1620 | ), | |
1621 | ); | |
416331ca | 1622 | } |
416331ca XL |
1623 | PatKind::Path(ref qself, ref path) => { |
1624 | self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat); | |
1625 | } | |
416331ca XL |
1626 | PatKind::Struct(ref path, ..) => { |
1627 | self.smart_resolve_path(pat.id, None, path, PathSource::Struct); | |
1628 | } | |
e1599b0c XL |
1629 | PatKind::Or(ref ps) => { |
1630 | // Add a new set of bindings to the stack. `Or` here records that when a | |
1631 | // binding already exists in this set, it should not result in an error because | |
1632 | // `V1(a) | V2(a)` must be allowed and are checked for consistency later. | |
1633 | bindings.push((PatBoundCtx::Or, Default::default())); | |
1634 | for p in ps { | |
1635 | // Now we need to switch back to a product context so that each | |
1636 | // part of the or-pattern internally rejects already bound names. | |
1637 | // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad. | |
1638 | bindings.push((PatBoundCtx::Product, Default::default())); | |
1639 | self.resolve_pattern_inner(p, pat_src, bindings); | |
1640 | // Move up the non-overlapping bindings to the or-pattern. | |
1641 | // Existing bindings just get "merged". | |
1642 | let collected = bindings.pop().unwrap().1; | |
1643 | bindings.last_mut().unwrap().1.extend(collected); | |
1644 | } | |
1645 | // This or-pattern itself can itself be part of a product, | |
1646 | // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`. | |
1647 | // Both cases bind `a` again in a product pattern and must be rejected. | |
1648 | let collected = bindings.pop().unwrap().1; | |
1649 | bindings.last_mut().unwrap().1.extend(collected); | |
1650 | ||
1651 | // Prevent visiting `ps` as we've already done so above. | |
1652 | return false; | |
1653 | } | |
416331ca XL |
1654 | _ => {} |
1655 | } | |
1656 | true | |
1657 | }); | |
e1599b0c | 1658 | } |
416331ca | 1659 | |
e1599b0c XL |
1660 | fn fresh_binding( |
1661 | &mut self, | |
1662 | ident: Ident, | |
1663 | pat_id: NodeId, | |
1664 | pat_src: PatternSource, | |
1665 | bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>, | |
1666 | ) -> Res { | |
1667 | // Add the binding to the local ribs, if it doesn't already exist in the bindings map. | |
1668 | // (We must not add it if it's in the bindings map because that breaks the assumptions | |
1669 | // later passes make about or-patterns.) | |
ba9703b0 | 1670 | let ident = ident.normalize_to_macro_rules(); |
e1599b0c | 1671 | |
60c5eb7d XL |
1672 | let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident)); |
1673 | // Already bound in a product pattern? e.g. `(a, a)` which is not allowed. | |
1674 | let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product); | |
1675 | // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`. | |
1676 | // This is *required* for consistency which is checked later. | |
1677 | let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or); | |
e1599b0c XL |
1678 | |
1679 | if already_bound_and { | |
1680 | // Overlap in a product pattern somewhere; report an error. | |
1681 | use ResolutionError::*; | |
1682 | let error = match pat_src { | |
1683 | // `fn f(a: u8, a: u8)`: | |
1684 | PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList, | |
1685 | // `Variant(a, a)`: | |
1686 | _ => IdentifierBoundMoreThanOnceInSamePattern, | |
1687 | }; | |
3dfed10e | 1688 | self.report_error(ident.span, error(ident.name)); |
e1599b0c XL |
1689 | } |
1690 | ||
1691 | // Record as bound if it's valid: | |
5869c6ff | 1692 | let ident_valid = ident.name != kw::Empty; |
e1599b0c XL |
1693 | if ident_valid { |
1694 | bindings.last_mut().unwrap().1.insert(ident); | |
1695 | } | |
1696 | ||
1697 | if already_bound_or { | |
1698 | // `Variant1(a) | Variant2(a)`, ok | |
1699 | // Reuse definition from the first `a`. | |
1700 | self.innermost_rib_bindings(ValueNS)[&ident] | |
1701 | } else { | |
1702 | let res = Res::Local(pat_id); | |
1703 | if ident_valid { | |
1704 | // A completely fresh binding add to the set if it's valid. | |
1705 | self.innermost_rib_bindings(ValueNS).insert(ident, res); | |
1706 | } | |
1707 | res | |
1708 | } | |
1709 | } | |
1710 | ||
1711 | fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> { | |
1712 | &mut self.ribs[ns].last_mut().unwrap().bindings | |
1713 | } | |
1714 | ||
1715 | fn try_resolve_as_non_binding( | |
1716 | &mut self, | |
1717 | pat_src: PatternSource, | |
1718 | pat: &Pat, | |
1719 | bm: BindingMode, | |
1720 | ident: Ident, | |
1721 | has_sub: bool, | |
1722 | ) -> Option<Res> { | |
e1599b0c XL |
1723 | // An immutable (no `mut`) by-value (no `ref`) binding pattern without |
1724 | // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could | |
1725 | // also be interpreted as a path to e.g. a constant, variant, etc. | |
dfeec247 | 1726 | let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not); |
e1599b0c | 1727 | |
ba9703b0 XL |
1728 | let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?; |
1729 | let (res, binding) = match ls_binding { | |
1730 | LexicalScopeBinding::Item(binding) | |
1731 | if is_syntactic_ambiguity && binding.is_ambiguity() => | |
dfeec247 | 1732 | { |
ba9703b0 XL |
1733 | // For ambiguous bindings we don't know all their definitions and cannot check |
1734 | // whether they can be shadowed by fresh bindings or not, so force an error. | |
1735 | // issues/33118#issuecomment-233962221 (see below) still applies here, | |
1736 | // but we have to ignore it for backward compatibility. | |
e1599b0c | 1737 | self.r.record_use(ident, ValueNS, binding, false); |
ba9703b0 XL |
1738 | return None; |
1739 | } | |
1740 | LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)), | |
1741 | LexicalScopeBinding::Res(res) => (res, None), | |
1742 | }; | |
1743 | ||
1744 | match res { | |
1745 | Res::SelfCtor(_) // See #70549. | |
1746 | | Res::Def( | |
1747 | DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam, | |
1748 | _, | |
1749 | ) if is_syntactic_ambiguity => { | |
1750 | // Disambiguate in favor of a unit struct/variant or constant pattern. | |
1751 | if let Some(binding) = binding { | |
1752 | self.r.record_use(ident, ValueNS, binding, false); | |
1753 | } | |
e1599b0c XL |
1754 | Some(res) |
1755 | } | |
ba9703b0 | 1756 | Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static, _) => { |
e1599b0c XL |
1757 | // This is unambiguously a fresh binding, either syntactically |
1758 | // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves | |
1759 | // to something unusable as a pattern (e.g., constructor function), | |
1760 | // but we still conservatively report an error, see | |
1761 | // issues/33118#issuecomment-233962221 for one reason why. | |
3dfed10e | 1762 | self.report_error( |
e1599b0c XL |
1763 | ident.span, |
1764 | ResolutionError::BindingShadowsSomethingUnacceptable( | |
1765 | pat_src.descr(), | |
1766 | ident.name, | |
ba9703b0 | 1767 | binding.expect("no binding for a ctor or static"), |
e1599b0c XL |
1768 | ), |
1769 | ); | |
1770 | None | |
1771 | } | |
ba9703b0 | 1772 | Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => { |
e1599b0c XL |
1773 | // These entities are explicitly allowed to be shadowed by fresh bindings. |
1774 | None | |
1775 | } | |
ba9703b0 XL |
1776 | _ => span_bug!( |
1777 | ident.span, | |
1778 | "unexpected resolution for an identifier in pattern: {:?}", | |
1779 | res, | |
1780 | ), | |
e1599b0c | 1781 | } |
416331ca XL |
1782 | } |
1783 | ||
1784 | // High-level and context dependent path resolution routine. | |
1785 | // Resolves the path and records the resolution into definition map. | |
1786 | // If resolution fails tries several techniques to find likely | |
1787 | // resolution candidates, suggest imports or other help, and report | |
1788 | // errors in user friendly way. | |
dfeec247 XL |
1789 | fn smart_resolve_path( |
1790 | &mut self, | |
1791 | id: NodeId, | |
1792 | qself: Option<&QSelf>, | |
1793 | path: &Path, | |
1794 | source: PathSource<'ast>, | |
1795 | ) { | |
416331ca XL |
1796 | self.smart_resolve_path_fragment( |
1797 | id, | |
1798 | qself, | |
1799 | &Segment::from_path(path), | |
1800 | path.span, | |
1801 | source, | |
1802 | CrateLint::SimplePath(id), | |
1803 | ); | |
1804 | } | |
1805 | ||
dfeec247 XL |
1806 | fn smart_resolve_path_fragment( |
1807 | &mut self, | |
1808 | id: NodeId, | |
1809 | qself: Option<&QSelf>, | |
1810 | path: &[Segment], | |
1811 | span: Span, | |
1812 | source: PathSource<'ast>, | |
1813 | crate_lint: CrateLint, | |
1814 | ) -> PartialRes { | |
3dfed10e | 1815 | tracing::debug!( |
5869c6ff | 1816 | "smart_resolve_path_fragment(id={:?}, qself={:?}, path={:?})", |
3dfed10e XL |
1817 | id, |
1818 | qself, | |
1819 | path | |
1820 | ); | |
416331ca | 1821 | let ns = source.namespace(); |
416331ca XL |
1822 | |
1823 | let report_errors = |this: &mut Self, res: Option<Res>| { | |
3dfed10e XL |
1824 | if this.should_report_errs() { |
1825 | let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res); | |
1826 | ||
5869c6ff | 1827 | let def_id = this.parent_scope.module.nearest_parent_mod; |
3dfed10e XL |
1828 | let instead = res.is_some(); |
1829 | let suggestion = | |
1830 | if res.is_none() { this.report_missing_type_error(path) } else { None }; | |
1831 | ||
1832 | this.r.use_injections.push(UseError { | |
1833 | err, | |
1834 | candidates, | |
1835 | def_id, | |
1836 | instead, | |
1837 | suggestion, | |
1838 | }); | |
1839 | } | |
f035d41b | 1840 | |
416331ca XL |
1841 | PartialRes::new(Res::Err) |
1842 | }; | |
1843 | ||
f035d41b XL |
1844 | // For paths originating from calls (like in `HashMap::new()`), tries |
1845 | // to enrich the plain `failed to resolve: ...` message with hints | |
1846 | // about possible missing imports. | |
1847 | // | |
1848 | // Similar thing, for types, happens in `report_errors` above. | |
1849 | let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| { | |
1850 | if !source.is_call() { | |
1851 | return Some(parent_err); | |
1852 | } | |
1853 | ||
1854 | // Before we start looking for candidates, we have to get our hands | |
1855 | // on the type user is trying to perform invocation on; basically: | |
5869c6ff XL |
1856 | // we're transforming `HashMap::new` into just `HashMap`. |
1857 | let path = match path.split_last() { | |
1858 | Some((_, path)) if !path.is_empty() => path, | |
1859 | _ => return Some(parent_err), | |
f035d41b XL |
1860 | }; |
1861 | ||
1862 | let (mut err, candidates) = | |
1863 | this.smart_resolve_report_errors(path, span, PathSource::Type, None); | |
1864 | ||
1865 | if candidates.is_empty() { | |
1866 | err.cancel(); | |
1867 | return Some(parent_err); | |
1868 | } | |
1869 | ||
1870 | // There are two different error messages user might receive at | |
1871 | // this point: | |
1872 | // - E0412 cannot find type `{}` in this scope | |
1873 | // - E0433 failed to resolve: use of undeclared type or module `{}` | |
1874 | // | |
1875 | // The first one is emitted for paths in type-position, and the | |
1876 | // latter one - for paths in expression-position. | |
1877 | // | |
1878 | // Thus (since we're in expression-position at this point), not to | |
1879 | // confuse the user, we want to keep the *message* from E0432 (so | |
1880 | // `parent_err`), but we want *hints* from E0412 (so `err`). | |
1881 | // | |
1882 | // And that's what happens below - we're just mixing both messages | |
1883 | // into a single one. | |
1884 | let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node); | |
1885 | ||
1886 | parent_err.cancel(); | |
1887 | ||
1888 | err.message = take(&mut parent_err.message); | |
1889 | err.code = take(&mut parent_err.code); | |
1890 | err.children = take(&mut parent_err.children); | |
1891 | ||
1892 | drop(parent_err); | |
1893 | ||
5869c6ff | 1894 | let def_id = this.parent_scope.module.nearest_parent_mod; |
f035d41b | 1895 | |
3dfed10e XL |
1896 | if this.should_report_errs() { |
1897 | this.r.use_injections.push(UseError { | |
1898 | err, | |
1899 | candidates, | |
1900 | def_id, | |
1901 | instead: false, | |
1902 | suggestion: None, | |
1903 | }); | |
1904 | } else { | |
1905 | err.cancel(); | |
1906 | } | |
f035d41b XL |
1907 | |
1908 | // We don't return `Some(parent_err)` here, because the error will | |
1909 | // be already printed as part of the `use` injections | |
1910 | None | |
1911 | }; | |
1912 | ||
416331ca XL |
1913 | let partial_res = match self.resolve_qpath_anywhere( |
1914 | id, | |
1915 | qself, | |
1916 | path, | |
1917 | ns, | |
1918 | span, | |
1919 | source.defer_to_typeck(), | |
1920 | crate_lint, | |
1921 | ) { | |
f035d41b | 1922 | Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => { |
fc512014 XL |
1923 | if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err |
1924 | { | |
416331ca XL |
1925 | partial_res |
1926 | } else { | |
60c5eb7d | 1927 | report_errors(self, Some(partial_res.base_res())) |
416331ca XL |
1928 | } |
1929 | } | |
f035d41b XL |
1930 | |
1931 | Ok(Some(partial_res)) if source.defer_to_typeck() => { | |
416331ca XL |
1932 | // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B` |
1933 | // or `<T>::A::B`. If `B` should be resolved in value namespace then | |
1934 | // it needs to be added to the trait map. | |
1935 | if ns == ValueNS { | |
1936 | let item_name = path.last().unwrap().ident; | |
5869c6ff | 1937 | let traits = self.traits_in_scope(item_name, ns); |
416331ca XL |
1938 | self.r.trait_map.insert(id, traits); |
1939 | } | |
1940 | ||
6a06907d | 1941 | if PrimTy::from_name(path[0].ident.name).is_some() { |
fc512014 XL |
1942 | let mut std_path = Vec::with_capacity(1 + path.len()); |
1943 | ||
1944 | std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std))); | |
1945 | std_path.extend(path); | |
416331ca | 1946 | if let PathResult::Module(_) | PathResult::NonModule(_) = |
f035d41b | 1947 | self.resolve_path(&std_path, Some(ns), false, span, CrateLint::No) |
dfeec247 | 1948 | { |
f035d41b | 1949 | // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8` |
dfeec247 | 1950 | let item_span = |
5869c6ff | 1951 | path.iter().last().map_or(span, |segment| segment.ident.span); |
f035d41b | 1952 | |
416331ca XL |
1953 | let mut hm = self.r.session.confused_type_with_std_module.borrow_mut(); |
1954 | hm.insert(item_span, span); | |
416331ca XL |
1955 | hm.insert(span, span); |
1956 | } | |
1957 | } | |
f035d41b | 1958 | |
416331ca XL |
1959 | partial_res |
1960 | } | |
f035d41b XL |
1961 | |
1962 | Err(err) => { | |
1963 | if let Some(err) = report_errors_for_call(self, err) { | |
3dfed10e | 1964 | self.report_error(err.span, err.node); |
f035d41b XL |
1965 | } |
1966 | ||
1967 | PartialRes::new(Res::Err) | |
1968 | } | |
1969 | ||
dfeec247 | 1970 | _ => report_errors(self, None), |
416331ca XL |
1971 | }; |
1972 | ||
5869c6ff | 1973 | if !matches!(source, PathSource::TraitItem(..)) { |
416331ca XL |
1974 | // Avoid recording definition of `A::B` in `<T as A>::B::C`. |
1975 | self.r.record_partial_res(id, partial_res); | |
1976 | } | |
f035d41b | 1977 | |
416331ca XL |
1978 | partial_res |
1979 | } | |
1980 | ||
1981 | fn self_type_is_available(&mut self, span: Span) -> bool { | |
1982 | let binding = self.resolve_ident_in_lexical_scope( | |
e1599b0c | 1983 | Ident::with_dummy_span(kw::SelfUpper), |
416331ca XL |
1984 | TypeNS, |
1985 | None, | |
1986 | span, | |
1987 | ); | |
1988 | if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false } | |
1989 | } | |
1990 | ||
1991 | fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool { | |
1992 | let ident = Ident::new(kw::SelfLower, self_span); | |
1993 | let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span); | |
1994 | if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false } | |
1995 | } | |
1996 | ||
3dfed10e XL |
1997 | /// A wrapper around [`Resolver::report_error`]. |
1998 | /// | |
1999 | /// This doesn't emit errors for function bodies if this is rustdoc. | |
2000 | fn report_error(&self, span: Span, resolution_error: ResolutionError<'_>) { | |
2001 | if self.should_report_errs() { | |
2002 | self.r.report_error(span, resolution_error); | |
2003 | } | |
2004 | } | |
2005 | ||
2006 | #[inline] | |
2007 | /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items. | |
2008 | fn should_report_errs(&self) -> bool { | |
2009 | !(self.r.session.opts.actually_rustdoc && self.in_func_body) | |
2010 | } | |
2011 | ||
416331ca XL |
2012 | // Resolve in alternative namespaces if resolution in the primary namespace fails. |
2013 | fn resolve_qpath_anywhere( | |
2014 | &mut self, | |
2015 | id: NodeId, | |
2016 | qself: Option<&QSelf>, | |
2017 | path: &[Segment], | |
2018 | primary_ns: Namespace, | |
2019 | span: Span, | |
2020 | defer_to_typeck: bool, | |
2021 | crate_lint: CrateLint, | |
f035d41b | 2022 | ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> { |
416331ca | 2023 | let mut fin_res = None; |
f035d41b | 2024 | |
fc512014 | 2025 | for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() { |
416331ca | 2026 | if i == 0 || ns != primary_ns { |
f035d41b | 2027 | match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? { |
dfeec247 XL |
2028 | Some(partial_res) |
2029 | if partial_res.unresolved_segments() == 0 || defer_to_typeck => | |
2030 | { | |
f035d41b | 2031 | return Ok(Some(partial_res)); |
dfeec247 XL |
2032 | } |
2033 | partial_res => { | |
2034 | if fin_res.is_none() { | |
fc512014 | 2035 | fin_res = partial_res; |
dfeec247 XL |
2036 | } |
2037 | } | |
416331ca XL |
2038 | } |
2039 | } | |
2040 | } | |
2041 | ||
416331ca | 2042 | assert!(primary_ns != MacroNS); |
f035d41b | 2043 | |
416331ca XL |
2044 | if qself.is_none() { |
2045 | let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident); | |
1b1a35ee | 2046 | let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None }; |
dfeec247 XL |
2047 | if let Ok((_, res)) = |
2048 | self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false) | |
2049 | { | |
f035d41b | 2050 | return Ok(Some(PartialRes::new(res))); |
416331ca XL |
2051 | } |
2052 | } | |
2053 | ||
f035d41b | 2054 | Ok(fin_res) |
416331ca XL |
2055 | } |
2056 | ||
2057 | /// Handles paths that may refer to associated items. | |
2058 | fn resolve_qpath( | |
2059 | &mut self, | |
2060 | id: NodeId, | |
2061 | qself: Option<&QSelf>, | |
2062 | path: &[Segment], | |
2063 | ns: Namespace, | |
2064 | span: Span, | |
2065 | crate_lint: CrateLint, | |
f035d41b | 2066 | ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> { |
416331ca XL |
2067 | debug!( |
2068 | "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})", | |
dfeec247 | 2069 | id, qself, path, ns, span, |
416331ca XL |
2070 | ); |
2071 | ||
2072 | if let Some(qself) = qself { | |
2073 | if qself.position == 0 { | |
2074 | // This is a case like `<T>::B`, where there is no | |
2075 | // trait to resolve. In that case, we leave the `B` | |
2076 | // segment to be resolved by type-check. | |
f035d41b | 2077 | return Ok(Some(PartialRes::with_unresolved_segments( |
dfeec247 XL |
2078 | Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), |
2079 | path.len(), | |
f035d41b | 2080 | ))); |
416331ca XL |
2081 | } |
2082 | ||
2083 | // Make sure `A::B` in `<T as A::B>::C` is a trait item. | |
2084 | // | |
2085 | // Currently, `path` names the full item (`A::B::C`, in | |
2086 | // our example). so we extract the prefix of that that is | |
2087 | // the trait (the slice upto and including | |
2088 | // `qself.position`). And then we recursively resolve that, | |
2089 | // but with `qself` set to `None`. | |
2090 | // | |
2091 | // However, setting `qself` to none (but not changing the | |
2092 | // span) loses the information about where this path | |
2093 | // *actually* appears, so for the purposes of the crate | |
2094 | // lint we pass along information that this is the trait | |
2095 | // name from a fully qualified path, and this also | |
2096 | // contains the full span (the `CrateLint::QPathTrait`). | |
2097 | let ns = if qself.position + 1 == path.len() { ns } else { TypeNS }; | |
2098 | let partial_res = self.smart_resolve_path_fragment( | |
2099 | id, | |
2100 | None, | |
2101 | &path[..=qself.position], | |
2102 | span, | |
2103 | PathSource::TraitItem(ns), | |
dfeec247 | 2104 | CrateLint::QPathTrait { qpath_id: id, qpath_span: qself.path_span }, |
416331ca XL |
2105 | ); |
2106 | ||
2107 | // The remaining segments (the `C` in our example) will | |
2108 | // have to be resolved by type-check, since that requires doing | |
2109 | // trait resolution. | |
f035d41b | 2110 | return Ok(Some(PartialRes::with_unresolved_segments( |
416331ca XL |
2111 | partial_res.base_res(), |
2112 | partial_res.unresolved_segments() + path.len() - qself.position - 1, | |
f035d41b | 2113 | ))); |
416331ca XL |
2114 | } |
2115 | ||
2116 | let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) { | |
2117 | PathResult::NonModule(path_res) => path_res, | |
2118 | PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => { | |
2119 | PartialRes::new(module.res().unwrap()) | |
2120 | } | |
2121 | // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we | |
2122 | // don't report an error right away, but try to fallback to a primitive type. | |
2123 | // So, we are still able to successfully resolve something like | |
2124 | // | |
2125 | // use std::u8; // bring module u8 in scope | |
2126 | // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8 | |
2127 | // u8::max_value() // OK, resolves to associated function <u8>::max_value, | |
2128 | // // not to non-existent std::u8::max_value | |
2129 | // } | |
2130 | // | |
2131 | // Such behavior is required for backward compatibility. | |
2132 | // The same fallback is used when `a` resolves to nothing. | |
dfeec247 XL |
2133 | PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. } |
2134 | if (ns == TypeNS || path.len() > 1) | |
6a06907d | 2135 | && PrimTy::from_name(path[0].ident.name).is_some() => |
dfeec247 | 2136 | { |
6a06907d | 2137 | let prim = PrimTy::from_name(path[0].ident.name).unwrap(); |
416331ca XL |
2138 | PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1) |
2139 | } | |
dfeec247 XL |
2140 | PathResult::Module(ModuleOrUniformRoot::Module(module)) => { |
2141 | PartialRes::new(module.res().unwrap()) | |
2142 | } | |
416331ca | 2143 | PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => { |
f035d41b | 2144 | return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion })); |
416331ca | 2145 | } |
f035d41b XL |
2146 | PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None), |
2147 | PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"), | |
416331ca XL |
2148 | }; |
2149 | ||
dfeec247 XL |
2150 | if path.len() > 1 |
2151 | && result.base_res() != Res::Err | |
2152 | && path[0].ident.name != kw::PathRoot | |
2153 | && path[0].ident.name != kw::DollarCrate | |
2154 | { | |
416331ca XL |
2155 | let unqualified_result = { |
2156 | match self.resolve_path( | |
2157 | &[*path.last().unwrap()], | |
2158 | Some(ns), | |
2159 | false, | |
2160 | span, | |
2161 | CrateLint::No, | |
2162 | ) { | |
2163 | PathResult::NonModule(path_res) => path_res.base_res(), | |
dfeec247 XL |
2164 | PathResult::Module(ModuleOrUniformRoot::Module(module)) => { |
2165 | module.res().unwrap() | |
2166 | } | |
f035d41b | 2167 | _ => return Ok(Some(result)), |
416331ca XL |
2168 | } |
2169 | }; | |
2170 | if result.base_res() == unqualified_result { | |
2171 | let lint = lint::builtin::UNUSED_QUALIFICATIONS; | |
e74abb32 | 2172 | self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification") |
416331ca XL |
2173 | } |
2174 | } | |
2175 | ||
f035d41b | 2176 | Ok(Some(result)) |
416331ca XL |
2177 | } |
2178 | ||
e1599b0c | 2179 | fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) { |
416331ca | 2180 | if let Some(label) = label { |
60c5eb7d XL |
2181 | if label.ident.as_str().as_bytes()[1] != b'_' { |
2182 | self.diagnostic_metadata.unused_labels.insert(id, label.ident.span); | |
2183 | } | |
e1599b0c | 2184 | self.with_label_rib(NormalRibKind, |this| { |
ba9703b0 | 2185 | let ident = label.ident.normalize_to_macro_rules(); |
416331ca XL |
2186 | this.label_ribs.last_mut().unwrap().bindings.insert(ident, id); |
2187 | f(this); | |
2188 | }); | |
2189 | } else { | |
2190 | f(self); | |
2191 | } | |
2192 | } | |
2193 | ||
dfeec247 | 2194 | fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) { |
416331ca XL |
2195 | self.with_resolved_label(label, id, |this| this.visit_block(block)); |
2196 | } | |
2197 | ||
dfeec247 | 2198 | fn resolve_block(&mut self, block: &'ast Block) { |
e1599b0c XL |
2199 | debug!("(resolving block) entering block"); |
2200 | // Move down in the graph, if there's an anonymous module rooted here. | |
2201 | let orig_module = self.parent_scope.module; | |
2202 | let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference | |
2203 | ||
2204 | let mut num_macro_definition_ribs = 0; | |
2205 | if let Some(anonymous_module) = anonymous_module { | |
2206 | debug!("(resolving block) found anonymous module, moving down"); | |
2207 | self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module))); | |
2208 | self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module))); | |
2209 | self.parent_scope.module = anonymous_module; | |
2210 | } else { | |
2211 | self.ribs[ValueNS].push(Rib::new(NormalRibKind)); | |
2212 | } | |
2213 | ||
2214 | // Descend into the block. | |
2215 | for stmt in &block.stmts { | |
e74abb32 XL |
2216 | if let StmtKind::Item(ref item) = stmt.kind { |
2217 | if let ItemKind::MacroDef(..) = item.kind { | |
e1599b0c | 2218 | num_macro_definition_ribs += 1; |
f035d41b | 2219 | let res = self.r.local_def_id(item.id).to_def_id(); |
e1599b0c XL |
2220 | self.ribs[ValueNS].push(Rib::new(MacroDefinition(res))); |
2221 | self.label_ribs.push(Rib::new(MacroDefinition(res))); | |
2222 | } | |
2223 | } | |
2224 | ||
2225 | self.visit_stmt(stmt); | |
2226 | } | |
2227 | ||
2228 | // Move back up. | |
2229 | self.parent_scope.module = orig_module; | |
dfeec247 | 2230 | for _ in 0..num_macro_definition_ribs { |
e1599b0c XL |
2231 | self.ribs[ValueNS].pop(); |
2232 | self.label_ribs.pop(); | |
2233 | } | |
2234 | self.ribs[ValueNS].pop(); | |
2235 | if anonymous_module.is_some() { | |
2236 | self.ribs[TypeNS].pop(); | |
2237 | } | |
2238 | debug!("(resolving block) leaving block"); | |
2239 | } | |
2240 | ||
29967ef6 XL |
2241 | fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) { |
2242 | debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat); | |
2243 | self.with_constant_rib( | |
2244 | is_repeat, | |
2245 | constant.value.is_potential_trivial_const_param(), | |
5869c6ff | 2246 | None, |
29967ef6 XL |
2247 | |this| { |
2248 | visit::walk_anon_const(this, constant); | |
2249 | }, | |
2250 | ); | |
2251 | } | |
2252 | ||
dfeec247 | 2253 | fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) { |
416331ca XL |
2254 | // First, record candidate traits for this expression if it could |
2255 | // result in the invocation of a method call. | |
2256 | ||
2257 | self.record_candidate_traits_for_expr_if_necessary(expr); | |
2258 | ||
2259 | // Next, resolve the node. | |
e74abb32 | 2260 | match expr.kind { |
416331ca XL |
2261 | ExprKind::Path(ref qself, ref path) => { |
2262 | self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent)); | |
2263 | visit::walk_expr(self, expr); | |
2264 | } | |
2265 | ||
6a06907d XL |
2266 | ExprKind::Struct(ref se) => { |
2267 | self.smart_resolve_path(expr.id, None, &se.path, PathSource::Struct); | |
416331ca XL |
2268 | visit::walk_expr(self, expr); |
2269 | } | |
2270 | ||
2271 | ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => { | |
f035d41b XL |
2272 | if let Some(node_id) = self.resolve_label(label.ident) { |
2273 | // Since this res is a label, it is never read. | |
2274 | self.r.label_res_map.insert(expr.id, node_id); | |
2275 | self.diagnostic_metadata.unused_labels.remove(&node_id); | |
416331ca XL |
2276 | } |
2277 | ||
2278 | // visit `break` argument if any | |
2279 | visit::walk_expr(self, expr); | |
2280 | } | |
2281 | ||
5869c6ff XL |
2282 | ExprKind::Break(None, Some(ref e)) => { |
2283 | // We use this instead of `visit::walk_expr` to keep the parent expr around for | |
2284 | // better diagnostics. | |
2285 | self.resolve_expr(e, Some(&expr)); | |
2286 | } | |
2287 | ||
e1599b0c | 2288 | ExprKind::Let(ref pat, ref scrutinee) => { |
416331ca | 2289 | self.visit_expr(scrutinee); |
e1599b0c | 2290 | self.resolve_pattern_top(pat, PatternSource::Let); |
416331ca XL |
2291 | } |
2292 | ||
2293 | ExprKind::If(ref cond, ref then, ref opt_else) => { | |
e1599b0c | 2294 | self.with_rib(ValueNS, NormalRibKind, |this| { |
1b1a35ee | 2295 | let old = this.diagnostic_metadata.in_if_condition.replace(cond); |
e1599b0c | 2296 | this.visit_expr(cond); |
1b1a35ee | 2297 | this.diagnostic_metadata.in_if_condition = old; |
e1599b0c XL |
2298 | this.visit_block(then); |
2299 | }); | |
f9f354fc XL |
2300 | if let Some(expr) = opt_else { |
2301 | self.visit_expr(expr); | |
2302 | } | |
416331ca XL |
2303 | } |
2304 | ||
2305 | ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block), | |
2306 | ||
e1599b0c | 2307 | ExprKind::While(ref cond, ref block, label) => { |
416331ca | 2308 | self.with_resolved_label(label, expr.id, |this| { |
e1599b0c XL |
2309 | this.with_rib(ValueNS, NormalRibKind, |this| { |
2310 | this.visit_expr(cond); | |
2311 | this.visit_block(block); | |
2312 | }) | |
416331ca XL |
2313 | }); |
2314 | } | |
2315 | ||
e1599b0c XL |
2316 | ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => { |
2317 | self.visit_expr(iter_expr); | |
2318 | self.with_rib(ValueNS, NormalRibKind, |this| { | |
2319 | this.resolve_pattern_top(pat, PatternSource::For); | |
2320 | this.resolve_labeled_block(label, expr.id, block); | |
2321 | }); | |
416331ca XL |
2322 | } |
2323 | ||
2324 | ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block), | |
2325 | ||
2326 | // Equivalent to `visit::walk_expr` + passing some context to children. | |
2327 | ExprKind::Field(ref subexpression, _) => { | |
2328 | self.resolve_expr(subexpression, Some(expr)); | |
2329 | } | |
f035d41b | 2330 | ExprKind::MethodCall(ref segment, ref arguments, _) => { |
416331ca XL |
2331 | let mut arguments = arguments.iter(); |
2332 | self.resolve_expr(arguments.next().unwrap(), Some(expr)); | |
2333 | for argument in arguments { | |
2334 | self.resolve_expr(argument, None); | |
2335 | } | |
2336 | self.visit_path_segment(expr.span, segment); | |
2337 | } | |
2338 | ||
2339 | ExprKind::Call(ref callee, ref arguments) => { | |
2340 | self.resolve_expr(callee, Some(expr)); | |
cdc7bbd5 | 2341 | let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default(); |
6a06907d XL |
2342 | for (idx, argument) in arguments.iter().enumerate() { |
2343 | // Constant arguments need to be treated as AnonConst since | |
2344 | // that is how they will be later lowered to HIR. | |
2345 | if const_args.contains(&idx) { | |
2346 | self.with_constant_rib( | |
2347 | IsRepeatExpr::No, | |
2348 | argument.is_potential_trivial_const_param(), | |
2349 | None, | |
2350 | |this| { | |
2351 | this.resolve_expr(argument, None); | |
2352 | }, | |
2353 | ); | |
2354 | } else { | |
2355 | self.resolve_expr(argument, None); | |
2356 | } | |
416331ca XL |
2357 | } |
2358 | } | |
3dfed10e XL |
2359 | ExprKind::Type(ref type_expr, ref ty) => { |
2360 | // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in | |
2361 | // type ascription. Here we are trying to retrieve the span of the colon token as | |
2362 | // well, but only if it's written without spaces `expr:Ty` and therefore confusable | |
2363 | // with `expr::Ty`, only in this case it will match the span from | |
2364 | // `type_ascription_path_suggestions`. | |
2365 | self.diagnostic_metadata | |
2366 | .current_type_ascription | |
2367 | .push(type_expr.span.between(ty.span)); | |
416331ca | 2368 | visit::walk_expr(self, expr); |
e74abb32 | 2369 | self.diagnostic_metadata.current_type_ascription.pop(); |
416331ca XL |
2370 | } |
2371 | // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to | |
2372 | // resolve the arguments within the proper scopes so that usages of them inside the | |
2373 | // closure are detected as upvars rather than normal closure arg usages. | |
74b04a01 | 2374 | ExprKind::Closure(_, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => { |
e1599b0c | 2375 | self.with_rib(ValueNS, NormalRibKind, |this| { |
f035d41b XL |
2376 | this.with_label_rib(ClosureOrAsyncRibKind, |this| { |
2377 | // Resolve arguments: | |
2378 | this.resolve_params(&fn_decl.inputs); | |
2379 | // No need to resolve return type -- | |
2380 | // the outer closure return type is `FnRetTy::Default`. | |
e1599b0c | 2381 | |
f035d41b XL |
2382 | // Now resolve the inner closure |
2383 | { | |
2384 | // No need to resolve arguments: the inner closure has none. | |
2385 | // Resolve the return type: | |
2386 | visit::walk_fn_ret_ty(this, &fn_decl.output); | |
2387 | // Resolve the body | |
2388 | this.visit_expr(body); | |
2389 | } | |
2390 | }) | |
e1599b0c | 2391 | }); |
416331ca | 2392 | } |
f035d41b XL |
2393 | ExprKind::Async(..) | ExprKind::Closure(..) => { |
2394 | self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr)); | |
2395 | } | |
29967ef6 XL |
2396 | ExprKind::Repeat(ref elem, ref ct) => { |
2397 | self.visit_expr(elem); | |
2398 | self.resolve_anon_const(ct, IsRepeatExpr::Yes); | |
2399 | } | |
416331ca XL |
2400 | _ => { |
2401 | visit::walk_expr(self, expr); | |
2402 | } | |
2403 | } | |
2404 | } | |
2405 | ||
dfeec247 | 2406 | fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) { |
e74abb32 | 2407 | match expr.kind { |
416331ca XL |
2408 | ExprKind::Field(_, ident) => { |
2409 | // FIXME(#6890): Even though you can't treat a method like a | |
2410 | // field, we need to add any trait methods we find that match | |
2411 | // the field name so that we can do some nice error reporting | |
2412 | // later on in typeck. | |
5869c6ff | 2413 | let traits = self.traits_in_scope(ident, ValueNS); |
416331ca XL |
2414 | self.r.trait_map.insert(expr.id, traits); |
2415 | } | |
2416 | ExprKind::MethodCall(ref segment, ..) => { | |
dfeec247 | 2417 | debug!("(recording candidate traits for expr) recording traits for {}", expr.id); |
5869c6ff | 2418 | let traits = self.traits_in_scope(segment.ident, ValueNS); |
416331ca XL |
2419 | self.r.trait_map.insert(expr.id, traits); |
2420 | } | |
2421 | _ => { | |
2422 | // Nothing to do. | |
2423 | } | |
2424 | } | |
2425 | } | |
2426 | ||
5869c6ff XL |
2427 | fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> { |
2428 | self.r.traits_in_scope( | |
2429 | self.current_trait_ref.as_ref().map(|(module, _)| *module), | |
2430 | &self.parent_scope, | |
2431 | ident.span.ctxt(), | |
2432 | Some((ident.name, ns)), | |
2433 | ) | |
416331ca | 2434 | } |
416331ca XL |
2435 | } |
2436 | ||
2437 | impl<'a> Resolver<'a> { | |
2438 | pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) { | |
416331ca XL |
2439 | let mut late_resolution_visitor = LateResolutionVisitor::new(self); |
2440 | visit::walk_crate(&mut late_resolution_visitor, krate); | |
e74abb32 XL |
2441 | for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() { |
2442 | self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label"); | |
416331ca XL |
2443 | } |
2444 | } | |
2445 | } |