This commit is contained in:
Chris Wanstrath 2025-10-10 14:21:43 -07:00
parent 8975bb91bd
commit 43842adc87
7 changed files with 261 additions and 47 deletions

View File

@ -219,6 +219,7 @@ CALL
- `CALL` - Call function (see calling convention above)
- `TAIL_CALL` - Tail-recursive call (no stack growth)
- `RETURN` - Return from function (pops return value)
- `TRY_CALL <name>` - Call function (if found), push value (if exists), or push name as string (if not found)
- `BREAK` - Exit iterator/loop (unwinds to break target)
### Arrays
@ -404,6 +405,32 @@ STORE factorial
TAIL_CALL ; Reuses stack frame
```
### Optional Function Calls (TRY_CALL)
Call function if defined, otherwise use value or name as string:
```
; Define optional hook
MAKE_FUNCTION () .onInit
STORE onInit
; Later: call if defined, skip if not
TRY_CALL onInit ; Calls onInit() if it's a function
; Pushes value if it exists but isn't a function
; Pushes "onInit" as string if undefined
; Use with values
PUSH 42
STORE answer
TRY_CALL answer ; Pushes 42 (not a function)
; Use with undefined
TRY_CALL unknown ; Pushes "unknown" as string
```
**Use Cases**:
- Optional hooks/callbacks in DSLs
- Shell-like languages where unknown identifiers become strings
- Templating systems with optional transformers
## Key Concepts
### Truthiness

37
SPEC.md
View File

@ -404,6 +404,43 @@ The created function captures `currentScope` as its `parentScope`.
**Errors**: Throws if no call frame to return from
#### TRY_CALL
**Operand**: Variable name (string)
**Effect**: Conditionally call function or push value/string onto stack
**Stack**: [] → [returnValue | value | name]
**Errors**: Never throws (unlike CALL)
**Behavior**:
1. Look up variable by name in scope chain
2. **If variable is a function**: Call it with 0 arguments (no positional, no named) and push the returned value onto the stack.
3. **If variable exists but is not a function**: Push the variable's value onto stack
4. **If variable doesn't exist**: Push the variable name as a string onto stack
**Use Cases**:
- DSL/templating languages with "call if callable, otherwise use as literal" semantics
- Shell-like behavior where unknown identifiers become strings
- Optional function hooks (call if defined, silently skip if not)
**Implementation Note**:
- Uses intentional fall-through in VM switch statement from TRY_CALL to CALL case
- When function is found, stacks are set up to match CALL's expectations exactly
- No break target marking or frame pushing occurs when non-function value is found
**Example**:
```
MAKE_FUNCTION () .body
STORE greet
PUSH 42
STORE answer
TRY_CALL greet ; Calls function greet(), returns its value
TRY_CALL answer ; Pushes 42 (number value)
TRY_CALL unknown ; Pushes "unknown" (string)
.body:
PUSH "Hello!"
RETURN
```
### Array Operations
#### MAKE_ARRAY

View File

@ -27,6 +27,7 @@ type InstructionTuple =
// Variables
| ["LOAD", string]
| ["STORE", string]
| ["TRY_LOAD", string]
// Arithmetic
| ["ADD"] | ["SUB"] | ["MUL"] | ["DIV"] | ["MOD"]
@ -54,6 +55,7 @@ type InstructionTuple =
| ["CALL"]
| ["TAIL_CALL"]
| ["RETURN"]
| ["TRY_CALL", string]
// Arrays
| ["MAKE_ARRAY", number]
@ -329,6 +331,8 @@ function toBytecodeFromArray(program: ProgramItem[]): Bytecode /* throws */ {
case "LOAD":
case "STORE":
case "TRY_LOAD":
case "TRY_CALL":
case "CALL_NATIVE":
operandValue = operand as string
break

View File

@ -44,6 +44,7 @@ export enum OpCode {
CALL, // operand: none | stack: [fn, ...args, posCount, namedCount] → [result] | marks break target
TAIL_CALL, // operand: none | stack: [fn, ...args, posCount, namedCount] → [result] | reuses frame
RETURN, // operand: none | stack: [value] → (restored with value) | return from function
TRY_CALL, /// operand: variable name (identifier) | stack: [] → [value] | call a function, load a variable, or load a string
// arrays
MAKE_ARRAY, // operand: item count (number) | stack: [item1, ..., itemN] → [array]

View File

@ -34,6 +34,8 @@ const OPCODES_WITH_OPERANDS = new Set([
OpCode.PUSH,
OpCode.LOAD,
OpCode.STORE,
OpCode.TRY_LOAD,
OpCode.TRY_CALL,
OpCode.JUMP,
OpCode.JUMP_IF_FALSE,
OpCode.JUMP_IF_TRUE,
@ -327,8 +329,9 @@ export function validateBytecode(source: string): ValidationResult {
}
}
// Validate variable names for LOAD/STORE
if ((opCode === OpCode.LOAD || opCode === OpCode.STORE) &&
// Validate variable names for LOAD/STORE/TRY_LOAD/TRY_CALL
if ((opCode === OpCode.LOAD || opCode === OpCode.STORE ||
opCode === OpCode.TRY_LOAD || opCode === OpCode.TRY_CALL) &&
!isValidIdentifier(operand)) {
errors.push({
line: lineNum,

View File

@ -353,6 +353,27 @@ export class VM {
})
break
// @ts-ignore
case OpCode.TRY_CALL: {
const varName = instruction.operand as string
const value = this.scope.get(varName)
if (value?.type === 'function') {
this.stack.push(value)
this.stack.push(toValue(0))
this.stack.push(toValue(0))
// No `break` here -- we want to fall through to OpCode.CALL!
} else if (value) {
this.stack.push(value)
break
} else {
this.stack.push(toValue(varName))
break
}
}
// don't put any `case` statement here - `TRY_CALL` MUST go before `CALL!`
case OpCode.CALL: {
// Pop named count from stack (top)
const namedCount = toNumber(this.stack.pop()!)

View File

@ -375,3 +375,124 @@ test("CALL - named args with defaults on fixed params", async () => {
// x should use default value 5
expect(result).toEqual({ type: 'number', value: 5 })
})
test("TRY_CALL - calls function if found", async () => {
const bytecode = toBytecode([
["MAKE_FUNCTION", [], ".body"],
["STORE", "myFunc"],
["TRY_CALL", "myFunc"],
["HALT"],
[".body:"],
["PUSH", 42],
["RETURN"]
])
const result = await new VM(bytecode).run()
expect(result).toEqual({ type: 'number', value: 42 })
})
test("TRY_CALL - pushes value if variable exists but is not a function", async () => {
const bytecode = toBytecode([
["PUSH", 99],
["STORE", "myVar"],
["TRY_CALL", "myVar"],
["HALT"]
])
const result = await new VM(bytecode).run()
expect(result).toEqual({ type: 'number', value: 99 })
})
test("TRY_CALL - pushes string if variable not found", async () => {
const bytecode = toBytecode([
["TRY_CALL", "unknownVar"],
["HALT"]
])
const result = await new VM(bytecode).run()
expect(result).toEqual({ type: 'string', value: 'unknownVar' })
})
test("TRY_CALL - handles arrays", async () => {
const bytecode = toBytecode([
["PUSH", 1],
["PUSH", 2],
["MAKE_ARRAY", 2],
["STORE", "myArray"],
["TRY_CALL", "myArray"],
["HALT"]
])
const result = await new VM(bytecode).run()
expect(result.type).toBe('array')
if (result.type === 'array') {
expect(result.value).toEqual([
{ type: 'number', value: 1 },
{ type: 'number', value: 2 }
])
}
})
test("TRY_CALL - handles dicts", async () => {
const bytecode = toBytecode([
["PUSH", "key"],
["PUSH", "value"],
["MAKE_DICT", 1],
["STORE", "myDict"],
["TRY_CALL", "myDict"],
["HALT"]
])
const result = await new VM(bytecode).run()
expect(result.type).toBe('dict')
if (result.type === 'dict') {
expect(result.value.get('key')).toEqual({ type: 'string', value: 'value' })
}
})
test("TRY_CALL - handles null values", async () => {
const bytecode = toBytecode([
["PUSH", null],
["STORE", "myNull"],
["TRY_CALL", "myNull"],
["HALT"]
])
const result = await new VM(bytecode).run()
expect(result).toEqual({ type: 'null', value: null })
})
test("TRY_CALL - function can access its parameters", async () => {
const bytecode = toBytecode([
["MAKE_FUNCTION", ["x"], ".body"],
["STORE", "addFive"],
["PUSH", 10],
["STORE", "x"],
["TRY_CALL", "addFive"],
["HALT"],
[".body:"],
["LOAD", "x"],
["PUSH", 5],
["ADD"],
["RETURN"]
])
const result = await new VM(bytecode).run()
// Function is called with 0 args, so x inside function should be null
// Then we add 5 to null (which coerces to 0)
expect(result).toEqual({ type: 'number', value: 5 })
})
test("TRY_CALL - with string format", async () => {
const bytecode = toBytecode(`
MAKE_FUNCTION () #4
STORE myFunc
TRY_CALL myFunc
HALT
PUSH 100
RETURN
`)
const result = await new VM(bytecode).run()
expect(result).toEqual({ type: 'number', value: 100 })
})