Skip to content

core.code #

Code Model

A comprehensive module for parsing, analyzing, and generating V code. The Code Model provides lightweight, language-agnostic structures to represent code elements like structs, functions, imports, and types.

Overview

The code module is useful for:

  • Code Parsing: Parse V files into structured models
  • Code Analysis: Extract information about functions, structs, and types
  • Code Generation: Generate V code from models using vgen()
  • Static Analysis: Inspect and traverse code using language utilities
  • Documentation Generation: Serialize code into other formats (JSON, Markdown, etc.)

Core Components

Code Structures (Models)

  • Struct: Represents V struct definitions with fields, visibility, and generics
  • Function: Represents functions/methods with parameters, return types, and bodies
  • Interface: Represents V interface definitions
  • VFile: Represents a complete V file with module, imports, constants, and items
  • Module: Represents a V module with nested files and folders
  • Import: Represents import statements
  • Param: Represents function parameters with types and modifiers
  • Type: Union type supporting arrays, maps, results, objects, and basic types
  • Const: Represents constant definitions

Type System

The Type union supports:- Basic types: String, Boolean, Integer (signed/unsigned, 8/16/32/64-bit)

  • Composite types: Array, Map, Object
  • Function types: Function
  • Result types: Result (for error handling with !)
  • Aliases: Alias

Usage Examples

Parsing a V File

import incubaid.herolib.core.code
import os

// Read and parse a V file
content := os.read_file('path/to/file.v')!
vfile := code.parse_vfile(content)!

// Access parsed elements
println('Module: ${vfile.mod}')
println('Imports: ${vfile.imports.len}')
println('Structs: ${vfile.structs().len}')
println('Functions: ${vfile.functions().len}')

Analyzing Structs

import incubaid.herolib.core.code

// Parse a struct definition
struct_code := 'pub struct User {
pub:
    name string
    age  int
}'

vfile := code.parse_vfile(struct_code)!
structs := vfile.structs()

for struct_ in structs {
    println('Struct: ${struct_.name}')
    println('  Is public: ${struct_.is_pub}')
    for field in struct_.fields {
        println('  Field: ${field.name} (${field.typ.symbol()})')
    }
}

Analyzing Functions

import incubaid.herolib.core.code

fn_code := 'pub fn greet(name string) string {
    return "Hello, \${name}!"
}'

vfile := code.parse_vfile(fn_code)!
functions := vfile.functions()

for func in functions {
    println('Function: ${func.name}')
    println('  Public: ${func.is_pub}')
    println('  Parameters: ${func.params.len}')
    println('  Returns: ${func.result.typ.symbol()}')
}

Code Generation

import incubaid.herolib.core.code

// Create a struct model
my_struct := code.Struct{
    name: 'Person'
    is_pub: true
    fields: [
        code.StructField{
            name: 'name'
            typ: code.type_from_symbol('string')
            is_pub: true
        },
        code.StructField{
            name: 'age'
            typ: code.type_from_symbol('int')
            is_pub: true
        }
    ]
}

// Generate V code from the model
generated_code := my_struct.vgen()
println(generated_code)
// Output: pub struct Person { ... }

V Language Utilities

import incubaid.herolib.core.code

// List all V files in a directory (excludes generated files ending with _.v)
v_files := code.list_v_files('/path/to/module')!

// Get a specific function from a module
func := code.get_function_from_module('/path/to/module', 'my_function')!
println('Found function: ${func.name}')

// Get a type definition from a module
type_def := code.get_type_from_module('/path/to/module', 'MyStruct')!
println(type_def)

// Run V tests
test_results := code.vtest('/path/to/module')!

Working With Modules and Files

import incubaid.herolib.core.code

// Create a module structure
my_module := code.Module{
    name: 'mymodule'
    description: 'My awesome module'
    version: '1.0.0'
    license: 'apache2'
    files: [
        code.VFile{
            name: 'structs'
            mod: 'mymodule'
            // ... add items
        }
    ]
}

// Write module to disk
write_opts := code.WriteOptions{
    overwrite: false
    format: true
    compile: false
}
my_module.write('/output/path', write_opts)!

Advanced Features

Custom Code Generation

import incubaid.herolib.core.code

// Generate a function call from a Function model
func := code.Function{
    name: 'calculate'
    params: [
        code.Param{ name: 'x', typ: code.type_from_symbol('int') },
        code.Param{ name: 'y', typ: code.type_from_symbol('int') }
    ]
    result: code.Param{ typ: code.type_from_symbol('int') }
}

call := func.generate_call(receiver: 'calculator')!
// Output: result := calculator.calculate(...)

Type Conversion

import incubaid.herolib.core.code

// Convert from type symbol to Type model
t := code.type_from_symbol('[]string')

// Get the V representation
v_code := t.vgen()  // Output: "[]string"

// Get the TypeScript representation
ts_code := t.typescript()  // Output: "string[]"

// Get the symbol representation
symbol := t.symbol()  // Output: "[]string"

Complete Example

See the working example at examples/core/code/code_parser.vsh for a complete demonstration of:

  • Listing V files in a directory
  • Parsing multiple V files
  • Extracting and analyzing structs and functions
  • Summarizing module contents

Run it with:

vrun ~/code/github/incubaid/herolib/examples/core/code/code_parser.vsh

Coding Instructions

When using the Code module:

  1. Always parse before analyzing: Use parse_vfile(), parse_struct(), or parse_function() to create models from code strings
  2. Use type filters: Filter code items by type using .filter(it is StructType) pattern
  3. Check visibility: Always verify is_pub flag when examining public API
  4. Handle errors: Code parsing can fail; always use ! or or blocks
  5. Generate code carefully: Use WriteOptions to control formatting, compilation, and testing
  6. Use language utilities: Prefer get_function_from_module() over manual file searching
  7. Cache parsed results: Store VFile objects if you need to access them multiple times
  8. Document generated code: Add descriptions to generated structs and functions

API Reference

Parsing Functions

  • parse_vfile(code string) !VFile - Parse an entire V file
  • parse_struct(code string) !Struct - Parse a struct definition
  • parse_function(code string) !Function - Parse a function definition
  • parse_param(code string) !Param - Parse a parameter
  • parse_type(type_str string) Type - Parse a type string
  • parse_const(code string) !Const - Parse a constant
  • parse_import(code string) Import - Parse an import statement

Code Generation

  • vgen(code []CodeItem) string - Generate V code from code items
  • Struct.vgen() string - Generate struct V code
  • Function.vgen() string - Generate function V code
  • Interface.vgen() string - Generate interface V code
  • Import.vgen() string - Generate import statement

Language Utilities

  • list_v_files(dir string) ![]string - List V files in directory
  • get_function_from_module(module_path string, name string) !Function - Find function
  • get_type_from_module(module_path string, name string) !string - Find type definition
  • get_module_dir(mod string) string - Convert module name to directory path

Constants #

const type_i8 = Integer{
	bytes: 8
}

Integer types

const type_u8 = Integer{
	bytes:  8
	signed: false
}
const type_i16 = Integer{
	bytes: 16
}
const type_u16 = Integer{
	bytes:  16
	signed: false
}
const type_i32 = Integer{
	bytes: 32
}
const type_u32 = Integer{
	bytes:  32
	signed: false
}
const type_i64 = Integer{
	bytes: 64
}
const type_u64 = Integer{
	bytes:  64
	signed: false
}
const type_f32 = Float{
	bytes: 32
}

Floating-point types

const type_f64 = Float{
	bytes: 64
}

fn function_to_interface_field #

fn function_to_interface_field(f Function) string

fn get_function_from_file #

fn get_function_from_file(file_path string, function_name string) !Function

get_function_from_file parses a V file and extracts a specific function block including its comments ARGS: file_path string - path to the V file function_name string - name of the function to extract RETURNS: string - the function block including comments, or error if not found

fn get_function_from_module #

fn get_function_from_module(module_path string, function_name string) !Function

get_function_from_module searches for a function in all V files within a module ARGS: module_path string - path to the module directory function_name string - name of the function to find RETURNS: string - the function definition if found, or error if not found

fn get_module_dir #

fn get_module_dir(mod string) string

get_module_dir converts a V module path to a directory path ARGS: mod string - module name (e.g., 'incubaid.herolib.mcp') RETURNS: string - absolute path to the module directory

fn get_struct #

fn get_struct(params GetStruct) ?Struct

fn get_type_from_module #

fn get_type_from_module(module_path string, type_name string) !string

get_type_from_module searches for a type definition in all V files within a module ARGS: module_path string - path to the module directory type_name string - name of the type to find RETURNS: string - the type definition if found, or error if not found

fn inflate_struct_fields #

fn inflate_struct_fields(code []CodeItem, mut struct_ CodeItem)

fn inflate_types #

fn inflate_types(mut code []CodeItem)

fn list_v_files #

fn list_v_files(dir string) ![]string

list_v_files returns all .v files in a directory (non-recursive), excluding generated files ending with _.v ARGS: dir string - directory path to search RETURNS: []string - list of absolute paths to V files

fn new_file #

fn new_file(config VFile) VFile

fn new_function #

fn new_function(code string) !Function

fn new_module #

fn new_module(mod Module) Module

fn new_param #

fn new_param(params Params) !Param

fn parse_const #

fn parse_const(code_ string) !Const

fn parse_consts #

fn parse_consts(code_ string) ![]Const

fn parse_enum #

fn parse_enum(code_ string) !Enum

fn parse_function #

fn parse_function(code_ string) !Function

fn parse_import #

fn parse_import(code_ string) Import

fn parse_param #

fn parse_param(code_ string) !Param

fn parse_struct #

fn parse_struct(code_ string) !Struct

parse_struct parses a struct definition string and returns a Struct object The input string should include the struct definition including any preceding comments

fn parse_type #

fn parse_type(type_str string) Type

parse_type parses a type string into a Type struct

fn parse_vfile #

fn parse_vfile(code string) !VFile

parse_vfile parses V code into a VFile struct It extracts the module name, imports, constants, structs, functions, enums and interfaces

fn type_from_symbol #

fn type_from_symbol(symbol_ string) Type

fn vgen #

fn vgen(code []CodeItem) string

fn vgen_generics #

fn vgen_generics(generics map[string]string) string

interface IBasicFolder #

interface IBasicFolder {
	name    string
	files   []IFile
	modules []Module
	write(string, WriteOptions) !
}

interface IFile #

interface IFile {
	name string
	write(string, WriteOptions) !
	write_str(WriteOptions) !string
}

interface IFolder #

interface IFolder {
	name    string
	files   []IFile
	modules []Module
	write(string, WriteOptions) !
}

type CodeItem #

type CodeItem = Alias
	| Comment
	| CustomCode
	| Function
	| Import
	| Struct
	| Sumtype
	| Interface
	| Enum

Code is a list of statements pub type Code = []CodeItem

type Type #

type Type = Void
	| Map
	| Array
	| Object
	| Result
	| Integer
	| Alias
	| String
	| Boolean
	| Function

fn (Type) symbol #

fn (t Type) symbol() string

fn (Type) typescript #

fn (t Type) typescript() string

fn (Type) vgen #

fn (t Type) vgen() string

Todo: enfore that cant be both mutable and shared

fn (Type) empty_value #

fn (t Type) empty_value() string

type Value #

type Value = string

struct Alias #

struct Alias {
pub:
	name        string
	description string
	typ         Type
}

fn (Alias) symbol #

fn (t Alias) symbol() string

struct Array #

struct Array {
pub:
	typ Type
}

struct Attribute #

struct Attribute {
pub:
	name    string // [name]
	has_arg bool
	arg     string // [name: arg]
}

struct BasicFolder #

struct BasicFolder {
pub:
	name    string
	files   []IFile
	folders []IBasicFolder
	modules []Module
}

fn (BasicFolder) write #

fn (f BasicFolder) write(path string, options WriteOptions) !

struct Boolean #

struct Boolean {}

fn (Boolean) symbol #

fn (t Boolean) symbol() string

struct Comment #

struct Comment {
pub:
	text     string
	is_multi bool
}

struct Const #

struct Const {
pub mut:
	name  string
	value string
}

struct CustomCode #

struct CustomCode {
pub:
	text string
}

item for adding custom code in

fn (CustomCode) vgen #

fn (custom CustomCode) vgen() string

struct Enum #

struct Enum {
pub mut:
	name        string
	description string
	is_pub      bool
	values      []EnumValue
}

fn (Enum) vgen #

fn (e Enum) vgen() string

struct EnumValue #

struct EnumValue {
pub:
	name        string
	value       string
	description string
}

struct Example #

struct Example {
	function Function
	values   map[string]Value
	result   Value
}

struct File #

struct File {
pub mut:
	name      string
	extension string
	content   string
}

fn (File) write #

fn (f File) write(path string, params WriteOptions) !

fn (File) write_str #

fn (f File) write_str(params WriteOptions) !string

fn (File) typescript #

fn (f File) typescript(path string, params WriteOptions) !

struct Folder #

struct Folder {
pub:
	name    string
	files   []IFile
	folders []IFolder
	modules []Module
}

fn (Folder) write #

fn (f Folder) write(path string, options WriteOptions) !

struct Function #

struct Function {
pub:
	name     string @[omitempty]
	receiver Param  @[omitempty]
	is_pub   bool   @[omitempty]
	mod      string @[omitempty]
pub mut:
	summary     string  @[omitempty]
	description string  @[omitempty]
	params      []Param @[omitempty]
	body        string  @[omitempty]
	result      Param   @[omitempty]
	has_return  bool    @[omitempty]
}

fn (Function) generate_call #

fn (func Function) generate_call(params GenerateCallParams) !string

fn (Function) symbol #

fn (t Function) symbol() string

fn (Function) vgen #

fn (function Function) vgen(options WriteOptions) string

vgen_function generates a function statement for a function

struct GenerateCallParams #

@[params]
struct GenerateCallParams {
pub:
	receiver string
}

struct GenerateValueParams #

@[params]
struct GenerateValueParams {
}

struct GetStruct #

struct GetStruct {
pub:
	code []CodeItem
	mod  string
	name string
}

struct Import #

struct Import {
pub mut:
	mod   string
	types []string
}

fn (Import) add_types #

fn (mut i Import) add_types(types []string)

fn (Import) vgen #

fn (import_ Import) vgen() string

vgen_import generates an import statement for a given type

struct Integer #

struct Integer {
	bytes  u8
	signed bool = true
}

fn (Integer) symbol #

fn (t Integer) symbol() string

struct Interface #

struct Interface {
pub mut:
	name        string
	description string
	is_pub      bool
	embeds      []Interface @[str: skip]
	attrs       []Attribute
	fields      []StructField
	methods     []Function
}

fn (Interface) vgen #

fn (iface Interface) vgen() string

struct Map #

struct Map {
pub:
	typ Type
}

struct Module #

struct Module {
pub mut:
	name        string
	description string
	version     string = '0.0.1'
	license     string = 'apache2'
	vcs         string = 'git'
	files       []IFile
	folders     []IFolder
	modules     []Module
	in_src      bool // whether mod will be generated in src folder
}

fn (Module) write #

fn (mod Module) write(path string, options WriteOptions) !

fn (Module) write_str #

fn (mod Module) write_str() !string

struct Object #

struct Object {
pub:
	name string
}

struct Param #

struct Param {
pub mut:
	required    bool   @[omitempty]
	mutable     bool   @[omitempty]
	is_shared   bool   @[omitempty]
	is_optional bool   @[omitempty]
	is_result   bool   @[omitempty]
	description string @[omitempty]
	name        string @[omitempty]
	typ         Type   @[omitempty]
}

fn (Param) generate_value #

fn (param Param) generate_value() !string

fn (Param) typescript #

fn (p Param) typescript() string

fn (Param) vgen #

fn (param Param) vgen() string

struct Params #

@[params]
struct Params {
pub:
	v string
}

struct Result #

struct Result {
pub:
	typ Type
}

struct String #

struct String {}

struct Struct #

struct Struct {
pub mut:
	name        string
	description string
	mod         string
	is_pub      bool
	embeds      []Struct          @[str: skip]
	generics    map[string]string @[str: skip]
	attrs       []Attribute
	fields      []StructField
}

fn (Struct) vgen #

fn (struct_ Struct) vgen() string

vgen_function generates a function statement for a function

fn (Struct) get_type_symbol #

fn (structure Struct) get_type_symbol() string

fn (Struct) typescript #

fn (s Struct) typescript() string

struct StructField #

struct StructField {
	Param
pub mut:
	comments    []Comment
	attrs       []Attribute
	description string
	default     string
	is_pub      bool
	is_mut      bool
	is_ref      bool
	anon_struct Struct @[str: skip] // sometimes fields may hold anonymous structs
	structure   Struct @[str: skip]
}

fn (StructField) vgen #

fn (field StructField) vgen() string

struct Sumtype #

struct Sumtype {
pub:
	name        string
	description string
	types       []Type
}

struct VFile #

struct VFile {
pub mut:
	name    string
	mod     string
	imports []Import
	consts  []Const
	items   []CodeItem
	content string
}

fn (VFile) add_import #

fn (mut file VFile) add_import(import_ Import) !

fn (VFile) write #

fn (code VFile) write(path string, options WriteOptions) !

fn (VFile) write_str #

fn (code VFile) write_str(options WriteOptions) !string

fn (VFile) get_function #

fn (file VFile) get_function(name string) ?Function

fn (VFile) set_function #

fn (mut file VFile) set_function(function Function) !

fn (VFile) functions #

fn (file VFile) functions() []Function

fn (VFile) structs #

fn (file VFile) structs() []Struct

fn (VFile) enums #

fn (file VFile) enums() []Enum

fn (VFile) interfaces #

fn (file VFile) interfaces() []Interface

struct Void #

struct Void {}

fn (Void) symbol #

fn (t Void) symbol() string

struct WriteCode #

struct WriteCode {
	destination string
}

struct WriteOptions #

@[params]
struct WriteOptions {
pub:
	format    bool
	overwrite bool
	document  bool
	prefix    string
	compile   bool // whether to compile the written code
	test      bool // whether to test the written code
}