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