Debian Codegraph @

gcc/rust/backend/rust-compile-expr.cc

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 #include "rust-compile-expr.h"
20 #include "rust-compile-struct-field-expr.h"
21 #include "rust-compile-pattern.h"
22 #include "rust-compile-resolve-path.h"
23 #include "rust-compile-block.h"
24 #include "rust-compile-implitem.h"
25 #include "rust-constexpr.h"
26 #include "rust-compile-type.h"
27 #include "rust-gcc.h"
28 #include "rust-compile-asm.h"
29 #include "fold-const.h"
30 #include "realmpfr.h"
31 #include "convert.h"
32 #include "print-tree.h"
33 #include "rust-system.h"
34 #include "rust-tyty.h"
35
36 namespace Rust {
37 namespace Compile {
38
39 CompileExpr::CompileExpr (Context *ctx)
40 : HIRCompileBase (ctx), translated (error_mark_node)
41 {}
42
43 tree
44 CompileExpr::Compile (HIR::Expr &expr, Context *ctx)
45 {
46 CompileExpr compiler (ctx);
47 expr.accept_vis (compiler);
48 return compiler.translated;
49 }
50
51 void
52 CompileExpr::visit (HIR::TupleIndexExpr &expr)
53 {
54 HIR::Expr &tuple_expr = expr.get_tuple_expr ();
55 TupleIndex index = expr.get_tuple_index ();
56
57 tree receiver_ref = CompileExpr::Compile (tuple_expr, ctx);
58
59 TyTy::BaseType *tuple_expr_ty = nullptr;
60 bool ok
61 = ctx->get_tyctx ()->lookup_type (tuple_expr.get_mappings ().get_hirid (),
62 &tuple_expr_ty);
63 rust_assert (ok);
64
65 // do we need to add an indirect reference
66 if (tuple_expr_ty->get_kind () == TyTy::TypeKind::REF)
67 {
68 tree indirect = indirect_expression (receiver_ref, expr.get_locus ());
69 receiver_ref = indirect;
70 }
71
72 translated
73 = Backend::struct_field_expression (receiver_ref, index, expr.get_locus ());
74 }
75
76 void
77 CompileExpr::visit (HIR::TupleExpr &expr)
78 {
79 if (expr.is_unit ())
80 {
81 translated = unit_expression (expr.get_locus ());
82 return;
83 }
84
85 TyTy::BaseType *tyty = nullptr;
86 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
87 &tyty))
88 {
89 rust_fatal_error (expr.get_locus (),
90 "did not resolve type for this TupleExpr");
91 return;
92 }
93
94 tree tuple_type = TyTyResolveCompile::compile (ctx, tyty);
95 rust_assert (tuple_type != nullptr);
96
97 // this assumes all fields are in order from type resolution
98 std::vector<tree> vals;
99 for (auto &elem : expr.get_tuple_elems ())
100 {
101 auto e = CompileExpr::Compile (*elem, ctx);
102 vals.push_back (e);
103 }
104
105 translated = Backend::constructor_expression (tuple_type, false, vals, -1,
106 expr.get_locus ());
107 }
108
109 void
110 CompileExpr::visit (HIR::ReturnExpr &expr)
111 {
112 auto fncontext = ctx->peek_fn ();
113
114 tree return_value = expr.has_return_expr ()
115 ? CompileExpr::Compile (expr.get_expr (), ctx)
116 : unit_expression (expr.get_locus ());
117
118 if (expr.has_return_expr ())
119 {
120 HirId id = expr.get_mappings ().get_hirid ();
121 location_t rvalue_locus = expr.return_expr->get_locus ();
122
123 TyTy::BaseType *expected = fncontext.retty;
124 location_t lvalue_locus
125 = ctx->get_mappings ().lookup_location (expected->get_ref ());
126
127 TyTy::BaseType *actual = nullptr;
128 bool ok = ctx->get_tyctx ()->lookup_type (
129 expr.return_expr->get_mappings ().get_hirid (), &actual);
130 rust_assert (ok);
131
132 return_value = coercion_site (id, return_value, actual, expected,
133 lvalue_locus, rvalue_locus);
134 }
135
136 tree return_stmt = Backend::return_statement (fncontext.fndecl, return_value,
137 expr.get_locus ());
138 ctx->add_statement (return_stmt);
139 }
140
141 void
142 CompileExpr::visit (HIR::ArithmeticOrLogicalExpr &expr)
143 {
144 auto op = expr.get_expr_type ();
145 auto lhs = CompileExpr::Compile (expr.get_lhs (), ctx);
146 auto rhs = CompileExpr::Compile (expr.get_rhs (), ctx);
147
148 // this might be an operator overload situation lets check
149 TyTy::FnType *fntype;
150 bool is_op_overload = ctx->get_tyctx ()->lookup_operator_overload (
151 expr.get_mappings ().get_hirid (), &fntype);
152 if (is_op_overload)
153 {
154 auto lang_item_type
155 = LangItem::OperatorToLangItem (expr.get_expr_type ());
156 translated = resolve_operator_overload (
157 lang_item_type, expr, lhs, rhs, expr.get_lhs (),
158 tl::optional<std::reference_wrapper<HIR::Expr>> (expr.get_rhs ()));
159 return;
160 }
161
162 bool can_generate_overflow_checks
163 = (ctx->in_fn () && !ctx->const_context_p ()) && flag_overflow_checks;
164 if (!can_generate_overflow_checks)
165 {
166 translated
167 = Backend::arithmetic_or_logical_expression (op, lhs, rhs,
168 expr.get_locus ());
169 return;
170 }
171
172 auto receiver_tmp = NULL_TREE;
173 auto receiver
174 = Backend::temporary_variable (ctx->peek_fn ().fndecl, NULL_TREE,
175 TREE_TYPE (lhs), lhs, true,
176 expr.get_locus (), &receiver_tmp);
177 auto check
178 = Backend::arithmetic_or_logical_expression_checked (op, lhs, rhs,
179 expr.get_locus (),
180 receiver);
181
182 ctx->add_statement (check);
183 translated = receiver->get_tree (expr.get_locus ());
184 }
185
186 void
187 CompileExpr::visit (HIR::CompoundAssignmentExpr &expr)
188 {
189 auto op = expr.get_expr_type ();
190 auto lhs = CompileExpr::Compile (expr.get_lhs (), ctx);
191 auto rhs = CompileExpr::Compile (expr.get_rhs (), ctx);
192
193 // this might be an operator overload situation lets check
194 TyTy::FnType *fntype;
195 bool is_op_overload = ctx->get_tyctx ()->lookup_operator_overload (
196 expr.get_mappings ().get_hirid (), &fntype);
197 if (is_op_overload)
198 {
199 auto lang_item_type = LangItem::CompoundAssignmentOperatorToLangItem (
200 expr.get_expr_type ());
201 auto compound_assignment
202 = resolve_operator_overload (lang_item_type, expr, lhs, rhs,
203 expr.get_lhs (), expr.get_rhs ());
204 ctx->add_statement (compound_assignment);
205
206 return;
207 }
208
209 if (ctx->in_fn () && !ctx->const_context_p ())
210 {
211 auto tmp = NULL_TREE;
212 auto receiver
213 = Backend::temporary_variable (ctx->peek_fn ().fndecl, NULL_TREE,
214 TREE_TYPE (lhs), lhs, true,
215 expr.get_locus (), &tmp);
216 auto check
217 = Backend::arithmetic_or_logical_expression_checked (op, lhs, rhs,
218 expr.get_locus (),
219 receiver);
220 ctx->add_statement (check);
221
222 translated
223 = Backend::assignment_statement (lhs,
224 receiver->get_tree (expr.get_locus ()),
225 expr.get_locus ());
226 }
227 else
228 {
229 translated
230 = Backend::arithmetic_or_logical_expression (op, lhs, rhs,
231 expr.get_locus ());
232 }
233 }
234
235 void
236 CompileExpr::visit (HIR::NegationExpr &expr)
237 {
238 auto op = expr.get_expr_type ();
239
240 auto &literal_expr = expr.get_expr ();
241
242 // If it's a negated integer/float literal, we can return early
243 if (op == NegationOperator::NEGATE
244 && literal_expr.get_expression_type () == HIR::Expr::ExprType::Lit)
245 {
246 auto &new_literal_expr = static_cast<HIR::LiteralExpr &> (literal_expr);
247 auto lit_type = new_literal_expr.get_lit_type ();
248 if (lit_type == HIR::Literal::LitType::INT
249 || lit_type == HIR::Literal::LitType::FLOAT)
250 {
251 new_literal_expr.set_negative ();
252 translated = CompileExpr::Compile (literal_expr, ctx);
253 return;
254 }
255 }
256
257 auto negated_expr = CompileExpr::Compile (literal_expr, ctx);
258 auto location = expr.get_locus ();
259
260 // this might be an operator overload situation lets check
261 TyTy::FnType *fntype;
262 bool is_op_overload = ctx->get_tyctx ()->lookup_operator_overload (
263 expr.get_mappings ().get_hirid (), &fntype);
264 if (is_op_overload)
265 {
266 auto lang_item_type = LangItem::NegationOperatorToLangItem (op);
267 translated
268 = resolve_operator_overload (lang_item_type, expr, negated_expr,
269 nullptr, expr.get_expr (), tl::nullopt);
270 return;
271 }
272
273 translated = Backend::negation_expression (op, negated_expr, location);
274 }
275
276 void
277 CompileExpr::visit (HIR::ComparisonExpr &expr)
278 {
279 auto op = expr.get_expr_type ();
280 auto lhs = CompileExpr::Compile (expr.get_lhs (), ctx);
281 auto rhs = CompileExpr::Compile (expr.get_rhs (), ctx);
282 auto location = expr.get_locus ();
283
284 // this might be an operator overload situation lets check
285 TyTy::FnType *fntype;
286 bool is_op_overload = ctx->get_tyctx ()->lookup_operator_overload (
287 expr.get_mappings ().get_hirid (), &fntype);
288 if (is_op_overload)
289 {
290 auto seg_name = LangItem::ComparisonToSegment (expr.get_expr_type ());
291 auto segment = HIR::PathIdentSegment (seg_name);
292 auto lang_item_type
293 = LangItem::ComparisonToLangItem (expr.get_expr_type ());
294
295 rhs = address_expression (rhs, EXPR_LOCATION (rhs));
296
297 translated = resolve_operator_overload (
298 lang_item_type, expr, lhs, rhs, expr.get_lhs (),
299 tl::optional<std::reference_wrapper<HIR::Expr>> (expr.get_rhs ()),
300 segment);
301 return;
302 }
303
304 translated = Backend::comparison_expression (op, lhs, rhs, location);
305 }
306
307 void
308 CompileExpr::visit (HIR::LazyBooleanExpr &expr)
309 {
310 auto op = expr.get_expr_type ();
311 auto lhs = CompileExpr::Compile (expr.get_lhs (), ctx);
312 auto rhs = CompileExpr::Compile (expr.get_rhs (), ctx);
313 auto location = expr.get_locus ();
314
315 translated = Backend::lazy_boolean_expression (op, lhs, rhs, location);
316 }
317
318 void
319 CompileExpr::visit (HIR::TypeCastExpr &expr)
320 {
321 TyTy::BaseType *type_to_cast_to_ty = nullptr;
322 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
323 &type_to_cast_to_ty))
324 {
325 translated = error_mark_node;
326 return;
327 }
328
329 TyTy::BaseType *casted_tyty = nullptr;
330 if (!ctx->get_tyctx ()->lookup_type (
331 expr.get_casted_expr ().get_mappings ().get_hirid (), &casted_tyty))
332 {
333 translated = error_mark_node;
334 return;
335 }
336
337 auto type_to_cast_to = TyTyResolveCompile::compile (ctx, type_to_cast_to_ty);
338 auto casted_expr = CompileExpr::Compile (expr.get_casted_expr (), ctx);
339
340 std::vector<Resolver::Adjustment> *adjustments = nullptr;
341 bool ok = ctx->get_tyctx ()->lookup_cast_autoderef_mappings (
342 expr.get_mappings ().get_hirid (), &adjustments);
343 if (ok)
344 {
345 casted_expr
346 = resolve_adjustements (*adjustments, casted_expr, expr.get_locus ());
347 }
348
349 translated
350 = type_cast_expression (type_to_cast_to, casted_expr, expr.get_locus ());
351 }
352
353 void
354 CompileExpr::visit (HIR::IfExpr &expr)
355 {
356 auto stmt = CompileConditionalBlocks::compile (&expr, ctx, nullptr);
357 ctx->add_statement (stmt);
358 }
359
360 void
361 CompileExpr::visit (HIR::InlineAsm &expr)
362 {
363 CompileAsm asm_codegen (ctx);
364 ctx->add_statement (asm_codegen.tree_codegen_asm (expr));
365 // translated = build_asm_expr (0, NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE,
366 // NULL_TREE, true, true);
367 // CompileAsm::asm_build_expr (expr);
368 }
369
370 void
371 CompileExpr::visit (HIR::IfExprConseqElse &expr)
372 {
373 TyTy::BaseType *if_type = nullptr;
374 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
375 &if_type))
376 {
377 rust_error_at (expr.get_locus (),
378 "failed to lookup type of IfExprConseqElse");
379 return;
380 }
381
382 Bvariable *tmp = NULL;
383 fncontext fnctx = ctx->peek_fn ();
384 tree enclosing_scope = ctx->peek_enclosing_scope ();
385 tree block_type = TyTyResolveCompile::compile (ctx, if_type);
386
387 bool is_address_taken = false;
388 tree ret_var_stmt = nullptr;
389 tmp = Backend::temporary_variable (fnctx.fndecl, enclosing_scope, block_type,
390 NULL, is_address_taken, expr.get_locus (),
391 &ret_var_stmt);
392 ctx->add_statement (ret_var_stmt);
393
394 auto stmt = CompileConditionalBlocks::compile (&expr, ctx, tmp);
395 ctx->add_statement (stmt);
396
397 translated = Backend::var_expression (tmp, expr.get_locus ());
398 }
399
400 void
401 CompileExpr::visit (HIR::BlockExpr &expr)
402 {
403 if (expr.has_label ())
404 {
405 rust_error_at (expr.get_locus (), "labeled blocks are not supported");
406 return;
407 }
408
409 TyTy::BaseType *block_tyty = nullptr;
410 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
411 &block_tyty))
412 {
413 rust_error_at (expr.get_locus (), "failed to lookup type of BlockExpr");
414 return;
415 }
416
417 Bvariable *tmp = NULL;
418 fncontext fnctx = ctx->peek_fn ();
419 tree enclosing_scope = ctx->peek_enclosing_scope ();
420 tree block_type = TyTyResolveCompile::compile (ctx, block_tyty);
421
422 bool is_address_taken = false;
423 tree ret_var_stmt = nullptr;
424 tmp = Backend::temporary_variable (fnctx.fndecl, enclosing_scope, block_type,
425 NULL, is_address_taken, expr.get_locus (),
426 &ret_var_stmt);
427 ctx->add_statement (ret_var_stmt);
428
429 auto block_stmt = CompileBlock::compile (expr, ctx, tmp);
430 rust_assert (TREE_CODE (block_stmt) == BIND_EXPR);
431 ctx->add_statement (block_stmt);
432
433 translated = Backend::var_expression (tmp, expr.get_locus ());
434 }
435
436 void
437 CompileExpr::visit (HIR::UnsafeBlockExpr &expr)
438 {
439 expr.get_block_expr ().accept_vis (*this);
440 }
441
442 void
443 CompileExpr::visit (HIR::StructExprStruct &struct_expr)
444 {
445 TyTy::BaseType *tyty = nullptr;
446 if (!ctx->get_tyctx ()->lookup_type (struct_expr.get_mappings ().get_hirid (),
447 &tyty))
448 {
449 rust_error_at (struct_expr.get_locus (), "unknown type");
450 return;
451 }
452
453 rust_assert (tyty->is_unit ());
454 translated = unit_expression (struct_expr.get_locus ());
455 }
456
457 void
458 CompileExpr::visit (HIR::StructExprStructFields &struct_expr)
459 {
460 TyTy::BaseType *tyty = nullptr;
461 if (!ctx->get_tyctx ()->lookup_type (struct_expr.get_mappings ().get_hirid (),
462 &tyty))
463 {
464 rust_error_at (struct_expr.get_locus (), "unknown type");
465 return;
466 }
467
468 // it must be an ADT
469 rust_assert (tyty->get_kind () == TyTy::TypeKind::ADT);
470 TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (tyty);
471
472 // what variant is it?
473 int union_disriminator = struct_expr.union_index;
474 TyTy::VariantDef *variant = nullptr;
475 if (!adt->is_enum ())
476 {
477 rust_assert (adt->number_of_variants () == 1);
478 variant = adt->get_variants ().at (0);
479 }
480 else
481 {
482 HirId variant_id;
483 bool ok = ctx->get_tyctx ()->lookup_variant_definition (
484 struct_expr.get_struct_name ().get_mappings ().get_hirid (),
485 &variant_id);
486 rust_assert (ok);
487
488 ok
489 = adt->lookup_variant_by_id (variant_id, &variant, &union_disriminator);
490 rust_assert (ok);
491 }
492
493 // compile it
494 tree compiled_adt_type = TyTyResolveCompile::compile (ctx, tyty);
495
496 std::vector<tree> arguments;
497 if (adt->is_union ())
498 {
499 rust_assert (struct_expr.get_fields ().size () == 1);
500
501 // assignments are coercion sites so lets convert the rvalue if
502 // necessary
503 auto respective_field = variant->get_field_at_index (union_disriminator);
504 auto expected = respective_field->get_field_type ();
505
506 // process arguments
507 auto &argument = struct_expr.get_fields ().at (0);
508 auto lvalue_locus
509 = ctx->get_mappings ().lookup_location (expected->get_ty_ref ());
510 auto rvalue_locus = argument->get_locus ();
511 auto rvalue = CompileStructExprField::Compile (*argument, ctx);
512
513 TyTy::BaseType *actual = nullptr;
514 bool ok = ctx->get_tyctx ()->lookup_type (
515 argument->get_mappings ().get_hirid (), &actual);
516
517 if (ok)
518 {
519 rvalue
520 = coercion_site (argument->get_mappings ().get_hirid (), rvalue,
521 actual, expected, lvalue_locus, rvalue_locus);
522 }
523
524 // add it to the list
525 arguments.push_back (rvalue);
526 }
527 else
528 {
529 // this assumes all fields are in order from type resolution and if a
530 // base struct was specified those fields are filed via accessors
531 for (size_t i = 0; i < struct_expr.get_fields ().size (); i++)
532 {
533 // assignments are coercion sites so lets convert the rvalue if
534 // necessary
535 auto respective_field = variant->get_field_at_index (i);
536 auto expected = respective_field->get_field_type ();
537
538 // process arguments
539 auto &argument = struct_expr.get_fields ().at (i);
540 auto lvalue_locus
541 = ctx->get_mappings ().lookup_location (expected->get_ty_ref ());
542 auto rvalue_locus = argument->get_locus ();
543 auto rvalue = CompileStructExprField::Compile (*argument, ctx);
544
545 TyTy::BaseType *actual = nullptr;
546 bool ok = ctx->get_tyctx ()->lookup_type (
547 argument->get_mappings ().get_hirid (), &actual);
548
549 // coerce it if required/possible see
550 // compile/torture/struct_base_init_1.rs
551 if (ok)
552 {
553 rvalue
554 = coercion_site (argument->get_mappings ().get_hirid (), rvalue,
555 actual, expected, lvalue_locus, rvalue_locus);
556 }
557
558 // add it to the list
559 arguments.push_back (rvalue);
560 }
561 }
562
563 if (!adt->is_enum ())
564 {
565 translated
566 = Backend::constructor_expression (compiled_adt_type, adt->is_enum (),
567 arguments, union_disriminator,
568 struct_expr.get_locus ());
569 return;
570 }
571
572 HIR::Expr &discrim_expr = variant->get_discriminant ();
573 tree discrim_expr_node = CompileExpr::Compile (discrim_expr, ctx);
574 tree folded_discrim_expr = fold_expr (discrim_expr_node);
575 tree qualifier = folded_discrim_expr;
576
577 tree enum_root_files = TYPE_FIELDS (compiled_adt_type);
578 tree payload_root = DECL_CHAIN (enum_root_files);
579
580 tree payload = Backend::constructor_expression (TREE_TYPE (payload_root),
581 adt->is_enum (), arguments,
582 union_disriminator,
583 struct_expr.get_locus ());
584
585 std::vector<tree> ctor_arguments = {qualifier, payload};
586
587 translated
588 = Backend::constructor_expression (compiled_adt_type, 0, ctor_arguments, -1,
589 struct_expr.get_locus ());
590 }
591
592 void
593 CompileExpr::visit (HIR::GroupedExpr &expr)
594 {
595 translated = CompileExpr::Compile (expr.get_expr_in_parens (), ctx);
596 }
597
598 void
599 CompileExpr::visit (HIR::FieldAccessExpr &expr)
600 {
601 HIR::Expr &receiver_expr = expr.get_receiver_expr ();
602 tree receiver_ref = CompileExpr::Compile (receiver_expr, ctx);
603
604 // resolve the receiver back to ADT type
605 TyTy::BaseType *receiver = nullptr;
606 if (!ctx->get_tyctx ()->lookup_type (
607 expr.get_receiver_expr ().get_mappings ().get_hirid (), &receiver))
608 {
609 rust_error_at (expr.get_receiver_expr ().get_locus (),
610 "unresolved type for receiver");
611 return;
612 }
613
614 size_t field_index = 0;
615 if (receiver->get_kind () == TyTy::TypeKind::ADT)
616 {
617 TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (receiver);
618 rust_assert (!adt->is_enum ());
619 rust_assert (adt->number_of_variants () == 1);
620
621 TyTy::VariantDef *variant = adt->get_variants ().at (0);
622 bool ok = variant->lookup_field (expr.get_field_name ().as_string (),
623 nullptr, &field_index);
624 rust_assert (ok);
625 }
626 else if (receiver->get_kind () == TyTy::TypeKind::REF)
627 {
628 TyTy::ReferenceType *r = static_cast<TyTy::ReferenceType *> (receiver);
629 TyTy::BaseType *b = r->get_base ();
630 rust_assert (b->get_kind () == TyTy::TypeKind::ADT);
631
632 TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (b);
633 rust_assert (!adt->is_enum ());
634 rust_assert (adt->number_of_variants () == 1);
635
636 TyTy::VariantDef *variant = adt->get_variants ().at (0);
637 bool ok = variant->lookup_field (expr.get_field_name ().as_string (),
638 nullptr, &field_index);
639 rust_assert (ok);
640
641 tree indirect = indirect_expression (receiver_ref, expr.get_locus ());
642 receiver_ref = indirect;
643 }
644
645 translated = Backend::struct_field_expression (receiver_ref, field_index,
646 expr.get_locus ());
647 }
648
649 void
650 CompileExpr::visit (HIR::QualifiedPathInExpression &expr)
651 {
652 translated = ResolvePathRef::Compile (expr, ctx);
653 }
654
655 void
656 CompileExpr::visit (HIR::PathInExpression &expr)
657 {
658 translated = ResolvePathRef::Compile (expr, ctx);
659 }
660
661 void
662 CompileExpr::visit (HIR::LoopExpr &expr)
663 {
664 TyTy::BaseType *block_tyty = nullptr;
665 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
666 &block_tyty))
667 {
668 rust_error_at (expr.get_locus (), "failed to lookup type of BlockExpr");
669 return;
670 }
671
672 fncontext fnctx = ctx->peek_fn ();
673 tree enclosing_scope = ctx->peek_enclosing_scope ();
674 tree block_type = TyTyResolveCompile::compile (ctx, block_tyty);
675
676 bool is_address_taken = false;
677 tree ret_var_stmt = NULL_TREE;
678 Bvariable *tmp
679 = Backend::temporary_variable (fnctx.fndecl, enclosing_scope, block_type,
680 NULL, is_address_taken, expr.get_locus (),
681 &ret_var_stmt);
682 ctx->add_statement (ret_var_stmt);
683 ctx->push_loop_context (tmp);
684
685 if (expr.has_loop_label ())
686 {
687 HIR::LoopLabel &loop_label = expr.get_loop_label ();
688 tree label
689 = Backend::label (fnctx.fndecl, loop_label.get_lifetime ().get_name (),
690 loop_label.get_locus ());
691 tree label_decl = Backend::label_definition_statement (label);
692 ctx->add_statement (label_decl);
693 ctx->insert_label_decl (
694 loop_label.get_lifetime ().get_mappings ().get_hirid (), label);
695 }
696
697 tree loop_begin_label = Backend::label (fnctx.fndecl, "", expr.get_locus ());
698 tree loop_begin_label_decl
699 = Backend::label_definition_statement (loop_begin_label);
700 ctx->add_statement (loop_begin_label_decl);
701 ctx->push_loop_begin_label (loop_begin_label);
702
703 tree code_block
704 = CompileBlock::compile (expr.get_loop_block (), ctx, nullptr);
705 tree loop_expr = Backend::loop_expression (code_block, expr.get_locus ());
706 ctx->add_statement (loop_expr);
707
708 ctx->pop_loop_context ();
709 translated = Backend::var_expression (tmp, expr.get_locus ());
710
711 ctx->pop_loop_begin_label ();
712 }
713
714 void
715 CompileExpr::visit (HIR::WhileLoopExpr &expr)
716 {
717 fncontext fnctx = ctx->peek_fn ();
718 if (expr.has_loop_label ())
719 {
720 HIR::LoopLabel &loop_label = expr.get_loop_label ();
721 tree label
722 = Backend::label (fnctx.fndecl, loop_label.get_lifetime ().get_name (),
723 loop_label.get_locus ());
724 tree label_decl = Backend::label_definition_statement (label);
725 ctx->add_statement (label_decl);
726 ctx->insert_label_decl (
727 loop_label.get_lifetime ().get_mappings ().get_hirid (), label);
728 }
729
730 std::vector<Bvariable *> locals;
731 location_t start_location = expr.get_loop_block ().get_locus ();
732 location_t end_location = expr.get_loop_block ().get_locus (); // FIXME
733
734 tree enclosing_scope = ctx->peek_enclosing_scope ();
735 tree loop_block = Backend::block (fnctx.fndecl, enclosing_scope, locals,
736 start_location, end_location);
737 ctx->push_block (loop_block);
738
739 tree loop_begin_label = Backend::label (fnctx.fndecl, "", expr.get_locus ());
740 tree loop_begin_label_decl
741 = Backend::label_definition_statement (loop_begin_label);
742 ctx->add_statement (loop_begin_label_decl);
743 ctx->push_loop_begin_label (loop_begin_label);
744
745 tree condition = CompileExpr::Compile (expr.get_predicate_expr (), ctx);
746 tree exit_condition = fold_build1_loc (expr.get_locus (), TRUTH_NOT_EXPR,
747 boolean_type_node, condition);
748 tree exit_expr = Backend::exit_expression (exit_condition, expr.get_locus ());
749 ctx->add_statement (exit_expr);
750
751 tree code_block_stmt
752 = CompileBlock::compile (expr.get_loop_block (), ctx, nullptr);
753 rust_assert (TREE_CODE (code_block_stmt) == BIND_EXPR);
754 ctx->add_statement (code_block_stmt);
755
756 ctx->pop_loop_begin_label ();
757 ctx->pop_block ();
758
759 tree loop_expr = Backend::loop_expression (loop_block, expr.get_locus ());
760 ctx->add_statement (loop_expr);
761 }
762
763 void
764 CompileExpr::visit (HIR::BreakExpr &expr)
765 {
766 if (expr.has_break_expr ())
767 {
768 tree compiled_expr = CompileExpr::Compile (expr.get_expr (), ctx);
769
770 Bvariable *loop_result_holder = ctx->peek_loop_context ();
771 tree result_reference
772 = Backend::var_expression (loop_result_holder,
773 expr.get_expr ().get_locus ());
774
775 tree assignment
776 = Backend::assignment_statement (result_reference, compiled_expr,
777 expr.get_locus ());
778 ctx->add_statement (assignment);
779 }
780
781 if (expr.has_label ())
782 {
783 NodeId resolved_node_id = UNKNOWN_NODEID;
784 if (flag_name_resolution_2_0)
785 {
786 auto &nr_ctx
787 = Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
788
789 if (auto id
790 = nr_ctx.lookup (expr.get_label ().get_mappings ().get_nodeid ()))
791 resolved_node_id = *id;
792 }
793 else
794 {
795 NodeId tmp = UNKNOWN_NODEID;
796 if (ctx->get_resolver ()->lookup_resolved_label (
797 expr.get_label ().get_mappings ().get_nodeid (), &tmp))
798 resolved_node_id = tmp;
799 }
800
801 if (resolved_node_id == UNKNOWN_NODEID)
802 {
803 rust_error_at (
804 expr.get_label ().get_locus (),
805 "failed to resolve compiled label for label %s",
806 expr.get_label ().get_mappings ().as_string ().c_str ());
807 return;
808 }
809
810 tl::optional<HirId> hid
811 = ctx->get_mappings ().lookup_node_to_hir (resolved_node_id);
812 if (!hid.has_value ())
813 {
814 rust_fatal_error (expr.get_locus (), "reverse lookup label failure");
815 return;
816 }
817 auto ref = hid.value ();
818
819 tree label = NULL_TREE;
820 if (!ctx->lookup_label_decl (ref, &label))
821 {
822 rust_error_at (expr.get_label ().get_locus (),
823 "failed to lookup compiled label");
824 return;
825 }
826
827 tree goto_label = Backend::goto_statement (label, expr.get_locus ());
828 ctx->add_statement (goto_label);
829 }
830 else
831 {
832 tree exit_expr
833 = Backend::exit_expression (Backend::boolean_constant_expression (true),
834 expr.get_locus ());
835 ctx->add_statement (exit_expr);
836 }
837 }
838
839 void
840 CompileExpr::visit (HIR::ContinueExpr &expr)
841 {
842 tree label = ctx->peek_loop_begin_label ();
843 if (expr.has_label ())
844 {
845 NodeId resolved_node_id = UNKNOWN_NODEID;
846 if (flag_name_resolution_2_0)
847 {
848 auto &nr_ctx
849 = Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
850
851 if (auto id
852 = nr_ctx.lookup (expr.get_label ().get_mappings ().get_nodeid ()))
853 resolved_node_id = *id;
854 }
855 else
856 {
857 NodeId tmp = UNKNOWN_NODEID;
858
859 if (ctx->get_resolver ()->lookup_resolved_label (
860 expr.get_label ().get_mappings ().get_nodeid (), &tmp))
861 resolved_node_id = tmp;
862 }
863
864 if (resolved_node_id == UNKNOWN_NODEID)
865 {
866 rust_error_at (
867 expr.get_label ().get_locus (),
868 "failed to resolve compiled label for label %s",
869 expr.get_label ().get_mappings ().as_string ().c_str ());
870 return;
871 }
872
873 tl::optional<HirId> hid
874 = ctx->get_mappings ().lookup_node_to_hir (resolved_node_id);
875 if (!hid.has_value ())
876 {
877 rust_fatal_error (expr.get_locus (), "reverse lookup label failure");
878 return;
879 }
880 auto ref = hid.value ();
881
882 if (!ctx->lookup_label_decl (ref, &label))
883 {
884 rust_error_at (expr.get_label ().get_locus (),
885 "failed to lookup compiled label");
886 return;
887 }
888 }
889
890 translated = Backend::goto_statement (label, expr.get_locus ());
891 }
892
893 void
894 CompileExpr::visit (HIR::BorrowExpr &expr)
895 {
896 tree main_expr = CompileExpr::Compile (expr.get_expr (), ctx);
897 if (RS_DST_FLAG_P (TREE_TYPE (main_expr)))
898 {
899 translated = main_expr;
900 return;
901 }
902
903 TyTy::BaseType *tyty = nullptr;
904 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
905 &tyty))
906 return;
907
908 tree expected_type = TyTyResolveCompile::compile (ctx, tyty);
909 translated = address_expression (main_expr, expr.get_locus (), expected_type);
910 }
911
912 void
913 CompileExpr::visit (HIR::DereferenceExpr &expr)
914 {
915 TyTy::BaseType *tyty = nullptr;
916 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
917 &tyty))
918 {
919 rust_fatal_error (expr.get_locus (),
920 "did not resolve type for this TupleExpr");
921 return;
922 }
923
924 tree main_expr = CompileExpr::Compile (expr.get_expr (), ctx);
925
926 // this might be an operator overload situation lets check
927 TyTy::FnType *fntype;
928 bool is_op_overload = ctx->get_tyctx ()->lookup_operator_overload (
929 expr.get_mappings ().get_hirid (), &fntype);
930 if (is_op_overload)
931 {
932 auto lang_item_type = LangItem::Kind::DEREF;
933 tree operator_overload_call
934 = resolve_operator_overload (lang_item_type, expr, main_expr, nullptr,
935 expr.get_expr (), tl::nullopt);
936
937 // rust deref always returns a reference from this overload then we can
938 // actually do the indirection
939 main_expr = operator_overload_call;
940 }
941
942 tree expected_type = TyTyResolveCompile::compile (ctx, tyty);
943 if (RS_DST_FLAG_P (TREE_TYPE (main_expr)) && RS_DST_FLAG_P (expected_type))
944 {
945 translated = main_expr;
946 return;
947 }
948
949 translated = indirect_expression (main_expr, expr.get_locus ());
950 }
951
952 void
953 CompileExpr::visit (HIR::LiteralExpr &expr)
954 {
955 TyTy::BaseType *tyty = nullptr;
956 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
957 &tyty))
958 return;
959
960 switch (expr.get_lit_type ())
961 {
962 case HIR::Literal::BOOL:
963 translated = compile_bool_literal (expr, tyty);
964 return;
965
966 case HIR::Literal::INT:
967 translated = compile_integer_literal (expr, tyty);
968 return;
969
970 case HIR::Literal::FLOAT:
971 translated = compile_float_literal (expr, tyty);
972 return;
973
974 case HIR::Literal::CHAR:
975 translated = compile_char_literal (expr, tyty);
976 return;
977
978 case HIR::Literal::BYTE:
979 translated = compile_byte_literal (expr, tyty);
980 return;
981
982 case HIR::Literal::STRING:
983 translated = compile_string_literal (expr, tyty);
984 return;
985
986 case HIR::Literal::BYTE_STRING:
987 translated = compile_byte_string_literal (expr, tyty);
988 return;
989 }
990 }
991
992 void
993 CompileExpr::visit (HIR::AssignmentExpr &expr)
994 {
995 auto lvalue = CompileExpr::Compile (expr.get_lhs (), ctx);
996 auto rvalue = CompileExpr::Compile (expr.get_rhs (), ctx);
997
998 // assignments are coercion sites so lets convert the rvalue if necessary
999 TyTy::BaseType *expected = nullptr;
1000 TyTy::BaseType *actual = nullptr;
1001
1002 bool ok;
1003 ok = ctx->get_tyctx ()->lookup_type (
1004 expr.get_lhs ().get_mappings ().get_hirid (), &expected);
1005 rust_assert (ok);
1006
1007 ok = ctx->get_tyctx ()->lookup_type (
1008 expr.get_rhs ().get_mappings ().get_hirid (), &actual);
1009 rust_assert (ok);
1010
1011 rvalue = coercion_site (expr.get_mappings ().get_hirid (), rvalue, actual,
1012 expected, expr.get_lhs ().get_locus (),
1013 expr.get_rhs ().get_locus ());
1014
1015 // rust_debug_loc (expr.get_locus (), "XXXXXX assignment");
1016 // debug_tree (rvalue);
1017 // debug_tree (lvalue);
1018
1019 tree assignment
1020 = Backend::assignment_statement (lvalue, rvalue, expr.get_locus ());
1021
1022 ctx->add_statement (assignment);
1023 }
1024
1025 // Helper for CompileExpr::visit (HIR::MatchExpr).
1026 // Check that the scrutinee of EXPR is a valid kind of expression to match on.
1027 // Return the TypeKind of the scrutinee if it is valid, or TyTy::TypeKind::ERROR
1028 // if not.
1029 static TyTy::TypeKind
1030 check_match_scrutinee (HIR::MatchExpr &expr, Context *ctx)
1031 {
1032 TyTy::BaseType *scrutinee_expr_tyty = nullptr;
1033 if (!ctx->get_tyctx ()->lookup_type (
1034 expr.get_scrutinee_expr ().get_mappings ().get_hirid (),
1035 &scrutinee_expr_tyty))
1036 {
1037 return TyTy::TypeKind::ERROR;
1038 }
1039
1040 TyTy::TypeKind scrutinee_kind = scrutinee_expr_tyty->get_kind ();
1041
1042 if (scrutinee_kind == TyTy::TypeKind::FLOAT)
1043 {
1044 // FIXME: CASE_LABEL_EXPR does not support floating point types.
1045 // Find another way to compile these.
1046 rust_sorry_at (expr.get_locus (),
1047 "match on floating-point types is not yet supported");
1048 }
1049
1050 TyTy::BaseType *expr_tyty = nullptr;
1051 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
1052 &expr_tyty))
1053 {
1054 return TyTy::TypeKind::ERROR;
1055 }
1056
1057 return scrutinee_kind;
1058 }
1059
1060 void
1061 CompileExpr::visit (HIR::MatchExpr &expr)
1062 {
1063 // https://gcc.gnu.org/onlinedocs/gccint/Basic-Statements.html#Basic-Statements
1064 // TODO
1065 // SWITCH_ALL_CASES_P is true if the switch includes a default label or the
1066 // case label ranges cover all possible values of the condition expression
1067
1068 TyTy::TypeKind scrutinee_kind = check_match_scrutinee (expr, ctx);
1069 if (scrutinee_kind == TyTy::TypeKind::ERROR)
1070 {
1071 translated = error_mark_node;
1072 return;
1073 }
1074
1075 TyTy::BaseType *expr_tyty = nullptr;
1076 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
1077 &expr_tyty))
1078 {
1079 translated = error_mark_node;
1080 return;
1081 }
1082
1083 // if the result of this expression is meant to be never type then we can
1084 // optimise this away but there is the case where match arms resolve to !
1085 // because of return statements we need to special case this
1086 if (!expr.has_match_arms () && expr_tyty->is<TyTy::NeverType> ())
1087 {
1088 translated = unit_expression (expr.get_locus ());
1089 return;
1090 }
1091
1092 fncontext fnctx = ctx->peek_fn ();
1093 Bvariable *tmp = NULL;
1094 tree enclosing_scope = ctx->peek_enclosing_scope ();
1095 tree block_type = TyTyResolveCompile::compile (ctx, expr_tyty);
1096
1097 bool is_address_taken = false;
1098 tree ret_var_stmt = nullptr;
1099 tmp = Backend::temporary_variable (fnctx.fndecl, enclosing_scope, block_type,
1100 NULL, is_address_taken, expr.get_locus (),
1101 &ret_var_stmt);
1102 ctx->add_statement (ret_var_stmt);
1103
1104 // lets compile the scrutinee expression
1105 tree match_scrutinee_rval
1106 = CompileExpr::Compile (expr.get_scrutinee_expr (), ctx);
1107
1108 Bvariable *match_scrutinee_tmp_var
1109 = Backend::temporary_variable (fnctx.fndecl, enclosing_scope,
1110 TREE_TYPE (match_scrutinee_rval), NULL,
1111 is_address_taken, expr.get_locus (),
1112 &ret_var_stmt);
1113 ctx->add_statement (ret_var_stmt);
1114
1115 tree match_scrutinee_expr = match_scrutinee_tmp_var->get_tree (
1116 expr.get_scrutinee_expr ().get_locus ());
1117
1118 tree assignment
1119 = Backend::assignment_statement (match_scrutinee_expr, match_scrutinee_rval,
1120 expr.get_locus ());
1121 ctx->add_statement (assignment);
1122
1123 // setup the end label so the cases can exit properly
1124 tree fndecl = fnctx.fndecl;
1125 location_t end_label_locus = expr.get_locus (); // FIXME
1126 tree end_label
1127 = Backend::label (fndecl, "" /* empty creates an artificial label */,
1128 end_label_locus);
1129 tree end_label_decl_statement
1130 = Backend::label_definition_statement (end_label);
1131
1132 for (auto &kase : expr.get_match_cases ())
1133 {
1134 // for now lets just get single pattern's working
1135 HIR::MatchArm &kase_arm = kase.get_arm ();
1136 rust_assert (kase_arm.get_patterns ().size () > 0);
1137
1138 for (auto &kase_pattern : kase_arm.get_patterns ())
1139 {
1140 // setup the match-arm-body-block
1141 location_t start_location = UNKNOWN_LOCATION; // FIXME
1142 location_t end_location = UNKNOWN_LOCATION; // FIXME
1143 tree arm_body_block = Backend::block (fndecl, enclosing_scope, {},
1144 start_location, end_location);
1145
1146 ctx->push_block (arm_body_block);
1147
1148 // setup the bindings for the block
1149 CompilePatternBindings::Compile (*kase_pattern, match_scrutinee_expr,
1150 ctx);
1151
1152 // compile the expr and setup the assignment if required when tmp !=
1153 // NULL
1154 location_t arm_locus = kase_arm.get_locus ();
1155 tree kase_expr_tree = CompileExpr::Compile (kase.get_expr (), ctx);
1156 tree result_reference = Backend::var_expression (tmp, arm_locus);
1157
1158 TyTy::BaseType *actual = nullptr;
1159 bool ok = ctx->get_tyctx ()->lookup_type (
1160 kase.get_expr ().get_mappings ().get_hirid (), &actual);
1161 rust_assert (ok);
1162
1163 tree coerced_result
1164 = coercion_site (kase.get_expr ().get_mappings ().get_hirid (),
1165 kase_expr_tree, actual, expr_tyty,
1166 expr.get_locus (), arm_locus);
1167
1168 tree assignment
1169 = Backend::assignment_statement (result_reference, coerced_result,
1170 arm_locus);
1171 ctx->add_statement (assignment);
1172
1173 // go to end label
1174 tree goto_end_label
1175 = build1_loc (arm_locus, GOTO_EXPR, void_type_node, end_label);
1176 ctx->add_statement (goto_end_label);
1177
1178 ctx->pop_block ();
1179
1180 tree check_expr
1181 = CompilePatternCheckExpr::Compile (*kase_pattern,
1182 match_scrutinee_expr, ctx);
1183
1184 tree check_stmt
1185 = Backend::if_statement (NULL_TREE, check_expr, arm_body_block,
1186 NULL_TREE, kase_pattern->get_locus ());
1187
1188 ctx->add_statement (check_stmt);
1189 }
1190 }
1191
1192 // setup the switch expression
1193 ctx->add_statement (end_label_decl_statement);
1194
1195 translated = Backend::var_expression (tmp, expr.get_locus ());
1196 }
1197
1198 void
1199 CompileExpr::visit (HIR::CallExpr &expr)
1200 {
1201 TyTy::BaseType *tyty = nullptr;
1202 if (!ctx->get_tyctx ()->lookup_type (
1203 expr.get_fnexpr ().get_mappings ().get_hirid (), &tyty))
1204 {
1205 rust_error_at (expr.get_locus (), "unknown type");
1206 return;
1207 }
1208
1209 // must be a tuple constructor
1210 bool is_adt_ctor = tyty->get_kind () == TyTy::TypeKind::ADT;
1211 if (is_adt_ctor)
1212 {
1213 rust_assert (tyty->get_kind () == TyTy::TypeKind::ADT);
1214 TyTy::ADTType *adt = static_cast<TyTy::ADTType *> (tyty);
1215 tree compiled_adt_type = TyTyResolveCompile::compile (ctx, tyty);
1216
1217 // what variant is it?
1218 int union_disriminator = -1;
1219 TyTy::VariantDef *variant = nullptr;
1220 if (!adt->is_enum ())
1221 {
1222 rust_assert (adt->number_of_variants () == 1);
1223 variant = adt->get_variants ().at (0);
1224 }
1225 else
1226 {
1227 HirId variant_id;
1228 bool ok = ctx->get_tyctx ()->lookup_variant_definition (
1229 expr.get_fnexpr ().get_mappings ().get_hirid (), &variant_id);
1230 rust_assert (ok);
1231
1232 ok = adt->lookup_variant_by_id (variant_id, &variant,
1233 &union_disriminator);
1234 rust_assert (ok);
1235 }
1236
1237 // this assumes all fields are in order from type resolution and if a
1238 // base struct was specified those fields are filed via accessors
1239 std::vector<tree> arguments;
1240 for (size_t i = 0; i < expr.num_params (); i++)
1241 {
1242 auto &argument = expr.get_arguments ().at (i);
1243 auto rvalue = CompileExpr::Compile (*argument, ctx);
1244
1245 // assignments are coercion sites so lets convert the rvalue if
1246 // necessary
1247 auto respective_field = variant->get_field_at_index (i);
1248 auto expected = respective_field->get_field_type ();
1249
1250 TyTy::BaseType *actual = nullptr;
1251 bool ok = ctx->get_tyctx ()->lookup_type (
1252 argument->get_mappings ().get_hirid (), &actual);
1253 rust_assert (ok);
1254
1255 // coerce it if required
1256 location_t lvalue_locus
1257 = ctx->get_mappings ().lookup_location (expected->get_ty_ref ());
1258 location_t rvalue_locus = argument->get_locus ();
1259 rvalue
1260 = coercion_site (argument->get_mappings ().get_hirid (), rvalue,
1261 actual, expected, lvalue_locus, rvalue_locus);
1262
1263 // add it to the list
1264 arguments.push_back (rvalue);
1265 }
1266
1267 if (!adt->is_enum ())
1268 {
1269 translated
1270 = Backend::constructor_expression (compiled_adt_type,
1271 adt->is_enum (), arguments,
1272 union_disriminator,
1273 expr.get_locus ());
1274 return;
1275 }
1276
1277 HIR::Expr &discrim_expr = variant->get_discriminant ();
1278 tree discrim_expr_node = CompileExpr::Compile (discrim_expr, ctx);
1279 tree folded_discrim_expr = fold_expr (discrim_expr_node);
1280 tree qualifier = folded_discrim_expr;
1281
1282 tree enum_root_files = TYPE_FIELDS (compiled_adt_type);
1283 tree payload_root = DECL_CHAIN (enum_root_files);
1284
1285 tree payload
1286 = Backend::constructor_expression (TREE_TYPE (payload_root), true,
1287 {arguments}, union_disriminator,
1288 expr.get_locus ());
1289
1290 std::vector<tree> ctor_arguments = {qualifier, payload};
1291 translated = Backend::constructor_expression (compiled_adt_type, false,
1292 ctor_arguments, -1,
1293 expr.get_locus ());
1294
1295 return;
1296 }
1297
1298 auto get_parameter_tyty_at_index
1299 = [] (const TyTy::BaseType *base, size_t index,
1300 TyTy::BaseType **result) -> bool {
1301 bool is_fn = base->get_kind () == TyTy::TypeKind::FNDEF
1302 || base->get_kind () == TyTy::TypeKind::FNPTR;
1303 rust_assert (is_fn);
1304
1305 if (base->get_kind () == TyTy::TypeKind::FNPTR)
1306 {
1307 const TyTy::FnPtr *fn = static_cast<const TyTy::FnPtr *> (base);
1308 *result = fn->get_param_type_at (index);
1309
1310 return true;
1311 }
1312
1313 const TyTy::FnType *fn = static_cast<const TyTy::FnType *> (base);
1314 auto &param = fn->param_at (index);
1315 *result = param.get_type ();
1316
1317 return true;
1318 };
1319
1320 auto fn_address = CompileExpr::Compile (expr.get_fnexpr (), ctx);
1321
1322 // is this a closure call?
1323 bool possible_trait_call
1324 = generate_possible_fn_trait_call (expr, fn_address, &translated);
1325 if (possible_trait_call)
1326 return;
1327
1328 bool is_variadic = false;
1329 size_t required_num_args = expr.get_arguments ().size ();
1330
1331 if (tyty->get_kind () == TyTy::TypeKind::FNDEF)
1332 {
1333 const TyTy::FnType *fn = static_cast<const TyTy::FnType *> (tyty);
1334 required_num_args = fn->num_params ();
1335 is_variadic = fn->is_variadic ();
1336 }
1337 else if (tyty->get_kind () == TyTy::TypeKind::FNPTR)
1338 {
1339 const TyTy::FnPtr *fn = static_cast<const TyTy::FnPtr *> (tyty);
1340 required_num_args = fn->num_params ();
1341 }
1342
1343 std::vector<tree> args;
1344 for (size_t i = 0; i < expr.get_arguments ().size (); i++)
1345 {
1346 auto &argument = expr.get_arguments ().at (i);
1347 auto rvalue = CompileExpr::Compile (*argument, ctx);
1348
1349 if (is_variadic && i >= required_num_args)
1350 {
1351 args.push_back (rvalue);
1352 continue;
1353 }
1354
1355 // assignments are coercion sites so lets convert the rvalue if
1356 // necessary
1357 bool ok;
1358 TyTy::BaseType *expected = nullptr;
1359 ok = get_parameter_tyty_at_index (tyty, i, &expected);
1360 rust_assert (ok);
1361
1362 TyTy::BaseType *actual = nullptr;
1363 ok = ctx->get_tyctx ()->lookup_type (
1364 argument->get_mappings ().get_hirid (), &actual);
1365 rust_assert (ok);
1366
1367 // coerce it if required
1368 location_t lvalue_locus
1369 = ctx->get_mappings ().lookup_location (expected->get_ty_ref ());
1370 location_t rvalue_locus = argument->get_locus ();
1371 rvalue = coercion_site (argument->get_mappings ().get_hirid (), rvalue,
1372 actual, expected, lvalue_locus, rvalue_locus);
1373
1374 // add it to the list
1375 args.push_back (rvalue);
1376 }
1377
1378 // must be a regular call to a function
1379 translated
1380 = Backend::call_expression (fn_address, args, nullptr, expr.get_locus ());
1381 }
1382
1383 void
1384 CompileExpr::visit (HIR::MethodCallExpr &expr)
1385 {
1386 // method receiver
1387 tree self = CompileExpr::Compile (expr.get_receiver (), ctx);
1388
1389 // lookup the expected function type
1390 TyTy::BaseType *lookup_fntype = nullptr;
1391 bool ok = ctx->get_tyctx ()->lookup_type (
1392 expr.get_method_name ().get_mappings ().get_hirid (), &lookup_fntype);
1393 rust_assert (ok);
1394 rust_assert (lookup_fntype->get_kind () == TyTy::TypeKind::FNDEF);
1395 TyTy::FnType *fntype = static_cast<TyTy::FnType *> (lookup_fntype);
1396
1397 TyTy::BaseType *receiver = nullptr;
1398 ok = ctx->get_tyctx ()->lookup_type (
1399 expr.get_receiver ().get_mappings ().get_hirid (), &receiver);
1400 rust_assert (ok);
1401
1402 bool is_dyn_dispatch
1403 = receiver->get_root ()->get_kind () == TyTy::TypeKind::DYNAMIC;
1404 bool is_generic_receiver = receiver->get_kind () == TyTy::TypeKind::PARAM;
1405 if (is_generic_receiver)
1406 {
1407 TyTy::ParamType *p = static_cast<TyTy::ParamType *> (receiver);
1408 receiver = p->resolve ();
1409 }
1410
1411 tree fn_expr = error_mark_node;
1412 if (is_dyn_dispatch)
1413 {
1414 const TyTy::DynamicObjectType *dyn
1415 = static_cast<const TyTy::DynamicObjectType *> (receiver->get_root ());
1416 fn_expr
1417 = get_fn_addr_from_dyn (dyn, receiver, fntype, self, expr.get_locus ());
1418 self = get_receiver_from_dyn (dyn, receiver, fntype, self,
1419 expr.get_locus ());
1420 }
1421 else
1422 // lookup compiled functions since it may have already been compiled
1423 fn_expr = resolve_method_address (fntype, receiver, expr.get_locus ());
1424
1425 // lookup the autoderef mappings
1426 HirId autoderef_mappings_id
1427 = expr.get_receiver ().get_mappings ().get_hirid ();
1428 std::vector<Resolver::Adjustment> *adjustments = nullptr;
1429 ok = ctx->get_tyctx ()->lookup_autoderef_mappings (autoderef_mappings_id,
1430 &adjustments);
1431 rust_assert (ok);
1432
1433 // apply adjustments for the fn call
1434 self = resolve_adjustements (*adjustments, self,
1435 expr.get_receiver ().get_locus ());
1436
1437 std::vector<tree> args;
1438 args.push_back (self); // adjusted self
1439
1440 // normal args
1441 for (size_t i = 0; i < expr.get_arguments ().size (); i++)
1442 {
1443 auto &argument = expr.get_arguments ().at (i);
1444 auto rvalue = CompileExpr::Compile (*argument, ctx);
1445
1446 // assignments are coercion sites so lets convert the rvalue if
1447 // necessary, offset from the already adjusted implicit self
1448 bool ok;
1449 TyTy::BaseType *expected = fntype->param_at (i + 1).get_type ();
1450
1451 TyTy::BaseType *actual = nullptr;
1452 ok = ctx->get_tyctx ()->lookup_type (
1453 argument->get_mappings ().get_hirid (), &actual);
1454 rust_assert (ok);
1455
1456 // coerce it if required
1457 location_t lvalue_locus
1458 = ctx->get_mappings ().lookup_location (expected->get_ty_ref ());
1459 location_t rvalue_locus = argument->get_locus ();
1460 rvalue = coercion_site (argument->get_mappings ().get_hirid (), rvalue,
1461 actual, expected, lvalue_locus, rvalue_locus);
1462
1463 // add it to the list
1464 args.push_back (rvalue);
1465 }
1466
1467 translated
1468 = Backend::call_expression (fn_expr, args, nullptr, expr.get_locus ());
1469 }
1470
1471 tree
1472 CompileExpr::get_fn_addr_from_dyn (const TyTy::DynamicObjectType *dyn,
1473 TyTy::BaseType *receiver,
1474 TyTy::FnType *fntype, tree receiver_ref,
1475 location_t expr_locus)
1476 {
1477 size_t offs = 0;
1478 const Resolver::TraitItemReference *ref = nullptr;
1479 for (auto &bound : dyn->get_object_items ())
1480 {
1481 const Resolver::TraitItemReference *item = bound.first;
1482 auto t = item->get_tyty ();
1483 rust_assert (t->get_kind () == TyTy::TypeKind::FNDEF);
1484 auto ft = static_cast<TyTy::FnType *> (t);
1485
1486 if (ft->get_id () == fntype->get_id ())
1487 {
1488 ref = item;
1489 break;
1490 }
1491 offs++;
1492 }
1493
1494 if (ref == nullptr)
1495 return error_mark_node;
1496
1497 // cast it to the correct fntype
1498 tree expected_fntype = TyTyResolveCompile::compile (ctx, fntype, true);
1499 tree idx = build_int_cst (size_type_node, offs);
1500
1501 tree vtable_ptr
1502 = Backend::struct_field_expression (receiver_ref, 1, expr_locus);
1503 tree vtable_array_access
1504 = build4_loc (expr_locus, ARRAY_REF, TREE_TYPE (TREE_TYPE (vtable_ptr)),
1505 vtable_ptr, idx, NULL_TREE, NULL_TREE);
1506
1507 tree vcall = build3_loc (expr_locus, OBJ_TYPE_REF, expected_fntype,
1508 vtable_array_access, receiver_ref, idx);
1509
1510 return vcall;
1511 }
1512
1513 tree
1514 CompileExpr::get_receiver_from_dyn (const TyTy::DynamicObjectType *dyn,
1515 TyTy::BaseType *receiver,
1516 TyTy::FnType *fntype, tree receiver_ref,
1517 location_t expr_locus)
1518 {
1519 // access the offs + 1 for the fnptr and offs=0 for the reciever obj
1520 return Backend::struct_field_expression (receiver_ref, 0, expr_locus);
1521 }
1522
1523 tree
1524 CompileExpr::resolve_operator_overload (
1525 LangItem::Kind lang_item_type, HIR::OperatorExprMeta expr, tree lhs, tree rhs,
1526 HIR::Expr &lhs_expr, tl::optional<std::reference_wrapper<HIR::Expr>> rhs_expr,
1527 HIR::PathIdentSegment specified_segment)
1528 {
1529 TyTy::FnType *fntype;
1530 bool is_op_overload = ctx->get_tyctx ()->lookup_operator_overload (
1531 expr.get_mappings ().get_hirid (), &fntype);
1532 rust_assert (is_op_overload);
1533
1534 TyTy::BaseType *receiver = nullptr;
1535 bool ok
1536 = ctx->get_tyctx ()->lookup_type (lhs_expr.get_mappings ().get_hirid (),
1537 &receiver);
1538 rust_assert (ok);
1539
1540 bool is_generic_receiver = receiver->get_kind () == TyTy::TypeKind::PARAM;
1541 if (is_generic_receiver)
1542 {
1543 TyTy::ParamType *p = static_cast<TyTy::ParamType *> (receiver);
1544 receiver = p->resolve ();
1545 }
1546
1547 // lookup compiled functions since it may have already been compiled
1548 HIR::PathIdentSegment segment_name
1549 = specified_segment.is_error ()
1550 ? HIR::PathIdentSegment (LangItem::ToString (lang_item_type))
1551 : specified_segment;
1552 tree fn_expr = resolve_method_address (fntype, receiver, expr.get_locus ());
1553
1554 // lookup the autoderef mappings
1555 std::vector<Resolver::Adjustment> *adjustments = nullptr;
1556 ok = ctx->get_tyctx ()->lookup_autoderef_mappings (
1557 expr.get_lvalue_mappings ().get_hirid (), &adjustments);
1558 rust_assert (ok);
1559
1560 // apply adjustments for the fn call
1561 tree self = resolve_adjustements (*adjustments, lhs, lhs_expr.get_locus ());
1562
1563 std::vector<tree> args;
1564 args.push_back (self); // adjusted self
1565 if (rhs != nullptr) // can be null for negation_expr (unary ones)
1566 args.push_back (rhs);
1567
1568 return Backend::call_expression (fn_expr, args, nullptr, expr.get_locus ());
1569 }
1570
1571 tree
1572 CompileExpr::compile_bool_literal (const HIR::LiteralExpr &expr,
1573 const TyTy::BaseType *tyty)
1574 {
1575 rust_assert (expr.get_lit_type () == HIR::Literal::BOOL);
1576
1577 const auto literal_value = expr.get_literal ();
1578 bool bval = literal_value.as_string ().compare ("true") == 0;
1579 return Backend::boolean_constant_expression (bval);
1580 }
1581
1582 tree
1583 CompileExpr::compile_integer_literal (const HIR::LiteralExpr &expr,
1584 const TyTy::BaseType *tyty)
1585 {
1586 rust_assert (expr.get_lit_type () == HIR::Literal::INT);
1587 const auto literal_value = expr.get_literal ();
1588
1589 tree type = TyTyResolveCompile::compile (ctx, tyty);
1590
1591 mpz_t ival;
1592 if (mpz_init_set_str (ival, literal_value.as_string ().c_str (), 10) != 0)
1593 {
1594 rust_error_at (expr.get_locus (), "bad number in literal");
1595 return error_mark_node;
1596 }
1597
1598 mpz_t type_min;
1599 mpz_t type_max;
1600 mpz_init (type_min);
1601 mpz_init (type_max);
1602 get_type_static_bounds (type, type_min, type_max);
1603
1604 if (expr.is_negative ())
1605 {
1606 mpz_neg (ival, ival);
1607 }
1608 if (mpz_cmp (ival, type_min) < 0 || mpz_cmp (ival, type_max) > 0)
1609 {
1610 rust_error_at (expr.get_locus (),
1611 "integer overflows the respective type %qs",
1612 tyty->get_name ().c_str ());
1613 return error_mark_node;
1614 }
1615
1616 tree result = wide_int_to_tree (type, wi::from_mpz (type, ival, true));
1617
1618 mpz_clear (type_min);
1619 mpz_clear (type_max);
1620 mpz_clear (ival);
1621
1622 return result;
1623 }
1624
1625 tree
1626 CompileExpr::compile_float_literal (const HIR::LiteralExpr &expr,
1627 const TyTy::BaseType *tyty)
1628 {
1629 rust_assert (expr.get_lit_type () == HIR::Literal::FLOAT);
1630 const auto literal_value = expr.get_literal ();
1631
1632 tree type = TyTyResolveCompile::compile (ctx, tyty);
1633
1634 mpfr_t fval;
1635 if (mpfr_init_set_str (fval, literal_value.as_string ().c_str (), 10,
1636 MPFR_RNDN)
1637 != 0)
1638 {
1639 rust_error_at (expr.get_locus (), "bad number in literal");
1640 return error_mark_node;
1641 }
1642
1643 // taken from:
1644 // see go/gofrontend/expressions.cc:check_float_type
1645 bool real_value_overflow;
1646
1647 if (mpfr_regular_p (fval) != 0)
1648 {
1649 mpfr_exp_t exp = mpfr_get_exp (fval);
1650 mpfr_exp_t min_exp;
1651 mpfr_exp_t max_exp;
1652
1653 /*
1654 * By convention, the radix point of the significand is just before the
1655 * first digit (which is always 1 due to normalization), like in the C
1656 * language, but unlike in IEEE 754 (thus, for a given number, the
1657 * exponent values in MPFR and in IEEE 754 differ by 1).
1658 */
1659 switch (TYPE_PRECISION (type))
1660 {
1661 case 32:
1662 min_exp = -128 + 1;
1663 max_exp = 127 + 1;
1664 break;
1665 case 64:
1666 min_exp = -1024 + 1;
1667 max_exp = 1023 + 1;
1668 break;
1669 default:
1670 rust_error_at (expr.get_locus (),
1671 "precision of type %<%s%> not supported",
1672 tyty->get_name ().c_str ());
1673 return error_mark_node;
1674 }
1675 real_value_overflow = exp < min_exp || exp > max_exp;
1676 }
1677 else
1678 {
1679 real_value_overflow = false;
1680 }
1681
1682 REAL_VALUE_TYPE r1;
1683 real_from_mpfr (&r1, fval, type, GMP_RNDN);
1684 REAL_VALUE_TYPE r2;
1685 real_convert (&r2, TYPE_MODE (type), &r1);
1686
1687 tree real_value = build_real (type, r2);
1688 if (TREE_OVERFLOW (real_value) || real_value_overflow)
1689 {
1690 rust_error_at (expr.get_locus (),
1691 "decimal overflows the respective type %qs",
1692 tyty->get_name ().c_str ());
1693 return error_mark_node;
1694 }
1695
1696 return real_value;
1697 }
1698
1699 tree
1700 CompileExpr::compile_char_literal (const HIR::LiteralExpr &expr,
1701 const TyTy::BaseType *tyty)
1702 {
1703 rust_assert (expr.get_lit_type () == HIR::Literal::CHAR);
1704 const auto literal_value = expr.get_literal ();
1705
1706 // FIXME needs wchar_t
1707 char c = literal_value.as_string ().c_str ()[0];
1708 return Backend::wchar_constant_expression (c);
1709 }
1710
1711 tree
1712 CompileExpr::compile_byte_literal (const HIR::LiteralExpr &expr,
1713 const TyTy::BaseType *tyty)
1714 {
1715 rust_assert (expr.get_lit_type () == HIR::Literal::BYTE);
1716 const auto literal_value = expr.get_literal ();
1717
1718 tree type = TyTyResolveCompile::compile (ctx, tyty);
1719 char c = literal_value.as_string ().c_str ()[0];
1720 return build_int_cst (type, c);
1721 }
1722
1723 tree
1724 CompileExpr::compile_string_literal (const HIR::LiteralExpr &expr,
1725 const TyTy::BaseType *tyty)
1726 {
1727 tree fat_pointer = TyTyResolveCompile::compile (ctx, tyty);
1728
1729 rust_assert (expr.get_lit_type () == HIR::Literal::STRING);
1730 const auto literal_value = expr.get_literal ();
1731
1732 auto base = Backend::string_constant_expression (literal_value.as_string ());
1733 tree data = address_expression (base, expr.get_locus ());
1734
1735 TyTy::BaseType *usize = nullptr;
1736 bool ok = ctx->get_tyctx ()->lookup_builtin ("usize", &usize);
1737 rust_assert (ok);
1738 tree type = TyTyResolveCompile::compile (ctx, usize);
1739
1740 tree size = build_int_cstu (type, literal_value.as_string ().size ());
1741
1742 return Backend::constructor_expression (fat_pointer, false, {data, size}, -1,
1743 expr.get_locus ());
1744 }
1745
1746 tree
1747 CompileExpr::compile_byte_string_literal (const HIR::LiteralExpr &expr,
1748 const TyTy::BaseType *tyty)
1749 {
1750 rust_assert (expr.get_lit_type () == HIR::Literal::BYTE_STRING);
1751
1752 // the type here is &[ty; capacity]
1753 rust_assert (tyty->get_kind () == TyTy::TypeKind::REF);
1754 const auto ref_tyty = static_cast<const TyTy::ReferenceType *> (tyty);
1755 auto base_tyty = ref_tyty->get_base ();
1756 rust_assert (base_tyty->get_kind () == TyTy::TypeKind::ARRAY);
1757 auto array_tyty = static_cast<TyTy::ArrayType *> (base_tyty);
1758
1759 std::string value_str = expr.get_literal ().as_string ();
1760 std::vector<tree> vals;
1761 std::vector<unsigned long> indexes;
1762 for (size_t i = 0; i < value_str.size (); i++)
1763 {
1764 char b = value_str.at (i);
1765 tree bb = Backend::char_constant_expression (b);
1766 vals.push_back (bb);
1767 indexes.push_back (i);
1768 }
1769
1770 tree array_type = TyTyResolveCompile::compile (ctx, array_tyty);
1771 tree constructed
1772 = Backend::array_constructor_expression (array_type, indexes, vals,
1773 expr.get_locus ());
1774
1775 return address_expression (constructed, expr.get_locus ());
1776 }
1777
1778 tree
1779 CompileExpr::type_cast_expression (tree type_to_cast_to, tree expr_tree,
1780 location_t location)
1781 {
1782 if (type_to_cast_to == error_mark_node || expr_tree == error_mark_node
1783 || TREE_TYPE (expr_tree) == error_mark_node)
1784 return error_mark_node;
1785
1786 if (Backend::type_size (type_to_cast_to) == 0
1787 || TREE_TYPE (expr_tree) == void_type_node)
1788 {
1789 // Do not convert zero-sized types.
1790 return expr_tree;
1791 }
1792 else if (TREE_CODE (type_to_cast_to) == INTEGER_TYPE)
1793 {
1794 tree cast = convert_to_integer (type_to_cast_to, expr_tree);
1795 // FIXME check for TREE_OVERFLOW?
1796 return cast;
1797 }
1798 else if (TREE_CODE (type_to_cast_to) == REAL_TYPE)
1799 {
1800 tree cast = convert_to_real (type_to_cast_to, expr_tree);
1801 // FIXME
1802 // We might need to check that the tree is MAX val and thusly saturate it
1803 // to inf. we can get the bounds and check the value if its >= or <= to
1804 // the min and max bounds
1805 //
1806 // https://github.com/Rust-GCC/gccrs/issues/635
1807 return cast;
1808 }
1809 else if (TREE_CODE (type_to_cast_to) == COMPLEX_TYPE)
1810 {
1811 return convert_to_complex (type_to_cast_to, expr_tree);
1812 }
1813 else if (TREE_CODE (type_to_cast_to) == POINTER_TYPE
1814 && TREE_CODE (TREE_TYPE (expr_tree)) == INTEGER_TYPE)
1815 {
1816 return convert_to_pointer (type_to_cast_to, expr_tree);
1817 }
1818 else if (TREE_CODE (type_to_cast_to) == RECORD_TYPE
1819 || TREE_CODE (type_to_cast_to) == ARRAY_TYPE)
1820 {
1821 return fold_build1_loc (location, VIEW_CONVERT_EXPR, type_to_cast_to,
1822 expr_tree);
1823 }
1824 else if (TREE_CODE (type_to_cast_to) == POINTER_TYPE
1825 && RS_DST_FLAG (TREE_TYPE (expr_tree)))
1826 {
1827 // returning a raw cast using NOP_EXPR seems to resut in an ICE:
1828 //
1829 // Analyzing compilation unit
1830 // Performing interprocedural optimizations
1831 // <*free_lang_data> {heap 2644k} <visibility> {heap 2644k}
1832 // <build_ssa_passes> {heap 2644k} <opt_local_passes> {heap 2644k}during
1833 // GIMPLE pass: cddce
1834 // In function ‘*T::as_ptr<i32>’:
1835 // rust1: internal compiler error: in propagate_necessity, at
1836 // tree-ssa-dce.cc:984 0x1d5b43e propagate_necessity
1837 // ../../gccrs/gcc/tree-ssa-dce.cc:984
1838 // 0x1d5e180 perform_tree_ssa_dce
1839 // ../../gccrs/gcc/tree-ssa-dce.cc:1876
1840 // 0x1d5e2c8 tree_ssa_cd_dce
1841 // ../../gccrs/gcc/tree-ssa-dce.cc:1920
1842 // 0x1d5e49a execute
1843 // ../../gccrs/gcc/tree-ssa-dce.cc:1992
1844
1845 // this is returning the direct raw pointer of the slice an assumes a very
1846 // specific layout
1847 return Backend::struct_field_expression (expr_tree, 0, location);
1848 }
1849
1850 return fold_convert_loc (location, type_to_cast_to, expr_tree);
1851 }
1852
1853 void
1854 CompileExpr::visit (HIR::ArrayExpr &expr)
1855 {
1856 TyTy::BaseType *tyty = nullptr;
1857 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
1858 &tyty))
1859 {
1860 rust_fatal_error (expr.get_locus (),
1861 "did not resolve type for this array expr");
1862 return;
1863 }
1864
1865 tree array_type = TyTyResolveCompile::compile (ctx, tyty);
1866 if (TREE_CODE (array_type) != ARRAY_TYPE)
1867 {
1868 translated = error_mark_node;
1869 return;
1870 }
1871
1872 rust_assert (tyty->get_kind () == TyTy::TypeKind::ARRAY);
1873 const TyTy::ArrayType &array_tyty
1874 = static_cast<const TyTy::ArrayType &> (*tyty);
1875
1876 HIR::ArrayElems &elements = expr.get_internal_elements ();
1877 switch (elements.get_array_expr_type ())
1878 {
1879 case HIR::ArrayElems::ArrayExprType::VALUES: {
1880 HIR::ArrayElemsValues &elems
1881 = static_cast<HIR::ArrayElemsValues &> (elements);
1882 translated
1883 = array_value_expr (expr.get_locus (), array_tyty, array_type, elems);
1884 }
1885 return;
1886
1887 case HIR::ArrayElems::ArrayExprType::COPIED:
1888 HIR::ArrayElemsCopied &elems
1889 = static_cast<HIR::ArrayElemsCopied &> (elements);
1890 translated
1891 = array_copied_expr (expr.get_locus (), array_tyty, array_type, elems);
1892 }
1893 }
1894
1895 tree
1896 CompileExpr::array_value_expr (location_t expr_locus,
1897 const TyTy::ArrayType &array_tyty,
1898 tree array_type, HIR::ArrayElemsValues &elems)
1899 {
1900 std::vector<unsigned long> indexes;
1901 std::vector<tree> constructor;
1902 size_t i = 0;
1903 for (auto &elem : elems.get_values ())
1904 {
1905 tree translated_expr = CompileExpr::Compile (*elem, ctx);
1906 if (translated_expr == error_mark_node)
1907 {
1908 rich_location r (line_table, expr_locus);
1909 r.add_fixit_replace (elem->get_locus (), "not a value");
1910 rust_error_at (r, ErrorCode::E0423, "expected value");
1911 return error_mark_node;
1912 }
1913
1914 constructor.push_back (translated_expr);
1915 indexes.push_back (i++);
1916 }
1917
1918 return Backend::array_constructor_expression (array_type, indexes,
1919 constructor, expr_locus);
1920 }
1921
1922 tree
1923 CompileExpr::array_copied_expr (location_t expr_locus,
1924 const TyTy::ArrayType &array_tyty,
1925 tree array_type, HIR::ArrayElemsCopied &elems)
1926 {
1927 // see gcc/cp/typeck2.cc:1369-1401
1928 gcc_assert (TREE_CODE (array_type) == ARRAY_TYPE);
1929 tree domain = TYPE_DOMAIN (array_type);
1930 if (!domain)
1931 return error_mark_node;
1932
1933 if (!TREE_CONSTANT (TYPE_MAX_VALUE (domain)))
1934 {
1935 rust_error_at (expr_locus, "non const capacity domain %qT", array_type);
1936 return error_mark_node;
1937 }
1938
1939 ctx->push_const_context ();
1940 tree capacity_expr = CompileExpr::Compile (elems.get_num_copies_expr (), ctx);
1941 ctx->pop_const_context ();
1942
1943 if (!TREE_CONSTANT (capacity_expr))
1944 {
1945 rust_error_at (expr_locus, "non const num copies %qT", array_type);
1946 return error_mark_node;
1947 }
1948
1949 // get the compiled value
1950 tree translated_expr = CompileExpr::Compile (elems.get_elem_to_copy (), ctx);
1951
1952 tree max_domain = TYPE_MAX_VALUE (domain);
1953 tree min_domain = TYPE_MIN_VALUE (domain);
1954
1955 auto max = wi::to_offset (max_domain);
1956 auto min = wi::to_offset (min_domain);
1957 auto precision = TYPE_PRECISION (TREE_TYPE (domain));
1958 auto sign = TYPE_SIGN (TREE_TYPE (domain));
1959 unsigned HOST_WIDE_INT len
1960 = wi::ext (max - min + 1, precision, sign).to_uhwi ();
1961
1962 // In a const context we must initialize the entire array, which entails
1963 // allocating for each element. If the user wants a huge array, we will OOM
1964 // and die horribly.
1965 if (ctx->const_context_p ())
1966 {
1967 size_t idx = 0;
1968 std::vector<unsigned long> indexes;
1969 std::vector<tree> constructor;
1970 for (unsigned HOST_WIDE_INT i = 0; i < len; i++)
1971 {
1972 constructor.push_back (translated_expr);
1973 indexes.push_back (idx++);
1974 }
1975
1976 return Backend::array_constructor_expression (array_type, indexes,
1977 constructor, expr_locus);
1978 }
1979
1980 else
1981 {
1982 // Create a new block scope in which to initialize the array
1983 tree fndecl = NULL_TREE;
1984 if (ctx->in_fn ())
1985 fndecl = ctx->peek_fn ().fndecl;
1986
1987 std::vector<Bvariable *> locals;
1988 tree enclosing_scope = ctx->peek_enclosing_scope ();
1989 tree init_block = Backend::block (fndecl, enclosing_scope, locals,
1990 expr_locus, expr_locus);
1991 ctx->push_block (init_block);
1992
1993 tree tmp;
1994 tree stmts = Backend::array_initializer (fndecl, init_block, array_type,
1995 capacity_expr, translated_expr,
1996 &tmp, expr_locus);
1997 ctx->add_statement (stmts);
1998
1999 tree block = ctx->pop_block ();
2000
2001 // The result is a compound expression which creates a temporary array,
2002 // initializes all the elements in a loop, and then yeilds the array.
2003 return Backend::compound_expression (block, tmp, expr_locus);
2004 }
2005 }
2006
2007 tree
2008 HIRCompileBase::resolve_adjustements (
2009 std::vector<Resolver::Adjustment> &adjustments, tree expression,
2010 location_t locus)
2011 {
2012 tree e = expression;
2013 for (auto &adjustment : adjustments)
2014 {
2015 if (e == error_mark_node)
2016 return error_mark_node;
2017
2018 switch (adjustment.get_type ())
2019 {
2020 case Resolver::Adjustment::AdjustmentType::ERROR:
2021 return error_mark_node;
2022
2023 case Resolver::Adjustment::AdjustmentType::IMM_REF:
2024 case Resolver::Adjustment::AdjustmentType::MUT_REF: {
2025 if (!RS_DST_FLAG (TREE_TYPE (e)))
2026 {
2027 e = address_expression (e, locus);
2028 }
2029 }
2030 break;
2031
2032 case Resolver::Adjustment::AdjustmentType::DEREF:
2033 case Resolver::Adjustment::AdjustmentType::DEREF_MUT:
2034 e = resolve_deref_adjustment (adjustment, e, locus);
2035 break;
2036
2037 case Resolver::Adjustment::AdjustmentType::INDIRECTION:
2038 e = resolve_indirection_adjustment (adjustment, e, locus);
2039 break;
2040
2041 case Resolver::Adjustment::AdjustmentType::UNSIZE:
2042 e = resolve_unsized_adjustment (adjustment, e, locus);
2043 break;
2044 }
2045 }
2046
2047 return e;
2048 }
2049
2050 tree
2051 HIRCompileBase::resolve_deref_adjustment (Resolver::Adjustment &adjustment,
2052 tree expression, location_t locus)
2053 {
2054 rust_assert (adjustment.is_deref_adjustment ()
2055 || adjustment.is_deref_mut_adjustment ());
2056 rust_assert (adjustment.has_operator_overload ());
2057
2058 TyTy::FnType *lookup = adjustment.get_deref_operator_fn ();
2059 TyTy::BaseType *receiver = adjustment.get_actual ();
2060 tree fn_address = resolve_method_address (lookup, receiver, locus);
2061
2062 // does it need a reference to call
2063 tree adjusted_argument = expression;
2064 bool needs_borrow = adjustment.get_deref_adjustment_type ()
2065 != Resolver::Adjustment::AdjustmentType::ERROR;
2066 if (needs_borrow)
2067 {
2068 adjusted_argument = address_expression (expression, locus);
2069 }
2070
2071 // make the call
2072 return Backend::call_expression (fn_address, {adjusted_argument}, nullptr,
2073 locus);
2074 }
2075
2076 tree
2077 HIRCompileBase::resolve_indirection_adjustment (
2078 Resolver::Adjustment &adjustment, tree expression, location_t locus)
2079 {
2080 return indirect_expression (expression, locus);
2081 }
2082
2083 tree
2084 HIRCompileBase::resolve_unsized_adjustment (Resolver::Adjustment &adjustment,
2085 tree expression, location_t locus)
2086 {
2087 bool expect_slice
2088 = adjustment.get_expected ()->get_kind () == TyTy::TypeKind::SLICE;
2089 bool expect_dyn
2090 = adjustment.get_expected ()->get_kind () == TyTy::TypeKind::DYNAMIC;
2091
2092 // assumes this is an array
2093 tree expr_type = TREE_TYPE (expression);
2094 if (expect_slice)
2095 {
2096 rust_assert (TREE_CODE (expr_type) == ARRAY_TYPE);
2097 return resolve_unsized_slice_adjustment (adjustment, expression, locus);
2098 }
2099
2100 rust_assert (expect_dyn);
2101 return resolve_unsized_dyn_adjustment (adjustment, expression, locus);
2102 }
2103
2104 tree
2105 HIRCompileBase::resolve_unsized_slice_adjustment (
2106 Resolver::Adjustment &adjustment, tree expression, location_t locus)
2107 {
2108 // assumes this is an array
2109 tree expr_type = TREE_TYPE (expression);
2110 rust_assert (TREE_CODE (expr_type) == ARRAY_TYPE);
2111
2112 // takes an array and returns a fat-pointer so this becomes a constructor
2113 // expression
2114 rust_assert (adjustment.get_expected ()->get_kind ()
2115 == TyTy::TypeKind::SLICE);
2116 tree fat_pointer
2117 = TyTyResolveCompile::compile (ctx, adjustment.get_expected ());
2118
2119 // make a constructor for this
2120 tree data = address_expression (expression, locus);
2121
2122 // fetch the size from the domain
2123 tree domain = TYPE_DOMAIN (expr_type);
2124 unsigned HOST_WIDE_INT array_size
2125 = wi::ext (wi::to_offset (TYPE_MAX_VALUE (domain))
2126 - wi::to_offset (TYPE_MIN_VALUE (domain)) + 1,
2127 TYPE_PRECISION (TREE_TYPE (domain)),
2128 TYPE_SIGN (TREE_TYPE (domain)))
2129 .to_uhwi ();
2130 tree size = build_int_cstu (size_type_node, array_size);
2131
2132 return Backend::constructor_expression (fat_pointer, false, {data, size}, -1,
2133 locus);
2134 }
2135
2136 tree
2137 HIRCompileBase::resolve_unsized_dyn_adjustment (
2138 Resolver::Adjustment &adjustment, tree expression, location_t locus)
2139 {
2140 tree rvalue = expression;
2141 location_t rvalue_locus = locus;
2142
2143 const TyTy::BaseType *actual = adjustment.get_actual ();
2144 const TyTy::BaseType *expected = adjustment.get_expected ();
2145
2146 const TyTy::DynamicObjectType *dyn
2147 = static_cast<const TyTy::DynamicObjectType *> (expected);
2148
2149 rust_debug ("resolve_unsized_dyn_adjustment actual={%s} dyn={%s}",
2150 actual->debug_str ().c_str (), dyn->debug_str ().c_str ());
2151
2152 return coerce_to_dyn_object (rvalue, actual, dyn, rvalue_locus);
2153 }
2154
2155 void
2156 CompileExpr::visit (HIR::RangeFromToExpr &expr)
2157 {
2158 tree from = CompileExpr::Compile (expr.get_from_expr (), ctx);
2159 tree to = CompileExpr::Compile (expr.get_to_expr (), ctx);
2160 if (from == error_mark_node || to == error_mark_node)
2161 {
2162 translated = error_mark_node;
2163 return;
2164 }
2165
2166 TyTy::BaseType *tyty = nullptr;
2167 bool ok
2168 = ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (), &tyty);
2169 rust_assert (ok);
2170
2171 tree adt = TyTyResolveCompile::compile (ctx, tyty);
2172
2173 // make the constructor
2174 translated = Backend::constructor_expression (adt, false, {from, to}, -1,
2175 expr.get_locus ());
2176 }
2177
2178 void
2179 CompileExpr::visit (HIR::RangeFromExpr &expr)
2180 {
2181 tree from = CompileExpr::Compile (expr.get_from_expr (), ctx);
2182 if (from == error_mark_node)
2183 {
2184 translated = error_mark_node;
2185 return;
2186 }
2187
2188 TyTy::BaseType *tyty = nullptr;
2189 bool ok
2190 = ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (), &tyty);
2191 rust_assert (ok);
2192
2193 tree adt = TyTyResolveCompile::compile (ctx, tyty);
2194
2195 // make the constructor
2196 translated = Backend::constructor_expression (adt, false, {from}, -1,
2197 expr.get_locus ());
2198 }
2199
2200 void
2201 CompileExpr::visit (HIR::RangeToExpr &expr)
2202 {
2203 tree to = CompileExpr::Compile (expr.get_to_expr (), ctx);
2204 if (to == error_mark_node)
2205 {
2206 translated = error_mark_node;
2207 return;
2208 }
2209
2210 TyTy::BaseType *tyty = nullptr;
2211 bool ok
2212 = ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (), &tyty);
2213 rust_assert (ok);
2214
2215 tree adt = TyTyResolveCompile::compile (ctx, tyty);
2216
2217 // make the constructor
2218 translated
2219 = Backend::constructor_expression (adt, false, {to}, -1, expr.get_locus ());
2220 }
2221
2222 void
2223 CompileExpr::visit (HIR::RangeFullExpr &expr)
2224 {
2225 TyTy::BaseType *tyty = nullptr;
2226 bool ok
2227 = ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (), &tyty);
2228 rust_assert (ok);
2229
2230 tree adt = TyTyResolveCompile::compile (ctx, tyty);
2231 translated
2232 = Backend::constructor_expression (adt, false, {}, -1, expr.get_locus ());
2233 }
2234
2235 void
2236 CompileExpr::visit (HIR::RangeFromToInclExpr &expr)
2237 {
2238 tree from = CompileExpr::Compile (expr.get_from_expr (), ctx);
2239 tree to = CompileExpr::Compile (expr.get_to_expr (), ctx);
2240 if (from == error_mark_node || to == error_mark_node)
2241 {
2242 translated = error_mark_node;
2243 return;
2244 }
2245
2246 TyTy::BaseType *tyty = nullptr;
2247 bool ok
2248 = ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (), &tyty);
2249 rust_assert (ok);
2250
2251 tree adt = TyTyResolveCompile::compile (ctx, tyty);
2252
2253 // make the constructor
2254 translated = Backend::constructor_expression (adt, false, {from, to}, -1,
2255 expr.get_locus ());
2256 }
2257
2258 void
2259 CompileExpr::visit (HIR::ArrayIndexExpr &expr)
2260 {
2261 tree array_reference = CompileExpr::Compile (expr.get_array_expr (), ctx);
2262 tree index = CompileExpr::Compile (expr.get_index_expr (), ctx);
2263
2264 // this might be an core::ops::index lang item situation
2265 TyTy::FnType *fntype;
2266 bool is_op_overload = ctx->get_tyctx ()->lookup_operator_overload (
2267 expr.get_mappings ().get_hirid (), &fntype);
2268 if (is_op_overload)
2269 {
2270 auto lang_item_type = LangItem::Kind::INDEX;
2271 tree operator_overload_call
2272 = resolve_operator_overload (lang_item_type, expr, array_reference,
2273 index, expr.get_array_expr (),
2274 expr.get_index_expr ());
2275
2276 tree actual_type = TREE_TYPE (operator_overload_call);
2277 bool can_indirect = TYPE_PTR_P (actual_type) || TYPE_REF_P (actual_type);
2278 if (!can_indirect)
2279 {
2280 // nothing to do
2281 translated = operator_overload_call;
2282 return;
2283 }
2284
2285 // rust deref always returns a reference from this overload then we can
2286 // actually do the indirection
2287 translated
2288 = indirect_expression (operator_overload_call, expr.get_locus ());
2289 return;
2290 }
2291
2292 // lets check if the array is a reference type then we can add an
2293 // indirection if required
2294 TyTy::BaseType *array_expr_ty = nullptr;
2295 bool ok = ctx->get_tyctx ()->lookup_type (
2296 expr.get_array_expr ().get_mappings ().get_hirid (), &array_expr_ty);
2297 rust_assert (ok);
2298
2299 // do we need to add an indirect reference
2300 if (array_expr_ty->get_kind () == TyTy::TypeKind::REF)
2301 {
2302 array_reference
2303 = indirect_expression (array_reference, expr.get_locus ());
2304 }
2305
2306 translated = Backend::array_index_expression (array_reference, index,
2307 expr.get_locus ());
2308 }
2309
2310 void
2311 CompileExpr::visit (HIR::ClosureExpr &expr)
2312 {
2313 TyTy::BaseType *closure_expr_ty = nullptr;
2314 if (!ctx->get_tyctx ()->lookup_type (expr.get_mappings ().get_hirid (),
2315 &closure_expr_ty))
2316 {
2317 rust_fatal_error (expr.get_locus (),
2318 "did not resolve type for this ClosureExpr");
2319 return;
2320 }
2321 rust_assert (closure_expr_ty->get_kind () == TyTy::TypeKind::CLOSURE);
2322 TyTy::ClosureType *closure_tyty
2323 = static_cast<TyTy::ClosureType *> (closure_expr_ty);
2324 tree compiled_closure_tyty = TyTyResolveCompile::compile (ctx, closure_tyty);
2325
2326 // generate closure function
2327 generate_closure_function (expr, *closure_tyty, compiled_closure_tyty);
2328
2329 // lets ignore state capture for now we need to instantiate the struct anyway
2330 // then generate the function
2331 std::vector<tree> vals;
2332 for (const auto &capture : closure_tyty->get_captures ())
2333 {
2334 // lookup the HirId
2335 if (auto hid = ctx->get_mappings ().lookup_node_to_hir (capture))
2336 {
2337 // lookup the var decl
2338 Bvariable *var = nullptr;
2339 bool found = ctx->lookup_var_decl (*hid, &var);
2340 rust_assert (found);
2341
2342 // FIXME
2343 // this should bes based on the closure move-ability
2344 tree var_expr = var->get_tree (expr.get_locus ());
2345 tree val = address_expression (var_expr, expr.get_locus ());
2346 vals.push_back (val);
2347 }
2348 else
2349 rust_unreachable ();
2350 }
2351
2352 translated = Backend::constructor_expression (compiled_closure_tyty, false,
2353 vals, -1, expr.get_locus ());
2354 }
2355
2356 tree
2357 CompileExpr::generate_closure_function (HIR::ClosureExpr &expr,
2358 TyTy::ClosureType &closure_tyty,
2359 tree compiled_closure_tyty)
2360 {
2361 TyTy::FnType *fn_tyty = nullptr;
2362 tree compiled_fn_type
2363 = generate_closure_fntype (expr, closure_tyty, compiled_closure_tyty,
2364 &fn_tyty);
2365 if (compiled_fn_type == error_mark_node)
2366 return error_mark_node;
2367
2368 const Resolver::CanonicalPath &parent_canonical_path
2369 = closure_tyty.get_ident ().path;
2370
2371 tl::optional<NodeId> nid = ctx->get_mappings ().lookup_hir_to_node (
2372 expr.get_mappings ().get_hirid ());
2373 rust_assert (nid.has_value ());
2374 auto node_id = nid.value ();
2375
2376 Resolver::CanonicalPath path = parent_canonical_path.append (
2377 Resolver::CanonicalPath::new_seg (node_id, "{{closure}}"));
2378
2379 std::string ir_symbol_name = path.get ();
2380 std::string asm_name = ctx->mangle_item (&closure_tyty, path);
2381
2382 unsigned int flags = 0;
2383 tree fndecl = Backend::function (compiled_fn_type, ir_symbol_name, asm_name,
2384 flags, expr.get_locus ());
2385
2386 // insert into the context
2387 ctx->insert_function_decl (fn_tyty, fndecl);
2388 ctx->insert_closure_decl (&closure_tyty, fndecl);
2389
2390 // setup the parameters
2391 std::vector<Bvariable *> param_vars;
2392
2393 // closure self
2394 Bvariable *self_param
2395 = Backend::parameter_variable (fndecl, "$closure", compiled_closure_tyty,
2396 expr.get_locus ());
2397 DECL_ARTIFICIAL (self_param->get_decl ()) = 1;
2398 param_vars.push_back (self_param);
2399
2400 // push a new context
2401 ctx->push_closure_context (expr.get_mappings ().get_hirid ());
2402
2403 // setup the implicit argument captures
2404 size_t idx = 0;
2405 for (const auto &capture : closure_tyty.get_captures ())
2406 {
2407 // lookup the HirId
2408 if (auto hid = ctx->get_mappings ().lookup_node_to_hir (capture))
2409 {
2410 // get the assessor
2411 tree binding = Backend::struct_field_expression (
2412 self_param->get_tree (expr.get_locus ()), idx, expr.get_locus ());
2413 tree indirection = indirect_expression (binding, expr.get_locus ());
2414
2415 // insert bindings
2416 ctx->insert_closure_binding (*hid, indirection);
2417
2418 // continue
2419 idx++;
2420 }
2421 else
2422 rust_unreachable ();
2423 }
2424
2425 // args tuple
2426 tree args_type
2427 = TyTyResolveCompile::compile (ctx, &closure_tyty.get_parameters ());
2428 Bvariable *args_param
2429 = Backend::parameter_variable (fndecl, "args", args_type,
2430 expr.get_locus ());
2431 param_vars.push_back (args_param);
2432
2433 // setup the implicit mappings for the arguments. Since argument passing to
2434 // closure functions is done via passing a tuple but the closure body expects
2435 // just normal arguments this means we need to destructure them similar to
2436 // what we do in MatchExpr's. This means when we have a closure-param of a we
2437 // actually setup the destructure to take from the args tuple
2438
2439 tree args_param_expr = args_param->get_tree (expr.get_locus ());
2440 size_t i = 0;
2441 for (auto &closure_param : expr.get_params ())
2442 {
2443 tree compiled_param_var
2444 = Backend::struct_field_expression (args_param_expr, i,
2445 closure_param.get_locus ());
2446
2447 CompilePatternBindings::Compile (closure_param.get_pattern (),
2448 compiled_param_var, ctx);
2449 i++;
2450 }
2451
2452 if (!Backend::function_set_parameters (fndecl, param_vars))
2453 {
2454 ctx->pop_closure_context ();
2455 return error_mark_node;
2456 }
2457
2458 // lookup locals
2459 HIR::Expr &function_body = expr.get_expr ();
2460 bool is_block_expr
2461 = function_body.get_expression_type () == HIR::Expr::ExprType::Block;
2462
2463 if (is_block_expr)
2464 {
2465 auto body_mappings = function_body.get_mappings ();
2466 if (flag_name_resolution_2_0)
2467 {
2468 auto &nr_ctx
2469 = Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
2470
2471 auto candidate = nr_ctx.values.to_rib (body_mappings.get_nodeid ());
2472
2473 rust_assert (candidate.has_value ());
2474 }
2475 else
2476 {
2477 Resolver::Rib *rib = nullptr;
2478 bool ok
2479 = ctx->get_resolver ()->find_name_rib (body_mappings.get_nodeid (),
2480 &rib);
2481 rust_assert (ok);
2482 }
2483 }
2484
2485 tree enclosing_scope = NULL_TREE;
2486 location_t start_location = function_body.get_locus ();
2487 location_t end_location = function_body.get_locus ();
2488 if (is_block_expr)
2489 {
2490 auto &body = static_cast<HIR::BlockExpr &> (function_body);
2491 start_location = body.get_locus ();
2492 end_location = body.get_end_locus ();
2493 }
2494
2495 tree code_block = Backend::block (fndecl, enclosing_scope, {} /*locals*/,
2496 start_location, end_location);
2497 ctx->push_block (code_block);
2498
2499 TyTy::BaseType *tyret = &closure_tyty.get_result_type ();
2500 Bvariable *return_address = nullptr;
2501
2502 tree return_type = TyTyResolveCompile::compile (ctx, tyret);
2503 bool address_is_taken = false;
2504 tree ret_var_stmt = NULL_TREE;
2505
2506 return_address
2507 = Backend::temporary_variable (fndecl, code_block, return_type, NULL,
2508 address_is_taken, expr.get_locus (),
2509 &ret_var_stmt);
2510
2511 ctx->add_statement (ret_var_stmt);
2512
2513 ctx->push_fn (fndecl, return_address, tyret);
2514
2515 if (is_block_expr)
2516 {
2517 auto &body = static_cast<HIR::BlockExpr &> (function_body);
2518 compile_function_body (fndecl, body, tyret);
2519 }
2520 else
2521 {
2522 tree value = CompileExpr::Compile (function_body, ctx);
2523 tree return_expr
2524 = Backend::return_statement (fndecl, value, function_body.get_locus ());
2525 ctx->add_statement (return_expr);
2526 }
2527
2528 tree bind_tree = ctx->pop_block ();
2529
2530 gcc_assert (TREE_CODE (bind_tree) == BIND_EXPR);
2531 DECL_SAVED_TREE (fndecl) = bind_tree;
2532
2533 ctx->pop_closure_context ();
2534 ctx->pop_fn ();
2535 ctx->push_function (fndecl);
2536
2537 return fndecl;
2538 }
2539
2540 tree
2541 CompileExpr::generate_closure_fntype (HIR::ClosureExpr &expr,
2542 const TyTy::ClosureType &closure_tyty,
2543 tree compiled_closure_tyty,
2544 TyTy::FnType **fn_tyty)
2545 {
2546 // grab the specified_bound
2547 rust_assert (closure_tyty.num_specified_bounds () == 1);
2548 const TyTy::TypeBoundPredicate &predicate
2549 = *closure_tyty.get_specified_bounds ().begin ();
2550
2551 // ensure the fn_once_output associated type is set
2552 closure_tyty.setup_fn_once_output ();
2553
2554 // the function signature is based on the trait bound that the closure
2555 // implements which is determined at the type resolution time
2556 //
2557 // https://github.com/rust-lang/rust/blob/7807a694c2f079fd3f395821bcc357eee8650071/library/core/src/ops/function.rs#L54-L71
2558
2559 TyTy::TypeBoundPredicateItem item = TyTy::TypeBoundPredicateItem::error ();
2560 if (predicate.get_name ().compare ("FnOnce") == 0)
2561 {
2562 item = predicate.lookup_associated_item ("call_once");
2563 }
2564 else if (predicate.get_name ().compare ("FnMut") == 0)
2565 {
2566 item = predicate.lookup_associated_item ("call_mut");
2567 }
2568 else if (predicate.get_name ().compare ("Fn") == 0)
2569 {
2570 item = predicate.lookup_associated_item ("call");
2571 }
2572 else
2573 {
2574 // FIXME error message?
2575 rust_unreachable ();
2576 return error_mark_node;
2577 }
2578
2579 rust_assert (!item.is_error ());
2580
2581 TyTy::BaseType *item_tyty = item.get_tyty_for_receiver (&closure_tyty);
2582 rust_assert (item_tyty->get_kind () == TyTy::TypeKind::FNDEF);
2583 *fn_tyty = static_cast<TyTy::FnType *> (item_tyty);
2584 return TyTyResolveCompile::compile (ctx, item_tyty);
2585 }
2586
2587 bool
2588 CompileExpr::generate_possible_fn_trait_call (HIR::CallExpr &expr,
2589 tree receiver, tree *result)
2590 {
2591 TyTy::FnType *fn_sig = nullptr;
2592 bool found_overload = ctx->get_tyctx ()->lookup_operator_overload (
2593 expr.get_mappings ().get_hirid (), &fn_sig);
2594 if (!found_overload)
2595 return false;
2596
2597 auto id = fn_sig->get_ty_ref ();
2598 auto dId = fn_sig->get_id ();
2599
2600 tree function = error_mark_node;
2601 bool found_closure = ctx->lookup_function_decl (id, &function, dId, fn_sig);
2602 if (!found_closure)
2603 {
2604 // something went wrong we still return true as this was meant to be an fn
2605 // trait call
2606 *result = error_mark_node;
2607 return true;
2608 }
2609
2610 // need to apply any autoderef's to the self argument
2611 HIR::Expr &fnexpr = expr.get_fnexpr ();
2612 HirId autoderef_mappings_id = fnexpr.get_mappings ().get_hirid ();
2613 std::vector<Resolver::Adjustment> *adjustments = nullptr;
2614 bool ok = ctx->get_tyctx ()->lookup_autoderef_mappings (autoderef_mappings_id,
2615 &adjustments);
2616 rust_assert (ok);
2617
2618 // apply adjustments for the fn call
2619 tree self = resolve_adjustements (*adjustments, receiver, expr.get_locus ());
2620
2621 // resolve the arguments
2622 std::vector<tree> tuple_arg_vals;
2623 for (auto &argument : expr.get_arguments ())
2624 {
2625 auto rvalue = CompileExpr::Compile (*argument, ctx);
2626 tuple_arg_vals.push_back (rvalue);
2627 }
2628
2629 // this is always the 2nd argument in the function signature
2630 tree fnty = TREE_TYPE (function);
2631 tree fn_arg_tys = TYPE_ARG_TYPES (fnty);
2632 tree tuple_args_tyty_chain = TREE_CHAIN (fn_arg_tys);
2633 tree tuple_args_tyty = TREE_VALUE (tuple_args_tyty_chain);
2634
2635 tree tuple_args
2636 = Backend::constructor_expression (tuple_args_tyty, false, tuple_arg_vals,
2637 -1, expr.get_locus ());
2638
2639 // args are always self, and the tuple of the args we are passing where
2640 // self is the path of the call-expr in this case the fn_address
2641 std::vector<tree> args;
2642 args.push_back (self);
2643 args.push_back (tuple_args);
2644
2645 tree call_address = address_expression (function, expr.get_locus ());
2646 *result
2647 = Backend::call_expression (call_address, args, nullptr /* static chain ?*/,
2648 expr.get_locus ());
2649 return true;
2650 }
2651
2652 } // namespace Compile
2653 } // namespace Rust