Skip to content

core.code #

Code Model

A set of models that represent code, such as structs and functions. The motivation behind this module is to provide a more generic, and lighter alternative to v.ast code models, that can be used for code parsing and code generation across multiple languages.

Using Codemodel

While the models in this module can be used in any domain, the models here are used extensively in the modules codeparser and codegen (under development). Below are examples on how codemodel can be used for parsing and generating code.## Code parsing with codemodel

As shown in the example below, the codemodels returned by the parser can be used to infer information about the code written

code := codeparser.parse('somedir') // code is a list of code models

num_functions := code.filter(it is Function).len
structs := code.filter(it is Struct)
println('This directory has ${num_functions} functions')
println('The directory has the structs: ${structs.map(it.name)}')

or can be used as intermediate structures to serialize code into some other format:

code_md := ''

// describes the struct in markdown format
for struct in structs {
    code_md +='# ${struct.name}'
    code_md +='Type: ${struct.typ.symbol()}'
    code_md += '## Fields:'
    for field in struct.fields {
        code_md +='- ${field.name}'
    }
}

The openrpc/docgen module demonstrates a good use case, where codemodels are serialized into JSON schema's, to generate an OpenRPC description document from a client in v.## V Language Utilities

The vlang_utils.v file provides a set of utility functions for working with V language files and code. These utilities are useful for:

  1. File Operations
  • list_v_files(dir string) ![]string - Lists all V files in a directory, excluding generated files
  • get_module_dir(mod string) string - Converts a V module path to a directory path
  1. Code Inspection and Analysis
  • get_function_from_file(file_path string, function_name string) !string - Extracts a function definition from a file
  • get_function_from_module(module_path string, function_name string) !string - Searches for a function across all files in a module
  • get_type_from_module(module_path string, type_name string) !string - Searches for a type definition across all files in a module
  1. V Language Tools
  • vtest(fullpath string) !string - Runs V tests on files or directories
  • vvet(fullpath string) !string - Runs V vet on files or directories

Example Usage

// Find and extract a function definition
function_def := code.get_function_from_module('/path/to/module', 'my_function') or {
    eprintln('Could not find function: ${err}')
    return
}
println(function_def)

// Run tests on a directory
test_results := code.vtest('/path/to/module') or {
    eprintln('Tests failed: ${err}')
    return
}
println(test_results)

These utilities are particularly useful when working with code generation, static analysis, or when building developer tools that need to inspect V code.

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., 'freeflowuniverse.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_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, and functions

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

fn vtest #

fn vtest(fullpath string) !string

vtest runs v test on the specified file or directory ARGS: fullpath string - path to the file or directory to test RETURNS: string - test results output, or error if test fails

fn vvet #

fn vvet(fullpath string) !string

vvet runs v vet on the specified file or directory ARGS: fullpath string - path to the file or directory to vet RETURNS: string - vet results output, or error if vet fails

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

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 {
	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 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

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
}