Skip to content

v.gen.c #

Preamble and expression lowering for the u128 / i128 primitives.

The C type names u128 and i128 come from prim_c_type, which already falls through by size. What they mean is decided by the helper header (int128_helpers.h, embedded below): the compiler's own __int128 where the toolchain supports it, a two-u64 struct everywhere else.

Every 128-bit operation is emitted as a call to a __v_u128_* / __v_i128_* helper, never as a C operator. That keeps one code path for both representations, which is why the portable path is exercised by the same tests as the native one.

Constants #

const headerless_libc_macro = '__V_HEADERLESS_LIBC'

headerless_libc_macro selects the libc surface of a merged portable compiler snapshot (see merge_libc_variants): 1 for V's own declarations, 0 for the system headers. Defining it on the C compiler's command line overrides the choice that the snapshot makes from the pointer width.

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_directive_flags_with_project #

fn cache_directive_flags_with_project(a &flat.FlatAst, vroot string, target pref.Target, compile_values map[string]string, project []cache_refresh.FlagGroup) []string

cache_directive_flags_with_project merges saved project groups with fresh module directives.

fn cache_native_dependency_directives #

fn cache_native_dependency_directives(a &flat.FlatAst, vroot string, flags []string, target pref.Target) string

cache_native_dependency_directives returns the native preprocessing context for a compiler-generated dependency manifest, including project-owned includes.

fn cache_native_flag_input_files #

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

cache_native_flag_input_files returns the native sources and objects that #flag directives name outright, for example #flag @VEXEROOT/thirdparty/sqlite/sqlite3.c or the prebuilt sqlite3.o used on Windows. These inputs complement include directives; neither path resolver reads native file contents.

Only directives that survive comptime branch resolution are seen, so a #flag guarded by an $if for another platform is correctly left out.

fn cache_native_input_is_source #

fn cache_native_input_is_source(path string) bool

cache_native_input_is_source reports whether a native input is a C, C++, Objective-C or assembly source rather than a header.

fn cache_native_input_language #

fn cache_native_input_language(path string, c_flags []string, c99_mode bool, target pref.Target) string

cache_native_input_language reports the exact preprocessor language cgen selects for a native input. The dependency probe and privacy preprocessing must use it so they observe the same predefined macros as the real build; an .mm source, for example, is Objective-C++ and defines both __OBJC__ and __cplusplus, so probing it as plain C or Objective-C omits __cplusplus and wrongly discards branches guarded by it.

fn cache_native_input_path_needs_objective_c #

fn cache_native_input_path_needs_objective_c(path string, c_flags []string, c99_mode bool, target pref.Target) bool

cache_native_input_path_needs_objective_c inspects native source files only. Header contents never participate in language or declaration inference.

fn cache_native_inputs #

fn cache_native_inputs(a &flat.FlatAst, vroot string, target pref.Target, user_c_flags []string, compile_values map[string]string, program_files map[string]bool) CacheNativeInputs

cache_native_inputs classifies the native inputs of a build for the V caches. Directives are attributed to the file that declares them: a V-shipped module may include system headers or add system search paths, while a user file may only name native files shipped with V without bypassing the caches.

fn cache_native_inputs_language #

fn cache_native_inputs_language(a &flat.FlatAst, vroot string, c_flags []string, c99_mode bool, ccompiler string, target pref.Target) string

cache_native_inputs_language reports the richest preprocessor language any native input requires. The shared compiler-macro probe uses it so it never omits a language macro (__OBJC__, __cplusplus) that an input's active branches depend on. An Objective-C(++) source include inside a #if branch that is definitely inactive is skipped: cgen omits such an include too, so it must not force the generated unit into Objective-C or rule out TCC.

fn cache_native_inputs_need_objective_c #

fn cache_native_inputs_need_objective_c(a &flat.FlatAst, vroot string, c_flags []string, c99_mode bool, ccompiler string, target pref.Target) bool

cache_native_inputs_need_objective_c reports whether native inputs need an Objective-C-capable toolchain, including sources compiled in separate wrappers.

fn cache_program_file_set #

fn cache_program_file_set(a &flat.FlatAst, files []string) map[string]bool

cache_program_file_set is the set that set_cache_program_files keeps: each program file by the path it was given and by its real path, so that a caller outside the generator (the driver deciding which $embed_file payloads are assembled, see embed_incbin_payloads) tests membership the same way.

fn cache_project_flag_groups #

fn cache_project_flag_groups(a &flat.FlatAst, vroot string, target pref.Target, compile_values map[string]string, program_files map[string]bool) []cache_refresh.FlagGroup

cache_project_flag_groups returns only directives the refresh importer cannot read. Entry files inside vlib are still project inputs; other vlib flags are resolved anew.

fn embed_incbin_payloads #

fn embed_incbin_payloads(a &flat.FlatAst, program_files map[string]bool, module_cache bool) []EmbedIncbinPayload

embed_incbin_payloads lists the payloads that take the .incbin path when the driver has enabled it: every payload too long for a string literal, in AST order, except, under the module cache, those that a cached module refers to. A cached module is a file outside program_files; its object is reused by later builds that do not assemble this build's objects, so its payloads stay self contained C arrays. The same bytes referred to from both sides are one symbol, and go the self contained way too. The driver and the generator derive the list from the same inputs, so they agree on which objects exist.

fn free_cgen_worker_scopes #

fn free_cgen_worker_scopes(scopes []voidptr)

free_cgen_worker_scopes releases arenas taken with take_parallel_worker_scopes. They are detached from every thread, so any thread can release them.

fn generated_c_unit_needs_objective_c #

fn generated_c_unit_needs_objective_c(a &flat.FlatAst, vroot string, c_flags []string, c99_mode bool, ccompiler string, target pref.Target) bool

generated_c_unit_needs_objective_c excludes ordinary .mm includes, which cgen compiles in separate Objective-C++ wrappers rather than in the generated unit.

fn manual_stdlib_c_headers_error #

fn manual_stdlib_c_headers_error() ?string

manual_stdlib_c_headers_error reports why the embedded manual_stdlib_c_headers.h cannot be used, or returns none. A truncated copy leaves a conditional directive open, which malforms the C preamble of every program that uses the system libc, so the driver checks it before generating any C.

fn merge_libc_variants #

fn merge_libc_variants(headerless string, headers string) string

merge_libc_variants merges two C files generated from the same program, one with V's own libc declarations (headerless) and one with the system headers (headers), into one file that preprocesses to the first when __V_HEADERLESS_LIBC is 1 and to the second when it is 0. The common parts appear once, and each differing run is wrapped in #if/#else/#endif. A run is widened until both of its sides are balanced conditional blocks, so the inserted directives nest correctly with the files' own.

fn module_const_init_order #

fn module_const_init_order(a &flat.FlatAst, tc &types.TypeChecker) []string

module_const_init_order returns the dependency-safe constant initialization order that declaration-only module headers must preserve.

fn msvc_compat_c_source #

fn msvc_compat_c_source(src string) string

msvc_compat_c_source rewrites generated C source so MSVC's cl can compile it.

fn native_include_input_files #

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

native_include_input_files resolves include paths from V directives without reading native files. The C compiler supplies their transitive dependencies.

fn native_path_is_shipped #

fn native_path_is_shipped(path string, vroot string) bool

native_path_is_shipped reports whether a resolved native file belongs to the trees shipped with the V installation at vroot.

fn preflight_directive_flags #

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

preflight_directive_flags resolves flags whose compile-time branches were decided by parsing. Deferred type/metadata conditions are left for the checked, transformed AST.

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 uses_manual_stdlib_c_headers #

fn uses_manual_stdlib_c_headers(a &flat.FlatAst, tc &types.TypeChecker, prefs &pref.Preferences, initial_c_flags []string, object_file_mode bool) bool

uses_manual_stdlib_c_headers reports whether this program needs the embedded libc preamble. It is only needed when the embedded header is damaged, before the driver starts C generation. object_file_mode must match the driver's object-output selection.

fn FlatGen.new #

fn FlatGen.new() FlatGen

new creates a FlatGen value for c.

struct CacheNativeInputs #

struct CacheNativeInputs {
pub mut:
	// module_inputs maps a module (`main` for program files) to the sorted paths of
	// the V-shipped native files and embedded resources its directives name directly.
	// Forced headers belong to __v3_c_flags__, which every cached object depends on.
	module_inputs map[string][]string
	// native_paths holds the paths in module_inputs that native directives name.
	native_paths map[string]bool
	// macro_paths holds forced -imacros inputs. Their declarations are discarded
	// by the C preprocessor, but their transitive files still affect cache keys.
	macro_paths map[string]bool
	// include_dirs are the include directories that every C flag of the build adds.
	include_dirs []string
	// implementation_define names the first `#define` that selects the implementation
	// section of a single-header C library, such as `STB_IMAGE_IMPLEMENTATION`.
	implementation_define string
	// user_supplied names the first user-supplied native input, if there is one.
	user_supplied string
}

CacheNativeInputs separates the native inputs that ship with V from the ones a user supplies. Headers under the V root's vlib/, thirdparty/ and cmd/ trees are versioned with the compiler and system headers with the platform, so their direct paths are only recorded, per owning module, next to $embed_file resources. A user-supplied header is never opened: only the C compiler can account for what it includes, so the first one found is reported instead.

struct EmbedIncbinPayload #

struct EmbedIncbinPayload {
pub:
	symbol  string // the suffix of the `_v_embed_blob_` object the generated C names
	payload string // the bytes that object holds
}

EmbedIncbinPayload is one $embed_file payload that the C build stores through the assembler's .incbin directive rather than a C array initializer.

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             []i32
	ast_string_literals            []string
	ast_string_literals_ready      bool
	ast_string_literals_parsed     int // how many leading ast_string_literals come from parsed nodes
	referenced_c_struct_ids        map[u32]bool
	referenced_c_struct_ids_ready  bool
	embed_payload_node_ids         []i32 // `$embed_file` payload nodes, in AST order
	embed_payload_nodes_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_global_decls          string
	parallel_forward_decls         string
	parallel_forward_decl_parts    []string
	parallel_forward_decl_lanes    bool
	parallel_support_decls         string
	parallel_enum_str_defs         string
	parallel_interface_stubs       string
	parallel_init_defs             string
	parallel_const_code            string
	parallel_support_ready         bool
	test_files                     map[string]bool
	show_test_stats                bool
	show_test_summary              bool
	show_test_file_results         bool
	test_run_only                  []string
	assert_expr_overrides          map[int]string
	callback_target_overrides      map[int]string
	print_fn_names                 []string
	profile_file                   string
	profile_no_inline              bool
	profile_fns                    []string
	profile_counters               []ProfileCounterMeta
	profile_fn_active              bool
	profile_fn_restore_enabled     bool
	is_prod                        bool
	is_debug                       bool
	check_overflow                 bool
	ignore_overflow                bool
	check_casts                    bool
	check_scope_vlib_prefixes      []string
	user_code_checks               bool
	force_bounds_checking          bool
	is_shared                      bool
	interface_exports              []string
	object_file_mode               bool
	tcc_program_unit               bool
	native_function_aliases        map[string]string
	no_builtin                     bool
	suppress_main                  bool
	coverage_dir                   string
	coverage_build_options         string
	race                           bool
	line_directives                bool
	vlines                         bool
	line_directive_paths           map[string]string
	line_directive_fn_start        int
	coverage_files                 map[string]&CoverageInfo
	coverage_counter_count         int
	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
	str_lit_chunk_indexes          []int // body chunk of each literal past str_lits_base_len
	// Worker snapshots inherit this immutable prefix from their parent generator.
	str_lits_base_len int
	global_types      map[string]types.Type
	// Globals declared `volatile`. A kernel writes these where the hardware or
	// the bootloader can see them, so the qualifier has to survive into the C.
	global_volatile_names          map[string]bool
	global_raw_type_texts          flat.TypeTextBindings
	global_shared_storage_present  bool
	enum_vals                      map[string]int
	enum_value_exprs               map[string]string
	enum_values_from_c             map[string]bool // C names of members valued from C (`a = C.FOO`); 0 in enum_vals
	enum_modules                   map[u32]string
	defers                         []flat.NodeId
	defer_cleanup_stack            []flat.NodeId // already emitted by the active cleanup path
	scope_defer_starts             []int
	fn_defers                      []flat.NodeId
	fn_defer_counts                map[int]string
	defer_capture_names            []string
	defer_capture_types            map[string]types.Type
	uses_recover                   bool // the program calls `recover()`, so every `defer` links a panic frame
	program_recover_known          bool // the driver said whether the program calls `recover()`, see set_program_uses_recover
	program_recover                bool
	cur_fn_panic_owner             bool   // the current function declared the `_v_unwind_owner` of its frames
	cur_panic_frame                string // frame of the deferred block being emitted, which `recover()` asks for
	interfaces                     map[u32][]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_helper_dependencies      &ConstHelperDependencies = unsafe { nil }
	cache_const_modules            map[string]bool
	cache_const_source_modules     map[string]bool
	cache_const_definitions        map[string][]string
	cache_const_declarations       map[string]string
	cache_decl_refs                map[string]bool
	cache_decl_demand              bool
	cache_pruned_fn_names          []string
	cache_pruned_fn_modules        []string
	cache_pruned_fn_refs           []string
	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
	in_global_array_pointer_init   bool
	enum_backing_infos             map[u32]EnumBackingInfo
	iface_impls                    map[u32][]u32   // interface source spelling ID -> concrete source spelling IDs
	interface_dispatch_required    map[string]bool // source/lowered concrete method names required by emitted interface dispatch
	iface_type_ids                 map[u64]int     // paired source spelling IDs -> 1-based dispatch ID
	interface_boxed_types          map[u64]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[u64]u32           // aggregate-kind/source-ID key -> concrete struct source-ID
	local_pointer_storage_by_owner map[string]bool       // exact scope binding owner -> C storage is already a pointer
	local_c_type_by_owner          flat.TypeTextBindings // 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        flat.TypeTextBindings // exact scope binding owner -> source-level raw type text
	local_indirect_value_by_owner  map[string]types.Type // exact scope binding owner -> semantic value behind indirect C storage
	local_implicit_deref_by_owner  map[string]bool       // exact scope binding owner -> C pointer storage read as a semantic value
	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[u32]u32           // full/short source spelling ID -> canonical sum spelling ID
	sum_variant_lookup             map[u32]map[u32]u32   // sum spelling ID -> exact/short variant ID -> canonical variant ID
	sum_variant_actual_cache       &SumVariantActualCache = &SumVariantActualCache{} // sum name + semantic actual type -> canonical variant (empty means miss)
	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_cleanup_fns             []string            // C names of module-level `cleanup()` fns, in source order
	module_cleanup_fn_modules      map[string]string   // C cleanup fn name -> V module name
	module_imports                 map[string][]string // module -> imported modules
	core_header_directives         []DeferredCoreHeader
	c_directives                   []CDirective
	preinclude_directives          []string
	postinclude_directives         []string
	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
	cache_native_c_symbols         map[string]bool
	inlined_c_typedef_names        map[string]bool
	inlined_c_fns                  map[string]bool
	inlined_c_declared_fns         map[string]bool
	files_with_c_includes          map[string]bool
	files_with_c_postincludes      map[string]bool
	files_linking_c_sources        map[string]bool
	mods_with_c_libs               map[string]bool
	mods_with_c_includes           map[string]bool
	inlined_c_active_macros        map[string]bool
	inlined_c_static_fns           map[string]bool
	cache_omitted_c_fns            map[string]bool
	initial_c_flags                []string
	cache_refresh_project_flags    []cache_refresh.FlagGroup
	c_flags                        []string
	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
	decl_fn_ptr_types              map[string]bool   // the declaration-side ones, see split_body_fn_ptr_types_from_decls
	split_body_fn_ptr_types        bool
	multi_return_types             []types.Type
	multi_return_type_names        map[string]bool
	multi_return_types_ready       bool
	decl_types_ready               bool
	selected_decl_types_ready      bool
	shared_sum_wrappers_ready      bool
	optional_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 __v_option_T ABI
	fixed_array_typedefs_needed    map[string]FixedArrayTypedefInfo
	fixed_array_typedefs_ready     bool
	fixed_array_map_key_types      map[string]types.ArrayFixed
	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
	shared_param_index_empty       bool
	has_shared_params              bool
	fn_decl_mut_receivers          map[string]bool
	specialized_method_c_names     map[string]string      // concrete declaration spelling -> selected C symbol
	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[u32]StructDeclInfo
	struct_decl_short_infos       map[u32]StructDeclInfo
	decl_attrs                    map[int][]string
	decl_attrs_by_source_position map[u64][]string
	c_decl_abi_names              map[string]string
	c_extern_forced_decls         map[string]bool
	export_c_abi_decls            map[string]flat.NodeId
	main_export_owners            map[string][]string
	main_export_c_abi_wrappers    map[string]bool
	c_extern_global_names         map[string]string
	export_global_names           map[string]string
	global_linker_sections        map[string]string
	global_cinit_names            map[string]bool
	static_c_initializer          bool
	const_init_depth              int                             // >0 while a const initializer is inlined; see ident_is_local_binding
	shared_type_names             map[string]SharedTypeInfo       // __shared__ wrapper name -> wrapped type metadata
	shared_alias_pointer_cache    map[u32]map[string][]types.Type // source spelling -> file/module resolution results
	shared_alias_pointer_shorts   map[u32]u32                     // alias short spelling ID -> shared inner source ID; 0 means ambiguous
	shared_alias_index_ready      bool
	needs_shared_runtime          bool
	needs_pthread_header          bool
	needs_thread_type             bool
	needs_thread_runtime          bool
	spawn_detached                bool // the spawn being emitted has its handle discarded
	spawn_comparable              bool // keep a discarded spawn's handle until its comparison finishes
	detached_spawn_drop           bool // ownership traversal also joins nested handles and destroys closures
	spawn_return_type             types.Type = cgen_void_type
	const_runtime_inits           []string
	const_runtime_init_modules    []string
	runtime_inits                 []string
	runtime_init_modules          []string
	compiler_vroot                string
	compiler_vexe                 string
	live_source_path              string
	live_rebuild_options          string
	compiler_vexe_env_setup       bool = true
	ccompiler                     string
	target                        pref.Target
	// output_cross_c keeps every target-dependent `$if` in the output, guarded by
	// the C preprocessor, so one generated snapshot compiles on any target.
	output_cross_c bool
	// cross_directive_guards maps a `#include`/`#flag` node to the C preprocessor
	// condition of the `$if` it was written in, for portable output.
	cross_directive_guards map[int]string
	// compile_defines are the `-d`/`-define` names of this build, reported in the
	// generated header the way the reference compiler did.
	compile_defines               []string
	subsystem                     pref.Subsystem
	target_libc_headers           bool
	windows_entry_point_generated bool
	windows_gui_entry_point       bool
	// C spelling for V's platform-width `int`: `i64` on 64-bit targets, `i32` on
	// 32-bit. Used by hand-written runtime helpers that operate on `[]int`
	// elements or `int` values directly (kept in sync with set_target).
	int_ct                        string = 'i64'
	thread_stack_size             int    = 8 * 1024 * 1024
	compile_values                map[string]string // explicit `-d` values used by `$d(...)` in C directives
	output_path                   string
	output_error                  string
	c99_mode                      bool
	trace_calls                   bool // -d trace: custom call-site hooks
	is_trace_calls                bool // -trace-calls: function-entry logging
	trace_fns                     []string
	track_heap                    bool
	inside_trace_call             bool
	skip_generics                 bool
	skip_enum_autostr             bool
	literal_output_only           bool
	placeholder_check_forced      bool
	cur_fn_name                   string
	cur_fn_source_file            string
	cur_fn_is_specialized         bool
	cur_fn_assert_continues       bool
	cur_fn_manualfree             bool
	current_decl_is_mut           bool
	direct_array_access           bool
	struct_default_module         string
	struct_default_generic_params []string
	struct_default_generic_args   flat.TypeTextList
	default_value_stack           map[u32]bool
	shallow_default_value_depth   int
	shadowed_global_locals        map[string]bool
	cur_param_names               []string
	cur_param_type_values         []&types.Type
	cur_param_types               map[string]&types.Type
	cur_param_name_bits           u64
	// Same filter for cur_mut_params: a name whose bit is clear is no mut parameter.
	cur_mut_param_name_bits         u64
	cur_concrete_optional_params    map[string]bool
	cur_mut_params                  map[string]bool
	cur_mut_pointer_params          map[string]bool
	cur_explicit_mut_pointer_params map[string]bool
	cur_mut_param_owners            map[string]types.ScopeBindingOwner
	cur_c_fn_calls                  map[string]bool
	cur_fn_ret                      types.Type = cgen_void_type
	cur_fn_ret_is_optional          bool
	cur_fn_ret_base                 types.Type = cgen_void_type
	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_defer_starts               []int
	loop_label_defer_starts         map[string]int
	loop_control_copybacks          []LoopControlCopyback
	map_loop_copyback_guards        []MapLoopCopybackGuard
	emitted_loop_break_labels       map[string]bool
	goto_label_c_names              map[string]string
	goto_label_count                int
	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 = cgen_void_type
	expected_enum                  u32
	known_expr_type_id             int        = -1
	known_expr_type                types.Type = cgen_void_type
	memo_usable_expr_types         bool
	cache_struct_fields            bool
	dedup_fn_decl_aliases          bool
	prefix_param_scan              bool
	lean_parallel_worker_init      bool
	lazy_param_abi_merge           bool
	usable_expr_type_memo          &UsableExprTypeMemo  = unsafe { nil }
	import_key_cache               &util.KeyRecentCache = unsafe { nil }
	needed_optional_types          flat.TypeTextBindings
	optional_pointer_struct_tags   map[string]string
	optional_payload_types         map[string]types.Type // C name -> struct or sum type, for option typedefs
	optional_payload_types_from    int                   // the checker's struct and sum count it was built from
	// cabi_int_out_args maps a C-call argument node to the C spelling to emit in its
	// place (the address of a temporary C `int`), while a `&int` out-parameter is
	// bridged by a temporary + copy-back around the wrapped call. Keyed by node id so
	// nested calls never collide.
	cabi_int_out_args               map[flat.NodeId]string
	emitted_optional_types          map[string]bool
	array_method_cache              map[string]string
	array_method_receiver_cache     map[u64]map[string]string
	param_types_cache               map[string][]types.Type // (name|fallback) -> resolved param types
	interface_receiver_cache        &TypeNameLookupCache          = unsafe { nil }
	normalize_call_cache            &ContextStringLookupCache     = unsafe { nil }
	flattened_generic_name_cache    &TypeNameLookupCache          = unsafe { nil }
	generic_struct_context_ct_cache &TypeNameLookupCache          = unsafe { nil }
	struct_cname_cache              &TypeNameLookupCache          = unsafe { nil }
	unique_struct_ct_cache          &TypeNameLookupCache          = unsafe { nil }
	alias_method_cache              &AliasMethodLookupCache       = unsafe { nil }
	import_alias_cache              &ContextStringLookupCache     = unsafe { nil }
	enum_selector_cache             &ContextSourceTypeLookupCache = unsafe { nil }
	enum_method_cache               &ContextStringLookupCache     = unsafe { nil }
	qualified_enum_method_cache     &ContextStringLookupCache     = unsafe { nil }
	import_type_cache               &ImportTypeCache              = unsafe { nil }
	embedded_fields_by_type         map[u32][]types.StructField // source type ID -> 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[u32]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
	callback_identity_used          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
	// Set on forks that read the master's complete, frozen c_extern_refs instead
	// of a copy; they have nothing of their own to merge back.
	c_extern_refs_shared            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 }
	local_typedef_shadow_facts      &FnNameFactCache      = unsafe { nil }
	local_global_shadow_facts       &ContextNameFactCache = unsafe { nil }
	local_global_suffix_names       map[string]bool
	local_global_suffix_names_ready bool
	// Per first byte, the set of lengths (bit 63 = 63 or longer) of the names
	// above, so a local name with no candidate skips hashing (see cgen_name_len_bits).
	local_global_suffix_len_bits []u64
	local_name_exceptions        &LocalNameExceptions = unsafe { nil }
	// C names a local must not take because a typedef already uses them; see
	// precompute_c_typedef_shadow_names.
	c_typedef_shadow_names       map[string]bool
	c_typedef_shadow_names_ready bool
	// None of the shadow names is a spelling that cname produces by renaming
	// another identifier (`v_x`, `int__str`, internal symbols).
	c_typedef_shadow_names_plain bool
	c_typedef_shadow_len_bits    []u64
	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
	// No registered type alias is spelled `main.<name>`, so main_type_alias_id
	// cannot find one and value_unalias_type skips building that key.
	main_type_aliases_absent bool
	// Dense view of the checker's sparse resolved-call map (names of the
	// transform-created call nodes, which cgen asks about far more often than
	// the parsed ones): index[idx - base] is 1 + the position in values, or 0.
	sparse_call_name_index       []u32
	sparse_call_name_values      []string
	sparse_call_name_index_base  int
	sparse_call_name_index_ready bool
	// offsetof_expr and leaf sizeof_expr nodes in AST order (referenced_c_structs).
	sizeof_offsetof_node_ids    []i32
	sizeof_offsetof_nodes_ready bool
	prep_typ_text_cache         &PrepTypTextCache = unsafe { nil }
	prep_alias_short_names      map[u32]bool
	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 }
	struct_field_index_base            &StructFieldIndexBase = unsafe { nil }
	type_name_short_index              &TypeNameShortIndex   = unsafe { nil }
	qualified_struct_c_types_by_suffix flat.TypeTextListBindings
	qualified_struct_c_types_ready     bool
	unused_param_seen                  &UnusedParamSeen = unsafe { nil }
	cache_split                        bool
	cache_stable_symbols               bool
	parallel_cc                        bool
	// Set when the driver stores long `$embed_file` payloads through the
	// assembler (see embed_incbin_payloads); the set of objects it does that for
	// is derived on first use.
	embed_incbin               bool
	embed_incbin_syms          map[string]bool
	embed_incbin_syms_ready    bool
	cache_native_input_paths   map[string]bool
	program_body_only          bool
	cached_program_cleanup     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
	type_metadata_node_ids    []i32
	type_metadata_nodes_ready bool
	// One bit per node: the type metadata nodes that collect_local_shared_type_names
	// has to visit (see shared_scan_node_relevant), set by the parallel info scan.
	shared_scan_bits       []u64
	shared_scan_bits_ready bool
}

FlatGen emits flat gen output used by c.

fn (FlatGen) set_cache_const_modules #

fn (mut g FlatGen) set_cache_const_modules(modules []string, source_modules []string)

set_cache_const_modules assigns constant storage to the modules linked as objects.

fn (FlatGen) set_cache_pruned_functions #

fn (mut g FlatGen) set_cache_pruned_functions(names []string, modules []string)

set_cache_pruned_functions names the functions of cached modules whose declarations the build took out of the AST before its stages ran: names[i] is declared in modules[i]. The generator has no prototype to give for them.

fn (FlatGen) referenced_pruned_cache_functions #

fn (g &FlatGen) referenced_pruned_cache_functions() ([]string, bool)

referenced_pruned_cache_functions returns the functions of set_cache_pruned_functions that the generated C names, and whether the generator could tell: it can when it emitted the declarations of cached modules on demand. A build with such a function has to be made again with its declaration.

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_cache_refresh_project_flags #

fn (mut g FlatGen) set_cache_refresh_project_flags(groups []cache_refresh.FlagGroup)

set_cache_refresh_project_flags restores project directives beside current module flags.

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_ccompiler #

fn (mut g FlatGen) set_ccompiler(name string)

set_ccompiler records the selected C compiler for compiler-specific output constraints.

fn (FlatGen) set_tcc_program_unit #

fn (mut g FlatGen) set_tcc_program_unit(enabled bool)

set_tcc_program_unit applies TCC's C constraints when the native owner uses another compiler.

fn (FlatGen) set_native_function_aliases #

fn (mut g FlatGen) set_native_function_aliases(names []string)

set_native_function_aliases redirects qualified C function references to owner pointers.

fn (FlatGen) set_prod #

fn (mut g FlatGen) set_prod(enabled bool)

set_prod controls production-only code generation such as removing assertions.

fn (FlatGen) set_debug #

fn (mut g FlatGen) set_debug(enabled bool)

set_debug enables source-aware panic reporting for debug builds.

fn (FlatGen) set_check_overflow #

fn (mut g FlatGen) set_check_overflow(enabled bool)

set_check_overflow enables runtime checks for integer addition, subtraction, multiplication, negation and division, and for out of range shift counts.

fn (FlatGen) set_check_casts #

fn (mut g FlatGen) set_check_casts(enabled bool)

set_check_casts enables runtime checks for integer casts that lose information.

fn (FlatGen) set_check_scope_vroot #

fn (mut g FlatGen) set_check_scope_vroot(vroot string)

set_check_scope_vroot records the V installation, whose standard library (vlib/) keeps V's defined negation, shift and cast semantics under -check-overflow and -check-casts.

fn (FlatGen) set_force_bounds_checking #

fn (mut g FlatGen) set_force_bounds_checking(enabled bool)

set_force_bounds_checking ignores direct-array-access attributes so every generated array access retains its runtime bounds check.

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_output_cross_c #

fn (mut g FlatGen) set_output_cross_c(enabled bool)

set_output_cross_c requests portable C that defers every target-dependent $if to the C preprocessor instead of resolving it for one target.

fn (FlatGen) set_compile_defines #

fn (mut g FlatGen) set_compile_defines(defines []string)

set_compile_defines records the -d/-define names to report in the header of the generated C.

fn (FlatGen) set_subsystem #

fn (mut g FlatGen) set_subsystem(subsystem pref.Subsystem)

set_subsystem configures the Windows executable subsystem.

fn (FlatGen) set_target_libc_headers #

fn (mut g FlatGen) set_target_libc_headers(target_libc_headers bool)

set_target_libc_headers marks a target that supplies the libc headers itself.

fn (FlatGen) generated_windows_gui_entry_point #

fn (g &FlatGen) generated_windows_gui_entry_point() ?bool

generated_windows_gui_entry_point reports the GUI decision when this generator emitted a Windows executable entry point, or none when the current generation did not emit one.

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_show_test_stats #

fn (mut g FlatGen) set_show_test_stats(enabled bool)

set_show_test_stats enables the per-test assertion summary used by v -stats test.

fn (FlatGen) set_show_test_summary #

fn (mut g FlatGen) set_show_test_summary(enabled bool)

set_show_test_summary enables the aggregate report used by the v test command.

fn (FlatGen) set_show_test_file_results #

fn (mut g FlatGen) set_show_test_file_results(enabled bool)

set_show_test_file_results enables the per-test-file OK/FAIL lines of v test.

fn (FlatGen) set_test_run_only #

fn (mut g FlatGen) set_test_run_only(patterns []string)

set_test_run_only limits the generated test harness to matching test functions.

fn (FlatGen) set_print_fn_names #

fn (mut g FlatGen) set_print_fn_names(names []string)

set_print_fn_names selects generated C functions to print to stdout.

fn (FlatGen) set_profile #

fn (mut g FlatGen) set_profile(file string, no_inline bool, fn_names []string)

set_profile configures V1-compatible per-function runtime profiling.

fn (FlatGen) set_shared #

fn (mut g FlatGen) set_shared(enabled bool)

set_shared configures shared-library entry point generation.

fn (FlatGen) set_no_builtin #

fn (mut g FlatGen) set_no_builtin(enabled bool)

set_no_builtin enables compatibility declarations when V libc bindings are unavailable.

fn (FlatGen) set_object_file_mode #

fn (mut g FlatGen) set_object_file_mode(enabled bool)

set_object_file_mode gives generated runtime symbols translation-unit-local linkage while retaining public entry-module functions through C ABI wrappers.

fn (FlatGen) set_suppress_main #

fn (mut g FlatGen) set_suppress_main(enabled bool)

set_suppress_main disables executable entry point generation for -d no_main builds.

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 C directives resolves configured values over fallbacks.

fn (FlatGen) set_track_heap #

fn (mut g FlatGen) set_track_heap(enabled bool)

set_track_heap records whether user-provided heap tracking hooks are required.

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_uses_recover #

fn (mut g FlatGen) set_program_uses_recover(uses_recover bool)

set_program_uses_recover tells whether the program reaches recover(), or has a cached module whose code calls it. A module cache build marks every function of a module it parses from source as used, recover among those of builtin, which says nothing about the program: the objects of its modules would link panic frames in the build that compiles builtin, and not in the one that reads its header.

fn (FlatGen) set_cache_stable_symbols #

fn (mut g FlatGen) set_cache_stable_symbols(enabled bool)

set_cache_stable_symbols turns on the content-addressed renaming of generated string-literal symbols. Only the module cache needs it, so that separately compiled generations agree on a symbol's name. A split C build shares one generated prefix with its own units, so it keeps the plain _str_N numbering and skips a rewrite pass over the whole translation unit.

fn (FlatGen) set_embed_incbin #

fn (mut g FlatGen) set_embed_incbin(enabled bool)

set_embed_incbin makes long $embed_file payloads refer to objects the driver assembles from the bytes with .incbin, instead of spelling the bytes out as C array initializers; see embed_incbin_payloads for which payloads that covers.

fn (FlatGen) set_parallel_cc #

fn (mut g FlatGen) set_parallel_cc(enabled bool)

set_parallel_cc marks safe top-level function batches for split C compilation.

fn (FlatGen) set_cache_native_input_paths #

fn (mut g FlatGen) set_cache_native_input_paths(paths []string)

set_cache_native_input_paths assigns native headers and sources to their owning cached module object instead of the shared generated declaration prefix.

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_cached_program_cleanup #

fn (mut g FlatGen) set_cached_program_cleanup(enabled bool)

set_cached_program_cleanup records whether the cached program prefix owns its exit hook.

fn (FlatGen) set_cache_program_files #

fn (mut g FlatGen) set_cache_program_files(a &flat.FlatAst, files []string)

set_cache_program_files assigns entry-module source files to the program translation unit rather than an imported module cache object. Each file is resolved through a's table of resolved source paths.

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) take_parallel_worker_scopes #

fn (mut g FlatGen) take_parallel_worker_scopes() []voidptr

take_parallel_worker_scopes hands the arenas retained for cgen's output over to the caller, which releases them with free_cgen_worker_scopes.

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

gen_with_used_test_options emits a like gen_with_used_options, generating the test harness for test_files. Each test file counts as written and as resolved through a's table of resolved source paths.

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.

fn (FlatGen) struct_default_generic_args_text #

@[inline]
fn (value &FlatGen) struct_default_generic_args_text() []string

struct_default_generic_args_text resolves the indexed source type spelling.

fn (FlatGen) set_coverage #

fn (mut g FlatGen) set_coverage(dir string, build_options string)

set_coverage enables V-compatible line coverage output.

fn (FlatGen) set_race #

fn (mut g FlatGen) set_race(enabled bool)

set_race generates C for a race build (-race). The generated C maps every V statement back to its source line with #line directives, so the C debug info carries the V file:line positions that the race detector shows in its stack traces, and the few V constructs that read memory without the C compiler loading it do load it.

fn (FlatGen) set_vlines #

fn (mut g FlatGen) set_vlines(enabled bool)

set_vlines maps generated C back to V sources for -g, while -cg keeps C positions. Race builds always need V positions, regardless of the selected debug flag.

fn (FlatGen) generated_literal_output_only #

fn (g &FlatGen) generated_literal_output_only() bool

generated_literal_output_only reports that the emitted program has no V runtime or atomic operations, so the driver need not link atomic support.

fn (FlatGen) set_live_source_path #

fn (mut g FlatGen) set_live_source_path(path string)

set_live_source_path records the original compilation target for the live reloader.

fn (FlatGen) set_live_rebuild_options #

fn (mut g FlatGen) set_live_rebuild_options(options []string)

set_live_rebuild_options records compiler arguments reused by the live shared-library build.

fn (FlatGen) set_trace_calls #

fn (mut g FlatGen) set_trace_calls(enabled bool, patterns []string)

set_trace_calls configures V1-compatible function-entry tracing. This is separate from the user-provided call-site hooks enabled with -d trace.