Debian Codegraph @

gcc/rust/resolve/rust-late-name-resolver-2.0.cc

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 #include "optional.h"
20 #include "rust-ast-full.h"
21 #include "rust-diagnostics.h"
22 #include "rust-hir-map.h"
23 #include "rust-late-name-resolver-2.0.h"
24 #include "rust-default-resolver.h"
25 #include "rust-name-resolution-context.h"
26 #include "rust-path.h"
27 #include "rust-system.h"
28 #include "rust-tyty.h"
29 #include "rust-hir-type-check.h"
30 #include "rust-ice-finalizer.h"
31 #include "rust-ast.h"
32
33 namespace Rust {
34 namespace Resolver2_0 {
35
36 Late::Late (NameResolutionContext &ctx)
37 : DefaultResolver (ctx), funny_error (false)
38 {}
39
40 static NodeId
41 next_node_id ()
42 {
43 return Analysis::Mappings::get ().get_next_node_id ();
44 };
45
46 static HirId
47 next_hir_id ()
48 {
49 return Analysis::Mappings::get ().get_next_hir_id ();
50 };
51
52 void
53 Late::setup_builtin_types ()
54 {
55 // access the global type context to setup the TyTys
56 auto &ty_ctx = *Resolver::TypeCheckContext::get ();
57
58 // Late builtin type struct helper
59 struct LType
60 {
61 std::string name;
62 NodeId node_id;
63 NodeId hir_id;
64 TyTy::BaseType *type;
65
66 explicit LType (std::string name, TyTy::BaseType *type)
67 : name (name), node_id (next_node_id ()), hir_id (type->get_ref ()),
68 type (type)
69 {}
70 };
71
72 static const LType builtins[] = {
73 {LType ("bool", new TyTy::BoolType (next_hir_id ()))},
74 {LType ("u8", new TyTy::UintType (next_hir_id (), TyTy::UintType::U8))},
75 {LType ("u16", new TyTy::UintType (next_hir_id (), TyTy::UintType::U16))},
76 {LType ("u32", new TyTy::UintType (next_hir_id (), TyTy::UintType::U32))},
77 {LType ("u64", new TyTy::UintType (next_hir_id (), TyTy::UintType::U64))},
78 {LType ("u128", new TyTy::UintType (next_hir_id (), TyTy::UintType::U128))},
79 {LType ("i8", new TyTy::IntType (next_hir_id (), TyTy::IntType::I8))},
80 {LType ("i16", new TyTy::IntType (next_hir_id (), TyTy::IntType::I16))},
81 {LType ("i32", new TyTy::IntType (next_hir_id (), TyTy::IntType::I32))},
82 {LType ("i64", new TyTy::IntType (next_hir_id (), TyTy::IntType::I64))},
83 {LType ("i128", new TyTy::IntType (next_hir_id (), TyTy::IntType::I128))},
84 {LType ("f32", new TyTy::FloatType (next_hir_id (), TyTy::FloatType::F32))},
85 {LType ("f64", new TyTy::FloatType (next_hir_id (), TyTy::FloatType::F64))},
86 {LType ("usize", new TyTy::USizeType (next_hir_id ()))},
87 {LType ("isize", new TyTy::ISizeType (next_hir_id ()))},
88 {LType ("char", new TyTy::CharType (next_hir_id ()))},
89 {LType ("str", new TyTy::StrType (next_hir_id ()))},
90 {LType ("!", new TyTy::NeverType (next_hir_id ()))},
91
92 // the unit type `()` does not play a part in name-resolution - so we only
93 // insert it in the type context...
94 };
95
96 // There's a special Rib for putting prelude items, since prelude items need
97 // to satisfy certain special rules.
98 ctx.scoped (Rib::Kind::Prelude, 0, [this, &ty_ctx] (void) -> void {
99 for (const auto &builtin : builtins)
100 {
101 auto ok = ctx.types.insert (builtin.name, builtin.node_id);
102 rust_assert (ok);
103
104 ctx.mappings.insert_node_to_hir (builtin.node_id, builtin.hir_id);
105 ty_ctx.insert_builtin (builtin.hir_id, builtin.node_id, builtin.type);
106 }
107 });
108
109 // ...here!
110 auto *unit_type = TyTy::TupleType::get_unit_type ();
111 ty_ctx.insert_builtin (unit_type->get_ref (), next_node_id (), unit_type);
112 }
113
114 void
115 Late::go (AST::Crate &crate)
116 {
117 setup_builtin_types ();
118
119 for (auto &item : crate.items)
120 item->accept_vis (*this);
121 }
122
123 void
124 Late::new_label (Identifier name, NodeId id)
125 {
126 // labels can always shadow, so `insert` should never fail. if it does, we're
127 // in big trouble!
128 auto ok = ctx.labels.insert (name, id);
129
130 rust_assert (ok);
131 }
132
133 void
134 Late::visit (AST::LetStmt &let)
135 {
136 DefaultASTVisitor::visit_outer_attrs (let);
137 if (let.has_type ())
138 visit (let.get_type ());
139 // visit expression before pattern
140 // this makes variable shadowing work properly
141 if (let.has_init_expr ())
142 visit (let.get_init_expr ());
143 visit (let.get_pattern ());
144
145 if (let.has_else_expr ())
146 visit (let.get_init_expr ());
147
148 // how do we deal with the fact that `let a = blipbloup` should look for a
149 // label and cannot go through function ribs, but `let a = blipbloup()` can?
150
151 // how do we insert ribs here, and only pop them when we exit the current
152 // function?
153 // keep a list of ribs to pop when a scope exits? so only for blocks?
154 // how do we pop ribs that need to be popped not in order?
155 // I think it's not important if we have shadowing, correct?
156
157 // if we have shadowing, it should work! we'll see
158
159 // ctx.insert(Identifier name, NodeId id, Namespace ns)
160 // ctx.scoped (Rib::Kind::Normal /* FIXME: Is that valid? */,
161 // Namespace::Labels,
162 // let.get_node_id (), [] () {});
163 }
164
165 void
166 Late::visit (AST::IdentifierPattern &identifier)
167 {
168 // do we insert in labels or in values
169 // but values does not allow shadowing... since functions cannot shadow
170 // do we insert functions in labels as well?
171
172 // We do want to ignore duplicated data because some situations rely on it.
173 std::ignore = ctx.values.insert_shadowable (identifier.get_ident (),
174 identifier.get_node_id ());
175 }
176
177 void
178 Late::visit (AST::SelfParam &param)
179 {
180 // handle similar to AST::IdentifierPattern
181
182 DefaultResolver::visit (param);
183 // FIXME: this location should be a bit off
184 // ex: would point to the begining of "mut self" instead of the "self"
185 std::ignore = ctx.values.insert (Identifier ("self", param.get_locus ()),
186 param.get_node_id ());
187 }
188
189 void
190 Late::visit (AST::BreakExpr &expr)
191 {
192 if (expr.has_label ())
193 resolve_label (expr.get_label_unchecked ().get_lifetime ());
194
195 if (expr.has_break_expr ())
196 {
197 auto &break_expr = expr.get_break_expr ();
198 if (break_expr.get_expr_kind () == AST::Expr::Kind::Identifier)
199 {
200 /* This is a break with an expression, and the expression is
201 just a single identifier. See if the identifier is either
202 "rust" or "gcc", in which case we have "break rust" or "break
203 gcc", and so may need to emit our funny error. We cannot yet
204 emit the error here though, because the identifier may still
205 be in scope, and ICE'ing on valid programs would not be very
206 funny. */
207 std::string ident
208 = static_cast<AST::IdentifierExpr &> (expr.get_break_expr ())
209 .as_string ();
210 if (ident == "rust" || ident == "gcc")
211 funny_error = true;
212 }
213 }
214
215 DefaultResolver::visit (expr);
216
217 funny_error = false;
218 }
219
220 void
221 Late::visit (AST::LoopLabel &label)
222 {
223 auto &lifetime = label.get_lifetime ();
224 ctx.labels.insert (Identifier (lifetime.as_string (), lifetime.get_locus ()),
225 lifetime.get_node_id ());
226 }
227
228 void
229 Late::resolve_label (AST::Lifetime &lifetime)
230 {
231 if (auto resolved = ctx.labels.get (lifetime.as_string ()))
232 {
233 if (resolved->get_node_id () != lifetime.get_node_id ())
234 ctx.map_usage (Usage (lifetime.get_node_id ()),
235 Definition (resolved->get_node_id ()));
236 }
237 else
238 rust_error_at (lifetime.get_locus (), ErrorCode::E0426,
239 "use of undeclared label %qs",
240 lifetime.as_string ().c_str ());
241 }
242
243 void
244 Late::visit (AST::ContinueExpr &expr)
245 {
246 if (expr.has_label ())
247 resolve_label (expr.get_label_unchecked ());
248
249 DefaultResolver::visit (expr);
250 }
251
252 void
253 Late::visit (AST::IdentifierExpr &expr)
254 {
255 // TODO: same thing as visit(PathInExpression) here?
256
257 tl::optional<Rib::Definition> resolved = tl::nullopt;
258 if (auto value = ctx.values.get (expr.get_ident ()))
259 {
260 resolved = value;
261 }
262 else if (auto type = ctx.types.get (expr.get_ident ()))
263 {
264 resolved = type;
265 }
266 else if (funny_error)
267 {
268 diagnostic_text_finalizer (global_dc) = Resolver::funny_ice_text_finalizer;
269 emit_diagnostic (DK_ICE_NOBT, expr.get_locus (), -1,
270 "are you trying to break %s? how dare you?",
271 expr.as_string ().c_str ());
272 }
273 else
274 {
275 if (auto type = ctx.types.get_lang_prelude (expr.get_ident ()))
276 {
277 resolved = type;
278 }
279 else
280 {
281 rust_error_at (expr.get_locus (), ErrorCode::E0425,
282 "cannot find value %qs in this scope",
283 expr.get_ident ().as_string ().c_str ());
284 return;
285 }
286 }
287
288 if (resolved->is_ambiguous ())
289 {
290 rust_error_at (expr.get_locus (), ErrorCode::E0659, "%qs is ambiguous",
291 expr.as_string ().c_str ());
292 return;
293 }
294
295 ctx.map_usage (Usage (expr.get_node_id ()),
296 Definition (resolved->get_node_id ()));
297
298 // For empty types, do we perform a lookup in ctx.types or should the
299 // toplevel instead insert a name in ctx.values? (like it currently does)
300 }
301
302 void
303 Late::visit (AST::StructExprFieldIdentifier &expr)
304 {
305 tl::optional<Rib::Definition> resolved = tl::nullopt;
306
307 if (auto value = ctx.values.get (expr.get_field_name ()))
308 {
309 resolved = value;
310 }
311 // seems like we don't need a type namespace lookup
312 else
313 {
314 rust_error_at (expr.get_locus (), "could not resolve struct field: %qs",
315 expr.get_field_name ().as_string ().c_str ());
316 return;
317 }
318
319 if (resolved->is_ambiguous ())
320 {
321 rust_error_at (expr.get_locus (), ErrorCode::E0659, "%qs is ambiguous",
322 expr.as_string ().c_str ());
323 return;
324 }
325
326 ctx.map_usage (Usage (expr.get_node_id ()),
327 Definition (resolved->get_node_id ()));
328 }
329
330 void
331 Late::visit (AST::PathInExpression &expr)
332 {
333 // TODO: How do we have a nice error with `can't capture dynamic environment
334 // in a function item` error here?
335 // do we emit it in `get<Namespace::Labels>`?
336
337 DefaultResolver::visit (expr);
338
339 if (expr.is_lang_item ())
340 {
341 ctx.map_usage (Usage (expr.get_node_id ()),
342 Definition (Analysis::Mappings::get ().get_lang_item_node (
343 expr.get_lang_item ())));
344 return;
345 }
346
347 auto resolved = ctx.resolve_path (expr, Namespace::Values, Namespace::Types);
348
349 if (!resolved)
350 {
351 if (!ctx.lookup (expr.get_segments ().front ().get_node_id ()))
352 rust_error_at (expr.get_locus (),
353 "could not resolve path expression: %qs",
354 expr.as_simple_path ().as_string ().c_str ());
355 return;
356 }
357
358 if (resolved->is_ambiguous ())
359 {
360 rust_error_at (expr.get_locus (), ErrorCode::E0659, "%qs is ambiguous",
361 expr.as_string ().c_str ());
362 return;
363 }
364
365 ctx.map_usage (Usage (expr.get_node_id ()),
366 Definition (resolved->get_node_id ()));
367 }
368
369 void
370 Late::visit (AST::TypePath &type)
371 {
372 // should we add type path resolution in `ForeverStack` directly? Since it's
373 // quite more complicated.
374 // maybe we can overload `resolve_path<Namespace::Types>` to only do
375 // typepath-like path resolution? that sounds good
376
377 DefaultResolver::visit (type);
378
379 // this *should* mostly work
380 // TODO: make sure typepath-like path resolution (?) is working
381 auto resolved = ctx.resolve_path (type, Namespace::Types);
382
383 if (!resolved.has_value ())
384 {
385 if (!ctx.lookup (type.get_segments ().front ()->get_node_id ()))
386 rust_error_at (type.get_locus (), "could not resolve type path %qs",
387 type.as_string ().c_str ());
388 return;
389 }
390
391 if (resolved->is_ambiguous ())
392 {
393 rust_error_at (type.get_locus (), ErrorCode::E0659, "%qs is ambiguous",
394 type.as_string ().c_str ());
395 return;
396 }
397
398 ctx.map_usage (Usage (type.get_node_id ()),
399 Definition (resolved->get_node_id ()));
400 }
401
402 void
403 Late::visit (AST::Trait &trait)
404 {
405 // kind of weird how this is done
406 // names are resolved to the node id of trait.get_implicit_self ()
407 // which is then resolved to the node id of trait
408 // we set up the latter mapping here
409 ctx.map_usage (Usage (trait.get_implicit_self ().get_node_id ()),
410 Definition (trait.get_node_id ()));
411
412 DefaultResolver::visit (trait);
413 }
414
415 void
416 Late::visit (AST::StructStruct &s)
417 {
418 auto s_vis = [this, &s] () { AST::DefaultASTVisitor::visit (s); };
419 ctx.scoped (Rib::Kind::Item, s.get_node_id (), s_vis);
420 }
421
422 void
423 Late::visit (AST::StructExprStruct &s)
424 {
425 visit_outer_attrs (s);
426 visit_inner_attrs (s);
427 DefaultResolver::visit (s.get_struct_name ());
428
429 auto resolved = ctx.resolve_path (s.get_struct_name (), Namespace::Types);
430
431 ctx.map_usage (Usage (s.get_struct_name ().get_node_id ()),
432 Definition (resolved->get_node_id ()));
433 }
434
435 void
436 Late::visit (AST::StructExprStructBase &s)
437 {
438 visit_outer_attrs (s);
439 visit_inner_attrs (s);
440 DefaultResolver::visit (s.get_struct_name ());
441 visit (s.get_struct_base ());
442
443 auto resolved = ctx.resolve_path (s.get_struct_name (), Namespace::Types);
444
445 ctx.map_usage (Usage (s.get_struct_name ().get_node_id ()),
446 Definition (resolved->get_node_id ()));
447 }
448
449 void
450 Late::visit (AST::StructExprStructFields &s)
451 {
452 visit_outer_attrs (s);
453 visit_inner_attrs (s);
454 DefaultResolver::visit (s.get_struct_name ());
455 if (s.has_struct_base ())
456 visit (s.get_struct_base ());
457 for (auto &field : s.get_fields ())
458 visit (field);
459
460 auto resolved = ctx.resolve_path (s.get_struct_name (), Namespace::Types);
461
462 ctx.map_usage (Usage (s.get_struct_name ().get_node_id ()),
463 Definition (resolved->get_node_id ()));
464 }
465
466 // needed because Late::visit (AST::GenericArg &) is non-virtual
467 void
468 Late::visit (AST::GenericArgs &args)
469 {
470 for (auto &lifetime : args.get_lifetime_args ())
471 visit (lifetime);
472
473 for (auto &generic : args.get_generic_args ())
474 visit (generic);
475
476 for (auto &binding : args.get_binding_args ())
477 visit (binding);
478 }
479
480 void
481 Late::visit (AST::GenericArg &arg)
482 {
483 if (arg.get_kind () == AST::GenericArg::Kind::Either)
484 {
485 // prefer type parameter to const parameter on ambiguity
486 auto type = ctx.types.get (arg.get_path ());
487 auto value = ctx.values.get (arg.get_path ());
488
489 if (!type.has_value () && value.has_value ())
490 arg = arg.disambiguate_to_const ();
491 else
492 arg = arg.disambiguate_to_type ();
493 }
494
495 DefaultResolver::visit (arg);
496 }
497
498 template <class Closure>
499 static void
500 add_captures (Closure &closure, NameResolutionContext &ctx)
501 {
502 auto vals = ctx.values.peek ().get_values ();
503 for (auto &val : vals)
504 {
505 ctx.mappings.add_capture (closure.get_node_id (),
506 val.second.get_node_id ());
507 }
508 }
509
510 void
511 Late::visit (AST::ClosureExprInner &closure)
512 {
513 add_captures (closure, ctx);
514 DefaultResolver::visit (closure);
515 }
516
517 void
518 Late::visit (AST::ClosureExprInnerTyped &closure)
519 {
520 add_captures (closure, ctx);
521 DefaultResolver::visit (closure);
522 }
523
524 } // namespace Resolver2_0
525 } // namespace Rust