Debian Codegraph @

gcc/rust/typecheck/rust-hir-type-check-type.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 "rust-hir-type-check-type.h"
20 #include "options.h"
21 #include "optional.h"
22 #include "rust-hir-map.h"
23 #include "rust-hir-trait-resolve.h"
24 #include "rust-hir-type-check-expr.h"
25 #include "rust-hir-path-probe.h"
26 #include "rust-hir-type-bounds.h"
27 #include "rust-immutable-name-resolution-context.h"
28 #include "rust-mapping-common.h"
29 #include "rust-substitution-mapper.h"
30 #include "rust-type-util.h"
31 #include "rust-system.h"
32
33 namespace Rust {
34 namespace Resolver {
35
36 HIR::GenericArgs
37 TypeCheckResolveGenericArguments::resolve (HIR::TypePathSegment &segment)
38 {
39 TypeCheckResolveGenericArguments resolver (segment.get_locus ());
40 switch (segment.get_type ())
41 {
42 case HIR::TypePathSegment::SegmentType::GENERIC:
43 resolver.visit (static_cast<HIR::TypePathSegmentGeneric &> (segment));
44 break;
45
46 default:
47 break;
48 }
49 return resolver.args;
50 }
51
52 void
53 TypeCheckResolveGenericArguments::visit (HIR::TypePathSegmentGeneric &generic)
54 {
55 args = generic.get_generic_args ();
56 }
57
58 TyTy::BaseType *
59 TypeCheckType::Resolve (HIR::Type &type)
60 {
61 // is it already resolved?
62 auto context = TypeCheckContext::get ();
63 TyTy::BaseType *resolved = nullptr;
64 bool already_resolved
65 = context->lookup_type (type.get_mappings ().get_hirid (), &resolved);
66 if (already_resolved)
67 return resolved;
68
69 TypeCheckType resolver (type.get_mappings ().get_hirid ());
70 type.accept_vis (resolver);
71 rust_assert (resolver.translated != nullptr);
72 resolver.context->insert_type (type.get_mappings (), resolver.translated);
73 return resolver.translated;
74 }
75
76 void
77 TypeCheckType::visit (HIR::BareFunctionType &fntype)
78 {
79 auto binder_pin = context->push_lifetime_binder ();
80 for (auto &lifetime_param : fntype.get_for_lifetimes ())
81 {
82 context->intern_and_insert_lifetime (lifetime_param.get_lifetime ());
83 }
84
85 TyTy::BaseType *return_type;
86 if (fntype.has_return_type ())
87 {
88 return_type = TypeCheckType::Resolve (fntype.get_return_type ());
89 }
90 else
91 {
92 // needs a new implicit ID
93 HirId ref = mappings.get_next_hir_id ();
94 return_type = TyTy::TupleType::get_unit_type ();
95 context->insert_implicit_type (ref, return_type);
96 }
97
98 std::vector<TyTy::TyVar> params;
99 for (auto &param : fntype.get_function_params ())
100 {
101 TyTy::BaseType *ptype = TypeCheckType::Resolve (param.get_type ());
102 params.push_back (TyTy::TyVar (ptype->get_ref ()));
103 }
104
105 translated = new TyTy::FnPtr (fntype.get_mappings ().get_hirid (),
106 fntype.get_locus (), std::move (params),
107 TyTy::TyVar (return_type->get_ref ()));
108 }
109
110 void
111 TypeCheckType::visit (HIR::TupleType &tuple)
112 {
113 if (tuple.is_unit_type ())
114 {
115 translated = TyTy::TupleType::get_unit_type ();
116 return;
117 }
118
119 std::vector<TyTy::TyVar> fields;
120 for (auto &elem : tuple.get_elems ())
121 {
122 auto field_ty = TypeCheckType::Resolve (*elem);
123 fields.push_back (TyTy::TyVar (field_ty->get_ref ()));
124 }
125
126 translated = new TyTy::TupleType (tuple.get_mappings ().get_hirid (),
127 tuple.get_locus (), fields);
128 }
129
130 void
131 TypeCheckType::visit (HIR::TypePath &path)
132 {
133 rust_debug ("{ARTHUR}: Path visited: %s", path.as_string ().c_str ());
134
135 // this can happen so we need to look up the root then resolve the
136 // remaining segments if possible
137 bool wasBigSelf = false;
138 size_t offset = 0;
139 TyTy::BaseType *root = resolve_root_path (path, &offset, &wasBigSelf);
140 if (root->get_kind () == TyTy::TypeKind::ERROR)
141 {
142 rust_debug_loc (path.get_locus (), "failed to resolve type-path type");
143 return;
144 }
145
146 TyTy::BaseType *path_type = root->clone ();
147 path_type->set_ref (path.get_mappings ().get_hirid ());
148 context->insert_implicit_type (path.get_mappings ().get_hirid (), path_type);
149
150 bool fully_resolved = offset >= path.get_segments ().size ();
151 if (fully_resolved)
152 {
153 translated = path_type;
154 rust_debug_loc (path.get_locus (), "root resolved type-path to: [%s]",
155 translated->debug_str ().c_str ());
156 return;
157 }
158
159 translated
160 = resolve_segments (path.get_mappings ().get_hirid (), path.get_segments (),
161 offset, path_type, path.get_mappings (),
162 path.get_locus (), wasBigSelf);
163
164 rust_debug_loc (path.get_locus (), "resolved type-path to: [%s]",
165 translated->debug_str ().c_str ());
166 }
167
168 void
169 TypeCheckType::visit (HIR::QualifiedPathInType &path)
170 {
171 HIR::QualifiedPathType qual_path_type = path.get_path_type ();
172 TyTy::BaseType *root = TypeCheckType::Resolve (qual_path_type.get_type ());
173 if (root->get_kind () == TyTy::TypeKind::ERROR)
174 {
175 rust_debug_loc (path.get_locus (), "failed to resolve the root");
176 return;
177 }
178
179 if (!qual_path_type.has_as_clause ())
180 {
181 translated
182 = resolve_segments (path.get_mappings ().get_hirid (),
183 path.get_segments (), 0, translated,
184 path.get_mappings (), path.get_locus (), false);
185
186 return;
187 }
188
189 // Resolve the trait now
190 auto &trait_path_ref = qual_path_type.get_trait ();
191 TraitReference *trait_ref = TraitResolver::Resolve (trait_path_ref);
192 if (trait_ref->is_error ())
193 return;
194
195 // get the predicate for the bound
196 auto specified_bound
197 = get_predicate_from_bound (qual_path_type.get_trait (),
198 qual_path_type.get_type (),
199 BoundPolarity::RegularBound, true);
200 if (specified_bound.is_error ())
201 return;
202
203 // inherit the bound
204 root->inherit_bounds ({specified_bound});
205
206 // lookup the associated item from the specified bound
207 HIR::TypePathSegment &item_seg = path.get_associated_segment ();
208 HIR::PathIdentSegment item_seg_identifier = item_seg.get_ident_segment ();
209 TyTy::TypeBoundPredicateItem item
210 = specified_bound.lookup_associated_item (item_seg_identifier.as_string ());
211 if (item.is_error ())
212 {
213 std::string item_seg_ident_name, rich_msg;
214 item_seg_ident_name = qual_path_type.get_trait ().as_string ();
215 rich_msg = "not found in `" + item_seg_ident_name + "`";
216
217 rich_location richloc (line_table, item_seg.get_locus ());
218 richloc.add_fixit_replace (rich_msg.c_str ());
219
220 rust_error_at (richloc, ErrorCode::E0576,
221 "cannot find associated type %qs in trait %qs",
222 item_seg_identifier.as_string ().c_str (),
223 item_seg_ident_name.c_str ());
224 return;
225 }
226
227 // we try to look for the real impl item if possible
228 TyTy::SubstitutionArgumentMappings args
229 = TyTy::SubstitutionArgumentMappings::error ();
230 HIR::ImplItem *impl_item = nullptr;
231 if (root->is_concrete ())
232 {
233 // lookup the associated impl trait for this if we can (it might be
234 // generic)
235 AssociatedImplTrait *associated_impl_trait
236 = lookup_associated_impl_block (specified_bound, root);
237 if (associated_impl_trait != nullptr)
238 {
239 associated_impl_trait->setup_associated_types (root, specified_bound,
240 &args);
241
242 for (auto &i :
243 associated_impl_trait->get_impl_block ()->get_impl_items ())
244 {
245 bool found = i->get_impl_item_name ().compare (
246 item_seg_identifier.as_string ())
247 == 0;
248 if (found)
249 {
250 impl_item = i.get ();
251 break;
252 }
253 }
254 }
255 }
256
257 if (impl_item == nullptr)
258 {
259 // this may be valid as there could be a default trait implementation here
260 // and we dont need to worry if the trait item is actually implemented or
261 // not because this will have already been validated as part of the trait
262 // impl block
263 translated = item.get_tyty_for_receiver (root);
264 }
265 else
266 {
267 HirId impl_item_id = impl_item->get_impl_mappings ().get_hirid ();
268 bool ok = query_type (impl_item_id, &translated);
269 if (!ok)
270 return;
271
272 if (!args.is_error ())
273 {
274 // apply the args
275 translated = SubstMapperInternal::Resolve (translated, args);
276 }
277 }
278
279 // turbo-fish segment path::<ty>
280 if (item_seg.get_type () == HIR::TypePathSegment::SegmentType::GENERIC)
281 {
282 auto &generic_seg = static_cast<HIR::TypePathSegmentGeneric &> (item_seg);
283
284 // turbo-fish segment path::<ty>
285 if (generic_seg.has_generic_args ())
286 {
287 if (!translated->has_substitutions_defined ())
288 {
289 rust_error_at (item_seg.get_locus (),
290 "substitutions not supported for %s",
291 translated->as_string ().c_str ());
292 translated
293 = new TyTy::ErrorType (path.get_mappings ().get_hirid ());
294 return;
295 }
296 translated
297 = SubstMapper::Resolve (translated, path.get_locus (),
298 &generic_seg.get_generic_args (),
299 context->regions_from_generic_args (
300 generic_seg.get_generic_args ()));
301 }
302 }
303
304 // continue on as a path-in-expression
305 bool fully_resolved = path.get_segments ().empty ();
306 if (fully_resolved)
307 return;
308
309 translated
310 = resolve_segments (path.get_mappings ().get_hirid (), path.get_segments (),
311 0, translated, path.get_mappings (), path.get_locus (),
312 false);
313 }
314
315 TyTy::BaseType *
316 TypeCheckType::resolve_root_path (HIR::TypePath &path, size_t *offset,
317 bool *wasBigSelf)
318 {
319 TyTy::BaseType *root_tyty = nullptr;
320 *offset = 0;
321
322 for (size_t i = 0; i < path.get_num_segments (); i++)
323 {
324 std::unique_ptr<HIR::TypePathSegment> &seg = path.get_segments ().at (i);
325
326 bool have_more_segments = (path.get_num_segments () - 1 != i);
327 bool is_root = *offset == 0;
328 NodeId ast_node_id = seg->get_mappings ().get_nodeid ();
329
330 // then lookup the reference_node_id
331 NodeId ref_node_id = UNKNOWN_NODEID;
332
333 if (seg->is_lang_item ())
334 ref_node_id = Analysis::Mappings::get ().get_lang_item_node (
335 seg->get_lang_item ());
336 else
337 {
338 // FIXME: HACK: ARTHUR: Remove this
339 if (flag_name_resolution_2_0)
340 {
341 auto &nr_ctx = Resolver2_0::ImmutableNameResolutionContext::get ()
342 .resolver ();
343
344 // assign the ref_node_id if we've found something
345 nr_ctx.lookup (ast_node_id)
346 .map (
347 [&ref_node_id] (NodeId resolved) { ref_node_id = resolved; });
348 }
349 else if (!resolver->lookup_resolved_name (ast_node_id, &ref_node_id))
350 resolver->lookup_resolved_type (ast_node_id, &ref_node_id);
351 }
352
353 // ref_node_id is the NodeId that the segments refers to.
354 if (ref_node_id == UNKNOWN_NODEID)
355 {
356 if (is_root)
357 {
358 rust_error_at (seg->get_locus (),
359 "unknown reference for resolved name: %qs",
360 seg->as_string ().c_str ());
361 return new TyTy::ErrorType (path.get_mappings ().get_hirid ());
362 }
363 else if (root_tyty == nullptr)
364 {
365 rust_error_at (seg->get_locus (),
366 "unknown reference for resolved name: %qs",
367 seg->as_string ().c_str ());
368 return new TyTy::ErrorType (path.get_mappings ().get_hirid ());
369 }
370 return root_tyty;
371 }
372
373 if (seg->is_ident_only () && seg->as_string () == "Self")
374 *wasBigSelf = true;
375
376 // node back to HIR
377 tl::optional<HirId> hid = mappings.lookup_node_to_hir (ref_node_id);
378 if (!hid.has_value ())
379 {
380 if (is_root)
381 {
382 rust_error_at (seg->get_locus (), "789 reverse lookup failure");
383 rust_debug_loc (
384 seg->get_locus (),
385 "failure with [%s] mappings [%s] ref_node_id [%u]",
386 seg->as_string ().c_str (),
387 seg->get_mappings ().as_string ().c_str (), ref_node_id);
388
389 return new TyTy::ErrorType (path.get_mappings ().get_hirid ());
390 }
391
392 return root_tyty;
393 }
394 auto ref = hid.value ();
395
396 auto seg_is_module = mappings.lookup_module (ref).has_value ();
397 auto seg_is_crate = mappings.is_local_hirid_crate (ref);
398 if (seg_is_module || seg_is_crate)
399 {
400 // A::B::C::this_is_a_module::D::E::F
401 // ^^^^^^^^^^^^^^^^
402 // Currently handling this.
403 if (have_more_segments)
404 {
405 (*offset)++;
406 continue;
407 }
408
409 // In the case of :
410 // A::B::C::this_is_a_module
411 // ^^^^^^^^^^^^^^^^
412 // This is an error, we are not expecting a module.
413 rust_error_at (seg->get_locus (), "expected value");
414 return new TyTy::ErrorType (path.get_mappings ().get_hirid ());
415 }
416
417 TyTy::BaseType *lookup = nullptr;
418 if (!query_type (ref, &lookup))
419 {
420 if (is_root || root_tyty == nullptr)
421 {
422 rust_error_at (seg->get_locus (),
423 "failed to resolve type path segment: %qs",
424 seg->as_string ().c_str ());
425 return new TyTy::ErrorType (path.get_mappings ().get_hirid ());
426 }
427
428 return root_tyty;
429 }
430
431 // if we have a previous segment type
432 if (root_tyty != nullptr)
433 {
434 // if this next segment needs substitution we must apply the
435 // previous type arguments
436 //
437 // such as: GenericStruct::<_>::new(123, 456)
438 if (lookup->needs_generic_substitutions ())
439 {
440 if (!root_tyty->needs_generic_substitutions ())
441 {
442 auto used_args_in_prev_segment
443 = GetUsedSubstArgs::From (root_tyty);
444 lookup
445 = SubstMapperInternal::Resolve (lookup,
446 used_args_in_prev_segment);
447 }
448 }
449 }
450
451 // turbo-fish segment path::<ty>
452 if (seg->is_generic_segment ())
453 {
454 auto &generic_segment
455 = static_cast<HIR::TypePathSegmentGeneric &> (*seg);
456
457 auto regions = context->regions_from_generic_args (
458 generic_segment.get_generic_args ());
459 lookup = SubstMapper::Resolve (lookup, path.get_locus (),
460 &generic_segment.get_generic_args (),
461 regions);
462 if (lookup->get_kind () == TyTy::TypeKind::ERROR)
463 return new TyTy::ErrorType (seg->get_mappings ().get_hirid ());
464 }
465 else if (lookup->needs_generic_substitutions ())
466 {
467 HIR::GenericArgs empty
468 = HIR::GenericArgs::create_empty (path.get_locus ());
469 lookup
470 = SubstMapper::Resolve (lookup, path.get_locus (), &empty,
471 context->regions_from_generic_args (empty));
472 }
473
474 *offset = *offset + 1;
475 root_tyty = lookup;
476
477 // this enforces the proper get_segments checks to take place
478 auto *maybe_adt = root_tyty->try_as<const TyTy::ADTType> ();
479 if (maybe_adt && maybe_adt->is_enum ())
480 return root_tyty;
481 }
482
483 return root_tyty;
484 }
485
486 bool
487 TypeCheckType::resolve_associated_type (const std::string &search,
488 TypeCheckBlockContextItem &ctx,
489 TyTy::BaseType **result)
490 {
491 if (ctx.is_trait_block ())
492 {
493 HIR::Trait &trait = ctx.get_trait ();
494 for (auto &item : trait.get_trait_items ())
495 {
496 if (item->get_item_kind () != HIR::TraitItem::TraitItemKind::TYPE)
497 continue;
498
499 if (item->trait_identifier () == search)
500 {
501 HirId item_id = item->get_mappings ().get_hirid ();
502 if (query_type (item_id, result))
503 return true;
504 }
505 }
506
507 // FIXME
508 // query any parent trait?
509
510 return false;
511 }
512
513 // look for any segment in here which matches
514 HIR::ImplBlock &block = ctx.get_impl_block ();
515 for (auto &item : block.get_impl_items ())
516 {
517 if (item->get_impl_item_type () != HIR::ImplItem::TYPE_ALIAS)
518 continue;
519
520 if (item->get_impl_item_name () == search)
521 {
522 HirId item_id = item->get_impl_mappings ().get_hirid ();
523 if (query_type (item_id, result))
524 return true;
525 }
526 }
527
528 return false;
529 }
530
531 TyTy::BaseType *
532 TypeCheckType::resolve_segments (
533 HirId expr_id, std::vector<std::unique_ptr<HIR::TypePathSegment>> &segments,
534 size_t offset, TyTy::BaseType *tyseg,
535 const Analysis::NodeMapping &expr_mappings, location_t expr_locus,
536 bool tySegIsBigSelf)
537 {
538 TyTy::BaseType *prev_segment = tyseg;
539 for (size_t i = offset; i < segments.size (); i++)
540 {
541 std::unique_ptr<HIR::TypePathSegment> &seg = segments.at (i);
542
543 bool reciever_is_generic
544 = prev_segment->get_kind () == TyTy::TypeKind::PARAM;
545 bool probe_bounds = true;
546 bool probe_impls = !reciever_is_generic;
547 bool ignore_mandatory_trait_items = !reciever_is_generic;
548 bool first_segment = i == offset;
549 bool selfResolveOk = false;
550
551 if (first_segment && tySegIsBigSelf
552 && context->block_context ().is_in_context ()
553 && context->block_context ().peek ().is_impl_block ())
554 {
555 TypeCheckBlockContextItem ctx = context->block_context ().peek ();
556 TyTy::BaseType *lookup = nullptr;
557 selfResolveOk
558 = resolve_associated_type (seg->as_string (), ctx, &lookup);
559 if (selfResolveOk)
560 {
561 prev_segment = tyseg;
562 tyseg = lookup;
563 }
564 }
565 if (!selfResolveOk)
566 {
567 // probe the path is done in two parts one where we search impls if no
568 // candidate is found then we search extensions from traits
569 auto candidates
570 = PathProbeType::Probe (prev_segment, seg->get_ident_segment (),
571 probe_impls, false,
572 ignore_mandatory_trait_items);
573 if (candidates.size () == 0)
574 {
575 candidates
576 = PathProbeType::Probe (prev_segment, seg->get_ident_segment (),
577 false, probe_bounds,
578 ignore_mandatory_trait_items);
579 if (candidates.size () == 0)
580 {
581 prev_segment->debug ();
582 rust_error_at (
583 seg->get_locus (),
584 "failed to resolve path segment using an impl Probe");
585 return new TyTy::ErrorType (expr_id);
586 }
587 }
588
589 if (candidates.size () > 1)
590 {
591 ReportMultipleCandidateError::Report (candidates,
592 seg->get_ident_segment (),
593 seg->get_locus ());
594 return new TyTy::ErrorType (expr_id);
595 }
596
597 auto &candidate = *candidates.begin ();
598 prev_segment = tyseg;
599 tyseg = candidate.ty;
600
601 if (candidate.is_enum_candidate ())
602 {
603 TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (tyseg);
604 auto last_variant = adt->get_variants ();
605 TyTy::VariantDef *variant = last_variant.back ();
606
607 rich_location richloc (line_table, seg->get_locus ());
608 richloc.add_fixit_replace ("not a type");
609
610 rust_error_at (richloc, ErrorCode::E0573,
611 "expected type, found variant of %<%s::%s%>",
612 adt->get_name ().c_str (),
613 variant->get_identifier ().c_str ());
614 return new TyTy::ErrorType (expr_id);
615 }
616 }
617
618 if (seg->is_generic_segment ())
619 {
620 auto &generic_segment
621 = static_cast<HIR::TypePathSegmentGeneric &> (*seg);
622
623 std::vector<TyTy::Region> regions;
624 for (auto &lifetime :
625 generic_segment.get_generic_args ().get_lifetime_args ())
626 {
627 auto region = context->lookup_and_resolve_lifetime (lifetime);
628 if (!region.has_value ())
629 {
630 rust_error_at (lifetime.get_locus (),
631 "failed to resolve lifetime");
632 return new TyTy::ErrorType (expr_id);
633 }
634 regions.push_back (region.value ());
635 }
636
637 tyseg = SubstMapper::Resolve (tyseg, expr_locus,
638 &generic_segment.get_generic_args (),
639 regions);
640 if (tyseg->get_kind () == TyTy::TypeKind::ERROR)
641 return new TyTy::ErrorType (expr_id);
642 }
643 }
644
645 return tyseg;
646 }
647
648 void
649 TypeCheckType::visit (HIR::TraitObjectType &type)
650 {
651 std::vector<TyTy::TypeBoundPredicate> specified_bounds;
652 for (auto &bound : type.get_type_param_bounds ())
653 {
654 // TODO: here we need to check if there are additional bounds that aren't
655 // auto traits. this is an error. for example, `dyn A + Sized + Sync` is
656 // okay, because Sized and Sync are both auto traits but `dyn A + Copy +
657 // Clone` is not okay and should error out.
658
659 if (bound->get_bound_type ()
660 != HIR::TypeParamBound::BoundType::TRAITBOUND)
661 continue;
662
663 HIR::TypeParamBound &b = *bound.get ();
664 HIR::TraitBound &trait_bound = static_cast<HIR::TraitBound &> (b);
665
666 auto binder_pin = context->push_lifetime_binder ();
667 for (auto &lifetime_param : trait_bound.get_for_lifetimes ())
668 {
669 context->intern_and_insert_lifetime (lifetime_param.get_lifetime ());
670 }
671
672 TyTy::TypeBoundPredicate predicate = get_predicate_from_bound (
673 trait_bound.get_path (),
674 tl::nullopt /*this will setup a PLACEHOLDER for self*/);
675
676 if (!predicate.is_error ()
677 && predicate.is_object_safe (true, type.get_locus ()))
678 specified_bounds.push_back (std::move (predicate));
679 }
680
681 RustIdent ident{CanonicalPath::create_empty (), type.get_locus ()};
682 translated
683 = new TyTy::DynamicObjectType (type.get_mappings ().get_hirid (), ident,
684 std::move (specified_bounds));
685 }
686
687 void
688 TypeCheckType::visit (HIR::ParenthesisedType &type)
689 {
690 // I think this really needs to be a tuple.. but will sort that out when we
691 // fix the parser issue
692 translated = TypeCheckType::Resolve (type.get_type_in_parens ());
693 }
694
695 void
696 TypeCheckType::visit (HIR::ArrayType &type)
697 {
698 auto capacity_type = TypeCheckExpr::Resolve (type.get_size_expr ());
699 if (capacity_type->get_kind () == TyTy::TypeKind::ERROR)
700 return;
701
702 TyTy::BaseType *expected_ty = nullptr;
703 bool ok = context->lookup_builtin ("usize", &expected_ty);
704 rust_assert (ok);
705 context->insert_type (type.get_size_expr ().get_mappings (), expected_ty);
706
707 unify_site (type.get_size_expr ().get_mappings ().get_hirid (),
708 TyTy::TyWithLocation (expected_ty),
709 TyTy::TyWithLocation (capacity_type,
710 type.get_size_expr ().get_locus ()),
711 type.get_size_expr ().get_locus ());
712
713 TyTy::BaseType *base = TypeCheckType::Resolve (type.get_element_type ());
714 translated = new TyTy::ArrayType (type.get_mappings ().get_hirid (),
715 type.get_locus (), type.get_size_expr (),
716 TyTy::TyVar (base->get_ref ()));
717 }
718
719 void
720 TypeCheckType::visit (HIR::SliceType &type)
721 {
722 TyTy::BaseType *base = TypeCheckType::Resolve (type.get_element_type ());
723 translated
724 = new TyTy::SliceType (type.get_mappings ().get_hirid (), type.get_locus (),
725 TyTy::TyVar (base->get_ref ()));
726 }
727 void
728 TypeCheckType::visit (HIR::ReferenceType &type)
729 {
730 TyTy::BaseType *base = TypeCheckType::Resolve (type.get_base_type ());
731 rust_assert (type.has_lifetime ());
732 auto region = context->lookup_and_resolve_lifetime (type.get_lifetime ());
733 if (!region.has_value ())
734 {
735 rust_error_at (type.get_locus (), "failed to resolve lifetime");
736 translated = new TyTy::ErrorType (type.get_mappings ().get_hirid ());
737 return;
738 }
739 translated = new TyTy::ReferenceType (type.get_mappings ().get_hirid (),
740 TyTy::TyVar (base->get_ref ()),
741 type.get_mut (), region.value ());
742 }
743
744 void
745 TypeCheckType::visit (HIR::RawPointerType &type)
746 {
747 TyTy::BaseType *base = TypeCheckType::Resolve (type.get_base_type ());
748 translated
749 = new TyTy::PointerType (type.get_mappings ().get_hirid (),
750 TyTy::TyVar (base->get_ref ()), type.get_mut ());
751 }
752
753 void
754 TypeCheckType::visit (HIR::InferredType &type)
755 {
756 translated = new TyTy::InferType (type.get_mappings ().get_hirid (),
757 TyTy::InferType::InferTypeKind::GENERAL,
758 TyTy::InferType::TypeHint::Default (),
759 type.get_locus ());
760 }
761
762 void
763 TypeCheckType::visit (HIR::NeverType &type)
764 {
765 TyTy::BaseType *lookup = nullptr;
766 bool ok = context->lookup_builtin ("!", &lookup);
767 rust_assert (ok);
768
769 translated = lookup->clone ();
770 }
771
772 void
773 TypeCheckType::visit (HIR::ImplTraitType &type)
774 {
775 std::vector<TyTy::TypeBoundPredicate> specified_bounds;
776 for (auto &bound : type.get_type_param_bounds ())
777 {
778 if (bound->get_bound_type ()
779 != HIR::TypeParamBound::BoundType::TRAITBOUND)
780 continue;
781
782 HIR::TypeParamBound &b = *bound.get ();
783 HIR::TraitBound &trait_bound = static_cast<HIR::TraitBound &> (b);
784
785 auto binder_pin = context->push_lifetime_binder ();
786 for (auto &lifetime_param : trait_bound.get_for_lifetimes ())
787 {
788 context->intern_and_insert_lifetime (lifetime_param.get_lifetime ());
789 }
790
791 TyTy::TypeBoundPredicate predicate = get_predicate_from_bound (
792 trait_bound.get_path (),
793 tl::nullopt /*this will setup a PLACEHOLDER for self*/);
794
795 if (!predicate.is_error ()
796 && predicate.is_object_safe (true, type.get_locus ()))
797 specified_bounds.push_back (std::move (predicate));
798 }
799
800 translated = new TyTy::OpaqueType (type.get_locus (),
801 type.get_mappings ().get_hirid (),
802 specified_bounds);
803 }
804
805 TyTy::ParamType *
806 TypeResolveGenericParam::Resolve (HIR::GenericParam &param,
807 bool resolve_trait_bounds, bool apply_sized)
808 {
809 TypeResolveGenericParam resolver (apply_sized, resolve_trait_bounds);
810 switch (param.get_kind ())
811 {
812 case HIR::GenericParam::GenericKind::TYPE:
813 resolver.visit (static_cast<HIR::TypeParam &> (param));
814 break;
815
816 case HIR::GenericParam::GenericKind::CONST:
817 resolver.visit (static_cast<HIR::ConstGenericParam &> (param));
818 break;
819
820 case HIR::GenericParam::GenericKind::LIFETIME:
821 resolver.visit (static_cast<HIR::LifetimeParam &> (param));
822 break;
823 }
824 return resolver.resolved;
825 }
826
827 void
828 TypeResolveGenericParam::ApplyAnyTraitBounds (HIR::TypeParam &param,
829 TyTy::ParamType *pty)
830 {
831 TypeResolveGenericParam resolver (true, true);
832 resolver.apply_trait_bounds (param, pty);
833 }
834
835 void
836 TypeResolveGenericParam::visit (HIR::LifetimeParam &param)
837 {
838 // nothing to do
839 }
840
841 void
842 TypeResolveGenericParam::visit (HIR::ConstGenericParam &param)
843 {
844 // TODO
845 }
846
847 void
848 TypeResolveGenericParam::visit (HIR::TypeParam &param)
849 {
850 if (param.has_type ())
851 TypeCheckType::Resolve (param.get_type ());
852
853 resolved
854 = new TyTy::ParamType (param.get_type_representation ().as_string (),
855 param.get_locus (),
856 param.get_mappings ().get_hirid (), param, {});
857
858 if (resolve_trait_bounds)
859 apply_trait_bounds (param, resolved);
860 }
861
862 void
863 TypeResolveGenericParam::apply_trait_bounds (HIR::TypeParam &param,
864 TyTy::ParamType *pty)
865 {
866 std::unique_ptr<HIR::Type> implicit_self_bound = nullptr;
867 if (param.has_type_param_bounds ())
868 {
869 // We need two possible parameter types. One with no Bounds and one with
870 // the bounds. the Self type for the bounds cannot itself contain the
871 // bounds otherwise it will be a trait cycle
872 HirId implicit_id = mappings.get_next_hir_id ();
873 TyTy::ParamType *p
874 = new TyTy::ParamType (param.get_type_representation ().as_string (),
875 param.get_locus (), implicit_id, param,
876 {} /*empty specified bounds*/);
877 context->insert_implicit_type (implicit_id, p);
878
879 // generate an implicit HIR Type we can apply to the predicate
880 Analysis::NodeMapping mappings (param.get_mappings ().get_crate_num (),
881 param.get_mappings ().get_nodeid (),
882 implicit_id,
883 param.get_mappings ().get_local_defid ());
884 implicit_self_bound = std::make_unique<HIR::TypePath> (
885 HIR::TypePath (mappings, {}, BUILTINS_LOCATION, false));
886 }
887
888 std::map<DefId, std::vector<TyTy::TypeBoundPredicate>> predicates;
889
890 // https://doc.rust-lang.org/std/marker/trait.Sized.html
891 // All type parameters have an implicit bound of Sized. The special syntax
892 // ?Sized can be used to remove this bound if it’s not appropriate.
893 //
894 // We can only do this when we are not resolving the implicit Self for Sized
895 // itself
896 if (apply_sized)
897 {
898 TyTy::TypeBoundPredicate sized_predicate
899 = get_marker_predicate (LangItem::Kind::SIZED, param.get_locus ());
900
901 predicates[sized_predicate.get_id ()] = {sized_predicate};
902 }
903
904 // resolve the bounds
905 if (param.has_type_param_bounds ())
906 {
907 for (auto &bound : param.get_type_param_bounds ())
908 {
909 switch (bound->get_bound_type ())
910 {
911 case HIR::TypeParamBound::BoundType::TRAITBOUND: {
912 HIR::TraitBound &b = static_cast<HIR::TraitBound &> (*bound);
913
914 TyTy::TypeBoundPredicate predicate = get_predicate_from_bound (
915 b.get_path (),
916 tl::optional<std::reference_wrapper<HIR::Type>> (
917 std::ref (*implicit_self_bound)),
918 b.get_polarity ());
919 if (!predicate.is_error ())
920 {
921 switch (predicate.get_polarity ())
922 {
923 case BoundPolarity::AntiBound: {
924 bool found = predicates.find (predicate.get_id ())
925 != predicates.end ();
926 if (found)
927 predicates.erase (predicate.get_id ());
928 else
929 {
930 // emit error message
931 rich_location r (line_table, b.get_locus ());
932 r.add_range (predicate.get ()->get_locus ());
933 rust_error_at (
934 r, "antibound for %s is not applied here",
935 predicate.get ()->get_name ().c_str ());
936 }
937 }
938 break;
939
940 default: {
941 if (predicates.find (predicate.get_id ())
942 == predicates.end ())
943 {
944 predicates[predicate.get_id ()] = {};
945 }
946 predicates[predicate.get_id ()].push_back (predicate);
947 }
948 break;
949 }
950 }
951 }
952 break;
953
954 default:
955 break;
956 }
957 }
958 }
959
960 // now to flat map the specified_bounds into the raw specified predicates
961 std::vector<TyTy::TypeBoundPredicate> specified_bounds;
962 for (auto it = predicates.begin (); it != predicates.end (); it++)
963 {
964 for (const auto &predicate : it->second)
965 {
966 specified_bounds.push_back (predicate);
967 }
968 }
969
970 // inherit them
971 pty->inherit_bounds (specified_bounds);
972 }
973
974 void
975 ResolveWhereClauseItem::Resolve (HIR::WhereClauseItem &item,
976 TyTy::RegionConstraints &region_constraints)
977 {
978 ResolveWhereClauseItem resolver (region_constraints);
979
980 auto binder_pin = resolver.context->push_lifetime_binder ();
981
982 switch (item.get_item_type ())
983 {
984 case HIR::WhereClauseItem::LIFETIME:
985 resolver.visit (static_cast<HIR::LifetimeWhereClauseItem &> (item));
986 break;
987
988 case HIR::WhereClauseItem::TYPE_BOUND:
989 resolver.visit (static_cast<HIR::TypeBoundWhereClauseItem &> (item));
990 break;
991 }
992 }
993
994 void
995 ResolveWhereClauseItem::visit (HIR::LifetimeWhereClauseItem &item)
996 {
997 auto lhs = context->lookup_and_resolve_lifetime (item.get_lifetime ());
998 if (!lhs.has_value ())
999 {
1000 rust_error_at (UNKNOWN_LOCATION, "failed to resolve lifetime");
1001 }
1002 for (auto &lifetime : item.get_lifetime_bounds ())
1003 {
1004 auto rhs_i = context->lookup_and_resolve_lifetime (lifetime);
1005 if (!rhs_i.has_value ())
1006 {
1007 rust_error_at (UNKNOWN_LOCATION, "failed to resolve lifetime");
1008 }
1009 region_constraints.region_region.emplace_back (lhs.value (),
1010 rhs_i.value ());
1011 }
1012 }
1013
1014 void
1015 ResolveWhereClauseItem::visit (HIR::TypeBoundWhereClauseItem &item)
1016 {
1017 auto binder_pin = context->push_lifetime_binder ();
1018 if (item.has_for_lifetimes ())
1019 {
1020 for (auto &lifetime_param : item.get_for_lifetimes ())
1021 {
1022 context->intern_and_insert_lifetime (lifetime_param.get_lifetime ());
1023 }
1024 }
1025
1026 auto &binding_type_path = item.get_bound_type ();
1027 TyTy::BaseType *binding = TypeCheckType::Resolve (binding_type_path);
1028
1029 // FIXME double check there might be a trait cycle here see TypeParam handling
1030
1031 std::vector<TyTy::TypeBoundPredicate> specified_bounds;
1032 for (auto &bound : item.get_type_param_bounds ())
1033 {
1034 switch (bound->get_bound_type ())
1035 {
1036 case HIR::TypeParamBound::BoundType::TRAITBOUND: {
1037 auto *b = static_cast<HIR::TraitBound *> (bound.get ());
1038
1039 TyTy::TypeBoundPredicate predicate
1040 = get_predicate_from_bound (b->get_path (), binding_type_path);
1041 if (!predicate.is_error ())
1042 specified_bounds.push_back (std::move (predicate));
1043 }
1044 break;
1045 case HIR::TypeParamBound::BoundType::LIFETIME: {
1046 if (auto param = binding->try_as<TyTy::ParamType> ())
1047 {
1048 auto *b = static_cast<HIR::Lifetime *> (bound.get ());
1049 auto region = context->lookup_and_resolve_lifetime (*b);
1050 if (!region.has_value ())
1051 {
1052 rust_error_at (UNKNOWN_LOCATION,
1053 "failed to resolve lifetime");
1054 }
1055 region_constraints.type_region.emplace_back (param,
1056 region.value ());
1057 }
1058 }
1059 break;
1060
1061 default:
1062 break;
1063 }
1064 }
1065 binding->inherit_bounds (specified_bounds);
1066
1067 // When we apply these bounds we must lookup which type this binding
1068 // resolves to, as this is the type which will be used during resolution
1069 // of the block.
1070 NodeId ast_node_id = binding_type_path.get_mappings ().get_nodeid ();
1071
1072 // then lookup the reference_node_id
1073 NodeId ref_node_id = UNKNOWN_NODEID;
1074 if (flag_name_resolution_2_0)
1075 {
1076 auto &nr_ctx
1077 = Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
1078
1079 if (auto id = nr_ctx.lookup (ast_node_id))
1080 ref_node_id = *id;
1081 }
1082 else
1083 {
1084 NodeId id = UNKNOWN_NODEID;
1085
1086 if (resolver->lookup_resolved_type (ast_node_id, &id))
1087 ref_node_id = id;
1088 }
1089
1090 if (ref_node_id == UNKNOWN_NODEID)
1091 {
1092 // FIXME
1093 rust_error_at (UNDEF_LOCATION,
1094 "Failed to lookup type reference for node: %s",
1095 binding_type_path.as_string ().c_str ());
1096 return;
1097 }
1098
1099 // node back to HIR
1100 if (auto hid = mappings.lookup_node_to_hir (ref_node_id))
1101 {
1102 // the base reference for this name _must_ have a type set
1103 TyTy::BaseType *lookup;
1104 if (!context->lookup_type (*hid, &lookup))
1105 {
1106 rust_error_at (mappings.lookup_location (*hid),
1107 "Failed to resolve where-clause binding type: %s",
1108 binding_type_path.as_string ().c_str ());
1109 return;
1110 }
1111
1112 // FIXME
1113 // rust_assert (binding->is_equal (*lookup));
1114 lookup->inherit_bounds (specified_bounds);
1115 return;
1116 }
1117 rust_error_at (UNDEF_LOCATION, "where-clause reverse lookup failure");
1118 }
1119
1120 } // namespace Resolver
1121 } // namespace Rust