言語ツアー · 03

値と引数モード

Onsa の値は、代入するとコピーされる「値」として振る舞います。参照を値として持たないのでライフタイムは無く、関数への渡し方は借用・inout・move の三つです。

この章の例のうち use の無いものは、その前の例と同じモジュールに置いたものです。

束縛: let と var

let は変更できない束縛、var は変更できる束縛です。var はローカルにだけ書けます。

pub struct Point {
  x: F32,
  y: F32,
}

test "assignment copies the value" {
  let a = Point { x: 1.0, y: 2.0 }
  var b = a
  b.x = 10.0
  assert a.x == 1.0 && b.x == 10.0
}

代入は 値 の代入です。var b = a の後で b を変えても、a は変わりません。参照は値として存在しないので、ライフタイムもありません。

let の束縛に代入すると、var に直す修正候補の付いた誤りになります。

assign_let.onsa:3:3: error[E0701]: cannot assign to this place: `total` is immutable (`let`); declare it with `var` (§5.2)
    total = total + 1
    ^^^^^
  fix: change `let` to `var`
    assign_let.onsa:2:3: replace `let` with `var`
  note: assign_let.onsa:2:7: declared here

シャドーイングは無い

ある名前の束縛が見えている間は、同じ名前を束縛し直せません。一つの名前は、見えている範囲で常に一つのものを指します。並んだ別々のスコープ(二つの for など)では、同じ名前を使えます。

shadow.onsa:2:7: error[E0304]: `x` is already bound and visible here; Onsa has no shadowing (§5.1)
    let x = x + 1
        ^
  note: shadow.onsa:1:6: first bound here

使わない束縛も誤りです。値を捨てるときは _ で明示します(let _ = e、for _ in 0 ..< n)。

unused.onsa:2:7: error[E0309]: `b` is bound and never read; a value that is not used is bound to `_` (§5.1)
    let b = a * 2
        ^
  fix: rename to `_`
    unused.onsa:2:7: replace `b` with `_`

Rust/C++ との比較

Rust の let mut は var です。Rust でよく使う let x = x + 1 のようなシャドーイングは書けず、別の名前を付けます。使わない変数は、Rust では警告ですが Onsa では誤りです。

引数モード

関数の引数の渡し方は三つです。渡し方は宣言にも、呼び出す側にも書きます。

モード 宣言 呼び出し 意味
借用(既定) x: T f(x) 読むだけ。呼び出しの間は変わらない
inout inout x: T f(inout x) 呼び出し側の値を書き換える
move move x: T f(move x) 所有権を受け取る
/// 借用(既定): 読むだけ
pub fn norm2(p: Point) -> F32 {
  p.x * p.x + p.y * p.y
}

/// inout: 呼び出し側の値を書き換える
pub fn scale(inout p: Point, k: F32) {
  p.x = p.x * k
  p.y = p.y * k
}

/// move: 所有権を受け取る
pub fn total(move b: Buf[F32]) -> F32 uses {Alloc} {
  var s: F32 = 0.0
  for v in b {
    s = s + v
  }
  s
}

test "argument modes" {
  var p = Point { x: 3.0, y: 4.0 }
  scale(inout p, 2.0)
  assert norm2(p) == 100.0

  var b: Buf[F32] = Buf.zeroed(4)
  b[0] = 1.5
  assert total(move b) == 1.5
}

呼び出す側の印は省けません。書き忘れると、印を足す修正候補の付いた誤りになります。呼び出しの行を読むだけで、どの値が書き換わり、どの値が手放されるかが分かります。

no_mark.onsa:13:9: error[E0703]: this parameter is `inout`; write `inout` before the argument (§5.2)
    scale(q, 2.0)
          ^
  fix: add `inout`
    no_mark.onsa:13:9: insert `inout `

total に uses {Alloc} が付いているのは、所有した Buf を関数の終わりで破棄する(ヒープを解放する)からです。ヒープの確保と解放はエフェクトとしてシグネチャに出ます(「エフェクトと handler」の章)。

Rust/C++ との比較

借用・inout・move は、Rust の &T・&mut T・値渡し、C++ の const T&・T&・T&& に近いものです。ただし参照は引数の位置にだけ現れ、呼び出しが終われば消えるので、ライフタイムの注釈は要りません。

排他性

inout で渡した場所は、その呼び出しの間、他の引数から見えてはいけません。同じ変数を inout と借用の両方に渡すと誤りです。

overlap.onsa:8:22: error[E0702]: `xs` is passed as `inout` and borrowed in the same call; the places may overlap (§5.2)
    add_into(inout xs, xs)
                       ^^
  note: overlap.onsa:8:18: `inout` here

同じ値の 異なるフィールド は重ならないものとして扱うので、そのまま渡せます。

pub struct Mixer {
  bus: [F32; 4],
  send: [F32; 4],
}

pub fn add_into(inout dst: [F32; 4], src: [F32; 4]) {
  for i in 0 ..< 4 {
    dst[i] = dst[i] + src[i]
  }
}

pub fn mix_send(inout m: Mixer) {
  add_into(inout m.bus, m.send) // 別のフィールドなので重ならない
}

test "fields do not overlap" {
  var m = Mixer { bus: [1.0; 4], send: [0.5; 4] }
  mix_send(inout m)
  assert m.bus[0] == 1.5
}

同じ配列の要素どうし(xs[i] と xs[j])は、添字が等しいかを静的に判定しないので、重なるものとして扱います。

Affine の値を移す

Buf のような Affine の値(「型」の章)は複製できず、移すことしかできません。値を消費する位置(move の引数、let の初期化など)では move と書きます。

copy_buf.onsa:3:11: error[E0711]: Affine value `a` is consumed here; write `move a` (§5.2)
    let b = a
            ^
  fix: add `move`
    copy_buf.onsa:3:11: insert `move `

移した後の変数は使えません。

after_move.onsa:12:18: error[E0704]: `b` was moved and cannot be used again (§5.2)
    t + total(move b)
                   ^
  note: after_move.onsa:11:22: moved here

関数の返り値として返すときは、move を書きません。値が関数の外へ出ることは、書かなくても見えるからです。

Rust/C++ との比較

Rust では let b = a; だけで移動しますが、Onsa では move と書いて、移動を見える形にします。C++ の std::move と違い、移した後の値を使うとコンパイル時に誤りになります。

受け手を書き換えるメソッド: !

inout self のメソッドは、名前の直後に ! を付けて呼びます。

pub struct Counter {
  n: U32,
}

impl Counter {
  pub fn get(self) -> U32 {
    self.n
  }

  pub fn bump(inout self) {
    self.n = self.n + 1
  }
}

test "methods that change the receiver" {
  var c = Counter { n: 0 }
  c.bump!()
  c.bump!()
  assert c.get() == 2
}

! を書き忘れると、! を足す修正候補の付いた誤りになります。受け手は var などの書き換えられる場所でなければなりません。

no_bang.onsa:12:3: error[E0713]: this method takes `inout self`: write `!` after its name (§5.2)
    c.bump()
    ^^^^^^^^
  fix: add `!`
    no_bang.onsa:12:9: insert `!`

第二級の値: 借用・Span・捕捉するクロージャ

次のものは 引数の位置にだけ 現れます。返り値や struct のフィールドにはできません。そのため、どれもヒープを使わず、ライフタイムも要りません。

  • 借用の引数
  • Span[T](連続した要素を指すビュー)
  • 外側の値を捕捉する無名関数

Span[T] には、固定長配列、Buf、その一部(xs.slice(from, to))をそのまま渡せます。

/// 最大の絶対値を求める。配列でも Buf でも、その一部でも受け取れる
pub rt fn peak(xs: Span[F32]) -> F32 {
  var m: F32 = 0.0
  for v in xs {
    let a = if v < 0.0 { -v } else { v }
    if a > m {
      m = a
    }
  }
  m
}

pub rt fn silence(inout xs: Span[F32]) {
  xs.fill!(0.0)
}

test "span" {
  var frame: [F32; 4] = [0.5, -2.0, 1.0, 0.25]
  assert peak(frame) == 2.0
  assert peak(frame.slice(2, 4)) == 1.0
  silence(inout frame)
  assert peak(frame) == 0.0
  let b: Buf[F32] = Buf.zeroed(8)
  assert peak(b) == 0.0
}

Span を返り値やフィールドにすると誤りです。

span_return.onsa:1:31: error[E0710]: `Span[F32]` is second-class: it is only the type of an argument, not of a field, a return value, a constant or a part of another type (§5.3)
  pub fn head(xs: Span[F32]) -> Span[F32] {
                                ^^^^^^^^^

外側の値を捕捉する無名関数も、引数の位置にだけ書けます。捕捉した値はコピーで、読み取り専用です。

use std.array

pub fn ramp(k: F32) -> [F32; 4] {
  array.from_fn(fn(i) { k * F32.round_from(i) })
}

test "closure in argument position" {
  let r = ramp(0.5)
  assert r[3] == 1.5
}

let に束縛すると誤りになります。捕捉の無い関数値(名前付きの関数など)は普通の値で、保存も返却もできます。

closure_let.onsa:2:11: error[E0710]: this value is second-class, an anonymous function that captures: it stands at an argument only and cannot be stored (§5.3)
    let f = fn(v: F32) -> F32 { k * v }
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^

Rust/C++ との比較

Span[T] は C++20 の std::span や Rust のスライス &[T] に当たります。Rust ではスライスを返したり struct に持たせたりするとライフタイムの注釈が要りますが、Onsa ではそもそも書けないので、注釈も借用検査器も要りません。その代わり、書ける形が限られます。

借用束縛

let の束縛が借用か所有かは、初期化の式の形で決まります。本体での使い方には依存しません。

初期化の形 束縛
借用の引数とその一部(let h = xs.slice(a, b)、let y = p.x) 借用(元の値を指す)
呼び出しの結果(let y = f(...))、let y = move x、var 所有
for v in xs 借用で反復する
for v in move xs xs を消費して反復する
pub rt fn first_half_sum(xs: Span[F32]) -> F32 {
  let h = xs.slice(0, xs.len() / 2) // 借用束縛: xs の一部を指す
  var s: F32 = 0.0
  for v in h {
    s = s + v
  }
  s
}

借用束縛は元の値を指すだけで、破棄されません。所有する束縛は、スコープの終わりで破棄されます(ヒープを持つ値なら Alloc が要ります)。