Debian Codegraph @

gcc/rust/typecheck/rust-tyty-variance-analysis.cc

raw
1 #include "rust-tyty-variance-analysis-private.h"
2 #include "rust-hir-type-check.h"
3
4 namespace Rust {
5 namespace TyTy {
6
7 BaseType *
8 lookup_type (HirId ref)
9 {
10 BaseType *ty = nullptr;
11 bool ok = Resolver::TypeCheckContext::get ()->lookup_type (ref, &ty);
12 rust_assert (ok);
13 return ty;
14 }
15
16 namespace VarianceAnalysis {
17
18 CrateCtx::CrateCtx () : private_ctx (new GenericTyPerCrateCtx ()) {}
19
20 // Must be here because of incomplete type.
21 CrateCtx::~CrateCtx () = default;
22
23 void
24 CrateCtx::add_type_constraints (ADTType &type)
25 {
26 private_ctx->process_type (type);
27 }
28
29 void
30 CrateCtx::solve ()
31 {
32 private_ctx->solve ();
33 private_ctx->debug_print_solutions ();
34 }
35
36 std::vector<Variance>
37 CrateCtx::query_generic_variance (const ADTType &type)
38 {
39 return private_ctx->query_generic_variance (type);
40 }
41
42 std::vector<Variance>
43 CrateCtx::query_type_variances (BaseType *type)
44 {
45 TyVisitorCtx ctx (*private_ctx);
46 return ctx.collect_variances (*type);
47 }
48
49 std::vector<Region>
50 CrateCtx::query_type_regions (BaseType *type)
51 {
52 return private_ctx->query_type_regions (type);
53 }
54
55 FreeRegions
56 CrateCtx::query_field_regions (const ADTType *parent, size_t variant_index,
57 size_t field_index,
58 const FreeRegions &parent_regions)
59 {
60 return private_ctx->query_field_regions (parent, variant_index, field_index,
61 parent_regions);
62 }
63
64 Variance
65 Variance::reverse () const
66 {
67 switch (kind)
68 {
69 case BIVARIANT:
70 return bivariant ();
71 case COVARIANT:
72 return contravariant ();
73 case CONTRAVARIANT:
74 return covariant ();
75 case INVARIANT:
76 return invariant ();
77 }
78
79 rust_unreachable ();
80 }
81
82 Variance
83 Variance::join (Variance lhs, Variance rhs)
84 {
85 return {Kind (lhs.kind | rhs.kind)};
86 }
87
88 void
89 Variance::join (Variance rhs)
90 {
91 *this = join (*this, rhs);
92 }
93
94 Variance
95 Variance::transform (Variance lhs, Variance rhs)
96 {
97 switch (lhs.kind)
98 {
99 case BIVARIANT:
100 return bivariant ();
101 case COVARIANT:
102 return rhs;
103 case CONTRAVARIANT:
104 return rhs.reverse ();
105 case INVARIANT:
106 return invariant ();
107 }
108 rust_unreachable ();
109 }
110
111 std::string
112 Variance::as_string () const
113 {
114 switch (kind)
115 {
116 case BIVARIANT:
117 return "o";
118 case COVARIANT:
119 return "+";
120 case CONTRAVARIANT:
121 return "-";
122 case INVARIANT:
123 return "*";
124 }
125 rust_unreachable ();
126 }
127
128 void
129 GenericTyPerCrateCtx::process_type (ADTType &type)
130 {
131 GenericTyVisitorCtx (*this).process_type (type);
132 }
133
134 void
135 GenericTyPerCrateCtx::solve ()
136 {
137 rust_debug ("Variance analysis solving started:");
138
139 // Fix point iteration
140 bool changed = true;
141 while (changed)
142 {
143 changed = false;
144 for (auto constraint : constraints)
145 {
146 rust_debug ("\tapplying constraint: %s <= %s",
147 to_string (constraint.target_index).c_str (),
148 to_string (*constraint.term).c_str ());
149
150 auto old_solution = solutions[constraint.target_index];
151 auto new_solution
152 = Variance::join (old_solution, evaluate (constraint.term));
153
154 if (old_solution != new_solution)
155 {
156 rust_debug ("\t\tsolution changed: %s => %s",
157 old_solution.as_string ().c_str (),
158 new_solution.as_string ().c_str ());
159
160 changed = true;
161 solutions[constraint.target_index] = new_solution;
162 }
163 }
164 }
165
166 constraints.clear ();
167 constraints.shrink_to_fit ();
168 }
169
170 void
171 GenericTyPerCrateCtx::debug_print_solutions ()
172 {
173 rust_debug ("Variance analysis results:");
174
175 for (auto type : map_from_ty_orig_ref)
176 {
177 auto solution_index = type.second;
178 auto ref = type.first;
179
180 BaseType *ty = lookup_type (ref);
181
182 std::string result = "\t";
183
184 if (auto adt = ty->try_as<ADTType> ())
185 {
186 result += adt->get_identifier ();
187 result += "<";
188
189 size_t i = solution_index;
190 for (auto &region : adt->get_used_arguments ().get_regions ())
191 {
192 (void) region;
193 if (i > solution_index)
194 result += ", ";
195 result += solutions[i].as_string ();
196 i++;
197 }
198 for (auto &param : adt->get_substs ())
199 {
200 if (i > solution_index)
201 result += ", ";
202 result += param.get_generic_param ()
203 .get_type_representation ()
204 .as_string ();
205 result += "=";
206 result += solutions[i].as_string ();
207 i++;
208 }
209
210 result += ">";
211 }
212 else
213 {
214 rust_sorry_at (
215 ty->get_ref (),
216 "This is a compiler bug: Unhandled type in variance analysis");
217 }
218 rust_debug ("%s", result.c_str ());
219 }
220 }
221
222 tl::optional<SolutionIndex>
223 GenericTyPerCrateCtx::lookup_type_index (HirId orig_ref)
224 {
225 auto it = map_from_ty_orig_ref.find (orig_ref);
226 if (it != map_from_ty_orig_ref.end ())
227 {
228 return it->second;
229 }
230 return tl::nullopt;
231 }
232
233 void
234 GenericTyVisitorCtx::process_type (ADTType &ty)
235 {
236 rust_debug ("add_type_constraints: %s", ty.as_string ().c_str ());
237
238 first_lifetime = lookup_or_add_type (ty.get_orig_ref ());
239 first_type = first_lifetime + ty.get_used_arguments ().get_regions ().size ();
240
241 for (auto &param : ty.get_substs ())
242 param_names.push_back (
243 param.get_generic_param ().get_type_representation ().as_string ());
244
245 for (const auto &variant : ty.get_variants ())
246 {
247 if (variant->get_variant_type () != VariantDef::NUM)
248 {
249 for (const auto &field : variant->get_fields ())
250 add_constraints_from_ty (field->get_field_type (),
251 Variance::covariant ());
252 }
253 }
254 }
255
256 std::string
257 GenericTyPerCrateCtx::to_string (const Term &term) const
258 {
259 switch (term.kind)
260 {
261 case Term::CONST:
262 return term.const_val.as_string ();
263 case Term::REF:
264 return "v(" + to_string (term.ref) + ")";
265 case Term::TRANSFORM:
266 return "(" + to_string (*term.transform.lhs) + " x "
267 + to_string (*term.transform.rhs) + ")";
268 }
269 rust_unreachable ();
270 }
271
272 std::string
273 GenericTyPerCrateCtx::to_string (SolutionIndex index) const
274 {
275 // Search all values in def_id_to_solution_index_start and find key for
276 // largest value smaller than index
277 std::pair<HirId, SolutionIndex> best = {0, 0};
278
279 for (const auto &ty_map : map_from_ty_orig_ref)
280 {
281 if (ty_map.second <= index && ty_map.first > best.first)
282 best = ty_map;
283 }
284 rust_assert (best.first != 0);
285
286 BaseType *ty = lookup_type (best.first);
287
288 std::string result = "";
289 if (auto adt = ty->try_as<ADTType> ())
290 {
291 result += (adt->get_identifier ());
292 }
293 else
294 {
295 result += ty->as_string ();
296 }
297
298 result += "[" + std::to_string (index - best.first) + "]";
299 return result;
300 }
301
302 Variance
303 GenericTyPerCrateCtx::evaluate (Term *term)
304 {
305 switch (term->kind)
306 {
307 case Term::CONST:
308 return term->const_val;
309 case Term::REF:
310 return solutions[term->ref];
311 case Term::TRANSFORM:
312 return Variance::transform (evaluate (term->transform.lhs),
313 evaluate (term->transform.rhs));
314 }
315 rust_unreachable ();
316 }
317
318 std::vector<Variance>
319 GenericTyPerCrateCtx::query_generic_variance (const ADTType &type)
320 {
321 auto solution_index = lookup_type_index (type.get_orig_ref ());
322 rust_assert (solution_index.has_value ());
323 auto num_lifetimes = type.get_num_lifetime_params ();
324 auto num_types = type.get_num_type_params ();
325
326 std::vector<Variance> result;
327 for (size_t i = 0; i < num_lifetimes + num_types; ++i)
328 {
329 result.push_back (solutions[solution_index.value () + i]);
330 }
331
332 return result;
333 }
334
335 FreeRegions
336 GenericTyPerCrateCtx::query_field_regions (const ADTType *parent,
337 size_t variant_index,
338 size_t field_index,
339 const FreeRegions &parent_regions)
340 {
341 auto orig = lookup_type (parent->get_orig_ref ());
342 FieldVisitorCtx ctx (*this, *parent->as<const SubstitutionRef> (),
343 parent_regions);
344 return ctx.collect_regions (*orig->as<const ADTType> ()
345 ->get_variants ()
346 .at (variant_index)
347 ->get_fields ()
348 .at (field_index)
349 ->get_field_type ());
350 }
351 std::vector<Region>
352 GenericTyPerCrateCtx::query_type_regions (BaseType *type)
353 {
354 TyVisitorCtx ctx (*this);
355 return ctx.collect_regions (*type);
356 }
357
358 SolutionIndex
359 GenericTyVisitorCtx::lookup_or_add_type (HirId hir_id)
360 {
361 BaseType *ty = lookup_type (hir_id);
362 auto index = ctx.lookup_type_index (hir_id);
363 if (index.has_value ())
364 {
365 return index.value ();
366 }
367
368 SubstitutionRef *subst = nullptr;
369 if (auto adt = ty->try_as<ADTType> ())
370 {
371 subst = adt;
372 }
373 else
374 {
375 rust_sorry_at (
376 ty->get_locus (),
377 "This is a compiler bug: Unhandled type in variance analysis");
378 }
379 rust_assert (subst != nullptr);
380
381 auto solution_index = ctx.solutions.size ();
382 ctx.map_from_ty_orig_ref.emplace (ty->get_orig_ref (), solution_index);
383
384 auto num_lifetime_param = subst->get_used_arguments ().get_regions ().size ();
385 auto num_type_param = subst->get_num_substitutions ();
386
387 for (size_t i = 0; i < num_lifetime_param + num_type_param; ++i)
388 ctx.solutions.emplace_back (Variance::bivariant ());
389
390 return solution_index;
391 }
392
393 void
394 GenericTyVisitorCtx::add_constraints_from_ty (BaseType *type, Term variance)
395 {
396 rust_debug ("\tadd_constraint_from_ty: %s with v=%s",
397 type->as_string ().c_str (), ctx.to_string (variance).c_str ());
398
399 Visitor visitor (*this, variance);
400 type->accept_vis (visitor);
401 }
402
403 void
404 GenericTyVisitorCtx::add_constraint (SolutionIndex index, Term term)
405 {
406 rust_debug ("\t\tadd_constraint: %s", ctx.to_string (term).c_str ());
407
408 if (term.kind == Term::CONST)
409 {
410 // Constant terms do not depend on other solutions, so we can
411 // immediately apply them.
412 ctx.solutions[index].join (term.const_val);
413 }
414 else
415 {
416 ctx.constraints.push_back ({index, new Term (term)});
417 }
418 }
419
420 void
421 GenericTyVisitorCtx::add_constraints_from_region (const Region &region,
422 Term term)
423 {
424 if (region.is_early_bound ())
425 {
426 add_constraint (first_lifetime + region.get_index (), term);
427 }
428 }
429
430 void
431 GenericTyVisitorCtx::add_constraints_from_generic_args (HirId ref,
432 SubstitutionRef &subst,
433 Term variance,
434 bool invariant_args)
435 {
436 SolutionIndex solution_index = lookup_or_add_type (ref);
437
438 size_t num_lifetimes = subst.get_used_arguments ().get_regions ().size ();
439 size_t num_types = subst.get_substs ().size ();
440
441 for (size_t i = 0; i < num_lifetimes + num_types; ++i)
442 {
443 // TODO: What about variance from other crates?
444 auto variance_i
445 = invariant_args
446 ? Term::make_transform (variance, Variance::invariant ())
447 : Term::make_transform (variance,
448 Term::make_ref (solution_index + i));
449
450 if (i < num_lifetimes)
451 {
452 auto region_i = i;
453 auto &region
454 = subst.get_substitution_arguments ().get_mut_regions ()[region_i];
455 add_constraints_from_region (region, variance_i);
456 }
457 else
458 {
459 auto type_i = i - num_lifetimes;
460 auto arg = subst.get_arg_at (type_i);
461 if (arg.has_value ())
462 {
463 add_constraints_from_ty (arg.value ().get_tyty (), variance_i);
464 }
465 }
466 }
467 }
468 void
469 GenericTyVisitorCtx::add_constrints_from_param (ParamType &type, Term variance)
470 {
471 auto it
472 = std::find (param_names.begin (), param_names.end (), type.get_name ());
473 rust_assert (it != param_names.end ());
474
475 auto index = first_type + std::distance (param_names.begin (), it);
476
477 add_constraint (index, variance);
478 }
479
480 Term
481 GenericTyVisitorCtx::contra (Term variance)
482 {
483 return Term::make_transform (variance, Variance::contravariant ());
484 }
485
486 void
487 TyVisitorCtx::add_constraints_from_ty (BaseType *ty, Variance variance)
488 {
489 Visitor visitor (*this, variance);
490 ty->accept_vis (visitor);
491 }
492
493 void
494 TyVisitorCtx::add_constraints_from_region (const Region &region,
495 Variance variance)
496 {
497 variances.push_back (variance);
498 regions.push_back (region);
499 }
500
501 void
502 TyVisitorCtx::add_constraints_from_generic_args (HirId ref,
503 SubstitutionRef &subst,
504 Variance variance,
505 bool invariant_args)
506 {
507 // Handle function
508 auto variances
509 = ctx.query_generic_variance (*lookup_type (ref)->as<ADTType> ());
510
511 size_t num_lifetimes = subst.get_used_arguments ().get_regions ().size ();
512 size_t num_types = subst.get_substs ().size ();
513
514 for (size_t i = 0; i < num_lifetimes + num_types; ++i)
515 {
516 // TODO: What about variance from other crates?
517 auto variance_i
518 = invariant_args
519 ? Variance::transform (variance, Variance::invariant ())
520 : Variance::transform (variance, variances[i]);
521
522 if (i < num_lifetimes)
523 {
524 auto region_i = i;
525 auto &region = subst.get_used_arguments ().get_regions ()[region_i];
526 add_constraints_from_region (region, variance_i);
527 }
528 else
529 {
530 auto type_i = i - num_lifetimes;
531 auto arg = subst.get_arg_at (type_i);
532 if (arg.has_value ())
533 {
534 add_constraints_from_ty (arg.value ().get_tyty (), variance_i);
535 }
536 }
537 }
538 }
539
540 FreeRegions
541 FieldVisitorCtx::collect_regions (BaseType &ty)
542 {
543 // Segment the regions into ranges for each type parameter. Type parameter
544 // at index i contains regions from type_param_ranges[i] to
545 // type_param_ranges[i+1] (exclusive).;
546 type_param_ranges.push_back (subst.get_num_lifetime_params ());
547
548 for (size_t i = 0; i < subst.get_num_type_params (); i++)
549 {
550 auto arg = subst.get_arg_at (i);
551 rust_assert (arg.has_value ());
552 type_param_ranges.push_back (
553 ctx.query_type_regions (arg.value ().get_tyty ()).size ());
554 }
555
556 add_constraints_from_ty (&ty, Variance::covariant ());
557 return regions;
558 }
559
560 void
561 FieldVisitorCtx::add_constraints_from_ty (BaseType *ty, Variance variance)
562 {
563 Visitor visitor (*this, variance);
564 ty->accept_vis (visitor);
565 }
566
567 void
568 FieldVisitorCtx::add_constraints_from_region (const Region &region,
569 Variance variance)
570 {
571 if (region.is_early_bound ())
572 {
573 regions.push_back (parent_regions[region.get_index ()]);
574 }
575 else if (region.is_late_bound ())
576 {
577 rust_debug ("Ignoring late bound region");
578 }
579 }
580
581 void
582 FieldVisitorCtx::add_constrints_from_param (ParamType &param, Variance variance)
583 {
584 size_t param_i = subst.get_used_arguments ().find_symbol (param).value ();
585 for (size_t i = type_param_ranges[param_i];
586 i < type_param_ranges[param_i + 1]; i++)
587 {
588 regions.push_back (parent_regions[i]);
589 }
590 }
591
592 Variance
593 TyVisitorCtx::contra (Variance variance)
594 {
595 return Variance::transform (variance, Variance::contravariant ());
596 }
597
598 Term
599 Term::make_ref (SolutionIndex index)
600 {
601 Term term;
602 term.kind = REF;
603 term.ref = index;
604 return term;
605 }
606
607 Term
608 Term::make_transform (Term lhs, Term rhs)
609 {
610 if (lhs.is_const () && rhs.is_const ())
611 {
612 return Variance::transform (lhs.const_val, rhs.const_val);
613 }
614
615 Term term;
616 term.kind = TRANSFORM;
617 term.transform.lhs = new Term (lhs);
618 term.transform.rhs = new Term (rhs);
619 return term;
620 }
621
622 } // namespace VarianceAnalysis
623 } // namespace TyTy
624 } // namespace Rust