言語ツアー · 11

ツールと診断

Onsa は、書かれたコードをコンパイラが局所的・決定的に否定し、その結果をもとに直す流れを前提にしています。そのための診断の形と、onsa のコマンドを紹介します。

診断の形

これまでの章で見てきたとおり、Onsa の診断は位置・コード・文面に加えて、修正候補(fix)と補足(note)を持ちます。

scale.onsa:1:13: error[E0020]: `&mut T` is written `inout name: T`; the mode comes before the name
  fn scale(x: &mut F32, k: F32) {
              ^^^^
  fix: write `inout` before the name
    scale.onsa:1:10: insert `inout `
    scale.onsa:1:13: remove `&mut `
  note: there are no references: an argument is borrowed by default and changed with `inout` before it (§5.2)

修正候補は、どの範囲をどの文字列に置き換えるかという編集の並びで、機械がそのまま当てられます。読み方が二つに割れる誤りでは、候補を両方並べます(「概要と特徴」の w + 1 % 8 の例)。

診断の出し方には、次の約束があります。

  • 宣言ごとに一つ。 一つの宣言(関数、型など)の中では、最初の誤りで検査を止めます。宣言どうしは独立に検査し、全ての宣言の誤りを一度に報告します。一つの原因から偽の誤りが連鎖しないようにし、直す回数を減らすためです。
  • コードは安定している。 一つの種類の誤りに一つのコードを割り当て、直し方が同じものをまとめ、違うものを分けます。
  • 扱えないものは黙って通さない。 この版のコンパイラが扱えない機能は、機能の名前を添えた E0200 にします。誤った結果を出すことはしません。

他の言語の書き方を受け付けて、Onsa の書き方を示すのも診断の役目です。上の &mut のほか、<T>、経路の ::、;、i32 などが対象です。

first.onsa:1:13: error[E0020]: type parameters and type arguments are written in `[ ]`
  pub fn first<T: Copy>(a: T, b: T) -> T {
              ^^^^^^^^^
  fix: write the brackets `[ ]`
    first.onsa:1:13: replace `<` with `[`
    first.onsa:1:21: replace `>` with `]`
  note: type parameters and type arguments are written in `[ ]` (§4.5)

JSON の診断

--json を付けると、同じ診断を JSON で出力します。エディタや LLM のエージェントは、こちらを読みます。「flow」の章の、^ を書き忘れた one_pole の例です。

{
  "diagnostics": [
    {
      "code": "E0801",
      "message": "`y` is defined below; names are defined from the top, and a later `let` is read as `^y` in the first argument of `prev~` / `delay~` / `vdelay~` (§11.2)",
      "span": {
        "file": "one_pole.onsa",
        "line": 2,
        "col": 37,
        "end_line": 2,
        "end_col": 38
      },
      "found": "y",
      "fixes": [
        {
          "title": "read the past value with `^`",
          "edits": [
            {
              "span": {
                "file": "one_pole.onsa",
                "line": 2,
                "col": 37,
                "end_line": 2,
                "end_col": 37
              },
              "replace": "^"
            }
          ]
        }
      ],
      "notes": [
        {
          "message": "defined here",
          "span": {
            "file": "one_pole.onsa",
            "line": 2,
            "col": 3,
            "end_line": 2,
            "end_col": 39
          }
        }
      ]
    }
  ]
}
  • span は、1 から数える行と列の半開区間です。列は文字(Unicode のスカラー値)で数えます。
  • fixes の一つの候補は、説明(title)と編集の並び(edits)です。挿入は、空の範囲の置き換えで表します(上の例は ^ の挿入)。
  • 欄は将来足すことがあり、読み手は知らない欄を読み飛ばします。

診断コード

コードの範囲は、誤りの分類ごとに分かれています。

範囲 分類
E00xx 字句・構文・演算子の群
E02xx この版のコンパイラでは未対応の機能(E0200)
E03xx モジュール・名前解決・シャドーイング・循環
E04xx 型・引数の数・フィールド・リテラルの型
E05xx 網羅性・到達しない文と腕
E06xx エフェクト・Alloc・ターゲットが与えるエフェクト
E07xx 引数モード・排他性・Affine・第二級の値
E08xx flow(順序と因果性・レート・遅延・@param・~)
E09xx rt
E10xx FFI・unsafe・変換
E11xx マニフェスト(onsa.toml)

onsa explain は、コードの説明と直し方の例を出します(説明はまだ一部のコードにだけ書かれています)。次は出力の冒頭です。

$ onsa explain E0811
# E0811: a flow call or a `par` that holds state needs `~`, and nothing with state stands where it is not evaluated every sample

Inside a flow body, `name~(args)` creates a stateful instance of the
flow `name`, while `name(args)` applies a stateless function point by
point (spec §2.6, §11.5). Calling a flow without `~` is an error so that
the two kinds of call never look the same.

型付きのホール

式の位置に _ を書くと、その位置に期待される型と、スコープの中で使える候補が報告されます(E0421)。書きかけのコードで「ここに何を置けばよいか」をコンパイラに尋ねる使い方です。

pub fn mix(a: F32, b: F32, gain: F32) -> F32 {
  let g = clamp_gain(gain)
  _
}

fn clamp_gain(g: F32) -> F32 {
  if g > 4.0 { 4.0 } else { g }
}
hole.onsa:3:3: error[E0421]: hole of type `F32`; candidates: a, b, gain, g
    _
    ^

ホールのあるプログラムはビルドできません。

Rust/C++ との比較

Rust の todo!() は検査を通して実行時に panic しますが、Onsa のホールは検査の段で止まり、型と候補を報告します。Haskell の typed holes と同じ考え方です。

onsa fmt

onsa fmt は、ソースを唯一の正規形に書き換えます。設定の項目はありません。

  • 空白、字下げ(2 空白)、数値のリテラルの綴り、空行の数を揃えます。
  • 書き手の改行(並びやメソッドの連鎖をどこで折るか)は保ち、行を自動で折り返しません。
  • プログラムの意味を変えず、二度かけても結果は同じです。
  • 構文の誤りがあるファイルは書き換えません。
const MAX_GAIN: F32 = 4.0E+0
const MASK: U32 = 0x_ff

pub fn mix(a: F32,b: F32,  gain: F32)->F32 {
  let g = if gain>MAX_GAIN { MAX_GAIN } else {gain}
  let sum = a*g + b*g


  return sum
}

onsa fmt の後:

const MAX_GAIN: F32 = 4.0e0
const MASK: U32 = 0xFF

pub fn mix(a: F32, b: F32, gain: F32) -> F32 {
  let g = if gain > MAX_GAIN { MAX_GAIN } else { gain }
  let sum = a * g + b * g

  sum
}

末尾の return sum は、意味を変えない余分な書き方なので sum になりました。仕様では、冗長な括弧、-> ()、空の uses {} も取り除くことになっていますが、この版の onsa fmt はまだ取り除きません。

onsa fmt --check は書き換えずに、書き換えが要るかだけを終了コードで返します。onsa diff --ast は二つのファイルの構文の木を比べ、fmt の書き換えだけの違いとコメントの違いは差分にしません。

Rust/C++ との比較

rustfmt や clang-format は設定ファイルで形を変えられますが、onsa fmt の形は一つです。どのプロジェクトのコードも同じ見た目になるので、人間にも LLM にも読みやすくなります。

コマンド

コマンド 内容 この版
onsa check [--json] 型・エフェクト・rt・flow の検査 ○
onsa fmt [--check] 唯一の表記への正規化 ○
onsa test [--json] [--filter <text>] test をインタプリタで実行 ○
onsa build --target <名前> マニフェストのターゲットをビルド ○(staticlib と C のソース)
onsa interface 公開するシグネチャ、種、大きさ、@param、flow の API ○
onsa graph <flow> flow の信号のグラフ(DOT、SVG) ○
onsa diff --ast 構文の木の差分 ○
onsa explain <code> 診断コードの説明 ○
onsa audit extern、unsafe、@fp(relaxed) の一覧、スタックの上限、flow の状態の大きさ 予定
onsa play <flow> flow を音で鳴らす。@param から UI を作る 予定
onsa probe <flow>.<name> 名前の付いた信号の波形とスペクトルを見る 予定
onsa primer 言語の要約と標準ライブラリのインタフェースを、LLM の文脈向けに出す 予定
onsa lsp エディタ向けの言語サーバ 予定

onsa graph は、flow の信号のグラフを DOT で出します。ノードの名前は let の名前で、帰還の辺は点線で描かれます。

$ onsa graph one_pole filters.onsa
digraph "one_pole" {
  rankdir=LR
  node [shape=box fontname="monospace"]
  "x" [label="x: F32 at sample" shape=ellipse color="black" fontcolor="black"]
  "p" [label="p: F32 at block" shape=ellipse color="blue" fontcolor="blue"]
  "y" [label="y: F32 at sample" color="black" fontcolor="black"]
  "_out" [label="out: F32 at sample" shape=doubleoctagon color="black" fontcolor="black"]
  "y.prev_0" [label="prev_0 = prev~: F32 at sample" style=rounded color="black" fontcolor="black"]
  "p" -> "y"
  "x" -> "y"
  "y.prev_0" -> "y"
  "y" -> "y.prev_0" [style=dashed]
  "y" -> "_out"
}

修復のループ

Onsa の診断とコマンドは、次のループを速く、確実に回すために設計されています。

  1. 書く。 LLM が、言語の要約(onsa primer、予定)を文脈に入れてコードを書きます。
  2. 検査する。 onsa check --json を実行します。誤りは宣言ごとに一つずつ、全ての宣言の分がまとめて返ります。
  3. 直す。 修正候補があればそのまま当てます。何を書けばよいか分からない位置には _ を置き、型と候補を尋ねます。
  4. 確かめる。 onsa test でテストを走らせ、onsa fmt で表記を揃えます。
  5. 監査する。 人間は onsa interface で公開するシグネチャ、エフェクト、状態の大きさを読みます。unsafe や @fp(relaxed) のように人間の判断が要る箇所は、onsa audit(予定)で一覧にします。

このループが収束しやすいのは、言語の側にも理由があります。シグネチャを全て注釈するので誤りが関数の中で閉じ(局所性)、書き方が一つなので候補が一つに決まり(一意性)、同じ入力には同じ診断が出ます(決定性)。