stlc API

用途

stlc 包是基于共享命名语法的简单类型 lambda 演算:类型、带类型常量的签名、类型上下文、双向类型推断与检查、有步数上限的操作式范式化,以及到 β-范式、η-长形式的带类型求值范式化(NbE)。

项是 @syntax.Term[Atom]:Bind(x, b) 是 λx. b\lambda 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) 是未解释的基本类型,Unit 是单位类型,Arrow(a, b) 是函数类型 a→ba \to b。类型按结构进行比较(Ty::equal,即提升的 Eq 实现);对简单类型而言,这恰好就是类型相等。该实现是手写的而非派生的,以保证栈安全;其语义与派生实现相同。Atom::equal 同样按名字比较常量。

签名与上下文

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 的相应函数相同,遮蔽规则也相同:类型检查器进入 lambda 时会扩展上下文,因此同名变量由最近的绑定子决定。当它从同一空上下文扩展此前构造的最长上下文(类型检查器在嵌套 lambda 下正是如此)时,extend_with 的摊销时间为常数,因此在 nn 个绑定子下检查所需的上下文扩展总计为 O(n)O(n);扩展一个已经扩展过的上下文则会复制其条目。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 不在签名中。
CannotInferLambdalambda 出现在必须推断其类型的位置。
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 的结果类型。单独的 lambda 无法推断(CannotInferLambda)。直接应用于参数的 lambda (λx. b) a1⋯an(\lambda x.\,b)\,a_1 \cdots a_n 的推断方式是:先推断 a1a_1 的类型,再在 xx 具有该类型的前提下为 b a2⋯anb\,a_2 \cdots a_n 定型。若 xx 在 a2,…,ana_2, \dots, a_n 中自由出现,形参会先被改名为新名字,使这些参数保持它们在上下文中的类型。没有参数的应用,无论位于脊的根部还是嵌套在其头部,都会得到 EmptyApplication。

check

check 将项对照类型进行检验。

pub fn check(Signature, TypeContext, @syntax.Term[Atom], Ty) -> Result[Unit, TypeError]

lambda 对照箭头类型进行检查时,会以定义域作为参数的类型,将体对照陪域进行检查。直接作用于参数的 lambda,即 (λx. b) a1⋯an(\lambda x.\,b)\,a_1 \cdots a_n,按 infer 为其定型的方式检查,只是 b a2⋯anb\,a_2 \cdots a_n 对照期望类型进行检查,而不是被推断:a1a_1 的类型仍然被推断,形参也以同样的方式改名,使其与 a2,…,ana_2, \dots, a_n 不冲突。因此,结果为 lambda 的可约式,例如 (λx. λy. y) ()(\lambda x.\,\lambda y.\,y)\,(),可以对照箭头类型通过检查,作为函数的参数时也是如此。其他所有项都先推断类型,再用 == 比较;若不同则给出 TypeMismatch。交给 lambda 的参数(如 a1a_1)必须可推断:该位置上的 lambda 会给出 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)),
  )
}

结果为 lambda 的可约式会对照期望的箭头类型进行检查:

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]

在结果中,每个箭头类型的子项都是 lambda,每个应用的头部都是变量或常量。上下文中的变量和签名中的常量保持原样,并按其类型进行 η-展开。不需要步数上限:良类型的项总能范式化。新的绑定子名称为 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::extendSignature::extend_with
TypeContext::extendTypeContext::extend_with

本包中各类型上隐藏的方法形式 not_equal 和 to_repr 已弃用;请使用 != 和 Repr(x)。

Signature 和 TypeContext 的字段 entries 不再公开;请改用 lookup、length 和 to_array。