Fun API Documentation 0.42.1
The programming language that makes you have fun!
Loading...
Searching...
No Matches
vm.c File Reference

Core virtual machine implementation and opcode dispatch for Fun. More...

#include <math.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "iter.c"
#include "map.c"
#include "string.c"
#include "value.h"
#include "vm.h"
#include "extensions/curl.c"
#include "extensions/ini.c"
#include "extensions/json.c"
#include "extensions/openssl.c"
#include "extensions/pcre2.c"
#include "extensions/pcsc.c"
#include "extensions/sqlite.c"
#include "extensions/xml2.c"
#include "extensions/kcgi.c"
#include "extensions/redis.c"
#include "vm/os/thread_common.c"
#include <setjmp.h>
#include "vm/arithmetic/add.c"
#include "vm/arithmetic/div.c"
#include "vm/arithmetic/mul.c"
#include "vm/arithmetic/sub.c"
#include "vm/arrays/apop.c"
#include "vm/arrays/clear.c"
#include "vm/arrays/contains.c"
#include "vm/arrays/enumerate.c"
#include "vm/arrays/index_get.c"
#include "vm/arrays/index_of.c"
#include "vm/arrays/index_set.c"
#include "vm/arrays/insert.c"
#include "vm/arrays/join.c"
#include "vm/arrays/make_array.c"
#include "vm/arrays/push.c"
#include "vm/arrays/remove.c"
#include "vm/arrays/set.c"
#include "vm/arrays/slice.c"
#include "vm/arrays/zip.c"
#include "vm/bitwise/band.c"
#include "vm/bitwise/bnot.c"
#include "vm/bitwise/bor.c"
#include "vm/bitwise/bxor.c"
#include "vm/bitwise/rol.c"
#include "vm/bitwise/ror.c"
#include "vm/bitwise/shl.c"
#include "vm/bitwise/shr.c"
#include "vm/core/call.c"
#include "vm/core/dup.c"
#include "vm/core/exit.c"
#include "vm/core/halt.c"
#include "vm/core/jump.c"
#include "vm/core/jump_if_false.c"
#include "vm/core/load_const.c"
#include "vm/core/load_global.c"
#include "vm/core/load_local.c"
#include "vm/core/nop.c"
#include "vm/core/pop.c"
#include "vm/core/return.c"
#include "vm/core/store_global.c"
#include "vm/core/store_local.c"
#include "vm/core/swap.c"
#include "vm/core/throw.c"
#include "vm/core/try_pop.c"
#include "vm/core/try_push.c"
#include "vm/io/input_line.c"
#include "vm/io/read_file.c"
#include "vm/io/write_file.c"
#include "vm/logic/and.c"
#include "vm/logic/eq.c"
#include "vm/logic/gt.c"
#include "vm/logic/gte.c"
#include "vm/logic/lt.c"
#include "vm/logic/lte.c"
#include "vm/logic/neq.c"
#include "vm/logic/not.c"
#include "vm/logic/or.c"
#include "vm/maps/has_key.c"
#include "vm/maps/keys.c"
#include "vm/maps/make_map.c"
#include "vm/maps/values.c"
#include "vm/math/abs.c"
#include "vm/math/ceil.c"
#include "vm/math/clamp.c"
#include "vm/math/cos.c"
#include "vm/math/exp.c"
#include "vm/math/floor.c"
#include "vm/math/fmax.c"
#include "vm/math/fmin.c"
#include "vm/math/gcd.c"
#include "vm/math/isqrt.c"
#include "vm/math/lcm.c"
#include "vm/math/log.c"
#include "vm/math/log10.c"
#include "vm/math/max.c"
#include "vm/math/min.c"
#include "vm/math/mod.c"
#include "vm/math/pow.c"
#include "vm/math/random_int.c"
#include "vm/math/random_seed.c"
#include "vm/math/round.c"
#include "vm/math/sign.c"
#include "vm/math/sin.c"
#include "vm/math/sqrt.c"
#include "vm/math/tan.c"
#include "vm/math/trunc.c"
#include "vm/rust/get_sp.c"
#include "vm/rust/hello.c"
#include "vm/rust/hello_args.c"
#include "vm/rust/hello_args_return.c"
#include "vm/rust/set_exit.c"
#include "vm/os/clock_mono_ms.c"
#include "vm/os/date_format.c"
#include "vm/os/env.c"
#include "vm/os/env_all.c"
#include "vm/os/fun_version.c"
#include "vm/os/proc_run.c"
#include "vm/os/proc_system.c"
#include "vm/os/random_number.c"
#include "vm/os/serial_close.c"
#include "vm/os/serial_config.c"
#include "vm/os/serial_open.c"
#include "vm/os/serial_recv.c"
#include "vm/os/serial_send.c"
#include "vm/os/sleep_ms.c"
#include "vm/os/thread_join.c"
#include "vm/os/thread_spawn.c"
#include "vm/os/time_now_ms.c"
#include "vm/os/socket_close.c"
#include "vm/os/socket_recv.c"
#include "vm/os/socket_send.c"
#include "vm/os/socket_tcp_accept.c"
#include "vm/os/socket_tcp_connect.c"
#include "vm/os/socket_tcp_listen.c"
#include "vm/os/socket_unix_connect.c"
#include "vm/os/socket_unix_listen.c"
#include "vm/os/fd_set_nonblock.c"
#include "vm/os/fd_poll_read.c"
#include "vm/os/fd_poll_write.c"
#include "vm/pcsc/connect.c"
#include "vm/pcsc/disconnect.c"
#include "vm/pcsc/establish.c"
#include "vm/pcsc/list_readers.c"
#include "vm/pcsc/release.c"
#include "vm/pcsc/transmit.c"
#include "vm/json/from_file.c"
#include "vm/json/parse.c"
#include "vm/json/stringify.c"
#include "vm/json/to_file.c"
#include "vm/xml/name.c"
#include "vm/xml/parse.c"
#include "vm/xml/root.c"
#include "vm/xml/text.c"
#include "vm/ini/free.c"
#include "vm/ini/get_bool.c"
#include "vm/ini/get_double.c"
#include "vm/ini/get_int.c"
#include "vm/ini/get_string.c"
#include "vm/ini/load.c"
#include "vm/ini/save.c"
#include "vm/ini/set.c"
#include "vm/ini/unset.c"
#include "vm/curl/download.c"
#include "vm/curl/get.c"
#include "vm/curl/post.c"
#include "vm/openssl/md5.c"
#include "vm/openssl/ripemd160.c"
#include "vm/openssl/sha256.c"
#include "vm/openssl/sha512.c"
#include "vm/sqlite/close.c"
#include "vm/sqlite/exec.c"
#include "vm/sqlite/open.c"
#include "vm/sqlite/query.c"
#include "vm/pcre2/findall.c"
#include "vm/pcre2/match.c"
#include "vm/pcre2/test.c"
#include "vm/strings/find.c"
#include "vm/strings/regex_match.c"
#include "vm/strings/regex_replace.c"
#include "vm/strings/regex_search.c"
#include "vm/strings/split.c"
#include "vm/strings/substr.c"
#include "vm/cast.c"
#include "vm/echo.c"
#include "vm/len.c"
#include "vm/line.c"
#include "vm/os/list_dir.c"
#include "vm/print.c"
#include "vm/sclamp.c"
#include "vm/to_number.c"
#include "vm/to_string.c"
#include "vm/typeof.c"
#include "vm/uclamp.c"

Go to the source code of this file.

Macros

#define _POSIX_C_SOURCE   200809L
#define _XOPEN_SOURCE   700
#define fprintf   fun_vm_fprintf
#define exit(code)
#define FUN_VERSION   "0.0.0-dev"

Functions

char * preprocess_includes (const char *src)
 Public wrapper to preprocess includes without a current path.
int map_expanded_line_to_include_path (const char *path, int line, char *out_path, size_t out_path_cap, int *out_line)
 Map a line number in expanded source back to original include path/line.
static int fun_vm_vfprintf (FILE *stream, const char *fmt, va_list ap)
 fprintf-like wrapper that annotates stderr messages with VM source context.
static int fun_vm_fprintf (FILE *stream, const char *fmt,...)
 fprintf wrapper forwarding to fun_vm_vfprintf.
static void fun_vm_exit (int code)
 Replacement for exit() used within this translation unit.
static void push_value (VM *vm, Value v)
 Push a Value onto the VM operand stack.
static int vm_ip_to_line (const Bytecode *bc, int ip)
void vm_raise_error (VM *vm, const char *msg)
 Raise a runtime error inside the VM, honoring try/catch/finally.
static const char * value_type_name (ValueType t)
 Get a human-readable name for a ValueType.
void vm_clear_output (VM *vm)
 Clear the VM's buffered output values and partial flags.
void vm_free (VM *vm)
 Free resources owned directly by the VM structure.
static void vm_pop_frame (VM *vm)
 Pop the current call frame and free its local variables.
void vm_reset (VM *vm)
 Reset the VM to a clean state.
void vm_dump_globals (VM *vm)
 Print all non-nil global variables to stdout for debugging.
void vm_debug_reset (VM *vm)
 Reset debugger state: breakpoints and stepping controls.
int vm_debug_add_breakpoint (VM *vm, const char *file, int line)
 Add a source breakpoint.
int vm_debug_delete_breakpoint (VM *vm, int id)
 Delete a breakpoint by id.
void vm_debug_clear_breakpoints (VM *vm)
 Remove all breakpoints from the VM.
void vm_debug_list_breakpoints (VM *vm)
 Print active breakpoints to stdout.
void vm_debug_request_step (VM *vm)
 Request single-step execution (stop after next instruction).
void vm_debug_request_next (VM *vm)
 Request step-over (stop after next instruction in current frame).
void vm_debug_request_finish (VM *vm)
 Request finish (run until the current frame returns).
void vm_debug_request_continue (VM *vm)
 Resume normal execution (clear stepping state and stop flag).
static int vm_stack_count (const VM *vm)
static int vm_stack_space (const VM *vm)
static void vm_require_stack (VM *vm, int n)
static Value pop_value (VM *vm)
 Pop a Value from the VM operand stack.
int64_t vm_pop_i64 (VM *vm)
 Pop a numeric Value and convert it to a 64-bit integer (C ABI helper).
void vm_push_i64 (VM *vm, int64_t v)
 Push a 64-bit integer as a VM int Value (C ABI helper).
size_t vm_sizeof (void)
 Return sizeof(VM) for external FFI consumers.
size_t vm_value_sizeof (void)
 Return sizeof(Value) for external FFI consumers.
void * vm_as_mut_ptr (VM *vm)
 Cast the VM pointer to an opaque mutable void* (unsafe FFI helper).
size_t vm_offset_of_exit_code (void)
 Obtain offsetof(VM, exit_code) for FFI struct field access.
size_t vm_offset_of_sp (void)
 Obtain offsetof(VM, sp) for FFI struct field access.
size_t vm_offset_of_stack (void)
 Obtain offsetof(VM, stack) for FFI struct field access.
size_t vm_offset_of_globals (void)
 Obtain offsetof(VM, globals) for FFI struct field access.
static void frame_init (Frame *f)
 Initialize a call frame to a clean state.
void vm_init (VM *vm)
 Initialize a VM instance to its default state.
static void vm_push_frame (VM *vm, Bytecode *fn, int argc, Value *args)
 Push a new call frame for a function and transfer arguments.
void vm_print_output (VM *vm)
 Print the VM's buffered output values to stdout.
void vm_print_stacktrace (VM *vm)

Variables

static __thread VMg_active_vm = NULL
static __thread jmp_buf g_vm_err_jmp

Detailed Description

Core virtual machine implementation and opcode dispatch for Fun.

Defines the VM state, stack helpers, debugger/stepping support, built-in opcode handlers (included as amalgamated C files), platform I/O helpers, and the main interpreter loop that executes bytecode produced by the Fun compiler. This file is the central runtime of the language.

Definition in file vm.c.

Macro Definition Documentation

◆ _POSIX_C_SOURCE

#define _POSIX_C_SOURCE   200809L

Definition at line 24 of file vm.c.

◆ _XOPEN_SOURCE

#define _XOPEN_SOURCE   700

Definition at line 27 of file vm.c.

◆ exit

#define exit ( code)
Value:
static void fun_vm_exit(int code)
Replacement for exit() used within this translation unit.
Definition vm.c:210

Definition at line 224 of file vm.c.

◆ fprintf

#define fprintf   fun_vm_fprintf

Definition at line 194 of file vm.c.

◆ FUN_VERSION

#define FUN_VERSION   "0.0.0-dev"

Function Documentation

◆ frame_init()

void frame_init ( Frame * f)
static

Initialize a call frame to a clean state.

Sets function pointer and instruction pointer, zeroes locals to nil and resets the try-stack pointer.

Parameters
fFrame to initialize.

Definition at line 729 of file vm.c.

◆ fun_vm_exit()

void fun_vm_exit ( int code)
static

Replacement for exit() used within this translation unit.

If REPL-on-error is enabled for the active VM, this performs a longjmp back to vm_run so the REPL can be entered with the current VM state intact. Otherwise, terminates the process immediately using _Exit/_exit.

Parameters
codeExit status code (non-zero values indicate error conditions).

Definition at line 210 of file vm.c.

◆ fun_vm_fprintf()

int fun_vm_fprintf ( FILE * stream,
const char * fmt,
... )
static

fprintf wrapper forwarding to fun_vm_vfprintf.

Convenience wrapper that collects varargs and calls fun_vm_vfprintf so that VM-aware diagnostics are consistently applied in this translation unit.

Parameters
streamOutput stream.
fmtprintf-style format string.
Returns
Number of characters written.

Definition at line 184 of file vm.c.

◆ fun_vm_vfprintf()

int fun_vm_vfprintf ( FILE * stream,
const char * fmt,
va_list ap )
static

fprintf-like wrapper that annotates stderr messages with VM source context.

When writing to stderr and a VM is active, this function appends file name, line number, function name, opcode and instruction pointer information to the message. It attempts to map expanded preprocessed line numbers back to the original included file for clearer diagnostics.

Parameters
streamOutput stream (typically stderr or stdout).
fmtprintf-style format string.
apVariable argument list corresponding to fmt.
Returns
Number of characters written, as returned by vfprintf.

Definition at line 105 of file vm.c.

◆ map_expanded_line_to_include_path()

int map_expanded_line_to_include_path ( const char * path,
int line,
char * out_path,
size_t out_path_cap,
int * out_line )
extern

Map a line number in expanded source back to original include path/line.

Scans the expanded text for the nearest preceding __include_begin__ marker and computes the corresponding inner line number.

Parameters
pathPath to the original top-level file that was expanded.
line1-based line number in the expanded text.
out_pathOutput buffer for the resolved file path.
out_path_capCapacity of out_path.
out_lineReceives 1-based line number within resolved file.
Returns
1 on success, 0 on failure.

Definition at line 996 of file parser_utils.c.

◆ pop_value()

Value pop_value ( VM * vm)
static

Pop a Value from the VM operand stack.

Caller takes ownership of the returned Value. Aborts execution on underflow.

Parameters
vmVM instance.
Returns
The top Value from the stack.

Definition at line 611 of file vm.c.

◆ preprocess_includes()

char * preprocess_includes ( const char * src)
extern

Public wrapper to preprocess includes without a current path.

Definition at line 965 of file parser_utils.c.

◆ push_value()

void push_value ( VM * vm,
Value v )
static

Push a Value onto the VM operand stack.

Takes ownership of the provided Value. Aborts execution on overflow.

Parameters
vmVM instance.
vValue to push (ownership transferred).

Definition at line 595 of file vm.c.

◆ value_type_name()

const char * value_type_name ( ValueType t)
static

Get a human-readable name for a ValueType.

Parameters
tThe value type enum.
Returns
Constant string naming the type (e.g., "int", "string").

Definition at line 328 of file vm.c.

◆ vm_as_mut_ptr()

void * vm_as_mut_ptr ( VM * vm)

Cast the VM pointer to an opaque mutable void* (unsafe FFI helper).

Get a mutable byte pointer to the VM object. Extremely unsafe; for low-level FFI use only.

Parameters
vmVM instance pointer.
Returns
The same pointer reinterpreted as void*.

Definition at line 681 of file vm.c.

◆ vm_clear_output()

void vm_clear_output ( VM * vm)

Clear the VM's buffered output values and partial flags.

Clear the buffered output captured by the VM.

Frees any dynamic storage held by buffered output Values and resets the output counters and partial line indicators.

Parameters
vmVM instance whose output buffer should be cleared.

Definition at line 359 of file vm.c.

◆ vm_debug_add_breakpoint()

int vm_debug_add_breakpoint ( VM * vm,
const char * file,
int line )

Add a source breakpoint.

Parameters
vmVM instance.
fileSource file path (must not be NULL).
lineOne-based source line number (> 0).
Returns
Breakpoint id (>=0) on success, -1 on failure (invalid args or full).

Definition at line 468 of file vm.c.

◆ vm_debug_clear_breakpoints()

void vm_debug_clear_breakpoints ( VM * vm)

Remove all breakpoints from the VM.

Parameters
vmVM instance.

Definition at line 507 of file vm.c.

◆ vm_debug_delete_breakpoint()

int vm_debug_delete_breakpoint ( VM * vm,
int id )

Delete a breakpoint by id.

Compacts the internal breakpoint list to keep ids dense.

Parameters
vmVM instance.
idBreakpoint identifier previously returned by add.
Returns
1 if deleted, 0 if id was invalid.

Definition at line 487 of file vm.c.

◆ vm_debug_list_breakpoints()

void vm_debug_list_breakpoints ( VM * vm)

Print active breakpoints to stdout.

Parameters
vmVM instance.

Definition at line 516 of file vm.c.

◆ vm_debug_request_continue()

void vm_debug_request_continue ( VM * vm)

Resume normal execution (clear stepping state and stop flag).

Parameters
vmVM instance.

Definition at line 566 of file vm.c.

◆ vm_debug_request_finish()

void vm_debug_request_finish ( VM * vm)

Request finish (run until the current frame returns).

Parameters
vmVM instance.

Definition at line 555 of file vm.c.

◆ vm_debug_request_next()

void vm_debug_request_next ( VM * vm)

Request step-over (stop after next instruction in current frame).

Parameters
vmVM instance.

Definition at line 543 of file vm.c.

◆ vm_debug_request_step()

void vm_debug_request_step ( VM * vm)

Request single-step execution (stop after next instruction).

Parameters
vmVM instance.

Definition at line 532 of file vm.c.

◆ vm_debug_reset()

void vm_debug_reset ( VM * vm)

Reset debugger state: breakpoints and stepping controls.

Clears all breakpoints, disables stepping modes, and resets counters.

Parameters
vmVM instance with debugger state to reset.

Definition at line 444 of file vm.c.

◆ vm_dump_globals()

void vm_dump_globals ( VM * vm)

Print all non-nil global variables to stdout for debugging.

Print non-nil globals (index and value) to stdout.

Parameters
vmVM whose globals should be dumped.

Definition at line 423 of file vm.c.

◆ vm_free()

void vm_free ( VM * vm)

Free resources owned directly by the VM structure.

Free all resources owned by the VM (globals, frames, output buffers). The VM object itself is not freed when allocated on the stack.

Currently a no-op because the VM does not allocate persistent internal resources outside frames, globals and outputs, which are managed elsewhere.

Parameters
vmVM instance to free resources for.

Definition at line 377 of file vm.c.

◆ vm_init()

void vm_init ( VM * vm)

Initialize a VM instance to its default state.

Initialize a VM instance to zero/initial state.

Resets stack/frame pointers, output buffers, instruction counters, debugger state and globals. Does not allocate memory.

Parameters
vmVM instance to initialize.

Definition at line 745 of file vm.c.

◆ vm_ip_to_line()

int vm_ip_to_line ( const Bytecode * bc,
int ip )
static

Definition at line 843 of file vm.c.

◆ vm_offset_of_exit_code()

size_t vm_offset_of_exit_code ( void )

Obtain offsetof(VM, exit_code) for FFI struct field access.

Returns
Byte offset of the exit_code field within VM.

Definition at line 690 of file vm.c.

◆ vm_offset_of_globals()

size_t vm_offset_of_globals ( void )

Obtain offsetof(VM, globals) for FFI struct field access.

Returns
Byte offset of the globals field within VM.

Definition at line 717 of file vm.c.

◆ vm_offset_of_sp()

size_t vm_offset_of_sp ( void )

Obtain offsetof(VM, sp) for FFI struct field access.

Returns
Byte offset of the sp field within VM.

Definition at line 699 of file vm.c.

◆ vm_offset_of_stack()

size_t vm_offset_of_stack ( void )

Obtain offsetof(VM, stack) for FFI struct field access.

Returns
Byte offset of the stack field within VM.

Definition at line 708 of file vm.c.

◆ vm_pop_frame()

void vm_pop_frame ( VM * vm)
static

Pop the current call frame and free its local variables.

Aborts if there is no active frame.

Parameters
vmVM instance.

Definition at line 812 of file vm.c.

◆ vm_pop_i64()

int64_t vm_pop_i64 ( VM * vm)

Pop a numeric Value and convert it to a 64-bit integer (C ABI helper).

Accepts int or float Values on the stack. Other types raise a runtime type error. The popped Value is freed.

Parameters
vmVM instance.
Returns
The numeric value converted to int64_t.

Definition at line 629 of file vm.c.

◆ vm_print_output()

void vm_print_output ( VM * vm)

Print the VM's buffered output values to stdout.

Print buffered output entries to stdout (debug aid).

Emits a newline after each value unless the corresponding partial flag is set.

Parameters
vmVM instance whose output should be printed.

Definition at line 832 of file vm.c.

◆ vm_print_stacktrace()

void vm_print_stacktrace ( VM * vm)

Print a human-readable VM stack trace to stderr (top frame first).

Definition at line 855 of file vm.c.

◆ vm_push_frame()

void vm_push_frame ( VM * vm,
Bytecode * fn,
int argc,
Value * args )
static

Push a new call frame for a function and transfer arguments.

The first argc Values from args are moved (ownership transfer) into the new frame's local slots starting at index 0. Aborts on frame stack overflow.

Parameters
vmVM instance.
fnFunction bytecode to execute in the new frame.
argcNumber of arguments provided.
argsArray of argument Values (may be NULL if argc == 0).

Definition at line 789 of file vm.c.

◆ vm_push_i64()

void vm_push_i64 ( VM * vm,
int64_t v )

Push a 64-bit integer as a VM int Value (C ABI helper).

Parameters
vmVM instance.
vInteger value to push.

Definition at line 652 of file vm.c.

◆ vm_raise_error()

void vm_raise_error ( VM * vm,
const char * msg )

Raise a runtime error inside the VM, honoring try/catch/finally.

Raise a runtime error honoring active try/catch/finally handlers. If a try handler is active in the current frame, control jumps to it with an error string pushed on the stack. Otherwise, prints the error (with location) and terminates execution.

If the current frame has a pending try handler, control is transferred to that handler and the error message is pushed onto the stack for the catch clause. If no handler exists, the error is printed and the VM is stopped.

Parameters
vmPointer to the VM instance.
msgHuman-readable error message (may be NULL).

Definition at line 244 of file vm.c.

◆ vm_require_stack()

void vm_require_stack ( VM * vm,
int n )
inlinestatic

Ensure at least n values are available to pop; aborts on underflow.

Definition at line 579 of file vm.c.

◆ vm_reset()

void vm_reset ( VM * vm)

Reset the VM to a clean state.

Reset VM to initial state, freeing globals/locals/output. The VM object remains valid for reuse after this call.

Pops all frames (releasing local variables), clears the operand stack and globals, resets the output buffer and debugger state, and zeros the exit code.

Parameters
vmVM instance to reset.

Definition at line 392 of file vm.c.

◆ vm_sizeof()

size_t vm_sizeof ( void )

Return sizeof(VM) for external FFI consumers.

Returns
Size of the VM struct in bytes.

Definition at line 662 of file vm.c.

◆ vm_stack_count()

int vm_stack_count ( const VM * vm)
inlinestatic

Return current number of values on the stack.

Definition at line 573 of file vm.c.

◆ vm_stack_space()

int vm_stack_space ( const VM * vm)
inlinestatic

Return available space left on the stack (in Values).

Definition at line 576 of file vm.c.

◆ vm_value_sizeof()

size_t vm_value_sizeof ( void )

Return sizeof(Value) for external FFI consumers.

Returns
Size of the Value struct in bytes.

Definition at line 671 of file vm.c.

Variable Documentation

◆ g_active_vm

__thread VM* g_active_vm = NULL
static

Definition at line 89 of file vm.c.

◆ g_vm_err_jmp

__thread jmp_buf g_vm_err_jmp
static

Definition at line 199 of file vm.c.