aboutsummaryrefslogtreecommitdiffstats
path: root/awk/scheme
diff options
context:
space:
mode:
authorelioat <elioat@tilde.institute>2025-07-20 19:08:39 -0400
committerelioat <elioat@tilde.institute>2025-07-20 19:08:39 -0400
commit38eb02424a4c72aa02573db8daf0eb6ac09dd1c1 (patch)
treec4bef97ec4bd829d86dd1d5489ae3e952f352d97 /awk/scheme
parente646440504995558950d48010142d8f827370bf6 (diff)
downloadtour-38eb02424a4c72aa02573db8daf0eb6ac09dd1c1.tar.gz
*
Diffstat (limited to 'awk/scheme')
-rw-r--r--awk/scheme/scheme/README.md19
-rwxr-xr-xawk/scheme/scheme/bin/vm.awk273
-rw-r--r--awk/scheme/scheme/scratch/standard-library-implementation-summary.md4
-rw-r--r--awk/scheme/scheme/test/unit/inc_alias_test.scm22
4 files changed, 180 insertions, 138 deletions
diff --git a/awk/scheme/scheme/README.md b/awk/scheme/scheme/README.md
index b3785d4..903d7c9 100644
--- a/awk/scheme/scheme/README.md
+++ b/awk/scheme/scheme/README.md
@@ -145,7 +145,9 @@ N:42
```scheme
scheme> (let ((x 10)) ((lambda (y) (+ x y)) 32))
N:42
-scheme> (let ((add1 (lambda (x) (+ x 1)))) (add1 41))
+scheme> (let ((inc (lambda (x) (+ x 1)))) (inc 41))
+N:42
+scheme> (++ 41) ; Using the ++ alias for inc
N:42
```
@@ -308,6 +310,21 @@ To add a new standard library function, you need to:
(assert (= (new-function arg) expected-result))
```
+### Creating Function Aliases
+
+You can create aliases for existing functions by registering multiple names for the same implementation:
+
+```awk
+# Register the main function
+FUNCTIONS["inc"] = "add_one"
+
+# Create aliases for the same function
+FUNCTIONS["++"] = "add_one" # Alias for inc function
+FUNCTIONS["increment"] = "add_one" # Another alias
+```
+
+This allows users to call the same function using different names, providing flexibility and convenience.
+
### Adding New Special Forms
1. Add parsing in `compile_expr()`
2. Implement code generation function
diff --git a/awk/scheme/scheme/bin/vm.awk b/awk/scheme/scheme/bin/vm.awk
index 847629d..e3a510e 100755
--- a/awk/scheme/scheme/bin/vm.awk
+++ b/awk/scheme/scheme/bin/vm.awk
@@ -1,7 +1,7 @@
#!/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.
@@ -36,12 +36,12 @@ BEGIN {
stack_ptr = 0 # Points to top of evaluation stack (1-indexed)
heap_ptr = 0 # Points to next free heap location for cons cells
pc = 0 # Program counter for instruction fetch and execution
-
+
# Original program storage for nested function definitions
# This preserves the complete program during function calls to support
# 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
@@ -49,7 +49,7 @@ BEGIN {
# Environment for variable bindings
# This implements lexical scoping by maintaining a stack of variable bindings
env_size = 0 # Current size of environment stack
-
+
# Closure support - captured environments for nested lambdas
# Closures capture their creation environment to support lexical scoping
# in nested function definitions
@@ -58,14 +58,14 @@ BEGIN {
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
-
+
# Function table for storing defined functions
# Functions are stored by name for efficient lookup during execution
delete func_def_names # Function names
delete func_def_pc # Entry points
delete func_def_code # Function bodies
func_def_size = 0 # Number of defined functions
-
+
# Call stack for function returns
# Tracks return addresses for proper function call/return semantics
call_stack_ptr = 0
@@ -99,7 +99,7 @@ BEGIN {
sub(/ .*$/, "", name)
code = line
sub(/^[^ ]+ /, "", code)
-
+
# Read the rest of the function code (until next FUNC or end of file)
debug("LOADING_STATE: Reading function code for " name)
while ((getline line < STATE_FILE) > 0) {
@@ -111,10 +111,10 @@ BEGIN {
}
code = code "\n" line
}
-
+
debug("Loaded function: " name)
debug("Code: " code)
-
+
# Store function in FUNCTIONS table
FUNCTIONS[name] = code
debug("LOADED_FUNCTION: " name " with code length " length(code))
@@ -137,7 +137,7 @@ BEGIN {
# 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
FUNCTIONS["+"] = "add"
FUNCTIONS["-"] = "subtract"
@@ -146,10 +146,10 @@ BEGIN {
FUNCTIONS["="] = "equals"
FUNCTIONS["<"] = "less_than"
FUNCTIONS[">"] = "greater_than"
- FUNCTIONS["add1"] = "add_one"
-
- # String operations - text manipulation utilities
- # These provide basic string functionality for text processing
+ FUNCTIONS["inc"] = "add_one"
+ FUNCTIONS["++"] = "add_one" # Alias for inc function
+
+ # String operations - text manipulation utilitie
FUNCTIONS["string-length"] = "string_length"
FUNCTIONS["string-append"] = "string_append"
FUNCTIONS["string-ref"] = "string_ref"
@@ -157,10 +157,9 @@ BEGIN {
FUNCTIONS["string=?"] = "string_equal"
FUNCTIONS["string<?"] = "string_less_than"
FUNCTIONS["string>?"] = "string_greater_than"
-
- # Standard library - List utilities
- # These provide essential list manipulation functions following Scheme conventions
- # The implementation prioritizes correctness and simplicity over performance
+
+ # Standard library - List utilitie
+ # The implementation prioritizes simplicity over performance
FUNCTIONS["list"] = "stdlib_list"
FUNCTIONS["null?"] = "stdlib_null_p"
FUNCTIONS["pair?"] = "stdlib_pair_p"
@@ -172,7 +171,7 @@ BEGIN {
FUNCTIONS["caddr"] = "stdlib_caddr"
FUNCTIONS["list-ref"] = "stdlib_list_ref"
FUNCTIONS["list-tail"] = "stdlib_list_tail"
-
+
debug("REGISTERING_BUILTINS: " length(FUNCTIONS) " functions after")
# Environment persistence configuration
@@ -188,9 +187,9 @@ BEGIN {
sub(/ .*$/, "", name)
val = line
sub(/^[^ ]+ /, "", val)
-
+
debug("Loaded env var: " name " = " val)
-
+
# Store in environment
env_name[env_size] = name
env_val[env_size] = val
@@ -255,7 +254,7 @@ function makeClosure(func_name, env_id) {
function getClosureFunction(closure_val) {
# Extract function name from CLOSURE:func_name:env_id
- return substr(closure_val, index(closure_val, ":") + 1,
+ return substr(closure_val, index(closure_val, ":") + 1,
index(substr(closure_val, index(closure_val, ":") + 1), ":") - 1)
}
@@ -270,7 +269,7 @@ function getClosureEnvId(closure_val) {
function captureEnvironment(env_id, i) {
debug("Capturing environment with ID: " env_id)
closure_env_sizes[env_id] = env_size
-
+
# Copy current environment to closure environment
for (i = 0; i < env_size; i++) {
# Only capture non-global variables
@@ -280,7 +279,7 @@ function captureEnvironment(env_id, i) {
debug("Captured: " env_name[i] " = " env_val[i])
}
}
-
+
debug("Captured environment size: " closure_env_sizes[env_id])
}
@@ -289,7 +288,7 @@ 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) {
@@ -364,7 +363,7 @@ function vm_add() {
if (stack_ptr < 2) error("ADD requires two operands")
val2 = pop()
val1 = pop()
- if (!isNumber(val1) || !isNumber(val2))
+ if (!isNumber(val1) || !isNumber(val2))
error("ADD requires numeric operands")
result = getValue(val1) + getValue(val2)
push(makeValue(T_NUMBER, result))
@@ -460,7 +459,7 @@ function execute(instr) {
split(instr, parts, " ")
op = parts[1]
debug("Execute: " instr)
-
+
# Dispatch based on instruction opcode
if (op == "PUSH_CONST") {
# Reconstruct the full value in case it contains spaces
@@ -602,7 +601,7 @@ END {
# debug("EXECUTING_PC_" pc ": " program[pc])
execute(program[pc++])
}
-
+
# Save state if we didn't halt normally
if (!normal_exit && PERSIST) {
save_state()
@@ -626,7 +625,7 @@ function vm_jump_if_false(label) {
if (stack_ptr < 1) error("JUMP_IF_FALSE requires one operand")
val = pop()
debug("Jump if false: " val " -> " label)
-
+
# Check if value is false (0, false, or nil)
is_false = (val == "B:0" || val == "N:0" || val == "NIL:")
if (is_false) {
@@ -638,7 +637,7 @@ function vm_jump_if_true(label) {
if (stack_ptr < 1) error("JUMP_IF_TRUE requires one operand")
val = pop()
debug("Jump if true: " val " -> " label)
-
+
# Check if value is true (non-zero, non-false, non-nil)
is_true = (val != "B:0" && val != "N:0" && val != "NIL:")
if (is_true) {
@@ -650,7 +649,7 @@ function vm_not() {
if (stack_ptr < 1) error("NOT requires one operand")
val = pop()
debug("NOT: " val)
-
+
# Negate the boolean value
if (val == "B:0" || val == "N:0" || val == "NIL:") {
push(makeValue(T_BOOLEAN, "1"))
@@ -674,7 +673,7 @@ function vm_clear_stack() {
# Variable binding implementation
function vm_store(name) {
debug("Storing " peek() " as " name " at env_size: " env_size)
-
+
# Handle global definitions specially
if (lookup_no_error("from_define")) {
name = "__global_" name
@@ -685,7 +684,7 @@ function vm_store(name) {
break
}
}
-
+
# Remove any previous definition of this global
for (i = env_size - 1; i >= 0; i--) {
if (env_name[i] == name) {
@@ -699,7 +698,7 @@ function vm_store(name) {
}
}
}
-
+
# Handle lambda functions
val = peek()
if (isSymbol(val)) {
@@ -716,12 +715,12 @@ function vm_store(name) {
return
}
}
-
+
# Add to environment
env_name[env_size] = name
env_val[env_size] = peek()
env_size++
-
+
debug("Environment after store:")
dump_env()
}
@@ -730,13 +729,13 @@ function vm_store(name) {
function vm_pop_env() {
if (env_size <= 0) error("Environment underflow")
debug("Popping environment at size: " env_size)
-
+
# Don't pop globals
if (env_name[env_size-1] ~ /^__global_/) {
debug("Keeping global definition: " env_name[env_size-1])
return
}
-
+
debug("Removing: " env_name[env_size-1] " = " env_val[env_size-1])
env_size--
}
@@ -782,7 +781,7 @@ function vm_lookup(name, i, global_name, val) {
function vm_define_function(name, start_pc) {
debug("Defining function: " name " at " start_pc)
debug("call_stack_ptr: " call_stack_ptr)
-
+
# Clear the from_define flag
for (i = env_size - 1; i >= 0; i--) {
if (env_name[i] == "from_define") {
@@ -791,11 +790,11 @@ function vm_define_function(name, start_pc) {
break
}
}
-
+
# Build function code
code = ""
i = start_pc
-
+
# If we're inside a function call, we need to find the corresponding position
# in the original program. For now, use a simple heuristic.
if (call_stack_ptr > 0) {
@@ -820,13 +819,13 @@ function vm_define_function(name, start_pc) {
}
}
code = code "\nRETURN"
-
+
# Store function
debug("Storing function: " name " = " code)
FUNCTIONS[name] = code
debug("Function stored. Total functions: " length(FUNCTIONS))
debug("FUNCTION_STORED: " name)
-
+
pc = i + 1
}
@@ -836,12 +835,12 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na
func_name = pop()
debug("Calling function: " func_name)
debug("CALLING_FUNCTION: " func_name)
-
+
# If name is a symbol, get its value
if (isSymbol(func_name)) {
func_name = getValue(func_name)
}
-
+
# Check if it's a built-in function first
if (func_name in FUNCTIONS) {
built_in_name = FUNCTIONS[func_name]
@@ -956,7 +955,7 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na
return
}
}
-
+
# Handle anonymous functions and closures
if (func_name ~ /^__lambda_/) {
if (!(func_name in FUNCTIONS)) {
@@ -967,27 +966,27 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na
debug("Calling closure: " func_name)
closure_func = getClosureFunction(func_name)
closure_env_id = getClosureEnvId(func_name)
-
+
if (!(closure_func in FUNCTIONS)) {
error("Undefined closure function: " closure_func)
}
-
+
# Restore the captured environment
pushClosureEnvironment(closure_env_id)
-
+
# Use the closure's function name for the rest of the call
func_name = closure_func
} else if (!(func_name in FUNCTIONS)) {
error("Undefined function: " func_name)
}
-
+
saved_pc = pc
saved_env_size = env_size
-
+
# 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(FUNCTIONS[func_name], code_lines, "\n")
-
+
# Check if this is a parameterized function
if (code_lines[1] ~ /^STORE /) {
# This is a parameterized function (lambda)
@@ -995,19 +994,19 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na
param_name = substr(code_lines[1], 7)
debug("Found parameter name: " param_name)
debug("FUNCTION_PARAM: " param_name)
-
+
# Get argument from stack
arg = pop()
debug("Function argument: " arg)
debug("FUNCTION_ARG: " arg)
-
+
# 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") {
@@ -1015,10 +1014,10 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na
execute(code_lines[j])
}
}
-
+
# Clean up parameter
vm_pop_env()
-
+
# Return to caller
debug("Function completed, returning to PC: " saved_pc)
pc = saved_pc
@@ -1026,7 +1025,7 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na
} else {
# This is a built-in function or non-parameterized function
debug("Calling non-parameterized function: " func_name)
-
+
# Execute all function code directly
for (j in code_lines) {
if (code_lines[j] != "") {
@@ -1034,7 +1033,7 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na
execute(code_lines[j])
}
}
-
+
# Return to caller
debug("Function completed, returning to PC: " saved_pc)
pc = saved_pc
@@ -1049,25 +1048,25 @@ function vm_call_function(code_lines, j, saved_pc, saved_env_size, arg, param_na
# # 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)
# }
# }
@@ -1191,9 +1190,9 @@ function divide() {
}
function add_one() {
- if (stack_ptr < 1) error("add1 requires one operand")
+ if (stack_ptr < 1) error("inc requires one operand")
val = pop()
- if (!isNumber(val)) error("add1 requires numeric operand")
+ if (!isNumber(val)) error("inc requires numeric operand")
result = getValue(val) + 1
push(makeValue(T_NUMBER, result))
}
@@ -1225,11 +1224,11 @@ function string_ref() {
str_val = pop()
if (!isNumber(index_val)) error("string-ref index must be a number")
if (!isString(str_val)) error("string-ref requires string operand")
-
+
str = getValue(str_val)
idx = getValue(index_val) + 1 # Convert to 1-indexed
if (idx < 1 || idx > length(str)) error("string-ref index out of bounds")
-
+
char = substr(str, idx, 1)
push(makeString(char))
}
@@ -1239,18 +1238,18 @@ function substring() {
end = pop()
start = pop()
str_val = pop()
-
+
if (!isNumber(start) || !isNumber(end)) error("substring indices must be numbers")
if (!isString(str_val)) error("substring requires string operand")
-
+
str = getValue(str_val)
start_idx = getValue(start) + 1 # Convert to 1-indexed
end_idx = getValue(end) + 1
-
+
if (start_idx < 1 || end_idx > length(str) || start_idx > end_idx) {
error("substring indices out of bounds")
}
-
+
result = substr(str, start_idx, end_idx - start_idx + 1)
push(makeString(result))
}
@@ -1320,12 +1319,12 @@ function stdlib_list() {
push("NIL:")
return
}
-
+
# Build list from stack elements (arguments are in reverse order on stack)
result = "NIL:"
nargs = stack_ptr
debug("Building list with " nargs " arguments")
-
+
# Pop arguments and build list in correct order
for (i = nargs; i >= 1; i--) {
val = pop()
@@ -1336,7 +1335,7 @@ function stdlib_list() {
result = makeValue(T_PAIR, pair_idx)
debug("Created pair: " result)
}
-
+
debug("Final result: " result)
push(result)
}
@@ -1365,19 +1364,19 @@ function stdlib_pair_p() {
function stdlib_length() {
if (stack_ptr < 1) error("length requires one argument")
val = pop()
-
+
if (val == "NIL:") {
push(makeValue(T_NUMBER, "0"))
return
}
-
+
if (!isPair(val)) {
error("length requires a list argument")
}
-
+
count = 0
current = val
-
+
while (current != "NIL:" && isPair(current)) {
count++
# Get cdr of current pair
@@ -1386,7 +1385,7 @@ function stdlib_length() {
cdr_val = substr(pair, index(pair, ",") + 1)
current = cdr_val
}
-
+
push(makeValue(T_NUMBER, count))
}
@@ -1397,26 +1396,26 @@ function stdlib_append() {
if (stack_ptr < 2) error("append requires two arguments")
list2 = pop()
list1 = pop()
-
+
if (list1 == "NIL:") {
push(list2)
return
}
-
+
if (!isPair(list1)) {
error("append requires list arguments")
}
-
+
# Copy first list
result = copy_list(list1)
-
+
# Find end of first list
current = result
while (current != "NIL:" && isPair(current)) {
pair_idx = getValue(current)
pair = getHeap(pair_idx)
cdr_val = substr(pair, index(pair, ",") + 1)
-
+
if (cdr_val == "NIL:") {
# Replace NIL: with second list
new_pair_val = substr(pair, 1, index(pair, ",")) list2
@@ -1425,7 +1424,7 @@ function stdlib_append() {
}
current = cdr_val
}
-
+
push(result)
}
@@ -1435,25 +1434,25 @@ function stdlib_append() {
function stdlib_cadr() {
if (stack_ptr < 1) error("cadr requires one argument")
val = pop()
-
+
if (val == "NIL:" || !isPair(val)) {
error("cadr requires a list with at least 2 elements")
}
-
+
# Get cdr
pair_idx = getValue(val)
pair = getHeap(pair_idx)
cdr_val = substr(pair, index(pair, ",") + 1)
-
+
if (cdr_val == "NIL:" || !isPair(cdr_val)) {
error("cadr requires a list with at least 2 elements")
}
-
+
# Get car of cdr
cdr_pair_idx = getValue(cdr_val)
cdr_pair = getHeap(cdr_pair_idx)
cadr_val = substr(cdr_pair, 1, index(cdr_pair, ",") - 1)
-
+
push(cadr_val)
}
@@ -1463,33 +1462,33 @@ function stdlib_cadr() {
function stdlib_caddr() {
if (stack_ptr < 1) error("caddr requires one argument")
val = pop()
-
+
if (val == "NIL:" || !isPair(val)) {
error("caddr requires a list with at least 3 elements")
}
-
+
# Get cdr of cdr
pair_idx = getValue(val)
pair = getHeap(pair_idx)
cdr_val = substr(pair, index(pair, ",") + 1)
-
+
if (cdr_val == "NIL:" || !isPair(cdr_val)) {
error("caddr requires a list with at least 3 elements")
}
-
+
cdr_pair_idx = getValue(cdr_val)
cdr_pair = getHeap(cdr_pair_idx)
cdot_val = substr(cdr_pair, index(cdr_pair, ",") + 1)
-
+
if (cdot_val == "NIL:" || !isPair(cdot_val)) {
error("caddr requires a list with at least 3 elements")
}
-
+
# Get car of cdr of cdr
cdot_pair_idx = getValue(cdot_val)
cdot_pair = getHeap(cdot_pair_idx)
caddr_val = substr(cdot_pair, 1, index(cdot_pair, ",") - 1)
-
+
push(caddr_val)
}
@@ -1499,35 +1498,35 @@ function stdlib_caddr() {
function stdlib_reverse() {
if (stack_ptr < 1) error("reverse requires one argument")
list_val = pop()
-
+
if (list_val == "NIL:") {
push("NIL:")
return
}
-
+
if (!isPair(list_val)) {
error("reverse requires a list argument")
}
-
+
# Build reversed list
result = "NIL:"
current = list_val
-
+
while (current != "NIL:" && isPair(current)) {
# Get car of current pair
pair_idx = getValue(current)
pair = getHeap(pair_idx)
car_val = substr(pair, 1, index(pair, ",") - 1)
-
+
# Add to result
pair_val = car_val "," result
pair_idx = allocate(pair_val)
result = makeValue(T_PAIR, pair_idx)
-
+
# Move to next element
current = substr(pair, index(pair, ",") + 1)
}
-
+
push(result)
}
@@ -1538,34 +1537,34 @@ function stdlib_member() {
if (stack_ptr < 2) error("member requires two arguments")
list_val = pop()
elem_val = pop()
-
+
if (list_val == "NIL:") {
push("NIL:")
return
}
-
+
if (!isPair(list_val)) {
error("member requires a list as second argument")
}
-
+
current = list_val
-
+
while (current != "NIL:" && isPair(current)) {
# Get car of current pair
pair_idx = getValue(current)
pair = getHeap(pair_idx)
car_val = substr(pair, 1, index(pair, ",") - 1)
-
+
# Check if element matches
if (car_val == elem_val) {
push(current) # Return the sublist starting from this element
return
}
-
+
# Move to next element
current = substr(pair, index(pair, ",") + 1)
}
-
+
# Element not found
push("NIL:")
}
@@ -1575,24 +1574,24 @@ function stdlib_list_ref() {
if (stack_ptr < 2) error("list-ref requires two arguments")
index_val = pop()
list_val = pop()
-
+
if (!isNumber(index_val)) {
error("list-ref index must be a number")
}
-
+
idx = getValue(index_val)
-
+
if (list_val == "NIL:") {
error("list-ref index out of bounds")
}
-
+
if (!isPair(list_val)) {
error("list-ref requires a list argument")
}
-
+
current = list_val
count = 0
-
+
while (current != "NIL:" && isPair(current)) {
if (count == idx) {
# Get car of current pair
@@ -1602,14 +1601,14 @@ function stdlib_list_ref() {
push(car_val)
return
}
-
+
# Move to next element
pair_idx = getValue(current)
pair = getHeap(pair_idx)
current = substr(pair, index(pair, ",") + 1)
count++
}
-
+
error("list-ref index out of bounds")
}
@@ -1618,47 +1617,47 @@ function stdlib_list_tail() {
if (stack_ptr < 2) error("list-tail requires two arguments")
index_val = pop()
list_val = pop()
-
+
if (!isNumber(index_val)) {
error("list-tail index must be a number")
}
-
+
idx = getValue(index_val)
-
+
if (idx == 0) {
push(list_val)
return
}
-
+
if (list_val == "NIL:") {
error("list-tail index out of bounds")
}
-
+
if (!isPair(list_val)) {
error("list-tail requires a list argument")
}
-
+
current = list_val
count = 0
-
+
while (current != "NIL:" && isPair(current)) {
if (count == idx) {
push(current)
return
}
-
+
# Move to next element
pair_idx = getValue(current)
pair = getHeap(pair_idx)
current = substr(pair, index(pair, ",") + 1)
count++
}
-
+
if (count == idx) {
push("NIL:")
return
}
-
+
error("list-tail index out of bounds")
}
@@ -1667,27 +1666,27 @@ function copy_list(list_val, result, current, pair_idx, pair, car_val, cdr_val)
if (list_val == "NIL:") {
return "NIL:"
}
-
+
if (!isPair(list_val)) {
error("copy_list requires a list argument")
}
-
+
result = "NIL:"
current = list_val
-
+
# Build result list in reverse order
temp_stack[0] = 0
while (current != "NIL:" && isPair(current)) {
pair_idx = getValue(current)
pair = getHeap(pair_idx)
car_val = substr(pair, 1, index(pair, ",") - 1)
-
+
temp_stack[++temp_stack[0]] = car_val
-
+
cdr_val = substr(pair, index(pair, ",") + 1)
current = cdr_val
}
-
+
# Build result in correct order
for (i = temp_stack[0]; i >= 1; i--) {
if (result == "NIL:") {
@@ -1698,6 +1697,6 @@ function copy_list(list_val, result, current, pair_idx, pair, car_val, cdr_val)
result = makeValue(T_PAIR, pair_idx)
}
}
-
+
return result
} \ No newline at end of file
diff --git a/awk/scheme/scheme/scratch/standard-library-implementation-summary.md b/awk/scheme/scheme/scratch/standard-library-implementation-summary.md
index 9838021..3b98ec2 100644
--- a/awk/scheme/scheme/scratch/standard-library-implementation-summary.md
+++ b/awk/scheme/scheme/scratch/standard-library-implementation-summary.md
@@ -37,6 +37,10 @@ The Awk-Scheme interpreter now includes a comprehensive standard library with th
- `(string<? str1 str2)` - String less than
- `(string>? str1 str2)` - String greater than
+#### Arithmetic Operations
+- `(inc n)` - Increment a number by 1
+- `(++ n)` - Alias for inc function
+
## Implementation Details
### VM Integration
diff --git a/awk/scheme/scheme/test/unit/inc_alias_test.scm b/awk/scheme/scheme/test/unit/inc_alias_test.scm
new file mode 100644
index 0000000..54b1cfa
--- /dev/null
+++ b/awk/scheme/scheme/test/unit/inc_alias_test.scm
@@ -0,0 +1,22 @@
+;; Test for inc function and ++ alias
+;; This test verifies that both inc and ++ work as increment functions
+
+;; Test basic inc function
+(assert (= (inc 41) 42))
+(assert (= (inc 0) 1))
+(assert (= (inc -1) 0))
+
+;; Test ++ alias
+(assert (= (++ 41) 42))
+(assert (= (++ 0) 1))
+(assert (= (++ -1) 0))
+
+;; Test that both functions are equivalent
+(assert (= (inc 10) (++ 10)))
+
+;; Test with larger numbers
+(assert (= (inc 999) 1000))
+(assert (= (++ 999) 1000))
+
+;; Test error handling for non-numeric arguments
+;; (This would be tested in a separate error test file) \ No newline at end of file