aboutsummaryrefslogtreecommitdiffstats
path: root/awk/scheme
diff options
context:
space:
mode:
authorelioat <{ID}+{username}@users.noreply.github.com>2025-07-21 09:29:12 -0400
committerelioat <{ID}+{username}@users.noreply.github.com>2025-07-21 09:29:12 -0400
commit7250bdf5aaa962ba276ee9e3181017a86cba2db2 (patch)
treea3cbee4288c1c1df596c8eb3398390f7f0d04a44 /awk/scheme
parente1662a5405920b6338e342c4e04b48e555dbf6bc (diff)
downloadtour-7250bdf5aaa962ba276ee9e3181017a86cba2db2.tar.gz
*
Diffstat (limited to 'awk/scheme')
-rw-r--r--awk/scheme/scheme/WHAT-NEEDS-FIXING.md39
-rwxr-xr-xawk/scheme/scheme/bin/compiler.awk134
2 files changed, 141 insertions, 32 deletions
diff --git a/awk/scheme/scheme/WHAT-NEEDS-FIXING.md b/awk/scheme/scheme/WHAT-NEEDS-FIXING.md
new file mode 100644
index 0000000..4c07b02
--- /dev/null
+++ b/awk/scheme/scheme/WHAT-NEEDS-FIXING.md
@@ -0,0 +1,39 @@
+# What Needs Fixing
+
+## Known Bugs
+
+### 1. Nested Defines and Multi-Expression Function Bodies
+- **Symptom:** Tests with nested `define` or multiple expressions in a function body (e.g., `advanced_functions.scm`, `environment_scoping.scm`, `complex_programs.scm`) fail with errors like:
+ - `Error: Unknown expression type: y))(inner1`
+ - `Error: Unknown expression type: global) globa`
+ - `Error: Unknown expression type: 1)))))(reverse-helperstr(-(string-leng`
+- **Suspected Cause:**
+ - The S-expression splitting or parsing logic is leaving behind fragments after processing nested defines or multi-expression bodies.
+ - There may be a mismatch between how the splitter and the parser advance through the input, especially for function bodies.
+
+### 2. Debug Output Not Triggered in Key Functions
+- **Symptom:** Even with `DEBUG_SEXPR=1`, debug output from `split_sexpressions` and `compile_lambda` does not appear, suggesting these functions are not being called for the failing cases.
+- **Suspected Cause:**
+ - The error may occur before any lambda body is processed, or in a code path that does not use these functions (e.g., top-level parsing or define handling).
+
+## Next Debugging Steps
+
+1. **Add Debug Prints to Key Functions**
+ - Add debug prints to `compile_define` and `compile_expr` to trace which expressions are being processed and when errors occur.
+ - This will help determine if the error is in top-level parsing, define handling, or function body processing.
+
+2. **Test the S-expression Splitter in Isolation**
+ - Take a failing function body and run it through `split_sexpressions` directly, printing the results.
+ - Confirm if the splitter is producing complete S-expressions or fragments.
+
+3. **Trace the Error Path**
+ - Use debug output to follow the flow from top-level parsing, through defines, into lambdas, and into function bodies.
+ - Identify exactly where the parser or code generator leaves behind fragments.
+
+4. **Compare with Reference Implementations**
+ - Review the approach in [littlelisp](https://github.com/maryrosecook/littlelisp) for robust S-expression parsing and evaluation.
+ - Consider adopting a similar recursive descent parsing strategy if needed.
+
+## Goal
+- Ensure that all S-expressions (top-level and in function bodies) are parsed and compiled correctly, with no fragments left behind.
+- Make the debug infrastructure robust and easy to enable/disable for future debugging. \ No newline at end of file
diff --git a/awk/scheme/scheme/bin/compiler.awk b/awk/scheme/scheme/bin/compiler.awk
index f36f497..7e43631 100755
--- a/awk/scheme/scheme/bin/compiler.awk
+++ b/awk/scheme/scheme/bin/compiler.awk
@@ -22,6 +22,14 @@
# - Stack clearing between expressions to prevent argument pollution
BEGIN {
+
+ # Debug mode configuration
+ # FIXME: Don't leave in, trigger on flag
+ print "[DEBUG_SEXPR] BEGIN block reached" > "/dev/stderr"
+ print "[DEBUG_SEXPR] ENVIRON[\"DEBUG_SEXPR\"] = " ENVIRON["DEBUG_SEXPR"] > "/dev/stderr"
+ DEBUG_SEXPR = (ENVIRON["DEBUG_SEXPR"] == "1") ? 1 : 0
+ if (DEBUG_SEXPR) print "[DEBUG_SEXPR] DEBUG_SEXPR is enabled" > "/dev/stderr"
+
# Compiler maintains internal state for code generation
curr_token = "" # Current token being processed by lexer
input_buffer = "" # Buffer for input text being tokenized
@@ -33,6 +41,7 @@ BEGIN {
# Unlike JS process.env, this is automatically available in awk
DEBUG = (ENVIRON["DEBUG"] == "1") ? 1 : 0
error_flag = 0 # Set to 1 if any error occurs
+ DEBUG_SEXPR = (ENVIRON["DEBUG_SEXPR"] == "1") ? 1 : 0
}
# Debug logging helper function
@@ -998,19 +1007,16 @@ function compile_define(args, name, params, body, param_array, nparams, i, paren
}
# Compiles lambda expressions (anonymous functions)
-function compile_lambda(args, params, body, param_array, nparams, i, lambda_name) {
+function compile_lambda(args, params, body, param_array, nparams, i, lambda_name, expr, op, rest, sexprs, nsexprs, j, first_body, last_body) {
+ if (DEBUG_SEXPR) print "[DEBUG_SEXPR] compile_lambda called" > "/dev/stderr"
# Generate a unique name for the lambda function
lambda_name = "__lambda_" next_label++
-
debug("compile_lambda: args = [" args "]")
-
# Handle both full lambda expression and just the arguments part
if (substr(args, 1, 7) == "(lambda") {
debug("compile_lambda: detected full lambda expression")
- # Full lambda expression: (lambda (params) body)
- args = substr(args, 8) # Remove "(lambda"
+ args = substr(args, 8)
debug("compile_lambda: after removing (lambda: [" args "]")
- # Find the closing parenthesis of the entire lambda expression
paren_count = 0
i = 1
while (i <= length(args)) {
@@ -1018,64 +1024,75 @@ function compile_lambda(args, params, body, param_array, nparams, i, lambda_name
if (c == "(") paren_count++
if (c == ")") {
paren_count--
- if (paren_count == -1) break # Found the closing paren of the lambda
+ if (paren_count == -1) break
}
i++
}
if (paren_count != -1) error("Unmatched parenthesis in lambda")
- args = substr(args, 1, i - 1) # Remove the closing parenthesis
+ args = substr(args, 1, i - 1)
debug("compile_lambda: after removing closing paren: [" args "]")
- # Remove leading whitespace
sub(/^[ \t\n]+/, "", args)
debug("compile_lambda: after removing leading whitespace: [" args "]")
}
-
# Split into parameters and body
if (substr(args, 1, 1) != "(") error("Malformed lambda expression")
-
- # Find matching closing parenthesis for parameters
paren_count = 1
i = 2
- # AWK FEATURE: length(string) returns the length of a string
- # Unlike JS string.length, this is a function call, not a property
while (paren_count > 0 && i <= length(args)) {
if (substr(args, i, 1) == "(") paren_count++
if (substr(args, i, 1) == ")") paren_count--
i++
}
if (paren_count > 0) error("Unmatched parenthesis in lambda parameters")
-
- params = substr(args, 2, i - 3) # Remove parentheses
+ params = substr(args, 2, i - 3)
body = substr(args, i)
-
- # Trim whitespace from body
sub(/^[ \t\n]+/, "", body)
sub(/[ \t\n]+$/, "", body)
-
debug("Lambda parameters: " params)
debug("Lambda body: " body)
-
- # Create function label
print "LABEL " lambda_name
-
- # Process parameters
- # AWK FEATURE: split(string, array, separator) splits string into array elements
- # Unlike JS string.split() which returns an array, this populates an existing array
nparams = split(params, param_array, " ")
for (i = 1; i <= nparams; i++) {
print "STORE " param_array[i]
}
-
- # Compile function body
- compile_expr(body)
-
- # Clean up parameters and return
+ # --- Use split_sexpressions for robust local define support ---
+ nsexprs = split_sexpressions(body, sexprs)
+ if (DEBUG_SEXPR) {
+ printf("[DEBUG_SEXPR] compile_lambda: processing %d expressions\n", nsexprs) > "/dev/stderr"
+ }
+ # Process all leading defines
+ j = 1
+ while (j <= nsexprs && substr(sexprs[j], 1, 7) == "(define") {
+ expr = sexprs[j]
+ if (DEBUG_SEXPR) printf("[DEBUG_SEXPR] local define: [%s]\n", expr) > "/dev/stderr"
+ op = substr(expr, 2, 6)
+ rest = substr(expr, 8)
+ compile_define(rest)
+ j++
+ }
+ # Remaining expressions are the body
+ first_body = j
+ last_body = nsexprs
+ for (i = first_body; i < last_body; i++) {
+ expr = sexprs[i]
+ sub(/^[ \t\n]+/, "", expr)
+ sub(/[ \t\n]+$/, "", expr)
+ if (DEBUG_SEXPR) printf("[DEBUG_SEXPR] body expr: [%s]\n", expr) > "/dev/stderr"
+ if (expr != "") compile_expr(expr)
+ }
+ # Only the last expression's value is returned
+ if (last_body >= first_body) {
+ expr = sexprs[last_body]
+ sub(/^[ \t\n]+/, "", expr)
+ sub(/[ \t\n]+$/, "", expr)
+ if (DEBUG_SEXPR) printf("[DEBUG_SEXPR] return expr: [%s]\n", expr) > "/dev/stderr"
+ if (expr != "") compile_expr(expr)
+ }
+ # --- End local define support ---
for (i = nparams; i >= 1; i--) {
print "POP_ENV"
}
print "RETURN"
-
- # Create closure that captures current environment
print "CAPTURE_ENV " lambda_name
print "PUSH_CONST CLOSURE:" lambda_name ":ENV_ID"
}
@@ -1389,4 +1406,57 @@ function error(msg) {
print "Error: " msg > "/dev/stderr"
error_flag = 1
exit 1
+}
+
+# Split a string into top-level S-expressions (returns count, fills sexpr_array)
+function split_sexpressions(str, sexpr_array, i, c, in_string, paren_count, current, n, in_comment) {
+ if (DEBUG_SEXPR) print "[DEBUG_SEXPR] split_sexpressions called" > "/dev/stderr"
+ in_string = 0
+ paren_count = 0
+ current = ""
+ n = 0
+ in_comment = 0
+ i = 1
+ while (i <= length(str)) {
+ c = substr(str, i, 1)
+ # Skip whitespace
+ if (!in_string && (c == " " || c == "\t" || c == "\n")) { i++; continue; }
+ # Skip comments (start with ; to end of line)
+ if (!in_string && c == ";") {
+ while (i <= length(str) && substr(str, i, 1) != "\n") i++;
+ i++; continue;
+ }
+ # Parse S-expression
+ current = ""
+ if (c == "(") {
+ paren_count = 0
+ while (i <= length(str)) {
+ c = substr(str, i, 1)
+ current = current c
+ if (c == "\"") in_string = !in_string
+ if (!in_string && c == "(") paren_count++
+ if (!in_string && c == ")") paren_count--
+ i++
+ if (paren_count == 0 && !in_string) break
+ }
+ sexpr_array[++n] = current
+ } else {
+ # Parse an atom
+ while (i <= length(str)) {
+ c = substr(str, i, 1)
+ if (!in_string && (c == " " || c == "\t" || c == "\n" || c == "(" || c == ")" || c == ";")) break;
+ if (c == "\"") in_string = !in_string
+ current = current c
+ i++
+ }
+ if (current != "") sexpr_array[++n] = current
+ }
+ }
+ if (DEBUG_SEXPR) {
+ printf("[DEBUG_SEXPR] split_sexpressions: found %d expressions\n", n) > "/dev/stderr"
+ for (i = 1; i <= n; i++) {
+ printf("[DEBUG_SEXPR] %d: [%s]\n", i, sexpr_array[i]) > "/dev/stderr"
+ }
+ }
+ return n
} \ No newline at end of file