builder/vm: stabilize json_lint_vm under unified calls

- Fix condition_fn resolution: Value call path + dev safety + stub injection
- VM bridge: handle Method::birth via BoxCall; ArrayBox push/get/length/set direct bridge
- Receiver safety: pin receiver in method_call_handlers to avoid undefined use across blocks
- Local vars: materialize on declaration (use init ValueId; void for uninit)
- Prefer legacy BoxCall for Array/Map/String/user boxes in emit_box_or_plugin_call (stability-first)
- Test runner: update LLVM hint to llvmlite harness (remove LLVM_SYS_180_PREFIX guidance)
- Docs/roadmap: update CURRENT_TASK with unified default-ON + guards

Note: NYASH_DEV_BIRTH_INJECT_BUILTINS=1 can re-enable builtin birth() injection during migration.
This commit is contained in:
nyash-codex
2025-09-28 12:19:49 +09:00
parent 41a46b433d
commit 510f4cf523
74 changed files with 2846 additions and 825 deletions

47
docs/abi/vm-kernel.md Normal file
View File

@ -0,0 +1,47 @@
# NYABI: VM Kernel Bridge (Draft)
Scope
- Provide a minimal, stable ABI for delegating selected VM policies/decisions to Ny code.
- Keep default behavior unchanged (OFF by default). Ny Kernel is a development aid only.
Design Principles
- Coarse-grained: call per feature, not per instruction (avoid hot-path crossings).
- FailFast: any error returns immediately; no silent fallbacks in dev.
- Safe by default: reentry forbidden; each call has a deadline (timeout).
- Backward compatible: API evolves via additive fields and optional methods only.
API (v0, draft)
- VmKernel.caps() -> { version: i64, features: [string] }
- VmKernel.stringify_policy(type: string) -> string
- Returns: "direct" | "rewrite_stringify" | "fallback"
- VmKernel.equals_policy(lhs_type: string, rhs_type: string) -> string
- Returns: "object" | "value" | "fallback"
- VmKernel.resolve_method_batch(reqs_json: string) -> string
- Input JSON: { reqs: [{class, method, arity}], context?: {...} }
- Output JSON: { plans: [{kind, target, notes?}], errors?: [...] }
Error & Timeout
- All calls run with a percall deadline (NYASH_VM_NY_KERNEL_TIMEOUT_MS; default 200ms when enabled).
- On timeout/NY error, Rust VM aborts the bridge call (OFF path remains intact).
Reentry Guard
- A threadlocal flag prevents reentering the Ny Kernel from within an ongoing Ny Kernel call.
- On violation, the bridge errors immediately (FailFast).
Data Model
- Strings for structured data (JSON) across the boundary to avoid shape drift.
- Primitive returns (i64/bool/string) for simple policies.
Toggles (reserved; default OFF)
- NYASH_VM_NY_KERNEL=0|1
- NYASH_VM_NY_KERNEL_TIMEOUT_MS=200
- NYASH_VM_NY_KERNEL_TRACE=0|1
Acceptance (v0)
- With bridge OFF, behavior is unchanged on all smokes.
- With bridge ON and a stub kernel, behavior is still unchanged; logging shows calls and zero decisions.
- Bridge API documented and skeleton Ny box exists (not wired by default).
Notes
- Router batching is critical to avoid percall overhead.
- Keep JSON schemas tiny and versioned; include a toplevel "v" if necessary.

View File

@ -0,0 +1,90 @@
# Phase 15.7: Known化Rewrite統合dev観測と MiniVM 安定化dev限定
目的
- Builderでの Known 化と Instance→Function の統一Known 経路を優先し、実行系VM/LLVM/Nyを単純化する。
- 早期観測resolve.try/choose, ssa.phiを devonly で整備し、Union の発生点を特定可能にする。
- 表示APIを `str()` に統一(互換: `stringify()`)し、言語表面のブレを解消する(挙動不変)。
- MiniVMNyを安全に安定化M2/M3代表ケース。NYABI Kernel は“下地のみ”既定OFF
背景
- Instance→Function 正規化の方針は既定ON。Known 経路は関数化し、VM側は単純化する。
- resolve.try/chooseBuilderと ssa.phiBuilderの観測は devonly で導入済み既定OFF
- MiniVM は M2/M3 の代表ケースを安定化(パス/境界厳密化)。
- VM Kernel の Ny 化は後段観測・ポリシーから段階導入、既定OFF
Unified Call開発既定ON
- 呼び出しの統一判定は、環境変数 `NYASH_MIR_UNIFIED_CALL``0|false|off` でない限り有効既定ON
- メソッド解決/関数化を `emit_unified_call` に集約し、以下の順序で決定:
1) 早期 toString/stringify→str
2) equals/1Known 優先→一意候補; ユーザーBox限定
3) Known→関数化`obj.m → Class.m(me,…)`)/一意候補フォールバック(決定性確保)
- レガシー側の関数化は dev ガードで抑止可能: `NYASH_DEV_DISABLE_LEGACY_METHOD_REWRITE=1`(移行期間の重複回避)
スコープ(やること)
1) Builder: Known 化 + Rewrite 統合Stage1
- P0: me 注入・Known 化origin 付与/維持)— 軽量PHI補強単一/一致時)
- P1: Known 経路 100% 関数化obj.m → Class.m(me,…)。special は `toString→str互換:stringify/equals` を統合
- 観測: resolve.try/choose / ssa.phi を devonly で JSONL 出力既定OFF`resolve.choose``certainty` を付加し、KPIKnown率を任意出力`NYASH_DEBUG_KPI_KNOWN=1`, `NYASH_DEBUG_SAMPLE_EVERY=N`)。
2) 表示APIの統一挙動不変
- 規範: `str()` / `x.str()`(同義)。`toString()` は早期に `str()` へ正規化
- 互換: `stringify()` は当面エイリアスとして許容
- QuickRef/ガイドの更新plus混在の誘導も `str()` に統一)
3) MiniVMMirVmMin安定化devのみ
- 厳密セグメントによる単一パス化、M2/M3 代表スモーク常緑const/binop/compare/branch/jump/ret
- パリティ: VM↔LLVM↔Ny のミニ・パリティ 2〜3件
4) NYABIVM Kernel Bridge下地未配線・既定OFF
- docs/abi/vm-kernel.md関数: caps()/policy.*()/resolve_method_batch()
- スケルトン: apps/selfhost/vm/boxes/vm_kernel_box.nyashpolicy スタブ)
- 既定OFFトグル予約: NYASH_VM_NY_KERNEL, *_TIMEOUT_MS, *_TRACE
非スコープ(やらない)
- 既定挙動の変更Rust VM/LLVMが主軸のまま
- PHI/SSAの一般化Phase 16 で扱う)
- VM Kernel の本配線(観測・ポリシーは devonly/未配線)
リスクと軽減策
- 性能: 境界越えは後Phaseに限る本Phaseは未配線。MiniVMは開発補助で性能要件なし。
- 複雑性: 設計は最小APIに限定。拡張は追加のみ後方互換維持
- 安全: すべて既定OFF。FailFast方針。再入禁止/タイムアウトを仕様に明記。
受け入れ条件Acceptance
- quick: MiniVMM2/M3代表スモーク緑const/binop/compare/branch/jump/ret
- integration: 代表パリティ緑llvmlite/ハーネス)
- Builder: resolve.try/choose と ssa.phi が devonly で取得可能NYASH_DEBUG_*
- 表示API: QuickRef/ガイドが `str()` に統一(実行挙動は従前と同じ)
- Unified Call は開発既定ONだが、`NYASH_MIR_UNIFIED_CALL=0|false|off` で即時オプトアウト可能(段階移行)。
実装タスク(小粒)
1. origin/observe/rewrite の分割方針を CURRENT_TASK に反映(ガイド/README付き
2. Known fastpath の一本化rewrite::try_known_rewrite special の集約
3. 表示APIの統一toString→str、互換:stringify— VM ルータ特例の整合・ドキュメント更新
4. MirVmMin: 単一パス化・境界厳密化M2/M3・代表スモーク緑
5. docs/abi/vm-kernel.md下書き維持・スケルトン Box未配線
トグル/ENV予約、既定OFF
- NYASH_VM_NY_KERNEL=0|1
- NYASH_VM_NY_KERNEL_TIMEOUT_MS=200
- NYASH_VM_NY_KERNEL_TRACE=0|1
ロールバック方針
- MiniVMの変更は apps/selfhost/ 配下に限定(本線コードは未配線)。
- NYABIは docs/ と スケルトンBoxのみ実行経路から未参照
- Unified Call は env で即時OFF可能。問題時は `NYASH_MIR_UNIFIED_CALL=0` を宣言してレガシーへ退避し、修正後に既定へ復帰。
補足(レイヤー・ガード)
- builder 層は origin→observe→rewrite の一方向依存を維持する。違反検出スクリプト: `tools/dev/check_builder_layers.sh`
関連(参照)
- Phase 15セルフホスティング: ../phase-15/README.md
- Phase 15.5(基盤整理): ../phase-15.5/README.md
- Known/Rewrite 観測: src/mir/builder/{method_call_handlers.rs,builder_calls.rs}, src/debug/hub.rs
- QuickRef表示API: docs/reference/language/quick-reference.md
- MiniVM: apps/selfhost/vm/boxes/mir_vm_min.nyash
- スモーク: tools/smokes/v2/profiles/quick/core/
更新履歴
- 20250928 v2本書: Known 化Rewrite 統合dev観測、表示API `str()` 統一、MiniVM 安定化へ焦点を再定義
- 20250928 初版: MiniVM M3 + NYABI下地の計画

View File

@ -19,6 +19,12 @@
5) LLVM 統合任意・AOT/ハーネス)
- 実行: `tools/smokes/v2/run.sh --profile integration`
最小 Ny 実行器MirVmMin
- 目的: Ny だけで MIR(JSON v0) のごく最小セットconst/binop/compare/retを実行できることを確認。
- 実行例VM:
- `./target/release/nyash --backend vm apps/selfhost/vm/mir_min_entry.nyash`
- 引数で MIR(JSON) を渡すことも可能(単一文字列)。簡単な例は `apps/selfhost/vm/mir_min_entry.nyash` のコメントを参照。
検証
- 期待出力: `Result: 0`selfhostminimal
- スモーク:全成功(非 0 は失敗)

View File

@ -0,0 +1,76 @@
# Nyash Quick Reference (MVP)
Purpose
- Onepage practical summary for writing and implementing Nyash.
- Keep grammar minimal; clarify rules that often cause confusion.
Keywords (reserved)
- control: `if`, `else`, `loop`, `match`, `case`, `break`, `continue`, `return`
- decl: `static`, `box`, `local`, `using`, `as`
- lit: `true`, `false`, `null`, `void`
Expressions and Calls
- Function call: `f(a, b)`
- Method call: `obj.m(a, b)` — internally rewritten to function form: `Class.m(me: obj, a, b)`
- Rewrite is defaultON; backends (VM/LLVM/Ny) receive the unified call shape.
- Member: `obj.field` or `obj.m`
Display & Conversion
- Humanreadable display: `str(x)`(推奨)/ `x.str()`
- 既存の `toString()``str()` に正規化Builder早期リライト
- 互換: 既存の `stringify()` は当面エイリアス(内部で `str()` 相当へ誘導)。
- Debug表示構造的・安定: `repr(x)`将来導入、devのみ
- JSONシリアライズ: `toJson(x)`(文字列)/ `toJsonNode(x)`(構造)
Operators (precedence high→low)
- Unary: `! ~ -`
- Multiplicative: `* / %`
- Additive: `+ -`
- Compare: `== != < <= > >=`
- Logical: `&& ||` (shortcircuit, sideeffect aware)
Semicolons and ASI (Automatic Semicolon Insertion)
- Allowed to omit semicolon at:
- End of line, before `}` or at EOF, when the statement is syntactically complete.
- Not allowed:
- Line break immediately after a binary operator (e.g., `1 +\n2`)
- Ambiguous continuations; parser must FailFast with a clear message.
Truthiness (boolean context)
- `Bool` → itself
- `Integer``0` is false; nonzero is true
- `String` → empty string is false; otherwise true
- `Array`/`Map` → nonnull is true (size is not consulted)
- `null`/`void` → false
Equality and Comparison
- `==` and `!=` compare primitive values (Integer/Bool/String). No implicit crosstype coercion.
- Box/Instance comparisons should use explicit methods (`equals`), or be normalized by the builder.
- Compare operators `< <= > >=` are defined on integers (MVP).
String and Numeric `+`
- If either side is `String`, `+` is string concatenation.
- If both sides are numeric, `+` is addition.
- Other mixes are errors (dev: warn; prod: error) — keep it explicit必要なら `str(x)` を使う)。
Blocks and Control
- `if (cond) { ... } [else { ... }]`
- `loop (cond) { ... }` — minimal loop form
- `match (expr) { case ... }` — MVP (literals and simple type patterns)
Using / SSOT
- Dev/CI: filebased `using` allowed for convenience.
- Prod: `nyash.toml` only. Duplicate imports or alias rebinding is an error.
Errors (format)
- Always: `Error at line X, column Y: <message>`
- For tokenizer errors, add the reason and show one nearby line if possible.
Dev/Prod toggles (indicative)
- `NYASH_DEV=1` — developer defaults (diagnostics, tracing; behavior unchanged)
- `NYASH_ENABLE_USING=1` — enable using resolver
- `NYASH_ENTRY_ALLOW_TOPLEVEL_MAIN=1` — allow `main` as toplevel entry
Notes
- Keep the language small. Prefer explicit conversions (`int(x)`, `str(x)`, `bool(x)`) in standard helpers over implicit coercions.
- Builder rewrites method calls to keep runtime dispatch simple and consistent across backends.