Compare commits

...

2 Commits

Author SHA1 Message Date
Chris Wanstrath
43842adc87 TRY_CALL 2025-10-10 14:21:43 -07:00
Chris Wanstrath
8975bb91bd fix validator 2025-10-10 14:02:49 -07:00
8 changed files with 407 additions and 50 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

@ -30,11 +30,12 @@ function isValidIdentifier(name: string): boolean {
return !/[\s;()[\]{}='"#@.]/.test(name)
}
// Opcodes that require operands
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,
@ -46,7 +47,6 @@ const OPCODES_WITH_OPERANDS = new Set([
OpCode.CALL_NATIVE,
])
// Opcodes that should NOT have operands
const OPCODES_WITHOUT_OPERANDS = new Set([
OpCode.POP,
OpCode.DUP,
@ -78,6 +78,21 @@ const OPCODES_WITHOUT_OPERANDS = new Set([
OpCode.DICT_HAS,
])
// immediate = immediate number, eg #5
const OPCODES_REQUIRING_IMMEDIATE_OR_LABEL = new Set([
OpCode.JUMP,
OpCode.JUMP_IF_FALSE,
OpCode.JUMP_IF_TRUE,
OpCode.PUSH_TRY,
OpCode.PUSH_FINALLY,
])
// immediate = immediate number, eg #5
const OPCODES_REQUIRING_IMMEDIATE = new Set([
OpCode.MAKE_ARRAY,
OpCode.MAKE_DICT,
])
export function validateBytecode(source: string): ValidationResult {
const errors: ValidationError[] = []
const lines = source.split("\n")
@ -172,6 +187,26 @@ export function validateBytecode(source: string): ValidationResult {
// Validate specific operand formats
if (operand) {
if (OPCODES_REQUIRING_IMMEDIATE_OR_LABEL.has(opCode)) {
if (!operand.startsWith('#') && !operand.startsWith('.')) {
errors.push({
line: lineNum,
message: `${opName} requires immediate (#number) or label (.label), got: ${operand}`,
})
continue
}
}
if (OPCODES_REQUIRING_IMMEDIATE.has(opCode)) {
if (!operand.startsWith('#')) {
errors.push({
line: lineNum,
message: `${opName} requires immediate number (#count), got: ${operand}`,
})
continue
}
}
// Check for label references
if (operand.startsWith('.') && !operand.includes('(')) {
const labelName = operand.slice(1)
@ -246,7 +281,7 @@ export function validateBytecode(source: string): ValidationResult {
}
} else if (param.includes('=')) {
// Default parameter
const [name, defaultValue] = param.split('=')
const [name] = param.split('=')
if (!isValidIdentifier(name!.trim())) {
errors.push({
line: lineNum,
@ -294,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 })
})

View File

@ -200,3 +200,113 @@ test("formatValidationErrors produces readable output", () => {
expect(formatted).toContain("Line")
expect(formatted).toContain("UNKNOWN")
})
test("detects JUMP without # or .label", () => {
const source = `
JUMP 5
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(false)
expect(result.errors[0]!.message).toContain("JUMP requires immediate (#number) or label (.label)")
})
test("detects JUMP_IF_TRUE without # or .label", () => {
const source = `
PUSH true
JUMP_IF_TRUE 2
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(false)
expect(result.errors[0]!.message).toContain("JUMP_IF_TRUE requires immediate (#number) or label (.label)")
})
test("detects JUMP_IF_FALSE without # or .label", () => {
const source = `
PUSH false
JUMP_IF_FALSE 2
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(false)
expect(result.errors[0]!.message).toContain("JUMP_IF_FALSE requires immediate (#number) or label (.label)")
})
test("allows JUMP with immediate number", () => {
const source = `
JUMP #2
PUSH 999
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(true)
})
test("detects MAKE_ARRAY without #", () => {
const source = `
PUSH 1
PUSH 2
MAKE_ARRAY 2
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(false)
expect(result.errors[0]!.message).toContain("MAKE_ARRAY requires immediate number (#count)")
})
test("detects MAKE_DICT without #", () => {
const source = `
PUSH "key"
PUSH "value"
MAKE_DICT 1
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(false)
expect(result.errors[0]!.message).toContain("MAKE_DICT requires immediate number (#count)")
})
test("allows MAKE_ARRAY with immediate number", () => {
const source = `
PUSH 1
PUSH 2
MAKE_ARRAY #2
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(true)
})
test("detects PUSH_TRY without # or .label", () => {
const source = `
PUSH_TRY 5
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(false)
expect(result.errors[0]!.message).toContain("PUSH_TRY requires immediate (#number) or label (.label)")
})
test("detects PUSH_FINALLY without # or .label", () => {
const source = `
PUSH_FINALLY 5
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(false)
expect(result.errors[0]!.message).toContain("PUSH_FINALLY requires immediate (#number) or label (.label)")
})
test("allows PUSH_TRY with label", () => {
const source = `
PUSH_TRY .catch
PUSH 42
HALT
.catch:
PUSH null
HALT
`
const result = validateBytecode(source)
expect(result.valid).toBe(true)
})