Runner API¶
Overview¶
The JSL Runner API provides the core execution engine for JSL programs, handling evaluation, environment management, and host interaction coordination.
Core Classes¶
JSL Runner - High-level execution interface
This module provides the JSLRunner class and related utilities for executing JSL programs with advanced features like environment management, host interaction, and performance monitoring.
JSLRunner(config=None, security=None, resource_limits=None, host_gas_policy=None, use_recursive_evaluator=False)
¶
High-level JSL execution engine with advanced features.
Initialize JSL runner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Optional[Dict[str, Any]]
|
Configuration options (recursion depth, debugging, etc.) |
None
|
security
|
Optional[Dict[str, Any]]
|
Security settings (allowed commands, sandbox mode, etc.) |
None
|
resource_limits
|
Optional[ResourceLimits]
|
Resource limits for execution |
None
|
host_gas_policy
|
Optional[HostGasPolicy]
|
Gas cost policy for host operations |
None
|
use_recursive_evaluator
|
bool
|
If True, use recursive evaluator instead of stack (default: False) |
False
|
Source code in jsl/runner.py
add_host_handler(command, handler)
¶
Add a host command handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
Command name (e.g., "file", "time") |
required |
handler
|
Any
|
Handler object or function |
required |
Source code in jsl/runner.py
disable_profiling()
¶
enable_profiling()
¶
execute(expression)
¶
Execute a JSL expression.
Supports multiple input formats: - S-expression Lisp style: "(+ 1 2 3)" - S-expression JSON style: "["+", 1, 2, 3]" - JPN postfix compiled: "[1, 2, 3, 3, "+"]"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression
|
Union[str, JSLExpression]
|
JSL expression as string or parsed structure |
required |
Returns:
| Type | Description |
|---|---|
JSLValue
|
The result of evaluating the expression |
Raises:
| Type | Description |
|---|---|
JSLSyntaxError
|
If the expression is malformed |
JSLRuntimeError
|
If execution fails |
Source code in jsl/runner.py
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 | |
get_performance_stats()
¶
Get performance statistics.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with performance metrics including: |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Source code in jsl/runner.py
new_environment()
¶
Create a new isolated environment context.
Yields:
| Name | Type | Description |
|---|---|---|
ExecutionContext |
New execution context |
Source code in jsl/runner.py
ExecutionContext(environment, parent=None)
¶
JSLRuntimeError(message, remaining_expr=None, env=None)
¶
JSLSyntaxError
¶
Bases: Exception
Syntax error in JSL code.
Usage Examples¶
Basic Program Execution¶
from jsl.runner import JSLRunner
# Create runner instance
runner = JSLRunner()
# Execute simple expression
result = runner.execute(["+", 1, 2])
print(result) # Output: 3
# Execute with variables
runner.define("x", 10)
result = runner.execute(["*", "x", 2])
print(result) # Output: 20
Environment Management¶
# Create isolated environment
with runner.new_environment() as env:
env.define("temp_var", 42)
result = env.execute(["*", "temp_var", 2])
print(result) # Output: 84
# temp_var is no longer accessible
Closure Execution¶
# Define function
runner.execute(["def", "square", ["lambda", ["x"], ["*", "x", "x"]]])
# Call function
result = runner.execute(["square", 5])
print(result) # Output: 25
# Access function object
square_fn = runner.get_variable("square")
print(square_fn.params) # Output: ["x"]
print(square_fn.body) # Output: ["*", "x", "x"]
Host Interaction¶
from jsl.runner import JSLRunner
from jsl.jhip import FileHandler
# Configure with host handlers
runner = JSLRunner()
runner.add_host_handler("file", FileHandler())
# Execute host interaction
result = runner.execute(["host", "file/read", "/tmp/data.txt"])
Error Handling¶
try:
result = runner.execute(["undefined_function", 1, 2])
except JSLRuntimeError as e:
print(f"Runtime error: {e}")
except JSLSyntaxError as e:
print(f"Syntax error: {e}")
Configuration Options¶
Runner Configuration¶
config = {
"max_recursion_depth": 1000,
"max_steps": 10000, # Limit evaluation steps (None for unlimited)
"enable_debugging": True,
"timeout_seconds": 30,
"memory_limit_mb": 512
}
runner = JSLRunner(config=config)
Security Settings¶
# Restrict to specific host commands
security_config = {
"allowed_host_commands": ["file/read", "time/now"]
}
runner = JSLRunner(security=security_config)
# Sandbox mode - blocks all host commands unless explicitly allowed
sandbox_config = {
"sandbox_mode": True,
"allowed_host_commands": ["safe_operation"] # Only this is allowed
}
sandbox_runner = JSLRunner(security=sandbox_config)
# Complete sandbox - no host operations
strict_sandbox = JSLRunner(security={"sandbox_mode": True})
Step Limiting and Resumption¶
JSL supports limiting the number of evaluation steps to prevent DOS attacks and enable fair resource allocation in distributed environments:
# Create runner with step limit
runner = JSLRunner(config={"max_steps": 1000})
try:
result = runner.execute(complex_expression)
except JSLRuntimeError as e:
if "Step limit exceeded" in str(e):
# Can resume with additional steps
if hasattr(e, 'remaining_expr'):
result = runner.resume(
e.remaining_expr,
e.env,
additional_steps=500
)
This enables:
- DOS Prevention: Limits computation to prevent infinite loops
- Fair Resource Allocation: In multi-tenant environments
- Pauseable Computation: Serialize and resume long-running tasks
- Step Accounting: Track resource usage per user/request
Performance Monitoring¶
# Enable performance tracking
runner.enable_profiling()
# Execute expressions
runner.execute('["*", 10, 20]') # Parse from JSON
runner.execute(["+", 1, 2, 3]) # Direct expression
# Get performance metrics
stats = runner.get_performance_stats()
print(f"Total time: {stats['total_time_ms']}ms")
print(f"Parse time: {stats.get('parse_time_ms', 0)}ms")
print(f"Eval time: {stats['eval_time_ms']}ms")
print(f"Call count: {stats['call_count']}")
print(f"Errors: {stats.get('error_count', 0)}")
# Reset stats
runner.reset_performance_stats()
# Disable profiling
runner.disable_profiling()