Skip to content

v2.gen.cleanc

fn Gen.new #

fn Gen.new(files []ast.File) &Gen

fn Gen.new_with_env #

fn Gen.new_with_env(files []ast.File, env &types.Environment) &Gen

fn Gen.new_with_env_and_pref #

fn Gen.new_with_env_and_pref(files []ast.File, env &types.Environment, p &pref.Preferences) &Gen

fn Gen.new_with_env_pref_and_flat #

fn Gen.new_with_env_pref_and_flat(flat &ast.FlatAst, env &types.Environment, p &pref.Preferences) &Gen

struct Gen #

struct Gen {
mut:
	files                   []ast.File
	flat                    &ast.FlatAst       = unsafe { nil }
	env                     &types.Environment = unsafe { nil }
	pref                    &pref.Preferences  = unsafe { nil }
	sb                      strings.Builder
	indent                  int
	cur_fn_scope            &types.Scope = unsafe { nil }
	cur_fn_name             string
	cur_fn_c_name           string
	cur_fn_ret_type         string
	cur_fn_c_ret_type       string
	expected_init_expr_type string
	cur_module              string
	cur_fn_scope_miss_key   string
	// Per-return drop snapshots for the current fn, populated by the
	// checker. Indexed positionally by `cur_fn_return_index`, which the
	// ReturnStmt handler increments. Reset at every fn entry. Empty for
	// fns the checker didn't see (e.g., plain V without `-d ownership`).
	cur_fn_return_drops [][]types.DropEntry
	cur_fn_return_index int
	// Set true while gen_return_if_branch synthesizes ReturnStmts for
	// `return if cond { x } else { y }`. The synthesized statements go
	// through the same ReturnStmt handler, but they represent the SAME
	// source-level return — emitting drops for them again would consume
	// the next snapshot (belonging to a later source return) and break
	// the parallel counter the checker relies on.
	suppress_return_drop_emit bool
	emitted_types             map[string]bool
	fn_param_is_ptr           map[string][]bool
	fn_param_types            map[string][]string
	fn_return_types           map[string]string
	v_fn_return_types         map[string]string
	runtime_local_types       map[string]string
	runtime_decl_types        map[string]string
	runtime_fn_pointer_types  map[string]types.Type
	cur_fn_returned_idents    map[string]bool
	active_generic_types      map[string]types.Type
	cur_fn_generic_params     map[string]string
	// Comptime $for field iteration state
	comptime_field_var      string // variable name (e.g., 'field')
	comptime_field_name     string // current field name (e.g., 'id')
	comptime_field_type     string // current field C type name
	comptime_field_raw_type types.Type = types.Struct{} // raw types.Type for comptime checks
	comptime_field_attrs    []string // current field attributes
	comptime_field_idx      int      // current field index
	comptime_field_is_embed bool     // current field is embedded
	comptime_continue_label string   // label for continue inside unrolled comptime field loops
	comptime_val_var        string   // the struct variable being decoded (e.g., 'val')
	comptime_val_type       string   // C type of val (e.g., 'Slack')
	// Comptime $for method iteration state
	comptime_method_var           string   // loop variable name (e.g., 'method')
	comptime_method_name          string   // current method name (e.g., 'index')
	comptime_method_attrs         []string // current method attributes
	comptime_method_return_type   ast.Expr = ast.empty_expr // current method return type (AST expr)
	comptime_method_args          []ast.Parameter // current method params (excluding receiver)
	comptime_method_idx           int             // current method index
	comptime_method_receiver_type string          // receiver C type (e.g., 'main__App')
	comptime_method_struct_name   string          // receiver struct V name (e.g., 'App')

	fixed_array_fields          map[string]bool
	fixed_array_field_elem      map[string]string
	fixed_array_globals         map[string]bool
	tuple_aliases               map[string][]string
	struct_field_types          map[string]string
	enum_value_to_enum          map[string]string
	enum_type_fields            map[string]map[string]bool
	array_aliases               map[string]bool
	map_aliases                 map[string]bool
	result_aliases              map[string]bool
	option_aliases              map[string]bool
	alias_base_types            map[string]string
	fn_type_aliases             map[string]bool
	emitted_result_structs      map[string]bool
	emitted_option_structs      map[string]bool
	embedded_field_owner        map[string]string
	collected_fixed_array_types map[string]FixedArrayInfo
	collected_map_types         map[string]MapTypeInfo
	fixed_array_ret_wrappers    map[string]string
	sum_type_variants           map[string][]string
	// Interface method signatures: interface_name -> [(method_name, cast_signature), ...]
	interface_methods                 map[string][]InterfaceMethodInfo
	interface_data_fields             map[string][]InterfaceDataFieldInfo
	interface_decls                   map[string]ast.InterfaceDecl
	emitted_interface_bodies          map[string]bool
	interface_wrapper_specs           map[string]InterfaceWrapperSpec
	needed_interface_wrappers         map[string]bool
	ierror_wrapper_bases              map[string]bool
	needed_ierror_wrapper_bases       map[string]bool
	tmp_counter                       int
	cur_fn_mut_params                 map[string]bool   // names of mut params in current function
	global_var_modules                map[string]string // global var name → module name
	global_var_types                  map[string]string // global var name → C type string
	module_storage_vars               map[string]string // module-prefixed storage symbol -> declaring module
	c_extern_module_storage           map[string]string // module-prefixed C extern symbol -> raw C name
	primitive_type_aliases            map[string]bool   // type names that are aliases for primitive types
	emit_modules                      map[string]bool   // when set, emit consts/globals/fns only for these modules
	type_modules                      map[string]bool   // when set, alias/type helpers may reference only these modules
	emit_files                        map[string]bool   // when set, emit consts/globals/fns only for these source files
	export_const_symbols              bool
	cache_bundle_name                 string
	cached_init_calls                 []string
	exported_const_seen               map[string]bool
	exported_const_symbols            []ExportedConstSymbol
	cur_file_name                     string
	cur_import_modules                map[string]string
	is_module_ident_cache             map[string]bool    // per-function cache for is_module_ident results
	not_local_var_cache               map[string]bool    // per-function negative cache for get_local_var_c_type
	resolved_module_names             map[string]string  // per-function cache for resolve_module_name
	cached_env_scopes                 map[string]voidptr // cache of env_scope results (avoids repeated locking)
	selector_field_type_cache         map[string]string
	selector_field_type_miss          map[string]bool
	struct_field_lookup_cache         map[string]string
	struct_field_lookup_miss          map[string]bool
	struct_type_lookup_cache          map[string]types.Struct
	struct_type_lookup_miss           map[string]bool
	struct_decl_info_cache            map[string]StructDeclInfo
	struct_decl_info_miss             map[string]bool
	flat_struct_decl_exact            map[string]FlatStructDeclInfo
	flat_struct_decl_short_by_mod     map[string]FlatStructDeclInfo
	flat_struct_decl_short            map[string]FlatStructDeclInfo
	flat_struct_decl_indexed          bool
	alias_base_lookup_cache           map[string]string
	alias_base_lookup_miss            map[string]bool
	declared_type_names_all           map[string]bool
	declared_type_names_by_mod        map[string]bool
	emit_file_modules                 map[string]bool
	declared_type_names_in_emit_files map[string]bool
	source_module_names               map[string]bool
	imported_symbols_index            map[string]string // "file_name\x01symbol_name" -> importing module (built once from g.files)
	v_method_return_index             map[string]string // method short name -> unique V return type (or v_method_ret_ambiguous)
	ierror_base_index                 map[string]string // base -> qualified concrete base from the smallest `*__base__msg` fn (built once)

	const_exprs                           map[string]string // const name → C expression string (for inlining)
	const_types                           map[string]string // const name → C type string
	const_c_names                         map[string]string // generated const name → collision-free C symbol name
	runtime_const_targets                 map[string]bool   // module-scoped consts initialized in __v_init_consts_*
	used_fn_keys                          map[string]bool
	force_emit_fn_names                   map[string]bool   // function C names that must be emitted regardless of mark_used
	export_fn_names                       map[string]string // V-qualified name → export name (from @[export:] attribute)
	called_fn_names                       map[string]bool
	called_specialized_names              map[string]string // base generic C name -> called specialized C name
	called_specialized_names_indexed      bool
	declared_fn_names                     map[string]bool // C function names that have a prototype/body head emitted
	should_emit_fn_decl_cache             map[string]bool
	generic_body_scan_cache               map[string]bool
	collect_generic_scan_calls            bool
	generic_call_spec_scan_only           bool
	generic_scan_called_names             map[string]bool
	generic_spec_index                    map[string][]string                // fn_name → matching keys in env.generic_types
	generic_fn_decl_index                 map[string]GenericFnDeclInfo       // generic fn C/base name → source location
	specialized_fn_bases                  map[string]bool                    // base C name with at least one _T_ specialization
	specialized_receiver_methods          map[string]string                  // receiver|method -> single matching specialized method
	specialized_receiver_method_ambiguous map[string]bool                    // receiver|method keys with multiple matches
	specialized_receiver_method_miss      map[string]bool                    // receiver|method keys with no matching specialized method
	specialized_receiver_method_indexed   bool                               // true after existing signature maps have been indexed
	late_generic_specs                    map[string][]map[string]types.Type // additional comptime-discovered specs
	anon_fn_defs                          []string        // lifted anonymous function definitions
	late_struct_defs                      []string        // struct definitions discovered during pass 5 codegen
	pending_late_body_keys                map[string]bool // body_keys in late_struct_defs but not yet flushed to g.sb
	late_generic_str_instances            []string        // c_names of late generic struct instances needing str macro check
	pass5_start_pos                       int             // position in sb where pass 5 starts
	deferred_m_includes                   []string        // Objective-C .m file #include lines deferred until after type definitions
	spawned_fns                           map[string]bool // spawn wrapper names already emitted
	spawn_wrapper_defs                    []string        // spawn wrapper struct + function definitions
	emitted_trampolines                   map[string]bool // bound method trampoline names already emitted
	trampoline_defs                       []string        // bound method trampoline definitions
	// @[live] hot code reloading
	live_fns                []LiveFnInfo                     // @[live] functions detected during code generation
	live_source_file        string                           // source file containing @[live] functions
	test_fn_names           []string                         // test function names collected in Pass 4
	has_main                bool                             // whether a main() function was found in Pass 4
	fn_owner_file           map[string]int                   // fn_key -> first file index (for parallel dedup)
	global_owner_file       map[string]int                   // global_name -> first file index (for parallel dedup)
	generic_struct_bindings map[string]map[string]types.Type // struct_name -> {T: concrete_type}
	// Multi-instantiation support: maps base struct C name (e.g. "json2__Node") to
	// a list of (suffix, bindings) pairs for each distinct concrete instantiation.
	// E.g. [("json2__ValueInfo", {T: ValueInfo}), ("json2__StructFieldInfo", {T: StructFieldInfo})]
	generic_struct_instances   map[string][]GenericStructInstance
	generic_setup_snapshot     GenericSetupSnapshot
	has_generic_setup_snapshot bool
	c_file_fn_keys             map[string]bool // fn_key -> emitted from a .c.v file, so plain .v fallback should be skipped
	c_struct_types             map[string]bool // C struct names declared with `struct C.Name`
	typedef_c_types            map[string]bool // C struct names with @[typedef] attribute (emit without 'struct' prefix)
	blocked_fn_keys            map[string]bool // worker-only fn keys reserved to other pass5 chunks
	cached_vhash               string          // cached git short hash for @VHASH/@VCURRENTHASH
	pass5_worker_id            int
	pass5_file_times           []Pass5FileTime
	// When a large file is split across workers, only the worker that owns its
	// globals takes file-level dedup ownership; the others block the file's fns.
	// During its assigned slice a non-owning worker sets these so gen_fn_decl can
	// bypass blocked_fn_keys for fns owned by exactly explicit_slice_file (the slice
	// it is explicitly responsible for) without unblocking anything reached from
	// another file. See gen_file_range / explicit_slice_emit_allows.
	explicit_slice_active bool
	explicit_slice_file   int
}

fn (Gen) add_called_fn_names #

fn (mut g Gen) add_called_fn_names(names []string)

fn (Gen) build_pass5_work_items #

fn (g &Gen) build_pass5_work_items(emit_indices []int) []Pass5WorkItem

build_pass5_work_items turns the emittable file indices into balanced work items, splitting any file whose codegen cost exceeds pass5_split_threshold into contiguous FnDecl-index slices.

fn (Gen) external_called_fn_names #

fn (g &Gen) external_called_fn_names() []string

fn (Gen) gen #

fn (mut g Gen) gen() string

gen generates C source from the transformed AST files (sequential).

fn (Gen) gen_finalize #

fn (mut g Gen) gen_finalize() string

gen_finalize runs post-pass-5 finalization and returns the complete C source string.

fn (Gen) gen_pass5_files #

fn (mut g Gen) gen_pass5_files(file_indices []int)

gen_pass5_files generates function bodies for a range of file indices. Used by parallel dispatch — each worker calls this with its assigned chunk.

fn (Gen) gen_pass5_post #

fn (mut g Gen) gen_pass5_post()

gen_pass5_post runs post-Pass-5 finalization (interface wrappers, live reload, map helpers).

fn (Gen) gen_pass5_pre #

fn (mut g Gen) gen_pass5_pre() []int

gen_pass5_pre runs Pass 5 sequential pre-work: extern globals and extern consts for non-emitted modules. Returns the list of file indices that need gen_file().

fn (Gen) gen_pass5_work_items #

fn (mut g Gen) gen_pass5_work_items(items []Pass5WorkItem)

gen_pass5_work_items emits each assigned work item. Whole-file items go through gen_file; split items emit only their FnDecl slice via gen_file_range.

fn (Gen) gen_passes_1_to_4 #

fn (mut g Gen) gen_passes_1_to_4()

gen_passes_1_to_4 runs setup and passes 1-4 (types, structs, constants, forward declarations).

fn (Gen) generic_setup_snapshot #

fn (g &Gen) generic_setup_snapshot() GenericSetupSnapshot

fn (Gen) merge_pass5_worker #

fn (mut g Gen) merge_pass5_worker(w &Gen)

merge_pass5_worker merges a parallel worker's output into the main Gen.

fn (Gen) new_pass5_worker #

fn (g &Gen) new_pass5_worker(file_indices []int, worker_id int) &Gen

new_pass5_worker creates a worker Gen for parallel Pass 5. file_indices specifies which files this worker will process. Functions owned by files outside this range are pre-marked as emitted to prevent duplicate emission across workers.

fn (Gen) pass5_file_cost #

fn (g &Gen) pass5_file_cost(file_idx int) int

pass5_file_cost estimates relative codegen work for balancing parallel chunks.

fn (Gen) print_pass5_file_times #

fn (g &Gen) print_pass5_file_times(limit int)

fn (Gen) set_cache_bundle_name #

fn (mut g Gen) set_cache_bundle_name(name string)

set_cache_bundle_name sets the cache bundle label used for emitting a deterministic cache-init function (e.g. __v2_cached_init_builtin).

fn (Gen) set_cached_init_calls #

fn (mut g Gen) set_cached_init_calls(calls []string)

fn (Gen) set_emit_files #

fn (mut g Gen) set_emit_files(files []string)

set_emit_files limits body/const/global emission to the provided source files. Type declarations and forward declarations are still emitted for all files.

fn (Gen) set_emit_modules #

fn (mut g Gen) set_emit_modules(modules []string)

set_emit_modules limits code emission to the provided module names. Type declarations and forward declarations are still emitted for all modules.

fn (Gen) set_export_const_symbols #

fn (mut g Gen) set_export_const_symbols(enable bool)

set_export_const_symbols controls whether emitted module const macros also get exported as linkable global symbols.

fn (Gen) set_force_emit_fn_names #

fn (mut g Gen) set_force_emit_fn_names(names []string)

fn (Gen) set_type_modules #

fn (mut g Gen) set_type_modules(modules []string)

fn (Gen) set_used_fn_keys #

fn (mut g Gen) set_used_fn_keys(used map[string]bool)

fn (Gen) use_generic_setup_snapshot #

fn (mut g Gen) use_generic_setup_snapshot(snapshot GenericSetupSnapshot)

struct GenericSetupSnapshot #

struct GenericSetupSnapshot {
mut:
	ready                       bool
	tuple_aliases               map[string][]string
	array_aliases               map[string]bool
	map_aliases                 map[string]bool
	result_aliases              map[string]bool
	option_aliases              map[string]bool
	collected_fixed_array_types map[string]FixedArrayInfo
	collected_map_types         map[string]MapTypeInfo
	generic_body_scan_cache     map[string]bool
	generic_spec_index          map[string][]string
	late_generic_specs          map[string][]map[string]types.Type
	generic_struct_bindings     map[string]map[string]types.Type
	generic_struct_instances    map[string][]GenericStructInstance
}

struct Pass5WorkItem #

struct Pass5WorkItem {
pub:
	file_idx     int
	fn_indices   []int // empty => emit the whole file (gen_file)
	emit_globals bool
	cost         int
}

Pass5WorkItem is one unit of parallel Pass 5 work. A small file is one item covering the whole file (fn_indices empty => use gen_file). A large file is split into several items, each owning a contiguous slice of the file's FnDecl statement indices; only the first slice (emit_globals) emits the file globals.