docs: add MIR13 mode doc and set PHI-off as default; bridge lowering split (if/loop/try); llvmlite resolver stabilization; curated runner default PHI-off; refresh CURRENT_TASK.md

This commit is contained in:
Selfhosting Dev
2025-09-17 10:58:12 +09:00
parent 31f90012e0
commit d99b941218
131 changed files with 2584 additions and 2657 deletions

12
.github/mlc_config.json vendored Normal file
View File

@ -0,0 +1,12 @@
{
"ignorePatterns": [
{ "pattern": "^mailto:" },
{ "pattern": "^vscode:" },
{ "pattern": "^file://" }
],
"timeout": "10s",
"retryOn429": true,
"retryCount": 2,
"aliveStatusCodes": [200, 206, 429]
}

34
.github/workflows/docs-link-check.yml vendored Normal file
View File

@ -0,0 +1,34 @@
name: docs-link-check
on:
push:
paths:
- '**.md'
- '.github/workflows/docs-link-check.yml'
- '.github/mlc_config.json'
pull_request:
paths:
- '**.md'
- '.github/workflows/docs-link-check.yml'
- '.github/mlc_config.json'
jobs:
markdown-link-check:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Run markdown-link-check on docs and READMEs
uses: gaurav-nelson/github-action-markdown-link-check@v1
with:
use-quiet-mode: 'yes'
use-verbose-mode: 'no'
config-file: '.github/mlc_config.json'
folder-path: |
docs
file-path: |
README.md
README.ja.md
CLAUDE.md

View File

@ -170,7 +170,7 @@ Flags
## Commit & Pull Request Guidelines
- Commits: concise imperative subject; scope the change (e.g., "llvm: fix argc handling in nyrt").
- PRs must include: description, rationale, reproduction (if bug), and run instructions.
- Link issues (`docs/issues/*.md`) and reference affected scripts (e.g., `tools/llvm_smoke.sh`).
- Link issues (`docs/development/issues/*.md`) and reference affected scripts (e.g., `tools/llvm_smoke.sh`).
- CI: ensure smokes pass; use env toggles in the workflow as needed.
## Security & Configuration Tips

View File

@ -4,9 +4,9 @@
## Start Here (必ずここから)
- 現在のタスク: [CURRENT_TASK.md](CURRENT_TASK.md)
- 📁 **Main**: [docs/current_task/main/](docs/current_task/main/)
- 📁 **LLVM**: [docs/current_task/llvm/](docs/current_task/llvm/)
- 📁 **Self**: [docs/current_task/self_current_task/](docs/current_task/self_current_task/)
- 📁 **Main**: [docs/development/current/main/](docs/development/current/main/)
- 📁 **LLVM**: [docs/development/current/llvm/](docs/development/current/llvm/)
- 📁 **Self**: [docs/development/current/self_current_task/](docs/development/current/self_current_task/)
- ドキュメントハブ: [README.md](README.md)
- 🚀 **開発マスタープラン**: [00_MASTER_ROADMAP.md](docs/development/roadmap/phases/00_MASTER_ROADMAP.md)
- 📊 **JIT統計JSONスキーマ(v1)**: [jit_stats_json_v1.md](docs/reference/jit/jit_stats_json_v1.md)

View File

@ -1,399 +1,49 @@
# Current Task — Phase 15 SelfHosting (20250916)
# Current Task — Phase 15 SelfHosting (20250917)
TL;DR
- 目標は「自己ホスティング達成」= Nyash製パーサで Ny → JSON v0 → Bridge → MIR 実行を安定化すること。
- PyVM は意味論の参照実行器開発補助。llvmlite は AOT/検証。配布やバンドル化は後回し(基礎固めが先)。
Summary
- Default execution is MIR13 (PHIoff). Bridge/Builder do not emit PHIs; llvmlite synthesizes PHIs when needed. MIR14 (PHIon) remains experimental for targeted tests.
- PyVM is the semantic reference engine; llvmlite is used for AOT and parity checks.
What Changed (today)
- Selfhost 経路の安定化Python MVP 優先→PyVM 実行。Selfhost Stage2直/Bridgeスモークは緑化。
- Using/Resolver を Runner 前処理に集約し、BoxIndexグローバル解決キャッシュを導入。
- nyash.toml の `[aliases]`/env `NYASH_ALIASES` 対応、候補提示、`NYASH_RESOLVE_TRACE=1` でトレース。
- strict プレフィクス: `NYASH_PLUGIN_REQUIRE_PREFIX=1` または `[plugins] require_prefix=true`
- perplugin meta`prefix/require_prefix/expose_short_names`)の読取導線を実装(挙動は現状据え置き)。
- CLI `--using` を追加(`--using "ns as Alias"` / `--using '"apps/foo.nyash" as Foo'`)。
- フィールドは box 先頭のみルールのリンタを Runner に追加(`NYASH_FIELDS_TOP_STRICT=1` でエラー)。
- Syntax Torture スイートの実行正規化(末行比較)。一部テスト本文を Nyash 仕様に合わせて修正。
- JSON v0 仕様に Stage3 ードBreak/Continue/Throw/Tryを追記。Parser Stage3 設計メモの現状/残課題を更新。
- LLVM curated smokes を新設(`tools/smokes/curated_llvm.sh`。core/async/loop/peek を10s/ケースで実行、PHIoff も検証可(`--phi-off`)。
- LLVM Stage3 受理スモークを追加(`tools/smokes/curated_llvm_stage3.sh`。try/finally・dead throw を10s/ケースで実行。PHIoff`--phi-off`/trap抑止`NYASH_LLVM_TRAP_ON_THROW=0`)も確認。
- 旧スモークは `tools/smokes/archive/` へ整理JIT/Cranelift 系は当面対象外)。
- Bridge/Builder に PHI 非生成モードを導入(`NYASH_MIR_NO_PHI=1`。LLVM Resolver 合成と統一し、Verifier は緩和ゲート(`verify_allow_no_phi()`)を追加。
- LLVM 側に PHI 合成トレースを追加(`NYASH_LLVM_TRACE_PHI=1`。jump/finalize/resolve の観測を統一タグで出力。
- LLVM Throw を最小降ろし(`llvm.trap``unreachable``NYASH_LLVM_TRAP_ON_THROW=0` で trap 抑止)。
- 環境変数アクセスを `config::env` に集約(`mir_no_phi()`/`verify_allow_no_phi()`/`llvm_use_harness()`)。
- dev プロファイル `tools/dev_env.sh phi_off` を追加。ルート清掃ユーティリティ `tools/clean_root_artifacts.sh` を追加。
- CIGH Actionsを curated LLVMPHIon/off実行に刷新。旧JITジョブは停止。
- Verifier: verification.rs 内の compute_* ラッパーを撤去し、全て `verification::utils::*` を直参照に置換。
- Parser: `bit_or/xor/and``equality/comparison/range/term/shift/factor` に加え、`call/primary``parser/expr/` へ分割。`expressions.rs` は委譲ラッパーのみに縮退(互換維持)。
- Optimizer(BoxField): 同一ブロック内の set 直後の get同一 box+indexを Copy に置換する軽量 peephole を追加load-after-store 短絡)。
- LLVM(select/terminators): `function.rs` から `instructions::term_emit_*` を利用しつつ、`normalize_branch_condition()` をブランチ直前で適用する流れを固定化truthy 正規化の前段フック)。
- Runner/env 集約: `src/config/env.rs` に CLI/自ホスト/VM まわりの getter を追加(`cli_verbose()/enable_using()/vm_use_py()/ny_compiler_*()` など)。`runner/selfhost.rs`/`runner/pipe_io.rs`/`runner/modes/common.rs` のホットパスを getter 参照に更新(段階導入)。
- VM dispatch: 実装は既に dispatch 中央化済み(`backend::dispatch` 経由)。`NYASH_VM_USE_DISPATCH` フラグの getter を追加(将来の選択切替用)。
- Runner/log: `runner/trace.rs` を追加。`cli_verbose()``cli_v!` マクロを導入し、`modes/common.rs` の一部情報ログを置換verbose ガードの明確化)。
- Selfhost helpers: PyVM ハーネス実行を `NyashRunner::run_pyvm_harness(..)` として共通化。EXE パーサ経路の JSON 抽出をまとめる `exe_try_parse_json_v0(..)` を追加(段階適用の足場)。
Refactor Progress (20250916, end of day)
- Runner: ヘッダ指令スキャンとトレース出力を分離(`runner/cli_directives.rs`, `runner/trace.rs`。using 解決ログを集約。
- LLVM: terminators(select) の足場を追加し、呼び出しを alias 経由に切替(挙動不変)。
- Optimizer: パス別に分割し、オーケストレータから委譲(挙動不変の足場)。
- `optimizer_passes/{normalize,diagnostics,reorder,boxfield,intrinsics}.rs`
- 統計を `optimizer_stats.rs` へ分離。
- Verifier: 主要チェックをモジュール化し、`verification.rs` を薄いオーケストレータ化。
- `verification/{ssa,dom,cfg,barrier,legacy,awaits,utils}.rs`
- AST: `Span``ast/span.rs` へ分離し、`ast.rs` は reexport。
- Parser: expressions を段階分割ternary/coalesce/logic を `parser/expr/*` へ)。
Remaining Refactors (Phase15 mainline)
- Verifier仕上げ
- `verification.rs` 内の `compute_*` ラッパーを完全撤去し、全呼び出しを `verification::utils` に集約。
- テスト追加: reachability/phi/await チェックの簡易ケース(任意)。
- Parser段階分割の続き
- `bit_or/bit_xor/bit_and``comparison/range/term/shift/factor``parser/expr/` へ移動し、`parse_expression` チェインを維持。
- `call/primary` は最後に移動(依存が多いため)。
- AST構造の分離
- `ast/nodes/{structure,expression,statement}.rs` へノード定義を分離し、`ast.rs``pub use` 集約のみへ縮退。
- Optimizer足場→実装へ
- `reorder/boxfield/intrinsics` の実装を段階導入(まず small win: CSE のキーフィルタ改善、boxfield の load-after-store
- `normalize` の terminator 側の補完(未移行箇所があれば寄せる)。
- Runner/env 集約
- ホットパスの環境参照を `config::env` getter へ置換(残件: VM trace/diagnostics の一部)。
- Runner/log 整理第2〜第3弾
- 情報ログverbose 連動)を `cli_v!` に一本化。エラー系は従来通り eprintln のまま。
- Selfhost EXE 経路の関数抽出(仕上げ)
- 既存の EXEfirst ブロックを `exe_try_parse_json_v0(..)` を用いた薄い分岐に縮退(挙動不変)。
- LLVM select/terminators実装化
- `select` に truthy 規約の軽い正規化を追加(等価変換のみ)。
- `terminators` へ実体移動(`flow` からの段階的差し替え)。
- VM dispatch段階導入
- `NYASH_VM_USE_DISPATCH=1` フラグを導入し、無副作用命令から `backend/dispatch.rs` 経由に切替。
Notes
- すべて挙動等価の範囲で段階的に進める。足場化したモジュールは後続で実装を徐々に移す。
SelfHosting plumbing (20250916, later in day)
- Runner: 自己ホスト経路で子プログラム(`apps/selfhost-compiler/compiler.nyash`)を優先実行し、`--read-tmp` 常時付与で安定運用に変更。
- PyVM 優先の統一(`NYASH_VM_USE_PY=1`)は EXE/inline/child の全分岐で尊重。
- CLI: `--stage3` を追加(`NYASH_NY_COMPILER_STAGE3=1` を設定)。
- Script args パススルーB案実装: `nyash ... FILE -- arg1 arg2``NYASH_SCRIPT_ARGS_JSON=["arg1","arg2"]` として `Main.main(args)` に ArrayBox で注入。
- Interpreter: `ArrayBox.of(...)` を追加して初期配列を簡潔に構築。
- Runner: Python MVP は `NYASH_NY_COMPILER_SKIP_PY=1` でスキップ可能(自己ホスト子を優先)。
Decision (Phase15 wrapup)
- MIR13 移行PHI 非生成): Phase15 の締めとして、MIR 生成層Bridge/Builderは PHI を生成しない方針に切替。PHI 合成は LLVM 層llvmlite/Resolverに集約。
- LoopForm は次フェーズMIR18で導入: まずは MIR14 を維持し、次フェーズで `LoopHeader/Enter/Latch` 等の占位命令を追加。現行 Phase15 は CFG パターン検知でループ搬送値を合成。
- 例外は段階導入: Throw/Catch は現行維持Bridge ゲートで出力可。Try/Finally の構造化は将来の TryRegion で検討。
Next Focus (Throw/Try — LLVM first)
- ブリッジ設計: `emit_degraded_throw` の差し替え方針を策定し、JSON v0 `Try` ノード → MIR 変換の仕様を決めるStage-3 例外モデル)。
- MIR Builder/Runtime 調査: Rust VM/PyVM の `ControlFlow::Throw` 経路と既存 TryCatch 降格の挙動を整理。必要に応じて docs と CURRENT_TASK に反映。
- PyVM 設計: 例外モデルをどこまで Python 側に実装するか決め、最小テスト計画を用意。
- LLVM 実装方針: Throw/Try の MIR 命令を LLVM 側がどう扱うかpanic扱い or fallbackを設計し、smoke 更新案を作る(現状 Throw は trap/unreachable 最小降ろし完了)。
- テスト計画: JSON フィクスチャと `tools/llvm_smoke.sh` を中心に Stage-3 例外用のスモーク/単体テストを整備。
Open Items (handoff)
- Selfhost Stage3 E2E smokeRunner→子→JSON→Bridgeの最終緑化
- 現状: 子へ `--read-tmp` は付与済み。`--stage3` は env→子へ透過済み。
- 直近 TODO: tools/selfhost_stage3_accept_smoke.sh を Runner 優先経路に再調整し、`NYASH_NY_COMPILER_SKIP_PY=1` 併用で安定化。
- 期待値: try/finally/break/continue/throw(accept) で exit=0degrade 経路)
- CLI argv 前処理の挙動監視
- `--` なしの通常実行での Positional FILE 受理を再検証Clapの警告再現時は build_command の宣言順/Arg要件を再点検
- LLVM: Throw 実投げの終了コード方針を決定し、trap on/off の期待値を固定化。
Next Steps (suggested order)
1) Selfhost Stage3 E2E 緑化smoke 修正 → 確認)
2) CLI FILE positional の回帰があれば即修正Clap設定の微調整
3) LLVM Throw 実投げの設計(終了コード/シグナル)+スモーク
4) Runner 実装の集約modes/common → selfhost.rsと微イズ削減
5) CI に Selfhost Stage2/E2E軽量をオプションで追加
※ Cranelift/JIT 系は当面対象外。ビルド時も LLVM のみを有効化JIT 関連 feature/CI は無視)。
Runner updates (20250916)
- Selfhost pipeline: PyVM 優先(`NYASH_VM_USE_PY=1`を全分岐で適用EXE/inline/child 経路の一貫性)。
- 重複関数の整理: `modes/common.rs::try_run_ny_compiler_pipeline``selfhost.rs::try_run_selfhost_pipeline` に委譲(ドリフト防止)。
- Stage3 受理導線: `NYASH_NY_COMPILER_STAGE3=1` で子プロセスに `--stage3` を付与。inline フォールバックは `stage3_enable(1)` を既定有効化。
- llvmlite/AOT本戦強化 — コアコレクション配線とエントリ統一
- Array/Map の BoxCall を NyRT ハンドルAPIに直結
- Array: `push``nyash.array.push_h``length/len``nyash.any.length_h`
- Map: `set``nyash.map.set_hh``get``nyash.map.get_hh``has``nyash.map.has_hh``size``nyash.any.length_h`
- `ny_main` を i64 戻りに統一し、`Main.main/1` を優先(既定 args は `new ArrayBox()`)。
- Core Box 生成の安定化:`nyash.array.birth_h` / `nyash.map.birth_h` を追加し、llvmlite `new` は birth_h を優先。
- AOT 実行確認:
- `[1,2,3].length()``Result: 3`
- `{"name":"Alice","age":25}.size()``Result: 2`
- `m.has("name") ? m.get("name").length() : 0``Result: 5`
Quick Next (today)
- いよいよ「Nyash で書く」段階へSelfHosting 実装の着手):
1) ParserBox 拡張Stage2 の堅牢化・回帰修正)✅ Done 20250916
- bool/null リテラルと空 RHS代入/return/localを Int(0) フォールバックで正規化。
- simple assignment → Local 正常化を `==` 判定と共に調整。
- 三項演算子 `cond ? a : b``Ternary` ノードに正規化し、自走スモーク追加。
2) EmitterBox 拡張JSON v0 の安定化)✅ Done 20250916
- `meta.usings` を常時出力(空は `[]`)。
3) Resolver/BoxIndex の prefix メタ反映 ✅ Done 20250916
- `plugin_meta_by_box` を構築し、`require_prefix` / `expose_short_names``resolve_using_target` へ適用。
- `NYASH_PLUGIN_REQUIRE_PREFIX` が無効でも per-plugin meta で短名禁止を検知。
4) Parser Stage3 下地 ✅ Done 20250916
- `ParserBox.stage3_enable()` を追加し、Break/Continue/Throw/Try を JSON v0 に出力できるゲートを実装。
- `--stage3` CLI フラグから ParserBox へ渡す導線を追加。
- `docs/reference/architecture/parser_mvp_stage3.md` に Stage3 設計を記録。
5) 自己ホスト経路で Ny 実装切替のゲート準備(現状は Python MVP 優先を維持)。
6) テスト:
- `source tools/dev_env.sh pyvm`
- `NYASH_VM_USE_PY=1 ./tools/selfhost_stage2_smoke.sh`
- `NYASH_VM_USE_PY=1 ./tools/selfhost_stage2_bridge_smoke.sh`
- TortureVM中心: `(cd tests/nyash_syntax_torture_20250916 && BACKENDS="vm" NYASH_BIN=../../target/release/nyash bash run_spec_smoke.sh)`
- LLVM Stage3 smoke (手動): `NYASH_LLVM_STAGE3_SMOKE=1 ./tools/llvm_smoke.sh release`
- Runner/Bridge 実行系
- `--ny-parser-pipe``NYASH_PIPE_USE_PYVM=1` で PyVM に委譲exit code 判定に統一)。
- 自己ホスト JSON 生成は Python MVP を優先、LLVM EXE/インラインVMを段階フォールバック。
- Runner 分割第1弾〜第2弾: `dispatch.rs` へ backend 分岐を集約、`tasks.rs`/`build.rs`/`demos.rs` へ職責分離。`mod.rs` を薄型化。
- LLVM Codegen リファクタ第1弾〜第2弾
- `codegen/utils.rs` を新設し `sanitize_symbol`/`build_const_str_map` を抽出。
- `codegen/function.rs` を追加し `lower_one_function` を完全移管(呼び出しは `function::lower_one_function`)。
- 旧レガシー断片コメントを除去して軽量化。機能・出力は不変。
- MIR Builder 整理(小分割)
- `builder/vars.rs` を追加し、Lambda の自由変数収集ロジックを外出し。
- 既存の `LoopBuilder`/`phi` 分割方針は維持(今後 small utils を `loops.rs` に抽出予定)。
What Changed (recent)
- MIR13 default enabled
- `mir_no_phi()` default set to true (can disable via `NYASH_MIR_NO_PHI=0`).
- Curated LLVM runner defaults to PHIoff; `--phi-on` enables MIR14 lane.
- Added doc: `docs/development/mir/MIR13_MODE.md`; README references it.
- JSON v0 Bridge lowering split (nonfunctional)
- Added `src/runner/json_v0_bridge/lowering/{if_else.rs, loop_.rs, try_catch.rs, merge.rs}` and routed calls from `lowering.rs`.
- llvmlite stability for MIR13
- Resolver: forbids crossblock nondominating vmap reuse; for multipred and no declared PHI, synthesizes a localization PHI at block head.
- Finalize remains functionlocal; `block_end_values` snapshots and placeholder wiring still in place.
- Parity runner pragmatics
- `tools/pyvm_vs_llvmlite.sh` compares exit code by default; use `CMP_STRICT=1` for stdout+exit.
Current Status
- Stage2: 自己ホスト → JSON v0 → PyVM の代表スモークは緑(配列/文字列/論理/if/loop)。
- Stage3: 構文受理のみ完了break/continue/throw/try/catch/finally。現時点では JSON 降格noop/Exprで安全受理。
- Runner: Using/Resolver を前処理に統合BoxIndex/キャッシュ/strict`--ny-parser-pipe` は PyVM 委譲exit code 判定)。
- llvmlite/AOT: Array/Map の基本操作push/get/set/has/size, lengthが NyRT ハンドルAPIで動作。`ny_main` は i64 戻り・`Main.main/1` 優先で起動。
- ログ: verbose 出力の一部を `cli_v!` で共通化(引き続き適用範囲を拡大中)。
- Selfhosting Bridge → PyVM smokes: PASS (Stage2 reps: array/string/logic/if/loop).
- Curated LLVM (PHIoff default): PASS.
- Curated LLVM (PHIon experimental): `apps/tests/loop_if_phi.nyash` shows a dominance issue (observed; not blocking, MIR13 recommended).
Open
- Bridge/PHI の正規化: 短絡(入れ子)における merge/PHI incoming を固定化rhs_end/fall_bb の順序)。
- JSON v0 の拡張方針: break/continue/try/catch/finally の表現(受け皿設計 or 受理時の事前降下)。➡ `docs/reference/architecture/parser_mvp_stage3.md`
- perplugin meta の反映: `require_prefix/expose_short_names/prefix` を Resolver 挙動へ段階適用(導線は実装済み)。✅ 20250916 prefix enforcement とテスト追加済み。
- `me` の扱い: MVP は `NYASH_BRIDGE_ME_DUMMY=1` の仮注入を継続(将来撤去)。
- LLVM 直結(任意): JSON v0 → LLVM の導線追加は後回し。
Next (short plan)
1) JSON v0 lowering: split remaining helpers (peek/ternary/expr) without behavior change.
2) PHIon lane (optional): investigate `loop_if_phi` dominance by tightening finalize ordering and resolver materialization (low priority).
3) Runner refactor (small PRs):
- `selfhost/{child.rs,json.rs}` split; `modes/common/{io,resolve,exec}.rs` split; reduce `runner/mod.rs` surface.
4) Optimizer/Verifier thinhub cleanup (nonfunctional): orchestrator minimalization and pass boundaries clarified.
- NyRT 整頓:
- FFI ヘルパー化handles/boxing 正規化birth_h→new_i64x 統合Core Box のプラグイン事前登録FFI エクスポートのマクロ化。
- llvmlite 整頓:
- boxcall のテーブル駆動化、追加 APIdelete/keys/values など)の段階配線。
How to Run
- PyVM reference smokes: `tools/pyvm_stage2_smoke.sh`
- Bridge → PyVM smokes: `tools/selfhost_stage2_bridge_smoke.sh`
- LLVM curated (PHIoff default): `tools/smokes/curated_llvm.sh`
- LLVM PHIon (experimental): `tools/smokes/curated_llvm.sh --phi-on`
- Parity (AOT vs PyVM): `tools/pyvm_vs_llvmlite.sh <file.nyash>` (`CMP_STRICT=1` to enable stdout check)
Plan (to SelfHosting)
1) Phase1: Stage2 完了+堅牢化(今ここ)
- 正常系スモークを自己ホスト直/BridgePyVMで常緑化追加分を反映済み
- 進捗ガードの継続検証(不完全入力セット)。
2) Phase2: Bridge 短絡/PHI 固定+パリティ収束
- 入れ子短絡の merge/PHI incoming を固定し、stdout 判定でスモークを緑化。
- PyVM/llvmlite パリティを常時緑(代表ケースを exit code 判定へ統一)。
3) Phase3: 構文受理の拡張(完了)→ Bootstrap c0→c1→c1
- 受理のみ: break/continue/throw/try-catch-finally実行意味論は降格
- emitonly で c1 を生成→既存経路にフォールバック実行、正規化 JSON 差分で等価を確認。
How to Run (dev)
- 推奨環境: `source tools/dev_env.sh pyvm`PyVM を既定。Bridge→PyVM 直送)
- 自己ホスト(子経路 ON: `NYASH_USE_NY_COMPILER=1`
- 安全弁: `NYASH_NY_COMPILER_TIMEOUT_MS=2000`、emitonly 既定: `NYASH_NY_COMPILER_EMIT_ONLY=1`
Smokes
- 無限ループ防止: `./tools/selfhost_progress_guard_smoke.sh`
- 自己ホスト → InterpreterBoxCallなし集合: `./tools/selfhost_stage2_smoke.sh`
- 自己ホスト → JSON → PyVMArray/String/Console 含む): `./tools/selfhost_stage2_bridge_smoke.sh`
- 動作確認(ローカル)
- VM: `./target/debug/nyash --backend vm apps/tmp_hello.nyash`Result: 0
- LLVM モック: `./target/debug/nyash --backend llvm apps/tmp_hello.nyash`
- PyVM/Stage2: `tools/pyvm_stage2_smoke.sh`All PASS
- Bridge/Stage2: `tools/ny_stage2_bridge_smoke.sh`All PASS
Key Flags
- `NYASH_MIR_NO_PHI` (default 1): PHIoff when 1 (MIR13). Set `0` for PHIon.
- `NYASH_VERIFY_ALLOW_NO_PHI` (default 1): relax verifier for PHIless MIR.
- `NYASH_LLVM_USE_HARNESS=1`: route AOT through llvmlite harness.
- `NYASH_LLVM_TRACE_PHI=1`: trace PHI resolution/wiring.
Notes / Policies
- PyVM は意味論の参照実行器として運用exit code 判定を基本)。
- Bridge は JSON v0 → MIR 降下で PHI を生成Phase15 中は現行方式を維持)。
- 配布/バンドル/EXE 化は任意の実験導線として維持Phase15 の主目的外)。
- Focus is selfhosting stability. JIT/Cranelift is out of scope (safety fixes only).
- PHI generation remains centralized in llvmlite; Bridge/Builder keep PHIoff by default.
- No full tracing GC yet; handles/Arc lifetimes govern object retention. Safepoint/barrier/roots are staging utilities.
Smoke Snapshot (20250915)
- 修正: `runner/dispatch.rs``vm` 分岐が欠落しており `--backend vm` が interpreter にフォールバックしていたため、PyVM スモークが作動せず。分岐を追加して復旧済み。
- PyVM Stage2 部分結果:
- PASS: string ops basic, me method call
- FAIL: loop/if/phi → 出力 `sum=4`(期待 `sum=9`
- 原因分析: ループ内 if の merge で `sum` の Phi 正規化が入らず、latch 側スナップショットが else 系の一時値を優先(`16`)しうる構造。`LoopBuilder::build_statement(If)``normalize_if_else_phi` 相当を呼ばず、変数マップが φ 統合されていない。
- 対応方針(最小修正):
- LoopBuilder の If 降下で merge 到達時に「両枝が同一変数に代入」の場合は `phi(dst=[then,else])` を emit→その φ を対象変数に bind。
- latch スナップショットはこの φ 後の変数マップで採取する。
- 代替(短期): Builder 側の `normalize_if_else_phi` を呼ぶ薄いフックを設けて流用。
Fixes Applied (20250915)
- LoopBuilder If 降下に φ 正規化を追加(両枝代入の変数を merge 時に φ で束ねて再束縛)。
- PyVM φ 解決ロジックを安定化incoming を [value, pred] 形に限定し、[pred, value] の曖昧推測を削除)。偶然一致による誤選択を排除。
- これにより `tools/pyvm_stage2_smoke.sh` は全 PASS を確認済み。
Refactor Candidates (early plan)
- runner/mod.rs~70K chars: “runner pipeline” を用途別に分割TODO #15
- runner/pipeline.rs入力正規化/using解決/環境注入)
- runner/pipe_io.rsstdin/file の JSON v0 受理・整形)
- runner/selfhost.rs自己ホスト EXE/VM/Python フォールバック、timeout/ログ含む)
- runner/dispatch.rsbackend 選択と実行、PyVM 委譲)
- 既存 json_v0_bridge/mir_json_emit は流用、mod.rs から薄いファサードに縮退。
- backend/llvm/compiler/codegen責務分割の継続
- 済: utils 抽出、`lower_one_function``function.rs` へ移管。
- 次: 終端系・選択系の薄層切り出し。
- `instructions/terminators.rs`: return/jump/branch の分岐ドライバemit_* 呼び出し集約)。
- `instructions/select.rs`: 条件・短絡・PHI 前処理sealed-SSA 前提の前段正規化)。
- 目標: `function.rs` の見通し改善1関数=制御フロー骨格)、テスト容易化。
- mir/builder.rsヘッダ~80行、全体~1K行
- 既に多くを modules に分割済み。残る “variable/phi 合流”“loop ヘッダ/出口管理” を builder/loops.rs / builder/phi.rs に抽出。
- 目標: 依存関係utils/exprs/stmtsを維持したまま、1ファイル1責務を徹底。
Recommended Next (short list)
- LLVM CodegenB 継続)
- `instructions/terminators.rs` を新設し、`function.rs` から終端分岐return/jump/branchを移譲。
- `instructions/select.rs` を新設し、条件/短絡/PHI 前処理sealed-SSA 前提の軽い正規化)を集約。
- `function.rs` は「BB 周回+各 lowering 呼び出し」の骨格のみへ縮退。
- MIR BuilderC 継続)
- `builder/loops.rs` を新設し、ループのヘッダ/出口の小物ユーティリティを抽出(`LoopBuilder` の補助レイヤ)。
Refactor Plan (MIR Core / Parser / Runner)
- MIR Core中〜高
- 問題点
- `optimizer.rs``verification.rs` に処理が集中し、追加パスや検証増に弱い構造(巨大化: 994/980 行規模)。
- 提案
- パス駆動に分割: `mir/passes/{dce.rs, ssa.rs, const_fold.rs, simplify.rs}``MirPass` トレイト(`run(&mut MirModule)`)。
- 進捗: dce/cse 抽出済み、`MirPass` 骨格導入済み。次は normalize 系の抽出を段階実施。
- `optimizer.rs` はパイプライン組立順序・ゲート・Stats 集約)に縮小。
- `verification.rs` もカテゴリ分割ブロック整合性、SSA/PHI、型整合。失敗メッセージ表現の一貫化hintを統一
- Parser/Tokenizer
- 問題点
- `parser/expressions.rs`~986行`parser/statements.rs`~562行`tokenizer.rs`~863行が肥大。
- 提案
- Pratt/precedence テーブル化で演算子別分岐の重複削減。
- 共通エラー生成ユーティリティで `expected(...)` メッセージを統一。
- `tokenizer.rs``tokens.rs`(定義)と `lexer.rs`(実装)に分離。テストは `tests/lexer_*.rs` へ退避。
- Runner
- 問題点
- `runner/modes/common.rs`~734行`runner/mod.rs`~597行に CLI/環境フラグ/実行分岐が混載。
- 提案
- `runner/modes/common/` ディレクトリ化し、CLI引数処理・環境フラグ解決・モードディスパッチを分離。
- 重複ログ/検証を共通ヘルパへ集約。
- `builder/vars.rs` に SSA 変数正規化の小物を段階追加(変数名再束縛/スコープ終端の型ヒント伝搬など)。
- Runner仕上げ
- `mod.rs` の残置ヘルパusingの候補提示・環境注入ログ`pipeline/dispatch` へ集約し、`mod.rs` を最小のオーケストレーションに。
- Namespaces Phase1実装着手: BoxIndex 構築・3段階解決・toml aliases・曖昧エラー改善・トレース
Smoke Policy (Phase15)
- PyVM: 一部チェックのみasync/nowait/await/GC/sync は対象外)
- LLVM: フル対応llvmlite harness`tools/smokes/curated_llvm.sh [--phi-off]` を利用
- JIT: 未整備JIT向けスモークは `tools/smokes/archive/` に移管)
- Stage3 acceptanceBridge 経路): `tools/ny_stage3_bridge_accept_smoke.sh`Try/Break/Continue/Throw を JSON v0 で受理できることを確認)
Next Phase — Selfhost Parser/Compiler in Nyash着手準備完了
- 目的: Nyash スクリプトで Parser/Emitter を実装し、Ny → JSON v0 → Bridge → MIR 実行の自己ホスト路線に移行。
- ステップ(最小 MVP:
1) `apps/selfhost-compiler/` に ParserBox/EmitterBox を Nyash で実装Stage2 構文、JSON v0 出力)。
2) ランナーに `NYASH_USE_NY_COMPILER=1` ゲートを追加し、子プロセス/pipe で JSON v0 を受け取って Bridge→MIR 実行。
3) curated LLVM スモークの一部を自己ホスト経路で通すPyVMは非対象、LLVMで検証
4) CI に自己ホスト最小ジョブを追加timeout/静音運用、PHIon 既定)。
- ガード/ポリシー:
- 既存 Rust Parser/Emitter はフォールバックとして保持(`NYASH_SKIP_TOML_ENV=1` で隔離可能)。
- 仕様差が出た場合は LLVM 側の意味論に合わせて Nyash 実装を調整。
MIR13 PlanPhase15 終盤)
- Bridge/Builder: PHI を生成しない受理は維持。If/Loop の合流は LLVM Resolver に任せる。
- llvmlite: Resolver を使い、BB 先頭で PHI 合成。ループは preheader/cond/body の CFG から搬送値を復元break は exit 側でマージ)。
- Smoke: LLVM はまず looponlybreak/continueを常時緑化。例外系throw/tryは IR 降ろし込み整備後に復帰。
- 詳細設計: `docs/private/papers/paper-e-loop-signal-ir/mir-evolution-plan.md` に MIR14→MIR13→MIR17 の段階的移行計画を記載。
Array/Map Literals PlanSyntax Sugar
- Stage1: Array literal `[e1, e2, ...]` を実装(ゲート: `NYASH_SYNTAX_SUGAR_LEVEL=basic|full` または `NYASH_ENABLE_ARRAY_LITERAL=1`)。
- Lowering: `new ArrayBox()` → 各要素を評価 → `.push(elem)` を左から右に順に発行 → 最後に配列値を返す。
- 末尾カンマ許可。
- スモーク: `apps/tests/array_literal_basic.nyash`size/順序/副作用1回性
- Stage2: Map literal `{ "k": v, ... }`(文字列キー限定)を実装(ゲート: `NYASH_SYNTAX_SUGAR_LEVEL=basic|full` or `NYASH_ENABLE_MAP_LITERAL=1`)。
- Lowering: `new MapBox()` → 各ペアを評価 → `.set("k", v)` を左から右に順に発行 → 最後に map 値を返す。
- 末尾カンマ許可。識別子キー糖 `{name: v}` は次フェーズ。
- スモーク: `apps/tests/map_literal_basic.nyash`size/get/順序検証)。
- Stage3: 識別子キー糖 `{name: v}` と末尾カンマを強化(任意)。
Gates / Semantics
- 左から右で評価一度だけ。push/set 失敗は即時伝播(既存 BoxCall 規約に追従)。
- IR 変更なしBoxCall/MethodCall のみ)。将来 `with_capacity(n)` 最適化は任意で追加。
Decision Log (20250915)
- Q: 警告削減(`ops_ext.rs` / `selfhost.rs`)を先にやる?それとも挙動スモークを先に回す?
- A: スモークを先に実施。理由は以下。
- リファクタ直後は回帰検出を最優先PyVM/自己ホスト/Bridge の3レーンで即座に検証
- 警告削減は挙動非変化を原則とするが、微妙なスコープや保存スロットの触りが混入し得るため、先に“緑”を固める。
Namespaces / Using現状
- 解決順(決定性): 1) ローカル/コア → 2) エイリアスnyash.toml/env→ 3) 相対/using.paths → 4) プラグイン(短名/qualified
- 曖昧時はエラー候補提示qualified または alias を要求)。
- モード切替: Relaxed既定/Strict`NYASH_PLUGIN_REQUIRE_PREFIX=1` または toml `[plugins] require_prefix=true`
- needs 糖衣は using の同義Runner で alias 登録)。
- Plugins は統合名前空間。qualified `network.HttpClient` 常時許可。
- nyash.tomlMVP: `[aliases]`/`[plugins]`(グローバル `require_prefix` のみ反映。perplugin は導線のみ)
- Index とキャッシュRunner:
- BoxIndexグローバル: `plugin_boxes`, `aliases` を保持。plugins init 後に構築。
- Resolve Cacheグローバル: `tgt|base|strict|paths` キーで再解決回避。
- `NYASH_RESOLVE_TRACE=1`: 解決手順/キャッシュヒット/未解決候補をログ出力。
- スモークが緑=基礎健全性確認後に、静的ノイズの除去を安全に一気通貫で行う。
**AOT Quick**
- Array literal: `NYASH_SYNTAX_SUGAR_LEVEL=basic ./tools/build_llvm.sh tmp/aot_array_literal_main.nyash -o app && ./app`
- Map literal: `NYASH_SYNTAX_SUGAR_LEVEL=basic NYASH_ENABLE_MAP_LITERAL=1 ./tools/build_llvm.sh tmp/aot_map_literal_main.nyash -o app && ./app`
Refactoring Plan (Phase15 followup)
- 背景: 巨大ファイルAST/MIR/LLVMが保守コスト増の主因。機能非変化の小刻みリファクタで視認性と変更容易性を上げる。
- 目的と範囲(非機能変更・段階適用)
1) ASTsrc/ast.rs:1: 定義とヘルパの分離、将来のサブenum活用導線の整備現行API互換
2) MIR Buildersrc/mir/builder.rs:1: build_module の骨格化・責務分離、既存分割builder/*)の徹底。
3) Python LLVMsrc/llvm_py/llvm_builder.py:1: lower_function の前処理/本体分離、lower_block の責務拡張。
4) MIR 命令src/mir/instruction.rs:1: 構造体+トレイト導線の導入enum への委譲を維持した非破壊移行)。
- 実施順小PR単位、CI緑維持
PR1: AST utils 抽出(非破壊)
- 追加: `src/ast/utils.rs` に classify/info/span/to_string などのヘルパを移設。
- `src/ast.rs` は ASTNode/StructureNode/ExpressionNode/StatementNode の定義中心に縮退。
- 互換維持: `pub use ast::utils::*;` で既存呼び出しを壊さない。
- 受入: 全ビルド/スモーク緑、差分はファイル移動のみ。
PR2: MIR Builder build_module 分割(非破壊)
- `build_module``prepare_module`/`lower_root`/`finalize_module` に3分割。
- 型推定value_types→返り値は finalize 側へ集約(現行ロジック移設)。
- 既存の exprs/stmts などの委譲を明示し、build_module 本体を「骨格のみ」に縮退。
- 受入: LLVM/PyVM/Bridge スモーク緑(挙動非変化)。
PR3: Python LLVM lower_function の前処理抽出
- 新設: `setup_phi_placeholders()` を導入し、PHI 宣言/CFG 依存前処理をここへ移設。
- `lower_block()` に snapshotblock_end_values 収集)までの責務を移動。メインループは薄い周回に。
- 受入: `tools/smokes/curated_llvm.sh` / `curated_llvm_stage3.sh` 緑。
PR4: AST ラッパー導入(非破壊導線)
- 追加: `src/ast/nodes.rs` に小さな構造体群Assign/Return/...)。
- enum `StatementNode/ExpressionNode` を構造体で保持。`From<T> for ASTNode` / `TryFrom<ASTNode> for T` を提供。
- Builder 入口(`builder/stmts.rs`, `builder/exprs.rs`)で ASTNode → TryFrom 変換を 1 行追加し以降はサブ型で match。
- 受入: ビルド/スモーク緑(機能非変化)。
PR5: MIR 命令トレイト POCConst/BinOp
- 追加: `src/mir/instruction_kinds/``const_.rs`, `binop.rs`(各命令を struct 化)。
- 共通トレイト `InstructionMeta { effects(), dst(), used() }` を定義。
- `MirInstruction::{effects,dst_value,used_values}` から一部を構造体 impl に委譲match 縮退の礎)。
- 受入: スモーク緑、`instruction_introspection.rs` の挙動非変化。
- リスクとガード
- 機能非変化を原則(挙動差分は不可)。
- CI で LLVM/Bridge を優先確認。Selfhost/E2E は任意ジョブで回す。
- PR は 400 行未満/ファイル移動中心を目安に分割。
- 参考ファイル
- AST: `src/ast.rs`, (新規)`src/ast/utils.rs`, (将来)`src/ast/nodes.rs`
- Builder: `src/mir/builder.rs`, `src/mir/builder/*`
- Python LLVM: `src/llvm_py/llvm_builder.py`
- MIR 命令: `src/mir/instruction.rs`, (新規)`src/mir/instruction_kinds/*`
Acceptance Criteria
- すべての変更は機能非変化(スモーク/CI 緑)。
- 大型関数・巨大match の見通しが改善し、追従点が局所化。
- 新規追加の導線AST サブ型/命令トレイト)は既存 API と共存し、段階移行を可能にする。

View File

@ -103,7 +103,7 @@ TODObitops
- 走査: コメント(`//`, `#`)・文字列内の `include` を無視する状態機械を導入(誤検出抑制)。
- サンプル: `apps/selfhost/smokes/dep_smoke_root.nyash`(子: `dep_smoke_child.nyash`)。
出力仕様・受け入れ基準: docs/selfhost/dep_tree_min_string.md に移設CURRENT_TASKは要点のみ表記
出力仕様・受け入れ基準: docs/development/current/selfhost/dep_tree_min_string.md に移設CURRENT_TASKは要点のみ表記
残タスクPhase 0 必須)
- P0-2: スモーク(循環あり/なし)と合わせて確認(追加済み)。
@ -439,9 +439,9 @@ Phase A 進捗(実施済)
- Phase 12 クローズアウト完了。言語糖衣12.7-B/P0と VM 分割は反映済み。
- Phase 15Self-Hosting: Cranelift AOTへフォーカス移行。
- 設計/仕様ドキュメントとスモーク雛形を追加済み。
- 設計: `docs/backend-cranelift-aot-design.md`
- API案: `docs/interfaces/cranelift-aot-box.md`
- LinkerBox: `docs/interfaces/linker-box.md`
- 設計: `docs/design/backend-cranelift-aot-design.md`
- API案: `docs/design/cranelift-aot-box.md`
- LinkerBox: `docs/design/linker-box.md`
- スモーク仕様: `docs/tests/aot_smoke_cranelift.md`
- 雛形スクリプト: `tools/aot_smoke_cranelift.sh`, `tools/aot_smoke_cranelift.ps1`
- README にセルフホスト到達の道筋を明記C ABI を Box 化)。
@ -848,7 +848,7 @@ Phase A 進捗(実施済)
- 参照
- Phase 15 概要/ロードマップ: `docs/development/roadmap/phases/phase-15/README.md`, `docs/development/roadmap/phases/phase-15/ROADMAP.md`
- ハンドオフ: `docs/handoff/phase-15-handoff.md`
- 設計/API: `docs/backend-cranelift-aot-design.md`, `docs/interfaces/*`
- 設計/API: `docs/design/backend-cranelift-aot-design.md`, `docs/design/*`
■ 合否基準P0: Ny→MIR→MIR-Interp→VM 最小成立)
- 自作Nyashパーサ最小サブセットが Nyash で動作し、テスト入力から中間形式(JSON暫定)を生成できる。

View File

@ -11,7 +11,8 @@ categories = ["development-tools::parsing", "interpreters"]
# Default features - minimal CLI only
[features]
default = ["cli", "plugins"]
default = ["cli", "plugins", "interpreter-legacy"]
interpreter-legacy = []
e2e = []
cli = []
plugins-only = []

View File

@ -15,7 +15,7 @@
---
開発者向けクイックスタート: `docs/DEV_QUICKSTART.md`
セルフホスト1枚ガイド: `docs/self-hosting.md`
セルフホスト1枚ガイド: `docs/how-to/self-hosting.md`
## 目次
- [Self-Hosting自己ホスト開発](#self-hosting)
@ -23,7 +23,7 @@
<a id="self-hosting"></a>
## 🧪 Self-Hosting自己ホスト開発
- ガイド: `docs/self-hosting.md`
- ガイド: `docs/how-to/self-hosting.md`
- 最小E2E: `NYASH_DISABLE_PLUGINS=1 ./target/release/nyash --backend vm apps/selfhost-minimal/main.nyash`
- スモーク: `bash tools/jit_smoke.sh` / `bash tools/selfhost_vm_smoke.sh`
- Makefile: `make run-minimal`, `make smoke-selfhost`

View File

@ -15,7 +15,8 @@
---
Developer quickstart: see `docs/DEV_QUICKSTART.md`. Changelog highlights: `CHANGELOG.md`.
Selfhosting onepager: `docs/self-hosting.md`.
MIR mode note: default is MIR13 (PHI-off). See `docs/development/mir/MIR13_MODE.md`.
Selfhosting onepager: `docs/how-to/self-hosting.md`.
## Table of Contents
- [SelfHosting (Dev Focus)](#self-hosting)
@ -23,7 +24,7 @@ Selfhosting onepager: `docs/self-hosting.md`.
<a id="self-hosting"></a>
## 🧪 SelfHosting (Dev Focus)
- Guide: `docs/self-hosting.md`
- Guide: `docs/how-to/self-hosting.md`
- Minimal E2E: `NYASH_DISABLE_PLUGINS=1 ./target/release/nyash --backend vm apps/selfhost-minimal/main.nyash`
- Smokes: `bash tools/jit_smoke.sh` / `bash tools/selfhost_vm_smoke.sh`
- Makefile: `make run-minimal`, `make smoke-selfhost`

View File

@ -178,4 +178,4 @@ The analysis reveals a well-architected system that would benefit from tactical
Phase 15 Addendum (Mainline only)
- Implemented: extracted CLI directives scanning and fields-top lint into `src/runner/cli_directives.rs` to slim `src/runner/mod.rs` without behavior changes.
- Proposed next steps (non-JIT): see `docs/refactoring/candidates_phase15.md` for focused items on Runner/LLVM/VM.
- Proposed next steps (non-JIT): see `docs/development/refactoring/candidates_phase15.md` for focused items on Runner/LLVM/VM.

BIN
app_pyvm_cmp Normal file

Binary file not shown.

View File

@ -19,7 +19,7 @@ Quickstart
Docs
- Onepage guide: `docs/self-hosting.md`
- Onepage guide: `docs/how-to/self-hosting.md`
Flags

View File

@ -3,7 +3,7 @@
This quickstart summarizes the most common build/run/test flows when working on Nyash.
See also
- Selfhosting onepager: `docs/self-hosting.md`
- Selfhosting onepager: `docs/how-to/self-hosting.md`
## Build
- VM/JIT (Cranelift): `cargo build --release --features cranelift-jit`

View File

@ -6,7 +6,7 @@
---
## 📂 新しいドキュメント構造(2025年8月20日再編成
## 📂 ドキュメント構造(指針
### 📖 [reference/](reference/) - 正式な技術仕様
- **language/** - 言語仕様構文、型システム、Box仕様
@ -22,6 +22,9 @@
- **examples/** - 実践的なサンプルコード
- **wasm-guide/** - WebAssemblyビルドガイド
### 🧩 [how-to/](how-to/) - 目的別ハウツー
- 手順重視の短いガイド(前提→コマンド→検証)
### 🔧 [development/](development/) - 開発者向け
- **current/** - 現在進行中のタスクCURRENT_TASK.md等
- **roadmap/** - 開発計画
@ -54,6 +57,9 @@
- [実行バックエンド](reference/architecture/execution-backends.md)
- [プラグインシステム](reference/plugin-system/)
- [CLIオプション早見表](tools/cli-options.md)
### デザイン
- [設計ノート(入口)](design/)
### 開発状況
- [現在のタスク](../CURRENT_TASK.md)
@ -63,7 +69,7 @@
---
## 📋 再編成について
## 📋 再編成について / フォルダの見分け方
ドキュメントは2025年8月20日に再編成されました。詳細は[REORGANIZATION_REPORT.md](REORGANIZATION_REPORT.md)を参照してください。
旧パスから新パスへの主な変更:
@ -73,4 +79,10 @@
---
補足:
- `reference/` は正本(仕様)。
- `guides/` は読み物、`how-to/` は手順書。
- `design/` は公開できる設計ノート。
- `private/` は下書き保管庫(将来 `reference/`/`design/` に昇格)。
Nyash は「Everything is Box」哲学に基づく言語です。詳細はコア概念とガイドを参照してください。

View File

@ -1,42 +1,14 @@
# Nyash Archive 🗄️
# Nyash Docs Archive
過去のドキュメント、設計決定、相談記録のアーカイブです。
This folder stores deprecated or historical documents. Links from active docs should not point here.
## 📂 ディレクトリ構造
When moving files into `archive/`:
- Add a brief note at the top explaining why it was archived and the new canonical location if any.
- Do not update content except light headers; avoid drifting from the canonical reference.
### consultations/
AI相談記録の保管場所
- **gemini/** - Gemini AIとの相談記録
- **chatgpt/** - ChatGPTとの相談記録
- **codex/** - Codexの解析結果
When searching for current information, prefer:
- `docs/reference/` (specifications)
- `docs/guides/` (user guides)
- `docs/how-to/` (taskoriented steps)
- `docs/design/` (stable architecture notes)
### decisions/
過去の設計決定とその理由
- アーキテクチャ決定記録ADR
- 廃止された機能の説明
- 設計変更の経緯
### build-logs/
ビルドログとベンチマーク結果
- パフォーマンス測定記録
- ビルドエラーの履歴
- 最適化の記録
### old-versions/
古いバージョンのドキュメント
- 廃止された仕様
- 以前のガイドやチュートリアル
- 旧バージョンのREADME
### generated/
自動生成されたドキュメント
- MIRダンプ
- ベンチマーク結果
- コード解析レポート
## ⚠️ 注意事項
このディレクトリの内容は歴史的参照用です。重複・旧版の資料が含まれます。
最新の計画・仕様は以下を参照してください:
- 現行の計画PLAN: `docs/development/roadmap/phases/phase-11.8_mir_cleanup/PLAN.md`
- 技術仕様TECHNICAL_SPEC: `docs/development/roadmap/phases/phase-11.8_mir_cleanup/TECHNICAL_SPEC.md`
- そのほか: `/reference/`(リファレンス), `/guides/`(利用ガイド), `/development/`(開発状況)

View File

@ -1,9 +0,0 @@
# CURRENT TASK — アーカイブ20250906
このファイルは `CURRENT_TASK.md` の旧来の完全版をそのまま保存するアーカイブです。
Cranelift/AOT/JITAOT 関連の詳細は今後 `docs/phase-15/cranelift/CRANELIFT_TASKS.md` 側で更新します。
注意: ここに記載のコマンドやパスは当時点のものです。最新の手順や方針は `CURRENT_TASK.md` と phase15 配下のドキュメントを参照してください。
(元の内容は Git 履歴から参照してください)

View File

@ -1,22 +0,0 @@
# Debug Reports
ChatGPT5さんへの調査依頼レポート集です。
## 最新レポート2025-09-11
### 1. chatgpt5_debug_request.md 🎯 **最重要**
プラグイン戻り値表示バグの根本原因を特定した詳細レポート:
- 問題の流れを完全に追跡
- nyrt::console.log_handleでの問題箇所を特定
- デバッグ提案を含む
### 2. chatgpt5_llvm_string_concat_bug.md
文字列連結バグも含む包括的なレポート:
- MIRでの型推論ミスString + Integer → Integer
- LLVMエラーの詳細
## テストファイル
`local_tests/test_plugin_*.nyash` - バグ再現用のテストファイル
## 使用方法
これらのレポートをChatGPT5に提示して、問題の修正を依頼してください。

View File

@ -1,66 +0,0 @@
# ChatGPT5さんへプラグイン戻り値表示バグ詳細調査レポート
## 🎯 根本原因特定完了
### 問題の流れ
1. **プラグイン戻り値取得** ✅ 正常
- `CounterBox.get()` → 整数2が返される
- L1016でvmapに生のi64値として格納
2. **LLVM console.log呼び出し** ✅ 正常
- L1270で`nyash.console.log_handle(生のi64値)`呼び出し
3. **nyrt処理****ここに問題**
```rust
// crates/nyrt/src/lib.rs:2391-2401
pub extern "C" fn nyash_console_log_handle(handle: i64) -> i64 {
if let Some(obj) = handles::get(handle as u64) { // ← 生の値2でハンドル検索→失敗
let s = obj.to_string_box().value;
println!("{}", s);
} else {
println!("{}", handle); // ← なぜか空白表示される
}
}
```
### 疑問点
**なぜ`println!("{}", handle)`が空白になるのか?**
- handleには実際の値2が入っているはず
- なぜprintln!が何も出力しない?
## 🔍 必要な修正案
### 提案1: デバッグ出力追加
```rust
pub extern "C" fn nyash_console_log_handle(handle: i64) -> i64 {
eprintln!("DEBUG: handle={}", handle); // デバッグ出力
if let Some(obj) = handles::get(handle as u64) {
let s = obj.to_string_box().value;
println!("{}", s);
} else {
eprintln!("DEBUG: handle {} not found in registry", handle);
println!("{}", handle); // 元のコード
}
0
}
```
### 提案2: 生の整数値対応
```rust
pub extern "C" fn nyash_console_log_handle(handle: i64) -> i64 {
if let Some(obj) = handles::get(handle as u64) {
let s = obj.to_string_box().value;
println!("{}", s);
} else {
// プラグイン戻り値の生の整数を直接表示
println!("{}", handle);
eprintln!("DEBUG: Printed raw value {}", handle);
}
0
}
```
## 🐛 追加問題: 文字列連結
MIRで`"result is: " + 2`が`String + Integer → Integer`と間違った型推論
お手数ですが、調査をお願いします!

View File

@ -1,99 +0,0 @@
# ChatGPT5さんへLLVM文字列連結バグ
## 問題
文字列と整数の連結でLLVMエラーが発生します。
## エラーメッセージ
```
❌ LLVM execution error: binop lhs %4 not integer
```
## テストコード
```nyash
local c = new CounterBox()
c.inc()
c.inc()
local result = c.get()
print("result is: " + result) // ← ここでエラー
print(result)
```
## MIR出力問題箇所
```mir
4: %3: Integer = call %0.get() // プラグイン戻り値(整数)
5: %4: String = const "result is: " // 文字列定数
6: %5: Integer = %4 Add %3 // ❌ 型が間違いString + Integer なのに結果がInteger
7: extern_call env.console.log(%5)
```
## 期待される動作
- `String + Integer``String` (文字列連結)
- または専用の文字列連結命令が必要
## 関連ファイル
1. `src/backend/llvm/compiler/real.rs` - BinaryOp処理
2. `src/mir/builder/ops.rs` - MIRビルダーのBinaryOp処理
## 参考:通常の整数表示は正常
```mir
9: %6: Integer = const 42
13: extern_call env.console.log(%6) // ← これは正常に "42" と表示される
```
プラグイン戻り値自体は正しく取得できているが、文字列連結の型処理に問題があるようです。
## 追加情報:プラグイン戻り値も空白のまま
### シンプルなテストで確認
```nyash
local c = new CounterBox()
c.inc()
c.inc()
print(c.get()) // 空白が表示される(何も出力されない)
```
### MIR出力
```mir
4: %3: Integer = call %0.get()
5: extern_call env.console.log(%3) [effects: pure|io]
```
MIRには正しく`Integer`型が付いているのに、実行時は空白表示。
## 根本原因判明!🎯
### 問題1: プラグイン戻り値表示バグ
**L1016**: プラグイン戻り値整数は正しくvmapに格納される
```rust
crate::mir::MirType::Integer => {
vmap.insert(*d, rv); // ← 生の i64 値が入る
}
```
**L1214-1270**: console.logは生の i64 値を受け取る
```rust
let av = *vmap.get(&args[0]).ok_or("extern arg missing")?;
// av = 生の i64 値(例: 2
```
**L2391-2401**: nyrt::console.log_handleの問題箇所
```rust
pub extern "C" fn nyash_console_log_handle(handle: i64) -> i64 {
if let Some(obj) = handles::get(handle as u64) { // ← handles::get(2) → None
let s = obj.to_string_box().value;
println!("{}", s);
} else {
println!("{}", handle); // ← ここでhandle=2が表示されるはず
}
}
```
**疑問**: なぜ`println!("{}", handle)`が空白になるのか?
### 問題2: 文字列連結バグ
MIRで`String + Integer → Integer`という間違った型推論が発生
## 調査が必要
1. handleの実際の値をログ出力で確認
2. println!が実際に呼ばれているか確認

View File

@ -34,3 +34,4 @@ References
- LOWERING_LLVM.md — lowering rules and runtime calls
- RESOLVER_API.md — Resolver design and usage
- LLVM_HARNESS.md — llvmlite harness interface and usage

13
docs/design/README.md Normal file
View File

@ -0,0 +1,13 @@
# Nyash Design Notes
Public, stable design documents and architecture explanations.
Use for rationale, tradeoffs, and diagrams that are safe to cite.
Contents to consolidate here:
- Architecture overviews derived from ARCHITECTURE.md
- Backend design (LLVM/Cranelift) summaries
- MIR/IR evolution notes that are not drafts
Draft, exploratory, or longform papers should remain under `docs/private/` until finalized.

View File

@ -1,29 +1,29 @@
# AOT-Plan v1 Schema (Phase 15.1)
Status: draft-frozen for Phase 15.1 (extensions via `extensions` object only)
Status: draft-frozen for Phase 15.1 (extensions via `extensions` only)
- version: string, must be "1"
- name: optional plan/module name
- functions: array of PlanFunction
- externs: optional array of extern identifiers (reserved; not required in 15.1)
- exports: optional array of export names (reserved)
- units: optional array of link units (reserved)
- externs: optional array (reserved; not required in 15.1)
- exports: optional array (reserved)
- units: optional array (reserved)
- extensions: optional object for forward-compatible keys
PlanFunction:
PlanFunction
- name: string
- params: array of { name: string, type?: string } (informational in 15.1)
- return_type: optional string; one of: integer, float, bool, string, void (or omitted → Unknown)
- body: optional object with tagged `kind`
- kind = "const_return": { value: any-json (int/bool/float/string supported) }
- kind = "empty": returns default 0 with Unknown type (Phase 15.1 importer behavior)
- body: optional tagged object
- kind = "const_return": { value: any-json (int/bool/float/string) }
- kind = "empty": returns default 0 with Unknown type (15.1 importer behavior)
Notes:
Notes
- 15.1 importer does not emit object code; it constructs MIR13 skeletons only.
- If `return_type` is omitted, importer uses Unknown to keep VM dynamic display.
- `extensions` is a free-form map; the importer ignores unknown keys.
Example:
Example
```
{
"version": "1",

View File

@ -0,0 +1,50 @@
MIR13 Mode (PHI-off by default)
Overview
- Goal: Stabilize execution by turning off PHI emission in the Bridge/Builder and letting the LLVM (llvmlite) layer synthesize PHIs as needed.
- Default: MIR13 is ON by default (PHI-off). Use env flags to flip.
Why
- Fewer SSA obligations in the front-end (Bridge/Builder) reduces CFG corner cases (shortcircuit, nested if/loop merges).
- Centralizes SSA invariants in a single place (llvmlite resolver/finalizer), improving correctness and maintenance.
Flags and Behavior
- NYASH_MIR_NO_PHI (default: 1)
- 1: Bridge/Builder emit edge copies instead of PHIs at merges (MIR13).
- 0: Bridge/Builder may emit PHIs (MIR14 experimental).
- NYASH_VERIFY_ALLOW_NO_PHI (default: 1)
- Relaxes verifier checks that assume PHIs at merges.
- NYASH_LLVM_USE_HARNESS=1 (AOT via llvmlite harness)
- Resolver/finalizer synthesize PHIs at block heads when needed.
LLVM (llvmlite) Responsibilities
- setup_phi_placeholders(): predeclare JSONprovided PHIs and collect incoming metadata.
- block_end_values: snapshot per block end to materialize predecessor values (dominancesafe).
- finalize_phis(): wire incoming edges for declared PHIs at block heads.
- Resolver.resolve_i64():
- singlepred: take predecessor end value;
- multipred + declared PHI: reuse placeholder at block head;
- multipred + no PHI: synthesize a localization PHI at the current block head (MIR13 compatibility);
- avoids reusing nondominating vmap values across blocks.
Bridge/Builder (JSON v0) Behavior
- If/Loop/Try are lowered without PHIs when MIR13 is ON; merges are performed with edge copies (merge_var_maps) and the final value is reconstituted by the LLVM layer if needed.
- Helper split for readability (no behavior change):
- lowering/{if_else.rs, loop_.rs, try_catch.rs, merge.rs}
Testing
- Curated LLVM (default = PHIoff):
- tools/smokes/curated_llvm.sh (use --phi-on to exercise MIR14)
- PHI invariants/parity (AOT vs PyVM):
- tools/pyvm_vs_llvmlite.sh (default compares exit code; use CMP_STRICT=1 for stdout+exit)
- Bridge/PyVM:
- tools/selfhost_stage2_bridge_smoke.sh
How to Force PHIon (MIR14 experimental)
- Set: NYASH_MIR_NO_PHI=0 and run tools/smokes/curated_llvm.sh --phi-on
- Known: loop_if_phi may trip dominance issues in PHIon; MIR13 is the recommended default.
Known Limitations (current)
- No full tracing GC; object lifetime is managed via handle registries and Arc lifetimes.
- PHIon path is still being refined for some controlflow patterns.

View File

@ -33,7 +33,7 @@ Avoid: deep AOT emission/linking, cross-platform toolchain work, or scope creep
## Deliverables
- `tools/aot_plan/` Nyash scripts and helpers
- `docs/specs/aot_plan_v1.md` (lightweight schema)
- `docs/design/aot-plan-v1.md` (lightweight schema)
- Compiler entry to import AOT-Plan → MIR13 (feature-gated)
- 3 smokes + 1 golden JSON sample
@ -86,4 +86,3 @@ Key takeaways aligned into this document:
- Importer can read that JSON and construct MIR13 module(s) without panics
- VM runs those modules and matches expected string/number results for trivial bodies
- Events present when enabled; counters reflect plan/import activity; no AOT emit performed

19
docs/how-to/README.md Normal file
View File

@ -0,0 +1,19 @@
# Nyash HowTo Guides
Taskoriented, copypaste friendly instructions for common goals.
Use when you already know what you want to do and just need the steps.
Suggested structure (add as needed):
- Build & Run
- AOT build with LLVM
- Run with PyVM / VM / JIT
- Tooling
- Enable verbose logs
- Run curated smokes / parity checks
- Language
- Using and namespaces quick setup
- Array/Map literals gate toggles
Contributions: keep each guide short (12 screens), start with prerequisites, end with verify step.

View File

@ -0,0 +1,39 @@
# SelfHosting — HowTo前提→手順→検証
目的
- Ny → MIR → VM/JIT の自己ホスト経路を最短手順で動かす。
前提
- Ruststable: `cargo --version`
- Bash + ripgrepWSL/Unix 推奨)
手順
1) ビルドJIT有効
- 実行: `cargo build --release --features cranelift-jit`
2) 最小 E2EVM、plugins 無効)
- 実行: `NYASH_DISABLE_PLUGINS=1 ./target/release/nyash --backend vm apps/selfhost-minimal/main.nyash`
3) コアスモーク
- 実行: `bash tools/jit_smoke.sh`
4) selfhostminimal スモーク
- 実行: `bash tools/selfhost_vm_smoke.sh`
5) 追加(任意)
- ブートストラップ: `bash tools/bootstrap_selfhost_smoke.sh`
- ラウンドトリップ: `bash tools/ny_roundtrip_smoke.sh`
検証
- 期待出力: `Result: 0`selfhostminimal
- スモーク:全成功(非 0 は失敗)
便利フラグ
- `NYASH_DISABLE_PLUGINS=1` 外部プラグイン無効化
- `NYASH_CLI_VERBOSE=1` 実行ログ詳細
- `NYASH_JIT_THRESHOLD=1` JIT 降臨テスト
トラブルシュート
- ハング: `timeout 15s ...` を付与、`NYASH_CLI_VERBOSE=1` で詳細
- プラグインエラー: まず `NYASH_DISABLE_PLUGINS=1`
- ルート相対パスで実行/`cargo clean -p nyash` で個別クリーン
関連
- CI: `.github/workflows/smoke.yml`
- マージ運用: `docs/CONTRIBUTING-MERGE.md`

35
docs/how-to/smokes.md Normal file
View File

@ -0,0 +1,35 @@
# Smokes — HowTo前提→手順→検証
目的
- 代表スモークを素早く回して、回帰を検知する。
前提
- リリースビルド済み: `cargo build --release --features llvm`
- LLVM 18 が導入済みAOT 経路のとき)
手順(推奨ランナー)
1) LLVM curated
- 実行: `tools/smokes/curated_llvm.sh [--phi-off]`
- `--phi-off`: `NYASH_MIR_NO_PHI=1` を有効化し、検証を緩和
2) PHI 不変条件パリティ
- 実行: `tools/smokes/curated_phi_invariants.sh`
- PyVM と llvmlite の stdout/exit code を比較
手動スモーク(例)
- Core (LLVM): `examples/llvm11_core_smoke.nyash`
- Async (LLVM only):
- `apps/tests/async-await-min/main.nyash`
- `apps/tests/async-spawn-instance/main.nyash`
- `apps/tests/async-await-timeout-fixed/main.nyash``NYASH_AWAIT_MAX_MS=100`
アーカイブ(非推奨)
- `tools/smokes/archive/` に旧ランナーJIT/Cranelift 時代)が存在
- `smoke_phase_10_10.sh`, `smoke_vm_jit.sh`, `smoke_async_spawn.sh`, `jit_smoke.sh`, `aot_smoke_cranelift.sh`
- これらは基本使わず、curated 系を使用
便利フラグ
- `NYASH_LLVM_USE_HARNESS=1`: llvmlite ハーネス経由
- `NYASH_MIR_NO_PHI=1`, `NYASH_VERIFY_ALLOW_NO_PHI=1`: PHI 無しモード
検証
- 0 で成功、非 0 で失敗CI 連携可)

View File

@ -4,7 +4,7 @@
**最新の完全な言語リファレンスは以下を参照してください:**
- **[🚀 Nyash Language Reference 2025](../language/LANGUAGE_REFERENCE_2025.md)** - 完全な言語仕様(最新版)
- **[🚀 Nyash Language Reference 2025](../../../../reference/language/LANGUAGE_REFERENCE_2025.md)** - 完全な言語仕様(最新版)
- **[📝 構文早見表](../../quick-reference/syntax-cheatsheet.md)** - よく使う構文のクイックリファレンス
## 📁 このディレクトリの内容
@ -20,4 +20,4 @@
---
**注意**: 言語仕様に関する最新情報は必ず [LANGUAGE_REFERENCE_2025.md](../language/LANGUAGE_REFERENCE_2025.md) を参照してください。
**注意**: 言語仕様に関する最新情報は必ず [LANGUAGE_REFERENCE_2025.md](../../../../reference/language/LANGUAGE_REFERENCE_2025.md) を参照してください。

View File

@ -1,659 +0,0 @@
# 🚀 Nyash Language Reference 2025
**最終更新: 2025年9月4日 - Phase 12.7実装済み機能の正確な反映**
## 📖 概要
Nyashは「Everything is Box」哲学に基づく革新的プログラミング言語です。
Rust製インタープリターによる高性能実行と、直感的な構文により、学習しやすく実用的な言語として完成しました。
---
## 🔤 **1. 予約語・キーワード完全リスト**
### **Phase 12.7で確定した15個の予約語**
| 予約語 | 用途 | 例 |
|-------|------|---|
| `box` | クラス定義 | `box MyClass { }` |
| `new` | オブジェクト生成 | `new ConsoleBox()` |
| `me` | 自己参照thisの代わり | `me.field = value` |
| `local` | ローカル変数宣言 | `local x, y = 10` |
| `return` | 関数リターン | `return value` |
| `from` | デリゲーション・親メソッド呼び出し | `box Child from Parent` / `from Parent.method()` |
| `birth` | コンストラクタ(統一名) | `birth(param) { }` |
| `static` | 静的Box・関数定義 | `static box Main { }` |
| `if` | 条件分岐 | `if condition { }` |
| `else` | else節 | `else { }` |
| `loop` | ループ(唯一の形式) | `loop(condition) { }` |
| `continue` | ループ継続 | `continue` |
| `peek` | パターンマッチング風分岐 | `peek value { "A" => 1, else => 0 }` |
| `try` | 例外捕獲開始 | `try { }` |
| `interface` | インターフェース定義 | `interface Comparable { }` |
### **その他の重要キーワード(予約語ではない)**
| キーワード | 用途 | 例 |
|-------|------|---|
| `override` | 明示的オーバーライド | `override speak() { }` |
| `break` | ループ脱出 | `break` |
| `catch` | 例外処理 | `catch (e) { }` |
| `finally` | 最終処理 | `finally { }` |
| `throw` | 例外発生 | `throw error` |
| `nowait` | 非同期実行 | `nowait future = task()` |
| `await` | 待機・結果取得 | `result = await future` |
| `include` | ファイル取り込み | `include "math.nyash"` |
| `print` | 出力(デバッグ用) | `print("Hello")` |
| `function`/`fn` | 関数定義 | `fn add(a,b) { }` |
| `init` | 初期化ブロック | `init { field1, field2 }` |
| `pack` | 旧コンストラクタ(互換性) | `pack(param) { }` |
| `outbox` | 所有権移転変数 | `outbox result = compute()` |
| `global` | グローバル変数 | `global CONFIG = "dev"` |
| `weak` | 弱参照修飾子 | `weak reference` |
| `using` | 名前空間インポート | `using namespace` |
### **演算子・論理**
| 演算子/キーワード | 用途 | 例 |
|-------|------|---|
| `not` | 論理否定 | `not condition` |
| `and` | 論理積 | `a and b` |
| `or` | 論理和 | `a or b` |
| `true`/`false` | 真偽値 | `flag = true` |
| `null` | null値 | `value = null` |
---
## 📝 **2. 文法・構文仕様**
### **2.1 Box定義文法**
#### **基本Box**
```nyash
box ClassName {
# フィールド宣言Phase 12.7形式)
field1: TypeBox # フィールド型アテーションP0では無視
field2: TypeBox
field3 # 型なしも可
# コンストラクタ
birth(param1, param2) { # birth構文に統一
me.field1 = param1
me.field2 = param2
me.field3 = defaultValue()
}
# メソッド
methodName(arg1, arg2) {
return me.field1 + arg1
}
# デストラクタfini
fini() {
print("Cleanup: " + me.field1)
}
}
```
#### **デリゲーションBox**
```nyash
box Child from Parent interface Comparable {
childField: TypeBox # 追加フィールド
birth(parentParam, childParam) { # birth構文に統一
from Parent.birth(parentParam) # 親コンストラクタ明示呼び出し
me.childField = childParam
}
# メソッドオーバーライド
override process(data) { # overrideキーワード必須
local result = from Parent.process(data) # 親メソッド呼び出し
return result + " (Child processed)"
}
# インターフェース実装
compareTo(other) {
return me.value - other.value
}
}
```
#### **Static Box推奨エントリーポイント**
```nyash
static box Main {
console: ConsoleBox
result: IntegerBox
main() {
me.console = new ConsoleBox()
me.console.log("🎉 Everything is Box!")
return "Success"
}
}
```
### **2.2 変数宣言**
#### **基本パターン**
```nyash
# 単一宣言
local x
local name = "初期値"
# 複数宣言
local a, b, c
local x = 10, y = 20, z # 混合初期化
# 所有権移転static関数内
static function Factory.create() {
outbox product # 呼び出し側に所有権移転
product = new Item()
return product
}
```
#### **変数宣言厳密化システム2025-08-09実装**
```nyash
# ✅ 正しい - 明示宣言必須
local temp
temp = 42
# ❌ エラー - 未宣言変数への代入
x = 42 # RuntimeError: 未宣言変数 + 修正提案表示
```
### **2.3 制御構文**
#### **条件分岐**
```nyash
if condition {
# 処理
} else if condition2 {
# 処理2
} else {
# else処理
}
```
#### **ループ(統一構文)**
```nyash
# ✅ 唯一の正しい形式
loop(condition) {
# ループ本体
if exitCondition {
break
}
if skipCondition {
continue # Phase 12.7で追加
}
}
# ❌ 削除済み - 使用不可
while condition { } # パーサーエラー
loop() { } # パーサーエラー
```
#### **Peek式Phase 12.7で追加)**
```nyash
# パターンマッチング風の分岐
local result = peek value {
"A" => 100,
"B" => 200,
"C" => 300,
else => 0 # else必須
}
# 文の形式も可
peek status {
"error" => {
print("Error occurred")
return null
},
"success" => {
print("All good")
},
else => {
print("Unknown status")
}
}
```
### **2.4 演算子・式**
#### **🚀 新実装: 関数オーバーロードシステム**
```nyash
# Rust風トレイトベース演算子2025-08-10実装完了
sum = 10 + 20 # IntegerBox + IntegerBox = IntegerBox
concat = "Hi" + " !" # StringBox + StringBox = StringBox
repeat = "Ha" * 3 # StringBox * IntegerBox = "HaHaHa"
mixed = 42 + " answer" # 混合型 → 自動文字列結合フォールバック
```
#### **演算子優先順位**
```nyash
result = a + b * c / d - e # 算術演算子は標準的優先順位
logic = not a and b or c # not > and > or
compare = (x > y) and (z <= w) # 比較は括弧推奨
```
#### **論理演算子**
```nyash
# キーワード版(推奨)
canAccess = level >= 5 and hasKey
isValid = not (isEmpty or hasError)
# シンボル版(互換)
result = condition && other || fallback # 利用可能だが非推奨
```
#### **特殊演算子Phase 12.7実装済み)**
```nyash
# ? 演算子 - Result伝播
local data = readFile(path)? # エラーなら早期return
# ラムダ式
local add = fn(x, y) { return x + y }
local double = fn(x) { x * 2 } # 単一式なら省略可
# await式
local result = await asyncTask()
```
---
## 🏗️ **3. Box構文詳細ガイド**
### **3.1 Everything is Box 原則**
```nyash
# すべての値がBox
number = 42 # IntegerBox
text = "hello" # StringBox
flag = true # BoolBox
array = new ArrayBox() # ArrayBox
console = new ConsoleBox() # ConsoleBox
# 統一的なメソッド呼び出し
print(number.to_string_box().value) # "42"
print(array.length()) # 配列長
console.log("Everything is Box!") # コンソール出力
```
### **3.2 コンストラクタパターン**
#### **パラメータ付きコンストラクタ**
```nyash
box Person {
public name: StringBox
public email: StringBox
private age: IntegerBox
birth(personName, personAge) { # birth構文に統一
me.name = personName
me.age = personAge
me.email = me.name + "@example.com" # 計算フィールド
}
# ファクトリーメソッド
static createGuest() {
outbox guest
guest = new Person("Guest", 0)
return guest
}
}
# 使用例
person = new Person("Alice", 25)
guest = Person.createGuest()
```
### **3.3 継承とインターフェース**
#### **デリゲーションチェーン**
```nyash
# 基底Box
box Animal {
public name: StringBox
public species: StringBox
birth(animalName, animalSpecies) {
me.name = animalName
me.species = animalSpecies
}
speak() {
return me.name + " makes a sound"
}
}
# デリゲーション
box Dog from Animal {
breed: StringBox # 追加フィールド
birth(dogName, dogBreed) {
from Animal.birth(dogName, "Canine") # 親コンストラクタ呼び出し
me.breed = dogBreed
}
override speak() { # 明示的オーバーライド
return me.name + " barks: Woof!"
}
}
# インターフェース実装
box Cat from Animal interface Playful {
# Playfulインターフェースの実装必須
}
```
### **3.4 Static Boxパターン**
#### **名前空間・ユーティリティ**
```nyash
static box MathUtils {
PI: FloatBox
E: FloatBox
# 注意: static初期化ブロックは未実装
# 初期化はメソッド内で行う
add(a, b) {
return a + b
}
circleArea(radius) {
# 初回アクセスで初期化パターン
if me.PI == null {
me.PI = 3.14159265
}
return me.PI * radius * radius
}
}
# 使用法
area = MathUtils.circleArea(5)
sum = MathUtils.add(10, 20)
```
#### **アプリケーションエントリーポイント**
```nyash
# 🎯 推奨: Static Box Main パターン
static box Main {
console: ConsoleBox
result: IntegerBox
main() {
me.console = new ConsoleBox()
me.console.log("🚀 Starting application...")
# アプリケーションロジック
me.result = processData()
return "Application completed successfully"
}
}
```
---
## 🚀 **4. 最新機能・革新技術**
### **4.1 Arc<Mutex> Revolution2025-08-10**
```nyash
# 全16種類のBox型が統一Arc<Mutex>パターンで実装
# 完全なスレッドセーフティと高性能を両立
array = new ArrayBox()
array.push(10) # スレッドセーフな追加
array.push(20)
item = array.get(0) # スレッドセーフな取得
json = new JSONBox()
json.set("name", "Alice") # 並行安全な操作
data = json.stringify() # JSON文字列化
```
### **4.2 Rust風トレイトベース演算子2025-08-10**
```nyash
# AI大相談会で決定された最適設計
# 静的・動的ハイブリッドディスパッチによる高性能実現
# 整数演算
result = 100 - 25 # IntegerBox間演算 → IntegerBox
product = 6 * 7 # 高速静的ディスパッチ
# 文字列操作
greeting = "Hello" + " World" # 文字列結合
repeated = "Echo" * 3 # "EchoEchoEcho"
# 混合型フォールバック
message = "Answer: " + 42 # "Answer: 42"
# Boolean演算
boolSum = true + false # 1 (IntegerBox)
```
### **4.3 変数宣言厳密化2025-08-09**
```nyash
# メモリ安全性・非同期安全性保証システム
static box Calculator {
private memory: ArrayBox # 必須フィールド宣言
calculate() {
local temp # 必須ローカル変数宣言
temp = me.memory * 2
return temp
}
}
```
---
## 🚀 **4.4 Phase 12.7実装済み機能**
### **Peek式 - パターンマッチング風分岐**
```nyash
# 式として使用(値を返す)
local grade = peek score {
100 => "Perfect",
90 => "Excellent",
80 => "Good",
else => "Needs improvement"
}
# 文として使用(アクション実行)
peek command {
"save" => {
saveFile()
print("Saved!")
},
"quit" => {
cleanup()
return
},
else => print("Unknown command")
}
```
### **Continue文**
```nyash
loop(i < 100) {
if i % 2 == 0 {
continue # 偶数をスキップ
}
process(i)
}
```
### **フィールド型アノテーション**
```nyash
box Person {
name: StringBox # 型情報を明記P0では無視
age: IntegerBox
email # 型なしも可
}
```
### **?演算子Result伝播**
```nyash
# ResultBoxのエラーを自動的に早期return
local data = readFile("config.json")?
local parsed = parseJSON(data)?
return parsed.get("version")
```
### **Lambda式**
```nyash
# 基本形
local add = fn(x, y) { return x + y }
# 単一式の場合returnは省略可
local double = fn(x) { x * 2 }
# 高階関数での使用
array.map(fn(x) { x * x })
```
---
## ⚡ **5. 実装済みBox型ライブラリ**
### **5.1 基本型**
- `StringBox` - 文字列split, find, replace, trim等
- `IntegerBox` - 64bit整数
- `FloatBox` - 64bit浮動小数点数
- `BoolBox` - 真偽値
- `NullBox` - null値
- `VoidBox` - void値
### **5.2 コレクション**
- `ArrayBox` - 動的配列push, pop, get, set, join等
- `MapBox` - 連想配列・辞書
### **5.3 システム・I/O**
- `ConsoleBox` - コンソール入出力
- `DebugBox` - デバッグ支援・メモリ追跡
- `FileBox` - ファイルシステム操作(プラグイン)
### **5.4 数学・時間**
- `MathBox` - 数学関数sin, cos, log, sqrt等
- `TimeBox` - 時刻操作・タイマー
- `RandomBox` - 乱数生成・選択・シャッフル
### **5.5 データ処理**
- `JSONBox` - JSON解析・生成parse, stringify, get, set
- `RegexBox` - 正規表現test, find, replace, split
- `BufferBox` - バイナリデータ処理
- `StreamBox` - ストリーム処理
### **5.6 ネットワーク・Web**
- `HttpClientBox` - HTTP通信プラグイン
- `WebDisplayBox` - HTML表示WASM
- `WebConsoleBox` - ブラウザコンソールWASM
- `WebCanvasBox` - Canvas描画WASM
### **5.7 GUI・マルチメディア**
- `EguiBox` - デスクトップGUIWindows/Linux、プラグイン
- `SoundBox` - 音声再生
### **5.8 特殊用途**
- `FutureBox` - 非同期処理結果
- `ResultBox` - エラー処理Ok/Err
- `TokenBox` - キャンセルトークン
- `FunctionBox` - 第一級関数
- `P2PBox` - P2P通信プラグイン
---
## 🎯 **6. パフォーマンス・デザイン原則**
### **6.1 メモリ安全性**
- Rust所有権システムによる完全なメモリ安全性
- Arc<Mutex>によるスレッドセーフな共有状態管理
- 自動参照カウント + 明示的デストラクタfini
### **6.2 実行効率**
- 統一されたBox型システムによる最適化
- 静的・動的ハイブリッドディスパッチで高速演算
- パーサー無限ループ対策(--debug-fuel
### **6.3 開発効率**
- 変数宣言厳密化による早期エラー検出
- 包括的デバッグ機能DebugBox
- 直感的な"Everything is Box"概念
---
## 📚 **7. 学習パス・ベストプラクティス**
### **7.1 初心者向け学習順序**
1. **基本概念**: Everything is Box哲学理解
2. **基本構文**: 変数宣言・制御構文・演算子
3. **Box定義**: 基本的なクラス作成
4. **Static Box Main**: アプリケーションエントリーポイント
5. **継承・インターフェース**: オブジェクト指向機能
### **7.2 推奨コーディングスタイル**
```nyash
# ✅ 推奨スタイル
static box Main {
public console: ConsoleBox # 公開フィールド明示
public result: IntegerBox
main() {
me.console = new ConsoleBox()
local data # 変数事前宣言
data = processInput()
me.result = data # 明確な代入
return "Success"
}
}
```
### **7.3 よくある間違いと対策**
```nyash
# ❌ よくある間違い
public { field1 field2 } # 旧構文 → 使用不可
x = 42 # 変数未宣言 → ランタイムエラー
while condition { } # 非対応構文 → パーサーエラー
this.field # thisは使用不可 → me.fieldを使用
# ✅ 正しい書き方Phase 12.7後)
field1: TypeBox # フィールド宣言(型は省略可)
field2 # 型なしフィールド
local x = 42 # 事前宣言必須
loop(condition) { } # 統一ループ構文
me.field # self参照はmeのみ
```
---
## 📌 **8. 糖衣構文Phase 12.7-B**
### 実装済み(ゲート: `NYASH_SYNTAX_SUGAR_LEVEL=basic|full`
```nyash
# パイプライン
result = data |> normalize() |> transform() |> process
# セーフアクセス + デフォルト
name = user?.profile?.name ?? "guest"
# 複合代入
x += 1; y *= 2
# 範囲(内部的には Range(a,b)
loop(i in 1 .. 5) { /* ... */ }
```
### 拡張(段階適用予定・設計済み)
```nyash
let {x, y} = point
let [first, second, ...rest] = array
```
---
**🎉 Nyash 2025は、AI協働設計による最先端言語システムとして、シンプルさと強力さを完全に両立しました。**
*最終更新: 2025年9月4日 - Phase 12.7実装済み機能の正確な反映*

View File

@ -4,7 +4,7 @@
**最新の完全な言語リファレンスは以下を参照してください:**
- **[🚀 Nyash Language Reference 2025](../language/LANGUAGE_REFERENCE_2025.md)** - 完全な言語仕様(最新版)
- **[🚀 Nyash Language Reference 2025](../../../reference/language/LANGUAGE_REFERENCE_2025.md)** - 完全な言語仕様(最新版)
- **[📝 構文早見表](../../quick-reference/syntax-cheatsheet.md)** - よく使う構文のクイックリファレンス
## 📁 このディレクトリの内容
@ -20,4 +20,4 @@
---
**注意**: 言語仕様に関する最新情報は必ず [LANGUAGE_REFERENCE_2025.md](../language/LANGUAGE_REFERENCE_2025.md) を参照してください。
**注意**: 言語仕様に関する最新情報は必ず [LANGUAGE_REFERENCE_2025.md](../../../reference/language/LANGUAGE_REFERENCE_2025.md) を参照してください。

View File

@ -1,659 +0,0 @@
# 🚀 Nyash Language Reference 2025
**最終更新: 2025年9月4日 - Phase 12.7実装済み機能の正確な反映**
## 📖 概要
Nyashは「Everything is Box」哲学に基づく革新的プログラミング言語です。
Rust製インタープリターによる高性能実行と、直感的な構文により、学習しやすく実用的な言語として完成しました。
---
## 🔤 **1. 予約語・キーワード完全リスト**
### **Phase 12.7で確定した15個の予約語**
| 予約語 | 用途 | 例 |
|-------|------|---|
| `box` | クラス定義 | `box MyClass { }` |
| `new` | オブジェクト生成 | `new ConsoleBox()` |
| `me` | 自己参照thisの代わり | `me.field = value` |
| `local` | ローカル変数宣言 | `local x, y = 10` |
| `return` | 関数リターン | `return value` |
| `from` | デリゲーション・親メソッド呼び出し | `box Child from Parent` / `from Parent.method()` |
| `birth` | コンストラクタ(統一名) | `birth(param) { }` |
| `static` | 静的Box・関数定義 | `static box Main { }` |
| `if` | 条件分岐 | `if condition { }` |
| `else` | else節 | `else { }` |
| `loop` | ループ(唯一の形式) | `loop(condition) { }` |
| `continue` | ループ継続 | `continue` |
| `peek` | パターンマッチング風分岐 | `peek value { "A" => 1, else => 0 }` |
| `try` | 例外捕獲開始 | `try { }` |
| `interface` | インターフェース定義 | `interface Comparable { }` |
### **その他の重要キーワード(予約語ではない)**
| キーワード | 用途 | 例 |
|-------|------|---|
| `override` | 明示的オーバーライド | `override speak() { }` |
| `break` | ループ脱出 | `break` |
| `catch` | 例外処理 | `catch (e) { }` |
| `finally` | 最終処理 | `finally { }` |
| `throw` | 例外発生 | `throw error` |
| `nowait` | 非同期実行 | `nowait future = task()` |
| `await` | 待機・結果取得 | `result = await future` |
| `include` | ファイル取り込み | `include "math.nyash"` |
| `print` | 出力(デバッグ用) | `print("Hello")` |
| `function`/`fn` | 関数定義 | `fn add(a,b) { }` |
| `init` | 初期化ブロック | `init { field1, field2 }` |
| `pack` | 旧コンストラクタ(互換性) | `pack(param) { }` |
| `outbox` | 所有権移転変数 | `outbox result = compute()` |
| `global` | グローバル変数 | `global CONFIG = "dev"` |
| `weak` | 弱参照修飾子 | `weak reference` |
| `using` | 名前空間インポート | `using namespace` |
### **演算子・論理**
| 演算子/キーワード | 用途 | 例 |
|-------|------|---|
| `not` | 論理否定 | `not condition` |
| `and` | 論理積 | `a and b` |
| `or` | 論理和 | `a or b` |
| `true`/`false` | 真偽値 | `flag = true` |
| `null` | null値 | `value = null` |
---
## 📝 **2. 文法・構文仕様**
### **2.1 Box定義文法**
#### **基本Box**
```nyash
box ClassName {
# フィールド宣言Phase 12.7形式)
field1: TypeBox # フィールド型アテーションP0では無視
field2: TypeBox
field3 # 型なしも可
# コンストラクタ
birth(param1, param2) { # birth構文に統一
me.field1 = param1
me.field2 = param2
me.field3 = defaultValue()
}
# メソッド
methodName(arg1, arg2) {
return me.field1 + arg1
}
# デストラクタfini
fini() {
print("Cleanup: " + me.field1)
}
}
```
#### **デリゲーションBox**
```nyash
box Child from Parent interface Comparable {
childField: TypeBox # 追加フィールド
birth(parentParam, childParam) { # birth構文に統一
from Parent.birth(parentParam) # 親コンストラクタ明示呼び出し
me.childField = childParam
}
# メソッドオーバーライド
override process(data) { # overrideキーワード必須
local result = from Parent.process(data) # 親メソッド呼び出し
return result + " (Child processed)"
}
# インターフェース実装
compareTo(other) {
return me.value - other.value
}
}
```
#### **Static Box推奨エントリーポイント**
```nyash
static box Main {
console: ConsoleBox
result: IntegerBox
main() {
me.console = new ConsoleBox()
me.console.log("🎉 Everything is Box!")
return "Success"
}
}
```
### **2.2 変数宣言**
#### **基本パターン**
```nyash
# 単一宣言
local x
local name = "初期値"
# 複数宣言
local a, b, c
local x = 10, y = 20, z # 混合初期化
# 所有権移転static関数内
static function Factory.create() {
outbox product # 呼び出し側に所有権移転
product = new Item()
return product
}
```
#### **変数宣言厳密化システム2025-08-09実装**
```nyash
# ✅ 正しい - 明示宣言必須
local temp
temp = 42
# ❌ エラー - 未宣言変数への代入
x = 42 # RuntimeError: 未宣言変数 + 修正提案表示
```
### **2.3 制御構文**
#### **条件分岐**
```nyash
if condition {
# 処理
} else if condition2 {
# 処理2
} else {
# else処理
}
```
#### **ループ(統一構文)**
```nyash
# ✅ 唯一の正しい形式
loop(condition) {
# ループ本体
if exitCondition {
break
}
if skipCondition {
continue # Phase 12.7で追加
}
}
# ❌ 削除済み - 使用不可
while condition { } # パーサーエラー
loop() { } # パーサーエラー
```
#### **Peek式Phase 12.7で追加)**
```nyash
# パターンマッチング風の分岐
local result = peek value {
"A" => 100,
"B" => 200,
"C" => 300,
else => 0 # else必須
}
# 文の形式も可
peek status {
"error" => {
print("Error occurred")
return null
},
"success" => {
print("All good")
},
else => {
print("Unknown status")
}
}
```
### **2.4 演算子・式**
#### **🚀 新実装: 関数オーバーロードシステム**
```nyash
# Rust風トレイトベース演算子2025-08-10実装完了
sum = 10 + 20 # IntegerBox + IntegerBox = IntegerBox
concat = "Hi" + " !" # StringBox + StringBox = StringBox
repeat = "Ha" * 3 # StringBox * IntegerBox = "HaHaHa"
mixed = 42 + " answer" # 混合型 → 自動文字列結合フォールバック
```
#### **演算子優先順位**
```nyash
result = a + b * c / d - e # 算術演算子は標準的優先順位
logic = not a and b or c # not > and > or
compare = (x > y) and (z <= w) # 比較は括弧推奨
```
#### **論理演算子**
```nyash
# キーワード版(推奨)
canAccess = level >= 5 and hasKey
isValid = not (isEmpty or hasError)
# シンボル版(互換)
result = condition && other || fallback # 利用可能だが非推奨
```
#### **特殊演算子Phase 12.7実装済み)**
```nyash
# ? 演算子 - Result伝播
local data = readFile(path)? # エラーなら早期return
# ラムダ式
local add = fn(x, y) { return x + y }
local double = fn(x) { x * 2 } # 単一式なら省略可
# await式
local result = await asyncTask()
```
---
## 🏗️ **3. Box構文詳細ガイド**
### **3.1 Everything is Box 原則**
```nyash
# すべての値がBox
number = 42 # IntegerBox
text = "hello" # StringBox
flag = true # BoolBox
array = new ArrayBox() # ArrayBox
console = new ConsoleBox() # ConsoleBox
# 統一的なメソッド呼び出し
print(number.to_string_box().value) # "42"
print(array.length()) # 配列長
console.log("Everything is Box!") # コンソール出力
```
### **3.2 コンストラクタパターン**
#### **パラメータ付きコンストラクタ**
```nyash
box Person {
public name: StringBox
public email: StringBox
private age: IntegerBox
birth(personName, personAge) { # birth構文に統一
me.name = personName
me.age = personAge
me.email = me.name + "@example.com" # 計算フィールド
}
# ファクトリーメソッド
static createGuest() {
outbox guest
guest = new Person("Guest", 0)
return guest
}
}
# 使用例
person = new Person("Alice", 25)
guest = Person.createGuest()
```
### **3.3 継承とインターフェース**
#### **デリゲーションチェーン**
```nyash
# 基底Box
box Animal {
public name: StringBox
public species: StringBox
birth(animalName, animalSpecies) {
me.name = animalName
me.species = animalSpecies
}
speak() {
return me.name + " makes a sound"
}
}
# デリゲーション
box Dog from Animal {
breed: StringBox # 追加フィールド
birth(dogName, dogBreed) {
from Animal.birth(dogName, "Canine") # 親コンストラクタ呼び出し
me.breed = dogBreed
}
override speak() { # 明示的オーバーライド
return me.name + " barks: Woof!"
}
}
# インターフェース実装
box Cat from Animal interface Playful {
# Playfulインターフェースの実装必須
}
```
### **3.4 Static Boxパターン**
#### **名前空間・ユーティリティ**
```nyash
static box MathUtils {
PI: FloatBox
E: FloatBox
# 注意: static初期化ブロックは未実装
# 初期化はメソッド内で行う
add(a, b) {
return a + b
}
circleArea(radius) {
# 初回アクセスで初期化パターン
if me.PI == null {
me.PI = 3.14159265
}
return me.PI * radius * radius
}
}
# 使用法
area = MathUtils.circleArea(5)
sum = MathUtils.add(10, 20)
```
#### **アプリケーションエントリーポイント**
```nyash
# 🎯 推奨: Static Box Main パターン
static box Main {
console: ConsoleBox
result: IntegerBox
main() {
me.console = new ConsoleBox()
me.console.log("🚀 Starting application...")
# アプリケーションロジック
me.result = processData()
return "Application completed successfully"
}
}
```
---
## 🚀 **4. 最新機能・革新技術**
### **4.1 Arc<Mutex> Revolution2025-08-10**
```nyash
# 全16種類のBox型が統一Arc<Mutex>パターンで実装
# 完全なスレッドセーフティと高性能を両立
array = new ArrayBox()
array.push(10) # スレッドセーフな追加
array.push(20)
item = array.get(0) # スレッドセーフな取得
json = new JSONBox()
json.set("name", "Alice") # 並行安全な操作
data = json.stringify() # JSON文字列化
```
### **4.2 Rust風トレイトベース演算子2025-08-10**
```nyash
# AI大相談会で決定された最適設計
# 静的・動的ハイブリッドディスパッチによる高性能実現
# 整数演算
result = 100 - 25 # IntegerBox間演算 → IntegerBox
product = 6 * 7 # 高速静的ディスパッチ
# 文字列操作
greeting = "Hello" + " World" # 文字列結合
repeated = "Echo" * 3 # "EchoEchoEcho"
# 混合型フォールバック
message = "Answer: " + 42 # "Answer: 42"
# Boolean演算
boolSum = true + false # 1 (IntegerBox)
```
### **4.3 変数宣言厳密化2025-08-09**
```nyash
# メモリ安全性・非同期安全性保証システム
static box Calculator {
private memory: ArrayBox # 必須フィールド宣言
calculate() {
local temp # 必須ローカル変数宣言
temp = me.memory * 2
return temp
}
}
```
---
## 🚀 **4.4 Phase 12.7実装済み機能**
### **Peek式 - パターンマッチング風分岐**
```nyash
# 式として使用(値を返す)
local grade = peek score {
100 => "Perfect",
90 => "Excellent",
80 => "Good",
else => "Needs improvement"
}
# 文として使用(アクション実行)
peek command {
"save" => {
saveFile()
print("Saved!")
},
"quit" => {
cleanup()
return
},
else => print("Unknown command")
}
```
### **Continue文**
```nyash
loop(i < 100) {
if i % 2 == 0 {
continue # 偶数をスキップ
}
process(i)
}
```
### **フィールド型アノテーション**
```nyash
box Person {
name: StringBox # 型情報を明記P0では無視
age: IntegerBox
email # 型なしも可
}
```
### **?演算子Result伝播**
```nyash
# ResultBoxのエラーを自動的に早期return
local data = readFile("config.json")?
local parsed = parseJSON(data)?
return parsed.get("version")
```
### **Lambda式**
```nyash
# 基本形
local add = fn(x, y) { return x + y }
# 単一式の場合returnは省略可
local double = fn(x) { x * 2 }
# 高階関数での使用
array.map(fn(x) { x * x })
```
---
## ⚡ **5. 実装済みBox型ライブラリ**
### **5.1 基本型**
- `StringBox` - 文字列split, find, replace, trim等
- `IntegerBox` - 64bit整数
- `FloatBox` - 64bit浮動小数点数
- `BoolBox` - 真偽値
- `NullBox` - null値
- `VoidBox` - void値
### **5.2 コレクション**
- `ArrayBox` - 動的配列push, pop, get, set, join等
- `MapBox` - 連想配列・辞書
### **5.3 システム・I/O**
- `ConsoleBox` - コンソール入出力
- `DebugBox` - デバッグ支援・メモリ追跡
- `FileBox` - ファイルシステム操作(プラグイン)
### **5.4 数学・時間**
- `MathBox` - 数学関数sin, cos, log, sqrt等
- `TimeBox` - 時刻操作・タイマー
- `RandomBox` - 乱数生成・選択・シャッフル
### **5.5 データ処理**
- `JSONBox` - JSON解析・生成parse, stringify, get, set
- `RegexBox` - 正規表現test, find, replace, split
- `BufferBox` - バイナリデータ処理
- `StreamBox` - ストリーム処理
### **5.6 ネットワーク・Web**
- `HttpClientBox` - HTTP通信プラグイン
- `WebDisplayBox` - HTML表示WASM
- `WebConsoleBox` - ブラウザコンソールWASM
- `WebCanvasBox` - Canvas描画WASM
### **5.7 GUI・マルチメディア**
- `EguiBox` - デスクトップGUIWindows/Linux、プラグイン
- `SoundBox` - 音声再生
### **5.8 特殊用途**
- `FutureBox` - 非同期処理結果
- `ResultBox` - エラー処理Ok/Err
- `TokenBox` - キャンセルトークン
- `FunctionBox` - 第一級関数
- `P2PBox` - P2P通信プラグイン
---
## 🎯 **6. パフォーマンス・デザイン原則**
### **6.1 メモリ安全性**
- Rust所有権システムによる完全なメモリ安全性
- Arc<Mutex>によるスレッドセーフな共有状態管理
- 自動参照カウント + 明示的デストラクタfini
### **6.2 実行効率**
- 統一されたBox型システムによる最適化
- 静的・動的ハイブリッドディスパッチで高速演算
- パーサー無限ループ対策(--debug-fuel
### **6.3 開発効率**
- 変数宣言厳密化による早期エラー検出
- 包括的デバッグ機能DebugBox
- 直感的な"Everything is Box"概念
---
## 📚 **7. 学習パス・ベストプラクティス**
### **7.1 初心者向け学習順序**
1. **基本概念**: Everything is Box哲学理解
2. **基本構文**: 変数宣言・制御構文・演算子
3. **Box定義**: 基本的なクラス作成
4. **Static Box Main**: アプリケーションエントリーポイント
5. **継承・インターフェース**: オブジェクト指向機能
### **7.2 推奨コーディングスタイル**
```nyash
# ✅ 推奨スタイル
static box Main {
public console: ConsoleBox # 公開フィールド明示
public result: IntegerBox
main() {
me.console = new ConsoleBox()
local data # 変数事前宣言
data = processInput()
me.result = data # 明確な代入
return "Success"
}
}
```
### **7.3 よくある間違いと対策**
```nyash
# ❌ よくある間違い
public { field1 field2 } # 旧構文 → 使用不可
x = 42 # 変数未宣言 → ランタイムエラー
while condition { } # 非対応構文 → パーサーエラー
this.field # thisは使用不可 → me.fieldを使用
# ✅ 正しい書き方Phase 12.7後)
field1: TypeBox # フィールド宣言(型は省略可)
field2 # 型なしフィールド
local x = 42 # 事前宣言必須
loop(condition) { } # 統一ループ構文
me.field # self参照はmeのみ
```
---
## 📌 **8. 糖衣構文Phase 12.7-B**
### 実装済み(ゲート: `NYASH_SYNTAX_SUGAR_LEVEL=basic|full`
```nyash
# パイプライン
result = data |> normalize() |> transform() |> process
# セーフアクセス + デフォルト
name = user?.profile?.name ?? "guest"
# 複合代入
x += 1; y *= 2
# 範囲(内部的には Range(a,b)
loop(i in 1 .. 5) { /* ... */ }
```
### 拡張(段階適用予定・設計済み)
```nyash
let {x, y} = point
let [first, second, ...rest] = array
```
---
**🎉 Nyash 2025は、AI協働設計による最先端言語システムとして、シンプルさと強力さを完全に両立しました。**
*最終更新: 2025年9月4日 - Phase 12.7実装済み機能の正確な反映*

View File

@ -4,9 +4,9 @@ This index points to the currently maintained architectural documents:
- Core Concepts: reference/architecture/nyash_core_concepts.md
- Execution Backends: reference/architecture/execution-backends.md
- Lowering Contexts: LOWERING_CONTEXTS.md
- LLVM Layer Overview: LLVM_LAYER_OVERVIEW.md
- Lowering Contexts: ../../design/LOWERING_CONTEXTS.md
- LLVM Layer Overview: ../../design/LLVM_LAYER_OVERVIEW.md
- VM Overview: VM_README.md
- Cranelift AOT design: backend-cranelift-aot-design.md
- Cranelift AOT design: ../../design/backend-cranelift-aot-design.md
Note: Some long-form papers reside under `private/papers/reference/architecture/`.

View File

@ -4,5 +4,5 @@ For the full guide, see:
- execution-backends.md (legacy location kept up to date)
Additional references:
- backend-llvm-implementation-guide.md
- ../../design/backend-llvm-implementation-guide.md
- VM_README.md

View File

@ -1,6 +1,659 @@
# Language Reference (2025)
# 🚀 Nyash Language Reference 2025
The canonical 2025 language reference currently lives here:
- private/papers/reference/language/LANGUAGE_REFERENCE_2025.md
**最終更新: 2025年9月4日 - Phase 12.7実装済み機能の正確な反映**
This stub exists to provide a stable public path under `docs/reference/language/`.
## 📖 概要
Nyashは「Everything is Box」哲学に基づく革新的プログラミング言語です。
Rust製インタープリターによる高性能実行と、直感的な構文により、学習しやすく実用的な言語として完成しました。
---
## 🔤 **1. 予約語・キーワード完全リスト**
### **Phase 12.7で確定した15個の予約語**
| 予約語 | 用途 | 例 |
|-------|------|---|
| `box` | クラス定義 | `box MyClass { }` |
| `new` | オブジェクト生成 | `new ConsoleBox()` |
| `me` | 自己参照thisの代わり | `me.field = value` |
| `local` | ローカル変数宣言 | `local x, y = 10` |
| `return` | 関数リターン | `return value` |
| `from` | デリゲーション・親メソッド呼び出し | `box Child from Parent` / `from Parent.method()` |
| `birth` | コンストラクタ(統一名) | `birth(param) { }` |
| `static` | 静的Box・関数定義 | `static box Main { }` |
| `if` | 条件分岐 | `if condition { }` |
| `else` | else節 | `else { }` |
| `loop` | ループ(唯一の形式) | `loop(condition) { }` |
| `continue` | ループ継続 | `continue` |
| `peek` | パターンマッチング風分岐 | `peek value { "A" => 1, else => 0 }` |
| `try` | 例外捕獲開始 | `try { }` |
| `interface` | インターフェース定義 | `interface Comparable { }` |
### **その他の重要キーワード(予約語ではない)**
| キーワード | 用途 | 例 |
|-------|------|---|
| `override` | 明示的オーバーライド | `override speak() { }` |
| `break` | ループ脱出 | `break` |
| `catch` | 例外処理 | `catch (e) { }` |
| `finally` | 最終処理 | `finally { }` |
| `throw` | 例外発生 | `throw error` |
| `nowait` | 非同期実行 | `nowait future = task()` |
| `await` | 待機・結果取得 | `result = await future` |
| `include` | ファイル取り込み | `include "math.nyash"` |
| `print` | 出力(デバッグ用) | `print("Hello")` |
| `function`/`fn` | 関数定義 | `fn add(a,b) { }` |
| `init` | 初期化ブロック | `init { field1, field2 }` |
| `pack` | 旧コンストラクタ(互換性) | `pack(param) { }` |
| `outbox` | 所有権移転変数 | `outbox result = compute()` |
| `global` | グローバル変数 | `global CONFIG = "dev"` |
| `weak` | 弱参照修飾子 | `weak reference` |
| `using` | 名前空間インポート | `using namespace` |
### **演算子・論理**
| 演算子/キーワード | 用途 | 例 |
|-------|------|---|
| `not` | 論理否定 | `not condition` |
| `and` | 論理積 | `a and b` |
| `or` | 論理和 | `a or b` |
| `true`/`false` | 真偽値 | `flag = true` |
| `null` | null値 | `value = null` |
---
## 📝 **2. 文法・構文仕様**
### **2.1 Box定義文法**
#### **基本Box**
```nyash
box ClassName {
# フィールド宣言Phase 12.7形式)
field1: TypeBox # フィールド型アテーションP0では無視
field2: TypeBox
field3 # 型なしも可
# コンストラクタ
birth(param1, param2) { # birth構文に統一
me.field1 = param1
me.field2 = param2
me.field3 = defaultValue()
}
# メソッド
methodName(arg1, arg2) {
return me.field1 + arg1
}
# デストラクタfini
fini() {
print("Cleanup: " + me.field1)
}
}
```
#### **デリゲーションBox**
```nyash
box Child from Parent interface Comparable {
childField: TypeBox # 追加フィールド
birth(parentParam, childParam) { # birth構文に統一
from Parent.birth(parentParam) # 親コンストラクタ明示呼び出し
me.childField = childParam
}
# メソッドオーバーライド
override process(data) { # overrideキーワード必須
local result = from Parent.process(data) # 親メソッド呼び出し
return result + " (Child processed)"
}
# インターフェース実装
compareTo(other) {
return me.value - other.value
}
}
```
#### **Static Box推奨エントリーポイント**
```nyash
static box Main {
console: ConsoleBox
result: IntegerBox
main() {
me.console = new ConsoleBox()
me.console.log("🎉 Everything is Box!")
return "Success"
}
}
```
### **2.2 変数宣言**
#### **基本パターン**
```nyash
# 単一宣言
local x
local name = "初期値"
# 複数宣言
local a, b, c
local x = 10, y = 20, z # 混合初期化
# 所有権移転static関数内
static function Factory.create() {
outbox product # 呼び出し側に所有権移転
product = new Item()
return product
}
```
#### **変数宣言厳密化システム2025-08-09実装**
```nyash
# ✅ 正しい - 明示宣言必須
local temp
temp = 42
# ❌ エラー - 未宣言変数への代入
x = 42 # RuntimeError: 未宣言変数 + 修正提案表示
```
### **2.3 制御構文**
#### **条件分岐**
```nyash
if condition {
# 処理
} else if condition2 {
# 処理2
} else {
# else処理
}
```
#### **ループ(統一構文)**
```nyash
# ✅ 唯一の正しい形式
loop(condition) {
# ループ本体
if exitCondition {
break
}
if skipCondition {
continue # Phase 12.7で追加
}
}
# ❌ 削除済み - 使用不可
while condition { } # パーサーエラー
loop() { } # パーサーエラー
```
#### **Peek式Phase 12.7で追加)**
```nyash
# パターンマッチング風の分岐
local result = peek value {
"A" => 100,
"B" => 200,
"C" => 300,
else => 0 # else必須
}
# 文の形式も可
peek status {
"error" => {
print("Error occurred")
return null
},
"success" => {
print("All good")
},
else => {
print("Unknown status")
}
}
```
### **2.4 演算子・式**
#### **🚀 新実装: 関数オーバーロードシステム**
```nyash
# Rust風トレイトベース演算子2025-08-10実装完了
sum = 10 + 20 # IntegerBox + IntegerBox = IntegerBox
concat = "Hi" + " !" # StringBox + StringBox = StringBox
repeat = "Ha" * 3 # StringBox * IntegerBox = "HaHaHa"
mixed = 42 + " answer" # 混合型 → 自動文字列結合フォールバック
```
#### **演算子優先順位**
```nyash
result = a + b * c / d - e # 算術演算子は標準的優先順位
logic = not a and b or c # not > and > or
compare = (x > y) and (z <= w) # 比較は括弧推奨
```
#### **論理演算子**
```nyash
# キーワード版(推奨)
canAccess = level >= 5 and hasKey
isValid = not (isEmpty or hasError)
# シンボル版(互換)
result = condition && other || fallback # 利用可能だが非推奨
```
#### **特殊演算子Phase 12.7実装済み)**
```nyash
# ? 演算子 - Result伝播
local data = readFile(path)? # エラーなら早期return
# ラムダ式
local add = fn(x, y) { return x + y }
local double = fn(x) { x * 2 } # 単一式なら省略可
# await式
local result = await asyncTask()
```
---
## 🏗️ **3. Box構文詳細ガイド**
### **3.1 Everything is Box 原則**
```nyash
# すべての値がBox
number = 42 # IntegerBox
text = "hello" # StringBox
flag = true # BoolBox
array = new ArrayBox() # ArrayBox
console = new ConsoleBox() # ConsoleBox
# 統一的なメソッド呼び出し
print(number.to_string_box().value) # "42"
print(array.length()) # 配列長
console.log("Everything is Box!") # コンソール出力
```
### **3.2 コンストラクタパターン**
#### **パラメータ付きコンストラクタ**
```nyash
box Person {
public name: StringBox
public email: StringBox
private age: IntegerBox
birth(personName, personAge) { # birth構文に統一
me.name = personName
me.age = personAge
me.email = me.name + "@example.com" # 計算フィールド
}
# ファクトリーメソッド
static createGuest() {
outbox guest
guest = new Person("Guest", 0)
return guest
}
}
# 使用例
person = new Person("Alice", 25)
guest = Person.createGuest()
```
### **3.3 継承とインターフェース**
#### **デリゲーションチェーン**
```nyash
# 基底Box
box Animal {
public name: StringBox
public species: StringBox
birth(animalName, animalSpecies) {
me.name = animalName
me.species = animalSpecies
}
speak() {
return me.name + " makes a sound"
}
}
# デリゲーション
box Dog from Animal {
breed: StringBox # 追加フィールド
birth(dogName, dogBreed) {
from Animal.birth(dogName, "Canine") # 親コンストラクタ呼び出し
me.breed = dogBreed
}
override speak() { # 明示的オーバーライド
return me.name + " barks: Woof!"
}
}
# インターフェース実装
box Cat from Animal interface Playful {
# Playfulインターフェースの実装必須
}
```
### **3.4 Static Boxパターン**
#### **名前空間・ユーティリティ**
```nyash
static box MathUtils {
PI: FloatBox
E: FloatBox
# 注意: static初期化ブロックは未実装
# 初期化はメソッド内で行う
add(a, b) {
return a + b
}
circleArea(radius) {
# 初回アクセスで初期化パターン
if me.PI == null {
me.PI = 3.14159265
}
return me.PI * radius * radius
}
}
# 使用法
area = MathUtils.circleArea(5)
sum = MathUtils.add(10, 20)
```
#### **アプリケーションエントリーポイント**
```nyash
# 🎯 推奨: Static Box Main パターン
static box Main {
console: ConsoleBox
result: IntegerBox
main() {
me.console = new ConsoleBox()
me.console.log("🚀 Starting application...")
# アプリケーションロジック
me.result = processData()
return "Application completed successfully"
}
}
```
---
## 🚀 **4. 最新機能・革新技術**
### **4.1 Arc<Mutex> Revolution2025-08-10**
```nyash
# 全16種類のBox型が統一Arc<Mutex>パターンで実装
# 完全なスレッドセーフティと高性能を両立
array = new ArrayBox()
array.push(10) # スレッドセーフな追加
array.push(20)
item = array.get(0) # スレッドセーフな取得
json = new JSONBox()
json.set("name", "Alice") # 並行安全な操作
data = json.stringify() # JSON文字列化
```
### **4.2 Rust風トレイトベース演算子2025-08-10**
```nyash
# AI大相談会で決定された最適設計
# 静的・動的ハイブリッドディスパッチによる高性能実現
# 整数演算
result = 100 - 25 # IntegerBox間演算 → IntegerBox
product = 6 * 7 # 高速静的ディスパッチ
# 文字列操作
greeting = "Hello" + " World" # 文字列結合
repeated = "Echo" * 3 # "EchoEchoEcho"
# 混合型フォールバック
message = "Answer: " + 42 # "Answer: 42"
# Boolean演算
boolSum = true + false # 1 (IntegerBox)
```
### **4.3 変数宣言厳密化2025-08-09**
```nyash
# メモリ安全性・非同期安全性保証システム
static box Calculator {
private memory: ArrayBox # 必須フィールド宣言
calculate() {
local temp # 必須ローカル変数宣言
temp = me.memory * 2
return temp
}
}
```
---
## 🚀 **4.4 Phase 12.7実装済み機能**
### **Peek式 - パターンマッチング風分岐**
```nyash
# 式として使用(値を返す)
local grade = peek score {
100 => "Perfect",
90 => "Excellent",
80 => "Good",
else => "Needs improvement"
}
# 文として使用(アクション実行)
peek command {
"save" => {
saveFile()
print("Saved!")
},
"quit" => {
cleanup()
return
},
else => print("Unknown command")
}
```
### **Continue文**
```nyash
loop(i < 100) {
if i % 2 == 0 {
continue # 偶数をスキップ
}
process(i)
}
```
### **フィールド型アノテーション**
```nyash
box Person {
name: StringBox # 型情報を明記P0では無視
age: IntegerBox
email # 型なしも可
}
```
### **?演算子Result伝播**
```nyash
# ResultBoxのエラーを自動的に早期return
local data = readFile("config.json")?
local parsed = parseJSON(data)?
return parsed.get("version")
```
### **Lambda式**
```nyash
# 基本形
local add = fn(x, y) { return x + y }
# 単一式の場合returnは省略可
local double = fn(x) { x * 2 }
# 高階関数での使用
array.map(fn(x) { x * x })
```
---
## ⚡ **5. 実装済みBox型ライブラリ**
### **5.1 基本型**
- `StringBox` - 文字列split, find, replace, trim等
- `IntegerBox` - 64bit整数
- `FloatBox` - 64bit浮動小数点数
- `BoolBox` - 真偽値
- `NullBox` - null値
- `VoidBox` - void値
### **5.2 コレクション**
- `ArrayBox` - 動的配列push, pop, get, set, join等
- `MapBox` - 連想配列・辞書
### **5.3 システム・I/O**
- `ConsoleBox` - コンソール入出力
- `DebugBox` - デバッグ支援・メモリ追跡
- `FileBox` - ファイルシステム操作(プラグイン)
### **5.4 数学・時間**
- `MathBox` - 数学関数sin, cos, log, sqrt等
- `TimeBox` - 時刻操作・タイマー
- `RandomBox` - 乱数生成・選択・シャッフル
### **5.5 データ処理**
- `JSONBox` - JSON解析・生成parse, stringify, get, set
- `RegexBox` - 正規表現test, find, replace, split
- `BufferBox` - バイナリデータ処理
- `StreamBox` - ストリーム処理
### **5.6 ネットワーク・Web**
- `HttpClientBox` - HTTP通信プラグイン
- `WebDisplayBox` - HTML表示WASM
- `WebConsoleBox` - ブラウザコンソールWASM
- `WebCanvasBox` - Canvas描画WASM
### **5.7 GUI・マルチメディア**
- `EguiBox` - デスクトップGUIWindows/Linux、プラグイン
- `SoundBox` - 音声再生
### **5.8 特殊用途**
- `FutureBox` - 非同期処理結果
- `ResultBox` - エラー処理Ok/Err
- `TokenBox` - キャンセルトークン
- `FunctionBox` - 第一級関数
- `P2PBox` - P2P通信プラグイン
---
## 🎯 **6. パフォーマンス・デザイン原則**
### **6.1 メモリ安全性**
- Rust所有権システムによる完全なメモリ安全性
- Arc<Mutex>によるスレッドセーフな共有状態管理
- 自動参照カウント + 明示的デストラクタfini
### **6.2 実行効率**
- 統一されたBox型システムによる最適化
- 静的・動的ハイブリッドディスパッチで高速演算
- パーサー無限ループ対策(--debug-fuel
### **6.3 開発効率**
- 変数宣言厳密化による早期エラー検出
- 包括的デバッグ機能DebugBox
- 直感的な"Everything is Box"概念
---
## 📚 **7. 学習パス・ベストプラクティス**
### **7.1 初心者向け学習順序**
1. **基本概念**: Everything is Box哲学理解
2. **基本構文**: 変数宣言・制御構文・演算子
3. **Box定義**: 基本的なクラス作成
4. **Static Box Main**: アプリケーションエントリーポイント
5. **継承・インターフェース**: オブジェクト指向機能
### **7.2 推奨コーディングスタイル**
```nyash
# ✅ 推奨スタイル
static box Main {
public console: ConsoleBox # 公開フィールド明示
public result: IntegerBox
main() {
me.console = new ConsoleBox()
local data # 変数事前宣言
data = processInput()
me.result = data # 明確な代入
return "Success"
}
}
```
### **7.3 よくある間違いと対策**
```nyash
# ❌ よくある間違い
public { field1 field2 } # 旧構文 → 使用不可
x = 42 # 変数未宣言 → ランタイムエラー
while condition { } # 非対応構文 → パーサーエラー
this.field # thisは使用不可 → me.fieldを使用
# ✅ 正しい書き方Phase 12.7後)
field1: TypeBox # フィールド宣言(型は省略可)
field2 # 型なしフィールド
local x = 42 # 事前宣言必須
loop(condition) { } # 統一ループ構文
me.field # self参照はmeのみ
```
---
## 📌 **8. 糖衣構文Phase 12.7-B**
### 実装済み(ゲート: `NYASH_SYNTAX_SUGAR_LEVEL=basic|full`
```nyash
# パイプライン
result = data |> normalize() |> transform() |> process
# セーフアクセス + デフォルト
name = user?.profile?.name ?? "guest"
# 複合代入
x += 1; y *= 2
# 範囲(内部的には Range(a,b)
loop(i in 1 .. 5) { /* ... */ }
```
### 拡張(段階適用予定・設計済み)
```nyash
let {x, y} = point
let [first, second, ...rest] = array
```
---
**🎉 Nyash 2025は、AI協働設計による最先端言語システムとして、シンプルさと強力さを完全に両立しました。**
*最終更新: 2025年9月4日 - Phase 12.7実装済み機能の正確な反映*

View File

@ -104,3 +104,36 @@ Notes
- Phase 15 keeps resolution in the Runner to minimize parser complexity. Future phases may leverage `meta.usings` for compiler decisions.
- Unknown fields in the toplevel JSON (like `meta`) are ignored by the current bridge.
- 未解決時非strictは実行を継続し、`NYASH_RESOLVE_TRACE=1` で候補を提示。strict時はエラーで候補を表示。
## Include/Export (Phase 1)
Simple include expression for filescoped modulesPhase 1 提案)。将来は `using`/Runner 解決へ統合予定。
Overview
- One file exports one static box. `include(path)` evaluates the file and returns that Box instance.
Syntax
```
local Math = include "lib/math.nyash"
local r = Math.add(1, 2)
```
Rules
- Single static box per file0/複数はエラー)
- Expression form: `include(...)` は Box インスタンスを返す式
- Caching: 同一パスは一度だけ評価2回目以降はキャッシュ返却
- Path resolutionMVP:
- Relative allowed; absolute discouraged
- nyash.toml `[include.roots]``std=/stdlib` 等のルート定義を許可
- 省略拡張は `.nyash`、ディレクトリなら `index.nyash`
Backends
- Interpreter: 実行時に評価し Box を返す
- VM/AOT: MIR Builder が対象ファイルを読み取り、同一 MIR モジュールに static box を降ろす(専用 MIR 命令は追加しない)
Limitations
- 循環 include の検出/診断は未実装(後続で active-load 追跡と経路表示を追加)
Rationale
- MIR 仕様に変更を入れず、実用的なモジュール分割を提供
- EverythingisBox に整合(モジュール=Box、メソッド/フィールド=API

Some files were not shown because too many files have changed in this diff Show More