Class: MilkTea::Lowerer

Defined Under Namespace

Classes: Artifacts, LoweringContext

Constant Summary

Constants included from MilkTea::Lowering::Resolve

MilkTea::Lowering::Resolve::COMPILE_TIME_BUILTINS, MilkTea::Lowering::Resolve::PASS_THROUGH_BUILTINS

Constants included from Intrinsics

Intrinsics::ATOMIC_METHOD_KINDS, Intrinsics::BUILTIN_CSTR, Intrinsics::EVENT_METHOD_KINDS, Intrinsics::EVENT_METHOD_NAMES, Intrinsics::SIMD_METHOD_KINDS, Intrinsics::SPECIALIZED_RECEIVERS, Intrinsics::STR_BUFFER_METHOD_KINDS, Intrinsics::STR_BUFFER_METHOD_NAMES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from MilkTea::Lowering::Utils

#addressable_storage_expression?, #array_element_type, #array_length, #array_to_span_compatible?, #array_type?, #bind_let_else_local?, #c_local_name, #c_reserved_identifier?, #c_type_name, #callable_type?, #cfg_block_always_terminates?, #char_array_text_type?, #cleanup_safe_return_expression?, #cleanup_statements, #collection_loop_item_value, #collection_loop_stop_value, #compile_time_builtin_function_type, #compile_time_builtin_specialization_function_type, #conditional_common_type, #conditional_null_common_type, #contains_label_target?, #contains_proc_storage_type?, #contains_task_type?, #cstr_list_trackable_type?, #cstr_trackable_type?, #current_actual_scope, #duplicate_env, #empty_env, #enum_member_c_name, #env_with_refinements, #external_function_c_name, #flow_refinements, #forward_declarable_external_opaque?, #fresh_c_temp_name, #fresh_proc_symbol, #function_binding_c_name, #generic_integer_type_argument?, #generic_type_argument_suffix, #if_expression_branch_compatible?, #imported_value_c_name, #infer_field_receiver_type, #infer_index_result_type, #infer_method_receiver_type, #infer_option_propagation_details, #infer_range_loop_type, #infer_result_propagation_details, #infer_result_propagation_type, #infer_result_propagation_types, #infer_value_type, #integer_type?, #integer_type_argument?, #let_else_binding_projection, #let_else_discards_binding?, #let_else_error_type, #let_else_failure_condition, #let_else_storage_c_name, #let_else_success_type, #local_binding, #lookup_value, #loop_exit_break, #loop_exit_continue, #loop_exit_label, #loop_exit_statement, #loop_flow, #lower_assignment_binding_target, #lower_assignment_target, #lower_bound_identifier, #lower_compile_time_literal, #lower_defer_cleanup_body, #lower_fatal_statement, #lower_loop_exit, #lower_range_match_condition, #lower_static_storage_initializer, #merge_refinements, #module_c_prefix, #module_function_c_name, #module_value_c_name, #nested_loop_flow, #null_test_refinements, #null_type, #nullable_candidate?, #nullable_some_literal, #opaque_c_type_name, #opaque_forward_declarable?, #option_let_else_type?, #pointer_like_type?, #pointer_to, #proc_env_pointer_type, #proc_invoke_function_type, #proc_release_function_type, #proc_retain_function_type, #range_end_of, #range_iterable?, #range_start_of, #read_call?, #reject_format_releases_for_assignment, #result_let_else_type?, #rewrite_static_storage_initializer, #sanitize_identifier, #scopes_with_refinements, #simd_type?, #snapshot_env, #static_storage_imported_analysis, #stored_ref_supported_type?, #str_buffer_capacity, #str_buffer_storage_capacity, #str_buffer_to_span_compatible?, #str_buffer_type?, #struct_contains_string_field?, #switch_loop_flow, #switch_loop_target, #terminating_ir_statement?, #validate_generic_type!, #value_c_name, #variant_binding_projection_expression, #variant_match_arm_name_from_pattern, #wildcard_arm_pattern?, #with_analysis_context, #wrap_nullable_field_value

Methods included from MilkTea::Lowering::Dyn

#dyn_vtable_struct_type, #ensure_dyn_vtable, #ensure_dyn_vtable_struct, #generate_dyn_vtable_constant, #generate_dyn_vtable_wrappers, #lower_adapt_call, #lower_dyn_method_call

Methods included from MilkTea::Lowering::Resolve

#aggregate_arithmetic_result_type, #aggregate_scalar_result, #analysis_for_module, #attribute_binding_supports_target?, #attribute_target_kind, #binary_right_env, #binding_cstr_backed?, #binding_cstr_list_backed?, #build_direct_function_proc_invoke_function, #builtin_attribute_binding, #cast_expression, #collect_type_substitutions, #compile_time_const_value, #compile_time_numeric_const_expression?, #const_declaration_for_module, #contextual_numeric_compatibility?, #copy_cstr_metadata!, #cstr_backed_expression?, #cstr_backed_storage_value?, #cstr_list_backed_expression?, #cstr_list_backed_storage_value?, #cstr_metadata_exit_envs_for_if_statement, #current_type_params, #direct_function_identity_expression?, #direct_function_to_proc_contextual_compatibility?, #each_non_raw_module_analysis, #each_raw_module_analysis, #evaluate_attribute_arg_call, #evaluate_attribute_of_call, #evaluate_attributes_of_call, #evaluate_callable_of_call, #evaluate_compile_time_call, #evaluate_const_function_body_lower, #evaluate_field_of_call, #evaluate_fields_of_call, #evaluate_has_attribute_call, #evaluate_members_of_call, #evaluate_reflection_target_argument, #evaluate_type_returning_call, #exact_compile_time_numeric_compatibility?, #external_numeric_assignment_target?, #extract_type_callee_info, #ffi_external_layout_root_type, #find_attribute_application, #find_struct_decl_by_name, #float_literal_expression?, #foreign_identity_projection_expression, #function_type_for_name, #harmonize_binary_float_literal_types, #harmonize_binary_integer_literal_types, #imports_for_module, #infer_binary_operand_types, #infer_expression_type, #infer_field_handle_member_type, #infer_function_type_arguments, #infer_member_handle_member_type, #infer_null_literal_type, #infer_receiver_type_substitutions, #instantiate_function_binding, #instantiate_function_binding_with_receiver, #integer_literal_expression?, #interface_implementation_key, #literal_type_argument_name_candidate?, #lower_array_to_span_expression, #lower_fn_to_proc_expression, #lower_str_buffer_to_span_expression, #merge_cstr_metadata_after_if_statement!, #method_analysis_key, #methods_receiver_type_argument_names!, #pointer_arithmetic_result_type, #pointer_lowered_method_receiver?, #pointer_lowered_sync_method_receiver?, #promoted_binary_operand_type, #propagating_expected_type, #receiver_type_uses_pointer_lowering?, #record_external_layout_assertion, #reflection_identifier_name, #reflection_positional_arguments?, #reflection_type_from_expression, #reinterpret_expression, #replace_binding_cstr_metadata!, #resolve_attribute_name_argument, #resolve_callable_handle_argument, #resolve_callee, #resolve_current_module_const_value, #resolve_default_specialization, #resolve_equal_specialization, #resolve_explicit_associated_binding, #resolve_explicit_default_binding, #resolve_explicit_equal_binding, #resolve_explicit_format_append_binding, #resolve_explicit_format_binding, #resolve_explicit_format_len_binding, #resolve_explicit_hash_binding, #resolve_explicit_instance_binding, #resolve_explicit_order_binding, #resolve_expression_callee, #resolve_field_handle_type_ref, #resolve_hash_specialization, #resolve_identifier_callee, #resolve_imported_module_const_value, #resolve_interface_ref, #resolve_member_access_callee, #resolve_named_generic_type, #resolve_named_generic_type_for_analysis, #resolve_named_literal_type_argument, #resolve_nested_type_ref, #resolve_order_specialization, #resolve_specialization_callee, #resolve_specialization_type_arguments, #resolve_specialized_callable_binding, #resolve_struct_handle_argument, #resolve_type_argument, #resolve_type_argument_ref, #resolve_type_expression, #resolve_type_member, #resolve_type_member_const_value, #resolve_type_ref, #resolve_type_ref_for_analysis, #resolved_attribute_applications_for_target, #same_attribute_binding?, #simulate_cstr_metadata_block, #specialize_function_binding, #struct_handle_for_type, #substitute_type, #substitute_value_binding, #trackable_binding_names, #try_resolve_type_ref, #type_contains_array_storage?, #type_implements_interface?, #types_for_module, #update_cstr_metadata_for_assignment!, #validate_function_type_param_constraints!, #validate_methods_receiver_type_arguments!, #value_param_declared_type, #value_param_literal, #value_param_substitution

Methods included from MilkTea::Lowering::StrBuffer

#lower_char_array_data_pointer, #lower_str_buffer_data_pointer, #lower_str_buffer_data_pointer_from_lowered, #lower_str_buffer_dirty_pointer, #lower_str_buffer_dirty_pointer_from_lowered, #lower_str_buffer_len_pointer, #lower_str_buffer_len_pointer_from_lowered, #str_buffer_args, #str_buffer_method_kind, #str_buffer_method_type

Methods included from MilkTea::Lowering::ForeignCstr

#inlineable_foreign_argument_expression?, #lower_contextual_expression, #lower_direct_cstr_list_argument, #lower_foreign_cstr_list_argument_value, #materialize_pointer_backed_value

Methods included from MilkTea::Lowering::Calls

#append_variadic_foreign_call_arguments, #atomic_method_kind, #automatic_foreign_cstr_list_temp_needed?, #automatic_foreign_cstr_temp_needed?, #automatic_variadic_foreign_cstr_temp_needed?, #bind_foreign_mapping_arguments, #consuming_foreign_call_refinements, #consuming_foreign_release_assignments, #consuming_foreign_release_bindings, #duplicable_foreign_argument_expression?, #expand_function_defaults, #foreign_argument_expression, #foreign_argument_needs_temporary_binding?, #foreign_call_consumes_binding?, #foreign_call_info, #foreign_function_binding?, #foreign_mapping_expression, #foreign_mapping_implicit_call?, #foreign_mapping_public_alias_name, #foreign_mapping_reference_counts, #foreign_mapping_uses_inline_replacement?, #foreign_slot_boundary_value_type, #implicit_ref_argument_bridge?, #inlineable_single_direct_call_names, #lower_addr_expression, #lower_atomic_method_call, #lower_call, #lower_call_arguments, #lower_event_subscribe_call, #lower_foreign_argument_value, #lower_foreign_call_components, #lower_foreign_call_inline, #lower_foreign_call_statement, #lower_foreign_char_pointer_buffer_argument_value, #lower_foreign_in_argument_value, #lower_foreign_pointer_argument_value, #lower_foreign_span_argument_value, #lower_hash_operation_argument, #lower_inline_foreign_mapping_call, #lower_inline_foreign_mapping_expression, #lower_inline_hash_operation_argument, #lower_method_receiver_argument, #lower_simd_lane_with, #lower_specialization, #lower_variadic_foreign_argument, #prepare_foreign_in_argument, #simd_method_kind, #substitute_foreign_mapping_expression, #task_expression_root_proc_bridge?, #temporary_foreign_cstr_expression?, #wrap_expression_in_ref_of, #wrap_task_expression_in_root_proc

Methods included from MilkTea::Lowering::Expressions

#build_dynamic_format_string_parts, #build_dynamic_format_string_temp_setup, #build_expression_from_qualified_name, #copy_explicit_format_sink_str_parts, #ensure_tuple_struct, #explicit_format_sink_append_call, #explicit_format_sink_call_info, #explicit_format_sink_runtime_call, #explicit_format_sink_target, #explicit_format_sink_target_buffer_view, #foreign_call_requires_statement_lowering?, #format_append_linkage_name, #format_length_linkage_name, #format_string_append_plan, #format_string_bin_append_plan, #format_string_custom_receiver_argument, #format_string_has_dynamic_parts?, #format_string_hex_append_plan, #format_string_oct_append_plan, #format_string_part_append_expression, #format_string_part_append_statements, #format_string_part_length_expression, #format_string_part_parameter_expression, #format_string_result_data_pointer, #format_string_static_text, #lower_aggregate_binary_operation, #lower_compile_time_handle_member, #lower_explicit_format_sink_expression_statement, #lower_expression, #lower_member_access, #lower_soa_indexed_field_access, #lower_vector_binary_operation, #lower_vector_binary_operation_on_vectors, #lower_vector_unary_operation, #materialize_prepared_expression, #member_c_name, #prepare_binary_expression_for_inline_lowering, #prepare_call_expression_for_inline_lowering, #prepare_expression_for_inline_lowering, #prepare_expression_with_cleanups, #prepare_format_string_expression_for_inline_lowering, #prepare_if_expression_for_inline_lowering, #prepare_match_expression_for_inline_lowering, #prepare_result_propagation_for_inline_lowering, #reachability_children, #register_prepared_temp!, #resolve_type_ref_with_fallback, #sanitize_type_name_for_tuple, #self_referencing_variant_field_access?, #sized_layout_ct_value?, #tuple_arm_condition, #tuple_type_name, #type_reaches_target?, #type_reaches_target_with_visited?

Methods included from MilkTea::Lowering::Loops

#collect_pfor_ir_names_expr, #collect_pfor_ir_names_stmt, #collect_pfor_local_decls, #collect_pfor_written_names, #collect_pfor_written_stmt, #iterator_loop_info, #lower_collection_for_stmt, #lower_detach_expr, #lower_for_stmt, #lower_gather_stmt, #lower_iterator_for_stmt, #lower_parallel_block_stmt, #lower_parallel_collection_for_stmt, #lower_range_for_stmt, #lower_range_index_assignment, #lower_threaded_for_stmt, #lower_while_stmt, #nullable_iterator_item_type?, #pfor_assignment_base_name, #rewrite_pfor_array_captures, #rewrite_pfor_expr, #rewrite_pfor_stmt, #validate_pfor_no_ref_captures!, #validate_pfor_write_conflicts!

Methods included from MilkTea::Lowering::Proc

#build_proc_invoke_function, #build_proc_noop_release_function, #build_proc_noop_retain_function, #build_proc_release_function, #build_proc_retain_function, #collect_proc_captures_from_expression, #collect_proc_captures_from_statement, #collect_proc_captures_from_statements, #expression_contains_proc_expr?, #lower_async_frame_proc_nullable_release_statements, #lower_proc_contained_lifecycle_statements, #lower_proc_contained_release_statements, #lower_proc_contained_retain_statements, #lower_proc_nullable_release_statements, #lower_proc_release_expression, #lower_proc_retain_expression, #lower_proc_selective_retain_statements, #proc_capture_binding, #proc_capture_entries

Methods included from MilkTea::Lowering::Block

#dereference_if_self_ref, #inline_loop_element_type, #lower_assignment_stmt, #lower_block, #lower_destructure_decl, #lower_emit_stmt, #lower_emitted_const, #lower_emitted_function, #lower_emitted_struct, #lower_expression_stmt, #lower_if_stmt, #lower_inline_for_stmt, #lower_inline_if_stmt, #lower_inline_match_stmt, #lower_inline_while_stmt, #lower_local_decl_stmt, #lower_match_stmt, #lower_proc_expression_for_local, #lower_range_match_stmt, #lower_return_stmt, #lower_string_match_stmt, #lower_tuple_match_stmt, #lower_unsafe_stmt, #lower_variant_struct_pattern_match, #lower_when_stmt, #variant_self_referencing_field?

Methods included from MilkTea::Lowering::Async

#analyze_async_function, #analyze_async_statements!, #ast_type_ref_for, #async_bind_local!, #async_collection_index_field_key, #async_collection_index_field_name, #async_collection_iterable_field_key, #async_collection_iterable_field_name, #async_complete_statements, #async_expression_contains_await?, #async_frame_cast_declaration, #async_frame_field_c_name, #async_frame_field_expression, #async_frame_local_name, #async_frame_raw_name, #async_local_decl_field_key, #async_local_decl_field_name, #async_local_decl_types, #async_main_runtime_callee_name, #async_match_binding_field_key, #async_match_binding_field_name, #async_resume_env_for, #async_return_context, #async_state_label, #async_task_call, #async_task_frame_expression, #async_variant_match_arm_binding, #bind_async_variant_match_arm_env!, #build_async_await_field_info, #build_async_cancel_function, #build_async_constructor_function, #build_async_frame_type, #build_async_main_entrypoint, #build_async_ready_function, #build_async_release_function, #build_async_resume_function, #build_async_set_waiter_function, #build_async_take_result_function, #build_async_while_with_condition_setup, #build_root_main_entrypoint, #build_root_main_entrypoint_bridge, #fresh_async_temp_name, #lower_async_assignment_statement, #lower_async_await_statement, #lower_async_body, #lower_async_cf_collection_for_stmt, #lower_async_cf_for_stmt, #lower_async_cf_if_stmt, #lower_async_cf_match_stmt, #lower_async_cf_parallel_collection_for_stmt, #lower_async_cf_range_for_stmt, #lower_async_cf_statements, #lower_async_cf_while_stmt, #lower_async_cleanup_entries, #lower_async_collection_for_stmt, #lower_async_defer_cleanup, #lower_async_expression_statement, #lower_async_for_stmt, #lower_async_local_decl_statement, #lower_async_loop_exit, #lower_async_non_await_statements, #lower_async_parallel_collection_for_stmt, #lower_async_range_for_stmt, #lower_async_return_statement, #lower_async_while_stmt, #lower_contained_task_release_statements, #lower_opt_task_value_release_statements, #lower_range_call, #normalize_async_assignment_target, #normalize_async_body, #normalize_async_expression, #normalize_async_if_branches, #normalize_async_if_statement, #normalize_async_statement, #normalize_async_statements, #reusable_async_await_task_field_name, #root_main_entrypoint_signature, #statements_contain_await?

Methods included from MilkTea::Lowering::Functions

#lower_async_function_decl, #lower_function_decl, #lower_functions, #resolve_extending_receiver_type, #resolve_value_type_params

Methods included from MilkTea::Lowering::Events

#active_event_slot_continue_guard, #array_of, #build_event_emit_function, #build_event_subscribe_function, #build_event_subscribe_stateful_function, #build_event_unsubscribe_function, #build_event_wait_function, #build_event_wait_ready_function, #build_event_wait_release_function, #build_event_wait_set_waiter_function, #build_event_wait_take_result_function, #ensure_event_error_enum, #ensure_event_runtime, #ensure_subscription_runtime, #event_failure_literal, #event_immediate_failure_task_literal, #event_listener_call_expression, #event_listener_function_type, #event_member_from_owner_type, #event_method_kind, #event_method_type, #event_next_generation_expression, #event_slot_activate_stateful_statements, #event_slot_activate_statements, #event_slot_active_expression, #event_slot_clear_statements, #event_slot_field_expression, #event_slot_local_decl, #event_slot_pointer_expression, #event_slot_wait_frame_expression, #event_stateful_listener_call_expression, #event_stateful_listener_function_type, #event_subscription_literal, #event_subscription_success_literal, #event_task_literal, #event_task_literal_from_raw_frame, #event_unsubscribe_call, #event_wait_success_literal, #inactive_event_slot_continue_guard, #lower_event_storage_pointer, #snapshot_field_expression, #subscription_field_expression, #void_value_expression, #wait_frame_field_expression

Methods included from MilkTea::Lowering::Declarations

#ensure_registered_storage_type_types, #expanded_declarations, #lower_const_value_literal, #lower_constants, #lower_enums, #lower_globals, #lower_imported_external_opaques, #lower_opaques, #lower_static_assert, #lower_static_asserts, #lower_struct_decl, #lower_structs, #lower_unions, #lower_variants, #static_initializer_ir_has_call?

Methods included from MilkTea::Lowering::Scans

#analysis_uses_fatal?, #analysis_uses_offsetof?, #block_uses_expression_pattern?, #block_uses_fatal?, #block_uses_offsetof?, #build_method_definitions, #collect_includes, #collect_nested_structs, #collect_one_struct_decl, #collect_structs, #expression_uses_pattern?, #fatal_expression?, #lower_when_chosen_body, #normalized_include_header, #offsetof_expression?, #prepare_analysis, #program_uses_fatal?, #program_uses_offsetof?, #standard_c_runtime_header?, #statement_uses_expression_pattern?

Methods included from Intrinsics

#current_nested_types, #event_subscription_result_type, #event_wait_result_type, #lookup_named_type, #method_receiver_nested_scope, #range_expr?, #string_literal_cstr_compatibility?, #type_ref_from_specialization

Methods included from Types::Predicates

#arity_error_message, #array_element_type, #array_length, #array_type?, #atomic_element_type, #atomic_type?, #call_arity_matches?, #callable_param_ref_supported?, #char_array_text_type?, #char_pointer_type?, #char_type?, #collection_loop_binding_type, #collection_loop_ref_element_type?, #collection_loop_type, #common_integer_type, #common_numeric_type, #const_pointer_to, #const_pointer_type?, #contains_ref_type?, #contains_type_var?, #contextual_int_to_float_compatibility?, #contextual_int_to_float_target?, #dyn_type?, #exact_integer_constant_value, #exactly_representable_float32?, #external_numeric_compatibility?, #external_typed_null_pointer_compatibility?, #flatten_field_types, #float_constant_fits_type?, #foreign_boundary_element_compatible?, #foreign_char_pointer_buffer_boundary_compatible?, #foreign_external_layout_compatible?, #foreign_external_layout_field_compatible?, #foreign_function_type_projection_compatible?, #foreign_identity_projection_cast_compatible?, #foreign_identity_projection_compatible?, #foreign_identity_projection_reinterpret_compatible?, #foreign_opaque_c_name, #foreign_span_boundary_compatible?, #function_type_matches_proc_type?, #generic_integer_type_argument?, #integer_constant_fits_type?, #integer_like_char_source_type?, #integer_to_char_compatibility?, #integer_type_argument?, #lossless_external_integer_compatibility?, #lossless_integer_compatibility?, #method_dispatch_receiver_type, #mutable_pointer_type?, #mutable_to_const_pointer_compatibility?, #native_foreign_layout_compatible?, #null_assignable_to?, #numeric_constant_fits_type?, #opaque_type?, #own_to_raw_pointer_compatibility?, #own_type?, #owned_referent_type, #pointee_type, #pointer_type?, #proc_type?, #quat_vec4_layout_compatible?, #ref_lifetime, #ref_type?, #ref_type_without_lifetime?, #referenced_type, #same_external_opaque_c_name?, #same_external_opaque_handle_pointer_compatibility?, #signed_type_above_width, #simd_type?, #soa_type?, #str_buffer_type?, #string_builder_ref_type?, #string_builder_type?, #struct_with_target_type?, #task_root_proc_type?, #task_type?, #validate_generic_type!, #value_fits_integer_type?, #void_pointer_type?, #wider_float_type

Constructor Details

#initialize(program) ⇒ Lowerer

Returns a new instance of Lowerer.



120
121
122
123
124
125
126
127
128
129
130
# File 'lib/milk_tea/core/lowering.rb', line 120

def initialize(program)
  @program = program
  @ctx = LoweringContext.new
  @artifacts = Artifacts.new
  @error_type = Types::Error.new
  @synthetic_proc_counter = 0
  @parallel_for_counter = 0
  @async_binding_counter = 0
  @method_definitions = build_method_definitions
  @bypass_sema_type_cache = false
end

Instance Attribute Details

#bypass_sema_type_cacheObject

Returns the value of attribute bypass_sema_type_cache.



102
103
104
# File 'lib/milk_tea/core/lowering.rb', line 102

def bypass_sema_type_cache
  @bypass_sema_type_cache
end

Instance Method Details

#assemble_modules(modules) ⇒ Object



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
# File 'lib/milk_tea/core/lowering.rb', line 257

def assemble_modules(modules)
  if @program.root_analysis.module_kind == :raw_module
    raise LoweringError.new("cannot emit C for external file #{@program.root_analysis.module_name}",
      line: 0, column: 0, path: @program.root_path)
  end

  regenerate_cross_module_synthetics

  includes = collect_includes

  ordered = ordered_module_fragments(modules)
  all_constants = ordered.flat_map(&:constants)
  all_constants.concat(@artifacts.synthetic_constants)
  all_globals = ordered.flat_map(&:globals)
  all_opaques = ordered.flat_map(&:opaques)
  all_structs = ordered.flat_map(&:structs)
  all_unions = ordered.flat_map(&:unions)
  all_enums = ordered.flat_map(&:enums)
  all_variants = ordered.flat_map(&:variants)
  all_static_asserts = ordered.flat_map(&:static_asserts)
  all_static_asserts.concat(@artifacts.external_layout_assertions)
  all_functions = ordered.flat_map(&:functions)

  all_opaques.concat(lower_imported_external_opaques)
  all_structs.concat(@artifacts.synthetic_structs.uniq { |s| s.linkage_name })
  all_enums.concat(@artifacts.synthetic_enums.uniq { |e| e.linkage_name })
  all_functions.concat(@artifacts.synthetic_functions.uniq { |f| f.linkage_name })

  # Add emit-generated declarations
  @artifacts.emitted_declarations.each do |emitted|
    case emitted
    when IR::Function
      all_functions << emitted
    when IR::StructDecl
      all_structs << emitted
    when IR::Constant
      all_constants << emitted
    end
  end

  IR::Program.new(
    module_name: @program.root_analysis.module_name,
    includes:,
    constants: all_constants,
    globals: all_globals,
    opaques: all_opaques,
    structs: all_structs,
    unions: all_unions,
    enums: all_enums,
    variants: all_variants,
    static_asserts: all_static_asserts,
    functions: all_functions,
    path: @program.root_path,
  )
end

#canonical_module_names(names, deps_of) ⇒ Object



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/milk_tea/core/lowering.rb', line 365

def canonical_module_names(names, deps_of)
  visited = {}
  on_stack = {}
  order = []
  visit = nil
  visit = lambda do |name|
    return if visited[name] || on_stack[name]

    on_stack[name] = true
    (deps_of[name] || []).sort.each { |dep| visit.call(dep) }
    on_stack.delete(name)
    visited[name] = true
    order << name
  end
  names.sort.each { |name| visit.call(name) }
  order
end

#compute_ordered_analysis_pairsObject



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/milk_tea/core/lowering.rb', line 335

def compute_ordered_analysis_pairs
  pairs = @program.analyses_by_path.to_a
  by_name = {}
  pairs.each do |path, analysis|
    name = analysis.module_name.to_s
    by_name[name] ||= [path, analysis]
  end

  present = by_name.keys.to_set
  deps_of = Hash.new { |hash, key| hash[key] = [] }
  pairs.each do |_path, analysis|
    name = analysis.module_name.to_s
    imported_module_names(analysis).each do |dep|
      deps_of[name] << dep if present.include?(dep) && dep != name
    end
  end
  deps_of.each_value(&:uniq!)

  canonical_module_names(by_name.keys, deps_of).map { |name| by_name[name] }
end

#ensure_events_for_analysis(analysis) ⇒ Object



250
251
252
253
254
255
# File 'lib/milk_tea/core/lowering.rb', line 250

def ensure_events_for_analysis(analysis)
  analysis.ast.declarations.grep(AST::EventDecl).each do |decl|
    event_type = analysis.values.fetch(decl.name).type
    ensure_event_runtime(event_type)
  end
end

#imported_module_names(analysis) ⇒ Object



356
357
358
359
360
361
362
363
# File 'lib/milk_tea/core/lowering.rb', line 356

def imported_module_names(analysis)
  imports = analysis.respond_to?(:imports) ? analysis.imports : nil
  return [] unless imports.respond_to?(:values)

  imports.values.filter_map do |binding|
    binding.name.to_s if binding.respond_to?(:name) && binding.name
  end
end

#lowerObject



132
133
134
135
# File 'lib/milk_tea/core/lowering.rb', line 132

def lower
  ir_program, _modules, _synths = lower_and_assemble
  ir_program
end

#lower_and_assemble(cached: nil, cached_synthetics: nil) ⇒ Object



137
138
139
140
# File 'lib/milk_tea/core/lowering.rb', line 137

def lower_and_assemble(cached: nil, cached_synthetics: nil)
  modules, per_module_synthetics = lower_modules(cached:, cached_synthetics:)
  [assemble_modules(modules), modules, per_module_synthetics]
end

#lower_modules(cached: nil, cached_synthetics: nil) ⇒ Object



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
# File 'lib/milk_tea/core/lowering.rb', line 142

def lower_modules(cached: nil, cached_synthetics: nil)
  if @program.root_analysis.module_kind == :raw_module
    raise LoweringError.new("cannot emit C for external file #{@program.root_analysis.module_name}",
      line: 0, column: 0, path: @program.root_path)
  end

  per_module_synthetics = {}
  per_module_funcs = Hash.new { |h, k| h[k] = [] }
  modules = {}

  cached_synthetics&.each do |_module_name, synths|
    @artifacts.synthetic_structs.concat(synths[:structs] || [])
    @artifacts.synthetic_enums.concat(synths[:enums] || [])
    @artifacts.synthetic_functions.concat(synths[:functions] || [])
    @artifacts.synthetic_constants.concat(synths[:constants] || [])
  end

  cached&.each do |module_name, cached_ir|
    modules[module_name] = cached_ir.with(functions: [])
    per_module_funcs[module_name] = cached_ir.functions.dup
    cached_ir.functions.each { |f| @artifacts.lowered_function_linkage_names[f.linkage_name] = true }
  end

  ordered_analysis_pairs.each do |path, analysis|
    next if analysis.module_kind == :raw_module
    next if modules.key?(analysis.module_name)

    prepare_analysis(analysis, path: path)
    collect_structs

    synth_before_s = @artifacts.synthetic_structs.length
    synth_before_e = @artifacts.synthetic_enums.length
    synth_before_f = @artifacts.synthetic_functions.length
    synth_before_c = @artifacts.synthetic_constants.length

    modules[analysis.module_name] = IR::Program.new(
      module_name: analysis.module_name,
      includes: [],
      constants: lower_constants.dup,
      globals: lower_globals.dup,
      opaques: lower_opaques.dup,
      structs: lower_structs.dup,
      unions: lower_unions.dup,
      enums: lower_enums.dup,
      variants: lower_variants.dup,
      static_asserts: lower_static_asserts.dup,
      functions: [],
      path: path,
    )
    per_module_funcs[analysis.module_name].concat(lower_functions)

    per_module_synthetics[analysis.module_name] = {
      structs: @artifacts.synthetic_structs[synth_before_s..] || [],
      enums: @artifacts.synthetic_enums[synth_before_e..] || [],
      functions: @artifacts.synthetic_functions[synth_before_f..] || [],
      constants: @artifacts.synthetic_constants[synth_before_c..] || [],
    }
  end

  pending = true
  while pending
    pending = false

    ordered_analysis_pairs.each do |path, analysis|
      next if analysis.module_kind == :raw_module

      prepare_analysis(analysis, path: path)
      ensure_events_for_analysis(analysis)

      synth_before_s = @artifacts.synthetic_structs.length
      synth_before_e = @artifacts.synthetic_enums.length
      synth_before_f = @artifacts.synthetic_functions.length
      synth_before_c = @artifacts.synthetic_constants.length

      newly_lowered = lower_functions
      next if newly_lowered.empty?

      per_module_funcs[analysis.module_name].concat(newly_lowered)

      delta = {
        structs: @artifacts.synthetic_structs[synth_before_s..] || [],
        enums: @artifacts.synthetic_enums[synth_before_e..] || [],
        functions: @artifacts.synthetic_functions[synth_before_f..] || [],
        constants: @artifacts.synthetic_constants[synth_before_c..] || [],
      }
      existing = per_module_synthetics[analysis.module_name]
      per_module_synthetics[analysis.module_name] = existing ? merge_synthetics(existing, delta) : delta

      pending = true
    end
  end

  modules.transform_values! do |fragment|
    fragment.with(functions: per_module_funcs[fragment.module_name])
  end

  [modules, per_module_synthetics]
end

#merge_synthetics(a, b) ⇒ Object



241
242
243
244
245
246
247
248
# File 'lib/milk_tea/core/lowering.rb', line 241

def merge_synthetics(a, b)
  {
    structs: (a[:structs] || []) + (b[:structs] || []),
    enums: (a[:enums] || []) + (b[:enums] || []),
    functions: (a[:functions] || []) + (b[:functions] || []),
    constants: (a[:constants] || []) + (b[:constants] || []),
  }
end

#ordered_analysis_pairsObject

Canonical, deterministic iteration order over the program's analyses so that lowering — and therefore the emitted C — is byte-identical regardless of how the analyses were assembled (live ModuleLoader vs. JSON-reconstructed bundle). Modules are emitted in dependency-first topological order, with lexicographic module-name order as a stable tiebreaker for independent modules and as a cycle-breaking fallback.



331
332
333
# File 'lib/milk_tea/core/lowering.rb', line 331

def ordered_analysis_pairs
  @ordered_analysis_pairs ||= compute_ordered_analysis_pairs
end

#ordered_module_fragments(modules) ⇒ Object



383
384
385
386
387
# File 'lib/milk_tea/core/lowering.rb', line 383

def ordered_module_fragments(modules)
  ordered = ordered_analysis_pairs.filter_map { |_path, analysis| modules[analysis.module_name] }
  ordered.concat(modules.values - ordered)
  ordered
end

#regenerate_cross_module_syntheticsObject



313
314
315
316
317
318
319
320
321
322
323
# File 'lib/milk_tea/core/lowering.rb', line 313

def regenerate_cross_module_synthetics
  ordered_analysis_pairs.each do |path, analysis|
    next if analysis.module_kind == :raw_module

    prepare_analysis(analysis, path: path)
    analysis.ast.declarations.grep(AST::EventDecl).each do |decl|
      event_type = analysis.values.fetch(decl.name).type
      ensure_event_runtime(event_type) if event_type.is_a?(Types::Event)
    end
  end
end