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
8 changes: 8 additions & 0 deletions .agents/skills/grill-me/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
name: grill-me
description: Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions "grill me".
---

Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one.

If a question can be answered by exploring the codebase, explore the codebase instead.
18 changes: 10 additions & 8 deletions AGENTS.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ console.log(`Your order total: $${total.toFixed(2)}`);

### Run via Souffle VM (Bytecode)

GocciaScript includes an alternative bytecode execution backend — the **Souffle VM** — a general-purpose register-based virtual machine that routes language features through a bridge layer to the GocciaScript evaluator. This approach passes 100% of the test suite (3,406 tests). The compiler infers types from initializers and type annotations, emitting specialized float opcodes inlined in the VM dispatch loop — typed code runs ~28–30% faster than untyped. Known structural limitation: the ABC-encoded instruction format limits constant pool references to 255 per prototype. `.sbc` files use little-endian byte order for cross-platform portability. See [Souffle VM Architecture](docs/souffle-vm.md) for full details.
GocciaScript includes an alternative bytecode execution backend — the **Souffle VM** — a general-purpose register-based virtual machine that routes language features through a bridge layer to the GocciaScript evaluator. This approach passes 100% of the test suite (3,501 tests). The compiler infers types from initializers and type annotations, emitting specialized float opcodes inlined in the VM dispatch loop — typed code runs ~28–30% faster than untyped. Known structural limitation: the ABC-encoded instruction format limits constant pool references to 255 per prototype. `.sbc` files use little-endian byte order for cross-platform portability. See [Souffle VM Architecture](docs/souffle-vm.md) for full details.

```bash
# Compile and execute via Souffle VM
Expand Down
6 changes: 4 additions & 2 deletions docs/code-style.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ FElements: TObjectList<TGocciaValue>;
FManagedScopes: TObjectList<TGocciaScope>;
```

**Why `TObjectList(False)` instead of `TList`?** Even when the collection does not own its elements (e.g., the GC's managed scopes list, which uses manual mark-and-sweep), using `TObjectList<T>.Create(False)` with a named alias keeps the VMT consistent. `TList<T>` and `TObjectList<T>` produce incompatible VMTs, so mixing them across units reintroduces the same cross-unit type check failures.
**Why `TObjectList(False)` instead of `TList`?** Even when the collection does not own its elements (e.g., the GC's managed scopes list, which uses manual mark-and-sweep), using `TObjectList<T>.Create(False)` with a named alias keeps the VMT consistent. `TList<T>` and `TObjectList<T>` produce incompatible VMTs, so mixing them across units reintroduces the same cross-unit type check failures. See [spikes/fpc-generics-performance.md](spikes/fpc-generics-performance.md) for the benchmark analysis confirming generics have zero runtime cost.

### Hash Map Selection

Expand All @@ -183,7 +183,7 @@ The codebase provides purpose-built hash maps that replace `TDictionary` on hot
| Scope bindings | `TOrderedStringMap<V>` | Hash-based O(1) lookup per scope level; chain walking in `TGocciaScope` |
| Cold-path / diagnostic | `TDictionary<K,V>` | Acceptable where performance is not critical |

**Never use** `TFPDataHashTable` — it has catastrophic insert performance (400,000 ns/insert vs 50 ns for `TOrderedStringMap` at N=20). See [spikes/fpc-hashmap-performance.pdf](spikes/fpc-hashmap-performance.pdf) for the full benchmark analysis.
**Never use** `TFPDataHashTable` — it has catastrophic insert performance (400,000 ns/insert vs 50 ns for `TOrderedStringMap` at N=20). See [spikes/fpc-hashmap-performance.md](spikes/fpc-hashmap-performance.md) for the full benchmark analysis.

**API compatibility:** All custom maps share the same core API as `TDictionary`: `Add`, `AddOrSetValue`, `TryGetValue`, `ContainsKey`, `Remove`, `Clear`. Iteration uses `Keys`, `Values`, or `ToArray` returning dynamic arrays (not enumerators), so use indexed `for` loops instead of `for...in`.

Expand Down Expand Up @@ -421,6 +421,8 @@ else if Node is TGocciaCallExpression then
// ...
```

See [spikes/fpc-dispatch-performance.md](spikes/fpc-dispatch-performance.md) for the benchmark analysis comparing virtual, interface, and manual VMT dispatch.

### Parser Combinator (Binary Expressions)

All left-associative binary operator parsers delegate to a shared `ParseBinaryExpression` helper:
Expand Down
51 changes: 51 additions & 0 deletions docs/decision-log.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Decision Log

Chronological record of key architectural and implementation decisions. Each entry gives a 1–3 sentence summary with links to the detailed documentation.

## Interpreter & Evaluator

**Pure evaluator functions.** The evaluator is pure — same AST node + context always produces the same result. State changes happen through scope and value objects, never evaluator-internal state. See [design-decisions.md § Pure Evaluator Functions](design-decisions.md#pure-evaluator-functions).

**Virtual dispatch value system.** Property access, `IsPrimitive`, and `IsCallable` use VMT dispatch on `TGocciaValue` instead of `is` type check chains. Eliminates multi-way branching at every call site. See [design-decisions.md § Virtual Dispatch Value System](design-decisions.md#virtual-dispatch-value-system).

**`TGocciaControlFlow` for break/return.** `break` and `return` use result records (`cfkBreak`, `cfkReturn`) instead of Pascal exceptions, eliminating `FPC_SETJMP` overhead from the interpreter's hot path. See [design-decisions.md § Error Handling Strategy](design-decisions.md#error-handling-strategy).

**Singleton special values.** `undefined`, `null`, `true`, `false`, `NaN`, `Infinity` are singletons enabling pointer equality instead of type checks. See [design-decisions.md § Singleton Special Values](design-decisions.md#singleton-special-values).

**Number dual representation.** Numbers use `Double` + `TGocciaNumberSpecialValue` enum to handle `NaN`, `Infinity`, `-0` correctly without IEEE 754 comparison pitfalls. See [design-decisions.md § Number Representation](design-decisions.md#number-representation).

## Souffle VM

**Two-tier ISA.** Tier 1 (0–127) has universal semantics inlined in the dispatch loop; Tier 2 (128–255) dispatches through `TSouffleRuntimeOperations` for language-specific behavior. See [design-decisions.md § Souffle VM](design-decisions.md#souffle-vm-two-tier-isa-with-pluggable-runtime) and [souffle-vm.md](souffle-vm.md).

**Register-based, not stack-based.** Fewer instructions per operation and no redundant stack manipulations, at the cost of wider instruction encoding. See [design-decisions.md § Why Register-Based](design-decisions.md#why-register-based).

**Self-contained value system.** `TSouffleValue` (16 bytes, 6 kinds) is independent of `TGocciaValue` to keep the VM language-agnostic. See [design-decisions.md § Why a Self-Contained Value System](design-decisions.md#why-a-self-contained-value-system).

**16-byte TSouffleValue record.** Reduced from 26 bytes (`string[23]`) to 16 bytes (`string[13]`) after benchmarking 8, 10, 16, and 26-byte variants. 16 bytes is the sweet spot — 13-char inline strings cover most property names while fitting more values per cache line. See [optimization-log.md § TSouffleValue Record Size](optimization-log.md#tsoufflevalue-record-size--16-bytes-pr-96).

**`OP_RT_EXT` over per-feature opcodes.** Language-specific features use a single `OP_RT_EXT` with sub-opcode dispatch instead of dedicated Tier 2 opcodes, keeping the VM language-agnostic. See [design-decisions.md § Why OP_RT_EXT](design-decisions.md#why-op_rt_ext-over-per-feature-opcodes).

**Compiler-side desugaring.** Language features (nullish coalescing, template literals, object spread) are compiled into sequences of generic VM instructions rather than adding specialized opcodes. See [design-decisions.md § Compiler-Side Desugaring](design-decisions.md#compiler-side-desugaring).

## Data Structures

**Custom hash maps over TDictionary.** Purpose-built `TOrderedStringMap`, `THashMap`, and `TOrderedMap` replace `TDictionary` on hot paths with 4–6× faster inserts at typical sizes. See [optimization-log.md § Custom Hash Map Hierarchy](optimization-log.md#custom-hash-map-hierarchy-pr-66) and [spikes/fpc-hashmap-performance.md](spikes/fpc-hashmap-performance.md).

**TOrderedStringMap for scope bindings.** A `TScopeMap` with linear scan was attempted and abandoned after profiling showed 2.7× slowdown vs hash-based lookup. Scope bindings use `TOrderedStringMap<TLexicalBinding>` with recursive parent walking. See [optimization-log.md § Custom Hash Map Hierarchy](optimization-log.md#custom-hash-map-hierarchy-pr-66).

**No TFPDataHashTable.** Catastrophic insert performance due to per-node heap allocation (400,000 ns/insert vs 50 ns for `TOrderedStringMap`). See [spikes/fpc-hashmap-performance.md](spikes/fpc-hashmap-performance.md).

## Strings

**TStringBuffer over TStringBuilder.** Both `TUnicodeStringBuilder` and `TAnsiStringBuilder` trigger a 750× slowdown from FPC's heap manager without preallocation. `TStringBuffer` (advanced record with doubling growth) is ~2× faster even with preallocation. See [spikes/fpc-string-performance.md](spikes/fpc-string-performance.md).

**No string interning.** Dictionary-based string interning was benchmarked at −4% across 172 benchmarks. FPC's COW semantics make allocation effectively free; the hash + lookup cost exceeds it. See [design-decisions.md § String Interning](design-decisions.md#string-interning--attempted-and-rejected).

## FPC Platform

**Generics have zero runtime cost.** Type aliases, subclasses, and multi-level generic inheritance produce byte-identical machine code. Design for API clarity, not performance. See [spikes/fpc-generics-performance.md](spikes/fpc-generics-performance.md).

**Virtual dispatch is constant-time.** Depth 1 and depth 5 dispatch cost the same ~2.5ns. Avoid `inherited` chains on hot paths (linear scaling), but hierarchy depth is free. See [spikes/fpc-dispatch-performance.md](spikes/fpc-dispatch-performance.md).

**ObjFPC vs Delphi mode: zero performance impact.** Both modes produce byte-identical machine code; choose based on syntax preference. See [spikes/fpc-dispatch-performance.md](spikes/fpc-dispatch-performance.md).
10 changes: 5 additions & 5 deletions docs/design-decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Beyond property access, the base class provides two additional virtual methods f
- **Simple call sites** — `Value.GetProperty(Name)` is a single virtual call. `Value.IsPrimitive` and `Value.IsCallable` are likewise single VMT calls. No capability queries, no casting.
- **Safe defaults** — The base class returns `nil` for `GetProperty`, no-ops for `SetProperty`, `False` for `IsPrimitive`, and `False` for `IsCallable`, so the evaluator can call these on any value without type-checking first.
- **Extensible** — New value types added to the hierarchy automatically participate by overriding the virtual methods.
- **Performance** — A single VMT call replaces multi-`is` type check chains. For `IsPrimitive`, this replaces five sequential `is` checks; for `IsCallable`, two. Benchmarks show 10-20% improvement in class-related operations where these checks are on the hot path.
- **Performance** — A single VMT call replaces multi-`is` type check chains. For `IsPrimitive`, this replaces five sequential `is` checks; for `IsCallable`, two. Benchmarks show 10-20% improvement in class-related operations where these checks are on the hot path. See [spikes/fpc-dispatch-performance.md](spikes/fpc-dispatch-performance.md) for the benchmark analysis comparing virtual, interface, and manual VMT dispatch.

## Centralized Keyword Constants

Expand Down Expand Up @@ -388,13 +388,13 @@ Adding a new language frontend requires implementing `TSouffleRuntimeOperations`

### Why a Self-Contained Value System?

The Souffle VM has its own `TSouffleValue` tagged union (26 bytes: kind + flags + variant data) with 6 value kinds: Nil, Boolean, Integer, Float, String (inline ≤23 chars), Reference. This is independent of `TGocciaValue`.
The Souffle VM has its own `TSouffleValue` tagged union (16 bytes: kind + flags + variant data) with 6 value kinds: Nil, Boolean, Integer, Float, String (inline ≤13 chars), Reference. This is independent of `TGocciaValue`.

The separation exists because:

- **Language-agnostic** — The VM doesn't know what "a string" or "an object" is. Those are all `svkReference` (pointer to a `TSouffleHeapObject`). The heap object's type tag is interpreted by the runtime, not the VM.
- **No GocciaScript dependency** — The VM can be used without any GocciaScript code, making it viable for other frontends.
- **Inline primitives** — Booleans, integers, floats, and short strings (≤23 chars) live in the register file with zero heap allocation. Only complex types and long strings go through the heap.
- **Inline primitives** — Booleans, integers, floats, and short strings (≤13 chars) live in the register file with zero heap allocation. Only complex types and long strings go through the heap.
- **Opaque flags** — `svkNil` carries a `Flags` byte the VM stores and compares but never interprets. GocciaScript uses it to distinguish `undefined` (flags=0) from `null` (flags=1). Other languages may use it differently or not at all.
- **WASM 3.0 mapping** — The 6 kinds map naturally to WASM's `anyref` hierarchy: Nil → `ref.null`, small integers/booleans → `i31ref`, floats → boxed `f64` GC structs, references → GC struct subtypes.

Expand Down Expand Up @@ -440,7 +440,7 @@ An earlier design had separate `OP_RT_CALL_SPREAD` and `OP_RT_CALL_METHOD_SPREAD
2. Delegating to the GocciaScript evaluator/interpreter
3. Converting `TGocciaValue` → `TSouffleValue` (wrap)

This "Unwrap-Delegate-Wrap" cycle was the fastest path to a working bytecode backend and achieves full language coverage — the bytecode backend passes 100% of the test suite (3,406 tests). However, the cycle creates deep coupling to the interpreter.
This "Unwrap-Delegate-Wrap" cycle was the fastest path to a working bytecode backend and achieves full language coverage — the bytecode backend passes 100% of the test suite (3,501 tests). However, the cycle creates deep coupling to the interpreter.

The target architecture eliminates the bridge entirely: `TGocciaRuntimeOperations` would implement JavaScript semantics directly on Souffle types (`TSouffleValue`, `TSouffleArray`, `TSouffleRecord`, `TSouffleBlueprint`), with prototype chain walking on delegate chains, type coercion natively on `TSouffleValue`, and all built-in methods as `TSouffleNativeFunction` delegates. This is a ground-up rewrite, not an incremental fix. See [souffle-vm.md § Current State](souffle-vm.md#current-state-and-bridge-architecture) for the full analysis.

Expand All @@ -451,7 +451,7 @@ The following operations delegate to the GocciaScript evaluator through the brid
- **Module imports** (`ImportModule`, 29 calls) — Delegates to the GocciaScript module resolver. Inherently interpreter-coupled (file I/O, path resolution, recursive compilation).
- **Async/await** (`AwaitValue`, 170 calls) — Delegates to `TGocciaPromiseValue` and the microtask queue.
- **Iteration** (`GetIterator`/`IteratorNext`, 146/427 calls) — Array, string, Map, and Set iteration has native fast paths. Remaining bridge calls are for other iterable types.
- **Decorator class compilation** — Classes with decorators are deferred to the interpreter via `GOCCIA_EXT_EVAL_CLASS`. All other class features (getters, setters, statics, private members, computed properties, built-in subclassing) compile natively to blueprint opcodes.
- **Decorator class compilation** — All classes, including those with decorators, compile natively to blueprint opcodes. Decorator evaluation uses `GOCCIA_EXT_BEGIN_DECORATORS` / `GOCCIA_EXT_APPLY_ELEMENT_DECORATOR` / `GOCCIA_EXT_FINISH_DECORATORS` extension opcodes.

Bridge reduction has dramatically reduced these crossings: `Invoke` went from 21,326 to 55 bridge calls (-99.7%), `GetProperty` from 12,408 to 157 (-98.7%), and `UnwrapToGocciaValue` from 97,212 to 50,132 (-48.4%). `EvaluateClassByIndex` was completely eliminated. The remaining bridge crossings are concentrated in construction (770 calls), async/await (170), iterators (573), and module imports (29).

Expand Down
Loading
Loading