Manuscript Offprint
arXiv:2611.04993Linking as Evaluation: Correct Separate Compilation via First-Class Environments
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Correct Separate Compilation via First-Class Environments
JAM KABEER ALI KHAN, Independent, Hong Kong
JINHAO TAN, The University of Hong Kong, China
BRUNO C. D. S. OLIVEIRA, The University of Hong Kong, China
Separate compilation is central to modular software: components are compiled independently and linked into an executable. Separate compilation is correct when a linked program behaves like the program formed by merging its sources. This property is less routine to prove than type soundness because it requires a formal account of linking.
We present , a simply typed calculus in which linking, modules, and environments are all first-class. Programmers control module linking through a link operator, which a type-directed elaboration translates into ordinary terms of a core calculus of first-class environments. The core calculus's existing evaluation rules then perform the linking: linking as evaluation. Linking independently compiled modules yields the same core term as elaborating their source link. Therefore, compilation and linking commute by construction. As a result, separate compilation correctness follows directly from the semantics preservation for both static and dynamic linking. All meta-theory is mechanized in Lean 4 and we implement a compiler to WebAssembly in OCaml.
Additional Key Words and Phrases: Separate Compilation, Linking, Semantics Preservation, First-Class Environments, Compiler Correctness, Lean 4 Mechanization
1 Introduction
Type soundness [52, 53] is a widely accepted sanity criterion for statically typed programming languages, supported by well-established proof techniques and mechanization frameworks. Modern software also relies on separate compilation: components are developed, typechecked, and compiled independently, then linked into larger systems [4, 26]. Separate compilation supports modularity, incremental builds, and third-party reuse. The correctness requirement is simple: linking independently compiled components should produce a program with the same behavior as linking their sources before compilation. However, establishing this correspondence is less routine than proving type soundness, even for simple types, because the proof requires a formal account of linking.
Cardelli [7] models separately compiled fragments as open terms and links them by substitution within linksets. He proves that linking preserves typing; SMLSC states the same property for Standard ML [48]. Both link outside the language, without proving that linked code behaves like the combined source program.
Other designs bring linking into the language. Units supports run-time composition [12], Alice ML expresses linking through functions [37], and MixML provides recursive module linking [39]. We know of no typed calculus with linking as an expression that proves that linking separately compiled components preserves source behavior. However, verified compilers have established separate compilation correctness, including SepCompCert [23] and CertiCoq [33]. For passes that commute with linking, SepCompCert derives this result from whole-program correctness. In both systems, however, linking remains outside the source language, and neither theorem covers dynamic linking.
We bring the two strands together: linking within the language, backed by a proof of separate compilation correctness that covers both, dynamic and static linking. Our approach is linking as evaluation: a source link elaborates into ordinary target terms so we can utilize the semantics of
Authors' Contact Information: Jam Kabeer Ali Khan, jamkhan@connect.hku.hk, Independent, Hong Kong; Jinhao Tan, jinhaot@connect.hku.hk, The University of Hong Kong, Hong Kong, China; Bruno C. d. S. Oliveira, bruno@cs.hku.hk, The University of Hong Kong, Hong Kong, China.
the target to perform the linking. Thus, evaluation provides a module's imports and produces a linked library.
We develop this approach in , a simply typed calculus with first-class modules, environments, and linking. First-class environments [50, 51] let programs construct the environment in which a module runs, and use a linked library or module as an environment for computation. elaborates into , a calculus of first-class environments [51]. A separately compiled module with imports becomes a closed function whose parameter supplies its import environment. Linking constructs this environment from the required exports of another module, applies the function, and combines their exports. Function application, field selection, and environment composition thus perform the linking using the target's existing evaluation rules. Sandboxing restricts a module to its declared import: it cannot access the scope where it is written and compiles to the same term wherever it appears. Linking supplies only the selected import, without exposing the scope at the link site. The client runs under its captured environment extended with that import.
Programmers control linking: a link is an ordinary expression. The same link can assemble compiled modules at top level, link against a module passed to a function at run time, or draw an import from the current environment. The link's elaboration uses only its operands' core terms and interfaces, so the core linker emits that same term from compiled fragments: compiling and linking commute by construction. Commutation is thus SepCompCert's easy case, holding by design and for dynamic links too.
We first prove that elaboration preserves types: well-typed source links compile to well-typed core terms. Beyond the typing guarantees studied by Cardelli, we define 's operational semantics and prove that elaboration preserves source semantics. That is, a source program and its elaboration evaluate to values related by elaboration or diverge together. Since the core linker produces the same term as elaborating the source link, semantics and behavior preservation establish separate compilation correctness directly from 's semantics. The result covers static and dynamic linking, both at top level and inside functions. The static case (Corollary 4.13) establishes, for , the semantic correctness property that Cardelli identifies but does not formalize. We also prove interface abstraction: a client's exports depend on its provider only through the imported values.
Our contributions are:
- The calculus (§3). A calculus with first-class modules, linking, and environments. We prove its type safety.
- Type-directed elaboration to (§4.2–4.3). We elaborate source programs into , translating first-class modules and linking into ordinary target terms. We prove type and semantics preservation.
- Separate compilation correctness (§4.3). We derive separate compilation correctness from semantics and behavior preservation. The design of elaboration makes the proof simple. We also prove interface abstraction and confinement for sandboxed modules.
- Extensions (§5.1). We extend the system with unions, iso-recursive types, fixpoints, and multi-import linking, showing that the approach still applies with these more expressive features.
- Mechanization and implementation (§5.2).¹ We mechanize all results in Lean 4 [29] and implement SCE-Lang, a prototype compiler written in OCaml. It targets WebAssembly [15] with no linking instruction and supports staged linking in both the core and WebAssembly.
¹The implementation and mechanization are available at https://github.com/jam-khan/SCE-Lang
The examples use a simplified surface syntax of SCE-Lang, our implementation (Section 5.2).
2.1 First-Class Environments
Environments are fundamental to language implementations: they hold the bindings against which code executes. However, environments normally belong to the implementation, not the language, so programs cannot reach or manipulate them. First-class environments [13, 36] lift this restriction: environments become ordinary values that programs can build, inspect, extend, and pass to functions. Because the body of a module is a sequence of bindings, a first-class environment can also represent that body. builds on this idea and elaborates into [51], a call-by-value calculus in which dependent merges [50] build first-class environments.
Dependent merges. In , a record supplies a single labeled entry. A merge evaluates its operands and joins their values into one environment, so multi-field records are merges of single-field ones. Merges are dependent: is evaluated first, and its value extends the environment in which runs. In a typing context is the type of an environment, so the typing rule extends the context with the left operand's type and pairs the result types:
For example, the right component of
refers to x. By the rule above, the merge has type . At run time, the value on the left is added to the environment before the right component runs. So x resolves to 2, and the merge evaluates to .
Dependencies between declarations are pervasive in modules, where a definition often refers to earlier definitions of the same module. A dependent merge makes such a sequence of dependent declarations an ordinary expression. The following declarations
let x : Int = 2 let y : Int = x + 1
are modeled as the merge above, and its type gives the types of the declarations.
Variables and closures. Every expression, such as the merge above, runs under a current, or ambient, environment. To resolve a variable, looks it up in the ambient environment and never substitutes into terms. Terms of are nameless: a variable is a de Bruijn index [9] giving the position of an entry in the environment. For readability, this section writes names instead of indices. It also writes for both the empty environment and its type. A function evaluates to a closure , which pairs the function with the environment of its definition.
Programmer-controlled environments. Besides dependent merges, which build first-class environments, provides constructs that let a program choose the environment a computation runs in. The query operator env returns the current environment. A box runs under the local environment produced by , which replaces the ambient one. Assuming that the ambient environment

Fig. 1. Double.sce compiled against interface Add.scei.
binds x to an integer, the expression
is well typed. Here env returns the ambient environment, which contains x. The merge extends it with the local binding y = 2. The box then runs the body under the extended environment, so both y and x are in scope. Dropping the query gives
which is ill typed, because the environment that the box supplies binds only y. A box therefore runs a computation under an environment that the program controls. Its body sees that environment's bindings and no others. The simply typed -calculus has no such construct: a only extends the environment, so a function body sees every enclosing binding.
With the box construct, provides a form of sandboxed modules [51]. A module that takes other modules as arguments is boxed under the empty environment, so it acts only through its arguments. The treatment is informal: has no module syntax, types or rules. Nor do Tan and Oliveira [51] study linking independently developed modules or separate compilation correctness.
2.2 Linking Outside The Language
Separate compilation compiles a client module against its provider's interface without the provider's implementation. The provider can be compiled independently and linked with the compiled client to produce an executable. Source files have the extension .sce, and interface files, which list a module's exports, have .scei. In Figure 1, Double imports Add and calls Add.op in double.Double.sce takes the type of Add.op from Add.scei, so it compiles before Add.sce is available. The figure shows only this compilation step, not how the modules are linked or what makes compiling and linking correct.
Cardelli [7] formalizes the linking step that the figure omits. Separately compiled modules become linksets: compilation produces them, and combination and linking act on them. The underlying calculus is , a simply typed -calculus. A judgment assigns type A to the term a under the typing environment , a typing context rather than a run-time environment. A linkset gathers judgments under distinct names:
The typing environment is the interface of the linkset and lists its imports. Each fragment exports the term under the name . The typing environment of fragment gives the types of the fragments that may refer to. Interfaces are thus typing environments outside the language: no term of has a typing environment as its type.
(a) Compilation
(b) Combination
(c) Linking
Fig. 2. Compiling, combining and linking the linksets of Add and Double, after Cardelli [7].
Figure 2 shows the three steps on the modules of Figure 1, in adapted notation. Shading marks what each step changes. Cardelli's modules list imports one variable at a time, not by module, so Double imports op directly. Compilation turns a module into a linkset with one fragment per binding, each typed under the earlier bindings. The linkset's interface lists the module's imports (a). Combining two linksets, written , puts their fragments into one linkset. An import of one linkset that the other exports moves from the interface to the typing environments of the importing fragments (b). Linking, written , then resolves every name in the typing environments by substitution: the moved imports and the earlier bindings. Each such name leaves the typing environment and is replaced by the term exported under that name by a closed fragment, one typed under the empty environment (c).
Cardelli proves that compilation, combination and linking preserve typing. That is, each fragment typechecks, and each import has exactly the type that its provider exports. Cardelli names separate compilation correctness, but has no evaluation in which to state it. It holds when linked code behaves like the merged sources, one program with both modules. Linking acts on linksets, not on terms of , so it lies outside the language. A correctness proof thus needs an account of linking.
Cardelli's account raises three questions:
-
Fragments are open terms, and linking rewrites them by substitution. Can a compiled module instead be a closed term that linking runs unchanged?
-
Interfaces are typing environments, and linking is an operation on linksets. Can interfaces be ordinary types, and can linking be an expression evaluated during execution?
-
Can separate compilation correctness follow from the compiler's correctness alone, with no account of linking?
Section 2.3 answers them in order, using first-class environments.
2.3 Linking Inside The Language
makes linking first-class: a program can write a link at top level, place it inside a function, or choose the link's provider at run time. This design unifies static and dynamic linking in a typed setting. It also makes separate compilation correctness a corollary of semantics and behavior preservation.
To illustrate, take Add and Double from Figure 1, now declared within the program. We make Double a sandboxed functor requiring an op operation of type Int Int Int. Any provider
(a) Importing file
import M (* sig x : Int; y : Int end *) let z : Int = M.x
(b) Sandboxed functor
sandbox functor (I : { M : sig x : Int; y : Int end }) -> struct let z : Int = I.M.x end
(c) Structure
struct let x : Int = 1; let y : Int = x + 1 end
Fig. 3. Source modules (left) and simplified elaborations (right, shaded gray). We omit administrative bindings. In (a–b), is the import record, by de Bruijn index. In (c), underlining marks a field lookup.
exposing a unique op of this type can be linked with Double. First-class linking lets us combine these modules into a library and use that library as the environment for a computation:
module Lib = link Add with Double
let main : Int = box Lib in op (double 5) unit (* 10 *)
The link operator supplies Double's import from Add and combines their exports in Lib. Because structures elaborate to first-class environments, Lib serves directly as the environment of main.
Modules as closed terms. Lib links two modules declared in the program. A separately compiled file links in the same way, because a file with imports elaborates to the same simplified form as a sandboxed functor, up to parameter renaming. Figure 3(a–b) shows this form on a smaller module: a boxed lambda whose parameter binds the imports. The box hides the ambient environment and the lambda binds every import, so the compiled file is closed. Linking applies it and never rewrites it, unlike the substitution of Figure 2(c). This answers the first question of Section 2.2. In Figure 3(c), a structure elaborates to a first-class environment built by dependent merge: y can refer to x.
Interfaces as types. Module interfaces are ordinary types, so functions can accept and return modules. This answers the first half of the second question. We write sig A for the type of a structure whose contents have type A, and for a functor with import type A and result type B. The type translation [·] maps the functor and structure types in Figure 3(b–c) as follows:
[[{M : sig ( {x : Int} & {y : Int} )} sig {z : Int}] = {M : {x : Int} & {y : Int}} {z : Int}
[[sig ( {x : Int} & {y : Int} )] = {x : Int} & {y : Int}
Linking as evaluation. The second question also asks whether linking can be an expression. In , a source link elaborates into ordinary terms, so the core evaluator links with its existing rules for application, lookup, selection and merge.
Link elaboration into . Figure 4 elaborates the link of Add (Figure 1) with Double, a sandboxed functor (marked ■) as in Figure 3(b). We write for link with . The judgment types a source term and translates it to a core term . In ELAB-LINK, the premise op : Int Int Int sig P checks that Add exports op exactly once, with the type Double imports.
In , the applications evaluate the provider and client once, in that order, and bind their values to and . The body selects the op field from and supplies it to as , then merges with the client's result. Linking thus becomes ordinary application and environment composition. Because the current environment , which inherits from , is a first-class
The examples assume integer arithmetic primitives, omitted from the formal grammar.
Fig. 4. Elaboration of Add linked with Double.
value (Section 2.1), it can also be the provider. In a structure that declares op, with no other op in scope, a later declaration can be , which links Double against that op.
Confined linking. Linking against env makes the link site the provider, by explicit choice. First-class environments invite a design that makes this implicit: run the client under the environment where the link is written, extended with its import. The client's meaning would then depend on the link site. A name that the client uses but does not import would resolve to whatever that site binds, and its compiled code would be valid only there. In , a link instead applies the client, as shows. The client runs under the environment its closure captured, extended with the selected import. The link itself adds nothing from its own site. This holds for every client. A functor without the sandbox mark, an open functor, still captures the environment where it is written. Its body thus sees the definition site. The box in removes that environment as well. Double's body runs under the empty environment extended with the record that f receives, so it sees op from Add and nothing else. A sandboxed client therefore compiles to the same term wherever it is written. The compiled client runs at any link site, against any provider that exports its import exactly once at the required type, and its exports depend only on that import. Context Independence (Lemma 4.1) and Sandbox and Link Confinement (Theorems 4.16 and 4.17) state these properties.
Link typing and the core linker. Elaboration preserves typing (Section 4.2), so a well-typed source link elaborates to a well-typed core term. In the example, the source link has type sig P & sig T: P describes Add's exports (op, unit), D the import (op), and T Double's export (double). Type translation gives the core types P for , D T for , and P & T for .
With these core types, the core linker needs no sources. Rule CL-LINK checks that P supplies the client's import and emits , the same term that ELAB-LINK produced:
The rule does not typecheck or . Given their typings, which elaboration guarantees, Link typing (Theorem 4.11) derives .
Linking semantics and preservation. A functor evaluates to a module closure , which pairs the functor with its captured environment . Let be Add's value, its addition closure, and Double's body. With and an empty ambient environment, the following abridged reduction supplies op to the client and retains both modules' exports:
Table 1. Separate compilation with linksets and .
| Linksets [7] | ||
|---|---|---|
| Compiled modules | Open fragments | Closed terms |
| Interfaces | Typing environments | Ordinary types |
| Linking | Operation on linksets | Ordinary expression |
| Import resolution | Term substitution | Argument passing and lookup |
| Separate compilation | Type preservation | Type, semantics and behavior preservation |
The semantics of Section 3.3 gives this reduction both for separately compiled files linked at top level and for modules linked inside a program. Semantics preservation (Theorem 4.8) ensures that evaluates to a value related to by elaboration.
Separate compilation correctness. We can now answer the last question: separate compilation correctness is a corollary of semantics and behavior preservation. Table 1 summarizes all three answers.
The upper square of Figure 5 compares the two paths. Rule ELAB-LINK elaborates the source link. That link is the merged program, and the source semantics gives its meaning. Rule CL-LINK links the independently compiled operands using only their interfaces. Both paths produce the same core term , so elaboration commutes with linking by construction. The lower square is semantics preservation, for terminating runs. With behavior preservation (Theorem 4.9), it yields separate compilation correctness for every well-typed link, at top level or in a program (Corollaries 4.12 and 4.13).

Fig. 5. Correctness diagram.
2.4 Programming with First-Class Linking and Environments
Linkset linking (Section 2.2) runs before execution, so it cannot take a provider that a program builds at run time. In , a link is an expression. So a program can load a compiled client at run time and link it against a provider built per call. Figure 6 builds a page renderer whose formatting plugin is such a client. The figure omits the imports of Sys and Loader and the union declarations. The host supplies logging and falls back to plain text if loading fails.
Compile the client once. First, the plugin in panel (a) imports Cap for logging and exports render. Compilation produces a sandboxed functor. Its body can call Cap.log but cannot name the host's Sys, although Sys is in scope where the host links it (Section 2.3). Sandboxed functors elaborate independently of their ambient context (Lemma 4.1).
Construct the provider. Next, caps in panel (b) builds a logger that captures the caller's name, and host packages it with a message. Both successful calls reuse aliceCap, although their providers carry different messages. Linking passes only Cap to the plugin, which exports the same render closure in both cases. This illustrates interface abstraction (Theorem 4.14). The linked result still contains message. A no-op logger would silence the plugin without recompiling it.
Link, then choose the environment. Finally, page in panel (c) loads the plugin. On success, linking saved with p produces lib. The box evaluates render message under lib, using the plugin's function and the provider's message. The calls return different strings because the host supplies different messages to that function. On failure, the box reads the message from the saved provider.
(a) Compile the plugin separately: fancy.sce to fancy.sceo import Cap : { log : String -> Unit } let render (text : String) : String = let noted : Unit = Cap.log "rendering" in "*** ^ text ^ "**
(b) Build a logger, then package it with a message let caps (name : String) = { log = fun (s : String) -> Sys.print ("[" ^ name ^ " ]" ^ s) } let host (cap : { log : String -> Unit }) (text : String) = struct let message : String = text let Cap = cap end
(c) Load the client, link it, and run under the resulting environment let page (cap : { log : String -> Unit }) (path text : String) : String = let saved = host cap text in match Loader.load path with | Plugin p -> let lib = link saved with p in box lib in render message | Failed e -> box saved in message end
let aliceCap = caps "alice" page aliceCap "fancy.sceo" "hello" (* prints "[alice] rendering"; returns "*** hello " ) page aliceCap "fancy.sceo" "bye" ( prints "[alice] rendering"; returns "* bye **" ) page aliceCap "missing.sceo" "hello" ( returns "hello" *)
Fig. 6. A plugin host in three steps. Comments show the output.
The declared type of Loader.load gives p the type of panel (a), so the compiler checks the link before loading. At run time, Loader.load returns Plugin p only for a compiled file of that type.
The example illustrates the linking construction covered by separate compilation correctness (Corollary 4.12). Strings, I/O, and artifact loading lie outside the formal calculus.
3 The Source Calculus:
extends [51] with first-class modules and a linking expression. It keeps first-class environments and dependent merges [50]. The merged program is the source link, which 's semantics evaluates: Section 4.3 states separate compilation against that evaluation. Rule ELAB-LINK translates a link to the term that the core linker emits for compiled fragments. By Corollary 3.7, a well-typed program cannot get stuck, even for links in functions or with providers chosen at run time.
3.1 Syntax
Figure 7 shows the syntax of . We use blue for modules and module types, and orange for the other extensions to . The black constructs are inherited from . These colors also distinguish the constructs in the typing and reduction rules.
Types as contexts. Metavariables , , and range over types. Any type can be a typing context. Types include integers (Int), a unit type () for the empty environment, environment types (), arrow types (), and single-field record types (). An environment type pairs two
| Types | A, B, | ::= | Int | | A B | A & B | {l : A} | sig A | A m B |
|---|---|---|---|
| Functor modes | s | ::= | ■ | ☐ |
| Expressions | e | ::= | env | i | | e.n | e.l | A. e | A. e \rangle | e_1 e_2 | {l = e} |
| | | e_1 e_2 | e_1 e_2 | e_1 e_2 | let e_1 in e_2 | open e_1 in e_2 | m | ||
| Modules | m | ::= | struct e | functor_s(A) e | | e_1 e_2 | e_1 e_2 |
| Values | v | ::= | i | | A. e \rangle | | struct v | v_1 v_2 | {l = v} |
| Sugar | l | env.l env.n |
Fig. 7. Syntax of .
environment components in order. There is no subtyping. Type equality is structural, so Int & differs from & Int, as (Int & Int) & does from Int & (Int & ). We associate chains of environment types and merges to the left. A multi-field record type abbreviates a chain of single-field ones.
Module types. Any module's type is its interface: an interface type for a structure, and a functor type for a functor. The interface type sig A, written with the keyword sig, classifies structures whose body has type A. The functor type classifies functors importing A and exporting B.
Expressions. Expressions include integers (i), a unit expression ( ), applications ( ), boxes ( ), dependent merges ( ), and lambda abstractions ( . e). A lambda binder is nameless. Its annotation A supplies the parameter type when typing the body. The query env returns the current environment. Projection (e.n) returns the n-th entry of the value of e, so a variable with de Bruijn index n [9] is env.n, abbreviated . Records ( ) create labeled entries, which selection (e.l) retrieves. Multi-field records are merges of single-field ones. The sugar abbreviates env.l. A closure ( ) saves the environment in which a function was created.
The orange constructs elaborate to core expressions (Section 4). A non-dependent merge evaluates both components under the same environment, without making the value of available to . The let binding (let in ) adds the value of to the environment of . It requires no annotation because typing synthesizes the type of (Section 3.2). Finally, open in opens a named component: must have a single-field record type , and its field value extends the environment of . If the field holds a structure, can then select the structure's exports by label.
Modules. The blue constructs form the syntactic category of modules, which is part of the expression grammar (). Their subterms are arbitrary expressions. In particular, the operands of module application and linking need not be module forms. A functor may be selected from the environment or computed by another expression.
A structure (struct ) evaluates its body under the ambient environment and packages the result as the value struct . A functor (functor ) abstracts a body over an import of type . Like a lambda abstraction, a functor evaluates to a closure, here a module closure (). The functor's mode determines the captured environment: empty in sandbox mode (■) and ambient in open mode (□). Module application () supplies the functor with its import . Modules can be bound, merged, passed to functions, and returned.
Linking connects a provider to a client functor . The client's import is a single-field record , as for open, and its label names an export of the provider. Linking selects that export, supplies it to the client, and merges the provider with the client's result. The provider can be any expression whose type contains the import, such as a function's argument or env (ELAB-ENV).
(Typing and elaboration)
Fig. 8. Containment, typing, and elaboration of expressions.
3.2 Typing
Figure 8 presents the typing and elaboration rules for expressions. The judgment states that source expression has type under and elaborates to the term . Elaborated terms are shaded gray, and translates a source type to a type. This subsection explains typing. Section 3.3 explains the term that rule ELAB-LINK generates, and Section 4.2 the type translation and other generated terms.
Environments and lookup. The query env inspects the context, and has the current context as its type (ELAB-ENV). A projection e.n has type lookup when e has type A (ELAB-IDX). The partial function lookup counts from the right end, so index 0 is the rightmost entry:
A box replaces the ambient context with the type of when checking (ELAB-BOX). Lambdas and dependent merges retain and extend it on the right to , where is the parameter type or the left operand's type, respectively. By rule ELAB-CLOS, a closure uses its captured environment: its body is checked under , where has type under .
Labels and containment. Projection finds an environment entry by position. Selection and linking instead find a field by label. Both use the containment judgment of Figure 8: type exposes exactly one field named , and that field has type . The function label( ) records the labels
(Typing and elaboration)
Fig. 9. Typing and elaboration of modules.
exposed by a type:
For an environment type, containment requires l in exactly one component. A merge may contain duplicate labels, but selecting a duplicated label or linking a client that imports it is ill typed.
Let and open. Like selection, open reads a field by its label, but it needs no containment. Its operand must have exactly the type . Rule ELAB-OPEN adds only A to the context. Rule ELAB-LET instead adds the whole synthesized type of , so for the same it adds . Take . After open in , selects the structure's export as . After let in , writes .x. Either way, the first label selects, x or M, must be unique in the context.
Modules and linking. Figure 9 gives the module rules. Like a let or open body, a functor body is checked under an extended context. Its import type A extends the empty context or the ambient one, depending on the functor's mode. A sandboxed body is checked under & A, so it accesses only its import. An open body is checked under & A and may also use ambient bindings. Both modes give the functor the type , where B is the type of its body. Open mode serves functors over ambient modules. Sandbox mode serves separately compiled clients.
Rule ELAB-LINK constructs the import from the one provider field of the required name and type. Although has no subtyping, linking thus accepts a provider with additional exports. Module application returns only the client's result, whereas linking returns the provider merged with that result. For example, take Add from Figure 1, which exports op : Int Int Int and unit : Int, and a functor Double' that imports only {op : Int Int Int} and exports double : Int Int. Direct application Double' Add is ill typed, because Add's interface differs from the required import record type. The adapted application Double' {op = Add.op} returns only the client's structure, whereas Add Double' needs no adapter. The link also retains op and unit.
(Selection)
(Small-step reduction)
Fig. 10. Small-step semantics of .
3.3 Small-Step Semantics
Figure 10 defines the call-by-value small-step semantics of . The judgment states that takes one step to under the ambient environment , which is a value. We write for its reflexive and transitive closure.
Environments in reduction. Frames specify left-to-right evaluation, and rule S-FRAME preserves the ambient environment. Rules S-ENV, S-BoxV, S-IXdV and S-SELV return the environment, the body's value, or the entry found. Boxes and dependent merges change the environment used for their right operands. A box replaces it with the value of (S-BoxR), whereas a dependent merge extends it with the left operand's value (S-MRGR). Rules S-LETV and S-OPENV reduce let and open to boxes whose bodies run under the ambient environment extended with the bound value. A non-dependent merge leaves the environment unchanged: frames evaluate both operands under it, and rule S-NMRGV then turns the two values into a dependent merge.
A lambda captures the ambient environment in a closure (S-LAM). Rule S-BETA then runs the body in a box under the captured environment extended with the argument, without substitution. Functors work in the same way (S-FUN, S-MBETA), except that rule S-FUN captures , which is the empty environment for a sandboxed functor. Rules S-MRGR and S-BETA both extend the environment on the right, so lookupV also counts from the right end:
For example, take an ambient environment and the term . Its two beta steps run the body under . The merge then adds the value of for its right operand. So the indices denote the following:
| Environment | |||
|---|---|---|---|
| Left operand | |||
| Right operand |
The same index thus denotes different entries in the two operands of a dependent merge. Index is on the left and on the right. This difference is what rule ELAB-LINK relies on. In its term , , the left denotes the provider. On the right, denotes the client and the provider.
Rule S-LINKV is module application followed by a merge: its right operand is the S-MBETA reduct of the client applied to , and the provider is merged on the left. The link evaluates the provider first, then the client. Below, the provider One supplies x to a client Inc that adds 1:
Under , the box runs the sandboxed client Inc, so its body can access only the selected import. The body evaluates to 2, and the link to One 2.
The link above selected x from One. Label selection searches both sides of a merge and looks through structures (SEL-MRGL, SEL-MRGR, SEL-STR). When the type of v contains l, only one side has l, so selection is unique, which makes well-typed evaluation deterministic (Theorem 4.15).
Rule S-LINKV uses only selection, a record, a box and merges, all of which has. Rule ELAB-LINK expresses this behavior as a term (Section 4.2), so needs no separate linking rule.
3.4 Type Safety
We state the typing properties of using the elaboration judgment with its core term hidden:
An expression has at most one type under a given context.
THEOREM 3.1 (INFERENCE UNIQUENESS). If and , then .
A value has the same type under every context.
LEMMA 3.2 (VALUE WEAKENING). If , then for every .
Indexed lookup and label selection succeed on a well-typed value and return an entry of the type that lookup or containment gives.
LEMMA 3.3 (LOOKUP PROGRESS). If and lookup, then lookup for some value with .
LEMMA 3.4 (SELECTION PROGRESS). If and , then for some value with .
Boxes and dependent merges change the environment during evaluation, so we prove progress and preservation for an arbitrary environment v of type . Because environments are values, the expression judgment types them too.
THEOREM 3.5 (PROGRESS). If and , then is a value or for some .
THEOREM 3.6 (PRESERVATION). If , and , then .
Although variables are de Bruijn indices, the proofs need no term-substitution or index-shifting lemmas: they use environment lookup and value weakening. For linking, Lemma 3.4 supplies the import value at the required type. The typing rules for records, boxes, and merges then establish preservation of the linked result. Instantiating both theorems with and gives type safety.
COROLLARY 3.7 (TYPE SAFETY). If , then is a value or for some , and every such satisfies .
4 Elaboration and Separate Compilation Correctness
Modules in elaborate to terms of the core calculus [51]. The elaboration of a source link is exactly the term that the core linker emits for the compiled fragments. Compiling and linking therefore commute by construction (the upper square of Figure 5). Separate compilation correctness then follows from semantics preservation (the lower square) and behavior preservation, for static and dynamic links alike. Section 4.1 fixes notation for , and Section 4.2 presents the elaboration. Section 4.3 proves correctness and interface abstraction.
4.1 Target calculus
The calculus has the expression and type forms shown in black in Figure 7. Tan and Oliveira [51] give the typing and semantics of . We write for source judgments and for core judgments. Where both calculi appear, ranges over core values and over source values.
Typing and Semantics. The typing judgment of uses a type as its context , as in . is type safe [51], and our mechanization reproves progress and preservation for .
4.2 Type-Directed Elaboration
Elaboration turns a structure into its body, a functor into a function, and a link into a core term built from applications, selection, and merge. The target therefore needs no module constructs. Figures 8 and 9 pair each typing rule with its core term, and this subsection explains those terms.
Type Translation. The translation [.] maps source types to types. It is homomorphic on the constructors shared with , removes interface wrappers, and turns functor types into arrows:
Since contexts are types, the same translation applies to the typing context .
Core Expressions. Elaboration preserves the expression forms shared with and recursively elaborates their subterms. Rules ELAB-LAM and ELAB-CLOS also translate the parameter annotation.
Derived Expressions. Let bindings, open expressions, and non-dependent merges elaborate to core environment operations. The examples evaluate under the ambient environment :
| Source expression | Elaborated term | Value |
|---|---|---|
| let {y = 1} in | .0 | 8 |
| open {m = {y = 1}} in | ((m = {y = 1}).m) | 8 |
| {x = 1} {z = + 1} | .0 | {x = 1} , {z = 8} |
A let binding uses a dependent merge to extend the body’s environment with the whole bound value, then projects the body’s result (ELAB-LET). An open expression instead extends the environment with only the field value of its operand (ELAB-OPEN). The operand’s synthesized type supplies the selection label and the lambda annotation : and in the second example. Only the open encoding uses type information.
In a non-dependent merge, the outer env saves the ambient environment, which boxes restore for each operand (ELAB-NMRG). In the third example, the right operand sees the ambient , so .
Modules. Elaboration removes structure wrappers (ELAB-STR) and maps module closures and applications to their core counterparts (ELAB-MCLOS, ELAB-MAPP). An open functor elaborates to a lambda abstraction that captures the ambient environment (ELAB-FUN☐). A sandboxed functor elaborates to the boxed abstraction . ) (ELAB-FUN☐). The box makes the abstraction capture the empty environment. Rule ELAB-FUN☐ ignores the ambient context, so a sandboxed functor elaborates the same way wherever it occurs. A sandboxed client therefore compiles once and links in any context:
LEMMA 4.1 (CONTEXT INDEPENDENCE). If , then
PROOF. Rule ELAB-FUN■ checks the body under , independently of the ambient context. □
Linking. A link , with operand types and , elaborates by rule ELAB-LINK to the following term. The named form identifies the provider and client :
\begin{array}{r l}{\mathrm{N a m e d}}&{\left|\begin{array}{c}{(\lambda(p:\left[\left[\Gamma_{1}\right]\right]).\lambda(f:\{l:\left[\left[A\right]\right]\})\to\left[\left[B\right]\right]).p\left(f\left\{l=p.l\right\}\right))e_{1}^{\prime}e_{2}^{\prime}}\\ {\mathrm{N a m e l e s s}}&{\left|\begin{array}{c}{(\lambda[\left[\Gamma_{1}\right]].\lambda(\{l:\left[\left[A\right]\right]\})\to\left[\left[B\right]\right]).\underline{1}_{\sqcup}(\underline{1}\{l=\underline{0}.l\}))e_{1}^{\prime}e_{2}^{\prime}}\end{array}\right.}\end{array} \tag{1}We write for this term. It generalizes the term that links and in the overview to any import label and interfaces.
Across all rules, elaboration preserves types (Theorem 4.2) and produces a unique core term (Theorem 4.3). With Theorem 3.1, a well-typed expression and its context therefore determine the expression's type and elaboration. The elaboration of a link is thus well defined.
THEOREM 4.2 (TYPE PRESERVATION). If then .
THEOREM 4.3 (ELABORATION UNIQUENESS). If and then .
4.3 Separate Compilation Correctness
A sandboxed client is compiled against only the interface of its import, and links with any provider whose type contains it. We derive separate compilation correctness from semantics and behavior preservation, and show that the client's result depends on its provider only through the import.
Big-Step Semantics. We use big-step evaluation to state semantics preservation. The judgment states that evaluates to the value under the ambient environment . Its rules evaluate subexpressions under the same environments as the small-step rules, and Appendix A gives the rules in full. The rule for a link mirrors rule S-LINKV:
Big-step evaluation agrees with small-step reduction to a value. The results on terminating runs below use big-step evaluation, and Theorem 4.4 carries them to small-step reduction:
THEOREM 4.4 (BIG-STEP/SMALL-STEP EQUIVALENCE). if and only if .
For , we write for big-step evaluation, which the mechanization also proves equivalent to small-step reduction.
Semantics Preservation. Elaboration preserves evaluation: a terminating source expression and its elaboration produce values related by elaboration. The proof uses three facts: source values elaborate to core values, and indexed lookup and label selection commute with elaboration. We use the same notation for the corresponding core operations.
LEMMA 4.5 (VALUE ELABORATION). If , then is a value.
LEMMA 4.6 (LOOKUP PRESERVATION). If , lookup, and lookup, then and .
LEMMA 4.7 (SELECTION PRESERVATION). If , , and , then and .
THEOREM 4.8 (SEMANTICS PRESERVATION). If , , and , then and .
PROOF SKETCH. By induction on the source evaluation, using Lemmas 4.5–4.7 for queries, indexed projections, and field selection. In the linking case, the induction hypotheses and Lemma 4.7 give the core provider, client, and export, and the term (1) runs the client body as rule EVAL-LINK does.
Theorem 4.8 runs from source to core and speaks only of terminating runs. Theorem 4.9 adds the converse and divergence. Big-step evaluation cannot express a run that never ends, so we write when has an infinite small-step reduction under , and likewise for .
THEOREM 4.9 (BEHAVIOR PRESERVATION). If and , then
(i) implies and for some and
(ii) if and only if .
PROOF SKETCH. An auxiliary simulation relation matches each source step with zero or more core steps. Zero-step matches strictly decrease a natural-number measure on source terms, so infinite source reductions yield infinite core reductions. Termination and divergence reflection then follow from source type safety, semantics preservation, and core determinism.
Fixpoints or iso-recursive types, added in Section 5.1, let terms diverge. Like every theorem in the paper, Theorem 4.9 covers that extended language.
Taking and in Theorems 4.8 and 4.9 gives correctness for whole programs.
COROLLARY 4.10 (WHOLE-PROGRAM CORRECTNESS). If , then and have the same behavior under :
(a) implies and for some
(b) implies and for some and
(c) if and only if .
Core Linking. Corollary 4.10 covers a program compiled as a whole. The core linker instead links separately compiled fragments. It receives two core fragments and their interfaces, not their sources. We model it by the judgment
The judgment links a provider of interface and a client into the term . Here the client imports a field of type and exports . The interfaces and play the roles of , and in term (1). Rule CL-LINK checks containment and emits the term of rule ELAB-LINK:
CL-LINK
The judgment uses only the fragments and their interfaces, so it has no context index and does not check the fragments' types. Theorem 4.11 assumes their typing under any core context .
THEOREM 4.11 (LINK TYPING). If , and , then .
The result keeps both modules' exports, so it can be the provider of a further link.
Reusing a Compiled Client. Rule CL-LINK lets one compiled client serve providers it was never compiled against. Take , the compiled Double of Section 2.3, whose interface is with , and a provider compiled with another interface:
Since op : Int Int Int holds, rule CL-LINK derives
Here op multiplies, so .double 5 evaluates to 25. Type equality is structural, so differs from the interface P of the compiled Add, which lists op first. The client is still reused unchanged, because rule CL-LINK checks only that contains op.
Separate Compilation. Separate compilation correctness is a corollary of semantics and behavior preservation, because the core linker emits the elaboration of the source link. The provider and the client may depend on the ambient context , for example when a function receives its provider as an argument. The linked core term then runs under the elaboration of the source environment.
In the corollaries, the provider's interface , the import type and the client's exports are source types. The core linker receives their translations and .
COROLLARY 4.12 (DYNAMIC SEPARATE COMPILATION). If
Then under v and under u have the same behavior:
(a) implies and for some ;
(b) implies and for some ; and
(c) .
PROOF SKETCH. With (1)–(3) and rules CL-LINK and ELAB-LINK, we have . Theorem 4.8, applied to this elaboration with (4), yields (a), and Theorem 4.9 yields (b) and (c).
A sandboxed client is compiled once, under , before any provider or scope is chosen: by Lemma 4.1, its compiled term satisfies (2) for every . An open client's compiled term may refer to , so it is valid only under the context in which it was compiled. The corollary also covers such clients, each in its own context, as well as clients that are variables bound to loaded modules. Loading itself lies outside the calculus: through premise (4), the corollary assumes that a loaded module's value elaborates to its compiled form. Static linking instead compiles both fragments under and runs them under the empty environment.
COROLLARY 4.13 (STATIC SEPARATE COMPILATION). Assume (1)–(3) of Corollary 4.12 with . Then (a)–(c) hold with .
PROOF. Apply Corollary 4.12 with .
In words, the core linker's output evaluates to the elaboration of the source link's result exactly when the source link terminates, and diverges exactly when the source link does. Both corollaries give this for a client compiled once and a separately compiled provider.
| Property | Description |
|---|---|
| Context independence (Lemma 4.1) | A sandboxed functor has the same type and elaborates to the same core term in every context., for all . |
| Interface abstraction (Theorem 4.14) | Fix a client of type under , and an environment of type . Provider values that contain in their types and select the same import value give. |
| Separate compilation (Corollary 4.12; Corollary 4.13) | Linking independently compiled modules preserves the result of their source link. For , let link their separately elaborated core terms. If , then. |
Fig. 11. Properties of linking and separate compilation.
The corollaries cover a single link. An SCE-Lang program is a sequence of files, each linked against the earlier ones, or merged with them if it has no imports. Theorem C.1 extends Corollary 4.13 to such a sequence of binary links and merges with import-free files (Appendix C.1).
Interface Abstraction. A new provider preserves the client's result if the selected import value is unchanged. We fix the client, ambient environment, and import value, with its captured environments.
THEOREM 4.14 (INTERFACE ABSTRACTION). Let and be values. Suppose , , and, for , , , and . Then, for every value ,
and if and only if .
PROOF SKETCH. Typing makes selection of unique, so rule EVAL-LINK supplies the same record to the client in both links. Reusing the client and body derivations proves each direction. A well-typed link diverges exactly when it does not terminate, which gives the divergence part.
Figure 11 summarizes context independence, interface abstraction, and separate compilation correctness. Its entries omit divergence, and the separate compilation entry shows only clause (a).
Sandbox and Link Confinement. A link never passes its own ambient environment to the client. The client runs under the environment it captured, extended with the selected import. A sandboxed client captures the empty environment (S-FUN), even inside a function, as the box in its elaboration (ELAB-FUN) does. Its body therefore sees only that import: no binding in scope where the client is written or linked, and no other export of the provider. Since typing makes every selection unique, source evaluation is deterministic, and the agreement of results follows from determinism, both for a sandboxed functor applied directly and for links. For divergence, both runs take the same first steps, then run the same body under the same environment, so they diverge together.
THEOREM 4.15 (DETERMINISM OF EVALUATION). If , and , then .
THEOREM 4.16 (SANDBOX CONFINEMENT). Let , and . For values , if for , then . Moreover, if and only if .
| Types | A, B, | ::= | | | | . A |
|---|---|---|---|
| Expressions | e | ::= | | e | e | e of | |
| | | fix(A B). e | fold [ .A] e | unfold e | ||
| Import interfaces | D | ::= | |
| Modules | m | ::= | | |
Fig. 12. Unions and recursion extend both calculi, and multi-import linking extends .
THEOREM 4.17 (LINK CONFINEMENT). Let with , and . For , let be a value with exactly when . For values , if for , then . Moreover, if and only if .
The client’s exports thus depend neither on the ambient environments nor on the rest of the providers. The closure captures the empty environment, which excludes a client that captured a nonempty one, such as an inline open functor. A sandboxed client evaluates to a closure over the empty environment wherever it is written (Section 2.3). For terminating runs, the client may be any expression that evaluates only to this closure, such as a variable bound to a loaded module.
5 Extensions, Implementation and Discussion
We extend the calculus and its metatheory (Section 5.1), present the WebAssembly compiler (Section 5.2), and discuss limitations and further extensions (Section 5.3).
5.1 Extensions
We add unions, recursive types, and fixpoints to both calculi, and multi-import linking to (Figure 12). Every theorem so far extends to these constructs, and Lean checks the new proof cases.
Unions and Recursion. Union types let the loader of Section 2.4 return either a plugin or an error. Matching the Plugin case binds the loaded plugin at the functor type required for linking. Iso-recursive types describe recursive data, and fixpoints define recursive functions. These constructs elaborate directly to their counterparts in ; Appendix B.1 gives the rules.
Multi-Import Linking. Multi-import linking selects a unique provider field of the required type for each import in . Elaboration replaces the single-field record in term (1) with , where names the provider. Core linking constructs the same term from separately compiled modules (CL-LINKN): source and core links terminate with results related by elaboration or diverge together, for both static and dynamic links. For a fixed well-typed client and ambient environment, links with typed provider values supplying the same import package yield the same client exports and diverge together. Separate compilation correctness also covers files combined in dependency order by linking against accumulated exports or merging import-free files. Rules and proofs appear in Appendix B.2 (Theorems B.4 and B.6) and Appendix C.1 (Theorems C.1 and C.2).
5.2 Implementation
SCE-Lang implements in about 4,500 lines of OCaml. The compiler parses and desugars source programs into terms, then typechecks and elaborates them into . It provides interpreters for both calculi and a WasmGC backend, and implements every extension above.
Units and Linking. SCE-Lang represents an importing file as a sandboxed functor over its imports, and an import-free file as a structure boxed under the empty environment. Each unit elaborates under the empty context to a core term, stored with the interfaces the loader checks. The linker chains units, saving each result as a unit for staged linking. Theorem C.2 proves chains correct.
C[[env]]_ρ = local.get ρ
C[[e_1 ▷ e_2]]_ρ = C[[e_1]]_ρ local.set ρ' C[[e_2]]_ρ'
C[[e_1 ₉ e_2]]_ρ = C[[e_1]]_ρ local.set x
local.get ρ local.get x struct.new $Pair local.set ρ'; ; ρ' = (ρ, x)
local.get x C[[e_2]]_ρ' struct.new $Pair
C[[λA. e]]_ρ = ref.func $f local.get ρ struct.new $Clos
where the lifted function $f(self, x) is
local.get self struct.get $Clos env local.get x
struct.new $Pair local.set ρ' ; ρ' = (self.env, x)
C[[e]]_ρ'
C[[e_1 e_2]]_ρ = C[[e_1]]_ρ local.tee c C[[e_2]]_ρ
local.get c struct.get $Clos fn call_ref $Fn
Fig. 13. Compiling the environment operations of to WasmGC.
Compilation to WebAssembly. The WasmGC backend compiles these units without a dedicated linking instruction. Figure 13 shows the compilation of 's environment operations, omitting tags and casts. At run time, a local holds an environment reference, and struct.new allocates garbage-collected pairs and closures. The merge code pairs with the value of to evaluate , then pairs with the result. The core linking term (1) needs only these operations, index lookup, records, and field selection. For multiple files, the backend emits a WebAssembly link module that imports unit entry points and links their results using the core construction of Theorem C.2. Saved linked units can likewise be compiled and linked again. Appendix C.2 gives the full rules; Appendix D traces the compilation of Add and Double.
5.3 Discussion and Limitations
The calculus is simply typed: signatures describe value exports, without ML-style abstract type components, sharing constraints, generativity, or polymorphism. These features would let separately compiled units hide representation choices and expose reusable interfaces over abstract types.
Subtyping offers a concrete next step. We could add an interface restriction : when the type of is a subtype of , a cast restricts its value to , discarding components outside that interface. This suggests the following module-application rule:
Here the inserted restriction supplies the functor's import interface. At the level of interfaces, this would allow applying Double directly to Add: restriction keeps only op. Application would thus perform import matching but return only the client's result: a form of linking as application. Disjointness at merges and context extensions would keep casts unambiguous. Such a discipline could draw on compositional programming [54] and type-directed operational semantics [21].
Sealing and polymorphism call for further extensions. One direction is to enrich the target with polymorphism and higher-order type operators, as in System , while retaining first-class environments. We could then investigate an elaboration in the style of F-ing modules [40], with the aim of supporting ML-style modules alongside first-class linking and environments.
6 Related Work
Program fragments and separate compilation. Cardelli's linksets (Section 2.2) formalize simply typed separate compilation, preserving typing under combination and linking [7]. SMLSC brings linksets to Standard ML [48]. Sewell proves that two ML-style structures build in sequence exactly when the second builds as a functor on the first [42]. Manifest types [26], Backpack [24] and MTAL [14] check units, packages and object files against imports. All link outside the language; none proves that linked code matches the merged sources. Corollary 4.13 proves this property.
Linking as a language construct. In Units, a compound expression links first-class units even inside functions [12]. Owens and Flatt type units [32]. Alice ML models components as functions of imports and static linking as an ordinary term [37]. MixML links mixins as a module construct [39]. Hirschowitz and Leroy compile a call-by-value CMS, a mixin calculus with mutual recursion, to a -calculus with records and let rec [3, 19]. These second-class mixins cannot be function arguments or results. Units and MixML support recursive linking, Owens and Flatt's units have type components, and Alice ML loads components at run time. These capabilities exceed ; none of these typed designs proves that linking compiled code agrees with the source link.
Flatt and Felleisen state no theorem. Owens and Flatt prove type soundness, and Rossberg states it unproved. MixML and Hirschowitz and Leroy prove only type safety, via typed translations. CMS and MM, a call-by-value mixin calculus, have reduction semantics [3, 20], but no compiler is proved against them. Lee and Friedman give two untyped calculi, and [25]. Source programs in are contexts (terms with holes), with no linking construct. They prove that primitive linking of compiled code agrees with compiling source contexts after meta-level hole filling. adds definitions, combined with seq and rec, whose compiled forms link compiled components. For , they prove no such theorem. In , a link is a source expression, reduced by rule S-LINKV, and Corollary 4.12 covers it, even at run time.
Units' implementation and Alice ML's semantics represent clients as functions of their imports. Units' formal model merges source text and contains no compiled code; Alice ML's static linking is only sketched. In , this form is the link's elaboration. Flatt and Felleisen argue informally for separate compilation of closed units; Lemma 4.1 proves that a sandboxed client compiles identically in every scope. Units and MixML check a component's body under its enclosing scope, as our open functors do [12, 39]. Alice ML instead uses a custom component manager to restrict imports at run time [37]. A sandboxed client is closed by typing and, once compiled, by its box, as in [51], wherever it is written, and Theorem 4.17 proves its confinement. Corollary 4.12 proves that the core linker agrees with source linking for every well-typed link, even under binders. We know of no other typed calculus with linking as an expression that states such a theorem.
Modules by elaboration. Module systems are often defined by elaboration [10, 38, 40]. Crary proves in Coq that his elaboration of ML modules is contextually correct and fully abstract [8]. These systems are richer than , with type abstraction, sharing and generativity, and full abstraction is stronger than our behavior preservation, which relates runs, not contextual equivalence. Yet none defines a linker for compiled fragments or a linking construct of its own. Harper and Lillibridge model linking as functor application and claim, without proof, that separate and whole-program compilation agree [16]. Corollary 4.13 proves a semantic counterpart for simple types.
Dynamic linking. Ancona et al. combine static and dynamic linking in one calculus, separating configuration and command languages [2]. They leave first-class linkset values as future work. In , links are ordinary expressions; providers and clients are first-class values. Links under binders realize Cardelli's suggestion of imports not restricted to the top level [6]. Drossopoulou et al., Assemblages, Acute, dynamic rebinding and TAL/Load model run-time code loading [11, 18, 27, 43, 44], covering lazy resolution, re-linking and versioning, which does not. They prove soundness (conjectured for Acute), and Drossopoulou et al. and dynamic rebinding also prove strategies equivalent. None proves that run-time linking of compiled code agrees with source linking.
Verified separate compilation. Verified compilers treat linking outside the source language. For SepCompCert, Kang et al. prove in Coq that linked, separately compiled C files refine the linked source, using whole-program correctness for passes that commute with linking [23]. CertiCoq's linker is a term template that plugs a library into an open client, and not every CertiCoq pass commutes with it [33]. Bowman and Ahmed link by substitution and prove that closure conversion commutes with it up to equivalence [5]. CakeML compiles code at run time but does not support partial compilation and linking [45]. SepCompCert and CertiCoq verify optimizing pipelines, far beyond our compiler. SepCompCert also relates I/O traces. has no I/O, and relates results and divergence. Still, none has a linking construct in its source, so commutation needs its own proof or fails. Nor do their theorems cover dynamic links. In , rule CL-LINK wraps compiled fragments in a fixed template, exactly the term that ELAB-LINK assigns to the source link. Commutation is thus a design property rather than a proof obligation, and Theorems 4.8 and 4.9 give correctness, static and dynamic.
Patterson and Ahmed distinguish linking with code from the same compiler, other compilers and other languages [34]. Ours is of the first kind, whereas Compositional CompCert, Pilsner, Perconti and Ahmed, and CompCertM cover the other kinds [30, 35, 46, 47]. Patterson and Ahmed warn that a theorem whose linker compiles source code is meaningless, as readers must trust the compiler. CL-LINK sees only compiled fragments and interfaces and emits a fixed template.
First-class environments. First-class environments turn bindings into values [13]; untyped languages use them for modules and run-time linking [22]. Queinnec and De Roure represent modules as functions of environments supplying their free variables [36]. Their import evaluates code in a supplied environment chained to the lexical one, but no theorem relates it to compiled code. The typed calculi of Nishizaki and Sato et al. prove subject reduction and confluence [31, 41], and Hashimoto and Ohori suggest contexts for run-time linking [17], but none states a linking theorem. encodes sandboxed modules as boxed functions, with no module types and no link [50, 51]. Like definitional interpreters [1], its metatheory avoids term substitution. Tan et al. [49] extend first-class environments to System F, supporting polymorphic modules with transparent type components, dynamic composition and sandboxing. Closure conversion also pairs closed code with environments, but translates a substitution-based source [28]. Over , adds the module language, links, the core linker and the separate compilation corollary. Commutation itself needs no first-class environments: any compositional translation of the link would do. They determine which links a program can write. A link can take the current scope as its provider, at a static type, and Corollary 4.12 covers it. A linked library can be the scope of a computation, as in box lib in e. Because a closure captures its whole environment, the box empties the environment of a compiled sandboxed client, even under a binder.
7 Conclusion
Separate compilation correctness needs an account of linking. Linking as evaluation makes that account the source semantics. The core linker emits the source link's elaboration, so compilation commutes with linking. Semantics and behavior preservation give links the same behavior at top level, under binders or at run time. Three ingredients shape the design: source reduction rules for linking, elaboration using only compiled operands and their interfaces, and contexts and interfaces as ordinary types, as in [50, 51]. Earlier work we know of has at most two. Cardelli's linksets, SMLSC and verified compilers lack source-level linking, and MixML and Alice ML define it only by translation. Units has the construct but merges source text. The first two yield separate compilation correctness, and the third decides which links a program can write.
Lean checks every proof, and the WebAssembly backend needs no linking instruction. Our results cover simple types. A concrete next step is subtyping, through an interface restriction. Polymorphic first-class environments [49] provide a starting point for extending our results to polymorphic modules. Sealing and higher-kinded polymorphism could build on a target that keeps first-class environments and adds the type operators of System , with an elaboration in the style of F-ing modules [40].
References
[1] Nada Amin and Tiark Rompf. 2017. Type soundness proofs with definitional interpreters. In Proceedings of the 44th ACM SIGPLAN Symposium on Principles of Programming Languages (POPL '17). ACM, 666–679. doi:10.1145/3009837.3009866 [2] Davide Ancona, Sonia Fagorzi, and Elena Zucca. 2003. A Calculus for Dynamic Linking. In Theoretical Computer Science. Springer, 284–301. doi:10.1007/978-3-540-45208-9_23 [3] Davide Ancona and Elena Zucca. 2002. A calculus of module systems. Journal of Functional Programming 12, 2 (March 2002), 91–132. doi:10.1017/s0956796801004257 [4] Andrew W. Appel and David B. MacQueen. 1994. Separate compilation for Standard ML. In Proceedings of the ACM SIGPLAN 1994 Conference on Programming Language Design and Implementation (Orlando, Florida, USA) (PLDI '94). Association for Computing Machinery, New York, NY, USA, 13–23. doi:10.1145/178243.178245 [5] William J. Bowman and Amal Ahmed. 2018. Typed closure conversion for the calculus of constructions. In Proceedings of the 39th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '18). ACM, 797–811. doi:10.1145/3192366.3192372 [6] Luca Cardelli. 1989. Typeful Programming. SRC Research Report 45. Digital Equipment Corporation, Systems Research Center, Palo Alto, CA. Revised January 1, 1993. [7] Luca Cardelli. 1997. Program Fragments, Linking, and Modularization. In Proceedings of the 24th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '97). ACM, 266–277. doi:10.1145/263699.263735 [8] Karl Crary. 2019. Fully abstract module compilation. Proceedings of the ACM on Programming Languages 3, POPL (Jan. 2019), 1–29. doi:10.1145/3290323 [9] N.G de Bruijn. 1972. Lambda calculus notation with nameless dummies, a tool for automatic formula manipulation, with application to the Church-Rosser theorem. Indagations Mathematicae (Proceedings) 75, 5 (1972), 381–392. doi:10.1016/1385-7258(72)90034-0 [10] Derek Dreyer, Karl Crary, and Robert Harper. 2003. A Type System for Higher-Order Modules. In Proceedings of the 30th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL 2003). ACM, 236–249. doi:10.1145/604131.604151 [11] Sophia Drossopoulou, Giovanni Lagorio, and Susan Eisenbach. 2003. Flexible Models for Dynamic Linking. In Programming Languages and Systems. Springer, 38–53. doi:10.1007/3-540-36575-3_4 [12] Matthew Platt and Matthias Felleisen. 1998. Units: Cool Modules for HOT Languages. In Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '98). ACM, 236–248. [13] David Gelernter, Suresh Jagannathan, and Thomas London. 1987. Environments as First Class Objects. In Proceedings of the 14th ACM SIGACT-SIGPLAN Symposium on Principles of Programming Languages (POPL). ACM, 98–110. doi:10.1145/41625.41634 [14] Neal Glew and Greg Morrisett. 1999. Type-Safe Linking and Modular Assembly Language. In Proceedings of the 26th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '99). ACM, 250–261. doi:10.1145/292540.292563 [15] Andreas Haas, Andreas Rossberg, Derek L. Schuff, Ben L. Titzer, Michael Holman, Dan Gohman, Luke Wagner, Alon Zakai, and JF Bastien. 2017. Bringing the web up to speed with WebAssembly. In Proceedings of the 38th ACM SIGPLAN Conference on Programming Language Design and Implementation (Barcelona, Spain) (PLDI 2017). Association for Computing Machinery, New York, NY, USA, 185–200. doi:10.1145/3062341.3062363 [16] Robert Harper and Mark Lillibridge. 1994. A Type-Theoretic Approach to Higher-Order Modules with Sharing. In Proceedings of the 21st ACM SIGACT-SIGACT Symposium on Principles of Programming Languages (POPL '94). ACM, 123–137. doi:10.1145/174675.176927 [17] Masatomo Hashimoto and Atsushi Otori. 2001. A typed context calculus. Theoretical Computer Science 266, 1-2 (Sept. 2001), 249–272. doi:10.1016/s0304-3975(00)00174-2 [18] Michael Hicks, Stephanie Weirich, and Karl Crary. 2001. Safe and Flexible Dynamic Linking of Native Code. In Types in Compilation. Springer Berlin Heidelberg, 147–176. doi:10.1007/3-540-45332-6_6 [19] Tom Hirschowitz and Xavier Leroy. 2005. Mixin modules in a call-by-value setting. ACM Transactions on Programming Languages and Systems 27, 5 (Sept. 2005), 857–881. doi:10.1145/1086642.1086644 [20] Tom Hirschowitz, Xavier Leroy, and J. B. Wells. 2004. Call-by-Value Mixin Modules: Reduction Semantics, Side Effects, Types. In Programming Languages and Systems, 13th European Symposium on Programming, ESOP 2004 (Lecture Notes in Computer Science), David Schmidt (Ed.). Springer Berlin Heidelberg, 64–78. doi:10.1007/978-3-540-24725-8_6
[21] Xuejing Huang and Bruno C. d. S. Oliveira. 2020. A Type-Directed Operational Semantics For a Calculus with a Merge Operator. In 34th European Conference on Object-Oriented Programming (ECOOP 2020) (Leibniz International Proceedings in Informatics (LIPlcs), Vol. 166). Robert Hirschfeld and Tobias Pape (Eds.). Schloss Dagstuhl – Leibniz-Zentrum für Informatik, Dagstuhl, Germany, 26:1–26:32. doi:10.4230/LIPlcs.ECOOP.2020.26
[22] Suresh Jagannathan. 1994. Metalevel building blocks for modular systems. ACM Transactions on Programming Languages and Systems 16, 3 (May 1994), 456–492. doi:10.1145/177492.177578
[23] Jeehoon Kang, Yoonseung Kim, Chung-Kil Hur, Derek Dreyer, and Viktor Vafeiadis. 2016. Lightweight Verification of Separate Compilation. In Proceedings of the 43rd Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '16). ACM, 178–190. doi:10.1145/2837614.2837642
[24] Scott Kilpatrick, Derek Dreyer, Simon Peyton Jones, and Simon Marlow. 2014. Backpack: retrofitting Haskell with interfaces. In Proceedings of the 41st ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (San Diego, California, USA) (POPL '14). Association for Computing Machinery, New York, NY, USA, 19–31. doi:10.1145/2535838.2535884
[25] Shinn-Der Lee and Daniel P. Friedman. 1996. Enriching the lambda calculus with contexts: toward a theory of incremental program construction. In Proceedings of the first ACM SIGPLAN international conference on Functional programming (ICFP96). ACM, 239–250. doi:10.1145/232627.232652
[26] Xavier Leroy. 1994. Manifest types, modules, and separate compilation. In Proceedings of the 21st ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (Portland, Oregon, USA) (POPL '94). Association for Computing Machinery, New York, NY, USA, 109–122. doi:10.1145/174675.176926
[27] Yu David Liu and Scott F. Smith. 2004. Modules with Interfaces for Dynamic Linking and Communication. In ECOOP 2004 – Object-Oriented Programming. Springer Berlin Heidelberg, 415–439. doi:10.1007/978-3-540-24851-4_19
[28] Yasuhiko Minamide, Greg Morrisett, and Robert Harper. 1996. Typed closure conversion. In Proceedings of the 23rd ACM SIGPLAN-SIGACT symposium on Principles of programming languages - POPL '96 (POPL '96). ACM Press, 271–283. doi:10.1145/237721.237791
[29] Leonardo de Moura and Sebastian Ullrich. 2021. The Lean 4 Theorem Prover and Programming Language. In Automated Deduction – CADE 28: 28th International Conference on Automated Deduction, Virtual Event, July 12–15, 2021, Proceedings. Springer-Verlag, Berlin, Heidelberg, 625–635. doi:10.1007/978-3-030-79876-5_37
[30] Georg Neis, Chung-Kil Hur, Jan-Oliver Kaiser, Craig McLaughlin, Derek Dreyer, and Viktor Vafeiadis. 2015. Pilsner: a compositionally verified compiler for a higher-order imperative language. In Proceedings of the 20th ACM SIGPLAN International Conference on Functional Programming (Vancouver, BC, Canada) (ICFP 2015). Association for Computing Machinery, New York, NY, USA, 166–178. doi:10.1145/2784731.2784764
[31] Shin-ya Nishizaki. 1994. Simply Typed Lambda Calculus with First-Class Environments. Publications of the Research Institute for Mathematical Sciences 30, 6 (Dec. 1994), 1055–1121. doi:10.2977/prims/1195164948
[32] Scott Owens and Matthew Flatt. 2006. From structures and functors to modules and units. In Proceedings of the eleventh ACM SIGPLAN international conference on Functional programming (ICFP06). ACM, 87–98. doi:10.1145/1159803.1159815
[33] Zoe Paraskevopoulou, John M. Li, and Andrew W. Appel. 2021. Compositional optimizations for CertiCoq. Proceedings of the ACM on Programming Languages 5, ICFP (Aug. 2021), 1–30. doi:10.1145/3473591
[34] Daniel Patterson and Amal Ahmed. 2019. The Next 700 Compiler Correctness Theorems (Functional Pearl). Proc. ACM Program. Lang. 3, ICFP, Article 85 (Aug. 2019), 29 pages. doi:10.1145/3341689
[35] James T. Perconti and Amal Ahmed. 2014. Verifying an Open Compiler Using Multi-language Semantics. In Programming Languages and Systems, Zhong Shao (Ed.). Springer Berlin Heidelberg, Berlin, Heidelberg, 128–148.
[36] Christian Queinne and David De Roure. 1996. Sharing Code through First-class Environments. In Proceedings of the First ACM SIGPLAN International Conference on Functional Programming (ICFP). ACM, 251–261. doi:10.1145/232627.232653
[37] Andreas Rossberg. 2006. The missing link: dynamic components for ML. In Proceedings of the eleventh ACM SIGPLAN international conference on Functional programming (ICFP06). ACM, 99–110. doi:10.1145/1159803.1159816
[38] Andreas Rossberg. 2018. 1ML – Core and Modules United. Journal of Functional Programming 28 (2018). doi:10.1017/S0956796818000205
[39] Andreas Rossberg and Derek Dreyer. 2013. Mixin' Up the ML Module System. ACM Transactions on Programming Languages and Systems 35, 1 (2013), 1–84. doi:10.1145/2450136.2450137
[40] Andreas Rossberg, Claudio Russo, and Derek Dreyer. 2014. F-ing Modules. Journal of Functional Programming 24, 5 (2014), 529–607. doi:10.1017/S0956796814000264
[41] Masahiko Sato, Takafumi Sakurai, and Yukiyoshi Kameyama. 2001. A simply typed context calculus with first-class environments. In Functional and Logic Programming, Herbert Kuchen and Kazunori Ueda (Eds.). Springer Berlin Heidelberg, Berlin, Heidelberg, 359–374.
[42] Peter Sewell. 2001. Modules, abstract types, and distributed versioning. In Proceedings of the 28th ACM SIGPLAN-SIGACT symposium on Principles of programming languages (POPL01). ACM, 236–247. doi:10.1145/360204.360225
[43] Peter Sewell, James J. Leifer, Keith Wansbrough, Francesco Zappa Nardelli, Mair Allen-Williams, Pierre Habouzit, and Viktor Vafeiadis. 2007. Acute: High-level programming language design for distributed computation. Journal of Functional Programming 17, 4-5 (July 2007), 547–612. doi:10.1017/s0956796807006442 [44] Peter Sewell, Gareth Stoyle, Michael Hicks, Gavin Bierman, and Keith Wansbrough. 2008. Dynamic rebinding for marshalling and update, via redex-time and destruct-time reduction. Journal of Functional Programming 18, 4 (2008), 437–502. doi:10.1017/s0956796807006600 [45] Thomas Sewell, Magnus O. Myreen, Yong Kiam Tan, Ramana Kumar, Alexander Mihajlovic, Oskar Abrahamsson, and Scott Owens. 2023. Cakes That Bake Cakes: Dynamic Computation in CakeML. Proceedings of the ACM on Programming Languages 7, PLDI (June 2023), 1121–1144. doi:10.1145/3591266 [46] Youngju Song, Minki Cho, Dongjoo Kim, Yonghyun Kim, Jeehoon Kang, and Chung-Kil Hur. 2020. CompCertM: CompCert with C-assembly linking and lightweight modular verification. Proceedings of the ACM on Programming Languages 4, POPL (Jan. 2020), 1–31. doi:10.1145/3371091 [47] Gordon Stewart, Lennart Beringer, Santiago Cuellar, and Andrew W. Appel. 2015. Compositional CompCert. In Proceedings of the 42nd Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '15). ACM, 275–287. doi:10.1145/2676726.2676985 [48] David Swasey, Tom Murphy VII, Karl Crary, and Robert Harper. 2006. A Separate Compilation Extension to Standard ML. In Proceedings of the 2006 Workshop on ML. ACM, 32–42. doi:10.1145/1159876.1159883 [49] Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira. 2026. Polymorphic First-Class Environments. arXiv:2610.36798 [cs.PL] https://arxiv.org/abs/2610.36798 [50] Jinhao Tan and Bruno C. d. S. Oliveira. 2023. Dependent Merges and First-Class Environments. In 37th European Conference on Object-Oriented Programming (ECOOP 2023) (Leibniz International Proceedings in Informatics (LIPics), Vol. 263), Karim Ali and Guido Salvaneschi (Eds.). Schloss Dagstuhl – Leibniz-Zentrum für Informatik, Dagstuhl, Germany, 34:1–34:32. doi:10.4230/LIPics.ECOOP.2023.34 [51] Jinhao Tan and Bruno C. d. S. Oliveira. 2024. A Case for First-Class Environments. Proc. ACM Program. Lang. 8, OOPSLA2, Article 360 (Oct. 2024), 30 pages. doi:10.1145/3689800 [52] Amin Timany, Robbert Krebbers, Derek Dreyer, and Lars Birkedal. 2024. A Logical Approach to Type Soundness. J. ACM 71, 6 (2024), 1–75. doi:10.1145/3676954 [53] A. K. Wright and Matthias Felleisen. 1994. A Syntactic Approach to Type Soundness. Information and Computation 115, 1 (1994), 38–94. doi:10.1006/INCO.1994.1093 [54] Weixin Zhang, Yaozhu Sun, and Bruno C. D. S. Oliveira. 2021. Compositional Programming. ACM Trans. Program. Lang. Syst. 43, 3, Article 9 (Sept. 2021), 61 pages. doi:10.1145/3460228
A Big-Step Semantics of
Figure 14 gives the big-step semantics used in Section 4.3. The lemmas below establish its equivalence with small-step evaluation (Theorem 4.4) and show that evaluation produces values.
(Big-step evaluation)
Fig. 14. Big-step semantics of .
LEMMA A.1 (SOUNDNESS OF BIG-STEP). If then .
LEMMA A.2 (COMPLETENESS OF BIG-STEP). If and is a value, then .
LEMMA A.3 (EVALUATION PRODUCES VALUES). If then is a value.
B Extensions
The following rules complete the extensions of Section 5.1.
B.1 Unions, Recursive Functions, and Recursive Types
Unions and recursion extend both calculi with the syntax of Figure 12 and the following runtime forms:
In the paper, types in judgments and annotations are closed: every type variable is bound by an enclosing . We write for capture-avoiding type substitution. The mechanization represents type variables by de Bruijn indices, and its fold constructor stores the body of the recursive-type annotation. The lemma elab_substTyp proves that type translation commutes with the mechanized substitution at any depth.
The core typing rules are obtained by replacing each judgment with and restricting all metavariables to the core syntax. Type preservation for fold and unfold uses the following lemma.
LEMMA B.1 (TRANSLATION COMMUTES WITH SUBSTITUTION). If is closed, then
The same frames and rules extend core reduction, with in place of throughout.
(Big-step evaluation: extensions)
\begin{aligned}&\text{EVAL-INJR}\\&\quad v\vdash e\Rightarrow v_{1}\\&\quad v\vdash\mathbf{inr}_{A}e\Rightarrow\mathbf{inr}_{A}v_{1}\\&\text{EVAL-CASER}\\&\quad v\vdash e\Rightarrow\mathbf{inr}_{A}v_{1}\quad v\text{,}v_{1}\vdash e_{2}\Rightarrow v^{\prime}\\&\quad\frac{v\vdash\mathbf{case}e\text{of}e_{1}\mid e_{2}\Rightarrow v^{\prime}}{\\&\text{EVAL-FIXAPP}\\&\quad v_{f}=\langle v_{1},\mathbf{fix}(A\rightarrow B).e\rangle_{f}\quad v\vdash e_{1}\Rightarrow v_{f}\\&\quad v\vdash e_{2}\Rightarrow v_{2}\quad v_{1}\text{,}v_{f}\text{,}v_{2}\vdash e\Rightarrow v^{\prime}\\&\quad\frac{v\vdash e_{1}e_{2}\Rightarrow v^{\prime}}{\text{EVAL-UNFOLD}}\\&\quad\frac{v\vdash e\Rightarrow\mathbf{fold}\left[\mu\alpha.A\right]v_{1}}{v\vdash\mathbf{unfold}e\Rightarrow v_{1}}\end{aligned}Rule EVAL-VAL covers the extended values. Replacing source judgments with core judgments gives the corresponding big-step rules.
B.2 Multi-Import Linking
Import interfaces D are defined in Figure 12.
(Interface satisfaction)
Elaboration and Core Linking. Figure 15 generalizes (1): builds the import package from a provider at index . Theorem B.3 establishes link typing under fragment typing and interface satisfaction. Unlike CL-LINK, rule CL-LINKN has no premise: Theorems B.3 and B.4 assume the satisfaction instead.
Fig. 15. Multi-import linking: elaboration, core linking, and the linking term for an import interface D. The term of (1) is the instance .
The right operand of each dependent merge uses index , since the left operand adds one environment entry. For & , the wire is , and the provider supplies the package .
Semantics. The judgment states that selecting the imports of from provider gives the package .
Two additional frames evaluate the provider and then the client under the ambient environment:
Properties.
LEMMA B.2 (WIRE TYPING). If and lookup then .
THEOREM B.3 (MULTI-IMPORT LINK TYPING). If , and then .
THEOREM B.4 (MULTI-IMPORT STATIC SEPARATE COMPILATION). Let with . Suppose , , and . Then clauses (a)–(c) of Corollary 4.12 hold for and , with .
PROOF SKETCH OF THEOREM B.4. Rules ELAB-LINKN and CL-LINKN produce the same core term under the theorem's premises. Theorems 4.8 and 4.9 then give clauses (a)–(c). □
As in Corollary 4.12, the result generalizes to a provider elaborated under and evaluation under a corresponding environment. Lemma 4.1 reuses the client's elaboration under unchanged.
For multi-import linking, the mechanized replacement law requires the replacement provider to preserve every extractable package, over all import interfaces.
THEOREM B.5 (MULTI-IMPORT INTERFACE REPLACEMENT). Suppose , and, for every and , implies . Then
If also , and then .
PROOF SKETCH. Reuse the client and body evaluations in rule EVAL-LINKN, with the replacement provider and the same import package. The equality follows from determinism (Theorem 4.15). □
The first part of Theorem B.5 needs no typing, and the theorem concerns only terminating runs. For typed provider values, a two-way law holds, the multi-import counterpart of Theorem 4.14. Providers that supply the same import package give the client the same exports, whatever they supply at other interfaces, and one link diverges exactly when the other does.
THEOREM B.6 (MULTI-IMPORT INTERFACE ABSTRACTION). Let and be values. Suppose , and, for , and . Then, for every value ,
and if and only if .
C Implementation Details
We give the unit-linking construction and WasmGC compilation used by SCE-Lang (Section 5.2).
C.1 Units and Linking
An importing file is represented by the sandboxed functor functor , with each read from 's interface file. An import-free file is a structure boxed under the empty environment.
Let be units in dependency order, with and import-free. Each elaborates independently under to , at type if import-free and otherwise. Write , , and for the source composition, core composition, and accumulated export type. Initially,
For an importing unit , require and set
For an import-free unit, set and construct from and using the encoding of rule ELAB-NMRG. In either case, . For binary chains, each importing unit has a singleton interface ; require and use . The core construction is unchanged.
THEOREM C.1 (UNIT-CHAIN CORRECTNESS). For a binary chain constructed above, , and clauses (a)–(c) of Corollary 4.10 hold for and at type .
THEOREM C.2 (MULTI-IMPORT UNIT-CHAIN CORRECTNESS). For a multi-import chain constructed above, , and clauses (a)–(c) of Corollary 4.10 hold for and at type .
PROOF SKETCH. Induct on the chain, starting from the first unit's elaboration. Each extension uses ELAB-LINK or ELAB-LINKN for an importing unit, and ELAB-NMRG for an import-free unit. Corollary 4.10 then gives clauses (a)–(c). □
For WebAssembly, a link module imports unit entry points and compiles the same composition with environment projections for their results (Appendix D.3).
C.2 Compilation to WebAssembly
Figure 16 compiles well-typed program terms of extended (Appendix B); runtime closures are not compilation inputs. Field selection uses the inferred type of its operand. The Wasm backend represents integers and performs arithmetic with i32, so the literal rule is restricted to signed 32-bit integers.
C[env]_ρ = local.get ρ C[ε]_ρ = global.get I32Box C[e.n]_ρ = C[e]_ρ L^n R C[e.l]_ρ = C[e]_ρ P(A,l) ref.cast(ref Lrec value C{{l = e}}_ρ = i32.const τ_lrec B(l) C[e]_ρ struct.new Pair local.set ρ' i32.const τ_mrg local.get x C[e_2]_ρ' struct.new f local.get ρ struct.new f(self,x) is i32.const τ_mrg local.get self ref.cast(ref Clos env local.get x struct.new Clos) struct.get Fn
L = ref.cast(ref Pair left R = ref.cast(ref Pair right B(l) = i32.const off_l i32.const len_l array.new_data strings P({l : A}, l) = [] P(A & B, l) = L P(A, l) if l ∈ label(A), l ∉ label(B) P(A & B, l) = R P(B, l) if l ∉ label(A), l ∈ label(B).
Fig. 16. WasmGC compilation of extended (1/2): the base calculus. The local holds the environment, and is the tag for constructor . Introduced locals are fresh; each compiled term leaves one value reference on the stack. In selection, is the inferred type of . Juxtaposition concatenates instruction sequences; repeats times. The pair locates in the passive data segment .
\begin{aligned} C[\text{fix}(A \to B). e]_\rho &= \begin{cases} \text{i32.const } \tau_{\text{fclos}} \text{ ref.func } $f \text{ local.get } \rho \\ \text{struct.new } \$Clos \\ \text{where the fresh lifted function } $f(\text{self}, x) \text{ is} \\ \quad \text{i32.const } \tau_{\text{mrg}} \quad \text{i32.const } \tau_{\text{mrg}} \\ \quad \text{local.get self ref.cast (ref } \$Clos) \text{ struct.get } \$Clos \text{ env} \\ \quad \text{local.get self struct.new } \$Pair \text{ local.get } x \\ \quad \text{struct.new } \$Pair \text{ local.set } \rho' \quad C[\text{e}]_\rho' \end{cases} \\ C[\text{inl}_B e]_\rho &= \text{i32.const } \tau_{\text{inl}} \quad C[\text{e}]_\rho \text{ struct.new } \$Wrap \\ C[\text{inr}_A e]_\rho &= \text{i32.const } \tau_{\text{inr}} \quad C[\text{e}]_\rho \text{ struct.new } \$Wrap \\ C[\text{case } e \text{ of } e_1 \mid e_2]_\rho &= \begin{cases} C[\text{e}]_\rho \text{ local.set } u \\ \text{local.get } u \text{ struct.get } \$Val \text{ tag} \\ \text{i32.const } \tau_{\text{inl}} \quad \text{i32.eq} \\ \text{if (result (ref null } \$Val)) \\ \quad \mathcal{E}(\rho, u, \rho_1) \quad C[\text{e}_1]_{\rho_1} \\ \quad \text{else} \\ \quad \mathcal{E}(\rho, u, \rho_2) \quad C[\text{e}_2]_{\rho_2} \\ \text{end} \end{cases} \\ C[\text{fold } [\mu a.A] e]_\rho &= \text{i32.const } \tau_{\text{fold}} \quad C[\text{e}]_\rho \text{ struct.new } \$Wrap \\ C[\text{unfold } e]_\rho &= C[\text{e}]_\rho \text{ ref.cast (ref } \$Wrap) \text{ struct.get } \$Wrap \text{ value} \\ \mathcal{E}(\rho, u, \rho') &= \begin{cases} \text{i32.const } \tau_{\text{mrg}} \text{ local.get } \rho \text{ local.get } u \\ \text{ref.cast (ref } \$Wrap) \text{ struct.get } \$Wrap \text{ value} \\ \text{struct.new } \$Pair \text{ local.set } \rho' \end{cases} \\ \text{Val tag:i32} \quad \$I32Box \text{ tag:i32, n:i32} \\ \text{Pair tag:i32, left:V, right:V} \quad \$Lrec \text{ tag:i32, label:B, value:V} \\ \text{Clos tag:i32, fn:F, env:V} \quad \$Wrap \text{ tag:i32, value:V} \\ V = (\text{ref null } \$Val), \quad B = (\text{ref null } \$Bytes), \quad F = (\text{ref null } \$Fn) \\ \text{Bytes = (array (mut i8))}, \quad \$Fn : (V, V) \to V, \quad \$UnitFn : () \to V. \end{aligned}Fig. 16. WasmGC compilation of extended (2/2): unions and recursion, with runtime layouts in field-index order. Struct fields are immutable; each struct except is a final subtype of . Value locals and results have type . The global is a with tag 3. Tags for integers, merges, records, closures, recursive closures, left and right injections, and folds are 0, 4, 5, 6, 7, 8, 9, 10, respectively.
D The Double Example Through Compilation
The files of Figure 1 appear below in the paper's surface notation.
Add.scei
sig op : Int -> Int -> Int unit : Int end
Add.sce
module Add = struct let op (x y : Int) : Int = x + y let unit : Int = 0 end
Double.scei
sig double : Int -> Int end
Double.sce
import Add module Double = struct let double (x : Int) : Int = Add.op x x end
D.1 Link, Then Compile
The unit wrappers give the following top-level link S:
link (sandbox struct module Add = struct let op (x y : Int) : Int = x + y let unit : Int = 0 end
end) with sandbox functor (M : { Add : sig op : Int -> Int -> Int; unit : Int end }) -> open M in struct module Double = struct let double (x : Int) : Int = Add.op x x end end
We abbreviate the core terms below, with . Identity applications and the internal label %open are retained from the compiler output.
.
Compiling S gives
The linked library exports Add and Double, and S.Double.double 5 evaluates to 10.
D.2 Compile, Then Link in the Core
Compiling the files independently produces:
The core linker selects Add for the client's import and produces
Both routes produce the same core term, with
D.3 Compile, Then Link in WebAssembly
The core units compile to separate modules, each exporting main : () -> (ref null $Val):
If their entry points return and , the link module constructs and executes the compiled term . The listing uses symbolic type and function names and omits shared type declarations and rendering support.
Lib.wasm
(module ; Shared types and rendering support omitted. (import "u0" "main" (func UnitFn))) (import "ul" "main" (func UnitFn))) (global Val) (struct.new labels "Add") (elem declare func link1)
(func UnitFn) (local (ref null Val) (ref null unit local.set 0 i32.const 4 local.get 0 call Pair local.set 0 i32.const 4 local.get 0 call Pair local.set 0 i32.const 6 ref.func Clos local.tee 1 local.get 0 ref.cast (ref Pair 1 ref.cast (ref Pair 2 local.get 1 ref.cast (ref Clos 1 call_ref Pair) struct.get Clos) struct.get Fn )
Lib.wasm (continued)
(func Fn) (local (ref null Clos) struct.get Pair local.set 2 i32.const 6 ref.func Clos )
(func Fn) (local (ref null Val) (ref null Val)) i32.const 4 local.get 0 ref.cast (ref Clos 2 local.get 1 struct.new Pair) struct.get Pair) struct.get Pair local.set 4 i32.const 4 local.get 3 local.get 4 ref.cast (ref Pair 1 ref.cast (ref Pair 2 local.tee 5 i32.const 5 i32.const 0 i32.const 3 array.new_data labels local.get 4 ref.cast (ref Pair 2 ref.cast (ref Lrec 2 struct.new Clos) struct.get Fn struct.new $Pair ) ;; sce.units: Add, Double )
Each unit and the link module declares the same recursive group of ABI types (Figure 16), allowing values to pass between instances. The host supplies the unit entry points and calls the linker:
const imports = { u0: { main: add.exports.main }, u1: { main: double.exports.main } }; const lib = new WebAssembly.Instance(linkModule, imports); const result = lib.exports.main();
The linked result, rendered by the implementation, is
{ Add = { op = <fun>, unit = 0 }, Double = { double = <fun> } }
Calling its Double.double function on 5 returns 10, as in Sections D.1 and D.2.