Module: MilkTea::LowererCalls

Included in:
Lowerer
Defined in:
lib/milk_tea/core/lowering/calls.rb

Instance Method Summary collapse

Instance Method Details

#append_variadic_foreign_call_arguments(lowered_expression, arguments, function_type, env:, lowered: nil, cleanup: nil) ⇒ Object



953
954
955
956
957
958
959
960
961
962
963
964
965
# File 'lib/milk_tea/core/lowering/calls.rb', line 953

def append_variadic_foreign_call_arguments(lowered_expression, arguments, function_type, env:, lowered: nil, cleanup: nil)
  return lowered_expression unless function_type.variadic

  extra_arguments = arguments.drop(function_type.params.length)
  return lowered_expression if extra_arguments.empty?
  return lowered_expression unless lowered_expression.is_a?(IR::Call)

  IR::Call.new(
    callee: lowered_expression.callee,
    arguments: lowered_expression.arguments + extra_arguments.map { |argument| lower_variadic_foreign_argument(argument, env:, lowered:, cleanup:) },
    type: lowered_expression.type,
  )
end

#atomic_method_kind(receiver_type, name) ⇒ Object



1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
# File 'lib/milk_tea/core/lowering/calls.rb', line 1557

def atomic_method_kind(receiver_type, name)
  return unless atomic_type?(receiver_type)

  case name
  when "load" then :atomic_load
  when "store" then :atomic_store
  when "add" then :atomic_add
  when "sub" then :atomic_sub
  when "exchange" then :atomic_exchange
  when "compare_exchange" then :atomic_compare_exchange
  end
end

#automatic_foreign_cstr_list_temp_needed?(parameter, _expression, env: nil) ⇒ Boolean

Returns:

  • (Boolean)


1492
1493
1494
1495
1496
1497
1498
# File 'lib/milk_tea/core/lowering/calls.rb', line 1492

def automatic_foreign_cstr_list_temp_needed?(parameter, _expression, env: nil)
  return false unless parameter.type.is_a?(Types::Span) && parameter.type.element_type == @ctx.types.fetch("str")
  return false unless parameter.boundary_type.is_a?(Types::Span)

  boundary_element_type = parameter.boundary_type.element_type
  boundary_element_type == @ctx.types.fetch("cstr") || char_pointer_type?(boundary_element_type)
end

#automatic_foreign_cstr_temp_needed?(parameter, expression, env:) ⇒ Boolean

Returns:

  • (Boolean)


1500
1501
1502
1503
1504
1505
1506
# File 'lib/milk_tea/core/lowering/calls.rb', line 1500

def automatic_foreign_cstr_temp_needed?(parameter, expression, env:)
  return false unless parameter.boundary_type == @ctx.types.fetch("cstr") && parameter.type == @ctx.types.fetch("str")
  return false if expression.is_a?(AST::StringLiteral) && !expression.cstring
  return false if cstr_backed_expression?(expression, env)

  infer_expression_type(expression, env:) != @ctx.types.fetch("cstr")
end

#automatic_variadic_foreign_cstr_temp_needed?(expression, env:) ⇒ Boolean

Returns:

  • (Boolean)


1508
1509
1510
1511
1512
1513
# File 'lib/milk_tea/core/lowering/calls.rb', line 1508

def automatic_variadic_foreign_cstr_temp_needed?(expression, env:)
  return false if expression.is_a?(AST::StringLiteral) && !expression.cstring
  return false if cstr_backed_expression?(expression, env)

  infer_expression_type(expression, env:) == @ctx.types.fetch("str")
end

#bind_foreign_mapping_arguments(binding, arguments, mapping_env, lowered, env:, reference_counts:, cleanup:) ⇒ Object



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
# File 'lib/milk_tea/core/lowering/calls.rb', line 595

def bind_foreign_mapping_arguments(binding, arguments, mapping_env, lowered, env:, reference_counts:, cleanup:)
  replacements = {}
  entries = binding.ast.params.each_with_index.map do |param_ast, index|
    parameter = binding.type.params.fetch(index)
    public_alias = param_ast.boundary_type ? foreign_mapping_public_alias_name(param_ast.name) : nil
    {
      argument: arguments.fetch(index),
      param_ast:,
      parameter:,
      temp_type: parameter.boundary_type || parameter.type,
      public_alias:,
      public_reference_count: public_alias ? reference_counts.fetch(public_alias, 0) : 0,
      reference_count: reference_counts.fetch(param_ast.name, 0),
      lowered_value: nil,
    }
  end

  entries.each do |entry|
    next unless entry[:public_reference_count].positive?

    public_value = lower_contextual_expression(entry[:argument].value, env:, expected_type: entry[:parameter].type)
    if public_value.is_a?(IR::Name)
      current_actual_scope(mapping_env[:scopes])[entry[:public_alias]] = local_binding(
        type: entry[:parameter].type,
        linkage_name: public_value.name,
        mutable: false,
        pointer: public_value.pointer,
      )
      replacements[entry[:public_alias]] = public_value
      next
    end

    public_temp_name = fresh_c_temp_name(env, "foreign_arg_public")
    lowered << IR::LocalDecl.new(
      name: public_temp_name,
      linkage_name: public_temp_name,
      type: entry[:parameter].type,
      value: public_value,
    )
    current_actual_scope(mapping_env[:scopes])[entry[:public_alias]] = local_binding(
      type: entry[:parameter].type,
      linkage_name: public_temp_name,
      mutable: false,
      pointer: false,
    )
    replacements[entry[:public_alias]] = IR::Name.new(name: public_temp_name, type: entry[:parameter].type, pointer: false)
  end

  entries.each do |entry|
    next unless entry[:reference_count].positive?

    source_argument = if entry[:public_reference_count].positive?
                        AST::Argument.new(name: nil, value: AST::Identifier.new(name: entry[:public_alias]))
                      else
                        entry[:argument]
                      end
    source_env = entry[:public_reference_count].positive? ? mapping_env : env
    source_argument = prepare_foreign_in_argument(entry[:parameter], source_argument, source_env:, lowered:, env:)
    entry[:lowered_value] = if automatic_foreign_cstr_list_temp_needed?(entry[:parameter], source_argument.value, env: source_env)
                              lower_foreign_cstr_list_argument_value(entry[:parameter], source_argument.value, env: source_env, lowered:, cleanup:)
                            else
                              lower_foreign_argument_value(entry[:parameter], source_argument, env: source_env)
                            end
  end

  inline_direct_call_names = inlineable_single_direct_call_names(entries)

  entries.each do |entry|
    next unless entry[:reference_count].positive?

    param_ast = entry[:param_ast]
    temp_type = entry[:temp_type]
    lowered_value = entry[:lowered_value]

    if !inline_direct_call_names.include?(param_ast.name) && foreign_argument_needs_temporary_binding?(lowered_value, reference_count: entry[:reference_count])
      temp_name = fresh_c_temp_name(env, "foreign_arg")
      lowered << IR::LocalDecl.new(
        name: temp_name,
        linkage_name: temp_name,
        type: temp_type,
        value: lowered_value,
      )
      current_actual_scope(mapping_env[:scopes])[param_ast.name] = local_binding(type: temp_type, linkage_name: temp_name, mutable: false, pointer: false)
      replacements[param_ast.name] = IR::Name.new(name: temp_name, type: temp_type, pointer: false)
      if temporary_foreign_cstr_expression?(lowered_value)
        cleanup << IR::ExpressionStmt.new(
          expression: IR::Call.new(
            callee: "mt_free_foreign_cstr_temp",
            arguments: [IR::Name.new(name: temp_name, type: temp_type, pointer: false)],
            type: @ctx.types.fetch("void"),
          ),
        )
      end
    else
      current_actual_scope(mapping_env[:scopes])[param_ast.name] = local_binding(type: temp_type, linkage_name: param_ast.name, mutable: false, pointer: false)
      replacements[param_ast.name] = lowered_value
    end
  end

  replacements
end

#consuming_foreign_call_refinements(foreign_call, env) ⇒ Object



568
569
570
571
572
# File 'lib/milk_tea/core/lowering/calls.rb', line 568

def consuming_foreign_call_refinements(foreign_call, env)
  consuming_foreign_release_bindings(foreign_call, env:).each_with_object({}) do |binding, refinements|
    refinements[binding[:name]] = null_type
  end
end

#consuming_foreign_release_assignments(foreign_call, env:) ⇒ Object



558
559
560
561
562
563
564
565
566
# File 'lib/milk_tea/core/lowering/calls.rb', line 558

def consuming_foreign_release_assignments(foreign_call, env:)
  consuming_foreign_release_bindings(foreign_call, env:).map do |binding|
    IR::Assignment.new(
      target: IR::Name.new(name: binding[:linkage_name], type: binding[:storage_type], pointer: binding[:pointer]),
      operator: "=",
      value: IR::NullLiteral.new(type: binding[:storage_type]),
    )
  end
end

#consuming_foreign_release_bindings(foreign_call, env:) ⇒ Object



574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/milk_tea/core/lowering/calls.rb', line 574

def consuming_foreign_release_bindings(foreign_call, env:)
  binding = foreign_call.fetch(:binding)
  call = foreign_call.fetch(:call)

  binding.type.params.each_with_index.filter_map do |parameter, index|
    next unless parameter.passing_mode == :consuming

    argument = call.arguments.fetch(index)
    unless argument.value.is_a?(AST::Identifier)
      raise LoweringError.new("consuming foreign calls require bare nullable local or parameter bindings", line: 0, column: 0, path: @ctx.current_analysis_path)
    end

    lowered_binding = lookup_value(argument.value.name, env)
    unless lowered_binding && lowered_binding[:storage_type].is_a?(Types::Nullable) && lowered_binding[:storage_type].base == parameter.type
      raise LoweringError.new("consuming foreign calls require bare nullable local or parameter bindings", line: 0, column: 0, path: @ctx.current_analysis_path)
    end

    lowered_binding.merge(name: argument.value.name)
  end
end

#duplicable_foreign_argument_expression?(expression) ⇒ Boolean

Returns:

  • (Boolean)


1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
# File 'lib/milk_tea/core/lowering/calls.rb', line 1464

def duplicable_foreign_argument_expression?(expression)
  case expression
  when AST::Identifier, AST::IntegerLiteral, AST::FloatLiteral, AST::StringLiteral, AST::BooleanLiteral, AST::NullLiteral,
        IR::Name, IR::IntegerLiteral, IR::FloatLiteral, IR::StringLiteral, IR::BooleanLiteral, IR::NullLiteral
    true
  when AST::MemberAccess
    duplicable_foreign_argument_expression?(expression.receiver)
  when IR::Member
    duplicable_foreign_argument_expression?(expression.receiver)
  when AST::UnaryOp
    duplicable_foreign_argument_expression?(expression.operand)
  when IR::Unary
    duplicable_foreign_argument_expression?(expression.operand)
  when AST::BinaryOp
    duplicable_foreign_argument_expression?(expression.left) && duplicable_foreign_argument_expression?(expression.right)
  when IR::Binary
    duplicable_foreign_argument_expression?(expression.left) && duplicable_foreign_argument_expression?(expression.right)
  else
    false
  end
end

#expand_function_defaults(arguments, binding) ⇒ Object



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/milk_tea/core/lowering/calls.rb', line 376

def expand_function_defaults(arguments, binding)
  return arguments unless binding.respond_to?(:ast) && binding.ast.respond_to?(:params)

  ast_params = binding.ast.params
  has_defaults = ast_params.any? { |p| p.respond_to?(:default_value) && p.default_value }
  return arguments unless has_defaults || arguments.any?(&:name)

  if arguments.any?(&:name)
    by_position = Array.new(ast_params.length)
    param_names = ast_params.map(&:name)

    arguments.each do |arg|
      if arg.name
        param_idx = param_names.index(arg.name)
        next unless param_idx

        by_position[param_idx] = arg
      else
        first_empty = by_position.index(nil)
        by_position[first_empty] = arg if first_empty
      end
    end

    by_position.each_with_index do |slot, idx|
      next if slot
      next unless ast_params[idx].respond_to?(:default_value) && ast_params[idx].default_value

      by_position[idx] = AST::Argument.new(name: nil, value: ast_params[idx].default_value)
    end

    by_position.compact
  else
    expanded = arguments.dup
    while expanded.length < ast_params.length
      ast_param = ast_params[expanded.length]
      break unless ast_param.respond_to?(:default_value) && ast_param.default_value

      expanded << AST::Argument.new(name: nil, value: ast_param.default_value)
    end
    expanded
  end
end

#foreign_argument_expression(argument) ⇒ Object



712
713
714
715
716
717
718
# File 'lib/milk_tea/core/lowering/calls.rb', line 712

def foreign_argument_expression(argument)
  if argument.value.is_a?(AST::UnaryOp) && ["out", "in", "inout"].include?(argument.value.operator)
    argument.value.operand
  else
    argument.value
  end
end

#foreign_argument_needs_temporary_binding?(expression, reference_count:) ⇒ Boolean

Returns:

  • (Boolean)


1486
1487
1488
1489
1490
# File 'lib/milk_tea/core/lowering/calls.rb', line 1486

def foreign_argument_needs_temporary_binding?(expression, reference_count:)
  return true if reference_count > 1 && !duplicable_foreign_argument_expression?(expression)

  !inlineable_foreign_argument_expression?(expression)
end

#foreign_call_consumes_binding?(binding) ⇒ Boolean

Returns:

  • (Boolean)


481
482
483
# File 'lib/milk_tea/core/lowering/calls.rb', line 481

def foreign_call_consumes_binding?(binding)
  binding.type.params.any? { |parameter| parameter.passing_mode == :consuming }
end

#foreign_call_info(expression, env) ⇒ Object



468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/milk_tea/core/lowering/calls.rb', line 468

def foreign_call_info(expression, env)
  call = expression if expression.is_a?(AST::Call)
  return unless call

  kind, _, _, _, binding = resolve_callee(call.callee, env, arguments: call.arguments)
  return unless kind == :function && binding && foreign_function_binding?(binding)

  {
    call:,
    binding:,
  }
end

#foreign_function_binding?(binding) ⇒ Boolean

Returns:

  • (Boolean)


1356
1357
1358
# File 'lib/milk_tea/core/lowering/calls.rb', line 1356

def foreign_function_binding?(binding)
  binding.ast.is_a?(AST::ForeignFunctionDecl)
end

#foreign_mapping_auto_call_shorthand?(expression) ⇒ Boolean

Returns:

  • (Boolean)


1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
# File 'lib/milk_tea/core/lowering/calls.rb', line 1369

def foreign_mapping_auto_call_shorthand?(expression)
  case expression
  when AST::Identifier
    true
  when AST::MemberAccess
    foreign_mapping_auto_call_shorthand?(expression.receiver)
  when AST::Specialization
    foreign_mapping_auto_call_shorthand?(expression.callee)
  else
    false
  end
end

#foreign_mapping_expression(decl) ⇒ Object



1360
1361
1362
1363
1364
1365
1366
1367
# File 'lib/milk_tea/core/lowering/calls.rb', line 1360

def foreign_mapping_expression(decl)
  return decl.mapping unless foreign_mapping_auto_call_shorthand?(decl.mapping)

  AST::Call.new(
    callee: decl.mapping,
    arguments: decl.params.map { |param| AST::Argument.new(name: nil, value: AST::Identifier.new(name: param.name)) },
  )
end

#foreign_mapping_public_alias_name(name) ⇒ Object



1382
1383
1384
# File 'lib/milk_tea/core/lowering/calls.rb', line 1382

def foreign_mapping_public_alias_name(name)
  "#{name}_public"
end

#foreign_mapping_reference_counts(expression, counts = Hash.new(0)) ⇒ Object



1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
# File 'lib/milk_tea/core/lowering/calls.rb', line 1434

def foreign_mapping_reference_counts(expression, counts = Hash.new(0))
  case expression
  when AST::Identifier
    counts[expression.name] += 1
  when AST::MemberAccess
    foreign_mapping_reference_counts(expression.receiver, counts)
  when AST::IndexAccess
    foreign_mapping_reference_counts(expression.receiver, counts)
    foreign_mapping_reference_counts(expression.index, counts)
  when AST::Specialization, AST::Call
    foreign_mapping_reference_counts(expression.callee, counts)
    expression.arguments.each { |argument| foreign_mapping_reference_counts(argument.value, counts) }
  when AST::UnaryOp
    foreign_mapping_reference_counts(expression.operand, counts)
  when AST::BinaryOp
    foreign_mapping_reference_counts(expression.left, counts)
    foreign_mapping_reference_counts(expression.right, counts)
  when AST::IfExpr
    foreign_mapping_reference_counts(expression.condition, counts)
    foreign_mapping_reference_counts(expression.then_expression, counts)
    foreign_mapping_reference_counts(expression.else_expression, counts)
  when AST::UnsafeExpr
    foreign_mapping_reference_counts(expression.expression, counts)
  when AST::PrefixCast
    foreign_mapping_reference_counts(expression.expression, counts)
  end

  counts
end

#foreign_mapping_uses_inline_replacement?(expression, replacements) ⇒ Boolean

Returns:

  • (Boolean)


1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
# File 'lib/milk_tea/core/lowering/calls.rb', line 1326

def foreign_mapping_uses_inline_replacement?(expression, replacements)
  case expression
  when AST::Identifier
    replacements.key?(expression.name)
  when AST::MemberAccess
    foreign_mapping_uses_inline_replacement?(expression.receiver, replacements)
  when AST::IndexAccess
    foreign_mapping_uses_inline_replacement?(expression.receiver, replacements) ||
      foreign_mapping_uses_inline_replacement?(expression.index, replacements)
  when AST::Specialization, AST::Call
    foreign_mapping_uses_inline_replacement?(expression.callee, replacements) ||
      expression.arguments.any? { |argument| foreign_mapping_uses_inline_replacement?(argument.value, replacements) }
  when AST::UnaryOp
    foreign_mapping_uses_inline_replacement?(expression.operand, replacements)
  when AST::BinaryOp
    foreign_mapping_uses_inline_replacement?(expression.left, replacements) ||
      foreign_mapping_uses_inline_replacement?(expression.right, replacements)
  when AST::IfExpr
    foreign_mapping_uses_inline_replacement?(expression.condition, replacements) ||
      foreign_mapping_uses_inline_replacement?(expression.then_expression, replacements) ||
      foreign_mapping_uses_inline_replacement?(expression.else_expression, replacements)
  when AST::UnsafeExpr
    foreign_mapping_uses_inline_replacement?(expression.expression, replacements)
  when AST::PrefixCast
    foreign_mapping_uses_inline_replacement?(expression.expression, replacements)
  else
    false
  end
end

#foreign_slot_boundary_value_type(type) ⇒ Object



802
803
804
805
806
807
808
# File 'lib/milk_tea/core/lowering/calls.rb', line 802

def foreign_slot_boundary_value_type(type)
  if type.is_a?(Types::Nullable) && pointer_like_type?(type.base)
    return type.base
  end

  type
end

#implicit_ref_argument_bridge?(expression, expected_type, env:) ⇒ Boolean

Returns:

  • (Boolean)


438
439
440
441
442
443
# File 'lib/milk_tea/core/lowering/calls.rb', line 438

def implicit_ref_argument_bridge?(expression, expected_type, env:)
  return false unless ref_type?(expected_type)

  actual_type = infer_expression_type(expression, env:)
  actual_type == referenced_type(expected_type) && addressable_storage_expression?(expression)
end

#inlineable_single_direct_call_names(entries) ⇒ Object



697
698
699
700
701
702
703
704
705
706
707
708
709
710
# File 'lib/milk_tea/core/lowering/calls.rb', line 697

def inlineable_single_direct_call_names(entries)
  blocked_entries = entries.select do |entry|
    next false unless entry[:reference_count].positive?

    entry[:reference_count] > 1 || !inlineable_foreign_argument_expression?(entry[:lowered_value])
  end
  return [] unless blocked_entries.length == 1

  blocked_entry = blocked_entries.first
  return [] unless blocked_entry[:reference_count] == 1 && blocked_entry[:lowered_value].is_a?(IR::Call)
  return [] if temporary_foreign_cstr_expression?(blocked_entry[:lowered_value])

  [blocked_entry[:param_ast].name]
end

#lower_addr_expression(expression, env:, target_type:) ⇒ Object



351
352
353
354
355
356
357
358
359
360
# File 'lib/milk_tea/core/lowering/calls.rb', line 351

def lower_addr_expression(expression, env:, target_type:)
  lowered_expression = lower_expression(expression, env:)
  return cast_expression(lowered_expression, target_type) if lowered_expression.is_a?(IR::Name) && lowered_expression.pointer

  if lowered_expression.is_a?(IR::Unary) && lowered_expression.operator == "*"
    return cast_expression(lowered_expression.operand, target_type)
  end

  IR::AddressOf.new(expression: lowered_expression, type: target_type)
end

#lower_atomic_method_call(kind, receiver, expression, env:, type:) ⇒ Object



1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
# File 'lib/milk_tea/core/lowering/calls.rb', line 1578

def lower_atomic_method_call(kind, receiver, expression, env:, type:)
  receiver_type = infer_expression_type(receiver, env:)
  elem_type = atomic_element_type(receiver_type)
  ptr_type = Types::Registry.generic_instance("ptr", [elem_type])
  receiver_ir = lower_expression(receiver, env:)
  addr = IR::AddressOf.new(expression: receiver_ir, type: ptr_type)
  seq_cst = IR::IntegerLiteral.new(value: 5, type: @ctx.types.fetch("int"))

  case kind
  when :atomic_load
    IR::Call.new(callee: "__atomic_load_n", arguments: [addr, seq_cst], type: elem_type)
  when :atomic_store
    arg = lower_contextual_expression(expression.arguments.first.value, env:, expected_type: elem_type)
    IR::Call.new(callee: "__atomic_store_n", arguments: [addr, arg, seq_cst], type:)
  when :atomic_add
    arg = lower_contextual_expression(expression.arguments.first.value, env:, expected_type: elem_type)
    IR::Call.new(callee: "__atomic_fetch_add", arguments: [addr, arg, seq_cst], type: elem_type)
  when :atomic_sub
    arg = lower_contextual_expression(expression.arguments.first.value, env:, expected_type: elem_type)
    IR::Call.new(callee: "__atomic_fetch_sub", arguments: [addr, arg, seq_cst], type: elem_type)
  when :atomic_exchange
    arg = lower_contextual_expression(expression.arguments.first.value, env:, expected_type: elem_type)
    IR::Call.new(callee: "__atomic_exchange_n", arguments: [addr, arg, seq_cst], type: elem_type)
  when :atomic_compare_exchange
    raise LoweringError.new("atomic compare_exchange is not yet implemented in the built-in surface; use std.sync.AtomicUint for compare-exchange operations", line: 0, column: 0, path: @ctx.current_analysis_path)
  end
end

#lower_call(expression, env:, type:) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/milk_tea/core/lowering/calls.rb', line 5

def lower_call(expression, env:, type:)
  ct_value = compile_time_const_value(expression, env:)
  if ct_value && (literal = lower_compile_time_literal(ct_value, type))
    if expression.callee.is_a?(AST::Identifier)
      binding = @ctx.functions[expression.callee.name]
      return literal unless binding&.ast&.respond_to?(:const) && binding.ast.const
    else
      return literal
    end
  end

  kind, callee_name, receiver, callee_type, callee_binding = resolve_callee(expression.callee, env, arguments: expression.arguments)

  case kind
  when :function
    if callee_binding && foreign_function_binding?(callee_binding)
      raise LoweringError.new("consuming foreign calls must be top-level expression statements", line: 0, column: 0, path: @ctx.current_analysis_path) if foreign_call_consumes_binding?(callee_binding)

      return lower_foreign_call_inline(expression, callee_binding, env:, type:)
    end

    lowered_arguments = expression.arguments
    lowered_arguments = expand_function_defaults(lowered_arguments, callee_binding) if callee_binding
    arguments = lower_call_arguments(lowered_arguments, callee_type, env:)
    IR::Call.new(callee: callee_name, arguments:, type:)
  when :callable_value
    callee_expression = lower_expression(expression.callee, env:, expected_type: callee_type)
    if proc_type?(callee_type)
      arguments = [
        IR::Member.new(receiver: callee_expression, member: "env", type: proc_env_pointer_type),
        *lower_call_arguments(expression.arguments, callee_type, env:),
      ]
      IR::Call.new(
        callee: IR::Member.new(receiver: callee_expression, member: "invoke", type: proc_invoke_function_type(callee_type)),
        arguments:,
        type:,
      )
    else
      arguments = lower_call_arguments(expression.arguments, callee_type, env:)
      IR::Call.new(callee: callee_expression, arguments:, type:)
    end
  when :method
    receiver_arg = lower_method_receiver_argument(receiver, callee_type, callee_binding, env:)
    arguments = [receiver_arg, *lower_call_arguments(expression.arguments, callee_type, env:)]
    IR::Call.new(callee: callee_name, arguments:, type:)
  when :str_buffer_clear
    IR::Call.new(
      callee: "mt_str_buffer_clear",
      arguments: str_buffer_args(receiver, env:),
      type:,
    )
  when :str_buffer_assign, :str_buffer_assign_format
    IR::Call.new(
      callee: "mt_str_buffer_assign",
      arguments: [
        lower_contextual_expression(expression.arguments.fetch(0).value, env:, expected_type: @ctx.types.fetch("str")),
        *str_buffer_args(receiver, env:),
      ],
      type:,
    )
  when :str_buffer_append, :str_buffer_append_format
    IR::Call.new(
      callee: "mt_str_buffer_append",
      arguments: [
        lower_contextual_expression(expression.arguments.fetch(0).value, env:, expected_type: @ctx.types.fetch("str")),
        *str_buffer_args(receiver, env:),
      ],
      type:,
    )
  when :str_buffer_len
    IR::Call.new(
      callee: "mt_str_buffer_len",
      arguments: str_buffer_args(receiver, env:),
      type:,
    )
  when :str_buffer_capacity
    receiver_type = infer_expression_type(receiver, env:)
    IR::IntegerLiteral.new(value: str_buffer_capacity(receiver_type), type: type)
  when :str_buffer_as_str
    args = str_buffer_args(receiver, env:)
    IR::AggregateLiteral.new(
      type:,
      fields: [
        IR::AggregateField.new(name: "data", value: args[0]),
        IR::AggregateField.new(
          name: "len",
          value: IR::Call.new(
            callee: "mt_str_buffer_len",
            arguments: args,
            type: @ctx.types.fetch("ptr_uint"),
          ),
        ),
      ],
    )
  when :str_buffer_as_cstr
    IR::Call.new(
      callee: "mt_str_buffer_as_cstr",
      arguments: str_buffer_args(receiver, env:),
      type:,
    )
  when :array_as_span
    receiver_type = infer_expression_type(receiver, env:)
    lower_array_to_span_expression(lower_expression(receiver, env:), type)
  when :event_subscribe, :event_subscribe_once, :event_unsubscribe, :event_emit, :event_wait
    event_type = infer_expression_type(receiver, env:)
    runtime = ensure_event_runtime(event_type)
    event_pointer = lower_event_storage_pointer(receiver, env:)

    case kind
    when :event_subscribe
      lower_event_subscribe_call(expression, env:, runtime:, event_pointer:, type:)
    when :event_subscribe_once
      lower_event_subscribe_call(expression, env:, runtime:, event_pointer:, type:, once: true)
    when :event_unsubscribe
      IR::Call.new(
        callee: runtime.fetch(:unsubscribe_linkage_name),
        arguments: [
          event_pointer,
          lower_contextual_expression(expression.arguments.fetch(0).value, env:, expected_type: @ctx.types.fetch("Subscription")),
        ],
        type:,
      )
    when :event_emit
      arguments = [event_pointer]
      if event_type.payload_type
        arguments << lower_contextual_expression(expression.arguments.fetch(0).value, env:, expected_type: event_type.payload_type)
      end
      IR::Call.new(callee: runtime.fetch(:emit_linkage_name), arguments:, type:)
    when :event_wait
      IR::Call.new(callee: runtime.fetch(:wait_linkage_name), arguments: [event_pointer], type:)
    end
  when :atomic_load, :atomic_store, :atomic_add, :atomic_sub, :atomic_exchange, :atomic_compare_exchange
    lower_atomic_method_call(kind, receiver, expression, env:, type:)
  when :simd_lane_with
    lower_simd_lane_with(kind, receiver, expression, env:, type:)
  when :associated_method
    arguments = lower_call_arguments(expression.arguments, callee_type, env:)
    IR::Call.new(callee: callee_name, arguments:, type:)
  when :struct_literal
    fields = expression.arguments.map do |argument|
      field_type = type.field(argument.name)
      lowered_value = lower_contextual_expression(
        argument.value,
        env:,
        expected_type: field_type,
        external_numeric: type.respond_to?(:external) && type.external,
        contextual_int_to_float: contextual_int_to_float_target?(field_type),
      )
      lowered_value = wrap_nullable_field_value(field_type, lowered_value, env)
      IR::AggregateField.new(
        name: argument.name,
        value: lowered_value,
      )
    end
    IR::AggregateLiteral.new(type:, fields:)
  when :struct_with
    explicit_names = expression.arguments.each_with_object({}) { |a, h| h[a.name] = a }
    lowered_receiver = lower_expression(receiver, env:)
    field_hash = callee_type.respond_to?(:fields) ? callee_type.fields : {}
    fields = field_hash.map do |field_name, field_type|
      if (explicit_arg = explicit_names[field_name])
        IR::AggregateField.new(
          name: field_name,
          value: lower_contextual_expression(
            explicit_arg.value,
            env:,
            expected_type: field_type,
            contextual_int_to_float: contextual_int_to_float_target?(field_type),
          ),
        )
      else
        IR::AggregateField.new(
          name: field_name,
          value: IR::Member.new(
            receiver: lowered_receiver,
            member: field_name,
            type: field_type,
          ),
        )
      end
    end
    IR::AggregateLiteral.new(type: callee_type, fields:)
  when :variant_arm_ctor
    _, _, _, variant_type, (_, arm_name) = resolve_callee(expression.callee, env, arguments: expression.arguments)
    arm_fields = variant_type.arm(arm_name)
    provided_names = expression.arguments.map(&:name).to_set
    payload_fields = expression.arguments.map do |argument|
      field_type = arm_fields.fetch(argument.name)
      lowered_value = lower_contextual_expression(
        argument.value,
        env:,
        expected_type: field_type,
        contextual_int_to_float: contextual_int_to_float_target?(field_type),
      )
      lowered_value = IR::AddressOf.new(expression: lowered_value, type: lowered_value.type) if field_type == variant_type
      lowered_value = wrap_nullable_field_value(field_type, lowered_value, env) unless field_type == variant_type
      IR::AggregateField.new(
        name: argument.name,
        value: lowered_value,
      )
    end
    arm_fields.each do |field_name, field_type|
      next if provided_names.include?(field_name)
      next unless field_type.void?

      payload_fields << IR::AggregateField.new(
        name: field_name,
        value: IR::IntegerLiteral.new(type: @ctx.types.fetch("ubyte"), value: 0),
      )
    end
    IR::VariantLiteral.new(type: variant_type, arm_name:, fields: payload_fields)
  when :array
    element_type = array_element_type(type)
    elements = expression.arguments.map do |argument|
      lower_contextual_expression(argument.value, env:, expected_type: element_type)
    end
    IR::ArrayLiteral.new(type:, elements:)
  when :simd
    element_type = simd_type?(type) ? type.element_type : array_element_type(type)
    elements = expression.arguments.map do |argument|
      lower_contextual_expression(argument.value, env:, expected_type: element_type)
    end
    IR::ArrayLiteral.new(type:, elements:)
  when :reinterpret
    argument = expression.arguments.fetch(0)
    source_type = infer_expression_type(argument.value, env:)
    IR::ReinterpretExpr.new(
      target_type: type,
      source_type:,
      expression: lower_expression(argument.value, env:, expected_type: source_type),
      type:,
    )
  when :hash
    resolution = resolve_hash_specialization(expression.callee, env:)
    argument = expression.arguments.fetch(0)
    IR::Call.new(
      callee: resolution.callee_name,
      arguments: [lower_hash_operation_argument(argument.value, env:, target_type: resolution.target_type)],
      type:,
    )
  when :equal
    resolution = resolve_equal_specialization(expression.callee, env:)
    left = expression.arguments.fetch(0)
    right = expression.arguments.fetch(1)
    IR::Call.new(
      callee: resolution.callee_name,
      arguments: [
        lower_hash_operation_argument(left.value, env:, target_type: resolution.target_type),
        lower_hash_operation_argument(right.value, env:, target_type: resolution.target_type),
      ],
      type:,
    )
  when :order
    resolution = resolve_order_specialization(expression.callee, env:)
    left = expression.arguments.fetch(0)
    right = expression.arguments.fetch(1)
    IR::Call.new(
      callee: resolution.callee_name,
      arguments: [
        lower_hash_operation_argument(left.value, env:, target_type: resolution.target_type),
        lower_hash_operation_argument(right.value, env:, target_type: resolution.target_type),
      ],
      type:,
    )
  when :zero
    IR::ZeroInit.new(type:)
  when :fatal
    argument = expression.arguments.fetch(0)
    message_type = infer_expression_type(argument.value, env:)
    callee = message_type == @ctx.types.fetch("cstr") ? "mt_fatal" : "mt_fatal_str"
    IR::Call.new(callee:, arguments: [lower_expression(argument.value, env:, expected_type: message_type)], type:)
  when :get
    receiver_arg = expression.arguments.fetch(0)
    index_arg = expression.arguments.fetch(1)
    receiver_type = infer_expression_type(receiver_arg.value, env:)
    receiver = lower_expression(receiver_arg.value, env:)
    index = lower_expression(index_arg.value, env:)
    if array_type?(receiver_type)
      IR::NullableIndex.new(receiver:, index:, receiver_type:, type:)
    elsif receiver_type.is_a?(Types::Span)
      IR::NullableSpanIndex.new(receiver:, index:, receiver_type:, type:)
    else
      raise LoweringError.new("get expects an array or span, got #{receiver_type}", line: 0, column: 0, path: @ctx.current_analysis_path)
    end
  when :ref_of
    argument = expression.arguments.fetch(0)
    lower_addr_expression(argument.value, env:, target_type: type)
  when :const_ptr_of
    argument = expression.arguments.fetch(0)
    lower_addr_expression(argument.value, env:, target_type: type)
  when :read
    argument = expression.arguments.fetch(0)
    IR::Unary.new(operator: "*", operand: lower_expression(argument.value, env:), type:)
  when :ptr_of
    argument = expression.arguments.fetch(0)
    argument_type = infer_expression_type(argument.value, env:)
    if ref_type?(argument_type)
      IR::Cast.new(target_type: type, expression: lower_expression(argument.value, env:), type:)
    else
      lower_addr_expression(argument.value, env:, target_type: type)
    end
  when :adapt
    lower_adapt_call(expression, env:, type:, interface: callee_binding)
  when :dyn_method
    lower_dyn_method_call(expression, receiver, callee_type, env:, type:)
  else
    raise LoweringError.new("unsupported call kind #{kind}", line: 0, column: 0, path: @ctx.current_analysis_path)
  end
end

#lower_call_arguments(arguments, callee_type, env:) ⇒ Object



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/milk_tea/core/lowering/calls.rb', line 419

def lower_call_arguments(arguments, callee_type, env:)
  arguments.map.with_index do |argument, index|
    parameter = index < callee_type.params.length ? callee_type.params[index] : nil
    expected_type = parameter&.type
    external_call = callee_type.respond_to?(:external) && callee_type.external && !expected_type.nil?
    if external_call && parameter && %i[out inout].include?(parameter.passing_mode)
      next lower_foreign_pointer_argument_value(parameter, argument, env:)
    end

    lower_contextual_expression(
      argument.value,
      env:,
      expected_type:,
      external_numeric: external_call,
      contextual_int_to_float: expected_type && contextual_int_to_float_target?(expected_type) && !external_call,
    )
  end
end

#lower_event_subscribe_call(expression, env:, runtime:, event_pointer:, type:, once: false) ⇒ Object



1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
# File 'lib/milk_tea/core/lowering/calls.rb', line 1619

def lower_event_subscribe_call(expression, env:, runtime:, event_pointer:, type:, once: false)
  stateful = expression.arguments.length == 2
  callee_key = if stateful
                  once ? :subscribe_once_stateful_linkage_name : :subscribe_stateful_linkage_name
                else
                  once ? :subscribe_once_linkage_name : :subscribe_linkage_name
                end
  arguments = [event_pointer]
  if stateful
    arguments << lower_contextual_expression(expression.arguments.fetch(0).value, env:, expected_type: runtime.fetch(:void_ptr))
    arguments << lower_contextual_expression(expression.arguments.fetch(1).value, env:, expected_type: runtime.fetch(:void_ptr))
  else
    arguments << lower_contextual_expression(expression.arguments.fetch(0).value, env:, expected_type: runtime.fetch(:listener_type))
  end
  IR::Call.new(callee: runtime.fetch(callee_key), arguments:, type:)
end

#lower_foreign_argument_value(parameter, argument, env:) ⇒ Object



720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'lib/milk_tea/core/lowering/calls.rb', line 720

def lower_foreign_argument_value(parameter, argument, env:)
  case parameter.passing_mode
  when :plain, :consuming
    if parameter.boundary_type.nil? || parameter.boundary_type == parameter.type
      expected = parameter.passing_mode == :consuming ? Types::Registry.nullable(parameter.type) : parameter.type
      lower_contextual_expression(argument.value, env:, expected_type: expected)
    elsif parameter.boundary_type == @ctx.types.fetch("cstr") && parameter.type == @ctx.types.fetch("str")
      if argument.value.is_a?(AST::StringLiteral) && !argument.value.cstring
        return IR::StringLiteral.new(value: argument.value.value, type: parameter.boundary_type, cstring: true)
      end

      actual_type = infer_expression_type(argument.value, env:)
      if actual_type == @ctx.types.fetch("cstr")
        return lower_expression(argument.value, env:, expected_type: parameter.boundary_type)
      end

      if cstr_backed_expression?(argument.value, env)
        lowered_value = lower_contextual_expression(argument.value, env:, expected_type: parameter.type)
        data_expression = IR::Member.new(receiver: lowered_value, member: "data", type: pointer_to(@ctx.types.fetch("char")))
        converted = foreign_identity_projection_expression(data_expression, parameter.boundary_type)
        return converted if converted
      end

      IR::Call.new(
        callee: "mt_foreign_str_to_cstr_temp",
        arguments: [lower_contextual_expression(argument.value, env:, expected_type: parameter.type)],
        type: parameter.boundary_type,
      )
    elsif foreign_span_boundary_compatible?(parameter.type, parameter.boundary_type)
      lower_foreign_span_argument_value(parameter, argument, env:)
    elsif foreign_char_pointer_buffer_boundary_compatible?(parameter.type, parameter.boundary_type)
      lower_foreign_char_pointer_buffer_argument_value(parameter, argument, env:)
    else
      lowered_value = lower_contextual_expression(argument.value, env:, expected_type: parameter.type)
      converted = foreign_identity_projection_expression(lowered_value, parameter.boundary_type)
      return converted if converted

      raise LoweringError.new("unsupported foreign boundary mapping #{parameter.type} as #{parameter.boundary_type}", line: 0, column: 0, path: @ctx.current_analysis_path)
    end
  when :in
    lower_foreign_in_argument_value(parameter, argument, env:)
  when :out, :inout
    lower_foreign_pointer_argument_value(parameter, argument, env:)
  else
    raise LoweringError.new("unsupported foreign passing mode #{parameter.passing_mode}", line: 0, column: 0, path: @ctx.current_analysis_path)
  end
end

#lower_foreign_call_components(foreign_call, env:, expected_type:, statement_position:) ⇒ Object



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/milk_tea/core/lowering/calls.rb', line 485

def lower_foreign_call_components(foreign_call, env:, expected_type:, statement_position:)
  call = foreign_call.fetch(:call)
  binding = foreign_call.fetch(:binding)
  raise LoweringError.new("consuming foreign calls must be top-level expression statements", line: 0, column: 0, path: @ctx.current_analysis_path) if foreign_call_consumes_binding?(binding) && !statement_position

  previous_type_substitutions = @ctx.current_type_substitutions
  @ctx.current_type_substitutions = binding.type_substitutions

  owner_analysis = analysis_for_module(binding.owner.module_name)
  mapping_expression = foreign_mapping_expression(binding.ast)
  reference_counts = foreign_mapping_reference_counts(mapping_expression)
  mapping_env = duplicate_env(env)
  lowered = []
  release_assignments = consuming_foreign_release_assignments(foreign_call, env:)
  cleanup_statements = []

  replacements = bind_foreign_mapping_arguments(binding, call.arguments, mapping_env, lowered, env:, reference_counts:, cleanup: cleanup_statements)

  call_type = binding.type.return_type
  lowered_call = lower_inline_foreign_mapping_expression(
    mapping_expression,
    mapping_env:,
    replacements:,
    owner_analysis:,
    expected_type: expected_type || call_type,
  )
  lowered_call = append_variadic_foreign_call_arguments(
    lowered_call,
    call.arguments,
    binding.type,
    env:,
    lowered:,
    cleanup: cleanup_statements,
  )

  [lowered, lowered_call, call_type, release_assignments, cleanup_statements]
ensure
  @ctx.current_type_substitutions = previous_type_substitutions
end

#lower_foreign_call_inline(expression, binding, env:, type:) ⇒ Object



872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
# File 'lib/milk_tea/core/lowering/calls.rb', line 872

def lower_foreign_call_inline(expression, binding, env:, type:)
  previous_type_substitutions = @ctx.current_type_substitutions
  @ctx.current_type_substitutions = binding.type_substitutions

  owner_analysis = analysis_for_module(binding.owner.module_name)
  mapping_expression = foreign_mapping_expression(binding.ast)
  reference_counts = foreign_mapping_reference_counts(mapping_expression)
  mapping_env = duplicate_env(env)

  binding.ast.params.each_with_index do |param_ast, index|
    public_alias = param_ast.boundary_type ? foreign_mapping_public_alias_name(param_ast.name) : nil
    total_references = reference_counts.fetch(param_ast.name, 0)
    total_references += reference_counts.fetch(public_alias, 0) if public_alias
    next unless total_references > 1
    next if duplicable_foreign_argument_expression?(expression.arguments.fetch(index).value)

    raise LoweringError.new("foreign call #{binding.name} cannot be used inline because #{param_ast.name} is referenced multiple times in its mapping; use it as a statement, local initializer, assignment, or return expression", line: 0, column: 0, path: @ctx.current_analysis_path)
  end

  binding.ast.params.each_with_index do |param_ast, index|
    parameter = binding.type.params.fetch(index)
    next unless automatic_foreign_cstr_temp_needed?(parameter, expression.arguments.fetch(index).value, env:) ||
                automatic_foreign_cstr_list_temp_needed?(parameter, expression.arguments.fetch(index).value, env:)

    raise LoweringError.new("foreign call #{binding.name} cannot be used inline because #{param_ast.name} needs temporary foreign text storage; use it as a statement, local initializer, assignment, or return expression", line: 0, column: 0, path: @ctx.current_analysis_path)
  end

  expression.arguments.drop(binding.type.params.length).each do |argument|
    next unless automatic_variadic_foreign_cstr_temp_needed?(argument.value, env:)

    raise LoweringError.new("foreign call #{binding.name} cannot be used inline because a variadic argument needs temporary foreign text storage; use it as a statement, local initializer, assignment, or return expression", line: 0, column: 0, path: @ctx.current_analysis_path)
  end

  binding.ast.params.each_with_index do |param_ast, index|
    parameter = binding.type.params.fetch(index)
    argument = expression.arguments.fetch(index)
    next unless parameter.passing_mode == :in
    next if addressable_storage_expression?(foreign_argument_expression(argument))

    raise LoweringError.new("foreign call #{binding.name} cannot be used inline because #{param_ast.name} needs temporary in storage; use it as a statement, local initializer, assignment, or return expression", line: 0, column: 0, path: @ctx.current_analysis_path)
  end

  replacements = {}
  binding.ast.params.each_with_index do |param_ast, index|
    parameter = binding.type.params.fetch(index)
    temp_type = parameter.boundary_type || parameter.type
    public_alias = param_ast.boundary_type ? foreign_mapping_public_alias_name(param_ast.name) : nil

    if reference_counts.fetch(param_ast.name, 0).positive?
      current_actual_scope(mapping_env[:scopes])[param_ast.name] = local_binding(type: temp_type, linkage_name: param_ast.name, mutable: false, pointer: false)
      replacements[param_ast.name] = lower_foreign_argument_value(parameter, expression.arguments.fetch(index), env:)
    end

    next unless public_alias && reference_counts.fetch(public_alias, 0).positive?

    current_actual_scope(mapping_env[:scopes])[public_alias] = local_binding(type: parameter.type, linkage_name: public_alias, mutable: false, pointer: false)
    replacements[public_alias] = lower_contextual_expression(expression.arguments.fetch(index).value, env:, expected_type: parameter.type)
  end

  lowered_expression = lower_inline_foreign_mapping_expression(
    mapping_expression,
    mapping_env:,
    replacements:,
    owner_analysis:,
    expected_type: type,
  )
  lowered_expression = append_variadic_foreign_call_arguments(
    lowered_expression,
    expression.arguments,
    binding.type,
    env:,
  )

  converted = foreign_identity_projection_expression(lowered_expression, type)
  return converted if converted

  lowered_expression
ensure
  @ctx.current_type_substitutions = previous_type_substitutions
end

#lower_foreign_call_statement(foreign_call, env:, expected_type:, statement_position:, discard_result: false) ⇒ Object

Raises:



525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/milk_tea/core/lowering/calls.rb', line 525

def lower_foreign_call_statement(foreign_call, env:, expected_type:, statement_position:, discard_result: false)
  lowered, lowered_call, call_type, release_assignments, cleanup_statements = lower_foreign_call_components(
    foreign_call,
    env:,
    expected_type:,
    statement_position:,
  )

  if call_type == @ctx.types.fetch("void")
    lowered << IR::ExpressionStmt.new(expression: lowered_call)
    lowered.concat(release_assignments)
    lowered.concat(cleanup_statements)
    return [lowered, nil]
  end

  raise LoweringError.new("consuming foreign calls must return void", line: 0, column: 0, path: @ctx.current_analysis_path) unless release_assignments.empty?

  if discard_result
    lowered << IR::ExpressionStmt.new(expression: lowered_call)
    lowered.concat(cleanup_statements)
    return [lowered, nil]
  end

  unless cleanup_statements.empty?
    result_name = fresh_c_temp_name(env, "foreign_result")
    lowered << IR::LocalDecl.new(name: result_name, linkage_name: result_name, type: call_type, value: lowered_call)
    lowered.concat(cleanup_statements)
    return [lowered, IR::Name.new(name: result_name, type: call_type, pointer: false)]
  end

  [lowered, lowered_call]
end

#lower_foreign_char_pointer_buffer_argument_value(parameter, argument, env:) ⇒ Object

Raises:



844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
# File 'lib/milk_tea/core/lowering/calls.rb', line 844

def lower_foreign_char_pointer_buffer_argument_value(parameter, argument, env:)
  public_type = parameter.type

  if char_array_text_type?(public_type)
    return lower_char_array_data_pointer(argument.value, env:)
  end

  if str_buffer_type?(public_type)
    return IR::Call.new(
      callee: "mt_str_buffer_prepare_write",
      arguments: [
        lower_str_buffer_data_pointer(argument.value, env:),
        IR::IntegerLiteral.new(value: str_buffer_capacity(public_type), type: @ctx.types.fetch("ptr_uint")),
        lower_str_buffer_dirty_pointer(argument.value, env:),
      ],
      type: parameter.boundary_type,
    )
  end

  lowered_value = lower_contextual_expression(argument.value, env:, expected_type: public_type)
  return IR::Member.new(receiver: lowered_value, member: "data", type: parameter.boundary_type) if public_type.is_a?(Types::Span) && public_type.element_type == @ctx.types.fetch("char")

  converted = foreign_identity_projection_expression(lowered_value, parameter.boundary_type)
  return converted if converted

  raise LoweringError.new("unsupported foreign boundary mapping #{public_type} as #{parameter.boundary_type}", line: 0, column: 0, path: @ctx.current_analysis_path)
end

#lower_foreign_in_argument_value(parameter, argument, env:) ⇒ Object

Raises:



831
832
833
834
835
836
837
838
839
840
841
842
# File 'lib/milk_tea/core/lowering/calls.rb', line 831

def lower_foreign_in_argument_value(parameter, argument, env:)
  address = lower_addr_expression(
    foreign_argument_expression(argument),
    env:,
    target_type: const_pointer_to(parameter.type),
  )

  converted = foreign_identity_projection_expression(address, parameter.boundary_type)
  return converted if converted

  raise LoweringError.new("unsupported foreign in boundary mapping #{parameter.type} as #{parameter.boundary_type}", line: 0, column: 0, path: @ctx.current_analysis_path)
end

#lower_foreign_pointer_argument_value(parameter, argument, env:) ⇒ Object

Raises:



791
792
793
794
795
796
797
798
799
800
# File 'lib/milk_tea/core/lowering/calls.rb', line 791

def lower_foreign_pointer_argument_value(parameter, argument, env:)
  slot_type = foreign_slot_boundary_value_type(parameter.type)
  operand = foreign_argument_expression(argument)
  address = lower_addr_expression(operand, env:, target_type: pointer_to(slot_type))

  converted = foreign_identity_projection_expression(address, parameter.boundary_type)
  return converted if converted

  raise LoweringError.new("unsupported foreign pointer boundary mapping #{parameter.type} as #{parameter.boundary_type}", line: 0, column: 0, path: @ctx.current_analysis_path)
end

#lower_foreign_span_argument_value(parameter, argument, env:) ⇒ Object

Raises:



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
# File 'lib/milk_tea/core/lowering/calls.rb', line 768

def lower_foreign_span_argument_value(parameter, argument, env:)
  public_type = parameter.type
  boundary_type = parameter.boundary_type
  lowered_value = lower_contextual_expression(argument.value, env:, expected_type: public_type)
  return lowered_value if public_type == boundary_type

  public_element_type = public_type.element_type
  boundary_element_type = boundary_type.element_type

  data_expression = IR::Member.new(receiver: lowered_value, member: "data", type: pointer_to(public_element_type))
  converted_data = foreign_identity_projection_expression(data_expression, pointer_to(boundary_element_type))
  raise LoweringError.new("unsupported foreign boundary mapping #{public_type} as #{boundary_type}", line: 0, column: 0, path: @ctx.current_analysis_path) unless converted_data

  len_expression = IR::Member.new(receiver: lowered_value, member: "len", type: @ctx.types.fetch("ptr_uint"))
  IR::AggregateLiteral.new(
    type: boundary_type,
    fields: [
      IR::AggregateField.new(name: "data", value: converted_data),
      IR::AggregateField.new(name: "len", value: len_expression),
    ],
  )
end

#lower_hash_operation_argument(expression, env:, target_type:) ⇒ Object



362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/milk_tea/core/lowering/calls.rb', line 362

def lower_hash_operation_argument(expression, env:, target_type:)
  actual_type = infer_expression_type(expression, env:)
  lowered_expression = lower_expression(expression, env:)
  pointer_type = const_pointer_to(target_type)

  if pointer_type?(actual_type) || ref_type?(actual_type)
    return cast_expression(lowered_expression, pointer_type)
  end

  return cast_expression(lowered_expression.operand, pointer_type) if lowered_expression.is_a?(IR::Unary) && lowered_expression.operator == "*"

  IR::AddressOf.new(expression: lowered_expression, type: pointer_type)
end

#lower_inline_foreign_mapping_call(expression, mapping_env:, replacements:, owner_analysis:, type:) ⇒ Object



1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
# File 'lib/milk_tea/core/lowering/calls.rb', line 1121

def lower_inline_foreign_mapping_call(expression, mapping_env:, replacements:, owner_analysis:, type:)
  kind, callee_name, receiver, callee_type, callee_binding = with_analysis_context(owner_analysis) do
    resolve_callee(expression.callee, mapping_env, arguments: expression.arguments)
  end

  case kind
  when :function
    raise LoweringError.new("consuming foreign calls must be top-level expression statements", line: 0, column: 0, path: @ctx.current_analysis_path) if callee_binding && foreign_function_binding?(callee_binding) && foreign_call_consumes_binding?(callee_binding)

    arguments = expression.arguments.map.with_index do |argument, index|
      expected_arg_type = index < callee_type.params.length ? callee_type.params[index].type : nil
      lower_inline_foreign_mapping_expression(
        argument.value,
        mapping_env:,
        replacements:,
        owner_analysis:,
        expected_type: expected_arg_type,
      )
    end
    IR::Call.new(callee: callee_name, arguments:, type:)
  when :reinterpret
    argument = expression.arguments.fetch(0)
    source_type = with_analysis_context(owner_analysis) do
      infer_expression_type(argument.value, env: mapping_env)
    end
    IR::ReinterpretExpr.new(
      target_type: type,
      source_type:,
      expression: lower_inline_foreign_mapping_expression(
        argument.value,
        mapping_env:,
        replacements:,
        owner_analysis:,
        expected_type: source_type,
      ),
      type:,
    )
  when :hash
    resolution = with_analysis_context(owner_analysis) do
      resolve_hash_specialization(expression.callee, env: mapping_env)
    end
    argument = expression.arguments.fetch(0)
    IR::Call.new(
      callee: resolution.callee_name,
      arguments: [
        lower_inline_hash_operation_argument(
          argument.value,
          mapping_env:,
          replacements:,
          owner_analysis:,
          target_type: resolution.target_type,
        ),
      ],
      type:,
    )
  when :equal
    resolution = with_analysis_context(owner_analysis) do
      resolve_equal_specialization(expression.callee, env: mapping_env)
    end
    left = expression.arguments.fetch(0)
    right = expression.arguments.fetch(1)
    IR::Call.new(
      callee: resolution.callee_name,
      arguments: [
        lower_inline_hash_operation_argument(
          left.value,
          mapping_env:,
          replacements:,
          owner_analysis:,
          target_type: resolution.target_type,
        ),
        lower_inline_hash_operation_argument(
          right.value,
          mapping_env:,
          replacements:,
          owner_analysis:,
          target_type: resolution.target_type,
        ),
      ],
      type:,
    )
  when :order
    resolution = with_analysis_context(owner_analysis) do
      resolve_order_specialization(expression.callee, env: mapping_env)
    end
    left = expression.arguments.fetch(0)
    right = expression.arguments.fetch(1)
    IR::Call.new(
      callee: resolution.callee_name,
      arguments: [
        lower_inline_hash_operation_argument(
          left.value,
          mapping_env:,
          replacements:,
          owner_analysis:,
          target_type: resolution.target_type,
        ),
        lower_inline_hash_operation_argument(
          right.value,
          mapping_env:,
          replacements:,
          owner_analysis:,
          target_type: resolution.target_type,
        ),
      ],
      type:,
    )
  when :zero
    IR::ZeroInit.new(type:)
  when :ref_of
    argument = expression.arguments.fetch(0)
    lowered_argument = lower_inline_foreign_mapping_expression(
      argument.value,
      mapping_env:,
      replacements:,
      owner_analysis:,
    )
    if lowered_argument.is_a?(IR::Name) && lowered_argument.pointer
      cast_expression(lowered_argument, type)
    elsif lowered_argument.is_a?(IR::Unary) && lowered_argument.operator == "*"
      cast_expression(lowered_argument.operand, type)
    else
      IR::AddressOf.new(expression: lowered_argument, type:)
    end
  when :const_ptr_of
    argument = expression.arguments.fetch(0)
    lowered_argument = lower_inline_foreign_mapping_expression(
      argument.value,
      mapping_env:,
      replacements:,
      owner_analysis:,
    )
    if lowered_argument.is_a?(IR::Name) && lowered_argument.pointer
      cast_expression(lowered_argument, type)
    elsif lowered_argument.is_a?(IR::Unary) && lowered_argument.operator == "*"
      cast_expression(lowered_argument.operand, type)
    else
      IR::AddressOf.new(expression: lowered_argument, type:)
    end
  when :read
    argument = expression.arguments.fetch(0)
    IR::Unary.new(
      operator: "*",
      operand: lower_inline_foreign_mapping_expression(
        argument.value,
        mapping_env:,
        replacements:,
        owner_analysis:,
      ),
      type:,
    )
  when :str_buffer_capacity
    receiver_type = with_analysis_context(owner_analysis) do
      infer_expression_type(receiver, env: mapping_env)
    end
    IR::IntegerLiteral.new(value: str_buffer_capacity(receiver_type), type:)
  when :ptr_of
    argument = expression.arguments.fetch(0)
    argument_type = with_analysis_context(owner_analysis) do
      infer_expression_type(argument.value, env: mapping_env)
    end
    if ref_type?(argument_type)
      IR::Cast.new(
        target_type: type,
        expression: lower_inline_foreign_mapping_expression(
          argument.value,
          mapping_env:,
          replacements:,
          owner_analysis:,
        ),
        type:,
      )
    else
      lower_addr_expression(
        argument.value,
        env: mapping_env,
        target_type: type,
      )
    end
  else
    raise LoweringError.new("unsupported inline foreign mapping call kind #{kind}", line: 0, column: 0, path: @ctx.current_analysis_path)
  end
end

#lower_inline_foreign_mapping_expression(expression, mapping_env:, replacements:, owner_analysis:, expected_type: nil) ⇒ Object



997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
# File 'lib/milk_tea/core/lowering/calls.rb', line 997

def lower_inline_foreign_mapping_expression(expression, mapping_env:, replacements:, owner_analysis:, expected_type: nil)
  unless foreign_mapping_uses_inline_replacement?(expression, replacements)
    return with_analysis_context(owner_analysis) do
      lower_expression(expression, env: mapping_env, expected_type:)
    end
  end

  type = with_analysis_context(owner_analysis) do
    infer_expression_type(expression, env: mapping_env, expected_type:)
  end

  case expression
  when AST::Identifier
    replacements.fetch(expression.name)
  when AST::MemberAccess
    receiver_type = with_analysis_context(owner_analysis) do
      infer_expression_type(expression.receiver, env: mapping_env)
    end
    receiver = lower_inline_foreign_mapping_expression(
      expression.receiver,
      mapping_env:,
      replacements:,
      owner_analysis:,
    )
    IR::Member.new(receiver:, member: member_c_name(receiver_type, expression.member), type:)
  when AST::IndexAccess
    receiver_type = with_analysis_context(owner_analysis) do
      infer_expression_type(expression.receiver, env: mapping_env)
    end
    receiver = lower_inline_foreign_mapping_expression(
      expression.receiver,
      mapping_env:,
      replacements:,
      owner_analysis:,
    )
    index = lower_inline_foreign_mapping_expression(
      expression.index,
      mapping_env:,
      replacements:,
      owner_analysis:,
    )
    if array_type?(receiver_type) && addressable_storage_expression?(expression.receiver)
      IR::CheckedIndex.new(receiver:, index:, receiver_type:, type:)
    elsif receiver_type.is_a?(Types::Span)
      IR::CheckedSpanIndex.new(receiver:, index:, receiver_type:, type:)
    else
      IR::Index.new(receiver:, index:, type:)
    end
  when AST::Call
    lower_inline_foreign_mapping_call(expression, mapping_env:, replacements:, owner_analysis:, type:)
  when AST::UnaryOp
    IR::Unary.new(
      operator: expression.operator,
      operand: lower_inline_foreign_mapping_expression(
        expression.operand,
        mapping_env:,
        replacements:,
        owner_analysis:,
        expected_type: type,
      ),
      type:,
    )
  when AST::BinaryOp
    left_type, right_type = with_analysis_context(owner_analysis) do
      infer_binary_operand_types(expression, env: mapping_env, expected_type: type)
    end
    operand_type = promoted_binary_operand_type(expression.operator, left_type, right_type)
    left = lower_inline_foreign_mapping_expression(
      expression.left,
      mapping_env:,
      replacements:,
      owner_analysis:,
      expected_type: operand_type || type,
    )
    right = lower_inline_foreign_mapping_expression(
      expression.right,
      mapping_env:,
      replacements:,
      owner_analysis:,
      expected_type: operand_type || left.type,
    )
    left = cast_expression(left, operand_type) if operand_type
    right = cast_expression(right, operand_type) if operand_type
    IR::Binary.new(operator: expression.operator, left:, right:, type:)
  when AST::IfExpr
    IR::Conditional.new(
      condition: lower_inline_foreign_mapping_expression(
        expression.condition,
        mapping_env:,
        replacements:,
        owner_analysis:,
        expected_type: @ctx.types.fetch("bool"),
      ),
      then_expression: lower_inline_foreign_mapping_expression(
        expression.then_expression,
        mapping_env:,
        replacements:,
        owner_analysis:,
        expected_type: type,
      ),
      else_expression: lower_inline_foreign_mapping_expression(
        expression.else_expression,
        mapping_env:,
        replacements:,
        owner_analysis:,
        expected_type: type,
      ),
      type:,
    )
  when AST::PrefixCast
    lowered_expr = lower_inline_foreign_mapping_expression(
      expression.expression,
      mapping_env:,
      replacements:,
      owner_analysis:,
    )
    IR::Cast.new(target_type: type, expression: lowered_expr, type:)
  else
    with_analysis_context(owner_analysis) do
      lower_expression(expression, env: mapping_env, expected_type:)
    end
  end
end

#lower_inline_hash_operation_argument(expression, mapping_env:, replacements:, owner_analysis:, target_type:) ⇒ Object



1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
# File 'lib/milk_tea/core/lowering/calls.rb', line 1305

def lower_inline_hash_operation_argument(expression, mapping_env:, replacements:, owner_analysis:, target_type:)
  actual_type = with_analysis_context(owner_analysis) do
    infer_expression_type(expression, env: mapping_env)
  end
  lowered_expression = lower_inline_foreign_mapping_expression(
    expression,
    mapping_env:,
    replacements:,
    owner_analysis:,
  )
  pointer_type = const_pointer_to(target_type)

  if pointer_type?(actual_type) || ref_type?(actual_type)
    return cast_expression(lowered_expression, pointer_type)
  end

  return cast_expression(lowered_expression.operand, pointer_type) if lowered_expression.is_a?(IR::Unary) && lowered_expression.operator == "*"

  IR::AddressOf.new(expression: lowered_expression, type: pointer_type)
end

#lower_method_receiver_argument(receiver, callee_type, callee_binding, env:) ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/milk_tea/core/lowering/calls.rb', line 315

def lower_method_receiver_argument(receiver, callee_type, callee_binding, env:)
  lowered_receiver = lower_expression(receiver, env:)
  declared_receiver_type = callee_type.receiver_type

  if pointer_lowered_method_receiver?(callee_type, callee_binding)
    return lowered_receiver if ref_type?(lowered_receiver.type)
    return lowered_receiver if pointer_type?(lowered_receiver.type)

    if lowered_receiver.is_a?(IR::Name) && lowered_receiver.pointer
      return lowered_receiver
    end

    if lowered_receiver.is_a?(IR::Unary) && lowered_receiver.operator == "*"
      return lowered_receiver.operand
    end

    return IR::AddressOf.new(expression: lowered_receiver, type: lowered_receiver.type)
  end

  return lowered_receiver if declared_receiver_type && pointer_type?(declared_receiver_type)

  if ref_type?(lowered_receiver.type)
    return IR::Unary.new(operator: "*", operand: lowered_receiver, type: referenced_type(lowered_receiver.type))
  end

  if lowered_receiver.is_a?(IR::Name) && lowered_receiver.pointer
    return IR::Unary.new(operator: "*", operand: lowered_receiver, type: lowered_receiver.type)
  end

  if pointer_type?(lowered_receiver.type)
    return IR::Unary.new(operator: "*", operand: lowered_receiver, type: pointee_type(lowered_receiver.type))
  end

  lowered_receiver
end

#lower_simd_lane_with(_kind, receiver, expression, env:, type:) ⇒ Object



1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
# File 'lib/milk_tea/core/lowering/calls.rb', line 1606

def lower_simd_lane_with(_kind, receiver, expression, env:, type:)
  receiver_ir = lower_expression(receiver, env:)
  index_ir = lower_expression(expression.arguments[0].value, env:, expected_type: @ctx.types.fetch("int"))
  value_ir = lower_contextual_expression(expression.arguments[1].value, env:, expected_type: type.element_type)

  IR::SimdLaneWith.new(
    src: receiver_ir,
    index: index_ir,
    value: value_ir,
    type:,
  )
end

#lower_specialization(expression, env:, type:) ⇒ Object

Raises:



1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
# File 'lib/milk_tea/core/lowering/calls.rb', line 1519

def lower_specialization(expression, env:, type:)
  if expression.callee.is_a?(AST::Identifier) && expression.callee.name == "zero"
    return IR::ZeroInit.new(type:)
  end

  if expression.callee.is_a?(AST::Identifier) && expression.callee.name == "default"
    resolution = resolve_default_specialization(expression, env:)
    return IR::Call.new(callee: resolution.callee_name, arguments: [], type:) if resolution.binding

    return IR::ZeroInit.new(type:)
  end

  if (literal = lower_compile_time_literal(compile_time_const_value(expression, env:), type))
    return literal
  end

  if (callable_resolution = resolve_specialized_callable_binding(expression, env:))
    callable_kind, function_binding, = callable_resolution
    raise LoweringError.new("specialized method must be called", line: 0, column: 0, path: @ctx.current_analysis_path) if callable_kind == :method

    raise LoweringError.new("foreign function #{function_binding.name} cannot be used as a value", line: 0, column: 0, path: @ctx.current_analysis_path) if foreign_function_binding?(function_binding)

    if function_binding.external
      return IR::Name.new(name: external_function_c_name(function_binding), type:, pointer: false)
    end

    return IR::Name.new(
      name: function_binding_c_name(function_binding, module_name: function_binding.owner.module_name),
      type:,
      pointer: false,
    )
  end

  raise LoweringError.new("specialization #{expression.callee.name} must be called", line: 0, column: 0, path: @ctx.current_analysis_path) if expression.callee.is_a?(AST::Identifier)

  raise LoweringError.new("unsupported specialization #{expression.class.name}", line: 0, column: 0, path: @ctx.current_analysis_path)
end

#lower_variadic_foreign_argument(argument, env:, lowered:, cleanup:) ⇒ Object

Raises:



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
# File 'lib/milk_tea/core/lowering/calls.rb', line 967

def lower_variadic_foreign_argument(argument, env:, lowered:, cleanup:)
  actual_type = infer_expression_type(argument.value, env:)
  return lower_contextual_expression(argument.value, env:, expected_type: nil) unless actual_type == @ctx.types.fetch("str")

  lowered_argument = lower_foreign_argument_value(
    Types::Registry.parameter("__mt_variadic", actual_type, passing_mode: :plain, boundary_type: @ctx.types.fetch("cstr")),
    argument,
    env:,
  )
  return lowered_argument unless temporary_foreign_cstr_expression?(lowered_argument)

  raise LoweringError.new("foreign variadic call cannot be used inline because an extra argument needs temporary foreign text storage; use it as a statement, local initializer, assignment, or return expression", line: 0, column: 0, path: @ctx.current_analysis_path) unless lowered && cleanup

  temp_name = fresh_c_temp_name(env, "foreign_arg")
  lowered << IR::LocalDecl.new(
    name: temp_name,
    linkage_name: temp_name,
    type: @ctx.types.fetch("cstr"),
    value: lowered_argument,
  )
  cleanup << IR::ExpressionStmt.new(
    expression: IR::Call.new(
      callee: "mt_free_foreign_cstr_temp",
      arguments: [IR::Name.new(name: temp_name, type: @ctx.types.fetch("cstr"), pointer: false)],
      type: @ctx.types.fetch("void"),
    ),
  )
  IR::Name.new(name: temp_name, type: @ctx.types.fetch("cstr"), pointer: false)
end

#prepare_foreign_in_argument(parameter, argument, source_env:, lowered:, env:) ⇒ Object



810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# File 'lib/milk_tea/core/lowering/calls.rb', line 810

def prepare_foreign_in_argument(parameter, argument, source_env:, lowered:, env:)
  return argument unless parameter.passing_mode == :in

  operand = foreign_argument_expression(argument)
  return argument if addressable_storage_expression?(operand)

  temp_name = fresh_c_temp_name(env, "foreign_in")
  lowered << IR::LocalDecl.new(
    name: temp_name,
    linkage_name: temp_name,
    type: parameter.type,
    value: lower_contextual_expression(operand, env: source_env, expected_type: parameter.type),
  )
  current_actual_scope(source_env[:scopes])[temp_name] = local_binding(type: parameter.type, linkage_name: temp_name, mutable: false, pointer: false)

  AST::Argument.new(
    name: argument.name,
    value: AST::Identifier.new(name: temp_name),
  )
end

#simd_method_kind(receiver_type, name) ⇒ Object



1570
1571
1572
1573
1574
1575
1576
# File 'lib/milk_tea/core/lowering/calls.rb', line 1570

def simd_method_kind(receiver_type, name)
  return unless simd_type?(receiver_type)

  case name
  when "with" then :simd_lane_with
  end
end

#substitute_foreign_mapping_expression(expression, replacements) ⇒ Object



1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
# File 'lib/milk_tea/core/lowering/calls.rb', line 1386

def substitute_foreign_mapping_expression(expression, replacements)
  case expression
  when AST::Identifier
    replacements.fetch(expression.name, expression)
  when AST::MemberAccess
    AST::MemberAccess.new(receiver: substitute_foreign_mapping_expression(expression.receiver, replacements), member: expression.member)
  when AST::IndexAccess
    AST::IndexAccess.new(
      receiver: substitute_foreign_mapping_expression(expression.receiver, replacements),
      index: substitute_foreign_mapping_expression(expression.index, replacements),
    )
  when AST::Specialization
    AST::Specialization.new(
      callee: substitute_foreign_mapping_expression(expression.callee, replacements),
      arguments: expression.arguments.map do |argument|
        AST::Argument.new(name: argument.name, value: substitute_foreign_mapping_expression(argument.value, replacements))
      end,
    )
  when AST::Call
    AST::Call.new(
      callee: substitute_foreign_mapping_expression(expression.callee, replacements),
      arguments: expression.arguments.map do |argument|
        AST::Argument.new(name: argument.name, value: substitute_foreign_mapping_expression(argument.value, replacements))
      end,
    )
  when AST::UnaryOp
    AST::UnaryOp.new(operator: expression.operator, operand: substitute_foreign_mapping_expression(expression.operand, replacements))
  when AST::BinaryOp
    AST::BinaryOp.new(
      operator: expression.operator,
      left: substitute_foreign_mapping_expression(expression.left, replacements),
      right: substitute_foreign_mapping_expression(expression.right, replacements),
    )
  when AST::IfExpr
    AST::IfExpr.new(
      condition: substitute_foreign_mapping_expression(expression.condition, replacements),
      then_expression: substitute_foreign_mapping_expression(expression.then_expression, replacements),
      else_expression: substitute_foreign_mapping_expression(expression.else_expression, replacements),
    )
  when AST::UnsafeExpr
    AST::UnsafeExpr.new(expression: substitute_foreign_mapping_expression(expression.expression, replacements))
  when AST::PrefixCast
    AST::PrefixCast.new(target_type: expression.target_type, expression: substitute_foreign_mapping_expression(expression.expression, replacements))
  else
    expression
  end
end

#task_expression_root_proc_bridge?(expression, expected_type, env:) ⇒ Boolean

Returns:

  • (Boolean)


445
446
447
448
449
450
# File 'lib/milk_tea/core/lowering/calls.rb', line 445

def task_expression_root_proc_bridge?(expression, expected_type, env:)
  return false unless task_root_proc_type?(expected_type)

  actual_type = infer_expression_type(expression, env:)
  actual_type.is_a?(Types::Task) && actual_type == expected_type.return_type
end

#temporary_foreign_cstr_expression?(expression) ⇒ Boolean

Returns:

  • (Boolean)


1515
1516
1517
# File 'lib/milk_tea/core/lowering/calls.rb', line 1515

def temporary_foreign_cstr_expression?(expression)
  expression.is_a?(IR::Call) && expression.callee == "mt_foreign_str_to_cstr_temp"
end

#wrap_expression_in_ref_of(expression) ⇒ Object



461
462
463
464
465
466
# File 'lib/milk_tea/core/lowering/calls.rb', line 461

def wrap_expression_in_ref_of(expression)
  AST::Call.new(
    callee: AST::Identifier.new(name: "ref_of"),
    arguments: [AST::Argument.new(name: nil, value: expression)],
  )
end

#wrap_task_expression_in_root_proc(expression, env:) ⇒ Object



452
453
454
455
456
457
458
459
# File 'lib/milk_tea/core/lowering/calls.rb', line 452

def wrap_task_expression_in_root_proc(expression, env:)
  task_type = infer_expression_type(expression, env:)
  AST::ProcExpr.new(
    params: [],
    return_type: ast_type_ref_for(task_type),
    body: [AST::ReturnStmt.new(value: expression)],
  )
end