# 指針: どの構造を sum type にするか

> [!NOTE]
> 執筆: Claude Code（Opus 5.5）。本文の基準（#158 の点検コメント）を一般化し、草稿を `moonbit/` のコードに照らして直した版。照らし合わせた結果は末尾の表にある。

本文の7項目は「Go の形を写していないか」を点検するための基準だった。ここではそれを、新しく型を書くときにも使える形に組み直す。問いは3つ。どの構造を sum type にするか、sum type にしない方がよいのはいつか、enum を超えて state machine に移した方がよいのはいつか。

## どの構造を sum type にするか

共通する兆候は「値の意味を、型ではなく呼び出し側が再解釈している」こと。次のどれかがあれば候補になる。

1. 排他な状態を複数の変数で表している。Bool が2つで4通り表現できるのに、意味のある組は3通り以下。あるいは「同時に1つしか非空にならない」バッファが並んでいる
2. 1つの状態が、型の違う2か所に分かれている。Bool と別の enum の variant、あるいは2つの enum の組で、直積に起こりえない組がある。1 と同じ問題だが、片方がすでに enum なので見落としやすい
3. ある状態のときだけ意味を持つフィールドがある。その状態でないときにダミー値（`""`、`0`、空の構造体）を入れている
4. 「無い」を値の領域の一部で表している。`""`、`-1`、`0` を返し、呼び出し側が `== ""` で分岐する
5. 閉じた語彙を文字列で持っている。取りうる値をコードの作者が列挙でき、増えるときはコードの変更を伴う
6. 性質を持ち主でない場所に置いている。リスト全体の性質を各項目に置き、「先頭項目で決まる」という規則を利用側が繰り返す
7. match に `_ =>` のフォールバックが要る。型が実際に取りうる値より広い

判断の要は 4 と 7 の「再解釈」で、`""` や `-1` があること自体ではない。値としての意味（空の文字列、ソートキーとしての -1）を持つなら残してよい。再解釈が1つの関数の中で閉じていて、外に漏れないなら優先度は低い。

置き換え先は兆候で決まる。

| 兆候 | 置き換え先 |
| ---- | ---- |
| 排他な状態、状態依存のフィールド | enum の variant と、その payload |
| 2か所に分かれた1つの状態 | 一方を他方の variant の payload に入れる。組で起こる値だけが残る |
| 欠落 | `T?` |
| 閉じた語彙 | payload のない enum。文字列への変換は出力の境界で |
| 性質の置き場所 | 持ち主の型へ移す。sum type の問題ではないが、移すと sum type の置き場所ができることが多い |

2 に当たった実例が、末尾の表にある router と `scan` の2件。「型の違う2か所」を縦横に掛け合わせると、意味のある組は直積の一部だけだった。enum に畳むと ○ の組だけが残る。

```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="14 17 733.05 179.2" width="733" height="179" role="img" aria-label="product grids of the two split states; O marks combinations that occur, x marks ones the types allow but no input produces">
<text x="24" y="40" font-size="13" fill="currentColor">Route: subtree x 最後の segment</text>
<path d="M24 44.6 L241.75000000000009 44.6" fill="none" stroke="currentColor" stroke-width="2"/>
<text x="139.64999999999998" y="56" font-size="11" text-anchor="middle" fill="currentColor">lit/{x}</text>
<text x="197.64999999999998" y="56" font-size="11" text-anchor="middle" fill="currentColor">{$}</text>
<text x="255.64999999999998" y="56" font-size="11" text-anchor="middle" fill="currentColor">{x...}</text>
<text x="313.65" y="56" font-size="11" text-anchor="middle" fill="currentColor">(empty)</text>
<text x="104.64999999999999" y="75" font-size="11" text-anchor="end" dominant-baseline="central" fill="currentColor">subtree=false</text>
<rect x="110.64999999999999" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="139.64999999999998" y="75" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="168.64999999999998" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="197.64999999999998" y="75" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="226.64999999999998" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="255.64999999999998" y="75" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="284.65" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="313.65" y="75" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<text x="104.64999999999999" y="101" font-size="11" text-anchor="end" dominant-baseline="central" fill="currentColor">subtree=true</text>
<rect x="110.64999999999999" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="139.64999999999998" y="101" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="168.64999999999998" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="197.64999999999998" y="101" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="226.64999999999998" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="255.64999999999998" y="101" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="284.65" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="313.65" y="101" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<text x="24" y="132" font-size="11" fill="currentColor" opacity="0.75">5 of 8 occur -&gt; Tail { Exact; End; Subtree; Rest }</text>
<text x="390.65" y="40" font-size="13" fill="currentColor">scan: mode x pending</text>
<path d="M390.65 44.6 L533.6500000000001 44.6" fill="none" stroke="currentColor" stroke-width="2"/>
<text x="476.04999999999995" y="56" font-size="11" text-anchor="middle" fill="currentColor">Nothing</text>
<text x="534.05" y="56" font-size="11" text-anchor="middle" fill="currentColor">Para</text>
<text x="592.05" y="56" font-size="11" text-anchor="middle" fill="currentColor">Items</text>
<text x="650.05" y="56" font-size="11" text-anchor="middle" fill="currentColor">Quote</text>
<text x="708.05" y="56" font-size="11" text-anchor="middle" fill="currentColor">Table</text>
<text x="441.04999999999995" y="75" font-size="11" text-anchor="end" dominant-baseline="central" fill="currentColor">Normal</text>
<rect x="447.04999999999995" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="476.04999999999995" y="75" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="505.04999999999995" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="534.05" y="75" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="563.04999999999995" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="592.05" y="75" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="621.05" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="650.05" y="75" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="679.05" y="62" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="708.05" y="75" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<text x="441.04999999999995" y="101" font-size="11" text-anchor="end" dominant-baseline="central" fill="currentColor">Code</text>
<rect x="447.04999999999995" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="476.04999999999995" y="101" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="505.04999999999995" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="534.05" y="101" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="563.05" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="592.05" y="101" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="621.05" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="650.05" y="101" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="679.05" y="88" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="708.05" y="101" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<text x="441.04999999999995" y="127" font-size="11" text-anchor="end" dominant-baseline="central" fill="currentColor">Details</text>
<rect x="447.04999999999995" y="114" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="476.04999999999995" y="127" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="505.04999999999995" y="114" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="534.05" y="127" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="563.05" y="114" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="592.05" y="127" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="621.05" y="114" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="650.05" y="127" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="679.05" y="114" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="708.05" y="127" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<text x="441.04999999999995" y="153" font-size="11" text-anchor="end" dominant-baseline="central" fill="currentColor">Footnote</text>
<rect x="447.04999999999995" y="140" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1.5" opacity="1"/>
<text x="476.04999999999995" y="153" font-size="13" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="1">O</text>
<rect x="505.04999999999995" y="140" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="534.05" y="153" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="563.05" y="140" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="592.05" y="153" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="621.05" y="140" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="650.05" y="153" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<rect x="679.05" y="140" width="58" height="26" rx="2" fill="none" stroke="currentColor" stroke-width="1" opacity="0.25"/>
<text x="708.05" y="153" font-size="12" text-anchor="middle" dominant-baseline="central" fill="currentColor" opacity="0.35">x</text>
<text x="390.65" y="184" font-size="11" fill="currentColor" opacity="0.75">8 of 20 occur -&gt; Normal(Pending)</text>
</svg>
```

## sum type にしない方がよい状況

1. 範囲のある数値。見出しの level 1..5 を5 variant にしても値の写しになるだけで、算術（`level + 1`）が書けなくなる。構築時の検査で足りる。その代わり、数値で分岐する match には `_ =>` が残る。これは7の例外として受け入れる
2. 外部入力そのもの。front matter の生の値や URL 文字列は文字列のまま受け取り、パースした結果を型にする。境界より内側だけを型で守る。front matter の `title: ""` を「指定なし」として扱うのは、境界で行う変換なのでここに当たる
3. 開いた集合。利用者やデータが新しい値を持ち込む（タグ名、ファイル拡張子、HTTP ヘッダ名）なら enum は閉じすぎる。既知の値に variant を与えて `Other(String)` を残す形もあるが、既知の値で分岐する処理が無いなら文字列のままでよい
4. データが増えて操作が固定のとき。variant を足すたびに全 match を直すことになる。操作の方が増えるなら enum、データの種類の方が増えるなら trait や関数の記録が向く（expression problem の二択）
5. 真の2値で、他の状態と組み合わさらない Bool。`at_line_start` のようなトグルは enum にしても名前が変わるだけ。名前付き引数の ON/OFF も同じ
6. 呼び出し側が存在を保証している API。ルータが一致を保証した後の `param` を `String?` にすると、全呼び出し側に到達しない unwrap が増える
7. 空のコレクション。空配列は `is []` で素直に分岐できる。`Option` が要るのは、空を作るために必須フィールドの値を捏造しないといけない型（`ItemList` の `kind`）だけ
8. 計算の中で使う番兵。API は `Int32?` で受け取り、関数の中で比較の下限として `-1` に直すのは構わない（`nest_items` の `parent.unwrap_or(-1)`）。番兵が関数の外に出ないなら、型が守るべき不変条件は無い
9. フラグはあるが、そのフラグのときだけ意味を持つフィールドが無い。variant にしても名前が明瞭になるだけなら優先度は低い。ただし先に「どの構造を」の 2 を確かめる。フラグが別の型の variant と排他なら、それは同じ状態の片割れで、この項には当たらない

## state machine に移した方がよい状況

enum で「今の状態」を表せても、遷移の規則がループ本体に散っていれば読みにくさは残る。次のときは遷移を関数として切り出すことを考える。

1. 状態が時間とともに変わり、遷移の順序に規則がある。「未ロード → ロード済み」のように後戻りしない、あるいは特定の入力でだけ遷移する
2. 複数の mutable 変数が共同で「今どのモードか」を表している。本文の `scan` がこれで、まず enum に畳み、その次の段階として遷移を切り出す
3. 「この入力はこの状態でしか起きない」という規則がある。例: コードフェンスの中では見出しを見ない
4. 同じ遷移が複数の場所に書かれている。典型は「閉じる入力が来たとき」と「入力が尽きたとき」の2か所に同じ後始末がある形。入力の終わりも1つの入力として扱い、`close(state)` に寄せる
5. 遷移そのものをテストしたい。`step(state, input) -> state` の形にすると、入力列を与えずに1遷移ずつ検査できる

逆に、enum にした段階で止めてよいのは次のとき。

- 遷移が一度きり、または「キーが変わったら作り直す」だけ。遅延初期化は `T?` か Lazy で足りる
- 遷移の規則がループ本体の1つの match に収まっていて、各 arm が短い
- 状態の外から観測されない。関数内のローカルな状態で、テストは入出力で取れる

## MoonBit で書くときの道具

- variant の payload を更新するには、`mut` ラベル付きフィールドと `as` 束縛を使う。`Details(..) as d` と束縛して `d.depth -= 1`。これを知らないと enum 化を諦めて mutable 変数に戻しがち
- variant の payload だけを触る処理は、その variant の match arm の内側に置く。外に置くと「ここでは必ずこの variant」が型に言えず、到達しない `else` を `abort` か `continue` で埋めることになる
- `is` パターンで「この variant のときだけ」を式の中に書ける（`if it.children is Some(sub)`）
- 文字列への変換は enum のメソッド（`name()` など）に1か所だけ置く
- JS や JSON への出力は内部の型に従わせる。ワイヤ形式のために内部の型を崩さない

## 点検の手順

1. `Bool` フィールドと `let mut` の Bool、`== ""`、`-1`、`_ =>` を検索する
2. 見つかった箇所ごとに、値が「欠落・状態」を表しているのか「値そのもの」なのかを判断する
3. 状態なら、同じ状態を表している他の変数や他の型の variant を探す。組で1つの状態なら enum の候補
4. 上の「しない方がよい状況」に当たらないかを確かめる
5. 遷移の規則が散っている、または同じ遷移が2か所にあれば、state machine への切り出しを検討する

## `moonbit/` に照らした結果

上の手順1の検索を、テストと `embedded.mbt`、計測用の `experiments/adapter-abi` と `experiments/profile-demo` を除いた `.mbt` に対して行い、引っかかった箇所を読んで判断した。コードは変更していない。

| 場所 | 形 | 当たる項目 | 判断 |
| ---- | ---- | ---- | ---- |
| `pkg/http/router.mbt` の `Route` | `subtree : Bool` と、`Segment` の `End`（`{$}`）・`Rest`（`{x...}`）が、どれも「パターンの末尾の形」を表す。3つは排他で、`End`/`Rest` は最後の位置にしか現れないが、型はどちらも許す。`match_path` は末尾の判定を `last() is Some(End)` と `self.subtree` の if 連鎖で再構成している | どの構造を 2 | 実施済み。`Route.tail : Tail { Exact; End; Subtree; Rest(String) }` に畳み、`Segment` は途中の位置の `Literal`/`Wildcard` だけになった。末尾判定と `rank` は `tail` の match |
| `pkg/tinymarkdown/tinymarkdown.mbt` の `scan` | `Mode` と `Pending` の2つの enum。`Mode` が `Normal` 以外に入る前に必ず `flush()` するので、`Pending` が非空なのは `Normal` のときだけ | どの構造を 2 | 実施済み。`Pending` は `Normal` の payload になり、スキャナの状態は `Scan { out, notes, mode }` の1値に。1行の処理は `Scan::step`、モードごとの遷移が `self.mode` の1つの match に収まる |
| 同じく `scan` | `Code` と `Footnote` を閉じる処理が、閉じる行のときと入力の終わりの2か所にある。`Code` の `info` を `""` なら `None` にする変換も2回書かれている | state machine 4 | 実施済み。閉じる処理は `Scan::close` に寄せ、ループ後は `close` を呼ぶだけになった。`info` は `Code` に入る時点で `String?` にし、閉じる側の変換は消えた |
| `nest_items` の `parent.unwrap_or(-1)` | API は `Int32?`、関数の中で下限として `-1` | しない方が 8 | このままでよい |
| `content.mbt` の `rank.unwrap_or(-1)` | ソートキー | しない方が 8 | このままでよい（本文と同じ判断） |
| `content.mbt` の `first_paragraph` | 見つからないときに `""` を返し、再帰の中で `!= ""` を再判定する | 再解釈が関数内で閉じる | 低優先。呼び出し側は `""` を説明文としてそのまま使うので、外では値として扱われている |
| `site.mbt` の `Site::Site` | ホスト部が取れないときに `""` を入れ、直後に `host == ""` でエラー | 再解釈が関数内で閉じる | 低優先。`guard` で直接エラーにすれば番兵が消える程度 |
| `views.mbt` の `heading` | `level` の match に `_ => @el.h5` | しない方が 1 | このままでよい |
| `compare.mbt` の `Report.same : Bool` | 一致・差分・取得エラーの3通りを `same` と `text` で表す | しない方が 9 | 低優先。`text` はどの場合も出力されるので、状態依存のフィールドは無い。エラーを区別したくなったら enum にする |
| worker の `SiteState` | `Unloaded \| Loaded(base~, result~)`。base が変わったら読み直す | state machine に移さない 1 | このままでよい。遷移は「キーが変わったら作り直す」だけ |
| `links.mbt` の `escape(fragment~)`、`resolver(repo_files~)`、`url.mbt` の `unescape(plus~)`、`inline.mbt` の `split_inlines(links~)`、`Router.decoded_path`、`wire.mbt` の `in_env`、`render.mbt` の `at_line_start`、`Details` の `in_code` | 名前付き引数の ON/OFF、真の2値トグル | しない方が 5 | このままでよい |

草稿から直したのは次の3点で、どれも照らし合わせて初めて見えたもの。

- 「どの構造を」に 2（2か所に分かれた1つの状態）を足した。草稿の 1 は「複数の変数」だけを見ていて、片方がすでに enum の場合を拾えなかった。router と `scan` の2件はどちらもこの形だった
- 「しない方が」の 9（旧 8）に、先に排他性を確かめるという但し書きを付けた。本文が router の `subtree` を見送った理由はこの項そのもので、但し書きがあれば判断が変わっていた
- 「しない方が」に 8（計算の中の番兵）を、state machine に 4（同じ遷移が2か所）を足した。前者は #162 で `Option` にした `nest_items` が中で `-1` に戻していることを、後者は `scan` の終端処理を読んで書いた
