Stack Evaluator API Reference¶
The stack evaluator module (jsl.stack_evaluator) provides a stack-based virtual machine for executing JSL programs compiled to JPN (JSL Postfix Notation).
Overview¶
The stack evaluator offers an alternative execution model to the recursive evaluator: - Linear execution of postfix instructions - Natural resumption support for distributed computing - Efficient resource tracking with step counting - Dict-based closures for JSON serialization
Classes¶
StackEvaluator¶
The main stack-based evaluator class:
jsl.stack_evaluator.StackEvaluator(env=None, resource_budget=None, host_dispatcher=None)
¶
Evaluator for postfix expressions using a value stack.
Initialize evaluator with optional environment and resource budget.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Optional[Env]
|
Environment for variable lookups (Env object) |
None
|
resource_budget
|
Optional[ResourceBudget]
|
Optional resource budget for tracking gas/memory |
None
|
host_dispatcher
|
Optional host dispatcher for side effects |
None
|
Source code in jsl/stack_evaluator.py
eval(instructions, state=None, env=None)
¶
Evaluate postfix instructions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instructions
|
List[Any]
|
List of postfix instructions |
required |
state
|
Optional[StackState]
|
Optional saved state for resumption |
None
|
env
|
Optional[Env]
|
Optional environment override (Env object) |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Result of evaluation |
Raises:
| Type | Description |
|---|---|
ValueError
|
On invalid instructions or stack underflow |
ResourceExhausted
|
When resource limits are exceeded |
Source code in jsl/stack_evaluator.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
eval_partial(instructions, max_steps, state=None)
¶
Evaluate with step limit for resumption.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instructions
|
List[Any]
|
Postfix instructions |
required |
max_steps
|
int
|
Maximum steps to execute |
required |
state
|
Optional[StackState]
|
Optional saved state |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Optional[Any], Optional[StackState]]
|
Tuple of (result, state) - result is None if not complete |
Raises:
| Type | Description |
|---|---|
ResourceExhausted
|
When resource limits are exceeded |
Source code in jsl/stack_evaluator.py
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 | |
StackState¶
Represents the state of the stack machine for resumption:
jsl.stack_evaluator.StackState(stack, pc, instructions, resource_checkpoint=None, env=None)
dataclass
¶
State of the stack evaluator, can be serialized for resumption.
from_dict(data, prelude_env=None)
classmethod
¶
Restore from dictionary.
Source code in jsl/stack_evaluator.py
to_dict()
¶
Convert to serializable dictionary.
Source code in jsl/stack_evaluator.py
Usage Examples¶
Basic Evaluation¶
from jsl.stack_evaluator import StackEvaluator
from jsl.compiler import compile_to_postfix
# Create evaluator
evaluator = StackEvaluator()
# Compile S-expression to JPN
expr = ["+", 1, 2, 3]
jpn = compile_to_postfix(expr) # [1, 2, 3, 3, "+"]
# Evaluate
result = evaluator.eval(jpn)
print(result) # Output: 6
Resumable Execution¶
from jsl.stack_evaluator import StackEvaluator
from jsl.compiler import compile_to_postfix
evaluator = StackEvaluator()
# Compile a complex expression
expr = ["*", ["+", 10, 20], ["-", 100, 50]]
jpn = compile_to_postfix(expr)
# Execute with step limit
result, state = evaluator.eval_partial(jpn, max_steps=3)
if state: # Execution paused
print(f"Paused at PC: {state.pc}")
print(f"Stack: {state.stack}")
# Resume execution
final_result, _ = evaluator.eval_partial(jpn, state=state)
print(f"Result: {final_result}") # Output: 1500
Working with Closures¶
from jsl.stack_evaluator import StackEvaluator
from jsl.compiler import compile_to_postfix
evaluator = StackEvaluator()
# Define a function
program = [
"do",
["def", "square", ["lambda", ["x"], ["*", "x", "x"]]],
["square", 5]
]
jpn = compile_to_postfix(program)
result = evaluator.eval(jpn)
print(result) # Output: 25
# The closure is stored as a dict
closure = evaluator.env.get("square")
print(closure["type"]) # "closure"
print(closure["params"]) # ["x"]
print(closure["body"]) # ["*", "x", "x"]
JPN Instruction Set¶
The stack evaluator processes these instruction types:
Values¶
- Literals: Numbers, strings, booleans, null, lists, dicts push themselves
- Variables: String identifiers trigger environment lookup
Operators¶
- N-ary operators: Preceded by arity count (e.g.,
3, "+"for 3-argument addition) - Built-in functions: Called like operators with arity
Special Forms¶
Opcode.SPECIAL_FORM: Marks special form instructionsOpcode.JUMP: Conditional/unconditional jumpsOpcode.JUMP_IF_FALSE: Jump if top of stack is falseOpcode.LAMBDA: Create closure from body and params
Stack Machine Architecture¶
Execution Model¶
- Program Counter (PC): Points to current instruction
- Operand Stack: Holds intermediate values
- Environment: Variable bindings (dict-based)
- Call Stack: For function calls (managed internally)
Instruction Processing¶
# Simplified execution loop
while pc < len(program):
instruction = program[pc]
if isinstance(instruction, (int, float, str, bool, type(None))):
stack.append(instruction)
elif instruction in operators:
arity = program[pc - 1]
args = [stack.pop() for _ in range(arity)]
result = operators[instruction](*reversed(args))
stack.append(result)
pc += 1
Differences from Recursive Evaluator¶
| Feature | Recursive Evaluator | Stack Evaluator |
|---|---|---|
| Execution | Tree walking | Linear instruction stream |
| Closures | Closure objects |
Dict representations |
| Resumption | Difficult | Natural with StackState |
| Performance | Good for small programs | Better for large programs |
| Debugging | Natural call stack | Requires PC tracking |
Integration with JSLRunner¶
The JSLRunner can use either evaluator:
from jsl.runner import JSLRunner
# Use stack evaluator (default)
runner_stack = JSLRunner(use_recursive_evaluator=False)
# Use recursive evaluator
runner_recursive = JSLRunner(use_recursive_evaluator=True)
# Both produce identical results
result1 = runner_stack.execute(["+", 1, 2, 3])
result2 = runner_recursive.execute(["+", 1, 2, 3])
assert result1 == result2 # True