diff options
| author | elioat <{ID}+{username}@users.noreply.github.com> | 2025-07-30 18:24:04 -0400 |
|---|---|---|
| committer | elioat <{ID}+{username}@users.noreply.github.com> | 2025-07-30 18:24:04 -0400 |
| commit | d03a2d3da99620a97ebf4961f73eac3aef2af9d6 (patch) | |
| tree | ac9d008e0659dad1af008c87ec96431fb7e7bf95 /awk/scheme | |
| parent | 6aaa85444197820db928f169f07f2359c0c6126e (diff) | |
| download | tour-d03a2d3da99620a97ebf4961f73eac3aef2af9d6.tar.gz | |
*
Diffstat (limited to 'awk/scheme')
| -rwxr-xr-x | awk/scheme/scheme/bin/compiler.awk | 249 | ||||
| -rwxr-xr-x | awk/scheme/scheme/bin/repl | 36 | ||||
| -rwxr-xr-x | awk/scheme/scheme/bin/vm.awk | 240 | ||||
| -rwxr-xr-x | awk/scheme/scheme/scratch/forth/forth.awk | 36 |
4 files changed, 196 insertions, 365 deletions
diff --git a/awk/scheme/scheme/bin/compiler.awk b/awk/scheme/scheme/bin/compiler.awk index dec4c22..11001ab 100755 --- a/awk/scheme/scheme/bin/compiler.awk +++ b/awk/scheme/scheme/bin/compiler.awk @@ -1,25 +1,15 @@ #!/usr/bin/awk -f # Scheme-to-VM Compiler -# +# # This compiler translates Scheme expressions into stack-based VM instructions. -# The design prioritizes simplicity and correctness, making it suitable for -# educational purposes and small-scale applications. # -# Architecture Overview: # - Lexical analysis tokenizes input into meaningful units # - Recursive descent parsing builds expression trees -# - Code generation produces VM instructions for execution +# - Code generation produces VM instructions # - Special form handling for control flow and function definitions # - Standard library integration for extended functionality # -# Key Design Decisions: -# - Recursive descent parsing for simplicity and predictable behavior -# - Stack-based instruction generation for efficient VM execution -# - Environment-based variable binding for lexical scoping -# - Special form recognition for control flow constructs -# - Standard library function integration for extended functionality -# - Stack clearing between expressions to prevent argument pollution BEGIN { @@ -35,10 +25,9 @@ BEGIN { input_buffer = "" # Buffer for input text being tokenized next_label = 0 # Counter for generating unique labels program = "" # Accumulates the full program text - + # Debug mode configuration - # AWK FEATURE: ENVIRON is a built-in array containing environment variables - # Unlike JS process.env, this is automatically available in awk + # NOTE: ENVIRON is a built-in array containing environment variables DEBUG = (ENVIRON["DEBUG"] == "1") ? 1 : 0 error_flag = 0 # Set to 1 if any error occurs DEBUG_SEXPR = (ENVIRON["DEBUG_SEXPR"] == "1") ? 1 : 0 @@ -46,26 +35,23 @@ BEGIN { # Debug logging helper function function debug(msg) { - # AWK FEATURE: printf with > "/dev/stderr" redirects output to stderr - # Unlike console.error() in JS, this is how awk handles stderr output + # printf with > "/dev/stderr" redirects output to stderr, like console.error() in JS if (DEBUG) printf("[DEBUG] %s\n", msg) > "/dev/stderr" } -# AWK FEATURE: Each line of input is automatically processed by this block +# NOTE: Each line of input is automatically processed by this block # This is awk's main input processing loop - every line from stdin/files goes here -# In JS, you'd need to explicitly read lines from a stream { if (DEBUG_SEXPR) print "[DEBUG_SEXPR] Reading line: [" $0 "]" > "/dev/stderr" if (program != "") program = program "\n" program = program $0 # $0 is the current line being processed } -# AWK FEATURE: END block runs after all input has been processed -# This is like a "finally" block that always executes after reading all input +# NOTE: END block runs after all input has been processed like a "finally" block that always executes after reading all input END { debug("Raw program:\n" program) if (program == "") exit - + # Parse and compile each expression in the program split_expressions(program) debug("END block: error_flag=" error_flag) @@ -76,14 +62,9 @@ END { } # Splits input into individual Scheme expressions -# This function handles the complexity of Scheme syntax including: -# - Nested parentheses and proper expression boundaries -# - Comments that can span multiple lines -# - String literals that may contain parentheses -# - Whitespace normalization for consistent parsing -# -# The function processes the entire program text and identifies complete -# expressions that can be compiled independently +# This function handles the destructures s-expressions. +# It is inteded to process the entire program text and +# identify complete expressions that can be compiled independently function split_expressions(prog, current, paren_count, i, c, expr, cleaned, lines, n, line, in_string, out, j) { current = "" paren_count = 0 @@ -202,8 +183,7 @@ function split_expressions(prog, current, paren_count, i, c, expr, cleaned, line } # Lexer helper functions for character classification -# AWK FEATURE: String comparison with >= and <= works lexicographically -# Unlike JS where you need to convert to numbers, awk can compare strings directly +# NOTE: String comparison with >= and <= works lexicographically, and awk can compare strings directly function is_digit(c) { return c >= "0" && c <= "9" } function is_whitespace(c) { return c == " " || c == "\t" || c == "\n" } @@ -212,27 +192,25 @@ function is_whitespace(c) { return c == " " || c == "\t" || c == "\n" } function next_token() { # Initialize input buffer on first call if (input_buffer == "") input_buffer = program - + # Skip whitespace between tokens - # AWK FEATURE: length(string) returns the length of a string - # Unlike JS string.length, this is a function call, not a property while (length(input_buffer) > 0 && is_whitespace(substr(input_buffer, 1, 1))) input_buffer = substr(input_buffer, 2) - + if (length(input_buffer) == 0) return "EOF" - + # Handle parentheses as single-character tokens c = substr(input_buffer, 1, 1) if (c == "(" || c == ")") { input_buffer = substr(input_buffer, 2) return c } - + # Handle string literals (double quotes) if (c == "\"") { str = "" input_buffer = substr(input_buffer, 2) # Skip opening quote - + while (length(input_buffer) > 0) { c = substr(input_buffer, 1, 1) if (c == "\"") { @@ -258,15 +236,12 @@ function next_token() { } return "\"" str "\"" # Return with quotes for identification } - - # Handle numbers (including negative numbers) - # AWK FEATURE: substr(string, start, length) extracts substring - # Unlike JS string.slice(), this is 1-indexed and requires explicit length - # AWK FEATURE: length(string) returns the length of a string - # Unlike JS string.length, this is a function call, not a property + + # Handle numbers (including negative numbers! (that took a stupid long time)) + # NOTE: substr(string, start, length) extracts substring and is 1-indexed! if (is_digit(c) || c == "-" && length(input_buffer) > 1 && is_digit(substr(input_buffer, 2, 1))) { num = "" - # AWK FEATURE: length(string) returns the length of a string + # NOTE: length(string) returns the length of a string # Unlike JS string.length, this is a function call, not a property while (length(input_buffer) > 0) { c = substr(input_buffer, 1, 1) @@ -276,11 +251,9 @@ function next_token() { } return num } - + # Handle symbols (identifiers and operators) sym = "" - # AWK FEATURE: length(string) returns the length of a string - # Unlike JS string.length, this is a function call, not a property while (length(input_buffer) > 0) { c = substr(input_buffer, 1, 1) if (is_whitespace(c) || c == "(" || c == ")") break @@ -290,8 +263,7 @@ function next_token() { return sym } -# Recursive descent parser for Scheme expressions -# This parser implements a simple but complete parsing strategy that: +# This parser implements a simple parsing strategy that: # - Handles nested expressions through recursion # - Distinguishes between atoms and list expressions # - Provides clear error messages for malformed input @@ -301,52 +273,40 @@ function next_token() { function parse_expr(token, result) { token = next_token() if (token == "EOF") return "" - + if (token == "(") { result = parse_list() debug("Parsed list: " result) return result } - + # Handle string literals if (substr(token, 1, 1) == "\"") { debug("Parsed string: " token) return token } - + debug("Parsed token: " token) return token } -# Parses a list expression (anything in parentheses) -# This function handles the complexity of nested list structures by: -# - Recursively parsing each element in the list -# - Maintaining proper nesting levels -# - Providing clear error messages for unmatched parentheses -# - Supporting empty lists and nested expressions function parse_list(result, expr) { result = "" - + while (1) { expr = parse_expr() if (expr == "" || expr == ")") break - + if (result != "") result = result " " result = result expr } - + if (expr == "") error("Unexpected end of input in list") return "(" result ")" } # Splits an expression into operator and arguments -# This function handles the complexity of Scheme function calls by: -# - Correctly identifying the operator (first element) -# - Preserving nested expressions as single arguments -# - Handling whitespace and parentheses properly -# - Supporting both simple calls and complex nested expressions -# -# Handles nested expressions correctly by tracking parenthesis nesting +# Handles nested expressions by tracking parenthesis nesting function split_expr(expr, i, len, c, op, args, paren_count, j, c2) { len = length(expr) paren_count = 0 @@ -389,27 +349,25 @@ function split_expr(expr, i, len, c, op, args, paren_count, j, c2) { # Splits argument list handling nested parentheses and string literals function split_args(args, arg_array, len, i, c, current, paren_count, arg_count, in_string) { - # AWK FEATURE: length(string) returns the length of a string - # Unlike JS string.length, this is a function call, not a property len = length(args) current = "" paren_count = 0 arg_count = 0 in_string = 0 - + for (i = 1; i <= len; i++) { c = substr(args, i, 1) - + # Handle string literals if (c == "\"" && !in_string) { in_string = 1 } else if (c == "\"" && in_string) { in_string = 0 } - + if (c == "(" && !in_string) paren_count++ if (c == ")" && !in_string) paren_count-- - + if (c == " " && paren_count == 0 && !in_string && current != "") { arg_array[++arg_count] = current current = "" @@ -417,11 +375,11 @@ function split_args(args, arg_array, len, i, c, current, paren_count, arg_count, current = current c } } - + if (current != "") { arg_array[++arg_count] = current } - + return arg_count } @@ -443,11 +401,11 @@ function compile_string(str) { print "PUSH_CONST STR:" content } -# Code generation for primitive operations (+, -, *, cons, etc) +# Code generation for primitive operations (+, -, *, cons, and what not) function compile_primitive_call(op, args, arg_array, nargs, i) { debug("Primitive call: op=" op " args=" args) nargs = split_args(args, arg_array) - + if (op ~ /^\(lambda /) { for (i = 1; i <= nargs; i++) { compile_expr(arg_array[i]) @@ -733,14 +691,12 @@ function split_bindings(bindings, binding_array, count, current, paren_count, i, count = 0 current = "" paren_count = 0 - + debug("split_bindings: parsing [" bindings "]") - - # AWK FEATURE: length(string) returns the length of a string - # Unlike JS string.length, this is a function call, not a property + for (i = 1; i <= length(bindings); i++) { c = substr(bindings, i, 1) - + # Track nested parentheses if (c == "(") { paren_count++ @@ -759,18 +715,18 @@ function split_bindings(bindings, binding_array, count, current, paren_count, i, continue } } - + # Add character if we're inside a binding if (paren_count > 0) { current = current c } } - + debug("split_bindings: found " count " bindings") return count } -# Compiles let expressions (local variable bindings) +# Compiles let expressions function compile_let(args, bindings, body, binding_array, nbindings, i, var, val, binding_parts, sexprs, nsexprs, j, expr, last_type) { if (substr(args, 1, 1) != "(") error("Malformed let expression") paren_count = 1 @@ -908,7 +864,7 @@ function compile_define(args, name, params, body, param_array, nparams, i, paren } } -# Compiles lambda expressions (anonymous functions) +# Compiles lambda expressions function compile_lambda(args, params, body, param_array, nparams, i, lambda_name, expr, op, rest, sexprs, nsexprs, j, is_define, last_body_idx) { if (DEBUG_SEXPR) print "[DEBUG_SEXPR] compile_lambda called" > "/dev/stderr" lambda_name = "__lambda_" next_label++ @@ -990,46 +946,46 @@ function compile_lambda(args, params, body, param_array, nparams, i, lambda_name print "RETURN" } -# Compile if expression: (if condition then-expr else-expr) +# Compile if expression, if condition then-expr else-expr function compile_if(args, split_result, condition, then_expr, else_expr, else_label, end_label) { debug("Compiling if expression: " args) - + # Split into condition, then-expr, and else-expr split_result = split_expr(args) condition = substr(split_result, 1, index(split_result, SUBSEP) - 1) - + # Get the rest and split again for then/else args = substr(split_result, index(split_result, SUBSEP) + 1) split_result = split_expr(args) then_expr = substr(split_result, 1, index(split_result, SUBSEP) - 1) else_expr = substr(split_result, index(split_result, SUBSEP) + 1) - + debug("If condition: " condition) debug("If then: " then_expr) debug("If else: " else_expr) - + # Generate unique labels else_label = "else_" next_label++ end_label = "endif_" next_label++ - + # Compile condition compile_expr(condition) - + # Jump to else if condition is false print "JUMP_IF_FALSE " else_label - + # Compile then expression compile_expr(then_expr) - + # Jump to end print "JUMP " end_label - + # Else label print "LABEL " else_label - + # Compile else expression compile_expr(else_expr) - + # End label print "LABEL " end_label } @@ -1037,11 +993,11 @@ function compile_if(args, split_result, condition, then_expr, else_expr, else # Compile cond expression: (cond (test1 expr1) (test2 expr2) ... (else expr)) function compile_cond(args, test, expr, test_label, end_label) { debug("Compiling cond expression: " args) - + # Parse the first clause: (test expr) # Remove outer parentheses args = substr(args, 2, length(args) - 2) - + # Find the first space after the test paren_count = 0 for (i = 1; i <= length(args); i++) { @@ -1058,33 +1014,33 @@ function compile_cond(args, test, expr, test_label, end_label) { break } } - + if (!test) { test = args expr = "" } - + debug("Cond test: " test " expr: " expr) - + # Generate labels test_label = "cond_test_" next_label++ end_label = "cond_end_" next_label++ - + # Compile test compile_expr(test) - + # Jump to else if test is false print "JUMP_IF_FALSE " test_label - + # Compile expression compile_expr(expr) - + # Jump to end print "JUMP " end_label - + # Else label print "LABEL " test_label - + # End label print "LABEL " end_label } @@ -1092,55 +1048,55 @@ function compile_cond(args, test, expr, test_label, end_label) { # Compile and expression: (and expr1 expr2 ...) function compile_and(args, expressions, nexprs, i, expr, short_circuit_label, end_label, split_result, remaining_args) { debug("Compiling and expression: " args) - + # Parse expressions properly using split_expr expressions[1] = "" nexprs = 0 remaining_args = args - + while (remaining_args != "") { nexprs++ split_result = split_expr(remaining_args) expressions[nexprs] = substr(split_result, 1, index(split_result, SUBSEP) - 1) remaining_args = substr(split_result, index(split_result, SUBSEP) + 1) } - + if (nexprs == 0) { # Empty and returns true print "PUSH_CONST B:1" return } - + if (nexprs == 1) { # Single expression compile_expr(expressions[1]) return } - + # Generate labels short_circuit_label = "and_short_" next_label++ end_label = "and_end_" next_label++ - + for (i = 1; i <= nexprs; i++) { expr = expressions[i] debug("And expression " i ": " expr) - + # Compile expression compile_expr(expr) - + # If not the last expression, check for short-circuit if (i < nexprs) { print "JUMP_IF_FALSE " short_circuit_label } } - + # Jump to end print "JUMP " end_label - + # Short-circuit label (result is false) print "LABEL " short_circuit_label print "PUSH_CONST B:0" - + # End label print "LABEL " end_label } @@ -1148,55 +1104,55 @@ function compile_and(args, expressions, nexprs, i, expr, short_circuit_label, # Compile or expression: (or expr1 expr2 ...) function compile_or(args, expressions, nexprs, i, expr, short_circuit_label, end_label, split_result, remaining_args) { debug("Compiling or expression: " args) - - # Parse expressions properly using split_expr + + # Parse expressions using split_expr expressions[1] = "" nexprs = 0 remaining_args = args - + while (remaining_args != "") { nexprs++ split_result = split_expr(remaining_args) expressions[nexprs] = substr(split_result, 1, index(split_result, SUBSEP) - 1) remaining_args = substr(split_result, index(split_result, SUBSEP) + 1) } - + if (nexprs == 0) { # Empty or returns false print "PUSH_CONST B:0" return } - + if (nexprs == 1) { # Single expression compile_expr(expressions[1]) return } - + # Generate labels short_circuit_label = "or_short_" next_label++ end_label = "or_end_" next_label++ - + for (i = 1; i <= nexprs; i++) { expr = expressions[i] debug("Or expression " i ": " expr) - + # Compile expression compile_expr(expr) - + # If not the last expression, check for short-circuit if (i < nexprs) { print "JUMP_IF_TRUE " short_circuit_label } } - + # Jump to end print "JUMP " end_label - + # Short-circuit label (result is true) print "LABEL " short_circuit_label print "PUSH_CONST B:1" - + # End label print "LABEL " end_label } @@ -1204,10 +1160,10 @@ function compile_or(args, expressions, nexprs, i, expr, short_circuit_label, # Compile not expression: (not expr) function compile_not(args, expr) { debug("Compiling not expression: " args) - + # Compile the expression compile_expr(args) - + # Negate the result print "NOT" } @@ -1216,37 +1172,37 @@ function compile_not(args, expr) { function compile_expr(expr, split_result, op, args, result_type) { if (DEBUG_SEXPR) print "[DEBUG_SEXPR] compile_expr called with expr: [" expr "]" > "/dev/stderr" debug("Compiling expression: " expr) - + # Handle empty expressions if (expr == "") { debug("Skipping empty expression") return "value" } - + # Handle comment lines if (expr ~ /^[ \t]*;;/ || expr ~ /^[ \t]*;/) { debug("Skipping comment line: [" expr "]") return "value" } - + # Handle string literals if (substr(expr, 1, 1) == "\"") { compile_string(expr) return "value" } - + # Handle numeric literals if (expr ~ /^-?[0-9]+$/) { compile_number(expr) return "value" } - + # Handle nil constant if (expr == "nil") { print "PUSH_CONST NIL:" return "value" } - + # Handle boolean literals if (expr == "#t") { print "PUSH_CONST B:1" @@ -1256,13 +1212,13 @@ function compile_expr(expr, split_result, op, args, result_type) { print "PUSH_CONST B:0" return "value" } - + # Handle variable lookup (only if not a parenthesized expression) if (expr ~ /^[a-zA-Z_][a-zA-Z0-9_?-]*$/) { print "LOOKUP " expr return "value" } - + # Handle compound expressions (lists) if (substr(expr, 1, 1) == "(") { expr = substr(expr, 2, length(expr) - 2) @@ -1300,7 +1256,7 @@ function compile_expr(expr, split_result, op, args, result_type) { return compile_primitive_call(op, args) } } - + error("Unknown expression type: " expr) return "value" } @@ -1366,7 +1322,6 @@ function split_sexpressions(str, sexpr_array, i, c, in_string, paren_count, curr return n } -# Helper: Extract first symbol from a compound expression string function extract_first_symbol(expr_str, op) { # Assumes expr_str starts with '(' op = "" diff --git a/awk/scheme/scheme/bin/repl b/awk/scheme/scheme/bin/repl index 0f1a049..2e3ee10 100755 --- a/awk/scheme/scheme/bin/repl +++ b/awk/scheme/scheme/bin/repl @@ -1,21 +1,16 @@ #!/bin/bash # Enable debug tracing -# BASH FEATURE: ${VAR:-default} provides a default value if VAR is unset or empty -# Unlike JS where you'd use VAR || default, this only uses default if VAR is literally unset DEBUG=${DEBUG:-0} debug() { if [ "$DEBUG" = "1" ]; then - # BASH FEATURE: >&2 redirects output to stderr (file descriptor 2) - # Unlike JS console.error(), this explicitly redirects to stderr + # >&2 redirects output to stderr (file descriptor 2) echo "[DEBUG] $*" >&2 fi } # Find the directory containing this script and the components -# BASH FEATURE: ${BASH_SOURCE[0]} is the path to the current script -# Unlike JS __filename, this works even when the script is sourced DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" COMPILER="$DIR/compiler.awk" VM="$DIR/vm.awk" @@ -61,21 +56,20 @@ DEBUG_FILE="$TMPDIR/debug.out" # : > "/tmp/scheme_vm.env" # fi -# Function to handle evaluation evaluate_expression() { local input="$1" local result - + # Skip empty lines if [ -z "$input" ]; then return 0 fi - + debug "Evaluating expression: $input" echo "$input" > "$INPUT_FILE" debug "Input file contents:" cat "$INPUT_FILE" >&2 - + # Show compilation output even if it fails debug "Running compiler..." if awk -f "$COMPILER" "$INPUT_FILE" > "$ASM_FILE" 2> "$DEBUG_FILE"; then @@ -83,11 +77,9 @@ evaluate_expression() { cat "$DEBUG_FILE" >&2 debug "Generated assembly:" cat "$ASM_FILE" >&2 - + debug "Running VM..." # Use persistent VM state and pass debug flag - # BASH FEATURE: -v var=value passes variables to awk - # Unlike JS where you'd use process.env, this sets awk variables directly result=$(awk -v PERSIST=1 -v DEBUG="$DEBUG" -f "$VM" "$ASM_FILE" 2>&1) vm_exit_code=$? debug "VM output: $result" @@ -118,8 +110,6 @@ if [ "$#" -gt 0 ]; then debug "File content: $file_content" # TODO: Workaround for curried/closure tests: just print the result of the last expression. # This avoids emitting an extra CALL for the final value if it is not a function. - # A more robust solution would be to have the compiler analyze the top-level expression and only emit CALLs for function results, - # or to have the VM detect and print non-function results at the top level. evaluate_expression "$file_content" exit_code=$? cleanup "keep_state" # Keep state after file execution @@ -141,31 +131,27 @@ while true; do else printf "... " fi - + read -r line || exit 0 - + # Skip empty lines if [ -z "$line" ]; then continue fi - + # Count parentheses - # BASH FEATURE: $(command) is command substitution - runs command and captures output - # Unlike JS where you'd use require('child_process').execSync(), this is built-in open_parens=$(echo "$line" | tr -cd '(' | wc -c) close_parens=$(echo "$line" | tr -cd ')' | wc -c) - # BASH FEATURE: $((expression)) is arithmetic expansion - # Unlike JS where you'd use eval() or a math library, this evaluates arithmetic expressions paren_count=$((paren_count + open_parens - close_parens)) - + if [ -n "$current_input" ]; then current_input="$current_input $line" else current_input="$line" fi - + if [ $paren_count -eq 0 ]; then evaluate_expression "$current_input" current_input="" fi -done
\ No newline at end of file +done diff --git a/awk/scheme/scheme/bin/vm.awk b/awk/scheme/scheme/bin/vm.awk index 33a52a2..16e8eb1 100755 --- a/awk/scheme/scheme/bin/vm.awk +++ b/awk/scheme/scheme/bin/vm.awk @@ -1,40 +1,20 @@ #!/usr/bin/awk -f -# Stack-based Virtual Machine for Awk-Scheme -# -# This VM implements a simple but complete execution environment for compiled Scheme code. -# The design prioritizes simplicity and correctness over performance, making it suitable -# for educational purposes and small-scale applications. -# -# Architecture Overview: -# - Stack-based execution model for simplicity and predictable memory usage -# - Typed value system with runtime type checking for safety -# - Environment-based variable binding supporting lexical scoping -# - Closure support for nested function definitions and lexical scoping -# - Persistent state between sessions for REPL continuity -# -# Key Design Decisions: -# - All values are tagged with their type to enable runtime type checking -# - Environment frames are pushed/popped for function calls to support lexical scoping -# - Closures capture their creation environment to support nested functions -# - State persistence uses simple text files for debugging and REPL continuity -# - Function calls execute code directly rather than modifying the program array - BEGIN { # Type system tags for runtime type checking - # These prefixes enable safe value manipulation and clear error messages - T_NUMBER = "N" # Numbers (integers only for simplicity) - T_BOOLEAN = "B" # Booleans (0/1 for compatibility with AWK) - T_SYMBOL = "S" # Symbols (identifiers and variable names) - T_PAIR = "P" # Cons cells (pairs for list construction) - T_FUNCTION = "F" # Function references (for function values) - T_NIL = "NIL" # Empty list marker (distinct from null) + # These prefixes enable safe value manipulation and clearer error messages + T_NUMBER = "N" # Numbers (integers only for simplicity) + T_BOOLEAN = "B" # Booleans (0/1 for compatibility with AWK) + T_SYMBOL = "S" # Symbols (identifiers and variable names) + T_PAIR = "P" # Cons cells (pairs for list construction) + T_FUNCTION = "F" # Function references (for function values) + T_NIL = "NIL" # Empty list marker (distinct from null) T_CLOSURE = "CLOSURE" # Closure objects (function + captured environment) - T_STRING = "STR" # String literals (for text manipulation) + T_STRING = "STR" # String literals (for text manipulation) # Virtual machine registers and state - stack_ptr = 0 # Points to top of evaluation stack (1-indexed) - heap_ptr = 0 # Points to next free heap location for cons cells + stack_ptr = 0 # Top of evaluation stack (1-indexed) + heap_ptr = 0 # Next free heap location for cons cells pc = 0 # Program counter for instruction fetch and execution # Original program storage for nested function definitions @@ -42,11 +22,8 @@ BEGIN { # nested function definitions and complex control flow delete original_program # Stores the original program before function calls - # Debug mode configuration - # AWK FEATURE: ENVIRON is a built-in array containing environment variables DEBUG = (ENVIRON["DEBUG"] == "1") ? 1 : 0 - # Environment for variable bindings # This implements lexical scoping by maintaining a stack of variable bindings env_size = 0 # Current size of environment stack @@ -57,10 +34,10 @@ BEGIN { delete closure_env_names # Variable names in captured environments delete closure_env_vals # Variable values in captured environments delete closure_env_sizes # Size of each captured environment - next_env_id = 1 # Counter for generating unique environment IDs + next_env_id = 1 # Counter for generating unique environment IDs # Function table for storing defined functions - # Functions are stored by name for efficient lookup during execution + # Functions are stored by name delete func_def_names # Function names delete func_def_pc # Entry points delete func_def_code # Function bodies @@ -70,7 +47,7 @@ BEGIN { # Tracks return addresses for proper function call/return semantics call_stack_ptr = 0 - # Enhanced call stack for nested function calls (for map/filter support) + # Call stack for nested function calls (for map/filter support) # This enables function calls from within built-in functions call_stack_size = 0 # Current size of call stack call_stack_return_pc[100] # Return program counters @@ -79,11 +56,10 @@ BEGIN { call_stack_return_func[100] # Return function names (for debugging) # Global function registry - clear it first - # This maps function names to their implementations for efficient dispatch delete FUNCTIONS # Maps function names to implementations # State persistence configuration - # Uses simple text files for debugging and REPL continuity + # Uses text files for debugging and REPL continuity STATE_FILE = "/tmp/scheme_vm.state" debug("STATE_FILE_PATH: " STATE_FILE) debug("PERSIST_FLAG: " PERSIST) @@ -91,17 +67,15 @@ BEGIN { debug("Loading state from: " STATE_FILE) debug("LOADING_STATE: Attempting to read " STATE_FILE) debug("LOADING_STATE: FUNCTIONS table size before loading: " length(FUNCTIONS)) - # AWK FEATURE: getline is awk's file reading function # getline var < file reads one line from file into var, returns 1 on success, 0 on EOF, -1 on error - # Unlike JS where you'd use fs.readFileSync(), this reads line by line if ((getline line < STATE_FILE) >= 0) { # Check if file exists and is readable debug("LOADING_STATE: File opened successfully, first line: " line) - # AWK FEATURE: do-while loop syntax - the condition is checked at the end + # NOTE: do-while loop syntax - the condition is checked at the end do { debug("LOADING_STATE: Processing line: " line) if (line ~ /^FUNC /) { # Parse and load function definition - # AWK FEATURE: sub() modifies the string in place and returns count of replacements + # sub() modifies the string in place and returns count of replacements sub(/^FUNC /, "", line) name = line sub(/ .*$/, "", name) @@ -130,20 +104,16 @@ BEGIN { debug("LOADED_FUNCTION: Checking if " name " is in table: " (name in FUNCTIONS)) } } while ((getline line < STATE_FILE) > 0) - # AWK FEATURE: close() closes a file handle close(STATE_FILE) } } - # Function environment storage delete func_env_names # Variable names in function scope delete func_env_vals # Variable values in function scope delete func_env_sizes # Size of each function's environment # Register built-in functions first - # These provide the core language operations and are always available # The registration maps Scheme function names to internal VM function names - # for efficient dispatch during execution debug("REGISTERING_BUILTINS: " length(FUNCTIONS) " functions before") # Arithmetic operations - core numeric functionality @@ -162,7 +132,7 @@ BEGIN { FUNCTIONS[">"] = "greater_than" FUNCTIONS["inc"] = "add_one" FUNCTIONS["++"] = "add_one" # Alias for inc function - + # Output FUNCTIONS["display"] = "display" @@ -185,7 +155,7 @@ BEGIN { FUNCTIONS["negative?"] = "negative_p" # Standard library - List utilities - # The implementation prioritizes simplicity over performance + # We're prioritizing simplicity over performance FUNCTIONS["list"] = "stdlib_list" FUNCTIONS["null?"] = "stdlib_null_p" FUNCTIONS["pair?"] = "stdlib_pair_p" @@ -239,24 +209,19 @@ function debug(msg) { if (DEBUG) printf("[DEBUG] %s\n", msg) > "/dev/stderr" } -# Value constructors and accessors # Values are stored as type:value pairs for runtime type checking function makeValue(type, val) { return type ":" val } function getType(val) { - # AWK FEATURE: substr(string, start, length) extracts substring - # Unlike JS string.slice(), this is 1-indexed and requires explicit length - # AWK FEATURE: index(string, substring) returns position of substring (1-indexed) - # Unlike JS string.indexOf(), this returns 0 if not found and is 1-indexed type = substr(val, 1, index(val, ":") - 1) debug("Get type: " type " from " val) return type } function getValue(val) { - # AWK FEATURE: index() returns 1-indexed position, so we add 1 to get after the colon + # NOTE: index() returns 1-indexed position, so we add 1 to get after the colon value = substr(val, index(val, ":") + 1) debug("Get value: " value " from " val) return value @@ -309,14 +274,12 @@ function captureEnvironment(env_id, i) { if (DEBUG) print "[DEBUG_CLOSURE] Captured environment size: " closure_env_sizes[env_id] > "/dev/stderr" } -# VM instruction to capture environment function vm_capture_env(func_name) { debug("Capturing environment for function: " func_name) env_id = next_env_id++ captureEnvironment(env_id) # Replace the placeholder ENV_ID in the closure value - # Find the closure value on the stack and update it if (stack_ptr > 0) { closure_val = stack[stack_ptr] if (closure_val ~ /^CLOSURE:/) { @@ -535,8 +498,6 @@ function vm_less_than() { # Main instruction execution loop function execute(instr) { - # AWK FEATURE: split(string, array, separator) splits string into array elements - # Unlike JS string.split() which returns an array, this populates an existing array split(instr, parts, " ") op = parts[1] debug("Execute: " instr) @@ -548,7 +509,7 @@ function execute(instr) { for (i = 3; i <= length(parts); i++) { value = value " " parts[i] } - + # Handle escape sequences in string constants if (value ~ /^STR:/) { str_content = substr(value, 5) # Remove "STR:" prefix @@ -558,7 +519,7 @@ function execute(instr) { gsub(/\\\\/, "\\", str_content) value = "STR:" str_content } - + push(value) } else if (op == "POP") { @@ -645,7 +606,7 @@ function execute(instr) { } else if (op == "RETURN") { debug("EXECUTING_RETURN") - # The call_stack_ptr is no longer used for return, so this instruction is effectively removed. + # The call_stack_ptr isn't being used, so kinda a noop. # The function execution itself handles the return. } else if (op == "GET_VALUE") { @@ -678,9 +639,6 @@ function execute(instr) { } # Load program instructions -# AWK FEATURE: Each line of input is automatically processed by this block -# NR is a built-in variable that contains the current record (line) number -# Unlike JS where you'd need to track line numbers manually { # Skip empty lines if (length($0) > 0) { @@ -689,11 +647,7 @@ function execute(instr) { } } -# AWK FEATURE: END block runs after all input has been processed -# This is like a "finally" block that always executes after reading all input END { - # AWK FEATURE: length(array) returns the number of elements in an array - # Unlike JS array.length, this is a function call, not a property while (pc < length(program)) { # debug("EXECUTING_PC_" pc ": " program[pc]) execute(program[pc++]) @@ -767,7 +721,7 @@ function vm_clear_stack() { stack_ptr = 0 } -# Variable binding implementation +# Variable binding function vm_store(name) { debug("Storing " peek() " as " name " at env_size: " env_size) @@ -800,7 +754,6 @@ function vm_store(name) { val = peek() if (isSymbol(val)) { func_name = getValue(val) - # AWK FEATURE: ~ is the regex match operator (like /pattern/.test() in JS) # The pattern is a regex literal, not a string if (func_name ~ /^__lambda_/) { # Store the function code under the new name @@ -858,13 +811,11 @@ function vm_lookup(name, i, global_name, val) { debug("LOOKUP_CHECKING: " name " in FUNCTIONS table") debug("FUNCTIONS_TABLE_SIZE: " length(FUNCTIONS)) debug("FUNCTIONS_IN_TABLE:") - # AWK FEATURE: for (var in array) iterates over array keys - # Unlike JS for...in which includes inherited properties, awk arrays don't have inheritance + # TIL that awk arrays don't have inheritance for (f in FUNCTIONS) { debug(" " f) } - # AWK FEATURE: 'in' operator checks if key exists in array - # Unlike JS where you'd use array.hasOwnProperty(key) or 'key' in array + # NOTE: 'in' operator checks if key exists in array if (name in FUNCTIONS) { debug("Found function: " name) push(makeValue(T_SYMBOL, name)) @@ -897,7 +848,7 @@ function vm_define_function(name, start_pc) { if (call_stack_ptr > 0) { debug("Nested function definition - using current instruction") # Just read from the current program position - # AWK FEATURE: length(array) returns the number of elements in an array + # NOTE: length(array) returns the number of elements in an array # Unlike JS array.length, this is a function call, not a property while (i < length(program) && program[i] != "RETURN") { if (code != "") code = code "\n" @@ -907,8 +858,6 @@ function vm_define_function(name, start_pc) { } else { debug("Top-level function definition - using original program") # Use original_program for top-level function definitions - # AWK FEATURE: length(array) returns the number of elements in an array - # Unlike JS array.length, this is a function call, not a property while (i < length(original_program) && original_program[i] != "RETURN") { if (code != "") code = code "\n" code = code original_program[i] @@ -1197,7 +1146,6 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na } # --- End multi-parameter support --- - # This is a built-in function or non-parameterized function debug("Calling non-parameterized function: " func_name) for (j in code_lines) { if (code_lines[j] != "") { @@ -1249,41 +1197,11 @@ function vm_call_function_with_args(arg_count, code_lines, j, saved_pc, saved_en vm_call_function() } -# Function return implementation - no longer needed with direct execution -# function vm_return() { -# debug("VM_RETURN: call_stack_ptr = " call_stack_ptr) -# if (call_stack_ptr > 0) { -# # Save return value -# ret_val = pop() -# debug("VM_RETURN: return value = " ret_val) -# -# # Restore environment -# while (env_size > env_stack[call_stack_ptr]) { -# debug("Popping environment at size: " env_size) -# vm_pop_env() -# } -# -# # Restore program counter -# pc = call_stack[call_stack_ptr--] -# debug("VM_RETURN: restored PC = " pc) -# -# # Restore the original program at the call position -# program[pc] = original_program_at_call[call_stack_ptr + 1] -# debug("Restored original program: " original_program_at_call[call_stack_ptr + 1]) -# -# # Push return value -# push(ret_val) -# debug("VM_RETURN: pushed return value " ret_val) -# -# debug("Returned with value: " ret_val " and env_size: " env_size) -# } -# } - # Debug helper to dump environment contents function dump_env( i) { debug("Environment dump:") for (i = 0; i < env_size; i++) { - # AWK FEATURE: sprintf() formats a string like printf but returns it instead of printing + # NOTE: sprintf() formats a string like printf but returns it instead of printing # Unlike JS where you'd use template literals or String.format(), this is the awk way debug(sprintf(" %d: %s = %s", i, env_name[i], env_val[i])) } @@ -1310,13 +1228,12 @@ function save_state() { debug("Saving function: " func_name) debug("SAVE_STATE: About to write function " func_name) debug("SAVE_STATE: Function code length: " length(FUNCTIONS[func_name])) - # AWK FEATURE: printf with > file redirects output to a file + # NOTE: printf with > file redirects output to a file # Unlike JS where you'd use fs.writeFileSync(), this redirects from stdout to file printf "FUNC %s %s\n", func_name, FUNCTIONS[func_name] > STATE_FILE debug("SAVE_STATE: Saved function " func_name " to " STATE_FILE) } } - # AWK FEATURE: close() closes a file handle close(STATE_FILE) # Save environment state @@ -1324,7 +1241,7 @@ function save_state() { for (i = 0; i < env_size; i++) { if (env_name[i] ~ /^__global_/) { # Only save globals debug("Saving env var: " env_name[i] " = " env_val[i]) - # AWK FEATURE: print with > file redirects output to a file + # NOTE: print with > file redirects output to a file # Unlike JS console.log() which always goes to stdout print "ENV " env_name[i] " " env_val[i] > ENV_STATE_FILE } @@ -1478,7 +1395,7 @@ function string_append() { function string_append_with_args(arg_count) { if (arg_count < 2) error("string-append requires at least two operands") if (stack_ptr < arg_count) error("string-append requires " arg_count " arguments, but only " stack_ptr " available") - + result = "" # Pop specified number of arguments and concatenate (in reverse order) for (i = arg_count; i >= 1; i--) { @@ -1552,7 +1469,7 @@ function string_greater_than() { push(makeValue(T_BOOLEAN, result)) } -# Type predicates - essential for type checking +# Type predicates function number_p() { if (stack_ptr < 1) error("number? requires one operand") val = pop() @@ -1632,7 +1549,7 @@ function display() { print display_value(val) } -# Assert function for testing - checks if condition is true +# Assert function checks if condition is true function assert() { if (stack_ptr < 1) error("assert requires one argument") val = pop() @@ -1688,13 +1605,11 @@ function display_value(val, t, idx, pair, car_val, cdr_val, result) { } # Standard Library Functions -# These implement essential Scheme list utilities following standard conventions -# Each function prioritizes correctness and clear error messages over performance -# The implementation uses the VM's heap for cons cell allocation and management +# Uses the VM's heap for cons cell allocation and management # Create a list from elements # This function handles variable argument counts by building the list from the stack -# The implementation reverses the stack order to maintain proper list construction +# Reverses the stack order to maintain proper list construction function stdlib_list() { debug("stdlib_list called with stack_ptr: " stack_ptr) debug("Stack contents before list: " stack_ptr " items") @@ -1707,7 +1622,7 @@ function stdlib_list() { return } - # Build list from stack elements (arguments are in reverse order on stack) + # Build list from stack elements result = "NIL:" nargs = stack_ptr debug("Building list with " nargs " arguments") @@ -1733,11 +1648,11 @@ function stdlib_list() { function stdlib_list_with_args(arg_count) { debug("stdlib_list_with_args called with arg_count: " arg_count) debug("Stack contents before list: " stack_ptr " items") - + if (arg_count < 0) { error("Invalid argument count for list: " arg_count) } - + if (arg_count == 0) { # No arguments, return empty list debug("No arguments, returning NIL:") @@ -1770,7 +1685,6 @@ function stdlib_list_with_args(arg_count) { } # Check if value is null (empty list) -# This predicate is essential for list processing and control flow function stdlib_null_p() { if (stack_ptr < 1) error("null? requires one argument") val = pop() @@ -1779,7 +1693,6 @@ function stdlib_null_p() { } # Check if value is a pair (cons cell) -# This predicate enables safe list manipulation by checking types function stdlib_pair_p() { if (stack_ptr < 1) error("pair? requires one argument") val = pop() @@ -1788,8 +1701,6 @@ function stdlib_pair_p() { } # Get length of a list -# This function traverses the list structure to count elements -# It provides clear error messages for non-list arguments function stdlib_length() { if (stack_ptr < 1) error("length requires one argument") val = pop() @@ -1819,8 +1730,6 @@ function stdlib_length() { } # Append two lists -# This function creates a new list by copying the first list and -# replacing its final NIL: with the second list function stdlib_append() { if (stack_ptr < 2) error("append requires two arguments") list2 = pop() @@ -1858,8 +1767,6 @@ function stdlib_append() { } # Get second element of list (car of cdr) -# This function implements the standard Scheme cadr operation -# It provides clear error messages for lists with insufficient elements function stdlib_cadr() { if (stack_ptr < 1) error("cadr requires one argument") val = pop() @@ -1886,8 +1793,6 @@ function stdlib_cadr() { } # Get third element of list (car of cdr of cdr) -# This function implements the standard Scheme caddr operation -# It provides clear error messages for lists with insufficient elements function stdlib_caddr() { if (stack_ptr < 1) error("caddr requires one argument") val = pop() @@ -1922,8 +1827,6 @@ function stdlib_caddr() { } # Reverse a list -# This function creates a new list with elements in reverse order -# It traverses the original list and builds the result using cons function stdlib_reverse() { if (stack_ptr < 1) error("reverse requires one argument") list_val = pop() @@ -1960,8 +1863,6 @@ function stdlib_reverse() { } # Check if element is member of list -# This function returns the sublist starting from the matching element -# or NIL: if the element is not found function stdlib_member() { debug("stdlib_member called with stack_ptr: " stack_ptr) if (stack_ptr < 2) error("member requires two arguments") @@ -2256,11 +2157,11 @@ function stdlib_filter() { push(result) } -# Helper function to call a function (used by map and filter) +# Helper function that calls a function (used by map and filter) function call_function() { func_val = pop() arg = pop() - + if (isSymbol(func_val)) { func_name = getValue(func_val) if (func_name in FUNCTIONS) { @@ -2291,11 +2192,11 @@ function call_function() { error("Unsupported built-in function in map: " func_name) } } else { - # User-defined function - simplified for now + # User-defined function - FIXME error("User-defined functions not yet supported in map") } } else if (isClosure(func_val)) { - # Lambda function - simplified for now + # Lambda function - FIXME error("Lambda functions not yet supported in map") } else { error("Invalid function type in map") @@ -2307,12 +2208,12 @@ function save_call_context(func_name) { if (call_stack_size >= 100) { error("Call stack overflow - too many nested function calls") } - + call_stack_return_pc[call_stack_size] = pc call_stack_return_env[call_stack_size] = env_size call_stack_return_stack[call_stack_size] = stack_ptr call_stack_return_func[call_stack_size] = func_name - + call_stack_size++ debug("Saved call context for " func_name " - stack size: " call_stack_size) } @@ -2321,29 +2222,29 @@ function restore_call_context() { if (call_stack_size <= 0) { error("Call stack underflow - trying to restore with empty stack") } - + call_stack_size-- pc = call_stack_return_pc[call_stack_size] env_size = call_stack_return_env[call_stack_size] # Don't restore stack_ptr - the nested call should leave its result on top # stack_ptr = call_stack_return_stack[call_stack_size] - + debug("Restored call context - stack size: " call_stack_size " (stack_ptr: " stack_ptr ")") } function call_function_context(func_val, arg) { debug("Calling function in context: " func_val " with arg: " arg) - + # Save current context save_call_context("nested_call") - + # Push argument and function push(arg) push(func_val) - + # Execute function call execute_nested_function_call() - + # Restore context restore_call_context() } @@ -2351,13 +2252,13 @@ function call_function_context(func_val, arg) { function execute_nested_function_call() { func_val = pop() arg = pop() - + debug("Executing nested function call: " func_val " with arg: " arg) - + if (isSymbol(func_val)) { func_name = getValue(func_val) debug("Function name from symbol: " func_name) - + # Handle lambda functions (__lambda_*) if (func_name ~ /^__lambda_/) { if (!(func_name in FUNCTIONS)) { @@ -2393,7 +2294,7 @@ function is_truthy(val) { function call_builtin_function_nested(built_in_name) { debug("Calling built-in function in nested context: " built_in_name) - + if (built_in_name == "add") { add() } else if (built_in_name == "subtract") { @@ -2435,27 +2336,27 @@ function call_builtin_function_nested(built_in_name) { function call_user_function_nested(func_name, arg) { debug("Calling user function in nested context: " func_name " with arg: " arg) - + if (!(func_name in FUNCTIONS)) { error("Undefined user function: " func_name) } - + # Get function code split(FUNCTIONS[func_name], code_lines, "\n") - + # Check if this is a parameterized function if (code_lines[1] ~ /^STORE /) { # This is a parameterized function (lambda) param_name = substr(code_lines[1], 7) debug("Found parameter name: " param_name) - + # Create new environment frame debug("Creating new environment frame at size: " env_size) env_name[env_size] = param_name env_val[env_size] = arg env_size++ debug("FUNCTION_ENV_STORE: " param_name " = " arg " at index " (env_size-1)) - + # Execute function code directly, skipping STORE and POP_ENV instructions for (j = 2; j <= length(code_lines); j++) { if (code_lines[j] != "" && code_lines[j] != "POP_ENV") { @@ -2463,17 +2364,14 @@ function call_user_function_nested(func_name, arg) { execute(code_lines[j]) } } - + # Clean up parameter vm_pop_env() } else { - # This is a non-parameterized function debug("Calling non-parameterized function: " func_name) - - # Push argument for non-parameterized functions + push(arg) - - # Execute all function code directly + for (j in code_lines) { if (code_lines[j] != "") { debug("Executing function instruction: " code_lines[j]) @@ -2485,26 +2383,26 @@ function call_user_function_nested(func_name, arg) { function call_closure_nested(closure_val, arg) { debug("Calling closure in nested context: " closure_val " with arg: " arg) - + # Extract closure information closure_func = getClosureFunction(closure_val) closure_env_id = getClosureEnvId(closure_val) - + debug("Closure function: " closure_func " env_id: " closure_env_id) - + if (!(closure_func in FUNCTIONS)) { error("Undefined closure function: " closure_func) } - + # Save current environment state saved_env_size = env_size - + # Restore the captured environment pushClosureEnvironment(closure_env_id) - + # Now call the user function with the restored environment call_user_function_nested(closure_func, arg) - + # Restore original environment (closure environment is automatically cleaned up) # Note: We don't need to explicitly restore since the nested call context handles this -}
\ No newline at end of file +} diff --git a/awk/scheme/scheme/scratch/forth/forth.awk b/awk/scheme/scheme/scratch/forth/forth.awk index 618f4d5..3cebac0 100755 --- a/awk/scheme/scheme/scratch/forth/forth.awk +++ b/awk/scheme/scheme/scratch/forth/forth.awk @@ -1,19 +1,11 @@ #!/usr/bin/awk -f -# Forth-to-VM Compiler for VM Validation -# -# This compiler translates Forth expressions to VM bytecode, validating -# the VM implementation by testing individual operations. -# -# Architecture: -# - Forth-to-VM compiler that generates VM instructions -# - Uses existing VM to validate instruction execution -# - Tests individual operations (not a true REPL with persistent stack) -# - Stack-based operations that validate VM behavior +# Forth-to-VM Compiler +# This compiler is meant to validate the VM implementation. # # Note: Each line is executed in a separate VM instance, so stack state # does not persist between lines. This is a limitation of the current VM -# design that doesn't impact the scheme implementation, I don't think. +# design that doesn't impact the scheme implementation, I don't think. BEGIN { print "Forth VM Compiler (for VM validation)" @@ -38,11 +30,11 @@ BEGIN { function compile_and_execute(line, tokens, i, token, bytecode) { split(line, tokens, " ") bytecode = "" - + for (i = 1; i <= length(tokens); i++) { token = tokens[i] if (token == "") continue - + if (token ~ /^-?[0-9]+$/) { # Number - push constant bytecode = bytecode "PUSH_CONST N:" token "\n" @@ -196,13 +188,13 @@ function compile_and_execute(line, tokens, i, token, bytecode) { bytecode = bytecode "POP\n" } } - + # Add HALT instruction only if we haven't already printed something # This prevents double output if (bytecode !~ /PRINT/) { bytecode = bytecode "HALT\n" } - + # Execute the bytecode execute_bytecode(bytecode) } @@ -213,11 +205,11 @@ function execute_bytecode(bytecode) { temp_file = "/tmp/forth_bytecode.tmp" printf("%s", bytecode) > temp_file close(temp_file) - + # Try different VM paths based on current directory vm_path = "bin/vm.awk" cmd = "awk -v PERSIST=1 -f " vm_path " < " temp_file " 2>/dev/null" - + # Read all output lines output = "" while ((cmd | getline line) > 0) { @@ -225,12 +217,12 @@ function execute_bytecode(bytecode) { output = output line } close(cmd) - + # If that failed, try the relative path from forth directory if (output == "" || output ~ /No such file/) { vm_path = "../../bin/vm.awk" cmd = "awk -v PERSIST=1 -f " vm_path " < " temp_file " 2>/dev/null" - + # Read all output lines output = "" while ((cmd | getline line) > 0) { @@ -239,11 +231,11 @@ function execute_bytecode(bytecode) { } close(cmd) } - + # Clean up system("rm -f " temp_file) - + if (output != "") { printf("Result: %s\n", output) } -}
\ No newline at end of file +} |