Debian Codegraph @

gcc/rust/typecheck/rust-hir-type-check.h

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 #ifndef RUST_HIR_TYPE_CHECK
20 #define RUST_HIR_TYPE_CHECK
21
22 #include "rust-hir-map.h"
23 #include "rust-tyty.h"
24 #include "rust-hir-trait-reference.h"
25 #include "rust-stacked-contexts.h"
26 #include "rust-autoderef.h"
27 #include "rust-tyty-region.h"
28 #include "rust-tyty-variance-analysis.h"
29 #include "rust-system.h"
30
31 namespace Rust {
32 namespace Resolver {
33
34 class TypeCheckContextItem
35 {
36 public:
37 enum ItemType
38 {
39 ITEM,
40 IMPL_ITEM,
41 TRAIT_ITEM,
42 ERROR
43 };
44
45 TypeCheckContextItem (HIR::Function *item);
46 TypeCheckContextItem (HIR::ImplBlock &impl_block, HIR::Function *item);
47 TypeCheckContextItem (HIR::TraitItemFunc *trait_item);
48 TypeCheckContextItem (const TypeCheckContextItem &other);
49
50 TypeCheckContextItem &operator= (const TypeCheckContextItem &other);
51
52 static TypeCheckContextItem get_error ();
53
54 bool is_error () const;
55
56 ItemType get_type () const;
57
58 HIR::Function *get_item ();
59
60 std::pair<HIR::ImplBlock *, HIR::Function *> &get_impl_item ();
61
62 HIR::TraitItemFunc *get_trait_item ();
63
64 TyTy::FnType *get_context_type ();
65
66 DefId get_defid () const;
67
68 private:
69 TypeCheckContextItem ();
70
71 union Item
72 {
73 HIR::Function *item;
74 std::pair<HIR::ImplBlock *, HIR::Function *> impl_item;
75 HIR::TraitItemFunc *trait_item;
76
77 Item (HIR::Function *item);
78 Item (HIR::ImplBlock *impl_block, HIR::Function *item);
79 Item (HIR::TraitItemFunc *trait_item);
80 };
81
82 ItemType type;
83 Item item;
84 };
85
86 class TypeCheckBlockContextItem
87 {
88 public:
89 enum ItemType
90 {
91 IMPL_BLOCK,
92 TRAIT
93 };
94
95 TypeCheckBlockContextItem (HIR::ImplBlock *block);
96 TypeCheckBlockContextItem (HIR::Trait *trait);
97
98 bool is_impl_block () const;
99 bool is_trait_block () const;
100
101 HIR::ImplBlock &get_impl_block ();
102 HIR::Trait &get_trait ();
103
104 private:
105 union Item
106 {
107 HIR::ImplBlock *block;
108 HIR::Trait *trait;
109
110 Item (HIR::ImplBlock *block);
111 Item (HIR::Trait *trait);
112 };
113 ItemType type;
114 Item item;
115 };
116
117 /**
118 * Interned lifetime representation in TyTy
119 *
120 * On the HIR->TyTy boundary HIR::Lifetime is interned into this struct.
121 */
122 class Lifetime
123 {
124 uint32_t interner_index;
125
126 public:
127 explicit constexpr Lifetime (uint32_t interner_index)
128 : interner_index (interner_index)
129 {}
130
131 Lifetime () = default;
132
133 WARN_UNUSED_RESULT bool is_static () const { return interner_index == 0; }
134
135 WARN_UNUSED_RESULT static constexpr Lifetime static_lifetime ()
136 {
137 return Lifetime (0);
138 }
139
140 WARN_UNUSED_RESULT static constexpr Lifetime anonymous_lifetime ()
141 {
142 return Lifetime (1);
143 }
144
145 static constexpr uint32_t FIRST_NAMED_LIFETIME = 2;
146
147 friend bool operator== (const Lifetime &lhs, const Lifetime &rhs)
148 {
149 return lhs.interner_index == rhs.interner_index;
150 }
151
152 friend bool operator!= (const Lifetime &lhs, const Lifetime &rhs)
153 {
154 return !(lhs == rhs);
155 }
156
157 WARN_UNUSED_RESULT Lifetime next () { return Lifetime (interner_index++); }
158 };
159
160 class TypeCheckContext
161 {
162 public:
163 static TypeCheckContext *get ();
164
165 ~TypeCheckContext ();
166
167 bool lookup_builtin (NodeId id, TyTy::BaseType **type);
168 bool lookup_builtin (std::string name, TyTy::BaseType **type);
169 void insert_builtin (HirId id, NodeId ref, TyTy::BaseType *type);
170 const std::vector<std::unique_ptr<TyTy::BaseType>> &get_builtins () const;
171
172 void insert_type (const Analysis::NodeMapping &mappings,
173 TyTy::BaseType *type);
174 bool lookup_type (HirId id, TyTy::BaseType **type) const;
175 void clear_type (TyTy::BaseType *ty);
176
177 void insert_implicit_type (HirId id, TyTy::BaseType *type);
178
179 void insert_type_by_node_id (NodeId ref, HirId id);
180 bool lookup_type_by_node_id (NodeId ref, HirId *id);
181
182 bool have_function_context () const;
183 TyTy::BaseType *peek_return_type ();
184 TypeCheckContextItem peek_context ();
185 void push_return_type (TypeCheckContextItem item,
186 TyTy::BaseType *return_type);
187 void pop_return_type ();
188
189 StackedContexts<TypeCheckBlockContextItem> &block_context ();
190
191 void iterate (std::function<bool (HirId, TyTy::BaseType *)> cb);
192
193 bool have_loop_context () const;
194 void push_new_loop_context (HirId id, location_t locus);
195 void push_new_while_loop_context (HirId id);
196 TyTy::BaseType *peek_loop_context ();
197 TyTy::BaseType *pop_loop_context ();
198
199 void swap_head_loop_context (TyTy::BaseType *val);
200
201 void insert_trait_reference (DefId id, TraitReference &&ref);
202 bool lookup_trait_reference (DefId id, TraitReference **ref);
203
204 void insert_associated_trait_impl (HirId id,
205 AssociatedImplTrait &&associated);
206 bool lookup_associated_trait_impl (HirId id,
207 AssociatedImplTrait **associated);
208
209 void insert_associated_type_mapping (HirId id, HirId mapping);
210 void clear_associated_type_mapping (HirId id);
211
212 // lookup any associated type mappings, the out parameter of mapping is
213 // allowed to be nullptr which allows this interface to do a simple does exist
214 // check
215 bool lookup_associated_type_mapping (HirId id, HirId *mapping);
216
217 void insert_associated_impl_mapping (HirId trait_id,
218 const TyTy::BaseType *impl_type,
219 HirId impl_id);
220 bool lookup_associated_impl_mapping_for_self (HirId trait_id,
221 const TyTy::BaseType *self,
222 HirId *mapping);
223
224 void insert_autoderef_mappings (HirId id,
225 std::vector<Adjustment> &&adjustments);
226 bool lookup_autoderef_mappings (HirId id,
227 std::vector<Adjustment> **adjustments);
228
229 void insert_cast_autoderef_mappings (HirId id,
230 std::vector<Adjustment> &&adjustments);
231 bool lookup_cast_autoderef_mappings (HirId id,
232 std::vector<Adjustment> **adjustments);
233
234 void insert_variant_definition (HirId id, HirId variant);
235 bool lookup_variant_definition (HirId id, HirId *variant);
236
237 void insert_operator_overload (HirId id, TyTy::FnType *call_site);
238 bool lookup_operator_overload (HirId id, TyTy::FnType **call);
239
240 void insert_unconstrained_check_marker (HirId id, bool status);
241 bool have_checked_for_unconstrained (HirId id, bool *result);
242
243 void insert_resolved_predicate (HirId id, TyTy::TypeBoundPredicate predicate);
244 bool lookup_predicate (HirId id, TyTy::TypeBoundPredicate *result);
245
246 void insert_query (HirId id);
247 void query_completed (HirId id);
248 bool query_in_progress (HirId id) const;
249
250 void insert_trait_query (DefId id);
251 void trait_query_completed (DefId id);
252 bool trait_query_in_progress (DefId id) const;
253
254 Lifetime intern_lifetime (const HIR::Lifetime &name);
255 WARN_UNUSED_RESULT tl::optional<Lifetime>
256 lookup_lifetime (const HIR::Lifetime &lifetime) const;
257
258 WARN_UNUSED_RESULT tl::optional<TyTy::Region>
259 lookup_and_resolve_lifetime (const HIR::Lifetime &lifetime) const;
260
261 void intern_and_insert_lifetime (const HIR::Lifetime &lifetime);
262
263 WARN_UNUSED_RESULT std::vector<TyTy::Region>
264 regions_from_generic_args (const HIR::GenericArgs &args) const;
265
266 void compute_inference_variables (bool error);
267
268 TyTy::VarianceAnalysis::CrateCtx &get_variance_analysis_ctx ();
269
270 private:
271 TypeCheckContext ();
272
273 std::map<NodeId, HirId> node_id_refs;
274 std::map<HirId, TyTy::BaseType *> resolved;
275 std::vector<std::unique_ptr<TyTy::BaseType>> builtins;
276 std::vector<std::pair<TypeCheckContextItem, TyTy::BaseType *>>
277 return_type_stack;
278 std::vector<TyTy::BaseType *> loop_type_stack;
279 StackedContexts<TypeCheckBlockContextItem> block_stack;
280 std::map<DefId, TraitReference> trait_context;
281 std::map<HirId, AssociatedImplTrait> associated_impl_traits;
282
283 // trait-id -> list of < self-tyty:impl-id>
284 std::map<HirId, std::vector<std::pair<const TyTy::BaseType *, HirId>>>
285 associated_traits_to_impls;
286
287 std::map<HirId, HirId> associated_type_mappings;
288
289 // adjustment mappings
290 std::map<HirId, std::vector<Adjustment>> autoderef_mappings;
291 std::map<HirId, std::vector<Adjustment>> cast_autoderef_mappings;
292
293 // operator overloads
294 std::map<HirId, TyTy::FnType *> operator_overloads;
295
296 // variants
297 std::map<HirId, HirId> variants;
298
299 // unconstrained type-params check
300 std::map<HirId, bool> unconstrained;
301
302 // predicates
303 std::map<HirId, TyTy::TypeBoundPredicate> predicates;
304
305 // query context lookups
306 std::set<HirId> querys_in_progress;
307 std::set<DefId> trait_queries_in_progress;
308
309 // variance analysis
310 TyTy::VarianceAnalysis::CrateCtx variance_analysis_ctx;
311
312 /** Used to resolve (interned) lifetime names to their bounding scope. */
313 class LifetimeResolver
314 {
315 /**
316 * The level of nested scopes, where the lifetime was declared.
317 *
318 * Index 0 is used for `impl` blocks and is skipped if not explicitly
319 * requested.
320 * Index 1 for the top-level of declarations of items.
321 * Index >1 is used for late-bound lifetimes.
322 */
323 using ScopeIndex = size_t;
324
325 static constexpr ScopeIndex IMPL_SCOPE = 0;
326 static constexpr ScopeIndex ITEM_SCOPE = 1;
327
328 /**
329 * A reference to a lifetime binder.
330 *
331 * This is used to resolve lifetimes to their scope.
332 */
333 struct LifetimeBinderRef
334 {
335 uint32_t scope; //> Depth of the scope where the lifetime was declared.
336 uint32_t index; //> Index of the lifetime in the scope.
337 };
338
339 /**
340 * A stack of the number of lifetimes declared in each scope.
341 *
342 * Used to pop the correct number of lifetimes when leaving a scope.
343 */
344 std::stack<uint32_t> binder_size_stack;
345
346 /**
347 * Merged stack of all lifetimes declared in all scopes.
348 *
349 * Use `binder_size_stack` to determine the number of lifetimes in each
350 * scope.
351 */
352 std::vector<std::pair<Lifetime, LifetimeBinderRef>> lifetime_lookup;
353
354 /**
355 * Whether the current scope is a function body.
356 *
357 * In function header, lifetimes are resolved as early-bound, in the body as
358 * named. This is because the header can be also used in call position.
359 */
360 bool is_body = false;
361
362 /** Return the number of the current scope. */
363 WARN_UNUSED_RESULT uint32_t get_current_scope () const
364 {
365 return binder_size_stack.size () - 1;
366 }
367
368 public:
369 /** Add new declaration of a lifetime. */
370 void insert_mapping (Lifetime placeholder)
371 {
372 lifetime_lookup.push_back (
373 {placeholder, {get_current_scope (), binder_size_stack.top ()++}});
374 }
375
376 WARN_UNUSED_RESULT tl::optional<TyTy::Region>
377 resolve (const Lifetime &placeholder) const;
378
379 /** Only to be used by the guard. */
380 void push_binder () { binder_size_stack.push (0); }
381 /** Only to be used by the guard. */
382 void pop_binder () { binder_size_stack.pop (); }
383
384 bool binder_empty () { return binder_size_stack.empty (); }
385
386 /**
387 * Switch from resolving a function header to a function body.
388 */
389 void switch_to_fn_body () { this->is_body = true; }
390
391 size_t get_num_bound_regions () const { return binder_size_stack.top (); }
392 };
393
394 // lifetime resolving
395 std::unordered_map<std::string, Lifetime> lifetime_name_interner;
396 Lifetime next_lifetime_index = Lifetime (Lifetime::FIRST_NAMED_LIFETIME);
397
398 /**
399 * Stack of lifetime resolvers.
400 *
401 * Due to the contruction of the type checker, it is possible to start
402 * resolution of a new type in the middle of resolving another type. This
403 * stack isolates the conexts in such cases.
404 */
405 std::stack<LifetimeResolver> lifetime_resolver_stack;
406
407 public:
408 WARN_UNUSED_RESULT LifetimeResolver &get_lifetime_resolver ()
409 {
410 rust_assert (!lifetime_resolver_stack.empty ());
411 return lifetime_resolver_stack.top ();
412 }
413
414 WARN_UNUSED_RESULT const LifetimeResolver &get_lifetime_resolver () const
415 {
416 rust_assert (!lifetime_resolver_stack.empty ());
417 return lifetime_resolver_stack.top ();
418 }
419
420 /**
421 * A guard that pushes a new lifetime resolver on the stack and pops it
422 * when it goes out of scope.
423 */
424 class LifetimeResolverGuard
425 {
426 public:
427 /** The kind of scope that is being pushed. */
428 enum ScopeKind
429 {
430 IMPL_BLOCK_RESOLVER, //> A new `impl` block scope.
431 RESOLVER, //> A new scope for a function body.
432 BINDER, //> A new scope for late-bound lifetimes.
433 };
434
435 private:
436 TypeCheckContext &ctx;
437 ScopeKind kind;
438
439 public:
440 LifetimeResolverGuard (TypeCheckContext &ctx, ScopeKind kind)
441 : ctx (ctx), kind (kind)
442 {
443 if (kind == IMPL_BLOCK_RESOLVER)
444 {
445 ctx.lifetime_resolver_stack.push (LifetimeResolver ());
446 }
447
448 if (kind == RESOLVER)
449 {
450 ctx.lifetime_resolver_stack.push (LifetimeResolver ());
451 // Skip the `impl` block scope.
452 ctx.lifetime_resolver_stack.top ().push_binder ();
453 }
454 rust_assert (!ctx.lifetime_resolver_stack.empty ());
455 ctx.lifetime_resolver_stack.top ().push_binder ();
456 }
457
458 ~LifetimeResolverGuard ()
459 {
460 rust_assert (!ctx.lifetime_resolver_stack.empty ());
461 if (!ctx.lifetime_resolver_stack.top ().binder_empty ())
462 ctx.lifetime_resolver_stack.top ().pop_binder ();
463 if (kind == RESOLVER)
464 {
465 ctx.lifetime_resolver_stack.pop ();
466 }
467 }
468 };
469
470 /** Start new late bound lifetime scope. */
471 WARN_UNUSED_RESULT LifetimeResolverGuard push_lifetime_binder ()
472 {
473 return LifetimeResolverGuard (*this, LifetimeResolverGuard::BINDER);
474 }
475
476 /** Start new function body scope. */
477 WARN_UNUSED_RESULT LifetimeResolverGuard
478 push_clean_lifetime_resolver (bool is_impl_block = false)
479 {
480 return LifetimeResolverGuard (*this,
481 is_impl_block
482 ? LifetimeResolverGuard::IMPL_BLOCK_RESOLVER
483 : LifetimeResolverGuard::RESOLVER);
484 }
485
486 /** Switch from resolving a function header to a function body. */
487 void switch_to_fn_body ()
488 {
489 this->lifetime_resolver_stack.top ().switch_to_fn_body ();
490 }
491 };
492
493 class TypeResolution
494 {
495 public:
496 static void Resolve (HIR::Crate &crate);
497 };
498
499 class TraitQueryGuard
500 {
501 public:
502 TraitQueryGuard (DefId id) : id (id), ctx (*TypeCheckContext::get ())
503 {
504 ctx.insert_trait_query (id);
505 }
506
507 ~TraitQueryGuard () { ctx.trait_query_completed (id); }
508
509 private:
510 DefId id;
511 TypeCheckContext &ctx;
512 };
513
514 } // namespace Resolver
515 } // namespace Rust
516
517 #endif // RUST_HIR_TYPE_CHECK