Skip to content
Merged
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
25 changes: 25 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,28 @@ jobs:
exit 1
fi
done

contract:
name: Language contract tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'

# Static checks always run: grammar JSON, keyword list, documentation
# claims, and fixture shape. The fixture-execution test is skipped here
# because it needs a built pd-vm-run, which this repository does not ship.
- name: Static contract checks
run: node --test --test-skip-pattern='executes the fixture' tests/option-result-contract.test.mjs

# Opt in to real execution by setting a repository variable named
# RUSTSCRIPT_CORE_BIN to the absolute path of pd-vm-run on the runner.
# Without it the step is skipped; the same command fails loudly when run
# locally with RUSTSCRIPT_CORE_BIN unset, so execution is never assumed.
- name: Fixture execution against pd-vm-run
if: vars.RUSTSCRIPT_CORE_BIN != ''
env:
RUSTSCRIPT_CORE_BIN: ${{ vars.RUSTSCRIPT_CORE_BIN }}
run: node --test tests/option-result-contract.test.mjs
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,47 @@ The specification is implementation-derived, but the public text is intentionall
- [Debugger conventions](runtime/debugger.md)
- [Host functions](runtime/host-functions.md)

## Values: Unit, Option, and Result

RustScript has no `null` literal and no `T?` optional type. Absence and failure are explicit values:

```rss
let unit: () = (); // Unit
let some: Option<int> = Option::Some(0); // present
let none: Option<int> = Option::None; // absent
let ok: Result<int, string> = Result::Ok(1);
let err: Result<int, string> = Result::Err("bad input");
```

- `()` is Unit. Its physical carrier is the VM's internal Null value, but Unit is a logical type and is not a nullable value.
- `Option<T>` wraps at most one value, selected by the carrier's Boolean `tag`. `Some(0)`, `Some(false)`, `Some("")`, and `Some(())` are present values; payload truthiness never selects `None`.
- `Result<T, E>` is a built-in typed success-or-guest-error value. Both parameters are required.
- `?` is expression-level propagation: `Option` passes `Some` through and exits the enclosing `Option`-returning function or closure on `None`; `Result` passes `Ok` through and returns the exact `Err` from the enclosing `Result`-returning function. Error types must match; use `map_err` or `.ok_or(...)` at the boundary.
- `?.` is fallible projection and yields an `Option`.
- A host returns a guest option as `GuestOption<T>` and a guest result as `GuestResult<T, E>`, with the outer `VmResult` reserved for fatal transport failures. See [Host functions](runtime/host-functions.md).

## Contract tests

The language contract is checked by a dependency-free Node test that validates the grammar JSON, the keyword list, the documentation claims, and the fixture below:

```sh
node --test tests/option-result-contract.test.mjs
```

The fixture `tests/fixtures/option-result.rss` is executed by the same test when `RUSTSCRIPT_CORE_BIN` points at a built `pd-vm-run`:

```sh
RUSTSCRIPT_CORE_BIN=/path/to/pd-vm-run node --test tests/option-result-contract.test.mjs
```

Without `RUSTSCRIPT_CORE_BIN` the fixture-execution test fails with an explicit error; it is never skipped silently, because a skipped execution check would report success without running anything. To run only the static checks while a binary is unavailable:

```sh
node --test --test-skip-pattern='executes the fixture' tests/option-result-contract.test.mjs
```

`--test-skip-pattern` is the flag that actually filters under current Node releases; `--test-name-pattern` does not exclude the fixture-execution test, so this document, the test header, and CI all use the skip pattern.

## Scope

This draft covers:
Expand Down
35 changes: 31 additions & 4 deletions formats/bytecode.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,37 @@ A bytecode artifact contains these logical sections:

## Versioning

The header declares a bytecode format version. A VM must reject bytecode with an unsupported major version. Minor-version changes may add optional sections or metadata, but must not change the meaning of existing instructions.
The current bytecode format is **VMBC v14**. A VM must reject bytecode whose version is not the current version.

Artifacts may also declare feature flags. A VM must reject an artifact that requires a feature it does not support.
There is one current schema layout and no compatibility layer: no legacy reader, no legacy adapter, and no version-dependent writer. Artifacts may declare feature flags; a VM must reject an artifact that requires a feature it does not support. Unknown schema tags, malformed carriers, and invalid schema budgets are rejected rather than repaired.

## Constant pool

The constant pool stores reusable literals and symbols. Primitive literals include null, booleans, integers, floats, strings, and bytes. Compound values may be represented directly or constructed by instructions, depending on the encoder.
The constant pool stores reusable literals and symbols. Primitive constants include booleans, integers, floats, strings, bytes, and the internal Null value that carries logical Unit. There is no source-level `null` literal, so the only Null constants are the Unit carrier and positions where the selected schema permits a missing payload.

Compound values may be represented directly or constructed by instructions, depending on the encoder.

Constant entries are immutable. Mutable arrays, maps, or objects created during execution must be runtime values, not shared mutable constants.

## Logical values: Unit, Option, Result

Type metadata carries logical schemas, and the physical carrier does not by itself define the logical type.

**Unit** has schema `()` and uses the internal Null value as its physical carrier. A Unit slot is not a nullable slot: an explicit source `null` is never inferred into Unit, and a Null value is Unit only where the declared schema is `()`. Under any other declared schema a Null is not a Unit value, and it is malformed where that schema requires a real payload.

**Option** has a logical `Option<T>` schema and a Map carrier with a Boolean `tag`:

- `tag: true` is `Some`, with the active value under `payload`;
- `tag: false` is `None`, and a `None` carrier has no active `payload` entry.

A non-Boolean or missing tag, extra fields, or a payload on `None` are malformed and fail validation. `Some(())` uses the internal Null value as its payload, and a canonicalizing writer may omit a Null-valued payload entry; a tag-only `Some` is restored only when the declared payload schema is logical Unit, while a missing payload under any other payload schema is malformed.

**Result** has a logical `Result<T, E>` schema that preserves both the `ok` and `err` schemas, and the same Map carrier convention: Boolean `tag` where `true` is `Ok`, with the selected value under `payload`. A missing payload means Null only when the selected schema permits it. A missing or non-Boolean tag, extra fields, or a wrong selected payload fail validation. Raw map construction does not establish guest `Result` typing.

Schema tags are part of the current wire contract. Host schemas encode logical Option with tag `15` and Unit with tag `16`; compiler schemas use tag `19` for Option and tag `20` for Unit. Existing tag numbers and builtin IDs are unchanged by this contract. A `Result` schema is encoded as its own schema variant with both parameters, so the two payload schemas survive typing, ownership, and serialization; substituting `unknown` or inventing a named-map identity is not permitted.

Variant selection is by the carrier tag, never by payload truthiness. `Some(0)`, `Some(false)`, `Some("")`, `Some(())`, and `None` are different encoded values, as are `Ok(0)`, `Err(0)`, `Ok(false)`, and `Err(false)`.

## Functions and entry points

A bytecode artifact has one top-level entry point. Additional functions may be private or exported.
Expand All @@ -56,12 +77,16 @@ Each function record declares:
- instruction range or entry address;
- optional source and symbol metadata.

A function that declares no return type has the logical Unit result schema. Propagation (`?`) is lowered into a branch plus the function's normal return continuation; the artifact does not gain a throw/catch mechanism.

## Instructions

The instruction stream is a sequence of VM operations. Each operation has a defined opcode and operands. Operands may reference constants, locals, functions, host calls, jump targets, or type metadata.

Instruction validation happens before execution. A conforming VM should reject malformed jumps, invalid local references, invalid constant references, wrong arity calls, and missing host requirements.

Logical payload type does not establish a native representation. Generic map reads can remain tagged and require checked unboxing, and a backend may decline a workload it cannot prove; interpreter, JIT, and AOT therefore share one value model rather than one instruction-selection strategy.

## Control flow

Control-flow instructions use artifact-local targets. Targets must point to instruction boundaries. Conditional and unconditional jumps must not enter the middle of another structured region in a way that violates VM validation rules.
Expand All @@ -72,12 +97,14 @@ Loop control is lowered into normal control-flow instructions. Source-level loop

The bytecode model is stack-oriented or register/local-oriented according to VM implementation, but the artifact must define the effect of each instruction on the abstract evaluation state. At validation time, each instruction boundary should have a consistent expected value shape.

Function calls consume arguments and produce exactly one result value, including null for procedures.
Function calls consume arguments and produce exactly one result value, including the logical Unit value `()` for procedures. A procedure does not produce a nullable result, and a caller must not treat the Unit result as `Option::None`.

## Errors and traps

Runtime errors are observable traps. Examples include invalid index access, unsupported operation for a value type, arity mismatch that was not rejected earlier, and host function failure.

A fatal trap and a guest `Result::Err` are separate channels. A guest error is an ordinary value in the declared `Result` schema; fuel or epoch suspension, cancellation, quota violations, invalid representation, and host transport failure remain fatal and are not representable as a guest error.

A trap should include enough context for diagnostics: instruction location, active function, source location if known, and an error category.

## Debug metadata
Expand Down
67 changes: 55 additions & 12 deletions language/grammar.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Notation:
- `+` means one or more
- `|` means alternatives

The `?` in this notation is always the optionality suffix described above and never the source-level operator. Source `?` appears only as the quoted token `"?"`.

## Program and statements

```ebnf
Expand Down Expand Up @@ -52,7 +54,7 @@ FunctionDecl ::=
TypeParams ::= "<" Identifier ("," Identifier)* ">"
ParamList ::= Param ("," Param)*
Param ::= Identifier (":" Type)?
ReturnType ::= "->" Type "?"?
ReturnType ::= "->" Type
FunctionBlock ::= "{" BlockStmt* TrailingExpr "}"

LetStmt ::= "let" "mut"? Identifier (":" Type)? "=" Expr
Expand All @@ -70,16 +72,16 @@ Block ::= "{" Statement* "}"

```ebnf
Type ::=
PrimitiveType OptionalSuffix? ArrayAlias*
| NamedType OptionalSuffix? ArrayAlias*
| ArrayType OptionalSuffix? ArrayAlias*
| CallableType OptionalSuffix? ArrayAlias*
| "null" OptionalSuffix? ArrayAlias*
PrimitiveType ArrayAlias*
| NamedType ArrayAlias*
| ArrayType ArrayAlias*
| CallableType ArrayAlias*
| UnitType ArrayAlias*

PrimitiveType ::= "unknown" | "int" | "float" | "number" | "bool" | "string" | "bytes"
NamedType ::= Identifier TypeArgs?
TypeArgs ::= "<" Type ("," Type)* ">"
OptionalSuffix ::= "?"
UnitType ::= "(" ")"
ArrayAlias ::= "[" "]"

ArrayType ::=
Expand All @@ -93,6 +95,15 @@ CallableType ::= "fn" "(" TypeList? ")" "->" Type
TypeList ::= Type ("," Type)*
```

There is no optional type suffix. `T?` is not a type, and neither is `null`. An optional value is written `Option<T>` and a fallible value is written `Result<T, E>`; `Option` and `Result` are compiler built-ins with required type arguments, so they also appear as ordinary `NamedType` applications. `()` is the Unit type. A function that declares no return type has the Unit return type.

```ebnf
OptionType ::= "Option" "<" Type ">"
ResultType ::= "Result" "<" Type "," Type ">"
```

Both `Result` parameters are required. `Option::None` has no payload from which to infer its parameter, so it needs an `Option<T>` annotation or another contextual type.

## Expressions

```ebnf
Expand All @@ -108,6 +119,7 @@ PrimaryExpr ::=
Literal
| Identifier CallSuffix?
| Identifier "::" PathSegments TypeCallArgs? "(" ArgList? ")"
| OptionNone
| "(" Expr ")"
| ArrayLiteral
| BraceLiteral
Expand All @@ -127,23 +139,42 @@ PostfixOp ::=
| "." Identifier
| "?." Identifier
| "?." "[" Expr "]"
| "?"
| "++"
```

The implementation applies postfix operations inside `PrimaryExpr`; this sketch separates them for readability.

`"?"` is the error and absence propagation operator. It applies to an `Option` operand inside an `Option`-returning function or closure, and to a `Result` operand inside a `Result`-returning function or closure whose error type matches exactly. It is not a type suffix and it is not `?.`; the two-character `?.` projection stays a single postfix operator.

## Literals and collections

```ebnf
Literal ::= "null" | "true" | "false" | IntLiteral | FloatLiteral | StringLiteral | BytesLiteral
Literal ::= "true" | "false" | "(" ")" | IntLiteral | FloatLiteral | StringLiteral | BytesLiteral

ArrayLiteral ::= "[" (Expr ("," Expr)* ","?)? "]"
BraceLiteral ::= "{" (BraceEntry ("," BraceEntry)* ","?)? "}"
BraceEntry ::= Expr | MapEntry
MapEntry ::= MapKey (":" | "=") Expr
MapKey ::= Identifier | StringLiteral | BytesLiteral | IntLiteral | FloatLiteral | "true" | "false" | "null" | "[" Expr "]"
MapKey ::= Identifier | StringLiteral | BytesLiteral | IntLiteral | FloatLiteral | "true" | "false" | "[" Expr "]"
```

`"(" ")"` is the Unit literal and is distinct from the parenthesized-expression form `"(" Expr ")"`.

Map keys are never absent: a key is an identifier, string, bytes, integer, float, or boolean literal, or a dynamic `[expr]` key. `null` is not a key form, and an explicit `null` key is rejected.

## Option, Result, and Unit values

```ebnf
OptionSome ::= "Option" "::" "Some" "(" Expr ")"
OptionNone ::= "Option" "::" "None"
ResultOk ::= "Result" "::" "Ok" "(" Expr ")"
ResultErr ::= "Result" "::" "Err" "(" Expr ")"
UnitValue ::= "(" ")"
```

`Option::Some`, `Result::Ok`, and `Result::Err` are ordinary namespace-qualified constructor calls, so they are already covered by `PrimaryExpr`'s namespace-call form. `Option::None` carries no argument list, so `PrimaryExpr` admits it explicitly through `OptionNone`. The bare forms `Some(...)`, `Ok(...)`, and `Err(...)` are not constructors: `Some(1)` is an unknown-function error, bare `None` in expression position is an unknown local, and `Ok(...)`/`Err(...)` are not valid match patterns either. Bare `None` and `Some(name)` survive only as legacy optional-slot match patterns, described below.

## If and match expressions

```ebnf
Expand All @@ -156,15 +187,27 @@ MatchPattern ::=
IntLiteral
| StringLiteral
| BytesLiteral
| "null"
| "None"
| "Option" "::" "None"
| "Option" "::" "Some" "(" MatchBinding ")"
| "Result" "::" "Ok" "(" MatchBinding ")"
| "Result" "::" "Err" "(" MatchBinding ")"
| LegacyOptionalPattern
| "_"
MatchBinding ::= Identifier | "_"

LegacyOptionalPattern ::=
"None"
| "Some" "(" Identifier ")"
| "Some" "(" MatchTypeName ")"
| "_"
MatchTypeName ::= "int" | "Int" | "float" | "Float" | "number" | "Number" | "bool" | "Bool" | "string" | "String" | "bytes" | "Bytes" | "array" | "Array" | "map" | "Map"
```

`MatchBinding` is a binding name or `_`, never a type test: `Option::Some(int)` binds a local named `int`. `Option::None` takes no payload, and `Option::None(x)` is rejected.

`LegacyOptionalPattern` is the retired optional-slot mechanism, kept here because the parser still accepts it. `Some(name)` binds a payload and needs a receiver that is a legacy optional slot, and `None` needs the same; a logical `Option` value is not an optional slot, so both fail with `Some(...) and None match patterns require an optional value`. `Some(TypeName)` is different: it carries no optional-slot precondition and compiles against any receiver, but it compares the receiver's runtime type name rather than a present payload, so the name it tests decides the result. An `Option` carrier is a `Value::Map` whose type name is `map`, so `Some(map)`/`Some(Map)` do match it, while `Some(int)`, `Some(float)`, `Some(bool)`, `Some(string)`, `Some(bytes)`, and `Some(array)` test the top-level value and are false against it; `Some(number)`/`Some(Number)` test two names, `int` or `float`, not one. `Some(_)` is rejected by the parser — `Some(_) is not supported; bind a name with Some(name)` — even though `_` sits in `Identifier` position here; only `Option::Some(_)` accepts a wildcard. All of them still need the trailing `_` arm. Legacy patterns cannot be mixed with constructor arms in one match, and the message names the constructor family: `Option match cannot mix constructor arms with value patterns` for an `Option` match, `Result match cannot mix constructor arms with value patterns` for a `Result` match. `Ok(...)`/`Err(...)` have no bare form at all — such an arm is a parse error.

An `Option` match is exhaustive with `Option::Some(binding)` and `Option::None`, and a `Result` match is exhaustive with `Result::Ok(binding)` and `Result::Err(binding)`. A wildcard may stand in for the absent branch when the present branch is a constructor arm. Nesting one constructor pattern inside another, and mixing `Option` and `Result` arms in the same match, are rejected; match the inner value in a second match instead. Literal matches still require a trailing `_` arm.

## Closures

```ebnf
Expand Down
14 changes: 10 additions & 4 deletions language/lexical.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,35 @@ Identifier ::= IdentifierStart IdentifierContinue*
The lexer recognizes these reserved words for RustScript:

```text
as break continue else false fn for if let match null pub struct true use while
as break continue else false fn for if let match pub struct true use while
```

The identifier `mut` is context-sensitive after `let` and `&`; it is not a lexer keyword.

`null` is neither a keyword nor a literal. Absence is expressed with the constructor `Option::None`, and "no value produced" is the Unit value `()`. `Option`, `Result`, `Some`, `None`, `Ok`, and `Err` are built-in type and constructor names, not reserved words, so the lexer still treats them as ordinary identifiers and paths.

## Punctuators and operators

```text
! != + ++ += - * / % & && | || ( ) [ ] { } , : ? . ... ; = == => < <= > >=
! != + ++ += - * / % & && | || ( ) [ ] { } , : ? ?. . ... ; = == => < <= > >=
```

The `++` and `+=` tokens are enabled for RustScript. `...` is only used by variadic array type schemas.

`?` and `?.` are distinct operators. `?` is expression-level error or absence propagation and follows its operand with no intervening token. `?.` is fallible projection; the `?` and `.` form one operator, and a projection is written as `receiver?.field` or `receiver?.[index]`. An empty `(` `)` pair spell both the Unit type and the Unit value.

## Literals

### Null and booleans
### Booleans and unit

```rustscript
null
true
false
()
```

`()` in value position is the Unit value. Unit is a logical type whose physical carrier is the VM's internal Null value, so a Unit value is not a source-level `null`: RustScript has no `null` literal, and an explicit `null` in source is rejected rather than silently producing Unit or `Option::None`.

### Integers

Integers are signed 64-bit values after unary `-` is applied. Decimal and hexadecimal forms are accepted:
Expand Down
Loading
Loading