Skip to content

Commit 1763e41

Browse files
stdlib v2: first-class functions + harmonic variants + polish round (28 new builtins)
Three coherent tracks land together — language-level first-class function values, OMNIcode-flavored harmonic operations, and the ergonomic polish round Python users expect. Track 1 — First-class functions (6 new HOFs): Value::Function(String) is now a real Value variant. Bare function names in expression context resolve to a function-value instead of erroring as undefined variable. is_known_builtin + self.functions HashMap handle resolution; call_first_class_function dispatches a callable back through call_function via synthetic-arg variables (same pattern as vm_call_builtin). Six higher-order array operations: arr_map(arr, fn) - apply fn per element arr_filter(arr, pred) - keep where pred truthy arr_reduce(arr, fn, init) - left fold arr_any(arr, pred) - short-circuit OR arr_all(arr, pred) - short-circuit AND arr_find(arr, pred) - first matching element or null Both user-defined functions AND built-ins work as values: arr_map(xs, double) # user fn by bare name arr_map(fibs, is_fibonacci) # built-in by bare name Captured "function" is its definition, not a closure over local scope. Proper closures = future work. Track 2 — OMNIcode harmonic variants (6 new functions): The architecturally distinctive piece. Anyone can write a file; these write harmonically — operations that route through the φ-math substrate to make decisions ordinary versions handle naively. harmonic_checksum(s) Resonance signature: sum of per-char codepoint resonance. harmonic_write_file(path, content) Atomic write with a resonance gate. Computes mean per-char resonance; commits via tmp+rename if score >= 0.5; rejects below the gate (returns negative score). Threshold matches value_danger's danger boundary. harmonic_read_file(path) Returns [content, mean_resonance] — caller decides whether to trust low-coherence content. harmonic_sort(arr) Sort by harmony_value DESCENDING. Pure Fibonacci values lead. Demo: [100, 89, 50, 144, 7, 233, 99] becomes [89, 144, 233, 50, 99, 100, 7]. Different from arr_sort (natural value ordering). harmonic_split(s) Chunk a string at Fibonacci-aligned word boundaries. 65-char string splits into [57, 8] (close to 55+8). harmonic_partition(arr) Group elements by nearest Fibonacci attractor. Returns outer array of buckets in attractor order. Track 3 — Polish round (8 new functions + 1 keyword tweak): random_int(lo, hi), random_float(), random_seed(s) xorshift64* PRNG, seeded from system nanos at interpreter construction. random_seed(s) for deterministic runs. println(x) — Display formatting (no HInt scaffolding) print_raw(x) — Same, no trailing newline (progress lines) str_pad_left(s, w, ch) / str_pad_right(s, w, ch) Table-formatting workhorses. arr_zip(a, b) Pair elements positionally; shorter array sets length. arr_unique(arr) Dedupe preserving first-occurrence order. Type-aware via values_equal (same as arr_contains uses). Interpreter state grows by one field: rng_state: Cell<u64>. First mutable-but-non-scope state since Phase O. Kept minimal — Cell<u64> not Mutex because the interpreter is single-threaded. Documentation: - STDLIB.md updated comprehensively. ~135 named builtins now. Alphabetical reference regenerated. - "Missing on purpose" section updated: map/filter/reduce and println/print_raw no longer missing. - "Future-tense work" section updated: removed first-class functions (done!) and random (done!); added closures-over- local-scope and more harmonic variants as the next candidates. New example files (3): - examples/harmonic_variants.omc — exercises every harmonic_* function with expected outputs in comments. - examples/polish_round.omc — random determinism check, println/print_raw demo, padding, zip, unique. README: - "What's proven right now" gains two rows (first-class functions + harmonic variants). - Host primitive count updated from ~100 to ~135. Regression: V.9b ✓✓✓ FIXPOINTS unchanged. H.5 6/6 demos converge. safe_keyword_host identical on tree-walk and OMC_VM=1. All previous demos pass. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent daee499 commit 1763e41

8 files changed

Lines changed: 960 additions & 41 deletions

File tree

CHANGELOG.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,78 @@ All notable changes to OMNIcode will be documented in this file.
44

55
## [Unreleased]
66

7+
### Added (First-class functions + OMNIcode harmonic variants + polish round — 28 new built-ins, 2026-05-14)
8+
9+
🎯 **Three coherent additions: language-level first-class function values, OMNIcode-flavored harmonic operations, and a polish round.**
10+
11+
#### Track 1 — First-class functions
12+
13+
`Value::Function(String)` is now a real Value variant. Bare function names in expression context resolve to a function-value (instead of erroring as undefined variable). The `is_known_builtin` set + `self.functions` HashMap handle the resolution; `call_first_class_function` dispatches a callable value back through `call_function` using synthetic-arg variables (same pattern as `vm_call_builtin`).
14+
15+
Six higher-order array operations:
16+
17+
| Function | Behavior |
18+
|---|---|
19+
| `arr_map(arr, fn)` | Apply fn to every element, collect results |
20+
| `arr_filter(arr, pred)` | Keep elements where pred is truthy |
21+
| `arr_reduce(arr, fn, init)` | Left fold: `fn(acc, elem) -> acc` |
22+
| `arr_any(arr, pred)` | 1 if any element passes; short-circuits |
23+
| `arr_all(arr, pred)` | 1 if every element passes; short-circuits |
24+
| `arr_find(arr, pred)` | First element passing pred, else `null` |
25+
26+
Both user-defined functions AND built-ins work as callable values:
27+
28+
```omc
29+
fn double(x) { return x * 2; }
30+
print(arr_join(arr_map(xs, double), ",")); # 2,4,6,10,16
31+
32+
# Pass a built-in by name:
33+
print(arr_join(arr_map(fibs, is_fibonacci), ",")); # 1,0,1,0,1,1
34+
```
35+
36+
The captured "function" is its definition, not a closure over local scope — proper closures are future work. Acceptable trade for the win in expressiveness.
37+
38+
#### Track 2 — OMNIcode harmonic variants
39+
40+
The architecturally distinctive piece. **Anyone can write a file; these write harmonically** — operations that route through the φ-math substrate to make decisions ordinary versions handle naively.
41+
42+
- **`harmonic_checksum(s)`** — resonance signature of a string. Sum over each char's codepoint resonance. Two strings with the same checksum are harmonically equivalent.
43+
- **`harmonic_write_file(path, content)`** — atomic write with a resonance gate. Computes content's mean per-char resonance; commits via tmp+rename if score ≥ 0.5; rejects (returns negative score) below the gate. The 0.5 threshold matches `value_danger`'s danger boundary — below that, content is "dangerous" by the substrate's own definition.
44+
- **`harmonic_read_file(path)`** — returns `[content, mean_resonance]` so callers can see the harmonic score alongside content and decide whether to trust it.
45+
- **`harmonic_sort(arr)`** — sort by `harmony_value` of each element **descending**. Pure Fibonacci values lead; off-grid sinks. Different from `arr_sort` which orders by NATURAL value. Demo: `[100, 89, 50, 144, 7, 233, 99] → [89, 144, 233, 50, 99, 100, 7]`.
46+
- **`harmonic_split(s)`** — chunk a string at Fibonacci-aligned word boundaries. Splits a 65-char string into `[57 chars, 8 chars]` (close to 55+8 with word-boundary walk). Useful for φ-aligned line wrapping and packet sizing.
47+
- **`harmonic_partition(arr)`** — group elements by nearest Fibonacci attractor. Returns outer array of buckets in attractor order. Use for distribution analysis along the φ-grid.
48+
49+
#### Track 3 — Polish round
50+
51+
Eight workhorse additions every Python user reaches for:
52+
53+
- `random_int(lo, hi)`, `random_float()`, `random_seed(s)` — xorshift64* PRNG, deterministic with `random_seed`. Not cryptographic.
54+
- `println(x)` — like `print` but uses Display formatting (no `HInt(...)` scaffolding). The original `print` is preserved for debug-format introspection.
55+
- `print_raw(x)` — same as `println` but no trailing newline. Pairs for progress-line patterns.
56+
- `str_pad_left(s, width, ch)` / `str_pad_right(s, width, ch)` — table formatting.
57+
- `arr_zip(a, b)` — pair elements positionally as `[a_i, b_i]`; shorter array sets length.
58+
- `arr_unique(arr)` — dedupe preserving first-occurrence order. Type-aware equality via the existing `values_equal` helper.
59+
60+
#### Documentation
61+
62+
- `STDLIB.md` — comprehensive reference for every built-in is now updated with the 28 new functions across all three tracks. Total stdlib surface is now ~135 named builtins plus `print` as a statement keyword.
63+
- Three new test files: `examples/harmonic_variants.omc`, `examples/polish_round.omc`, plus updates to the existing patterns. Each test exercises its track's surface with expected outputs in inline comments.
64+
65+
#### Architectural note: Interpreter state grows
66+
67+
Adding random required interior state on the Interpreter struct (`rng_state: Cell<u64>`, xorshift64*, seeded from system nanos at construction). This is the **first** mutable-but-non-scope state we've added since Phase O. Kept it minimal — `Cell<u64>` not `Mutex` because the interpreter is single-threaded.
68+
69+
#### Verification
70+
71+
All existing demos pass without regression:
72+
- V.9b: ✓✓✓ ALL THREE FIXPOINTS REACHED
73+
- H.5: 6/6 demos converge
74+
- safe_keyword_host.omc: identical on tree-walk and OMC_VM=1
75+
- stdlib_expansion.omc: identical on tree-walk and OMC_VM=1
76+
- harmonic_variants.omc: all sections produce expected outputs
77+
- polish_round.omc: `random_seed(42)` produces identical sequence across reseeds (determinism verified)
78+
779
### Added (Standard library expansion — 16 new built-ins, 2026-05-14)
880

981
🎯 **`examples/stdlib_expansion.omc` + `STDLIB.md` — OMC's standard library now covers the common workflows developers reach for instead of writing from scratch.**

README.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ The math is documented in `PHI_PI_FIB_ALGORITHM.md` and the type system in `ARCH
2525

2626
What you can do with OMC right now, with the binary in this repo:
2727

28-
- **Run a Turing-complete language.** Recursion, functions, strings, arrays, mutating builtins, while loops, if/else. ~100 host primitives across strings, arrays, file I/O, type introspection, math, harmonic-math, and self-healing — full reference in `STDLIB.md`. See `examples/fibonacci.omc`, `array_ops.omc`, `strings.omc`, `stdlib_expansion.omc`.
28+
- **Run a Turing-complete language.** Recursion, functions, strings, arrays, mutating builtins, while loops, if/else. ~135 host primitives across strings, arrays, file I/O, type introspection, math, harmonic-math, and self-healing — full reference in `STDLIB.md`. See `examples/fibonacci.omc`, `array_ops.omc`, `strings.omc`, `stdlib_expansion.omc`.
2929
- **Compile OMC to bytecode AND execute that bytecode** — both stages of which can be written in OMC. The bytecode VM is faithful to the tree-walker: byte-identical output across both paths for any program in the supported feature surface.
3030
- **Feed broken code into a self-healing compiler.** A program with a missing semicolon, a missing `}`, a typo'd function name, an off-by-one Fibonacci constant, and a `/0` runtime crash will be **rewritten and executed to a finite answer** — no try/catch, no defensive guards. The math is the error handling.
3131

@@ -44,6 +44,8 @@ What this is **not**: a fast runtime, a production toolchain, a stable API, a de
4444
| Array-bounds healing — out-of-bounds reads become attractor-landing | `examples/self_healing_h5.omc` | Loop walking 8 indices off a 5-element array; every output has `φ=1.000` |
4545
| Host-level `safe` keyword — works in any OMC program, not just the self-healing demos | `examples/safe_keyword_host.omc` | `safe 89/0 → 89`, `safe arr_get(xs, 999) → 20`, `safe arr_set(xs, 999, 99)` mutates xs[1] |
4646
| Python-tier standard library: 16 new built-ins added 2026-05-14 | `examples/stdlib_expansion.omc` | `str_split`, `arr_sort`, `read_file`/`write_file`, `type_of`, `gcd`, `now_ms` and more — see `STDLIB.md` for the full reference |
47+
| First-class functions + higher-order array ops | `examples/harmonic_variants.omc` | `arr_map(xs, double)`, `arr_filter(xs, gt_5)`, `arr_reduce(xs, add, 0)`, plus `arr_any/all/find` |
48+
| OMNIcode harmonic variants — operations that USE the φ-math substrate | `examples/harmonic_variants.omc` | `harmonic_write_file` gates writes by resonance ≥ 0.5; `harmonic_sort` puts Fibonacci values first; `harmonic_split` chunks strings at φ-aligned word boundaries; `harmonic_partition` buckets by nearest attractor |
4749

4850
Run any of these with the binary built from this repo:
4951

@@ -145,7 +147,7 @@ cargo build --release
145147

146148
## Try the language
147149

148-
A taste of OMC syntax. The grammar is defined in `omnimcode-core/src/parser.rs`. The complete standard library — ~100 host primitives organized by category — is in `STDLIB.md`.
150+
A taste of OMC syntax. The grammar is defined in `omnimcode-core/src/parser.rs`. The complete standard library — ~135 host primitives organized by category — is in `STDLIB.md`.
149151

150152
### Hello world
151153

@@ -193,7 +195,7 @@ This is a research codebase. Honest list of things that are NOT done:
193195
- Naive brace placement in token-level repair appends missing `}` at EOF — fine for end-of-file mistakes, will fold mid-source statements into function bodies if the missing brace is conceptually mid-source. Indentation-aware repair (H.3.1) is logged.
194196
- The healer's identifier-correction has no semantic check beyond edit-distance. A typo that resolves to ANOTHER typo would stabilize but not be correct.
195197
- The `stuck` and `exhausted` outcomes of `heal_until_fixpoint` are designed but unexercised — no current demo triggers them.
196-
- **No production deployment target.** No package manager. No formatter. No LSP. No debugger. The standard library is real (~100 host primitives covering strings, arrays, file I/O, type introspection, math, φ-math, and self-healing — see `STDLIB.md`), but it's not Python-tier — no first-class functions, no formatters, no module ecosystem.
198+
- **No production deployment target.** No package manager. No formatter. No LSP. No debugger. The standard library is real (~135 host primitives covering strings, arrays, file I/O, type introspection, math, φ-math, and self-healing — see `STDLIB.md`), but it's not Python-tier — no first-class functions, no formatters, no module ecosystem.
197199
- **Adversarial cases untested.** The healer's correctness has been demonstrated on the demo inputs in `examples/self_healing_*.omc`. Fuzz testing, malicious inputs, and pathological edge cases have not been done.
198200
- **Single-developer experiment.** The codebase has not had external review. There are likely bugs we don't know about.
199201

0 commit comments

Comments
 (0)