目录
正在加载目录…
正在阅读专栏 Essentials of Compilation 专栏 第 12 篇 · 共 13 篇 · 92%

Essentials of Compilation:参数多态

发布于 2026-09-16 22:17 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 5,417 · 预计阅读 11 分钟 👁 18 次阅读

Essentials of Compilation:参数多态

[!abstract] 译注 本笔记对应《Essentials of Compilation》Racket 版第 11 章 Parametric Polymorphism。All、Inst、Poly、type variable 和 compiler pass 名称保留原文,以避免把语言构造与普通中文概念混淆。

TL;DR

参数多态(parametric polymorphism,也称 generics)让函数和数据结构可以参数化于它们操作的类型。本文以 All 表示全称类型,以类型变量表示抽象类型;type checker 在调用处通过实参类型推导类型参数,并生成 Inst。编译时采用 mixed representation:把类型变量擦除为 Any,再在实例化边界插入 Cast,从而复用渐进式类型章节已经实现的机制。

[!note] 版本说明 源材料中的 Python edition 在本章标记为 UNDER CONSTRUCTION;下面的完整内容对应可用的 Racket edition。

目录

    1. 参数多态
    1. 语法与 first-class polymorphism
    1. 类型检查
    1. 编译参数多态
    1. 类型擦除
    1. 编译流水线

1. 参数多态

本章研究如何编译 Typed Racket 的 LangPoly 子集。参数多态通过让函数和数据结构参数化于其操作的类型,提高代码复用性。

例如,map 可以处理任意类型的二元 tuple:

racket
(: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
(define (map f v)
  (vector (f (vector-ref v 0)) (f (vector-ref v 1))))

(define (inc [x : Integer]) : Integer (+ x 1))

(vector-ref (map inc (vector 0 41)) 1)

map 的类型是:

text
(All (a) ((a -> a) (Vector a a) -> (Vector a a)))

它可以在 a = Integer 时处理整数 tuple,也可以在 a = Boolean 时处理 Boolean tuple。

2. 语法与 first-class polymorphism

2.1 类型声明

LangPoly 在 define 之外增加一种函数定义形式:类型声明位于 define 之前。

text
Type ::= (All (Var ...) Type) | Var
Def  ::= (: Var Type)
      | (define (Var Var ...) Exp)

在 abstract syntax 中,普通 Def 的返回类型仍暂时写作 Any,但有类型声明时,应以声明中的返回类型为准。类型声明使函数能够使用 All 类型,也使 type variable 合法。

text
Type ::= (All (Var ...) Type) | Var
Def  ::= Decl(Var, Type)
      | Def(Var, Var..., Any, '(), Exp)

2.2 First-class polymorphism

由于 polymorphic type 属于 Type,它可以递归地出现在 function type 内部。因此 LangPoly 支持 first-class polymorphism:多态函数可以作为参数传给另一个函数。

racket
(: apply-twice ((All (b) (b -> b)) -> Integer))
(define (apply-twice f)
  (if (f #t) (f 42) (f 777)))

(: id (All (a) (a -> a)))
(define (id x) x)

(apply-twice id)

这里 id 在同一个 apply-twice 调用内部可以分别实例化为 Boolean identity 与 Integer identity。许多语言只支持 second-class polymorphism;本章的 All 作为普通 Type,因此选择了 first-class polymorphism。

具体来说,apply-twice 的 parameter f 的 type 是 (All (b) (b -> b))。第一次 application (f #t) 令 match-types 推导 b = Boolean,得到一个返回 Boolean 的实例;第二次 application (f 42) 则重新建立推导环境,得到 b = Integer。两次 application 共享同一个 polymorphic value,却各自生成独立的 Inst node;type variable 的 substitution 不会泄漏到另一次 application。

3. 类型检查

相比 LangLam,LangPoly 的 type checker 主要增加三项职责。

3.1 多态函数调用与类型参数推导

若 operator expression 的类型是普通 function type,调用规则与之前相同。若它是:

text
(All (a ...) (T1 ... -> Tret))

type checker 会把每个 parameter type 与对应 argument type 进行匹配,推导类型参数。辅助函数 match-types 递归检查:

  • primitive type 必须相等;
  • Vector 与 function type 递归匹配各个组成类型;
  • 左侧第一次遇到 type variable 时,把它绑定到右侧对应类型;
  • 再次遇到同一变量时,必须与此前推导出的类型相等;
  • 嵌套 All 时,为内层变量建立新的映射环境。

推导结束后,operator expression 被包在 Inst AST 节点中。Inst 记录原始 polymorphic type 和推导出的 type arguments;调用的返回类型则通过 subst-type 将 type variables 替换为这些实参类型。

例如,map inc (vector 0 41) 的 a 被推导为 Integer:

racket
((inst map
       (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
       (Integer))
 inc (vector 0 41))

type checker 的完整输出会把 declaration 与 definition 合并为 Poly,并在调用处显式保留 Inst:

racket
(poly (a)
  (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
    (vector (f (vector-ref v 0))
            (f (vector-ref v 1)))))

(define (inc [x : Integer]) : Integer (+ x 1))

(vector-ref
 ((inst map
        (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
        (Integer))
  inc (vector 0 41))
 1)

3.2 比较 polymorphic type

两个 polymorphic type 即使文字形式不同,也可能是同一个类型:

text
(All (a) (a -> a))
(All (b) (b -> b))

type-equal? 不能直接比较变量名;它会先把第一个类型的绑定变量重命名,使之与第二个类型的变量对应,再递归比较类型体。这是一种 alpha-equivalence 判断。

racket
(define/override (type-equal? t1 t2)
  (match* (t1 t2)
    [(`(All ,xs ,T1) `(All ,ys ,T2))
     (define env (map cons xs ys))
     (type-equal? (subst-type env T1) T2)]
    [(other wise)
     (super type-equal? t1 t2)]))

3.3 Well-formed type

类型注解中只能出现已经定义的 type variable。check-well-formed 递归检查 primitive、Vector、function type 和 All:进入 All 时将其绑定变量加入环境;遇到未绑定的 symbol 则报告错误。

racket
(define/public ((check-well-formed env) ty)
  (match ty
    ['Integer (void)]
    ['Boolean (void)]
    ['Void (void)]
    [(? symbol? a)
     (match (dict-ref env a (lambda () #f))
       ['Type (void)]
       [else (error 'type-check "undefined type variable ~a" a)])]
    [`(Vector ,ts ...)
     (for ([t ts]) ((check-well-formed env) t))]
    [`(,ts ... -> ,t)
     (for ([t ts]) ((check-well-formed env) t))
     ((check-well-formed env) t)]
    [`(All ,xs ,t)
     (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
     ((check-well-formed env^) t)]
    [else (error 'type-check "unrecognized type ~a" ty)]))

3.4 LangInst

type checker 将 type declaration 和 polymorphic function 合并成 Poly definition,使下一个 compiler pass 更容易处理。输出语言 LangInst 新增:

text
Exp ::= ... | (Inst Exp Type (Type ...))
Def ::= ...
      | (Poly (Var ...) Def)

Poly 保存类型参数列表与函数定义;Inst 保存实例化时的具体 type arguments。

3.5 match-types 与 subst-type

match-types 维护 type variable 到具体类型的环境:

racket
[(? symbol? x) at]
  (match (dict-ref env x (lambda () #f))
    [#f (error 'type-check "undefined type variable ~a" x)]
    ['Type (cons (cons x at) env)]
    [t^ (check-type-equal? at t^ 'matching) env])]

subst-type 递归替换类型变量。进入 All 时要把变量映射到自身,避免替换穿透绑定作用域:

racket
[`(All ,xs ,t)
 `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
[(? symbol? x) (dict-ref env x)]

match-types 的完整递归骨架如下。它只允许 parameter type 中的 type variable 被绑定;当同一个变量再次出现时,必须与已经推导出的 type 相等:

racket
(define/public (match-types env pt at)
  (match* (pt at)
    [('Integer 'Integer) env]
    [('Boolean 'Boolean) env]
    [('Void 'Void) env]
    [('Any 'Any) env]
    [(`(Vector ,pts ...) `(Vector ,ats ...))
     (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
       (match-types env^ pt1 at1))]
    [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
     (define env^ (match-types env prt art))
     (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
       (match-types env^^ pt1 at1))]
    [(`(All ,pxs ,pt1) `(All ,axs ,at1))
     (define env^ (append (map cons pxs axs) env))
     (match-types env^ pt1 at1)]
    [((? symbol? x) at)
     (match (dict-ref env x (lambda () #f))
       [#f (error 'type-check "undefined type variable ~a" x)]
       ['Type (cons (cons x at) env)]
       [t^ (check-type-equal? at t^ 'matching) env])]
    [(other wise)
     (error 'type-check "mismatch ~a != ~a" pt at)]))

对应的 subst-type 需要注意 All 的 shadowing:进入绑定类型变量的 scope 后,把每个变量映射到自身,防止外部 substitution 意外穿透内层 binder:

racket
(define/public (subst-type env t)
  (match t
    ['Integer 'Integer]
    ['Boolean 'Boolean]
    ['Void 'Void]
    ['Any 'Any]
    [`(Vector ,ts ...)
     `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
    [`(,ts ... -> ,rt)
     `(,@(for/list ([t ts]) (subst-type env t))
       -> ,(subst-type env rt))]
    [`(All ,xs ,t)
     `(All ,xs
           ,(subst-type (append (map cons xs xs) env) t))]
    [(? symbol? x)
     (dict-ref env x (lambda () x))]
    [else (error 'subst-type "unrecognized type ~a" t)]))

type checker 还要合并相邻的 declaration 与 definition:声明为 All 时生成 Generic/Poly,普通函数类型则生成带完整参数类型的普通 Def。

源文中的 type-check-poly-class 负责把这些规则接入既有的 LangLam type checker。普通 function application 直接检查参数;遇到 All type 时,先为 bound type variables 建立 Type environment,再通过 match-types 推导 type arguments,最后生成 Inst:

racket
(define type-check-poly-class
  (class type-check-Llambda-class
    (super-new)
    (inherit check-type-equal?)

    (define/override (type-check-apply env e1 es)
      (define-values (e^ ty) ((type-check-exp env) e1))
      (define-values (es^ ty*)
        (for/lists (es^ ty*) ([e (in-list es)])
          ((type-check-exp env) e)))
      (match ty
        [`(,ty^* ... -> ,rt)
         (for ([arg-ty ty*] [param-ty ty^*])
           (check-type-equal? arg-ty param-ty (Apply e1 es)))
         (values e^ es^ rt)]
        [`(All ,xs (,tys ... -> ,rt))
         (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
         (define env^^
           (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
             (match-types env^^ param-ty arg-ty)))
         (define targs
           (for/list ([x xs])
             (match (dict-ref env^^ x (lambda () #f))
               [#f
                (error 'type-check
                       "type variable ~a not deduced\nin ~v"
                       x (Apply e1 es))]
               [ty ty])))
         (values (Inst e^ ty targs)
                 es^
                 (subst-type env^^ rt))]
        [else (error 'type-check "expected a function, not ~a" ty)]))

    (define/override ((type-check-exp env) e)
      (match e
        [(Lambda `([,xs : ,Ts] ...) rT body)
         (for ([T Ts]) ((check-well-formed env) T))
         ((check-well-formed env) rT)
         ((super type-check-exp env) e)]
        [(HasType e1 ty)
         ((check-well-formed env) ty)
         ((super type-check-exp env) e)]
        [else ((super type-check-exp env) e)])))

    (define/override ((type-check-def env) d)
      (match d
        [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...))
                          rt info body))
         (define ts-env (for/list ([t ts]) (cons t 'Type)))
         (for ([p ps]) ((check-well-formed ts-env) p))
         ((check-well-formed ts-env) rt)
         (define new-env (append ts-env (map cons xs ps) env))
         (define-values (body^ ty^)
           ((type-check-exp new-env) body))
         (check-type-equal? ty^ rt body)
         (Generic ts (Def f p:t* rt info body^))]
        [else ((super type-check-def env) d)]))

    (define/override (type-check-program p)
      (match p
        [(Program info body)
         (type-check-program (ProgramDefsExp info '() body))]
        [(ProgramDefsExp info ds body)
         (define ds^ (combine-decls-defs ds))
         (define new-env
           (for/list ([d ds^])
             (cons (def-name d) (fun-def-type d))))
         (define ds^^
           (for/list ([d ds^]) ((type-check-def new-env) d)))
         (define-values (body^ ty) ((type-check-exp new-env) body))
         (check-type-equal? ty 'Integer body)
         (ProgramDefsExp info ds^^ body^)]))))

其中 combine-decls-defs 将相邻的 Decl 与 Def 合并成 Generic 或带完整 parameter types 的普通 Def;type-check-program 先建立所有 definition 的 function-type environment,再检查每个 definition 和最终 expression,因此 mutual recursion 与 forward reference 都能正常工作。

4. 编译参数多态

编译 parametric polymorphism 大致有四种方法。

4.1 Monomorphization

为每一组实际使用的 type arguments 生成一份专门的 polymorphic function。优点是代码效率最高;缺点是需要 whole-program compilation、不能 separate compilation,并可能显著增加 code size。对于 first-class polymorphism,编译期有时无法知道 generic function 会搭配哪些 type arguments 使用;JIT 可以在 runtime 做这件事。

这种方法用于 C++ templates,以及 NESL、ML 的 polymorphic functions。

4.2 Uniform representation

所有值使用共同的 boxed representation,例如 LangAny 的 tagged value。polymorphic 与 monomorphic code 都类似动态语言:primitive 操作前从 Any project,结果再 inject 回 Any。它支持 separate compilation 与 first-class polymorphism,但整个程序都承担 boxing 与 dispatch 开销,因此效率最低。CLU、ML 和 Java 的实现采用过这种思路。

4.3 Mixed representation

每个 polymorphic function 只生成一份代码,但 type variables 使用 boxed representation。monomorphic code 保持普通表示,只在 monomorphic 与 polymorphic 边界进行转换,例如实例化并调用 polymorphic function 时。

它兼容 separate compilation 和 first-class polymorphism,并保持 monomorphic code 的效率;代价是边界处有额外开销。本章采用这种方案,因为它适合现有工具,也容易借助 gradual typing 已实现的机制完成。

4.4 Type passing

monomorphic 与 polymorphic code 都使用 unboxed representation。每个 polymorphic function 编译成一个带额外参数的函数,这些参数描述 type arguments;生成代码在 runtime 根据类型信息访问 unboxed value。

它支持 separate compilation、first-class polymorphism,并保持 monomorphic code 的效率;polymorphic code 需要承担根据类型信息 dispatch 的 runtime overhead。

本章只新增一个 compiler pass:erase-types,把 LangInst 编译为 LangCast。

5. 类型擦除

5.1 用 Any 表示 type variable

erase-types 使用 Any 表示 type variable。例如,map 的所有 a 都变成 Any,All 被移除:

racket
(define (map [f : (Any -> Any)] [v : (Vector Any Any)])
                   : (Vector Any Any)
  (vector (f (vector-ref v 0)) (f (vector-ref v 1))))

(define (inc [x : Integer]) : Integer (+ x 1))

5.2 实例化边界

擦除后 map 的类型是:

text
((Any -> Any) (Vector Any Any) -> (Vector Any Any))

但本次实例化要求:

text
((Integer -> Integer) (Vector Integer Integer)
 -> (Vector Integer Integer))

因此,在实例化位置插入一个 cast:

racket
(vector-ref
 ((cast map
        ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
        ((Integer -> Integer) (Vector Integer Integer)
                              -> (Vector Integer Integer)))
  inc (vector 0 41))
 1)

源类型与目标类型是一致的,因为它们都来自同一个 polymorphic type:前者把变量替换为 Any,后者把变量替换为推导出的 type arguments。

这一步正是 mixed representation 的边界转换:map 的函数体只保留一份,内部以 Any 形式处理 type variable;每个具体调用点通过 cast 恢复该次实例化所要求的接口。由于 Any 与任意 type consistent,cast 的 source/target 满足 consistency 条件。

5.3 erase-type

定义递归辅助函数 erase-type,执行两项转换:

text
x                       ↦ Any
(All xs T1)              ↦ T1'

其中 T1' 是递归擦除后的 T1。程序中的所有 type annotations 都要经过该函数。

5.4 Inst 的翻译

如果 e 的类型为 (All xs T),Inst 的 type arguments 为 ts,则:

text
(Inst e (All xs T) ts)  ↦  (Cast e' T' T'')
  • e' 是递归翻译后的表达式;
  • T' = erase-type(T);
  • T'' = erase-type(subst-type(s, T));
  • s = (map cons xs ts)。

换句话说,先把多态函数擦除成 Any 版本,再把它 cast 到本次实例化所需的具体类型。

5.5 Poly 的翻译

每个 polymorphic function 最终变成普通函数:类型参数消失,参数类型、返回类型和函数体全部进行 type erasure。

text
(Poly ts
      (Def f ([x1 : T1] ...) Tr info e))
↦
(Def f ([x1 : T1'] ...) Tr' info e')

这样,后续 lower-casts、proxy differentiation、closure conversion 与 x86 backend 就可以复用渐进式类型章节的实现。

形式化地说,若定义中类型参数为 ts,函数名为 f,参数类型为 T1 ...,返回类型为 Tr,函数体为 e,则:

text
(Poly ts (Def f ([x1 : T1] ...) Tr info e))
  ↦
(Def f ([x1 : T1'] ...) Tr' info e')

其中 T1'、Tr' 和 e' 分别是递归应用 erase-type / erase-types 的结果;ts 不再出现在生成的普通 Def 中。

6. 编译流水线

mermaid
flowchart LR
  A[LangPoly] -->|type_check| B[LangInst]
  B -->|erase_types| C[LangCast]
  C -->|lower_casts| D[LangProxy]
  D -->|differentiate_proxies| E[LangPVec]
  E --> F[shrink]
  F --> G[uniquify]
  G --> H[reveal_functions]
  H --> I[reveal_casts]
  I --> J[convert_assignments]
  J --> K[convert_to_closures]
  K --> L[limit_functions]
  L --> M[expose_allocation]
  M --> N[uncover_get!]
  N --> O[remove_complex_operands]
  O --> P[explicate_control]
  P --> Q[select_instructions]
  Q --> R[uncover_live]
  R --> S[build_interference]
  S --> T[allocate_registers]
  T --> U[patch_instructions]
  U --> V[prelude_and_conclusion]

本章练习:扩展 LangGrad compiler,实现 LangPoly compiler;创建 6 个使用 polymorphic functions 的测试程序,其中一些必须使用 first-class polymorphism。

原文信息

  • 原书章节:Parametric Polymorphism
  • 主要语言:LangPoly、LangInst、LangCast
  • 新增 pass:type_check、erase_types
  • 本章方案:mixed representation

参考

← 返回列表
← 上一篇 Essentials of Compilation:渐进式类型 下一篇 → Essentials of Compilation:附录

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论