Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions DIRECTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,24 @@ booleans, and literal strings work in single-file programs. Independent CLI
tests compare interpreter/native results and exercise diagnostics, evaluation
order, arithmetic traps, build safety, and optimized/UBSan C output.

The Rust [embedding prototype](docs/embedding.md) compiles in-memory libraries,
calls scalar functions, registers typed host callbacks, and returns failures as
data. Output is captured by the runtime. Heap-backed execution stacks and
per-call fuel bound script execution; callbacks remain trusted and memory is
unbounded. It is a prototype API, not a sandbox.

The [alpha contract](docs/alpha.md) defines implemented behavior. The wider
language proposal remains in the [README](README.md) and design notes.
Borrowing, resources, regions, JavaScript, and self-hosting are unimplemented;
memory feasibility and performance gates remain unperformed.

## Immediate priority

Make the existing interpreter embeddable for runtime scripts and plugins before
self-hosting. Hosts need to load and check source, register typed host functions,
call Chasm functions, and receive values and diagnostics without terminating the
host process. Runtime execution must work without an external C compiler.
Interpretation is the initial execution strategy; a JIT is a later optimization
subject to measured need and the same semantic conformance gates.
Finish and adversarially review the bounded embedding prototype, then wayfind
with Mia before selecting the next implementation slice. Compare its real host
integration and execution limits with the agent-authoring goals. Embedding
precedes self-hosting and runs without an external C compiler. A JIT is a later
optimization subject to measured need and the same semantic conformance gates.

Extend the working scalar core toward the bootstrap subset in thin slices.
Resolve copying versus resource ownership, borrow validity during storage changes,
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ single source file. It supports typed functions, mutable locals, `if`/`else`,
`while`, recursion, named arguments, checked 32-bit integers, booleans, and
string literals. See the [alpha contract](docs/alpha.md) for the implemented
syntax, commands, and limits, and [examples/](examples/) for runnable programs.
Rust applications can also run Chasm functions in-process; see
Comment thread
mia-riezebos marked this conversation as resolved.
Resolved
[Embedding](docs/embedding.md).

```sh
cargo test --workspace
Expand Down Expand Up @@ -103,8 +105,8 @@ Runtime scripting and plugins are core requirements. An application should be
able to load Chasm source, check it, and execute it through an embedded runtime
without an external C compiler. The typed-IR interpreter is the initial path;
a bytecode VM or JIT can improve execution speed later. Embedding comes before
self-hosting. The alpha currently provides CLI interpretation through `chasm run`;
it has no public embedding API or JIT.
self-hosting. The alpha provides CLI interpretation through `chasm run` and a
prototype Rust [embedding API](docs/embedding.md); it has no JIT.

The runtime also supports the planned REPL, hot module replacement, and local development. Native compilation supports release binaries, servers, desktop applications, and command-line tools. JavaScript compilation supports browsers, Node.js, and worker runtimes without requiring WebAssembly.

Expand Down
22 changes: 14 additions & 8 deletions docs/alpha.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,11 @@ Precedence runs from loosest to tightest: `or`, `and`, `not`, comparisons,
left-associative. Comparisons do not chain: `a < b < c` is an error.

Nesting is limited to 200 levels. Each block, `else if`, parenthesized
expression, call argument, condition, unary `-` or `not`, and each binary
operator in a chain such as `1 + 2 + 3` adds a level while it is open, so a
chain of more than about 200 operators in one expression is rejected. Split
long expressions with `let`.
expression, call argument, condition, unary `-` or `not`, and binary operator
adds a level. In a chain such as `1 + 2 + 3`, each operator nests everything
to its left one level deeper, so a chain of more than about 200 operators in
one expression is rejected. Parentheses do not reset the count. Split long
expressions with `let`.

### Declarations and names

Expand Down Expand Up @@ -246,9 +247,10 @@ before the panic is written to stdout first.
| `call depth limit exceeded` | a call would make more than 10000 calls active at once, counting `main` |

The interpreter and native executables apply the same call-count guard. Their
host resource limits differ: the interpreter uses a 512 MiB worker stack, while
native executables use the platform's main-thread stack. Large frames or deep
recursion can exhaust either stack before the guard is reached. Host memory or
host resource limits differ: the interpreter keeps calls and blocks on the heap,
so recursion reaches the guard without using the host stack, while native
executables use the platform's main-thread stack, which large frames or deep
recursion can exhaust before the guard is reached. Host memory or
stack exhaustion is outside the portable contract and may terminate execution
without a Chasm panic. Infinite loops run forever on both lanes while host
resources remain available.
Expand All @@ -263,10 +265,14 @@ with status 1, while native executables ignore them.

```text
source → lexer → parser → checker + lowering → typed IR → IR validator
├── interpreter (run)
├── interpreter (run, embedding)
└── C emitter → cc (emit c, build)
```

The crate is also a library: Rust applications can compile source and call
its functions through the interpreter. [Embedding](embedding.md) describes that
API.

- The IR is structured: blocks, `if`, `loop`, `break`, and `return`. Every
operand is a variable or a constant, and every operation stores into a
variable, so evaluation order is fixed in the IR rather than left to C.
Expand Down
156 changes: 156 additions & 0 deletions docs/embedding.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Embedding Chasm

> **Status:** prototype on the `0.1.0-alpha.1` scalar language. The API may
> change in any release. It runs trusted host code with untrusted-script
> limits on fuel and call depth only; it is not a sandbox.

The `chasm` crate in `host/` is a library as well as the CLI. A Rust
application compiles Chasm source in memory, registers host functions that
scripts may call, and calls script functions by name. Execution uses the
interpreter, so no C compiler is involved. The language is the one
[the alpha contract](alpha.md) describes.

```rust
use chasm::{CallError, Runtime, Value};

let mut runtime = Runtime::new();
runtime.register("double", |n: i32| -> Result<i32, String> {
n.checked_mul(2).ok_or_else(|| "too large".into())
})?;

let script = runtime.compile("fn quadruple(n: Int) -> Int {\n return double(double(n))\n}")?;
assert_eq!(runtime.call(&script, "quadruple", &[5.into()])?, Some(Value::Int(20)));

match runtime.call(&script, "quadruple", &[i32::MAX.into()]) {
Err(CallError::Host { function, message, span }) => { /* "double", "too large", 2:16 */ }
other => { /* ... */ }
}
```

`host/examples/embed.rs` is a complete program with a stateful wallet
capability, a host error, an arithmetic panic, fuel exhaustion, and a
successful call afterwards. Run it from `host/` with
`cargo run --example embed`.

## API

| Item | Purpose |
| --- | --- |
| `Runtime::new()` | A runtime with no host functions and the default fuel. |
| `runtime.register(name, f)` | Lets scripts compiled afterwards call `f` as `name`. |
| `runtime.compile(source)` | Checks source into a `Script`, or returns `CompileError`. |
| `runtime.call(&script, name, &args)` | Calls a script function; returns `Option<Value>` or `CallError`. |
| `runtime.set_fuel(n)` | Sets the fuel each later call starts with. |
| `runtime.take_output()` | Returns and clears the text `print` has written. |

`Value` is `Int(i32)`, `Bool(bool)`, or `String(String)`, with `From`
conversions from `i32`, `bool`, `String`, and `&str`. A function without a
return type returns `None`. Returned strings are owned by the caller.

### Libraries

`compile` treats source as a library: a list of functions with no `main`
required. `main` is an ordinary function name there. The CLI still requires
`fn main()`.

### Host functions

A host function's Rust signature sets its Chasm signature. Parameters are
`i32` (Int), `bool` (Bool), or `String`, up to four of them. The closure
returns `Result<R, String>`, where `R` is one of those types or `()` for no
value. The compiler checks every script call against that signature, so a
callback only ever receives arguments of its declared types, and its result
type is fixed by Rust.

- Scripts call host functions by bare name, positionally. Host parameters
have no names; diagnostics call them `#1`, `#2`, and so on.
- `register` rejects names that are not identifiers or are keywords or
reserved words (`RegisterError::InvalidName`), and `print` or an already
registered name (`RegisterError::Taken`).
- A script that defines a function with a host function's name does not
compile.
- Registrations are permanent and append-only. A script's host calls are
bound when it compiles, and it runs only on the runtime that compiled it
(`CallError::ForeignScript` otherwise). A function registered later is
visible only to scripts compiled later.
- An `Err(message)` from a callback stops the script with
`CallError::Host { function, message, span }`, where `span` is the call site.

### Errors

`CompileError::Source` holds the diagnostics the CLI would print, each with a
`span` (1-based line and column) and a `message`. `CompileError::Internal`
reports a compiler bug.

`CallError` variants:

| Variant | Meaning | Did anything run? |
| --- | --- | --- |
| `UnknownFunction` | The script has no function by that name. | No |
| `Arguments` | Wrong argument count or types. | No |
| `ForeignScript` | Another runtime compiled the script. | No |
| `Panic { message, span }` | `integer overflow`, `division by zero`, or `call depth limit exceeded`. | Yes |
| `OutOfFuel` | The call used up its fuel. | Yes |
| `Host { function, message, span }` | A host function returned `Err`. | Yes |

Errors are values: nothing is printed and the process does not exit. A
failed call's effects stay: host callbacks it already made and output it
already printed are not rolled back. The runtime keeps no other state
between calls, so the next call starts with fresh fuel and an empty call
stack. A rejected source leaves the runtime unchanged.

### Output

`print` appends to a buffer the runtime owns, never to the process's stdout
or stderr. `take_output` returns and clears it. The buffer grows until taken;
fuel bounds how many lines one call can print.

## Execution limits

| Limit | Default | Notes |
| --- | --- | --- |
| Fuel | 1,000,000 per call | One unit per IR statement executed and per loop iteration. Configurable. |
| Call depth | 10,000 active calls | The language's limit, counting the entry call and host calls. Not configurable. |

- **Fuel** is deterministic: the same script, arguments, and host results use
the same fuel and fail at the same point, including loops whose conditions
call host functions. The unit depends on the compiler's IR, so counts may
change between releases. Fuel is not a time limit: it does not run while a
host callback runs. `set_fuel(0)` fails any call that executes a statement;
`set_fuel(u64::MAX)` is effectively unlimited, so an infinite loop runs
until it exhausts that budget or execution is terminated externally.
- **Call depth** past the limit is `CallError::Panic` with
`call depth limit exceeded`, as in the CLI.
- **Host stack.** The interpreter keeps calls and nested blocks in heap
vectors, so script recursion and nesting do not grow the Rust stack. The
compiler passes and IR destruction still use the Rust stack. The
200-level syntax limit bounds nesting, not stack usage in bytes. The
integration suite compiles and runs a 120-block recursive function on
a 2 MiB thread in debug and release; arbitrary small host stacks are
unsupported.
- **Heap.** Memory grows with the active call depth times each function's
locals and nesting, plus string sizes and the output buffer. There is no
memory budget; allocation failure behaves as it does elsewhere in Rust.

## Trust model

Host callbacks are trusted code. They run synchronously on the calling thread,
fuel cannot interrupt them, and they may block, loop, or panic. A callback
panic unwinds out of `Runtime::call`; the runtime holds no partial state, so
a host that catches the panic can keep using it. Callbacks cannot call back
into the runtime, since `call` holds it mutably.

Scripts can affect the world only through registered host functions and
`print`. The runtime does not limit memory or wall-clock time and gives no
process isolation, so do not treat it as a security boundary.

`Runtime` and `Script` are not `Send`: callbacks may capture `Rc` state, and
scripts share string literals through `Rc`. Create and use them on one
thread.

## Not included

Modules and imports, borrows and resources, typed call entry points (`call`
takes `&[Value]`), host functions with more than four parameters,
reentrant callbacks, async or suspended execution, hot reloading, a JIT, and
memory or time budgets.
84 changes: 84 additions & 0 deletions host/examples/embed.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//! Runs a Chasm script inside a Rust application.
//!
//! The host owns a wallet balance and lends scripts two capabilities:
//! `withdraw` and `log`. Each call's failure comes back as a value, and the
//! runtime keeps working afterwards.
//!
//! Run with `cargo run --example embed` from `host/`.

use std::cell::Cell;
use std::rc::Rc;

use chasm::{Runtime, Value};

const SCRIPT: &str = r#"
fn checkout(price: Int, quantity: Int) -> Int {
let total = price * quantity
let left = withdraw(total)
log("paid")
print(left)
return left
}

fn spin() {
while true {
}
}
"#;

fn main() {
let balance = Rc::new(Cell::new(100));
let mut runtime = Runtime::new();

let wallet = Rc::clone(&balance);
runtime
.register("withdraw", move |amount: i32| -> Result<i32, String> {
if amount < 0 {
return Err(format!("cannot withdraw a negative amount ({amount})"));
}
if amount > wallet.get() {
return Err(format!(
"cannot withdraw {amount}; the balance is {}",
wallet.get()
));
}
wallet.set(wallet.get() - amount);
Ok(wallet.get())
})
.expect("`withdraw` is a valid, unused name");
runtime
.register("log", |message: String| -> Result<(), String> {
println!(" host log: {message}");
Ok(())
})
.expect("`log` is a valid, unused name");

let script = match runtime.compile(SCRIPT) {
Ok(script) => script,
Err(error) => {
eprintln!("{error}");
std::process::exit(1);
}
};
runtime.set_fuel(10_000);

let calls: [(&str, Vec<Value>); 5] = [
("checkout", vec![30.into(), 2.into()]),
("checkout", vec![50.into(), 1.into()]),
("checkout", vec![i32::MAX.into(), 2.into()]),
("spin", vec![]),
("checkout", vec![10.into(), 1.into()]),
];
for (name, args) in calls {
println!("{name}({args:?})");
match runtime.call(&script, name, &args) {
Ok(value) => println!(" returned {value:?}"),
Err(error) => println!(" failed: {error}"),
}
let printed = runtime.take_output();
if !printed.is_empty() {
print!(" script printed: {printed}");
}
println!(" balance: {}", balance.get());
}
}
3 changes: 3 additions & 0 deletions host/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ pub enum Stmt {
pub struct Expr {
pub kind: ExprKind,
pub span: Span,
/// Levels of expression below this one; 0 for a leaf. The parser bounds it
/// so the recursive passes stay off the end of the host stack.
pub height: u32,
}

pub enum ExprKind {
Expand Down
14 changes: 11 additions & 3 deletions host/src/diag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub struct Span {
}

/// One compile error, rendered as `PATH:LINE:COLUMN: error: MESSAGE`.
#[derive(Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diagnostic {
pub span: Span,
pub message: String,
Expand All @@ -24,8 +24,16 @@ impl Diagnostic {
}

pub fn render(&self, path: &str) -> String {
format!(
"{path}:{}:{}: error: {}",
format!("{path}:{self}")
}
}

/// `LINE:COLUMN: error: MESSAGE`, for source without a path.
impl std::fmt::Display for Diagnostic {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{}:{}: error: {}",
self.span.line, self.span.col, self.message
)
}
Expand Down
Loading
Loading