このページは 98% 翻訳済みです。翻訳のない部分は英語で表示されます。 翻訳に協力する
stlc API
目的
stlc パッケージは、共有の名前付き構文上の単純型付きラムダ計算である。型、型付き定数のシグネチャ、型文脈、双方向の型推論と型検査、ステップ数に上限のある操作的正規化、そして β 正規形・η 長形式への型付き評価による正規化(NbE)を提供する。
項は @syntax.Term[Atom] である。Bind(x, b) は (型注釈なし)、Apply は適用、Variable は変数であり、Value は Atom を保持する。型付け規則と NbE アルゴリズムは stlc の設計に記載されている。
このパッケージのすべての関数は、型に対する == も含め、項と型の入れ子の深さに関してスタックセーフである。型検査、評価、読み戻しは、保留中の処理をヒープ配列に保持するループとして動作し、ホストスタックを一定量だけ使う。どのバックエンドでも、項は束縛子、引数位置、カリー化されたスパイン、入れ子の簡約基を含めて 100 000 階層まで、型は余域または定義域で同じ深さまで扱える。そのような項、型、エラーの Debug はスタックセーフではない。
インポート
このパッケージと、そのシグネチャに型が現れるパッケージを moon.pkg に追加する:
import {
"Luna-Flow/type_theory/core",
"Luna-Flow/type_theory/syntax",
"Luna-Flow/type_theory/rewrite",
"Luna-Flow/type_theory/stlc",
}
このページの例では、すべての名前をパッケージの別名を通して参照する。たとえば @core.Name である。
構文
Atom, Atom::equal
Atom はこの計算体系の定数である。
pub(all) enum Atom {
UnitLit
Const(@core.Name)
} derive(Eq, @debug.Debug)
pub fn Atom::equal(Self, Self) -> Bool
UnitLit は単位値 である。Const(c) は型が Signature で宣言された定数である。
Term
Term は STLC の項の型である。
pub type Term = @syntax.Term[Atom]
これは別名なので、syntax、substitution、rewrite のすべてが STLC の項に適用できる。
Ty, Ty::equal
Ty は単純型である。
pub(all) enum Ty {
Base(@core.Name)
Unit
Arrow(Ty, Ty)
} derive(@debug.Debug)
pub impl Eq for Ty
pub fn Ty::equal(Self, Self) -> Bool
Base(b) is an uninterpreted base type, Unit the unit type, and
Arrow(a, b) the function type . Types are compared structurally
(Ty::equal, the promoted Eq implementation); for simple types this is
exactly type equality. The implementation is written by hand rather than
derived so that it is stack-safe; it has the semantics of the derived one. Atom::equal likewise compares constants by name.
シグネチャと文脈
Signature, Signature::empty, Signature::extend_with, Signature::lookup, Signature::length, Signature::to_array, Signature::equal
Signature は定数に型を割り当てる。
type Signature derive(Eq, @debug.Debug)
pub fn Signature::empty() -> Self
#alias(extend, deprecated)
pub fn Signature::extend_with(Self, @core.Name, Ty) -> Self
pub fn Signature::lookup(Self, @core.Name) -> Ty?
pub fn Signature::length(Self) -> Int
pub fn Signature::to_array(Self) -> Array[(@core.Name, Ty)]
pub fn Signature::equal(Self, Self) -> Bool
この型は抽象型であり、シグネチャは empty と extend_with でのみ作られ、作った後は変更できない。empty() は定数を持たない。extend_with(c, ty) は c : ty を追加した新しいシグネチャを返す。同じ名前に対する後の項目は前の項目を隠し、lookup は最新のもの、または None を返す。length は隠された項目も含めて項目を数える。to_array は項目を挿入順に並べた新しい配列を返すので、それを変更してもシグネチャは変わらない。equal は項目のリストを比較する。
TypeContext, TypeContext::empty, TypeContext::extend_with, TypeContext::lookup, TypeContext::length, TypeContext::to_array, TypeContext::equal
TypeContext は自由変数に型を割り当てる。
type TypeContext
pub impl Eq for TypeContext
pub impl @debug.Debug for TypeContext
pub fn TypeContext::empty() -> Self
#alias(extend, deprecated)
pub fn TypeContext::extend_with(Self, @core.Name, Ty) -> Self
pub fn TypeContext::lookup(Self, @core.Name) -> Ty?
pub fn TypeContext::length(Self) -> Int
pub fn TypeContext::to_array(Self) -> Array[(@core.Name, Ty)]
pub fn TypeContext::equal(Self, Self) -> Bool
関数の振る舞いは Signature のものと同じで、シャドーイング規則も共通する。型検査器はラムダに入るときに文脈を拡張するため、最も近い束縛子がその名前に対して有効になる。検査器が入れ子のラムダの下で行うように、同じ空文脈からこれまでに作られた最長の文脈を拡張する場合、extend_with は償却定数時間で動作する。そのため、 個の束縛子の下での検査では拡張のコストは となる。すでに拡張済みの文脈をさらに拡張すると、項目がコピーされる。Eq と Debug は手書きであり、従来どおり挿入順に項目を比較・表示する。
test "signatures and contexts" {
let c = @core.Name::new("c")
let x = @core.Name::new("x")
let a = @stlc.Ty::Base(@core.Name::new("A"))
let sig = @stlc.Signature::empty().extend_with(c, @stlc.Ty::Arrow(a, a))
let ctx = @stlc.TypeContext::empty().extend_with(x, a).extend_with(x, @stlc.Ty::Unit)
assert_eq(sig.lookup(c), Some(@stlc.Ty::Arrow(a, a)))
assert_eq(ctx.lookup(x), Some(@stlc.Ty::Unit))
assert_eq(ctx.length(), 2)
let entries = ctx.to_array()
entries.push((x, a))
assert_eq(ctx.length(), 2)
assert_eq(ctx.lookup(x), Some(@stlc.Ty::Unit))
}
エラー
TypeError, TypeError::equal
TypeError は項が拒否された理由を報告する。
pub(all) enum TypeError {
UnboundVariable(@core.Name)
UnknownConstant(@core.Name)
CannotInferLambda
ExpectedFunction(Ty)
TypeMismatch(expected~ : Ty, actual~ : Ty)
EmptyApplication
ScopeError(@debruijn.ScopeError)
NormalizationError(message~ : String)
} derive(Eq, @debug.Debug)
pub fn TypeError::equal(Self, Self) -> Bool
| ケース | 意味 |
|---|---|
UnboundVariable(x) | x が文脈にない。 |
UnknownConstant(c) | c がシグネチャにない。 |
CannotInferLambda | 型を推論しなければならない位置にラムダが現れた。 |
ExpectedFunction(ty) | 関数型でない型 ty の項が適用された。 |
TypeMismatch(expected, actual) | 推論された型が期待される型と異なる。 |
EmptyApplication | 適用ノード Apply(head, []) に引数がない。 |
ScopeError(e) | de Bruijn のスコープ失敗のために予約されている。現在の関数はこれを生成しない。 |
NormalizationError(message) | 型付き NbE の内部不変条件が破れた。検査済みの入力では起こらないはずである。 |
型検査
infer
infer は項の型を合成する。
pub fn infer(Signature, TypeContext, @syntax.Term[Atom]) -> Result[Ty, TypeError]
単位リテラルの型は Unit であり、定数と変数は宣言された型を持つ。適用 f a_1 … a_n は、各引数を対応する定義域に対して検査した後の f の結果型を持つ。単独のラムダは推論できない(CannotInferLambda)。引数に直接適用されたラムダ は、 の型を推論し、 にその型を与えて を型付けすることで推論される。 が に自由に現れる場合は、まずパラメータを新しい名前に替えるので、それらの引数は文脈における型を保つ。引数のない適用は、スパインの根にあっても先頭に入れ子になっていても EmptyApplication になる。
check
check は項を型に対して検査する。
pub fn check(Signature, TypeContext, @syntax.Term[Atom], Ty) -> Result[Unit, TypeError]
ラムダは矢印型に対して、パラメータに定義域を与えたうえで本体を値域に対して検査することで検査される。引数に直接適用されたラムダ は infer が型付けするのと同じように検査されるが、 は推論されるのではなく期待される型に対して検査される。 の型はやはり推論され、パラメータも同じように と衝突しない名前に替えられる。したがって のように結果がラムダである簡約基は、関数の引数であっても矢印型に対して検査に通る。それ以外の項はすべて型を推論し == で比較する。異なれば TypeMismatch となる。 のようにラムダに渡される引数は推論可能でなければならない。そこにラムダがあると CannotInferLambda となる。
test "infer and check" {
let x = @core.Name::new("x")
let f = @core.Name::new("f")
let a = @stlc.Ty::Base(@core.Name::new("A"))
let id : @stlc.Term = Bind(x, Variable(x))
let sig = @stlc.Signature::empty()
let ctx = @stlc.TypeContext::empty()
assert_eq(@stlc.check(sig, ctx, id, @stlc.Ty::Arrow(a, a)), Ok(()))
assert_eq(@stlc.infer(sig, ctx, id), Err(@stlc.TypeError::CannotInferLambda))
let ctx_f = ctx.extend_with(f, @stlc.Ty::Arrow(a, a))
let bad : @stlc.Term = Apply(Variable(f), [Value(@stlc.Atom::UnitLit)])
assert_eq(
@stlc.infer(sig, ctx_f, bad),
Err(@stlc.TypeError::TypeMismatch(expected=a, actual=@stlc.Ty::Unit)),
)
}
結果がラムダである簡約基は、期待される矢印型に対して検査される:
test "check a redex that returns a lambda" {
let x = @core.Name::new("x")
let y = @core.Name::new("y")
let f = @core.Name::new("f")
let a = @stlc.Ty::Base(@core.Name::new("A"))
let sig = @stlc.Signature::empty()
let ctx = @stlc.TypeContext::empty()
// (λx. λy. y) ()
let redex : @stlc.Term = Apply(Bind(x, Bind(y, Variable(y))), [
Value(@stlc.Atom::UnitLit),
])
let unit_to_unit = @stlc.Ty::Arrow(@stlc.Ty::Unit, @stlc.Ty::Unit)
assert_eq(@stlc.check(sig, ctx, redex, unit_to_unit), Ok(()))
assert_eq(@stlc.infer(sig, ctx, redex), Err(@stlc.TypeError::CannotInferLambda))
// f ((λx. λy. y) ()) with f : (A -> A) -> A
let ctx_f = ctx.extend_with(
f,
@stlc.Ty::Arrow(@stlc.Ty::Arrow(a, a), a),
)
assert_eq(@stlc.infer(sig, ctx_f, Apply(Variable(f), [redex])), Ok(a))
}
簡約基の後続の引数は、そのパラメータの下ではなく、簡約基の文脈で型付けされる:
test "trailing redex arguments keep their own types" {
let x = @core.Name::new("x")
let y = @core.Name::new("y")
let b = @stlc.Ty::Base(@core.Name::new("B"))
let sig = @stlc.Signature::empty()
let ctx = @stlc.TypeContext::empty().extend_with(x, b)
// (λx. λy. y) () x, where the last x is the x : B of the context
let term : @stlc.Term = Apply(Bind(x, Bind(y, Variable(y))), [
Value(@stlc.Atom::UnitLit),
Variable(x),
])
assert_eq(@stlc.infer(sig, ctx, term), Ok(b))
assert_eq(
@stlc.check(sig, ctx, term, @stlc.Ty::Unit),
Err(@stlc.TypeError::TypeMismatch(expected=@stlc.Ty::Unit, actual=b)),
)
}
正規化
normalize_checked
normalize_checked は項を型に対して検査し、その後、型なしの βη 簡約器で正規化する。
pub fn normalize_checked(Signature, TypeContext, @syntax.Term[Atom], Ty, Int) -> Result[@rewrite.NormalizationResult[Atom], TypeError]
型エラーの場合は簡約せずに Err を返す。そうでなければ Ok(@lambda.normalize(term, max_steps)) を返す。これはステップ上限付きの正規順序 βη 簡約である。その正規形は β 正規かつ η 短形式である(単項適用について。@lambda.eta_rule を参照)。よく型付けされた項はすべて強正規化可能なので、max_steps を十分大きくすれば必ず NormalForm が得られる。
normalize_eta_long
normalize_eta_long は項を型に対して検査し、型付きの評価による正規化で beta 正規形かつ eta 長形を返す。検査で非公開の型付き実行計画を構築するため、評価とクロージャ適用は確定済みの型を再利用し、元の部分項を再検査・再推論しない。計画構築は check が報告する最初のエラーを保つ。公開の項表現は変わらない。公開 check と infer は同じ計画構築機械を使って結果の計画を破棄するため、成功した型付け訪問数に比例する一時的な計画領域が加わる。
pub fn normalize_eta_long(Signature, TypeContext, @syntax.Term[Atom], Ty) -> Result[@syntax.Term[Atom], TypeError]
結果において、矢印型の部分項はすべてラムダであり、すべての適用は頭部に変数または定数を持つ。文脈の変数とシグネチャの定数はそのまま保たれ、それぞれの型に従って η 展開される。ステップ上限は不要である。型の付く項は常に正規化されるからである。新しい束縛子の名前は x、x_1、… であり、項と文脈のすべての名前を避けるように選ばれる。
test "beta-normal eta-long form" {
let f = @core.Name::new("f")
let x = @core.Name::new("x")
let a = @stlc.Ty::Base(@core.Name::new("A"))
let ctx = @stlc.TypeContext::empty().extend_with(f, @stlc.Ty::Arrow(a, a))
let sig = @stlc.Signature::empty()
// f is eta-expanded to λx. f x
let expected : @stlc.Term = Bind(x, Apply(Variable(f), [Variable(x)]))
match @stlc.normalize_eta_long(sig, ctx, Variable(f), @stlc.Ty::Arrow(a, a)) {
Ok(normal) => assert_true(@syntax.alpha_equal(normal, expected))
Err(_) => fail("well typed")
}
// the operational normalizer contracts the redex but does not expand
let redex : @stlc.Term = Apply(Bind(x, Variable(x)), [Variable(f)])
assert_eq(
@stlc.normalize_checked(sig, ctx, redex, @stlc.Ty::Arrow(a, a), 10),
Ok(NormalForm(term=Variable(f), steps=1)),
)
}
非推奨
| 非推奨 | 代替 |
|---|---|
Signature::extend | Signature::extend_with |
TypeContext::extend | TypeContext::extend_with |
このパッケージの型にある隠されたメソッド形式 not_equal と to_repr は非推奨である。!= と Repr(x) を使うこと。
Signature と TypeContext のフィールド entries は公開されなくなった。代わりに lookup、length、to_array を使う。