docs(lang): adopt match as unified pattern matching; remove peek from docs; update EBNF and guides

- Decision recorded in CURRENT_TASK: replace  with  (no compat alias)
- EBNF: add match_expr/pattern/guard; note legacy peek removal
- Guides/Reference: update examples and wording (null-coalesce/safe-access sugar via match)
This commit is contained in:
Selfhosting Dev
2025-09-19 07:42:38 +09:00
parent 52ab2957e6
commit 45e1d57536
5 changed files with 255 additions and 20 deletions

View File

@ -26,6 +26,20 @@ factor := INT
| 'new' IDENT '(' args? ')'
| '[' args? ']' ; Array literal (Stage1 sugar, gated)
| '{' map_entries? '}' ; Map literal (Stage2 sugar, gated)
| match_expr ; Pattern matching (replaces legacy peek)
match_expr := 'match' expr '{' match_arm+ default_arm? '}'
match_arm := pattern guard? '=>' (expr | block) ','?
default_arm:= '_' '=>' (expr | block) ','?
pattern := '_'
| STRING | INT | 'true' | 'false' | 'null'
| IDENT '(' IDENT? ')' ; Type pattern e.g., StringBox(s)
| '[' (IDENT (',' '..' IDENT)? )? ']'
| '{' ( (STRING|IDENT) ':' IDENT (',' '..')? )? '}'
| pattern '|' pattern ; OR pattern (same arm)
guard := 'if' expr
map_entries := (STRING | IDENT) ':' expr (',' (STRING | IDENT) ':' expr)* [',']
@ -42,6 +56,57 @@ Notes
- Array literal is enabled when syntax sugar is on (NYASH_SYNTAX_SUGAR_LEVEL=basic|full) or when NYASH_ENABLE_ARRAY_LITERAL=1 is set.
- Map literal is enabled when syntax sugar is on (NYASH_SYNTAX_SUGAR_LEVEL=basic|full) or when NYASH_ENABLE_MAP_LITERAL=1 is set.
- Identifier keys (`{name: v}`) are Stage3 and require either NYASH_SYNTAX_SUGAR_LEVEL=full or NYASH_ENABLE_MAP_IDENT_KEY=1.
- Pattern matching: `match` replaces legacy `peek`. MVP supports wildcard `_`, literals, simple type patterns, fixed/variadic array heads `[hd, ..tl]`, simple map key extract `{ "k": v, .. }`, OR patterns, and guards `if`.
## Box Members (Phase15, env gate: NYASH_ENABLE_UNIFIED_MEMBERS; default ON)
This section adds a minimal grammar for Box members (a unified member model) without changing JSON v0/MIR. Parsing is controlled by env `NYASH_ENABLE_UNIFIED_MEMBERS` (default ON; set `0/false/off` to disable).
```
box_decl := 'box' IDENT '{' member* '}'
member := stored
| computed
| once_decl
| birth_once_decl
| method_decl
| block_as_role ; nyash-mode (block-first) equivalent
stored := IDENT ':' TYPE ( '=' expr )?
; stored property (read/write). No handlers supported.
computed := IDENT ':' TYPE ( '=>' expr | block ) handler_tail?
; computed property (readonly). Recomputes on each read.
once_decl := 'once' IDENT ':' TYPE ( '=>' expr | block ) handler_tail?
; lazy once. First read computes and caches; later reads return cached value.
birth_once_decl:= 'birth_once' IDENT ':' TYPE ( '=>' expr | block ) handler_tail?
; eager once. Computed during construction (before user birth), in declaration order.
method_decl := IDENT '(' params? ')' ( ':' TYPE )? block handler_tail?
; nyash-mode (block-first) variant — gated with NYASH_ENABLE_UNIFIED_MEMBERS=1
block_as_role := block 'as' ( 'once' | 'birth_once' )? IDENT ':' TYPE
handler_tail := ( catch_block )? ( cleanup_block )?
catch_block := 'catch' ( '(' ( IDENT IDENT | IDENT )? ')' )? block
cleanup_block := 'cleanup' block
```
Semantics (summary)
- stored: O(1) slot read; write via assignment. Initializer (if present) evaluates at construction once.
- computed: readonly; each read evaluates the block; assignment is an error unless a setter is explicitly defined.
- once: first read evaluates the block and caches the value; subsequent reads return the cached value. On exception without a `catch`, the property becomes poisoned and rethrows on later reads (no retries).
- birth_once: evaluated before the user `birth` body, in declaration order; exceptions without a `catch` abort construction; cycles between `birth_once` members are an error.
- handlers: `catch/cleanup` are permitted for computed/once/birth_once/method blocks (Stage3), not for stored.
Lowering (no JSON v0 change)
- stored → slot
- computed → synthesize `__get_name():T { try body; catch; finally }`; reads of `obj.name` become `obj.__get_name()`
- once → add `__name: Option<T>` and emit `__get_name()` with firstread initialization; on uncaught exception mark poisoned and rethrow on subsequent reads
- birth_once → add `__name: T` and insert initialization just before user `birth` in declaration order; handlers apply to each initializer
- method → existing method forms; optional postfix handlers lower to try/catch/finally
## Stage3 (Gated) Additions
@ -63,4 +128,8 @@ Enabled when `NYASH_PARSER_STAGE3=1` for the Rust parser (and via `--stage3`/`NY
- `method_decl := 'method' IDENT '(' params? ')' block ('catch' '(' (IDENT IDENT | IDENT | ε) ')' block)? ('cleanup' block)?`
- Gate: `NYASH_METHOD_CATCH=1`(または `NYASH_PARSER_STAGE3=1` と同梱)
- Memberlevel postfix catch/cleanupPhase 15.6, gated
- Applies to computed/once/birth_once in the unified member model: see “Box Members”.
- Gate: `NYASH_PARSER_STAGE3=1` (shared). Stored members do not accept handlers.
These constructs remain experimental; behaviour may degrade to noop in some backends until runtime support lands, as tracked in CURRENT_TASK.md.

View File

@ -1,6 +1,6 @@
# 🚀 Nyash Language Reference 2025
**最終更新: 2025年9月4日 - Phase 12.7実装済み機能の正確な反映**
**最終更新: 2025年9月18日 - Property System Revolution + Method-Level Exception Handling**
## 📖 概要
@ -11,7 +11,7 @@ Rust製インタープリターによる高性能実行と、直感的な構文
## 🔤 **1. 予約語・キーワード完全リスト**
### **Phase 12.7で確定した15個の予約語**
### **Phase 15で確定した17個の予約語**
| 予約語 | 用途 | 例 |
|-------|------|---|
| `box` | クラス定義 | `box MyClass { }` |
@ -26,9 +26,11 @@ Rust製インタープリターによる高性能実行と、直感的な構文
| `else` | else節 | `else { }` |
| `loop` | ループ(唯一の形式) | `loop(condition) { }` |
| `continue` | ループ継続 | `continue` |
| `peek` | パターンマッチング風分岐 | `peek value { "A" => 1, else => 0 }` |
| `match` | パターンマッチング(構造/型/ガード) | `match value { "A" => 1, _ => 0 }` |
| `try` | 例外捕獲開始 | `try { }` |
| `interface` | インターフェース定義 | `interface Comparable { }` |
| `once` | **NEW** 遅延評価プロパティ | `once cache: CacheBox { build() }` |
| `birth_once` | **NEW** 即座評価プロパティ | `birth_once config: ConfigBox { load() }` |
### **その他の重要キーワード(予約語ではない)**
| キーワード | 用途 | 例 |
@ -194,7 +196,7 @@ loop() { } # パーサーエラー
#### **Peek式Phase 12.7で追加)**
```nyash
# パターンマッチング風の分岐
local result = peek value {
local result = match value {
"A" => 100,
"B" => 200,
"C" => 300,
@ -202,7 +204,7 @@ local result = peek value {
}
# 文の形式も可
peek status {
match status {
"error" => {
print("Error occurred")
return null
@ -254,6 +256,63 @@ local add = fn(x, y) { return x + y }
local double = fn(x) { x * 2 } # 単一式なら省略可
# await式
### **2.5 プロパティ(統一メンバ — Phase 15、既定ON: NYASH_ENABLE_UNIFIED_MEMBERS**
概要
- Box 内のメンバを「格納/計算/一度だけ(遅延 or 生成時」で統一的に扱います。JSON v0/MIR は変更せず、ローワで既存の slot/method に展開します。
- 環境変数 `NYASH_ENABLE_UNIFIED_MEMBERS` で制御Phase 15 では既定ON、`0/false/off` で無効化)。
分類と構文headerfirst
- stored格納・読み書き可
- `name: Type` または `name: Type = expr`(初期値は生成時に一度だけ評価)
- computed計算・読み専用
- `name: Type { /* body */ }`(読むたびに計算。代入不可)
- once初回アクセス時に一度だけ計算 → 以後は保存値)
- `once name: Type { /* body */ }` または `once name: Type => expr`
- birth_once生成時に一度だけ計算 → 以後は保存値)
- `birth_once name: Type { /* body */ }` または `birth_once name: Type => expr`
nyashモードblockfirst、オプション
- `{"..."}` の直後に `as` を置く統一構文を、Box メンバ領域で受理
- computed: `{ body } as name: Type`
- once: `{ body } as once name: Type`
- birth_once: `{ body } as birth_once name: Type`
- stored は blockfirst では宣言しないheaderfirst を使用)
共通ルール
- 読みは全て `obj.name` で同一表記。違いは書き込み可否と計算タイミングのみ。
- 代入:
- stored のみ許可(`obj.name = v`)。
- computed/once/birth_once は代入不可エラー。setter を定義した場合のみ糖衣で許可(`obj.name = v` → `__set_name(v)`)。
```nyash
box MyBox {
name: StringBox # stored
size: IntegerBox { me.items.len() } # computed
once cache: CacheBox { buildCache() } # once
birth_once token: StringBox { readEnv("TOKEN") } # eager once
}
```
例外・ハンドラStage3, `NYASH_PARSER_STAGE3=1`
- stored 以外のブロック末尾に `catch`/`cleanup` を付与可能headerfirst / blockfirst 両対応)。
- computed: `name: T { body } catch(e) { ... } cleanup { ... }`
- once: `once name: T { body } catch { ... } cleanup { ... }`
- birth_once: `birth_once name: T { body } catch { ... } cleanup { ... }`
- once の例外ポリシーcatch が無い場合): 例外をその場で伝播し、プロパティは poison 状態となり以後の読みでも同じ例外を再スロー(再実行しない)。
- birth_once の実行順: ユーザ `birth` 本体の前、宣言順で実行。未捕捉例外はコンストラクタ失敗として伝播。自己参照はエラー。相互依存の循環は検出してエラー。
ローワ(下ろし先の概要)
- stored → slot初期化子は生成時に一度だけ評価
- computed → `__get_name():T` メソッドを合成し、`obj.name` 読みを呼び出しに解決。
- once → `__name: Option<T>` + `__get_name()`(初回のみ評価・保存)。未捕捉例外で poison し、以後は即 rethrow。
- birth_once → `__name: T` を用意し、`birth` 直前に宣言順で初期化コードを挿入。未捕捉例外は `new` 失敗。
注意
- JSON v0 は unchanged。Unified Members はパーサ/ローワの砂糖として振る舞います。
- stored の初期化子は式のみ(`catch/cleanup` は不可)。
local result = await asyncTask()
```
@ -453,15 +512,15 @@ static box Calculator {
### **Peek式 - パターンマッチング風分岐**
```nyash
# 式として使用(値を返す)
local grade = peek score {
local grade = match score {
100 => "Perfect",
90 => "Excellent",
80 => "Good",
else => "Needs improvement"
_ => "Needs improvement"
}
# 文として使用(アクション実行)
peek command {
match command {
"save" => {
saveFile()
print("Saved!")
@ -470,7 +529,7 @@ peek command {
cleanup()
return
},
else => print("Unknown command")
_ => print("Unknown command")
}
```

View File

@ -4,11 +4,11 @@ This is the entry point for Nyash language documentation.
- Full Language Reference (2025): reference/language/LANGUAGE_REFERENCE_2025.md
- Syntax Cheat Sheet: quick-reference/syntax-cheatsheet.md
- Phase 12.7 Grammar Specs (peek, ternary, sugar):
- Phase 12.7 Grammar Specs (ternary, sugar; peek → match に統合):
- Overview: development/roadmap/phases/phase-12.7/grammar-specs/README.md
- Token/Grammar: development/roadmap/phases/phase-12.7/ancp-specs/ANCP-Token-Specification-v1.md
- Sugar Transformations (?., ??, |> and friends): parser/sugar.rs (source) and tools/nyfmt/NYFMT_POC_ROADMAP.md
- Peek Expression Design/Usage: covered in the Language Reference and Phase 12.7 specs above
- Match Expression (pattern matching): see the Language Reference and EBNF (peek was replaced by match)
Statement separation and semicolons
- See: reference/language/statements.md — newline as primary separator; semicolons optional for multiple statements on one line; minimal ASI rules.
@ -18,6 +18,10 @@ Imports and namespaces
Grammar (EBNF)
- See: reference/language/EBNF.md — Stage2 grammar specification used by parser implementations.
- Unified Members (stored/computed/once/birth_once): see reference/language/EBNF.md “Box Members (Phase 15)” and the Language Reference section. Default ON (disable with `NYASH_ENABLE_UNIFIED_MEMBERS=0`).
Member exceptions and handlers (Stage3)
- Postfix `catch/cleanup` may be attached to computed/once/birth_once/method blocks when Stage3 is enabled. Stored members (plain `name: Type [= expr]`) do not support handlers.
Related implementation notes
- Tokenizer: src/tokenizer.rs
@ -26,4 +30,4 @@ Related implementation notes
Navigation tips
- The “reference/language/LANGUAGE_REFERENCE_2025.md” is the canonical longform reference; use the Cheat Sheet for quick syntax lookup.
- Phase 12.7 files capture the finalized sugar and new constructs (peek, ternary, nullsafe).
- Phase 12.7 files capture the finalized sugar and new constructs (match (replaces peek), ternary, nullsafe).