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 "optional.h"
20 : #include "rust-common.h"
21 : #include "rust-diagnostics.h"
22 : #include "rust-hir-expr.h"
23 : #include "rust-hir-map.h"
24 : #include "rust-rib.h"
25 : #include "rust-system.h"
26 : #include "rust-tyty-call.h"
27 : #include "rust-hir-type-check-struct-field.h"
28 : #include "rust-hir-path-probe.h"
29 : #include "rust-substitution-mapper.h"
30 : #include "rust-hir-trait-resolve.h"
31 : #include "rust-hir-dot-operator.h"
32 : #include "rust-hir-type-check-pattern.h"
33 : #include "rust-hir-type-check-expr.h"
34 : #include "rust-hir-type-check-stmt.h"
35 : #include "rust-hir-type-check-item.h"
36 : #include "rust-type-util.h"
37 : #include "rust-finalized-name-resolution-context.h"
38 : #include "rust-compile-base.h"
39 : #include "rust-tyty-util.h"
40 : #include "rust-tyty.h"
41 :
42 : namespace Rust {
43 : namespace Resolver {
44 :
45 202786 : TypeCheckExpr::TypeCheckExpr () : TypeCheckBase (), infered (nullptr) {}
46 :
47 : TyTy::BaseType *
48 202771 : TypeCheckExpr::Resolve (HIR::Expr &expr)
49 : {
50 202771 : TypeCheckExpr resolver;
51 202771 : expr.accept_vis (resolver);
52 :
53 : // the error type has to go in the context like any other, autoderef
54 : // looks this expression's type up by ref later and would get nullptr
55 202354 : if (resolver.infered == nullptr)
56 165 : resolver.infered = new TyTy::ErrorType (expr.get_mappings ().get_hirid ());
57 :
58 202354 : if (resolver.infered->get_kind () != TyTy::TypeKind::CONST)
59 : {
60 201581 : auto ref = expr.get_mappings ().get_hirid ();
61 201581 : resolver.infered->set_ref (ref);
62 : }
63 202354 : resolver.context->insert_type (expr.get_mappings (), resolver.infered);
64 :
65 202354 : if (auto fn = resolver.infered->try_as<const TyTy::FnType> ())
66 : {
67 12968 : if (fn->is_syn_constant ())
68 28 : resolver.infered = fn->get_return_type ();
69 : }
70 :
71 202354 : return resolver.infered;
72 202354 : }
73 :
74 : TyTy::BaseType *
75 15 : TypeCheckExpr::ResolveOpOverload (LangItem::Kind lang_item_type,
76 : HIR::OperatorExprMeta expr,
77 : TyTy::BaseType *lhs, TyTy::BaseType *rhs,
78 : HIR::PathIdentSegment specified_segment,
79 : TyTy::BaseType *result_type)
80 : {
81 15 : TypeCheckExpr resolver;
82 :
83 30 : resolver.resolve_operator_overload (lang_item_type, expr, lhs, rhs,
84 : specified_segment, false, result_type);
85 15 : return resolver.infered;
86 15 : }
87 :
88 : void
89 1987 : TypeCheckExpr::visit (HIR::TupleIndexExpr &expr)
90 : {
91 1987 : auto resolved
92 1987 : = TypeCheckExpr::Resolve (expr.get_tuple_expr ())->destructure ();
93 1973 : if (resolved->get_kind () == TyTy::TypeKind::ERROR)
94 : {
95 2 : rust_error_at (expr.get_tuple_expr ().get_locus (),
96 : "failed to resolve TupleIndexExpr receiver");
97 2 : return;
98 : }
99 :
100 : // Box<T> autoderef
101 1971 : if (auto resolved_base = TyTy::try_get_box_inner_type (resolved))
102 : {
103 2 : resolved = *resolved_base;
104 : }
105 :
106 : // FIXME does this require autoderef here?
107 1971 : if (resolved->get_kind () == TyTy::TypeKind::REF)
108 : {
109 325 : TyTy::ReferenceType *r = static_cast<TyTy::ReferenceType *> (resolved);
110 325 : resolved = r->get_base ();
111 : }
112 :
113 1971 : bool is_valid_type = resolved->get_kind () == TyTy::TypeKind::ADT
114 1971 : || resolved->get_kind () == TyTy::TypeKind::TUPLE;
115 2 : if (!is_valid_type)
116 : {
117 2 : rust_error_at (expr.get_tuple_expr ().get_locus (),
118 : "Expected Tuple or ADT got: %s",
119 2 : resolved->as_string ().c_str ());
120 2 : return;
121 : }
122 :
123 1969 : if (resolved->get_kind () == TyTy::TypeKind::TUPLE)
124 : {
125 446 : TyTy::TupleType *tuple = static_cast<TyTy::TupleType *> (resolved);
126 446 : TupleIndex index = expr.get_tuple_index ();
127 446 : if ((size_t) index >= tuple->num_fields ())
128 : {
129 1 : rust_error_at (expr.get_locus (), ErrorCode::E0609,
130 : "no field %qi on type %qs", index,
131 1 : resolved->get_name ().c_str ());
132 1 : return;
133 : }
134 :
135 445 : auto field_tyty = tuple->get_field ((size_t) index);
136 445 : if (field_tyty == nullptr)
137 : {
138 0 : rust_error_at (expr.get_locus (),
139 : "failed to lookup field type at index %i", index);
140 0 : return;
141 : }
142 :
143 445 : infered = field_tyty;
144 445 : return;
145 : }
146 :
147 1523 : TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (resolved);
148 1523 : if (!adt->is_tuple_struct ())
149 : {
150 4 : rust_error_at (expr.get_locus (),
151 : "expected tuple or tuple struct, found %qs",
152 4 : adt->get_name ().c_str ());
153 4 : return;
154 : }
155 1519 : rust_assert (adt->number_of_variants () == 1);
156 :
157 1519 : TyTy::VariantDef *variant = adt->get_variants ().at (0);
158 1519 : TupleIndex index = expr.get_tuple_index ();
159 1519 : if ((size_t) index >= variant->num_fields ())
160 : {
161 0 : rust_error_at (expr.get_locus (), "unknown field at index %i", index);
162 0 : return;
163 : }
164 :
165 1519 : auto field_tyty = variant->get_field_at_index ((size_t) index);
166 1519 : if (field_tyty == nullptr)
167 : {
168 0 : rust_error_at (expr.get_locus (),
169 : "failed to lookup field type at index %i", index);
170 0 : return;
171 : }
172 :
173 1519 : infered = field_tyty->get_field_type ();
174 : }
175 :
176 : void
177 705 : TypeCheckExpr::visit (HIR::TupleExpr &expr)
178 : {
179 705 : if (expr.is_unit ())
180 : {
181 152 : infered = TyTy::TupleType::get_unit_type ();
182 152 : return;
183 : }
184 :
185 553 : std::vector<TyTy::TyVar> fields;
186 1782 : for (auto &elem : expr.get_tuple_elems ())
187 : {
188 1229 : auto field_ty = TypeCheckExpr::Resolve (*elem);
189 1229 : fields.emplace_back (field_ty->get_ref ());
190 : }
191 1106 : infered = new TyTy::TupleType (expr.get_mappings ().get_hirid (),
192 1106 : expr.get_locus (), fields);
193 553 : }
194 :
195 : void
196 6 : TypeCheckExpr::visit (HIR::BoxExpr &expr)
197 : {
198 6 : auto owned_box_defid
199 6 : = mappings.get_lang_item (LangItem::Kind::OWNED_BOX, expr.get_locus ());
200 :
201 6 : HIR::Item *item = mappings.lookup_defid (owned_box_defid).value ();
202 6 : TyTy::BaseType *item_type = TypeCheckItem::Resolve (*item);
203 :
204 6 : if (item_type->get_kind () != TyTy::TypeKind::ADT)
205 : {
206 0 : rust_error_at (item->get_locus (), ErrorCode::E0718,
207 : "%qs language item must be applied to a struct",
208 : "owned_box");
209 2 : return;
210 : }
211 6 : TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (item_type);
212 6 : if (!adt->is_tuple_struct () && !adt->is_struct_struct ())
213 : {
214 1 : rust_error_at (item->get_locus (), ErrorCode::E0718,
215 : "%qs language item must be applied to a struct",
216 : "owned_box");
217 1 : return;
218 : }
219 :
220 : // this is at least one generic item
221 5 : if (adt->get_num_substitutions () < 1)
222 : {
223 1 : rust_error_at (expr.get_locus (),
224 : "%qs lang item must be applied to a struct with at least "
225 : "1 generic argument",
226 : "owned_box");
227 1 : return;
228 : }
229 :
230 4 : TyTy::BaseType *inner_ty = TypeCheckExpr::Resolve (expr.get_expr ());
231 4 : if (inner_ty->get_kind () == TyTy::TypeKind::ERROR)
232 : {
233 0 : infered = inner_ty;
234 0 : return;
235 : }
236 :
237 4 : auto lookup = SubstMapper::InferSubst (adt, expr.get_locus ());
238 4 : rust_assert (lookup->get_kind () == TyTy::TypeKind::ADT);
239 4 : TyTy::ADTType *adt_box = static_cast<TyTy::ADTType *> (lookup);
240 :
241 4 : TyTy::BaseType *infer = adt_box->get_substs ().at (0).get_param_ty ();
242 :
243 8 : unify_site (expr.get_mappings ().get_hirid (),
244 4 : TyTy::TyWithLocation (infer, expr.get_locus ()),
245 4 : TyTy::TyWithLocation (inner_ty, expr.get_locus ()),
246 : expr.get_locus ());
247 :
248 4 : infered = adt_box;
249 : }
250 :
251 : void
252 1238 : TypeCheckExpr::visit (HIR::ReturnExpr &expr)
253 : {
254 1238 : if (!context->have_function_context ())
255 : {
256 1 : rust_error_at (expr.get_locus (), ErrorCode::E0572,
257 : "return statement outside of function body");
258 1 : infered = new TyTy::ErrorType (expr.get_mappings ().get_hirid ());
259 1 : return;
260 : }
261 :
262 1237 : auto fn_return_tyty = context->peek_return_type ();
263 1237 : location_t expr_locus = expr.has_return_expr ()
264 1237 : ? expr.get_expr ().get_locus ()
265 37 : : expr.get_locus ();
266 :
267 : // Push expected type so the resolver of the return expression
268 : // inference before checking its arguments which is needed
269 : // for things like:
270 : //
271 : // return Try::from_error(...)
272 : //
273 : // Where Self has to bind from the fn return type before the param
274 : // projection can be normalized.
275 1237 : TyTy::BaseType *expr_ty;
276 1237 : if (expr.has_return_expr ())
277 : {
278 1200 : context->push_expected_type (fn_return_tyty);
279 1200 : expr_ty = TypeCheckExpr::Resolve (expr.get_expr ());
280 1200 : context->pop_expected_type ();
281 : }
282 : else
283 37 : expr_ty = TyTy::TupleType::get_unit_type ();
284 :
285 2474 : coercion_site (expr.get_mappings ().get_hirid (),
286 1237 : TyTy::TyWithLocation (fn_return_tyty),
287 1237 : TyTy::TyWithLocation (expr_ty, expr_locus), expr.get_locus ());
288 :
289 1237 : infered = new TyTy::NeverType (expr.get_mappings ().get_hirid ());
290 : }
291 :
292 : void
293 15576 : TypeCheckExpr::visit (HIR::CallExpr &expr)
294 : {
295 15576 : TyTy::BaseType *function_tyty = TypeCheckExpr::Resolve (expr.get_fnexpr ());
296 :
297 15575 : rust_debug_loc (expr.get_locus (), "resolved_call_expr to: {%s}",
298 : function_tyty->get_name ().c_str ());
299 :
300 15575 : TyTy::VariantDef &variant = TyTy::VariantDef::get_error_node ();
301 15575 : if (function_tyty->get_kind () == TyTy::TypeKind::ADT)
302 : {
303 2591 : TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (function_tyty);
304 2591 : if (adt->is_enum ())
305 : {
306 : // lookup variant id
307 1060 : HirId variant_id;
308 1060 : bool ok = context->lookup_variant_definition (
309 1060 : expr.get_fnexpr ().get_mappings ().get_hirid (), &variant_id);
310 :
311 1060 : if (!ok)
312 : {
313 1 : rust_error_at (expr.get_locus (), ErrorCode::E0423,
314 : "expected function, tuple struct or tuple "
315 : "variant, found enum");
316 1 : return;
317 : }
318 :
319 1059 : TyTy::VariantDef *lookup_variant = nullptr;
320 1059 : ok = adt->lookup_variant_by_id (variant_id, &lookup_variant);
321 1059 : rust_assert (ok);
322 :
323 1059 : variant = std::move (*lookup_variant->clone ());
324 : }
325 : else
326 : {
327 1531 : rust_assert (adt->number_of_variants () == 1);
328 1531 : variant = std::move (*adt->get_variants ().at (0)->clone ());
329 : }
330 2590 : infered
331 2590 : = TyTy::TypeCheckCallExpr::go (function_tyty, expr, variant, context);
332 2562 : return;
333 : }
334 :
335 12984 : bool resolved_fn_trait_call
336 12984 : = resolve_fn_trait_call (expr, function_tyty, &infered);
337 12984 : if (resolved_fn_trait_call)
338 : return;
339 :
340 12918 : bool valid_tyty
341 12961 : = function_tyty->is<TyTy::FnType> () || function_tyty->is<TyTy::FnPtr> ();
342 13 : if (!valid_tyty)
343 : {
344 13 : bool emit_error = !function_tyty->is<TyTy::ErrorType> ();
345 13 : if (emit_error)
346 : {
347 2 : rich_location r (line_table, expr.get_locus ());
348 2 : rust_error_at (r, ErrorCode::E0618, "expected function, found %<%s%>",
349 2 : function_tyty->get_name ().c_str ());
350 2 : }
351 : return;
352 : }
353 :
354 12905 : infered = TyTy::TypeCheckCallExpr::go (function_tyty, expr, variant, context);
355 :
356 : // Pre-GATS: associated types were PlaceholderType; post-GATS they are
357 : // ProjectionType, this hHandle both so the isize special-case still fires
358 12877 : auto discriminant_type_lookup
359 12877 : = mappings.lookup_lang_item (LangItem::Kind::DISCRIMINANT_TYPE);
360 12877 : bool is_discriminant_type = false;
361 12877 : if (discriminant_type_lookup)
362 : {
363 1097 : if (auto *p = infered->try_as<TyTy::PlaceholderType> ())
364 0 : is_discriminant_type
365 0 : = p->get_def_id () == discriminant_type_lookup.value ();
366 13974 : else if (auto *p = infered->try_as<TyTy::ProjectionType> ())
367 0 : is_discriminant_type
368 0 : = p->get_item_defid () == discriminant_type_lookup.value ();
369 : }
370 0 : if (is_discriminant_type)
371 : {
372 : // This is a special case: discriminant_value returns the repr of the
373 : // enum. We don't currently support repr on enum yet, so the default
374 : // is always isize.
375 0 : bool ok = context->lookup_builtin ("isize", &infered);
376 0 : rust_assert (ok);
377 :
378 0 : rust_assert (function_tyty->is<TyTy::FnType> ());
379 0 : auto &fn = *static_cast<TyTy::FnType *> (function_tyty);
380 0 : rust_assert (fn.has_substitutions ());
381 0 : rust_assert (fn.get_num_type_params () == 1);
382 0 : auto &mapping = fn.get_substs ().at (0);
383 0 : auto param_ty = mapping.get_param_ty ();
384 :
385 0 : if (!param_ty->can_resolve ())
386 : {
387 0 : rust_internal_error_at (expr.get_locus (),
388 : "something wrong computing return type");
389 : return;
390 : }
391 :
392 0 : auto resolved = param_ty->resolve ();
393 0 : if (resolved->is<TyTy::ADTType> ())
394 : {
395 0 : const auto &adt = *static_cast<TyTy::ADTType *> (resolved);
396 0 : infered = adt.get_repr_options ().repr;
397 0 : rust_assert (infered != nullptr);
398 : }
399 : }
400 : }
401 :
402 : void
403 2704 : TypeCheckExpr::visit (HIR::AssignmentExpr &expr)
404 : {
405 2704 : infered = TyTy::TupleType::get_unit_type ();
406 :
407 2704 : auto lhs = TypeCheckExpr::Resolve (expr.get_lhs ());
408 2704 : auto rhs = TypeCheckExpr::Resolve (expr.get_rhs ());
409 :
410 5408 : if (lhs->is<TyTy::ErrorType> () || rhs->is<TyTy::ErrorType> ())
411 : return;
412 :
413 5402 : coercion_site (expr.get_mappings ().get_hirid (),
414 2701 : TyTy::TyWithLocation (lhs, expr.get_lhs ().get_locus ()),
415 2701 : TyTy::TyWithLocation (rhs, expr.get_rhs ().get_locus ()),
416 : expr.get_locus ());
417 : }
418 :
419 : void
420 722 : TypeCheckExpr::visit (HIR::CompoundAssignmentExpr &expr)
421 : {
422 722 : infered = TyTy::TupleType::get_unit_type ();
423 :
424 722 : auto lhs = TypeCheckExpr::Resolve (expr.get_lhs ());
425 722 : auto rhs = TypeCheckExpr::Resolve (expr.get_rhs ());
426 :
427 1444 : if (lhs->is<TyTy::ErrorType> () || rhs->is<TyTy::ErrorType> ())
428 : return;
429 :
430 722 : auto lang_item_type
431 722 : = LangItem::CompoundAssignmentOperatorToLangItem (expr.get_expr_type ());
432 722 : bool operator_overloaded
433 722 : = resolve_operator_overload (lang_item_type, expr, lhs, rhs);
434 722 : if (operator_overloaded)
435 : return;
436 :
437 708 : bool valid_lhs = validate_arithmetic_type (lhs, expr.get_expr_type ());
438 708 : bool valid_rhs = validate_arithmetic_type (rhs, expr.get_expr_type ());
439 708 : bool valid = valid_lhs && valid_rhs;
440 708 : if (!valid)
441 : {
442 0 : rust_error_at (expr.get_locus (),
443 : "cannot apply operator %qs to types %s and %s",
444 0 : expr.get_operator_str ().c_str (),
445 0 : lhs->as_string ().c_str (), rhs->as_string ().c_str ());
446 0 : return;
447 : }
448 :
449 708 : switch (expr.get_expr_type ())
450 : {
451 15 : case ArithmeticOrLogicalOperator::LEFT_SHIFT:
452 15 : case ArithmeticOrLogicalOperator::RIGHT_SHIFT:
453 15 : {
454 15 : TyTy::TyWithLocation from (rhs, expr.get_rhs ().get_locus ());
455 15 : TyTy::TyWithLocation to (lhs, expr.get_lhs ().get_locus ());
456 15 : cast_site (expr.get_mappings ().get_hirid (), from, to,
457 : expr.get_locus ());
458 15 : break;
459 : }
460 693 : default:
461 : // we dont care about the result of the unify from a compound assignment
462 : // since this is a unit-type expr
463 1386 : coercion_site (expr.get_mappings ().get_hirid (),
464 693 : TyTy::TyWithLocation (lhs, expr.get_lhs ().get_locus ()),
465 693 : TyTy::TyWithLocation (rhs, expr.get_rhs ().get_locus ()),
466 : expr.get_locus ());
467 : }
468 : }
469 :
470 : void
471 29526 : TypeCheckExpr::visit (HIR::LiteralExpr &expr)
472 : {
473 29526 : infered = resolve_literal (expr.get_mappings (), expr.get_literal (),
474 : expr.get_locus ());
475 29526 : }
476 :
477 : void
478 8928 : TypeCheckExpr::visit (HIR::ArithmeticOrLogicalExpr &expr)
479 : {
480 8928 : auto lhs = TypeCheckExpr::Resolve (expr.get_lhs ());
481 8928 : auto rhs = TypeCheckExpr::Resolve (expr.get_rhs ());
482 :
483 17813 : if (lhs->is<TyTy::ErrorType> () || rhs->is<TyTy::ErrorType> ())
484 : return;
485 :
486 8906 : auto lang_item_type = LangItem::OperatorToLangItem (expr.get_expr_type ());
487 8906 : bool operator_overloaded
488 8906 : = resolve_operator_overload (lang_item_type, expr, lhs, rhs);
489 8878 : if (operator_overloaded)
490 : return;
491 :
492 4149 : bool valid_lhs = validate_arithmetic_type (lhs, expr.get_expr_type ());
493 4149 : bool valid_rhs = validate_arithmetic_type (rhs, expr.get_expr_type ());
494 4149 : bool valid = valid_lhs && valid_rhs;
495 4149 : if (!valid)
496 : {
497 6 : rust_error_at (expr.get_locus (),
498 : "cannot apply operator %qs to types %s and %s",
499 6 : expr.get_operator_str ().c_str (),
500 6 : lhs->as_string ().c_str (), rhs->as_string ().c_str ());
501 3 : return;
502 : }
503 :
504 4146 : switch (expr.get_expr_type ())
505 : {
506 237 : case ArithmeticOrLogicalOperator::LEFT_SHIFT:
507 237 : case ArithmeticOrLogicalOperator::RIGHT_SHIFT:
508 237 : {
509 237 : TyTy::TyWithLocation from (rhs, expr.get_rhs ().get_locus ());
510 237 : TyTy::TyWithLocation to (lhs, expr.get_lhs ().get_locus ());
511 237 : infered = cast_site (expr.get_mappings ().get_hirid (), from, to,
512 : expr.get_locus ());
513 : }
514 237 : break;
515 :
516 3909 : default:
517 3909 : {
518 7818 : infered = unify_site (
519 3909 : expr.get_mappings ().get_hirid (),
520 3909 : TyTy::TyWithLocation (lhs, expr.get_lhs ().get_locus ()),
521 3909 : TyTy::TyWithLocation (rhs, expr.get_rhs ().get_locus ()),
522 : expr.get_locus ());
523 : }
524 3909 : break;
525 : }
526 : }
527 :
528 : void
529 5024 : TypeCheckExpr::visit (HIR::ComparisonExpr &expr)
530 : {
531 5024 : auto lhs = TypeCheckExpr::Resolve (expr.get_lhs ());
532 5024 : auto rhs = TypeCheckExpr::Resolve (expr.get_rhs ());
533 :
534 10019 : if (lhs->is<TyTy::ErrorType> () || rhs->is<TyTy::ErrorType> ())
535 1013 : return;
536 :
537 5009 : auto borrowed_lhs
538 5009 : = new TyTy::ReferenceType (mappings.get_next_hir_id (),
539 5009 : TyTy::TyVar (lhs->get_ref ()), Mutability::Imm);
540 5009 : context->insert_implicit_type (borrowed_lhs->get_ref (), borrowed_lhs);
541 :
542 5009 : auto borrowed_rhs
543 5009 : = new TyTy::ReferenceType (mappings.get_next_hir_id (),
544 5009 : TyTy::TyVar (rhs->get_ref ()), Mutability::Imm);
545 5009 : context->insert_implicit_type (borrowed_rhs->get_ref (), borrowed_rhs);
546 :
547 5009 : auto seg_name = LangItem::ComparisonToSegment (expr.get_expr_type ());
548 10018 : auto segment = HIR::PathIdentSegment (seg_name);
549 5009 : auto lang_item_type = LangItem::ComparisonToLangItem (expr.get_expr_type ());
550 :
551 5009 : bool operator_overloaded
552 5009 : = resolve_operator_overload (lang_item_type, expr, lhs, borrowed_rhs,
553 : segment, true, nullptr, borrowed_lhs);
554 5009 : if (operator_overloaded)
555 1012 : return;
556 :
557 7994 : unify_site (expr.get_mappings ().get_hirid (),
558 3997 : TyTy::TyWithLocation (lhs, expr.get_lhs ().get_locus ()),
559 3997 : TyTy::TyWithLocation (rhs, expr.get_rhs ().get_locus ()),
560 : expr.get_locus ());
561 :
562 3997 : bool ok = context->lookup_builtin ("bool", &infered);
563 3997 : rust_assert (ok);
564 5009 : }
565 :
566 : void
567 1062 : TypeCheckExpr::visit (HIR::LazyBooleanExpr &expr)
568 : {
569 1062 : auto lhs = TypeCheckExpr::Resolve (expr.get_lhs ());
570 1062 : auto rhs = TypeCheckExpr::Resolve (expr.get_rhs ());
571 :
572 2123 : if (lhs->is<TyTy::ErrorType> () || rhs->is<TyTy::ErrorType> ())
573 1 : return;
574 :
575 : // we expect the lhs and rhs must be bools at this point
576 1061 : TyTy::BaseType *boolean_node = nullptr;
577 1061 : bool ok = context->lookup_builtin ("bool", &boolean_node);
578 1061 : rust_assert (ok);
579 :
580 : // verify the lhs and rhs before unifying together
581 2122 : lhs = unify_site (expr.get_mappings ().get_hirid (),
582 : TyTy::TyWithLocation (boolean_node,
583 1061 : expr.get_lhs ().get_locus ()),
584 1061 : TyTy::TyWithLocation (lhs, expr.get_lhs ().get_locus ()),
585 : expr.get_locus ());
586 :
587 2122 : rhs = unify_site (expr.get_mappings ().get_hirid (),
588 : TyTy::TyWithLocation (boolean_node,
589 1061 : expr.get_rhs ().get_locus ()),
590 1061 : TyTy::TyWithLocation (rhs, expr.get_rhs ().get_locus ()),
591 : expr.get_locus ());
592 :
593 1061 : infered
594 2122 : = unify_site (expr.get_mappings ().get_hirid (),
595 1061 : TyTy::TyWithLocation (lhs, expr.get_lhs ().get_locus ()),
596 1061 : TyTy::TyWithLocation (rhs, expr.get_rhs ().get_locus ()),
597 : expr.get_locus ());
598 : }
599 :
600 : void
601 1359 : TypeCheckExpr::visit (HIR::NegationExpr &expr)
602 : {
603 1359 : auto negated_expr_ty = TypeCheckExpr::Resolve (expr.get_expr ());
604 :
605 1359 : if (negated_expr_ty->is<TyTy::ErrorType> ())
606 : return;
607 :
608 : // check for operator overload
609 1359 : auto lang_item_type
610 1359 : = LangItem::NegationOperatorToLangItem (expr.get_expr_type ());
611 1359 : bool operator_overloaded
612 1359 : = resolve_operator_overload (lang_item_type, expr, negated_expr_ty,
613 : nullptr);
614 1352 : if (operator_overloaded)
615 : return;
616 :
617 : // https://doc.rust-lang.org/reference/expressions/operator-expr.html#negation-operators
618 1163 : switch (expr.get_expr_type ())
619 : {
620 755 : case NegationOperator::NEGATE:
621 755 : {
622 755 : bool valid
623 755 : = (negated_expr_ty->get_kind () == TyTy::TypeKind::INT)
624 564 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::UINT)
625 564 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::FLOAT)
626 548 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::ISIZE)
627 538 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::USIZE)
628 538 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::INFER
629 537 : && (((TyTy::InferType *) negated_expr_ty)->get_infer_kind ()
630 : == TyTy::InferType::INTEGRAL))
631 756 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::INFER
632 0 : && (((TyTy::InferType *) negated_expr_ty)->get_infer_kind ()
633 1162 : == TyTy::InferType::FLOAT));
634 1 : if (!valid)
635 : {
636 1 : rust_error_at (expr.get_locus (), "cannot apply unary - to %s",
637 1 : negated_expr_ty->as_string ().c_str ());
638 1 : return;
639 : }
640 : }
641 : break;
642 :
643 408 : case NegationOperator::NOT:
644 408 : {
645 408 : bool valid
646 408 : = (negated_expr_ty->get_kind () == TyTy::TypeKind::BOOL)
647 145 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::INT)
648 103 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::UINT)
649 26 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::ISIZE)
650 18 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::USIZE)
651 418 : || (negated_expr_ty->get_kind () == TyTy::TypeKind::INFER
652 9 : && (((TyTy::InferType *) negated_expr_ty)->get_infer_kind ()
653 1162 : == TyTy::InferType::INTEGRAL));
654 1 : if (!valid)
655 : {
656 1 : rust_error_at (expr.get_locus (), "cannot apply unary %<!%> to %s",
657 1 : negated_expr_ty->as_string ().c_str ());
658 1 : return;
659 : }
660 : }
661 : break;
662 : }
663 :
664 1161 : infered = negated_expr_ty->clone ();
665 1161 : infered->append_reference (negated_expr_ty->get_ref ());
666 : }
667 :
668 : void
669 1978 : TypeCheckExpr::visit (HIR::IfExpr &expr)
670 : {
671 1978 : TyTy::BaseType *bool_ty = nullptr;
672 1978 : bool ok = context->lookup_builtin ("bool", &bool_ty);
673 1978 : rust_assert (ok);
674 :
675 1978 : TyTy::BaseType *cond_type = TypeCheckExpr::Resolve (expr.get_if_condition ());
676 :
677 3956 : unify_site (expr.get_mappings ().get_hirid (), TyTy::TyWithLocation (bool_ty),
678 : TyTy::TyWithLocation (cond_type,
679 1978 : expr.get_if_condition ().get_locus ()),
680 : expr.get_locus ());
681 :
682 1978 : TyTy::BaseType *block_type = TypeCheckExpr::Resolve (expr.get_if_block ());
683 :
684 1978 : TyTy::BaseType *unit_ty = nullptr;
685 1978 : ok = context->lookup_builtin ("()", &unit_ty);
686 1978 : rust_assert (ok);
687 :
688 1978 : infered
689 3956 : = coercion_site (expr.get_mappings ().get_hirid (),
690 1978 : TyTy::TyWithLocation (unit_ty),
691 : TyTy::TyWithLocation (block_type,
692 1978 : expr.get_if_block ().get_locus ()),
693 : expr.get_locus ());
694 1978 : }
695 :
696 : void
697 1388 : TypeCheckExpr::visit (HIR::IfExprConseqElse &expr)
698 : {
699 1388 : TyTy::BaseType *bool_ty = nullptr;
700 1388 : bool ok = context->lookup_builtin ("bool", &bool_ty);
701 1388 : rust_assert (ok);
702 :
703 1388 : TyTy::BaseType *cond_type = TypeCheckExpr::Resolve (expr.get_if_condition ());
704 :
705 2748 : unify_site (expr.get_mappings ().get_hirid (), TyTy::TyWithLocation (bool_ty),
706 : TyTy::TyWithLocation (cond_type,
707 1374 : expr.get_if_condition ().get_locus ()),
708 : expr.get_locus ());
709 :
710 1374 : auto if_blk_resolved = TypeCheckExpr::Resolve (expr.get_if_block ());
711 1374 : auto else_blk_resolved = TypeCheckExpr::Resolve (expr.get_else_block ());
712 :
713 1374 : if (if_blk_resolved->get_kind () == TyTy::NEVER)
714 40 : infered = else_blk_resolved;
715 1334 : else if (else_blk_resolved->get_kind () == TyTy::NEVER)
716 7 : infered = if_blk_resolved;
717 : else
718 : {
719 1327 : infered
720 2654 : = unify_site (expr.get_mappings ().get_hirid (),
721 : TyTy::TyWithLocation (if_blk_resolved,
722 1327 : expr.get_if_block ().get_locus ()),
723 : TyTy::TyWithLocation (
724 1327 : else_blk_resolved, expr.get_else_block ().get_locus ()),
725 : expr.get_locus ());
726 : }
727 1374 : }
728 :
729 : void
730 4383 : TypeCheckExpr::visit (HIR::UnsafeBlockExpr &expr)
731 : {
732 4383 : infered = TypeCheckExpr::Resolve (expr.get_block_expr ());
733 4369 : }
734 :
735 : void
736 29379 : TypeCheckExpr::visit (HIR::BlockExpr &expr)
737 : {
738 29379 : bool has_label = expr.has_label ();
739 29379 : if (expr.has_label ())
740 3 : context->push_new_loop_context (expr.get_mappings ().get_hirid (),
741 : expr.get_locus ());
742 :
743 : // Forward the caller's expected type to the block's tail expression only.
744 29379 : TyTy::BaseType *outer_expected = context->peek_expected_type ();
745 29379 : context->push_expected_type (nullptr);
746 :
747 57209 : for (auto &s : expr.get_statements ())
748 : {
749 27830 : if (!s->is_item ())
750 27369 : continue;
751 :
752 461 : TypeCheckStmt::Resolve (*s);
753 : }
754 :
755 57209 : for (auto &s : expr.get_statements ())
756 : {
757 27830 : if (s->is_item ())
758 461 : continue;
759 :
760 27369 : auto resolved = TypeCheckStmt::Resolve (*s);
761 27369 : if (resolved == nullptr)
762 : {
763 0 : rust_error_at (s->get_locus (), "failure to resolve type");
764 0 : context->pop_expected_type ();
765 0 : if (has_label)
766 0 : context->pop_loop_context ();
767 29274 : return;
768 : }
769 :
770 27369 : if (s->is_unit_check_needed () && !resolved->is_unit ())
771 : {
772 6 : auto unit = TyTy::TupleType::get_unit_type ();
773 12 : unify_site (s->get_mappings ().get_hirid (),
774 6 : TyTy::TyWithLocation (unit),
775 6 : TyTy::TyWithLocation (resolved), s->get_locus ());
776 : }
777 : }
778 :
779 29379 : context->pop_expected_type ();
780 :
781 29379 : TyTy::BaseType *tail_expr_type = nullptr;
782 29379 : if (expr.has_expr ())
783 : {
784 21382 : context->push_expected_type (outer_expected);
785 21382 : tail_expr_type = TypeCheckExpr::Resolve (expr.get_final_expr ());
786 21277 : context->pop_expected_type ();
787 : }
788 :
789 29274 : TyTy::BaseType *label_context_type = nullptr;
790 29274 : bool label_context_type_infered = false;
791 29274 : if (has_label)
792 : {
793 3 : label_context_type = context->pop_loop_context ();
794 :
795 3 : label_context_type_infered
796 3 : = (label_context_type->get_kind () != TyTy::TypeKind::INFER)
797 3 : || ((label_context_type->get_kind () == TyTy::TypeKind::INFER)
798 3 : && (((TyTy::InferType *) label_context_type)->get_infer_kind ()
799 : != TyTy::InferType::GENERAL));
800 : }
801 :
802 29274 : if (tail_expr_type != nullptr)
803 : {
804 21277 : if (label_context_type_infered)
805 : {
806 2 : if (tail_expr_type->get_kind () == TyTy::TypeKind::NEVER)
807 0 : infered = label_context_type;
808 : else
809 4 : infered = unify_site (
810 2 : expr.get_mappings ().get_hirid (),
811 2 : TyTy::TyWithLocation (label_context_type),
812 : TyTy::TyWithLocation (tail_expr_type,
813 2 : expr.get_final_expr ().get_locus ()),
814 : expr.get_locus ());
815 : }
816 : else
817 21275 : infered = tail_expr_type;
818 : }
819 7997 : else if (label_context_type_infered)
820 1 : infered = label_context_type;
821 7996 : else if (expr.is_tail_reachable ())
822 6846 : infered = TyTy::TupleType::get_unit_type ();
823 : else
824 : {
825 : // FIXME this seems wrong
826 1150 : infered = new TyTy::NeverType (expr.get_mappings ().get_hirid ());
827 : }
828 : }
829 :
830 : void
831 1303 : TypeCheckExpr::visit (HIR::AnonConst &expr)
832 : {
833 1303 : if (!expr.is_deferred ())
834 : {
835 1291 : infered = TypeCheckExpr::Resolve (expr.get_inner_expr ());
836 1291 : return;
837 : }
838 :
839 12 : TyTy::TyVar var
840 12 : = TyTy::TyVar::get_implicit_const_infer_var (expr.get_locus ());
841 12 : infered = var.get_tyty ();
842 : }
843 :
844 : void
845 40 : TypeCheckExpr::visit (HIR::ConstBlock &expr)
846 : {
847 40 : infered = TypeCheckExpr::Resolve (expr.get_const_expr ());
848 40 : }
849 :
850 : void
851 74 : TypeCheckExpr::visit (HIR::RangeFromToExpr &expr)
852 : {
853 74 : auto lang_item_type = LangItem::Kind::RANGE;
854 :
855 74 : auto lang_item_defined = mappings.lookup_lang_item (lang_item_type);
856 : // we need to have it maybe
857 74 : if (!lang_item_defined)
858 : {
859 0 : rust_internal_error_at (expr.get_locus (),
860 : "unable to find relevant lang item: %s",
861 0 : LangItem::ToString (lang_item_type).c_str ());
862 : return;
863 : }
864 74 : DefId respective_lang_item_id = lang_item_defined.value ();
865 :
866 : // look it up and it _must_ be a struct definition
867 74 : HIR::Item *item = mappings.lookup_defid (respective_lang_item_id).value ();
868 :
869 74 : TyTy::BaseType *item_type = TypeCheckItem::Resolve (*item);
870 74 : rust_assert (item_type->get_kind () == TyTy::TypeKind::ADT);
871 74 : TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (item_type);
872 :
873 : // this is a single generic item lets assert that
874 74 : rust_assert (adt->get_num_substitutions () == 1);
875 :
876 : // resolve the range expressions and these types must unify then we use that
877 : // type to substitute into the ADT
878 74 : TyTy::BaseType *from_ty = TypeCheckExpr::Resolve (expr.get_from_expr ());
879 74 : TyTy::BaseType *to_ty = TypeCheckExpr::Resolve (expr.get_to_expr ());
880 :
881 148 : TyTy::BaseType *unified = unify_site (
882 74 : expr.get_mappings ().get_hirid (),
883 74 : TyTy::TyWithLocation (from_ty, expr.get_from_expr ().get_locus ()),
884 74 : TyTy::TyWithLocation (to_ty, expr.get_to_expr ().get_locus ()),
885 74 : expr.get_locus ());
886 :
887 : // substitute it in
888 74 : std::vector<TyTy::SubstitutionArg> subst_mappings;
889 74 : const TyTy::SubstitutionParamMapping *param_ref = &adt->get_substs ().at (0);
890 74 : subst_mappings.emplace_back (param_ref, unified);
891 :
892 74 : TyTy::SubstitutionArgumentMappings subst (
893 74 : subst_mappings, {}, adt->get_substitution_arguments ().get_regions (),
894 74 : expr.get_locus ());
895 74 : infered = SubstMapperInternal::Resolve (adt, subst);
896 74 : }
897 :
898 : void
899 7 : TypeCheckExpr::visit (HIR::RangeFromExpr &expr)
900 : {
901 7 : auto lang_item_type = LangItem::Kind::RANGE_FROM;
902 :
903 7 : auto lang_item_defined = mappings.lookup_lang_item (lang_item_type);
904 : // we need to have it maybe
905 7 : if (!lang_item_defined)
906 : {
907 0 : rust_internal_error_at (expr.get_locus (),
908 : "unable to find relevant lang item: %s",
909 0 : LangItem::ToString (lang_item_type).c_str ());
910 : return;
911 : }
912 7 : DefId &respective_lang_item_id = lang_item_defined.value ();
913 :
914 : // look it up and it _must_ be a struct definition
915 7 : HIR::Item *item = mappings.lookup_defid (respective_lang_item_id).value ();
916 :
917 7 : TyTy::BaseType *item_type = TypeCheckItem::Resolve (*item);
918 7 : rust_assert (item_type->get_kind () == TyTy::TypeKind::ADT);
919 7 : TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (item_type);
920 :
921 : // this is a single generic item lets assert that
922 7 : rust_assert (adt->get_num_substitutions () == 1);
923 :
924 : // resolve the range expressions and these types must unify then we use that
925 : // type to substitute into the ADT
926 7 : TyTy::BaseType *from_ty = TypeCheckExpr::Resolve (expr.get_from_expr ());
927 :
928 : // substitute it in
929 7 : std::vector<TyTy::SubstitutionArg> subst_mappings;
930 7 : const TyTy::SubstitutionParamMapping *param_ref = &adt->get_substs ().at (0);
931 7 : subst_mappings.emplace_back (param_ref, from_ty);
932 :
933 7 : TyTy::SubstitutionArgumentMappings subst (
934 7 : subst_mappings, {}, adt->get_substitution_arguments ().get_regions (),
935 7 : expr.get_locus ());
936 7 : infered = SubstMapperInternal::Resolve (adt, subst);
937 7 : }
938 :
939 : void
940 7 : TypeCheckExpr::visit (HIR::RangeToExpr &expr)
941 : {
942 7 : auto lang_item_type = LangItem::Kind::RANGE_TO;
943 :
944 7 : auto lang_item_defined = mappings.lookup_lang_item (lang_item_type);
945 : // we need to have it maybe
946 7 : if (!lang_item_defined)
947 : {
948 0 : rust_internal_error_at (expr.get_locus (),
949 : "unable to find relevant lang item: %s",
950 0 : LangItem::ToString (lang_item_type).c_str ());
951 : return;
952 : }
953 :
954 7 : DefId &respective_lang_item_id = lang_item_defined.value ();
955 : // look it up and it _must_ be a struct definition
956 7 : HIR::Item *item = mappings.lookup_defid (respective_lang_item_id).value ();
957 :
958 7 : TyTy::BaseType *item_type = TypeCheckItem::Resolve (*item);
959 7 : rust_assert (item_type->get_kind () == TyTy::TypeKind::ADT);
960 7 : TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (item_type);
961 :
962 : // this is a single generic item lets assert that
963 7 : rust_assert (adt->get_num_substitutions () == 1);
964 :
965 : // resolve the range expressions and these types must unify then we use that
966 : // type to substitute into the ADT
967 7 : TyTy::BaseType *from_ty = TypeCheckExpr::Resolve (expr.get_to_expr ());
968 :
969 : // substitute it in
970 7 : std::vector<TyTy::SubstitutionArg> subst_mappings;
971 7 : const TyTy::SubstitutionParamMapping *param_ref = &adt->get_substs ().at (0);
972 7 : subst_mappings.emplace_back (param_ref, from_ty);
973 :
974 7 : TyTy::SubstitutionArgumentMappings subst (
975 7 : subst_mappings, {}, adt->get_substitution_arguments ().get_regions (),
976 7 : expr.get_locus ());
977 7 : infered = SubstMapperInternal::Resolve (adt, subst);
978 7 : }
979 :
980 : void
981 34 : typecheck_inline_asm_operand (HIR::InlineAsm &expr)
982 : {
983 34 : const auto &operands = expr.get_operands ();
984 34 : using RegisterType = AST::InlineAsmOperand::RegisterType;
985 77 : for (auto &operand : operands)
986 : {
987 43 : switch (operand.get_register_type ())
988 : {
989 17 : case RegisterType::In:
990 17 : {
991 17 : auto in = operand.get_in ();
992 17 : TypeCheckExpr::Resolve (*in.expr);
993 17 : break;
994 17 : }
995 24 : case RegisterType::Out:
996 24 : {
997 24 : auto out = operand.get_out ();
998 24 : TypeCheckExpr::Resolve (*out.expr);
999 24 : break;
1000 24 : }
1001 0 : case RegisterType::InOut:
1002 0 : {
1003 0 : auto in_out = operand.get_in_out ();
1004 0 : TypeCheckExpr::Resolve (*in_out.expr);
1005 0 : break;
1006 0 : }
1007 2 : case RegisterType::SplitInOut:
1008 2 : {
1009 2 : auto split_in_out = operand.get_split_in_out ();
1010 2 : TypeCheckExpr::Resolve (*split_in_out.in_expr);
1011 2 : TypeCheckExpr::Resolve (*split_in_out.out_expr);
1012 2 : break;
1013 2 : }
1014 0 : case RegisterType::Const:
1015 0 : {
1016 0 : auto anon_const = operand.get_const ().anon_const;
1017 0 : TypeCheckExpr::Resolve (anon_const.get_inner_expr ());
1018 0 : break;
1019 0 : }
1020 0 : case RegisterType::Sym:
1021 0 : {
1022 0 : auto sym = operand.get_sym ();
1023 0 : TypeCheckExpr::Resolve (*sym.expr);
1024 0 : break;
1025 0 : }
1026 0 : case RegisterType::Label:
1027 0 : {
1028 0 : auto label = operand.get_label ();
1029 0 : TypeCheckExpr::Resolve (*label.expr);
1030 0 : break;
1031 0 : }
1032 : }
1033 : }
1034 34 : }
1035 : void
1036 34 : TypeCheckExpr::visit (HIR::InlineAsm &expr)
1037 : {
1038 34 : typecheck_inline_asm_operand (expr);
1039 :
1040 : // NOTE: Hoise out if we have noreturn as an option
1041 : // to return a never type
1042 : // TODO : new keyword for memory seems sooooo shaky
1043 34 : if (expr.options.count (AST::InlineAsm::Option::NORETURN) == 1)
1044 1 : infered = new TyTy::NeverType (expr.get_mappings ().get_hirid ());
1045 : else
1046 33 : infered = TyTy::TupleType::get_unit_type ();
1047 34 : }
1048 :
1049 : void
1050 2 : TypeCheckExpr::visit (HIR::LlvmInlineAsm &expr)
1051 : {
1052 : // TODO: verify input/output types?
1053 :
1054 4 : for (auto &i : expr.inputs)
1055 2 : TypeCheckExpr::Resolve (*i.expr);
1056 :
1057 2 : for (auto &o : expr.outputs)
1058 0 : TypeCheckExpr::Resolve (*o.expr);
1059 :
1060 : // always unit type
1061 2 : infered = TyTy::TupleType::get_unit_type ();
1062 2 : }
1063 :
1064 : void
1065 15 : TypeCheckExpr::visit (HIR::OffsetOf &expr)
1066 : {
1067 15 : TypeCheckType::Resolve (expr.get_type ());
1068 :
1069 : // FIXME: Does offset_of always return a usize?
1070 15 : TyTy::BaseType *size_ty;
1071 15 : bool ok = context->lookup_builtin ("usize", &size_ty);
1072 15 : rust_assert (ok);
1073 :
1074 15 : infered = size_ty;
1075 15 : }
1076 :
1077 : void
1078 0 : TypeCheckExpr::visit (HIR::RangeFullExpr &expr)
1079 : {
1080 0 : auto lang_item_type = LangItem::Kind::RANGE_FULL;
1081 :
1082 0 : auto lang_item_defined = mappings.lookup_lang_item (lang_item_type);
1083 : // we need to have it maybe
1084 0 : if (!lang_item_defined)
1085 : {
1086 0 : rust_internal_error_at (expr.get_locus (),
1087 : "unable to find relevant lang item: %s",
1088 0 : LangItem::ToString (lang_item_type).c_str ());
1089 : return;
1090 : }
1091 0 : DefId &respective_lang_item_id = lang_item_defined.value ();
1092 :
1093 : // look it up and it _must_ be a struct definition
1094 0 : HIR::Item *item = mappings.lookup_defid (respective_lang_item_id).value ();
1095 :
1096 0 : TyTy::BaseType *item_type = TypeCheckItem::Resolve (*item);
1097 0 : rust_assert (item_type->is_unit ());
1098 :
1099 0 : infered = item_type;
1100 : }
1101 :
1102 : void
1103 311 : TypeCheckExpr::visit (HIR::ArrayIndexExpr &expr)
1104 : {
1105 311 : auto array_expr_ty = TypeCheckExpr::Resolve (expr.get_array_expr ());
1106 311 : if (array_expr_ty->get_kind () == TyTy::TypeKind::ERROR)
1107 309 : return;
1108 :
1109 311 : auto index_expr_ty = TypeCheckExpr::Resolve (expr.get_index_expr ());
1110 311 : if (index_expr_ty->get_kind () == TyTy::TypeKind::ERROR)
1111 : return;
1112 :
1113 : // first attempt to use direct array index logic
1114 311 : auto direct_array_expr_ty = array_expr_ty;
1115 311 : if (direct_array_expr_ty->get_kind () == TyTy::TypeKind::REF)
1116 : {
1117 : // lets try and deref it since rust allows this
1118 29 : auto ref = static_cast<TyTy::ReferenceType *> (direct_array_expr_ty);
1119 29 : auto base = ref->get_base ();
1120 29 : if (base->get_kind () == TyTy::TypeKind::ARRAY
1121 29 : || base->get_kind () == TyTy::TypeKind::SLICE)
1122 : direct_array_expr_ty = base;
1123 : }
1124 : // Box<T> autoderef
1125 282 : else if (auto base = TyTy::try_get_box_inner_type (direct_array_expr_ty))
1126 : {
1127 6 : direct_array_expr_ty = *base;
1128 : }
1129 :
1130 311 : TyTy::BaseType *size_ty;
1131 311 : bool ok = context->lookup_builtin ("usize", &size_ty);
1132 311 : rust_assert (ok);
1133 :
1134 311 : bool maybe_simple_array_access
1135 311 : = types_compatable (TyTy::TyWithLocation (index_expr_ty),
1136 311 : TyTy::TyWithLocation (size_ty), expr.get_locus (),
1137 : false);
1138 :
1139 311 : auto base_kind = direct_array_expr_ty->get_kind ();
1140 311 : if (maybe_simple_array_access
1141 275 : && (base_kind == TyTy::TypeKind::ARRAY
1142 275 : || base_kind == TyTy::TypeKind::SLICE))
1143 : {
1144 520 : unify_site (expr.get_index_expr ().get_mappings ().get_hirid (),
1145 260 : TyTy::TyWithLocation (size_ty),
1146 : TyTy::TyWithLocation (index_expr_ty,
1147 260 : expr.get_index_expr ().get_locus ()),
1148 : expr.get_locus ());
1149 :
1150 260 : if (base_kind == TyTy::TypeKind::ARRAY)
1151 : {
1152 229 : TyTy::ArrayType *array_type
1153 : = static_cast<TyTy::ArrayType *> (direct_array_expr_ty);
1154 229 : infered = array_type->get_element_type ()->clone ();
1155 : }
1156 : else
1157 : {
1158 : // is slice type instead
1159 31 : rust_assert (base_kind == TyTy::TypeKind::SLICE);
1160 31 : TyTy::SliceType *slice_type
1161 : = static_cast<TyTy::SliceType *> (direct_array_expr_ty);
1162 31 : infered = slice_type->get_element_type ()->clone ();
1163 : }
1164 :
1165 260 : return;
1166 : }
1167 :
1168 : // is this a case of core::ops::index?
1169 51 : auto lang_item_type = LangItem::Kind::INDEX;
1170 51 : bool operator_overloaded
1171 51 : = resolve_operator_overload (lang_item_type, expr, array_expr_ty,
1172 : index_expr_ty);
1173 51 : if (operator_overloaded)
1174 : {
1175 : // index and index mut always return a reference to the element
1176 49 : TyTy::BaseType *resolved = infered;
1177 49 : rust_assert (resolved->get_kind () == TyTy::TypeKind::REF);
1178 49 : TyTy::ReferenceType *ref = static_cast<TyTy::ReferenceType *> (resolved);
1179 :
1180 49 : infered = ref->get_base ()->clone ();
1181 49 : return;
1182 : }
1183 :
1184 : // error[E0277]: the type `[{integer}]` cannot be indexed by `u32`
1185 2 : rich_location r (line_table, expr.get_locus ());
1186 2 : r.add_range (expr.get_array_expr ().get_locus ());
1187 2 : r.add_range (expr.get_index_expr ().get_locus ());
1188 2 : rust_error_at (r, ErrorCode::E0277, "the type %qs cannot be indexed by %qs",
1189 4 : array_expr_ty->get_name ().c_str (),
1190 2 : index_expr_ty->get_name ().c_str ());
1191 2 : }
1192 :
1193 : void
1194 455 : TypeCheckExpr::visit (HIR::ArrayExpr &expr)
1195 : {
1196 455 : auto &elements = expr.get_internal_elements ();
1197 :
1198 455 : TyTy::BaseType *expected_ty = nullptr;
1199 455 : bool ok = context->lookup_builtin ("usize", &expected_ty);
1200 455 : rust_assert (ok);
1201 :
1202 455 : HIR::Expr *capacity_expr = nullptr;
1203 455 : TyTy::BaseType *element_type = nullptr;
1204 455 : TyTy::BaseType *capacity_type = nullptr;
1205 :
1206 455 : switch (elements.get_array_expr_type ())
1207 : {
1208 136 : case HIR::ArrayElems::ArrayExprType::COPIED:
1209 136 : {
1210 136 : HIR::ArrayElemsCopied &elems
1211 : = static_cast<HIR::ArrayElemsCopied &> (elements);
1212 136 : context->push_const_context ();
1213 136 : element_type = TypeCheckExpr::Resolve (elems.get_elem_to_copy ());
1214 136 : context->pop_const_context ();
1215 :
1216 136 : auto capacity_expr_ty
1217 136 : = TypeCheckExpr::Resolve (elems.get_num_copies_expr ());
1218 136 : if (capacity_expr_ty->is<TyTy::ErrorType> ())
1219 11 : return;
1220 :
1221 130 : context->insert_type (elems.get_num_copies_expr ().get_mappings (),
1222 : expected_ty);
1223 :
1224 260 : auto result = unify_site (
1225 130 : expr.get_mappings ().get_hirid (), TyTy::TyWithLocation (expected_ty),
1226 : TyTy::TyWithLocation (capacity_expr_ty,
1227 130 : elems.get_num_copies_expr ().get_locus ()),
1228 : expr.get_locus ());
1229 130 : if (result->is<TyTy::ErrorType> ())
1230 : return;
1231 :
1232 126 : capacity_expr = &elems.get_num_copies_expr ();
1233 126 : capacity_type = expected_ty;
1234 : }
1235 126 : break;
1236 :
1237 319 : case HIR::ArrayElems::ArrayExprType::VALUES:
1238 319 : {
1239 319 : HIR::ArrayElemsValues &elems
1240 : = static_cast<HIR::ArrayElemsValues &> (elements);
1241 319 : context->push_const_context ();
1242 319 : std::vector<TyTy::BaseType *> types;
1243 1862 : for (auto &elem : elems.get_values ())
1244 : {
1245 1543 : auto elem_ty = TypeCheckExpr::Resolve (*elem);
1246 1543 : types.push_back (elem_ty);
1247 : }
1248 319 : context->pop_const_context ();
1249 :
1250 : // this is a LUB
1251 319 : element_type
1252 319 : = TyTy::TyVar::get_implicit_infer_var (expr.get_locus ()).get_tyty ();
1253 1860 : for (auto &type : types)
1254 : {
1255 1542 : if (type->is<TyTy::ErrorType> ())
1256 1 : return;
1257 :
1258 1541 : element_type
1259 1541 : = unify_site (expr.get_mappings ().get_hirid (),
1260 1541 : TyTy::TyWithLocation (element_type),
1261 1541 : TyTy::TyWithLocation (type, type->get_locus ()),
1262 : expr.get_locus ());
1263 : }
1264 :
1265 : // a failed unify leaves the shared error node here, whose ref
1266 : // isn't in the context
1267 318 : if (element_type->is<TyTy::ErrorType> ())
1268 : return;
1269 :
1270 318 : auto crate_num = mappings.crate.get_current_crate ();
1271 318 : Analysis::NodeMapping mapping (crate_num, UNKNOWN_NODEID,
1272 318 : mappings.get_next_hir_id (crate_num),
1273 318 : UNKNOWN_LOCAL_DEFID);
1274 318 : std::string capacity_str = std::to_string (elems.get_num_elements ());
1275 318 : capacity_expr = new HIR::LiteralExpr (mapping, capacity_str,
1276 : HIR::Literal::LitType::INT,
1277 : PrimitiveCoreType::CORETYPE_USIZE,
1278 954 : UNDEF_LOCATION, {});
1279 :
1280 : // mark the type for this implicit node
1281 318 : context->insert_type (mapping, expected_ty);
1282 318 : capacity_type = expected_ty;
1283 319 : }
1284 318 : break;
1285 : }
1286 :
1287 444 : rust_assert (capacity_expr);
1288 444 : rust_assert (capacity_type);
1289 444 : auto ctx = Compile::Context::get ();
1290 444 : tree capacity_value
1291 444 : = Compile::HIRCompileBase::query_compile_const_expr (ctx, capacity_type,
1292 : *capacity_expr);
1293 :
1294 : // Create ConstValueType with ref == ty_ref (both pointing to capacity_expr)
1295 : // ty_ref gets updated during substitution via set_ty_ref()
1296 444 : HirId capacity_expr_id = capacity_expr->get_mappings ().get_hirid ();
1297 444 : auto const_type
1298 : = new TyTy::ConstValueType (capacity_value, expected_ty, capacity_expr_id,
1299 444 : capacity_expr_id);
1300 :
1301 : // Insert the ConstValueType at its ref
1302 444 : context->insert_type (capacity_expr->get_mappings (),
1303 444 : const_type->as_base_type ());
1304 :
1305 444 : infered
1306 888 : = new TyTy::ArrayType (expr.get_mappings ().get_hirid (), expr.get_locus (),
1307 : TyTy::TyVar (
1308 444 : const_type->as_base_type ()->get_ty_ref ()),
1309 888 : TyTy::TyVar (element_type->get_ref ()));
1310 : }
1311 :
1312 : // empty struct
1313 : void
1314 81 : TypeCheckExpr::visit (HIR::StructExprStruct &struct_expr)
1315 : {
1316 81 : HIR::PathInExpression &path = struct_expr.get_struct_name ();
1317 :
1318 81 : TyTy::BaseType *struct_path_ty = TypeCheckExpr::Resolve (path);
1319 81 : if (struct_path_ty->get_kind () != TyTy::TypeKind::ADT)
1320 : {
1321 0 : rust_error_at (path.get_locus (), "expected an ADT type for constructor");
1322 1 : return;
1323 : }
1324 :
1325 81 : TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (struct_path_ty);
1326 81 : TyTy::VariantDef *variant;
1327 :
1328 : // unwrap and type check the variant if it's an enum
1329 81 : if (adt->is_enum ())
1330 : {
1331 3 : HirId variant_id;
1332 3 : bool ok = context->lookup_variant_definition (
1333 3 : struct_expr.get_struct_name ().get_mappings ().get_hirid (),
1334 : &variant_id);
1335 3 : if (!ok)
1336 : {
1337 0 : rich_location r (line_table, struct_expr.get_locus ());
1338 0 : r.add_range (struct_expr.get_struct_name ().get_locus ());
1339 0 : rust_error_at (
1340 0 : struct_expr.get_struct_name ().get_locus (), ErrorCode::E0574,
1341 : "expected a struct, variant or union type, found enum %qs",
1342 0 : adt->get_name ().c_str ());
1343 0 : return;
1344 0 : }
1345 :
1346 3 : ok = adt->lookup_variant_by_id (variant_id, &variant);
1347 3 : rust_assert (ok);
1348 : }
1349 : else
1350 : {
1351 78 : rust_assert (adt->number_of_variants () == 1);
1352 78 : variant = adt->get_variants ().at (0);
1353 : }
1354 :
1355 81 : if (!variant->get_fields ().empty ())
1356 : {
1357 1 : std::vector<std::string> field_names;
1358 4 : for (auto &field : variant->get_fields ())
1359 3 : field_names.push_back (field->get_name ());
1360 1 : Error missing_fields_error
1361 : = TypeCheckStructExpr::make_missing_field_error (
1362 1 : struct_expr.get_locus (), field_names, struct_path_ty->get_name ());
1363 : // We might want to return or handle these in the future emit for now.
1364 1 : missing_fields_error.emit ();
1365 1 : return;
1366 1 : }
1367 :
1368 80 : infered = struct_path_ty;
1369 : }
1370 :
1371 : void
1372 1480 : TypeCheckExpr::visit (HIR::StructExprStructFields &struct_expr)
1373 : {
1374 1480 : infered = TypeCheckStructExpr::Resolve (struct_expr);
1375 1480 : }
1376 :
1377 : void
1378 4673 : TypeCheckExpr::visit (HIR::GroupedExpr &expr)
1379 : {
1380 4673 : infered = TypeCheckExpr::Resolve (expr.get_expr_in_parens ());
1381 4644 : }
1382 :
1383 : void
1384 5157 : TypeCheckExpr::visit (HIR::FieldAccessExpr &expr)
1385 : {
1386 5157 : auto struct_base = TypeCheckExpr::Resolve (expr.get_receiver_expr ());
1387 :
1388 : // Box<T> autoderef
1389 5157 : if (auto try_struct_base = TyTy::try_get_box_inner_type (struct_base))
1390 : {
1391 3 : struct_base = *try_struct_base;
1392 : }
1393 :
1394 : // FIXME does this require autoderef here?
1395 5157 : if (struct_base->get_kind () == TyTy::TypeKind::REF)
1396 : {
1397 3525 : TyTy::ReferenceType *r = static_cast<TyTy::ReferenceType *> (struct_base);
1398 3525 : struct_base = r->get_base ();
1399 : }
1400 :
1401 5157 : bool is_valid_type = struct_base->get_kind () == TyTy::TypeKind::ADT;
1402 5157 : if (!is_valid_type)
1403 : {
1404 2 : rust_error_at (expr.get_locus (), "expected algebraic data type got %qs",
1405 2 : struct_base->get_name ().c_str ());
1406 6 : return;
1407 : }
1408 :
1409 5155 : TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (struct_base);
1410 5155 : rust_assert (adt->number_of_variants () > 0);
1411 5155 : TyTy::VariantDef *vaiant = adt->get_variants ().at (0);
1412 :
1413 5155 : TyTy::StructFieldType *lookup = nullptr;
1414 5155 : bool found = vaiant->lookup_field (expr.get_field_name ().as_string (),
1415 : &lookup, nullptr);
1416 5155 : if (!found || adt->is_enum ())
1417 : {
1418 4 : rich_location r (line_table, expr.get_locus ());
1419 4 : r.add_range (expr.get_field_name ().get_locus ());
1420 4 : rust_error_at (r, ErrorCode::E0609, "no field %qs on type %qs",
1421 8 : expr.get_field_name ().as_string ().c_str (),
1422 4 : adt->get_name ().c_str ());
1423 4 : return;
1424 4 : }
1425 :
1426 5151 : infered = lookup->get_field_type ();
1427 : }
1428 :
1429 : bool
1430 43 : is_default_fn (const MethodCandidate &candidate)
1431 : {
1432 43 : if (candidate.candidate.is_impl_candidate ())
1433 : {
1434 43 : auto *item = candidate.candidate.item.impl.impl_item;
1435 :
1436 43 : if (item->get_impl_item_type () == HIR::ImplItem::FUNCTION)
1437 : {
1438 43 : auto &fn = static_cast<HIR::Function &> (*item);
1439 :
1440 43 : return fn.is_default ();
1441 : }
1442 : }
1443 :
1444 : return false;
1445 : }
1446 :
1447 : void
1448 2 : emit_ambiguous_resolution_error (HIR::MethodCallExpr &expr,
1449 : std::set<MethodCandidate> &candidates)
1450 : {
1451 2 : rich_location r (line_table, expr.get_method_name ().get_locus ());
1452 2 : std::string rich_msg = "multiple "
1453 6 : + expr.get_method_name ().get_segment ().to_string ()
1454 2 : + " found";
1455 :
1456 : // We have to filter out default candidates
1457 6 : for (auto &c : candidates)
1458 4 : if (!is_default_fn (c))
1459 4 : r.add_range (c.candidate.locus);
1460 :
1461 2 : r.add_fixit_replace (rich_msg.c_str ());
1462 :
1463 2 : rust_error_at (r, ErrorCode::E0592, "duplicate definitions with name %qs",
1464 6 : expr.get_method_name ().get_segment ().to_string ().c_str ());
1465 2 : }
1466 :
1467 : // We are allowed to have multiple candidates if they are all specializable
1468 : // functions or if all of them except one are specializable functions.
1469 : // In the later case, we just return a valid candidate without erroring out
1470 : // about ambiguity. If there are two or more specialized functions, then we
1471 : // error out.
1472 : //
1473 : // FIXME: The first case is not handled at the moment, so we error out
1474 : tl::optional<const MethodCandidate &>
1475 16 : handle_multiple_candidates (HIR::MethodCallExpr &expr,
1476 : std::set<MethodCandidate> &candidates)
1477 : {
1478 16 : auto all_default = true;
1479 16 : tl::optional<const MethodCandidate &> found = tl::nullopt;
1480 :
1481 53 : for (auto &c : candidates)
1482 : {
1483 39 : if (!is_default_fn (c))
1484 : {
1485 18 : all_default = false;
1486 :
1487 : // We haven't found a final candidate yet, so we can select
1488 : // this one. However, if we already have a candidate, then
1489 : // that means there are multiple non-default candidates - we
1490 : // must error out
1491 18 : if (!found)
1492 : {
1493 : found = c;
1494 : }
1495 : else
1496 : {
1497 2 : emit_ambiguous_resolution_error (expr, candidates);
1498 2 : return tl::nullopt;
1499 : }
1500 : }
1501 : }
1502 :
1503 : // None of the candidates were a non-default (specialized) function, so we
1504 : // error out
1505 14 : if (all_default)
1506 : {
1507 0 : rust_sorry_at (expr.get_locus (),
1508 : "cannot resolve method calls to non-specialized methods "
1509 : "(all function candidates are %qs)",
1510 : "default");
1511 0 : return tl::nullopt;
1512 : }
1513 :
1514 14 : return found;
1515 : }
1516 :
1517 : void
1518 3512 : TypeCheckExpr::visit (HIR::MethodCallExpr &expr)
1519 : {
1520 3512 : auto receiver_tyty = TypeCheckExpr::Resolve (expr.get_receiver ());
1521 3512 : if (receiver_tyty->get_kind () == TyTy::TypeKind::ERROR)
1522 : {
1523 1 : rust_error_at (expr.get_receiver ().get_locus (),
1524 : "failed to resolve receiver in MethodCallExpr");
1525 14 : return;
1526 : }
1527 :
1528 3511 : rust_debug_loc (expr.get_locus (), "attempting to resolve method for %s",
1529 : receiver_tyty->debug_str ().c_str ());
1530 3511 : auto candidates
1531 : = MethodResolver::Probe (receiver_tyty,
1532 3511 : expr.get_method_name ().get_segment ());
1533 3455 : if (candidates.empty ())
1534 : {
1535 9 : rich_location richloc (line_table, expr.get_method_name ().get_locus ());
1536 9 : richloc.add_fixit_replace ("method not found");
1537 9 : rust_error_at (
1538 : richloc, ErrorCode::E0599,
1539 : "no method named %qs found in the current scope",
1540 18 : expr.get_method_name ().get_segment ().to_string ().c_str ());
1541 9 : return;
1542 9 : }
1543 :
1544 3446 : tl::optional<const MethodCandidate &> candidate = *candidates.begin ();
1545 :
1546 3446 : if (candidates.size () > 1)
1547 16 : candidate = handle_multiple_candidates (expr, candidates);
1548 :
1549 3446 : if (!candidate)
1550 : return;
1551 :
1552 3444 : auto found_candidate = *candidate;
1553 :
1554 3444 : rust_debug_loc (expr.get_method_name ().get_locus (),
1555 : "resolved method to: {%u} {%s} with [%lu] adjustments",
1556 : found_candidate.candidate.ty->get_ref (),
1557 : found_candidate.candidate.ty->debug_str ().c_str (),
1558 : (unsigned long) found_candidate.adjustments.size ());
1559 :
1560 : // Get the adjusted self
1561 3444 : Adjuster adj (receiver_tyty);
1562 3444 : TyTy::BaseType *adjusted_self = adj.adjust_type (found_candidate.adjustments);
1563 3444 : rust_debug ("receiver: %s adjusted self %s",
1564 : receiver_tyty->debug_str ().c_str (),
1565 : adjusted_self->debug_str ().c_str ());
1566 :
1567 : // store the adjustments for code-generation to know what to do which must be
1568 : // stored onto the receiver to so as we don't trigger duplicate deref mappings
1569 : // ICE when an argument is a method call
1570 3444 : HirId autoderef_mappings_id
1571 3444 : = expr.get_receiver ().get_mappings ().get_hirid ();
1572 3444 : context->insert_autoderef_mappings (autoderef_mappings_id,
1573 : std::move (found_candidate.adjustments));
1574 :
1575 3444 : PathProbeCandidate &resolved_candidate = found_candidate.candidate;
1576 3444 : TyTy::BaseType *lookup_tyty = found_candidate.candidate.ty;
1577 3444 : NodeId resolved_node_id
1578 3444 : = resolved_candidate.is_impl_candidate ()
1579 3444 : ? resolved_candidate.item.impl.impl_item->get_impl_mappings ()
1580 2396 : .get_nodeid ()
1581 1048 : : resolved_candidate.item.trait.item_ref->get_mappings ().get_nodeid ();
1582 :
1583 3444 : if (lookup_tyty->get_kind () != TyTy::TypeKind::FNDEF)
1584 : {
1585 0 : rich_location r (line_table, expr.get_method_name ().get_locus ());
1586 0 : r.add_range (resolved_candidate.locus);
1587 0 : rust_error_at (r, "associated impl item is not a method");
1588 0 : return;
1589 0 : }
1590 :
1591 3444 : TyTy::BaseType *lookup = lookup_tyty;
1592 3444 : TyTy::FnType *fn = static_cast<TyTy::FnType *> (lookup);
1593 6888 : if (!fn->is_method ())
1594 : {
1595 0 : rich_location r (line_table, expr.get_method_name ().get_locus ());
1596 0 : r.add_range (resolved_candidate.locus);
1597 0 : rust_error_at (r, "associated function is not a method");
1598 0 : return;
1599 0 : }
1600 :
1601 3444 : rust_debug_loc (expr.get_locus (), "resolved method call to: {%u} {%s}",
1602 : found_candidate.candidate.ty->get_ref (),
1603 : found_candidate.candidate.ty->debug_str ().c_str ());
1604 :
1605 3444 : if (resolved_candidate.is_impl_candidate ())
1606 : {
1607 2396 : auto infer_arguments = TyTy::SubstitutionArgumentMappings::empty ();
1608 2396 : infer_arguments.get_mut_regions ()
1609 2396 : = fn->get_used_arguments ().get_regions ();
1610 2396 : HIR::ImplBlock &impl = *resolved_candidate.item.impl.parent;
1611 2396 : TyTy::BaseType *impl_self_infer
1612 2396 : = TypeCheckItem::ResolveImplBlockSelfWithInference (impl,
1613 : expr.get_locus (),
1614 : &infer_arguments);
1615 2396 : if (impl_self_infer->get_kind () == TyTy::TypeKind::ERROR)
1616 : {
1617 0 : rich_location r (line_table, expr.get_locus ());
1618 0 : r.add_range (impl.get_type ().get_locus ());
1619 0 : rust_error_at (
1620 : r, "failed to resolve impl type for method call resolution");
1621 0 : return;
1622 0 : }
1623 :
1624 2396 : if (!infer_arguments.is_empty ())
1625 602 : lookup = SubstMapperInternal::Resolve (lookup, infer_arguments);
1626 2396 : }
1627 :
1628 : // apply any remaining generic arguments
1629 3444 : if (expr.get_method_name ().has_generic_args ())
1630 : {
1631 29 : HIR::GenericArgs &args = expr.get_method_name ().get_generic_args ();
1632 29 : rust_debug_loc (args.get_locus (),
1633 : "applying generic arguments to method_call: {%s}",
1634 : lookup->debug_str ().c_str ());
1635 :
1636 29 : lookup
1637 29 : = SubstMapper::Resolve (lookup, expr.get_method_name ().get_locus (),
1638 : &args);
1639 29 : if (lookup->get_kind () == TyTy::TypeKind::ERROR)
1640 : return;
1641 : }
1642 3415 : else if (lookup->needs_generic_substitutions ())
1643 : {
1644 936 : rust_debug ("method needs inference: {%s}",
1645 : lookup->debug_str ().c_str ());
1646 936 : lookup = SubstMapper::InferSubst (lookup,
1647 936 : expr.get_method_name ().get_locus ());
1648 : }
1649 :
1650 3443 : rust_debug ("type-checking method_call: {%s}", lookup->debug_str ().c_str ());
1651 :
1652 3443 : TyTy::BaseType *function_ret_tyty
1653 3443 : = TyTy::TypeCheckMethodCallExpr::go (static_cast<TyTy::FnType *> (lookup),
1654 : expr, adjusted_self, context);
1655 3429 : if (function_ret_tyty == nullptr
1656 3429 : || function_ret_tyty->get_kind () == TyTy::TypeKind::ERROR)
1657 : {
1658 0 : rust_error_at (expr.get_locus (),
1659 : "failed to lookup type to MethodCallExpr");
1660 0 : return;
1661 : }
1662 :
1663 : // store the expected fntype
1664 3429 : context->insert_type (expr.get_method_name ().get_mappings (), lookup);
1665 :
1666 3429 : auto &nr_ctx = Resolver2_0::FinalizedNameResolutionContext::get ();
1667 :
1668 3429 : nr_ctx.map_usage (Resolver2_0::Usage (expr.get_mappings ().get_nodeid ()),
1669 3429 : Resolver2_0::Definition (resolved_node_id),
1670 : Resolver2_0::Namespace::Values);
1671 :
1672 : // return the result of the function back
1673 3429 : infered = function_ret_tyty;
1674 3442 : }
1675 :
1676 : void
1677 187 : TypeCheckExpr::visit (HIR::LoopExpr &expr)
1678 : {
1679 187 : context->push_new_loop_context (expr.get_mappings ().get_hirid (),
1680 : expr.get_locus ());
1681 187 : TyTy::BaseType *block_expr = TypeCheckExpr::Resolve (expr.get_loop_block ());
1682 187 : if (!block_expr->is_unit ())
1683 : {
1684 0 : rust_error_at (expr.get_loop_block ().get_locus (),
1685 : "expected %<()%> got %s",
1686 0 : block_expr->as_string ().c_str ());
1687 0 : return;
1688 : }
1689 :
1690 187 : TyTy::BaseType *loop_context_type = context->pop_loop_context ();
1691 :
1692 187 : bool loop_context_type_infered
1693 187 : = (loop_context_type->get_kind () != TyTy::TypeKind::INFER)
1694 187 : || ((loop_context_type->get_kind () == TyTy::TypeKind::INFER)
1695 177 : && (((TyTy::InferType *) loop_context_type)->get_infer_kind ()
1696 356 : != TyTy::InferType::GENERAL));
1697 :
1698 187 : infered = loop_context_type_infered ? loop_context_type
1699 169 : : TyTy::TupleType::get_unit_type ();
1700 : }
1701 :
1702 : void
1703 95 : TypeCheckExpr::visit (HIR::WhileLoopExpr &expr)
1704 : {
1705 95 : context->push_new_while_loop_context (expr.get_mappings ().get_hirid ());
1706 95 : TyTy::BaseType *predicate_type
1707 95 : = TypeCheckExpr::Resolve (expr.get_predicate_expr ());
1708 95 : if (predicate_type->get_kind () != TyTy::TypeKind::BOOL
1709 95 : && predicate_type->get_kind () != TyTy::TypeKind::NEVER)
1710 : {
1711 0 : rust_error_at (expr.get_predicate_expr ().get_locus (),
1712 : "expected boolean expression in %<while%> condition");
1713 0 : context->pop_loop_context ();
1714 0 : return;
1715 : }
1716 95 : TyTy::BaseType *block_expr = TypeCheckExpr::Resolve (expr.get_loop_block ());
1717 95 : if (!block_expr->is_unit ())
1718 : {
1719 0 : rust_error_at (expr.get_loop_block ().get_locus (),
1720 : "expected %<()%> got %s",
1721 0 : block_expr->as_string ().c_str ());
1722 0 : context->pop_loop_context ();
1723 0 : return;
1724 : }
1725 95 : context->pop_loop_context ();
1726 95 : infered = TyTy::TupleType::get_unit_type ();
1727 : }
1728 :
1729 : void
1730 155 : TypeCheckExpr::visit (HIR::BreakExpr &expr)
1731 : {
1732 155 : if (!context->have_loop_context ())
1733 : {
1734 2 : rust_error_at (expr.get_locus (), ErrorCode::E0268,
1735 : "%<break%> outside of a loop or labeled block");
1736 2 : return;
1737 : }
1738 :
1739 153 : if (expr.has_break_expr ())
1740 : {
1741 25 : TyTy::BaseType *break_expr_tyty
1742 25 : = TypeCheckExpr::Resolve (expr.get_expr ());
1743 :
1744 25 : TyTy::BaseType *loop_context = context->peek_loop_context ();
1745 25 : if (loop_context->get_kind () == TyTy::TypeKind::ERROR)
1746 : {
1747 4 : rust_error_at (
1748 : expr.get_locus (), ErrorCode::E0571,
1749 : "can only %<break%> with a value inside a %<loop%> block");
1750 4 : return;
1751 : }
1752 :
1753 21 : TyTy::BaseType *unified_ty
1754 42 : = unify_site (expr.get_mappings ().get_hirid (),
1755 21 : TyTy::TyWithLocation (loop_context),
1756 : TyTy::TyWithLocation (break_expr_tyty,
1757 21 : expr.get_expr ().get_locus ()),
1758 : expr.get_locus ());
1759 21 : context->swap_head_loop_context (unified_ty);
1760 : }
1761 :
1762 149 : infered = new TyTy::NeverType (expr.get_mappings ().get_hirid ());
1763 : }
1764 :
1765 : void
1766 28 : TypeCheckExpr::visit (HIR::ContinueExpr &expr)
1767 : {
1768 28 : if (!context->have_loop_context ())
1769 : {
1770 3 : rust_error_at (expr.get_locus (), ErrorCode::E0268,
1771 : "%<continue%> outside of a loop");
1772 3 : return;
1773 : }
1774 25 : infered = new TyTy::NeverType (expr.get_mappings ().get_hirid ());
1775 : }
1776 :
1777 : void
1778 2709 : TypeCheckExpr::visit (HIR::BorrowExpr &expr)
1779 : {
1780 2709 : TyTy::BaseType *resolved_base = TypeCheckExpr::Resolve (expr.get_expr ());
1781 2709 : if (resolved_base->is<TyTy::ErrorType> ())
1782 : return;
1783 :
1784 : // In Rust this is valid because of DST's
1785 : //
1786 : // fn test() {
1787 : // let a:&str = "TEST 1";
1788 : // let b:&str = &"TEST 2";
1789 : // }
1790 2707 : if (resolved_base->get_kind () == TyTy::TypeKind::REF)
1791 : {
1792 44 : const TyTy::ReferenceType *ref
1793 : = static_cast<const TyTy::ReferenceType *> (resolved_base);
1794 :
1795 : // this might end up being a more generic is_dyn object check but lets
1796 : // double check dyn traits type-layout first
1797 44 : if (ref->is_dyn_str_type ())
1798 : {
1799 9 : infered = resolved_base;
1800 9 : return;
1801 : }
1802 : }
1803 :
1804 2698 : if (expr.is_raw_borrow ())
1805 : {
1806 4 : infered = new TyTy::PointerType (expr.get_mappings ().get_hirid (),
1807 4 : TyTy::TyVar (resolved_base->get_ref ()),
1808 8 : expr.get_mut ());
1809 :
1810 4 : return;
1811 : }
1812 :
1813 2694 : infered = new TyTy::ReferenceType (expr.get_mappings ().get_hirid (),
1814 2694 : TyTy::TyVar (resolved_base->get_ref ()),
1815 5388 : expr.get_mut ());
1816 : }
1817 :
1818 : void
1819 5157 : TypeCheckExpr::visit (HIR::DereferenceExpr &expr)
1820 : {
1821 5157 : TyTy::BaseType *resolved_base = TypeCheckExpr::Resolve (expr.get_expr ());
1822 :
1823 5157 : rust_debug_loc (expr.get_locus (), "attempting deref operator overload");
1824 5157 : auto lang_item_type = LangItem::Kind::DEREF;
1825 5157 : bool operator_overloaded
1826 5157 : = resolve_operator_overload (lang_item_type, expr, resolved_base, nullptr);
1827 5157 : if (operator_overloaded)
1828 : {
1829 : // operator overloaded deref always refurns a reference type lets assert
1830 : // this
1831 50 : rust_assert (infered->get_kind () == TyTy::TypeKind::REF);
1832 50 : resolved_base = infered;
1833 : }
1834 :
1835 5157 : bool is_valid_type = resolved_base->get_kind () == TyTy::TypeKind::REF
1836 5157 : || resolved_base->get_kind () == TyTy::TypeKind::POINTER;
1837 :
1838 5157 : auto try_owned_box = TyTy::try_get_box_inner_type (resolved_base);
1839 :
1840 5157 : if (!is_valid_type && !try_owned_box)
1841 : {
1842 0 : rust_error_at (expr.get_locus (), "expected reference type got %s",
1843 0 : resolved_base->as_string ().c_str ());
1844 0 : return;
1845 : }
1846 :
1847 5157 : if (try_owned_box)
1848 : {
1849 1 : infered = (*try_owned_box)->clone ();
1850 : }
1851 5156 : else if (resolved_base->get_kind () == TyTy::TypeKind::REF)
1852 : {
1853 4961 : TyTy::ReferenceType *ref_base
1854 : = static_cast<TyTy::ReferenceType *> (resolved_base);
1855 4961 : infered = ref_base->get_base ()->clone ();
1856 : }
1857 : else
1858 : {
1859 195 : TyTy::PointerType *ref_base
1860 : = static_cast<TyTy::PointerType *> (resolved_base);
1861 195 : infered = ref_base->get_base ()->clone ();
1862 : }
1863 : }
1864 :
1865 : void
1866 6372 : TypeCheckExpr::visit (HIR::TypeCastExpr &expr)
1867 : {
1868 6372 : TyTy::BaseType *expr_to_convert
1869 6372 : = TypeCheckExpr::Resolve (expr.get_casted_expr ());
1870 6351 : TyTy::BaseType *tyty_to_convert_to
1871 6351 : = TypeCheckType::Resolve (expr.get_type_to_convert_to ());
1872 :
1873 6351 : TyTy::TyWithLocation from (expr_to_convert,
1874 6351 : expr.get_casted_expr ().get_locus ());
1875 6351 : TyTy::TyWithLocation to (tyty_to_convert_to,
1876 6351 : expr.get_type_to_convert_to ().get_locus ());
1877 6351 : infered = cast_site (expr.get_mappings ().get_hirid (), from, to,
1878 : expr.get_locus ());
1879 6351 : }
1880 :
1881 : void
1882 1237 : TypeCheckExpr::visit (HIR::MatchExpr &expr)
1883 : {
1884 : // this needs to perform a least upper bound coercion on the blocks and then
1885 : // unify the scruintee and arms
1886 1237 : TyTy::BaseType *scrutinee_tyty
1887 1237 : = TypeCheckExpr::Resolve (expr.get_scrutinee_expr ());
1888 :
1889 : // https://github.com/Rust-GCC/gccrs/issues/3231#issuecomment-2462660048
1890 : // https://github.com/rust-lang/rust/blob/3d1dba830a564d1118361345d7ada47a05241f45/compiler/rustc_hir_typeck/src/_match.rs#L32-L36
1891 1237 : if (!expr.has_match_arms ())
1892 : {
1893 : // this is a special case where rustc returns !
1894 5 : TyTy::BaseType *lookup = nullptr;
1895 5 : bool ok = context->lookup_builtin ("!", &lookup);
1896 5 : rust_assert (ok);
1897 5 : infered = lookup->clone ();
1898 5 : return;
1899 : }
1900 :
1901 1232 : bool saw_error = false;
1902 1232 : std::vector<TyTy::BaseType *> kase_block_tys;
1903 4097 : for (auto &kase : expr.get_match_cases ())
1904 : {
1905 : // lets check the arms
1906 2865 : HIR::MatchArm &kase_arm = kase.get_arm ();
1907 2865 : auto &pattern = kase_arm.get_pattern ();
1908 2865 : TyTy::BaseType *kase_arm_ty
1909 2865 : = TypeCheckPattern::Resolve (*pattern, scrutinee_tyty);
1910 2865 : if (kase_arm_ty->get_kind () == TyTy ::TypeKind::ERROR)
1911 : {
1912 11 : saw_error = true;
1913 13 : continue;
1914 : }
1915 :
1916 5708 : TyTy::BaseType *checked_kase = unify_site (
1917 2854 : expr.get_mappings ().get_hirid (),
1918 : TyTy::TyWithLocation (scrutinee_tyty,
1919 2854 : expr.get_scrutinee_expr ().get_locus ()),
1920 2854 : TyTy::TyWithLocation (kase_arm_ty, pattern->get_locus ()),
1921 : expr.get_locus ());
1922 2854 : if (checked_kase->get_kind () == TyTy::TypeKind::ERROR)
1923 : {
1924 2 : saw_error = true;
1925 2 : continue;
1926 : }
1927 :
1928 : // the guard is a bool condition evaluated with the bindings of the
1929 : // pattern in scope
1930 2852 : if (kase_arm.has_match_arm_guard ())
1931 : {
1932 62 : TyTy::BaseType *bool_ty = nullptr;
1933 62 : bool ok = context->lookup_builtin ("bool", &bool_ty);
1934 62 : rust_assert (ok);
1935 :
1936 62 : HIR::Expr &guard = kase_arm.get_guard_expr ();
1937 62 : TyTy::BaseType *guard_ty = TypeCheckExpr::Resolve (guard);
1938 62 : unify_site (guard.get_mappings ().get_hirid (),
1939 62 : TyTy::TyWithLocation (bool_ty),
1940 62 : TyTy::TyWithLocation (guard_ty, guard.get_locus ()),
1941 62 : guard.get_locus ());
1942 : }
1943 :
1944 : // check the kase type
1945 2852 : TyTy::BaseType *kase_block_ty = TypeCheckExpr::Resolve (kase.get_expr ());
1946 2852 : kase_block_tys.push_back (kase_block_ty);
1947 : }
1948 1232 : if (saw_error)
1949 : return;
1950 :
1951 1225 : if (kase_block_tys.size () == 0)
1952 : {
1953 0 : infered = TyTy::TupleType::get_unit_type ();
1954 0 : return;
1955 : }
1956 :
1957 : // this is a LUB
1958 1225 : infered = kase_block_tys.at (0);
1959 2844 : for (size_t i = 1; i < kase_block_tys.size (); i++)
1960 : {
1961 1619 : TyTy::BaseType *kase_ty = kase_block_tys.at (i);
1962 1619 : infered
1963 1619 : = coercion_site (expr.get_mappings ().get_hirid (),
1964 1619 : TyTy::TyWithLocation (infered),
1965 1619 : TyTy::TyWithLocation (kase_ty), expr.get_locus ());
1966 : }
1967 1232 : }
1968 :
1969 : void
1970 66 : TypeCheckExpr::visit (HIR::ClosureExpr &expr)
1971 : {
1972 66 : std::vector<TyTy::SubstitutionParamMapping> subst_refs;
1973 66 : HirId ref = expr.get_mappings ().get_hirid ();
1974 66 : DefId id = expr.get_mappings ().get_defid ();
1975 66 : RustIdent ident{CanonicalPath::create_empty (), expr.get_locus ()};
1976 :
1977 66 : if (context->have_function_context ())
1978 : {
1979 64 : TypeCheckContextItem current_context = context->peek_context ();
1980 64 : TyTy::FnType *current_context_fndecl
1981 64 : = current_context.get_context_type ();
1982 :
1983 64 : ident = RustIdent{current_context_fndecl->get_ident ().path,
1984 64 : expr.get_locus ()};
1985 :
1986 64 : subst_refs = current_context_fndecl->clone_substs ();
1987 : }
1988 :
1989 66 : std::vector<TyTy::TyVar> parameter_types;
1990 126 : for (auto &p : expr.get_params ())
1991 : {
1992 60 : TyTy::BaseType *param_tyty = nullptr;
1993 60 : if (p.has_type_given ())
1994 : {
1995 58 : param_tyty = TypeCheckType::Resolve (p.get_type ());
1996 : }
1997 : else
1998 : {
1999 2 : param_tyty = ClosureParamInfer::Resolve (p.get_pattern ());
2000 : }
2001 :
2002 60 : TyTy::TyVar param_ty (param_tyty->get_ref ());
2003 60 : parameter_types.push_back (param_ty);
2004 :
2005 60 : TypeCheckPattern::Resolve (p.get_pattern (), param_ty.get_tyty ());
2006 : }
2007 :
2008 : // we generate an implicit hirid for the closure args
2009 66 : HirId implicit_args_id = mappings.get_next_hir_id ();
2010 66 : TyTy::TupleType *closure_args
2011 : = new TyTy::TupleType (implicit_args_id, expr.get_locus (),
2012 66 : parameter_types);
2013 66 : context->insert_implicit_type (closure_args->get_ref (), closure_args);
2014 :
2015 66 : location_t result_type_locus = expr.has_return_type ()
2016 66 : ? expr.get_return_type ().get_locus ()
2017 66 : : expr.get_locus ();
2018 66 : TyTy::TyVar result_type
2019 66 : = expr.has_return_type ()
2020 66 : ? TyTy::TyVar (
2021 : TypeCheckType::Resolve (expr.get_return_type ())->get_ref ())
2022 66 : : TyTy::TyVar::get_implicit_infer_var (expr.get_locus ());
2023 :
2024 : // resolve the block
2025 66 : location_t closure_expr_locus = expr.get_expr ().get_locus ();
2026 66 : TyTy::BaseType *closure_expr_ty = TypeCheckExpr::Resolve (expr.get_expr ());
2027 132 : coercion_site (expr.get_mappings ().get_hirid (),
2028 : TyTy::TyWithLocation (result_type.get_tyty (),
2029 66 : result_type_locus),
2030 66 : TyTy::TyWithLocation (closure_expr_ty, closure_expr_locus),
2031 : expr.get_locus ());
2032 :
2033 : // generate the closure type
2034 66 : NodeId closure_node_id = expr.get_mappings ().get_nodeid ();
2035 :
2036 : // Resolve closure captures
2037 :
2038 66 : std::set<NodeId> captures;
2039 :
2040 66 : if (auto opt_cap
2041 66 : = Analysis::Mappings::get ().lookup_captures (closure_node_id))
2042 42 : for (auto cap : opt_cap.value ())
2043 21 : captures.insert (cap);
2044 :
2045 66 : infered = new TyTy::ClosureType (ref, id, ident, closure_args, result_type,
2046 132 : subst_refs, captures);
2047 :
2048 : // FIXME
2049 : // all closures automatically inherit the appropriate fn trait. Lets just
2050 : // assume FnOnce for now. I think this is based on the return type of the
2051 : // closure
2052 :
2053 66 : LangItem::Kind lang_item_type = LangItem::Kind::FN_ONCE;
2054 :
2055 66 : DefId respective_lang_item_id
2056 66 : = mappings.get_lang_item (lang_item_type, expr.get_locus ());
2057 :
2058 : // these lang items are always traits
2059 65 : HIR::Item *item = mappings.lookup_defid (respective_lang_item_id).value ();
2060 65 : rust_assert (item->get_item_kind () == HIR::Item::ItemKind::Trait);
2061 65 : HIR::Trait *trait_item = static_cast<HIR::Trait *> (item);
2062 :
2063 65 : TraitReference *trait = TraitResolver::Resolve (*trait_item);
2064 65 : rust_assert (!trait->is_error ());
2065 :
2066 65 : TyTy::TypeBoundPredicate predicate (*trait, BoundPolarity::RegularBound,
2067 65 : expr.get_locus ());
2068 :
2069 : // resolve the trait bound where the <(Args)> are the parameter tuple type
2070 65 : HIR::GenericArgs args = HIR::GenericArgs::create_empty (expr.get_locus ());
2071 :
2072 : // lets generate an implicit Type so that it resolves to the implict tuple
2073 : // type we have created
2074 65 : auto crate_num = mappings.crate.get_current_crate ();
2075 65 : Analysis::NodeMapping mapping (crate_num, expr.get_mappings ().get_nodeid (),
2076 65 : implicit_args_id, UNKNOWN_LOCAL_DEFID);
2077 65 : HIR::TupleType *implicit_tuple
2078 : = new HIR::TupleType (mapping,
2079 : {} // we dont need to fill this out because it will
2080 : // auto resolve because the hir id's match
2081 : ,
2082 65 : expr.get_locus ());
2083 65 : args.get_type_args ().emplace_back (implicit_tuple);
2084 :
2085 : // apply the arguments
2086 65 : predicate.apply_generic_arguments (&args, false, false);
2087 :
2088 : // finally inherit the trait bound
2089 65 : infered->inherit_bound (predicate);
2090 65 : }
2091 :
2092 : bool
2093 21219 : TypeCheckExpr::resolve_operator_overload (
2094 : LangItem::Kind lang_item_type, HIR::OperatorExprMeta expr,
2095 : TyTy::BaseType *lhs, TyTy::BaseType *rhs,
2096 : HIR::PathIdentSegment specified_segment, bool allow_defer,
2097 : TyTy::BaseType *result_type, TyTy::BaseType *probe_lhs)
2098 : {
2099 : // look up lang item for arithmetic type
2100 21219 : std::string associated_item_name = LangItem::ToString (lang_item_type);
2101 :
2102 21219 : auto lang_item_defined = mappings.lookup_lang_item (lang_item_type);
2103 : // probe for the lang-item
2104 21219 : if (!lang_item_defined)
2105 : return false;
2106 :
2107 8436 : DefId &respective_lang_item_id = lang_item_defined.value ();
2108 8436 : auto def_lookup = mappings.lookup_defid (respective_lang_item_id);
2109 8436 : rust_assert (def_lookup.has_value ());
2110 :
2111 8436 : HIR::Item *def_item = def_lookup.value ();
2112 8436 : rust_assert (def_item->get_item_kind () == HIR::Item::ItemKind::Trait);
2113 8436 : HIR::Trait &trait = *static_cast<HIR::Trait *> (def_item);
2114 :
2115 : // we might be in a static or const context and unknown is fine
2116 8436 : TypeCheckContextItem current_context = TypeCheckContextItem::get_error ();
2117 8436 : if (context->have_function_context ())
2118 : {
2119 8400 : current_context = context->peek_context ();
2120 : }
2121 :
2122 8436 : auto segment = specified_segment.is_error ()
2123 15029 : ? HIR::PathIdentSegment (associated_item_name)
2124 8436 : : specified_segment;
2125 8436 : TyTy::BaseType *method_receiver = probe_lhs == nullptr ? lhs : probe_lhs;
2126 8436 : auto candidates
2127 8436 : = MethodResolver::Probe (method_receiver, segment, false, &trait);
2128 :
2129 : // remove any recursive candidates
2130 8401 : std::set<MethodCandidate> resolved_candidates;
2131 403248 : for (auto &c : candidates)
2132 : {
2133 394847 : const TyTy::BaseType *candidate_type = c.candidate.ty;
2134 394847 : rust_assert (candidate_type->get_kind () == TyTy::TypeKind::FNDEF);
2135 :
2136 394847 : const TyTy::FnType &fn
2137 : = *static_cast<const TyTy::FnType *> (candidate_type);
2138 :
2139 394911 : if (probe_lhs != nullptr
2140 396757 : && !types_compatable (TyTy::TyWithLocation (fn.get_self_type ()),
2141 1910 : TyTy::TyWithLocation (probe_lhs),
2142 : UNDEF_LOCATION, false /* emit_errors */))
2143 64 : continue;
2144 :
2145 394783 : DefId current_fn_defid = current_context.get_defid ();
2146 789566 : bool recursive_candidated = fn.get_id () == current_fn_defid;
2147 392720 : if (!recursive_candidated)
2148 : {
2149 392720 : resolved_candidates.insert (c);
2150 : }
2151 : }
2152 :
2153 8401 : std::vector<TyTy::BaseType *> select_args = {};
2154 8401 : if (rhs != nullptr)
2155 7849 : select_args = {rhs};
2156 8401 : auto selected_candidates
2157 8401 : = MethodResolver::Select (resolved_candidates, method_receiver, select_args,
2158 8401 : result_type);
2159 :
2160 8401 : bool have_implementation_for_lang_item = selected_candidates.size () > 0;
2161 8401 : if (!have_implementation_for_lang_item)
2162 : return false;
2163 :
2164 6208 : if (selected_candidates.size () > 1)
2165 : {
2166 4201 : if (!allow_defer)
2167 : return false;
2168 :
2169 4201 : TyTy::TyVar result_type
2170 4201 : = TyTy::TyVar::get_implicit_infer_var (expr.get_locus ());
2171 4201 : TyTy::BaseType *result_tyty = result_type.get_tyty ();
2172 4201 : rust_assert (result_tyty != nullptr);
2173 4201 : rust_debug ("deferring operator expr=%u result-ref=%u result-ty-ref=%u "
2174 : "lhs-ref=%u rhs-ref=%u",
2175 : expr.get_mappings ().get_hirid (), result_type.get_ref (),
2176 : result_tyty->get_ty_ref (), lhs->get_ref (),
2177 : rhs == nullptr ? UNKNOWN_HIRID : rhs->get_ref ());
2178 8402 : DeferredOpOverload defer (expr.get_mappings ().get_hirid (),
2179 : lang_item_type, specified_segment, expr,
2180 8402 : result_type);
2181 4201 : context->insert_deferred_operator_overload (std::move (defer));
2182 :
2183 4201 : infered = result_tyty;
2184 4201 : return true;
2185 4201 : }
2186 :
2187 : // Get the adjusted self
2188 2007 : MethodCandidate candidate = *selected_candidates.begin ();
2189 2007 : if (probe_lhs != nullptr)
2190 1013 : candidate.adjustments.insert (
2191 1013 : candidate.adjustments.begin (),
2192 1013 : Adjustment (Adjustment::AdjustmentType::IMM_REF, lhs, probe_lhs));
2193 2007 : Adjuster adj (lhs);
2194 2007 : TyTy::BaseType *adjusted_self = adj.adjust_type (candidate.adjustments);
2195 :
2196 : // store the adjustments for code-generation to know what to do
2197 2007 : context->insert_autoderef_mappings (expr.get_lvalue_mappings ().get_hirid (),
2198 : std::move (candidate.adjustments));
2199 :
2200 2007 : PathProbeCandidate &resolved_candidate = candidate.candidate;
2201 2007 : TyTy::BaseType *lookup_tyty = candidate.candidate.ty;
2202 2007 : NodeId resolved_node_id
2203 2007 : = resolved_candidate.is_impl_candidate ()
2204 2007 : ? resolved_candidate.item.impl.impl_item->get_impl_mappings ()
2205 1603 : .get_nodeid ()
2206 404 : : resolved_candidate.item.trait.item_ref->get_mappings ().get_nodeid ();
2207 :
2208 2007 : rust_assert (lookup_tyty->get_kind () == TyTy::TypeKind::FNDEF);
2209 2007 : TyTy::BaseType *lookup = lookup_tyty;
2210 2007 : TyTy::FnType *fn = static_cast<TyTy::FnType *> (lookup);
2211 4014 : rust_assert (fn->is_method ());
2212 :
2213 2007 : rust_debug ("is_impl_item_candidate: %s",
2214 : resolved_candidate.is_impl_candidate () ? "true" : "false");
2215 :
2216 : // in the case where we resolve to a trait bound we have to be careful we are
2217 : // able to do so there is a case where we are currently resolving the deref
2218 : // operator overload function which is generic and this might resolve to the
2219 : // trait item of deref which is not valid as its just another recursive case
2220 2007 : if (current_context.get_type () == TypeCheckContextItem::ItemType::IMPL_ITEM)
2221 : {
2222 1306 : auto &impl_item = current_context.get_impl_item ();
2223 1306 : HIR::ImplBlock *parent = impl_item.first;
2224 1306 : HIR::Function *fn = impl_item.second;
2225 :
2226 1306 : bool is_deref = lang_item_type == LangItem::Kind::DEREF
2227 1306 : || lang_item_type == LangItem::Kind::DEREF_MUT;
2228 5224 : bool is_deref_match = fn->get_function_name ().as_string ().compare (
2229 2612 : LangItem::ToString (LangItem::Kind::DEREF))
2230 : == 0
2231 3771 : || fn->get_function_name ().as_string ().compare (
2232 2465 : LangItem::ToString (LangItem::Kind::DEREF_MUT))
2233 : == 0;
2234 :
2235 1306 : bool is_recursive_op
2236 2612 : = fn->get_function_name ().as_string ().compare (associated_item_name)
2237 : == 0
2238 1306 : || (is_deref && is_deref_match);
2239 1306 : if (parent->has_trait_ref () && is_recursive_op)
2240 : {
2241 588 : TraitReference *trait_reference
2242 588 : = TraitResolver::Lookup (parent->get_trait_ref ());
2243 588 : if (!trait_reference->is_error ())
2244 : {
2245 588 : TyTy::BaseType *lookup = nullptr;
2246 588 : bool ok = context->lookup_type (fn->get_mappings ().get_hirid (),
2247 : &lookup);
2248 588 : rust_assert (ok);
2249 588 : rust_assert (lookup->get_kind () == TyTy::TypeKind::FNDEF);
2250 :
2251 588 : TyTy::FnType *fntype = static_cast<TyTy::FnType *> (lookup);
2252 1176 : rust_assert (fntype->is_method ());
2253 :
2254 588 : bool is_lang_item_impl
2255 588 : = trait_reference->get_mappings ().get_defid ()
2256 590 : == respective_lang_item_id
2257 2 : || (is_deref && is_deref_match);
2258 588 : bool self_is_lang_item_self
2259 588 : = fntype->get_self_type ()->is_equal (*adjusted_self);
2260 588 : bool recursive_operator_overload
2261 : = is_lang_item_impl && self_is_lang_item_self;
2262 :
2263 588 : if (recursive_operator_overload)
2264 150 : return false;
2265 : }
2266 : }
2267 : }
2268 :
2269 : // we found a valid operator overload
2270 1857 : rust_debug_loc (expr.get_locus (), "resolved operator overload to: {%u} {%s}",
2271 : candidate.candidate.ty->get_ref (),
2272 : candidate.candidate.ty->debug_str ().c_str ());
2273 :
2274 : // handle generics
2275 1857 : if (lookup->needs_generic_substitutions ())
2276 383 : lookup = SubstMapper::InferSubst (lookup, expr.get_locus ());
2277 :
2278 : // type check the arguments if required
2279 1857 : TyTy::FnType *type = static_cast<TyTy::FnType *> (lookup);
2280 1857 : rust_assert (type->num_params () > 0);
2281 1857 : auto &fnparam = type->param_at (0);
2282 :
2283 : // typecheck the self
2284 3714 : unify_site (expr.get_mappings ().get_hirid (),
2285 1857 : TyTy::TyWithLocation (fnparam.get_type ()),
2286 1857 : TyTy::TyWithLocation (adjusted_self), expr.get_locus ());
2287 1857 : if (rhs == nullptr)
2288 : {
2289 169 : rust_assert (type->num_params () == 1);
2290 : }
2291 : else
2292 : {
2293 1688 : rust_assert (type->num_params () == 2);
2294 1688 : auto &fnparam = type->param_at (1);
2295 3376 : unify_site (expr.get_mappings ().get_hirid (),
2296 1688 : TyTy::TyWithLocation (fnparam.get_type ()),
2297 1688 : TyTy::TyWithLocation (rhs), expr.get_locus ());
2298 : }
2299 :
2300 1857 : rust_assert (lookup->get_kind () == TyTy::TypeKind::FNDEF);
2301 1857 : fn = static_cast<TyTy::FnType *> (lookup);
2302 1857 : fn->monomorphize ();
2303 :
2304 : // get the return type
2305 1857 : TyTy::BaseType *function_ret_tyty
2306 1857 : = type->get_return_type ()->monomorphized_clone ();
2307 :
2308 : // store the expected fntype
2309 1857 : context->insert_operator_overload (expr.get_mappings ().get_hirid (), type);
2310 :
2311 : // set up the resolved name on the path
2312 1857 : auto &nr_ctx = Resolver2_0::FinalizedNameResolutionContext::get ();
2313 :
2314 1857 : nr_ctx.map_usage (Resolver2_0::Usage (expr.get_mappings ().get_nodeid ()),
2315 1857 : Resolver2_0::Definition (resolved_node_id),
2316 : Resolver2_0::Namespace::Types);
2317 :
2318 : // return the result of the function back
2319 1857 : infered = function_ret_tyty;
2320 :
2321 1857 : return true;
2322 10408 : }
2323 :
2324 : HIR::PathIdentSegment
2325 12984 : TypeCheckExpr::resolve_possible_fn_trait_call_method_name (
2326 : const TyTy::BaseType &receiver,
2327 : TyTy::TypeBoundPredicate *associated_predicate)
2328 : {
2329 : // FIXME
2330 : // the logic to map the FnTrait to their respective call trait-item is
2331 : // duplicated over in the backend/rust-compile-expr.cc
2332 13011 : for (const auto &bound : receiver.get_specified_bounds ())
2333 : {
2334 93 : bool found_fn = bound.get_name ().compare ("Fn") == 0;
2335 93 : bool found_fn_mut = bound.get_name ().compare ("FnMut") == 0;
2336 93 : bool found_fn_once = bound.get_name ().compare ("FnOnce") == 0;
2337 :
2338 93 : if (found_fn)
2339 : {
2340 0 : *associated_predicate = bound;
2341 0 : return HIR::PathIdentSegment ("call");
2342 : }
2343 93 : else if (found_fn_mut)
2344 : {
2345 0 : *associated_predicate = bound;
2346 0 : return HIR::PathIdentSegment ("call_mut");
2347 : }
2348 93 : else if (found_fn_once)
2349 : {
2350 66 : *associated_predicate = bound;
2351 66 : return HIR::PathIdentSegment ("call_once");
2352 : }
2353 : }
2354 :
2355 12918 : if (receiver.is<TyTy::ReferenceType> ())
2356 : {
2357 0 : const auto &ref = static_cast<const TyTy::ReferenceType &> (receiver);
2358 0 : const auto &underlying = *ref.get_base ();
2359 0 : for (const auto &bound : underlying.get_specified_bounds ())
2360 : {
2361 0 : bool found_fn = bound.get_name ().compare ("Fn") == 0;
2362 0 : bool found_fn_mut = bound.get_name ().compare ("FnMut") == 0;
2363 0 : bool found_fn_once = bound.get_name ().compare ("FnOnce") == 0;
2364 :
2365 0 : if (found_fn)
2366 : {
2367 0 : *associated_predicate = bound;
2368 0 : return HIR::PathIdentSegment ("call");
2369 : }
2370 0 : else if (found_fn_mut)
2371 : {
2372 0 : *associated_predicate = bound;
2373 0 : return HIR::PathIdentSegment ("call_mut");
2374 : }
2375 0 : else if (found_fn_once)
2376 : {
2377 0 : *associated_predicate = bound;
2378 0 : return HIR::PathIdentSegment ("call_once");
2379 : }
2380 : }
2381 : }
2382 :
2383 : // nothing
2384 12918 : *associated_predicate = TyTy::TypeBoundPredicate::error ();
2385 12918 : return HIR::PathIdentSegment ("");
2386 : }
2387 :
2388 : bool
2389 12984 : TypeCheckExpr::resolve_fn_trait_call (HIR::CallExpr &expr,
2390 : TyTy::BaseType *receiver_tyty,
2391 : TyTy::BaseType **result)
2392 : {
2393 : // we turn this into a method call expr
2394 : // TODO: add implicit self argument (?)
2395 12984 : auto associated_predicate = TyTy::TypeBoundPredicate::error ();
2396 12984 : HIR::PathIdentSegment method_name
2397 : = resolve_possible_fn_trait_call_method_name (*receiver_tyty,
2398 12984 : &associated_predicate);
2399 12984 : if (method_name.is_error () || associated_predicate.is_error ())
2400 : return false;
2401 :
2402 66 : auto candidates = MethodResolver::Probe (receiver_tyty, method_name);
2403 66 : if (candidates.empty ())
2404 : return false;
2405 :
2406 66 : if (candidates.size () > 1)
2407 : {
2408 0 : rich_location r (line_table, expr.get_locus ());
2409 0 : for (auto &c : candidates)
2410 0 : r.add_range (c.candidate.locus);
2411 :
2412 0 : rust_error_at (
2413 : r, "multiple candidates found for function trait method call %qs",
2414 0 : method_name.to_string ().c_str ());
2415 0 : return false;
2416 0 : }
2417 :
2418 : // FnOnce::Output is normalized lazily by normalize_projection's closure
2419 : // special-case; no explicit setup is required here.
2420 :
2421 66 : auto candidate = *candidates.begin ();
2422 66 : rust_debug_loc (expr.get_locus (),
2423 : "resolved call-expr to fn trait: {%u} {%s}",
2424 : candidate.candidate.ty->get_ref (),
2425 : candidate.candidate.ty->debug_str ().c_str ());
2426 :
2427 : // Get the adjusted self
2428 66 : Adjuster adj (receiver_tyty);
2429 66 : TyTy::BaseType *adjusted_self = adj.adjust_type (candidate.adjustments);
2430 :
2431 : // store the adjustments for code-generation to know what to do which must be
2432 : // stored onto the receiver to so as we don't trigger duplicate deref mappings
2433 : // ICE when an argument is a method call
2434 66 : HIR::Expr &fnexpr = expr.get_fnexpr ();
2435 66 : HirId autoderef_mappings_id = fnexpr.get_mappings ().get_hirid ();
2436 66 : context->insert_autoderef_mappings (autoderef_mappings_id,
2437 : std::move (candidate.adjustments));
2438 :
2439 66 : PathProbeCandidate &resolved_candidate = candidate.candidate;
2440 66 : TyTy::BaseType *lookup_tyty = candidate.candidate.ty;
2441 66 : NodeId resolved_node_id
2442 66 : = resolved_candidate.is_impl_candidate ()
2443 66 : ? resolved_candidate.item.impl.impl_item->get_impl_mappings ()
2444 0 : .get_nodeid ()
2445 66 : : resolved_candidate.item.trait.item_ref->get_mappings ().get_nodeid ();
2446 :
2447 66 : if (lookup_tyty->get_kind () != TyTy::TypeKind::FNDEF)
2448 : {
2449 0 : rich_location r (line_table, expr.get_locus ());
2450 0 : r.add_range (resolved_candidate.locus);
2451 0 : rust_error_at (r, "associated impl item is not a method");
2452 0 : return false;
2453 0 : }
2454 :
2455 66 : TyTy::BaseType *lookup = lookup_tyty;
2456 66 : TyTy::FnType *fn = static_cast<TyTy::FnType *> (lookup);
2457 132 : if (!fn->is_method ())
2458 : {
2459 0 : rich_location r (line_table, expr.get_locus ());
2460 0 : r.add_range (resolved_candidate.locus);
2461 0 : rust_error_at (r, "associated function is not a method");
2462 0 : return false;
2463 0 : }
2464 :
2465 : // fn traits only support tuple argument passing so we need to implicitly set
2466 : // this up to get the same type checking we get in the rest of the pipeline
2467 :
2468 66 : std::vector<TyTy::TyVar> call_args;
2469 132 : for (auto &arg : expr.get_arguments ())
2470 : {
2471 66 : TyTy::BaseType *a = TypeCheckExpr::Resolve (*arg);
2472 66 : call_args.emplace_back (a->get_ref ());
2473 : }
2474 :
2475 : // crate implicit tuple
2476 66 : HirId implicit_arg_id = mappings.get_next_hir_id ();
2477 66 : Analysis::NodeMapping mapping (mappings.crate.get_current_crate (),
2478 : UNKNOWN_NODEID, implicit_arg_id,
2479 66 : UNKNOWN_LOCAL_DEFID);
2480 :
2481 66 : TyTy::TupleType *tuple
2482 66 : = new TyTy::TupleType (implicit_arg_id, expr.get_locus (), call_args);
2483 66 : context->insert_implicit_type (implicit_arg_id, tuple);
2484 :
2485 66 : std::vector<TyTy::Argument> args;
2486 66 : args.emplace_back (mapping, tuple,
2487 66 : expr.get_locus () /*FIXME is there a better location*/);
2488 :
2489 66 : TyTy::BaseType *function_ret_tyty
2490 66 : = TyTy::TypeCheckMethodCallExpr::go (fn, expr.get_mappings (), args,
2491 : expr.get_locus (), expr.get_locus (),
2492 : adjusted_self, context);
2493 66 : if (function_ret_tyty == nullptr
2494 66 : || function_ret_tyty->get_kind () == TyTy::TypeKind::ERROR)
2495 : {
2496 0 : rust_error_at (expr.get_locus (),
2497 : "failed check fn trait call-expr MethodCallExpr");
2498 0 : return false;
2499 : }
2500 :
2501 : // store the expected fntype
2502 66 : context->insert_operator_overload (expr.get_mappings ().get_hirid (), fn);
2503 :
2504 : // set up the resolved name on the path
2505 66 : auto &nr_ctx = Resolver2_0::FinalizedNameResolutionContext::get ();
2506 :
2507 : // TODO: What namespace to use for inserting and looking up here? It's a trait
2508 : // call, so NS::Types is right?
2509 :
2510 66 : auto existing = nr_ctx.lookup (expr.get_mappings ().get_nodeid (),
2511 : Resolver2_0::Namespace::Types);
2512 66 : if (existing)
2513 9 : rust_assert (*existing == resolved_node_id);
2514 : else
2515 57 : nr_ctx.map_usage (Resolver2_0::Usage (expr.get_mappings ().get_nodeid ()),
2516 57 : Resolver2_0::Definition (resolved_node_id),
2517 : Resolver2_0::Namespace::Types);
2518 :
2519 : // return the result of the function back
2520 66 : auto mono = function_ret_tyty->monomorphized_clone ();
2521 66 : *result = mono;
2522 :
2523 66 : return true;
2524 13182 : }
2525 :
2526 : bool
2527 9714 : TypeCheckExpr::validate_arithmetic_type (
2528 : const TyTy::BaseType *tyty, HIR::ArithmeticOrLogicalExpr::ExprType expr_type)
2529 : {
2530 9714 : auto type = tyty->destructure ();
2531 9714 : if (type->get_kind () == TyTy::TypeKind::CONST)
2532 : {
2533 23 : auto base_const = type->as_const_type ();
2534 23 : type = base_const->get_specified_type ();
2535 : }
2536 :
2537 : // https://doc.rust-lang.org/reference/expressions/operator-expr.html#arithmetic-and-logical-binary-operators
2538 : // this will change later when traits are added
2539 9714 : switch (expr_type)
2540 : {
2541 7796 : case ArithmeticOrLogicalOperator::ADD:
2542 7796 : case ArithmeticOrLogicalOperator::SUBTRACT:
2543 7796 : case ArithmeticOrLogicalOperator::MULTIPLY:
2544 7796 : case ArithmeticOrLogicalOperator::DIVIDE:
2545 7796 : case ArithmeticOrLogicalOperator::MODULUS:
2546 7796 : return (type->get_kind () == TyTy::TypeKind::INT)
2547 5782 : || (type->get_kind () == TyTy::TypeKind::UINT)
2548 4664 : || (type->get_kind () == TyTy::TypeKind::FLOAT)
2549 4186 : || (type->get_kind () == TyTy::TypeKind::USIZE)
2550 3453 : || (type->get_kind () == TyTy::TypeKind::ISIZE)
2551 3357 : || (type->get_kind () == TyTy::TypeKind::INFER
2552 3354 : && (((const TyTy::InferType *) type)->get_infer_kind ()
2553 : == TyTy::InferType::INTEGRAL))
2554 7836 : || (type->get_kind () == TyTy::TypeKind::INFER
2555 37 : && (((const TyTy::InferType *) type)->get_infer_kind ()
2556 : == TyTy::InferType::FLOAT));
2557 :
2558 : // integers or bools
2559 1414 : case ArithmeticOrLogicalOperator::BITWISE_AND:
2560 1414 : case ArithmeticOrLogicalOperator::BITWISE_OR:
2561 1414 : case ArithmeticOrLogicalOperator::BITWISE_XOR:
2562 1414 : return (type->get_kind () == TyTy::TypeKind::INT)
2563 1197 : || (type->get_kind () == TyTy::TypeKind::UINT)
2564 257 : || (type->get_kind () == TyTy::TypeKind::USIZE)
2565 222 : || (type->get_kind () == TyTy::TypeKind::ISIZE)
2566 194 : || (type->get_kind () == TyTy::TypeKind::BOOL)
2567 1538 : || (type->get_kind () == TyTy::TypeKind::INFER
2568 124 : && (((const TyTy::InferType *) type)->get_infer_kind ()
2569 : == TyTy::InferType::INTEGRAL));
2570 :
2571 : // integers only
2572 504 : case ArithmeticOrLogicalOperator::LEFT_SHIFT:
2573 504 : case ArithmeticOrLogicalOperator::RIGHT_SHIFT:
2574 504 : return (type->get_kind () == TyTy::TypeKind::INT)
2575 419 : || (type->get_kind () == TyTy::TypeKind::UINT)
2576 121 : || (type->get_kind () == TyTy::TypeKind::USIZE)
2577 105 : || (type->get_kind () == TyTy::TypeKind::ISIZE)
2578 595 : || (type->get_kind () == TyTy::TypeKind::INFER
2579 91 : && (((const TyTy::InferType *) type)->get_infer_kind ()
2580 : == TyTy::InferType::INTEGRAL));
2581 : }
2582 :
2583 0 : rust_unreachable ();
2584 : return false;
2585 : }
2586 :
2587 : } // namespace Resolver
2588 : } // namespace Rust
|