Skip to content

v3.gen.c

fn cache_c_flag_input_files #

fn cache_c_flag_input_files(flags []string) []string

cache_c_flag_input_files returns forced include/macro files whose contents affect every cached object compiled with the supplied C flags.

fn cache_directive_flags #

fn cache_directive_flags(a &flat.FlatAst, vroot string, target pref.Target, compile_values map[string]string) []string

cache_directive_flags resolves source C flags that affect early C cache keys.

fn cache_external_input_files #

fn cache_external_input_files(a &flat.FlatAst, vroot string, source_modules map[string]bool, initial_c_flags []string, target pref.Target) (map[string][]string, map[string][]string, bool)

cache_external_input_files returns local include/embed inputs grouped by the module whose cached object incorporates their contents, plus the ordered root native source includes for each module. Forced-include inputs affect every object and are kept in a configuration-wide group. The last result reports include forms whose dependencies cannot be resolved statically.

fn cache_external_input_files_with_resolved_flags #

fn cache_external_input_files_with_resolved_flags(a &flat.FlatAst, vroot string, source_modules map[string]bool, c_flags []string, target pref.Target) (map[string][]string, map[string][]string, map[string][]string, []string, []string, bool)

cache_external_input_files_with_resolved_flags collects cache inputs without resolving source #flag directives a second time. unscoped_inputs contains the dependency trees of direct non-source includes that remain in the program unit. resolution_dirs contains every searched include directory whose contents can change path resolution; missing_resolution_paths are the first nonexistent path components searched.

fn tokenize_c_flag #

fn tokenize_c_flag(value string) []string

tokenize_c_flag splits a C flag on unquoted whitespace while preserving quotes.

fn FlatGen.new #

fn FlatGen.new() FlatGen

new creates a FlatGen value for c.

struct FlatGen #

struct FlatGen {
mut:
	sb                             strings.Builder
	indent                         int
	a                              &flat.FlatAst    = unsafe { nil }
	used_fns                       &map[string]bool = unsafe { nil }
	used_fn_names                  []string
	fn_gen_items                   []FlatFnGenItem
	top_level_node_ids             []int
	ast_string_literals            []string
	ast_string_literals_ready      bool
	fn_segs                        []string
	fn_seg_chunk_indexes           []int
	parallel_chunk_wrapper_defs    []ParallelChunkWrapperDefs
	parallel_chunk_wrapper_capture int = -1
	parallel_type_decls            string
	parallel_forward_decls         string
	parallel_const_code            string
	parallel_support_ready         bool
	test_files                     map[string]bool
	cache_program_files            map[string]bool
	incremental_fn_names           map[string]bool
	str_lits                       []string
	str_lit_ids                    map[string]int
	str_lits_shared                bool
	global_types                   map[string]types.Type
	global_raw_type_texts          map[string]string
	enum_vals                      map[string]int
	enum_value_exprs               map[string]string
	defers                         []flat.NodeId
	fn_defers                      []flat.NodeId
	fn_defer_counts                map[int]string
	defer_capture_names            []string
	defer_capture_types            map[string]types.Type
	interfaces                     map[string][]string
	const_vals                     map[string]flat.NodeId
	const_modules                  map[string]string
	const_files                    map[string]string // const name -> declaring file (for import-alias type resolution)
	const_init_order               []string
	fixed_storage_consts           map[string]bool
	global_modules                 map[string]string
	global_files                   map[string]string      // qualified global name -> declaring file (for import-alias type resolution)
	global_inits                   map[string]flat.NodeId // qualified global name -> initializer value node
	global_init_order              []string               // qualified global names, in declaration order
	enum_backing_infos             map[string]EnumBackingInfo
	iface_impls                    map[string][]string // interface name -> implementing concrete type names
	interface_dispatch_required    map[string]bool     // source/lowered concrete method names required by emitted interface dispatch
	iface_type_ids                 map[string]int      // "${iface}::${concrete}" -> 1-based type id
	interface_boxed_types          map[string]bool
	interface_boxed_types_done     bool
	ierror_method_emit_names       map[string]bool   // names/lowered names of concrete IError msg/code methods
	ierror_stack_pointer_aliases   []map[string]bool // scoped local pointer aliases to stack subobjects
	ierror_owned_pointer_by_owner  map[string]bool   // exact scope binding owner -> local owns its pointer allocation
	recursive_drop_helpers         map[string]string // expansion key -> concrete struct type name
	local_pointer_storage_by_owner map[string]bool   // exact scope binding owner -> C storage is already a pointer
	local_c_type_by_owner          map[string]string // exact scope binding owner -> emitted C declaration type
	local_mutable_by_owner         map[string]bool
	local_pointer_alias_by_owner   map[string]string   // exact scope binding owner -> stack local whose address is stored
	local_pointer_alias_mut_param  map[string]bool     // exact scope binding owner -> alias source is a mut parameter
	local_raw_type_by_owner        map[string]string   // exact scope binding owner -> source-level raw type text
	local_shared_storage_by_owner  map[string]bool     // exact scope binding owner -> C storage is a shared wrapper pointer
	local_fn_value_c_name_by_owner map[string]string   // exact scope binding owner -> lifted fn-literal C name
	sum_name_lookup                map[string]string   // full/short sum type name -> canonical sum type name
	module_init_fns                []string            // C names of module-level `init()` fns, in source order
	module_init_fn_modules         map[string]string   // C init fn name -> V module name
	module_imports                 map[string][]string // module -> imported modules
	c_directives                   []CDirective
	early_c_source_directives      map[string]bool
	native_source_contexts         map[string][]NativeSourceContextDirective
	objective_cpp_source_requests  []ObjectiveCppSourceRequest
	native_source_wrapper_index    int
	inlined_c_structs              map[string]bool
	inlined_c_typedef_names        map[string]bool
	inlined_c_fns                  map[string]bool
	inlined_c_declared_fns         map[string]bool
	inlined_c_static_fns           map[string]bool
	cache_omitted_c_fns            map[string]bool
	preserved_header_files_seen    map[string]bool
	initial_c_flags                []string
	c_flags                        []string
	use_system_stdint              bool
	libc_compat_fns                map[string]bool
	tc                             &types.TypeChecker = unsafe { nil }
	has_builtins                   bool
	tmp_count                      int
	line_start                     bool
	field_name_set                 map[string]bool   // every struct field's C name (lazy) — for const/field collision checks
	modules                        map[string]string // alias -> full module name
	fn_ptr_types                   map[string]string // fn_ptr:ret|params -> typedef name
	used_fn_ptr_types              map[string]bool   // signatures referenced by emitted C
	multi_return_types             []types.Type
	multi_return_type_names        map[string]bool
	multi_return_types_ready       bool
	decl_types_ready               bool
	fixed_array_ret_wrappers       map[string]bool // bare fixed-array c_type name -> has a return wrapper struct
	emitted_fixed_array_typedefs   map[string]bool // bare fixed-array typedefs already written (shared across passes)
	concrete_optional_abi_fns      map[string]bool // emitted fn names whose option/result params use Optional_T ABI
	fixed_array_typedefs_needed    map[string]FixedArrayTypedefInfo
	fixed_array_typedefs_ready     bool
	fn_decl_param_types            map[string][]types.Type
	fn_decl_variadic               map[string]bool
	fn_decl_variadic_short_counts  map[string]int
	fn_decl_shared_params          map[string][]bool
	fn_shared_params_resolved      map[string][]bool
	has_shared_params              bool
	fn_decl_mut_receivers          map[string]bool
	fn_decl_ret_types              map[string]types.Type // fn decl name (and qualified variants) -> return type
	// Const dependency analysis follows helper calls. Keep declaration indexes so
	// resolving each call does not scan the whole flattened AST.
	fn_decl_nodes_by_name         map[string]flat.NodeId
	fn_decl_nodes_by_short        map[string]flat.NodeId
	fn_decl_nodes_by_module_short map[string]flat.NodeId
	// set of `${module}\x01${name}` for every non-generic fn decl, built once in
	// precompute_non_generic_fn_index. Replaces the former full-node scan in
	// non_generic_fn_decl_exists_in_module (O(nodes) per call, hot in cgen).
	non_generic_fn_names_by_module map[string]bool
	// indexes over tc.fn_generic_params keys, built once in
	// precompute_generic_fn_key_index. They replace the former full-map scan in
	// generic_plain_fn_base_for_call (O(generic fns) with two string allocations
	// per key, run for nearly every emitted call). The ordinal preserves the
	// map's iteration order so multi-match resolution stays byte-identical.
	generic_fn_keys_by_short     map[string][]string
	generic_fn_keys_by_cname     map[string][]string
	generic_fn_key_ordinal       map[string]int
	struct_decl_infos            map[string]StructDeclInfo
	struct_decl_short_infos      map[string]StructDeclInfo
	decl_attrs                   map[int][]string
	shared_type_names            map[string]SharedTypeInfo // __shared__ wrapper name -> wrapped type metadata
	shared_alias_pointer_shorts  map[string]string         // alias short name -> shared inner type; '' means ambiguous
	needs_shared_runtime         bool
	const_runtime_inits          []string
	const_runtime_init_modules   []string
	runtime_inits                []string
	runtime_init_modules         []string
	compiler_vroot               string
	compiler_vexe                string
	compiler_vexe_env_setup      bool = true
	target                       pref.Target
	thread_stack_size            int = 8 * 1024 * 1024
	compile_values               map[string]string // explicit `-d` values used by `$d(...)` in `#flag`s
	output_path                  string
	output_error                 string
	c99_mode                     bool
	skip_generics                bool
	skip_enum_autostr            bool
	placeholder_check_forced     bool
	cur_fn_name                  string
	current_decl_is_mut          bool
	direct_array_access          bool
	struct_default_module        string
	default_value_stack          map[string]bool
	shadowed_global_locals       map[string]bool
	cur_param_names              []string
	cur_param_type_values        []types.Type
	cur_param_types              map[string]types.Type
	cur_concrete_optional_params map[string]bool
	cur_mut_params               map[string]bool
	cur_mut_param_owners         map[string]types.ScopeBindingOwner
	cur_fn_ret                   types.Type = types.Type(types.void_)
	cur_fn_ret_is_optional       bool
	cur_fn_ret_base              types.Type = types.Type(types.void_)
	defer_return_tmp_var         string
	active_locks                 []ActiveLock
	unsafe_depth                 int
	loop_depth                   int
	conditional_branch_scopes    []&types.Scope
	conditional_branch_depths    []int
	conditional_branch_depth     int
	loop_label_depths            map[string]int
	loop_control_copybacks       []LoopControlCopyback
	map_loop_copyback_guards     []MapLoopCopybackGuard
	goto_label_lock_scopes       map[string][]int
	pending_loop_label           string
	// in_return is true only while generating a `return` statement's value, so a bare
	// generic literal (`return Box{...}`) may adopt `cur_fn_ret`'s concrete instance —
	// but a literal in a local decl / argument elsewhere in the body does not.
	in_return                       bool
	cur_return_node_id              int = -1
	ownership_return_index          int
	ownership_seen_return_sources   map[string]bool
	ownership_propagation_index     int
	ownership_loop_control_index    int
	ownership_loop_iteration_index  int
	ownership_scope_index           int
	cur_return_drops                []types.OwnershipDropEntry
	pending_return_scope_drops      []types.OwnershipDropEntry
	expected_expr_type              types.Type = types.Type(types.void_)
	expected_enum                   string
	known_expr_type_id              int        = -1
	known_expr_type                 types.Type = types.Type(types.void_)
	needed_optional_types           map[string]string
	emitted_optional_types          map[string]bool
	emitted_fns                     map[string]bool
	array_method_cache              map[string]string
	param_types_cache               map[string][]types.Type // (name|fallback) -> resolved param types
	interface_receiver_cache        &StringLookupCache        = unsafe { nil }
	normalize_call_cache            &StringLookupCache        = unsafe { nil }
	flattened_generic_name_cache    &StringLookupCache        = unsafe { nil }
	generic_struct_context_ct_cache &StringLookupCache        = unsafe { nil }
	struct_cname_cache              &StringLookupCache        = unsafe { nil }
	unique_struct_ct_cache          &StringLookupCache        = unsafe { nil }
	alias_method_cache              &StringLookupCache        = unsafe { nil }
	import_alias_cache              &ContextStringLookupCache = unsafe { nil }
	enum_selector_cache             &ContextStringLookupCache = unsafe { nil }
	enum_method_cache               &ContextStringLookupCache = unsafe { nil }
	qualified_enum_method_cache     &ContextStringLookupCache = unsafe { nil }
	embedded_fields_by_type         map[string][]types.StructField // type name -> its embedded fields (usually empty)
	param_types_by_short            map[string][]types.Type        // method short-name suffix -> param types (fallback index)
	generic_method_candidates       map[string][]GenericMethodCandidate
	spawn_wrapper_names             map[string]string
	spawn_wrapper_defs              []string
	spawn_wrapper_defs_seen         map[string]bool
	callback_wrapper_names          map[string]string
	callback_wrapper_defs           []string
	callback_wrapper_defs_seen      map[string]bool
	parallel_used                   bool
	c_name_cache                    &CNameCache = unsafe { nil }
	emitted_fn_ptr_typedefs         map[string]bool
	c_extern_refs                   map[string]bool
	c_extern_refs_ready             bool
	parallel_prepared               bool
	scoped_fn_items_scope           voidptr
	scoped_fn_output_path           string
	scoped_fn_output_paths          []string
	const_short_index               &ConstShortIndex = unsafe { nil }
	mut_recv_facts                  &FnNameFactCache = unsafe { nil }
	generic_app_cache               &GenericAppCache = unsafe { nil }
	want_parallel_prep              bool
	want_parallel_c_extern_prep     bool
	// Set while selected items' C-extern refs still have to be collected: the
	// fused prep walk defers them to the parallel exact-cost pass, which falls
	// back to a serial top-up when it cannot run.
	prep_externs_pending bool
	prep_costs_pending   bool
	prep_typ_text_cache  &PrepTypTextCache = unsafe { nil }
	preseed_type_seen    &PreseedTypeSeen  = unsafe { nil }
	// Separate seen-cache for the declaration preseed family
	// (preseed_fn_ptr_type has optional-typedef side effects the body-walk
	// preseed does not); armed only for the contiguous pre-dispatch preseed
	// block, while no arena scope can be freed and reused.
	preseed_sig_type_seen      &PreseedTypeSeen     = unsafe { nil }
	struct_decl_pref_cache     &StructDeclPrefCache = unsafe { nil }
	unused_param_seen          &UnusedParamSeen     = unsafe { nil }
	cache_split                bool
	program_body_only          bool
	cached_support_identifiers map[string]bool
	// Set when the target is built with -prealloc / -d prealloc: the bump
	// arena's base block pointer must be thread-local (matching V1's cgen),
	// or every spawned thread would race on the same arena.
	prealloc               bool
	scope_parallel_workers bool
	worker_scope           voidptr
	parallel_worker_scopes []voidptr
}

FlatGen emits flat gen output used by c.

fn (FlatGen) was_parallel #

fn (g &FlatGen) was_parallel() bool

was_parallel reports whether the last fn codegen actually ran across threads.

fn (FlatGen) c_flags #

fn (g &FlatGen) c_flags() []string

fn (FlatGen) set_initial_c_flags #

fn (mut g FlatGen) set_initial_c_flags(flags []string)

set_initial_c_flags makes command-line C flags available while collecting directives.

fn (FlatGen) set_c99_mode #

fn (mut g FlatGen) set_c99_mode(enabled bool)

set_c99_mode configures whether generated C should support strict C99 builds.

fn (FlatGen) set_prealloc #

fn (mut g FlatGen) set_prealloc(on bool)

set_prealloc marks the build as using the -prealloc bump arena.

fn (FlatGen) set_skip_generics #

fn (mut g FlatGen) set_skip_generics(on bool)

set_skip_generics removes generic-only metadata work when reachability proved that the generated program has no generic instantiations.

fn (FlatGen) set_skip_enum_autostr #

fn (mut g FlatGen) set_skip_enum_autostr(on bool)

set_skip_enum_autostr omits synthesized enum string helpers when reachability proves the program cannot format an enum.

fn (FlatGen) set_compiler_vexe #

fn (mut g FlatGen) set_compiler_vexe(path string)

set_compiler_vexe sets the V executable path baked into generated test/runtime helpers.

fn (FlatGen) set_compiler_vexe_env_setup #

fn (mut g FlatGen) set_compiler_vexe_env_setup(enabled bool)

set_compiler_vexe_env_setup controls whether generated programs populate an unset VEXE.

fn (FlatGen) set_target #

fn (mut g FlatGen) set_target(target pref.Target)

set_target sets the canonical code-generation target.

fn (FlatGen) set_thread_stack_size #

fn (mut g FlatGen) set_thread_stack_size(size int)

set_thread_stack_size configures the stack size used by generated worker threads.

fn (FlatGen) set_compile_values #

fn (mut g FlatGen) set_compile_values(values map[string]string)

set_compile_values records explicit -d values so $d(...) inside #flag directives resolves configured values over fallbacks.

fn (FlatGen) set_cache_split #

fn (mut g FlatGen) set_cache_split(enabled bool)

set_cache_split enables stable cache markers and string symbols in generated C. The v3 driver uses them to split one checked program into independently cached module objects without changing regular -o file.c output.

fn (FlatGen) set_program_body_only #

fn (mut g FlatGen) set_program_body_only(enabled bool)

set_program_body_only omits the reusable declaration/type prefix. It is used when that prefix has already been validated and loaded from the module cache.

fn (FlatGen) set_cache_program_files #

fn (mut g FlatGen) set_cache_program_files(files []string)

set_cache_program_files assigns entry-module source files to the program translation unit rather than an imported module cache object.

fn (FlatGen) set_incremental_fn_names #

fn (mut g FlatGen) set_incremental_fn_names(names map[string]bool)

set_incremental_fn_names limits program-body generation to functions whose parsed bodies changed. An empty map preserves normal whole-program emission.

fn (FlatGen) set_cached_support_declarations #

fn (mut g FlatGen) set_cached_support_declarations(source string)

set_cached_support_declarations records C identifiers already supplied by the cached program prefix so body-only generation emits only newly needed typedefs.

fn (FlatGen) set_scope_parallel_workers #

fn (mut g FlatGen) set_scope_parallel_workers(enabled bool)

set_scope_parallel_workers makes cgen helpers use disposable prealloc arenas. The caller must release them with free_parallel_worker_scopes after consuming the generated C output and cgen metadata.

fn (FlatGen) free_parallel_worker_scopes #

fn (mut g FlatGen) free_parallel_worker_scopes()

free_parallel_worker_scopes releases scratch arenas retained by joined cgen helper threads.

fn (FlatGen) gen #

fn (mut g FlatGen) gen(a &flat.FlatAst) string

gen supports gen handling for FlatGen.

fn (FlatGen) gen_with_used #

fn (mut g FlatGen) gen_with_used(a &flat.FlatAst, used_fns map[string]bool, tc &types.TypeChecker) string

gen_with_used emits with used output for c.

fn (FlatGen) gen_with_used_test_options #

fn (mut g FlatGen) gen_with_used_test_options(a &flat.FlatAst, used_fns map[string]bool, tc &types.TypeChecker, no_parallel bool, test_files []string) string

fn (FlatGen) gen_to_file_with_used_test_options #

fn (mut g FlatGen) gen_to_file_with_used_test_options(path string, a &flat.FlatAst, used_fns map[string]bool, tc &types.TypeChecker, no_parallel bool, test_files []string) !

gen_to_file_with_used_test_options writes the completed translation unit by transferring the builder buffer to the file writer, avoiding a second full-size string allocation.

fn (FlatGen) gen_with_used_options #

fn (mut g FlatGen) gen_with_used_options(a &flat.FlatAst, used_fns map[string]bool, tc &types.TypeChecker, no_parallel bool) string

gen_with_used_options emits with used options output for c.