Manuscript Offprint
arXiv:2610.36798Polymorphic First-Class Environments
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
JINHAO TAN, The University of Hong Kong, China
JAM KABEER ALI KHAN, The University of Hong Kong, China
BRUNO C. D. S. OLIVEIRA, The University of Hong Kong, China
First-class environments expose runtime environments as ordinary values and support a substitution-free, environment-based operational semantics. They also support applications such as first-class modules, dynamic composition of environment fragments, and sandboxing via local environments. Existing environment-based calculi, however, are mostly studied in a simply typed setting and stop short of System F and polymorphism.
We present , a polymorphic calculus with first-class environments that conservatively extends System F with a small-step environment semantics. eliminates all forms of substitution in System F. Term and type abstractions evaluate to closures, boxes run code under local environments, and box types expose the local typing assumptions of both. Manifest types, together with a two-sided type equivalence, play a dual role: they model type-level instantiation, and enable transparent type components in environments and modules. We prove type soundness, normalization, decidability and standard properties of type equivalence, and conservativity over System F. The metatheory of is based on instantiation lemmas rather than substitution lemmas. This foundation supports polymorphic first-class modules with dynamic composition and sandboxing. We study in two forms. Our main presentation is an explicit, type-passing calculus that follows conventional System F. We also develop an implicitly-typed variant aligned with the semantics of polymorphic functional languages. All metatheory is mechanized in the Rocq theorem prover.
1 Introduction
Runtime environments are central to programming language implementations. They record the bindings used to execute code, but programmers usually cannot manipulate them directly in the language. First-class environments [Gelernter et al. 1987; Miller and Rozas 1991; Nishizaki 1994, 2000; Queinnec and Roure 1996; Sato et al. 2001, 2002; Shutt 2010; Tan and Oliveira 2023] turn these environments into ordinary values that can be created, passed, inspected, and composed. Once environments become first-class, they can serve not only as a runtime device, but also as a programming construct for controlling the context in which code executes.
Recent work shows that first-class environments already support several useful forms of modularity. In [Tan and Oliveira 2024], environment fragments can act as first-class modules and can be composed dynamically through dependent merges [Tan and Oliveira 2023]. Boxes of the form evaluate under the local environment , giving a direct account of sandboxing. Because the supplied environment determines which bindings and resources are available during execution, the same mechanism also supports capability-style modularity, making authority explicit [Melicher et al. 2017; Miller 2006; Miller et al. 2000, 2008].
First-class environments are also attractive semantically. Standard presentations of the lambda calculus and System F organize reduction and metatheory around capture-avoiding substitution, while implementations execute programs with closures and environments. This mismatch has motivated several lines of work that aim to eliminate or internalize meta-substitution, from explicit substitutions [Abadi et al. 1991; Curien et al. 1996] to explicit environments and environment-based semantics [Nishizaki 1994, 2000; Sato et al. 2001; Tan and Oliveira 2024]. In an environment-based account, bindings are carried explicitly at runtime rather than propagated by substitution. Such a semantics is closer to implementations and can also be attractive for mechanization.
Authors' Contact Information: Jinhao Tan, jhtan@cs.hku.hk, The University of Hong Kong, Hong Kong, China; Jam Kabeer Ali Khan, jamkhan@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.
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
For calculi with first-class environments, the simply typed case is now reasonably well understood, but the polymorphic case remains a key challenge. , for instance, is conservative over the Simply Typed Lambda Calculus and stops short of System F. Extending first-class environments from the simply typed setting to System F requires more than adding universal quantification. In a standard presentation of System F, substitution appears in three places: term beta-reduction, type beta-reduction, and type instantiation at type application. An environment-based semantics already gives a natural account of term substitution through closures, and the same operational idea can be used for type abstractions. But this polymorphic setting introduces further typing problems as well: closures and boxes must now carry enough information to track local typing assumptions compositionally.
This paper presents : a calculus with polymorphism and first-class environments. introduces two central devices. Box types expose the local typing assumptions needed to type closures and boxes in the presence of polymorphism, so polymorphic environments can be typed compositionally. Manifest types have a dual role. Semantically, they model type-level instantiation. The same mechanism is also what supports manifest type components in modules, as found in ML-style module systems [Leroy 1994; MacQueen 1984; Milner et al. 1997; Rossberg 2018; Rossberg and Dreyer 2013] and related designs with type members [Amin et al. 2014]. Unlike ML modules, supports only transparent type components, while sealing is left to future work (Section 6.3). Manifest types are the sole mechanism for type instantiation in , avoiding a second, meta-level mechanism that would have to interact with type equivalence. preserves a substitution-free, environment-based account and remains conservative over System F.
The resulting metatheory differs substantially from standard developments of System F. Traditional System F metatheory relies heavily on substitution lemmas. In these are replaced by instantiation lemmas, which describe how typing is preserved when moving between universal types and their manifest instantiations. Combined with de Bruijn indices and an environment-based semantics, this yields a direct mechanization in Rocq. We develop in two forms. The first form is an explicit, type-passing calculus, which is our main focus in the paper. It follows the conventional presentation of System F, with explicit type abstractions and applications. Although this calculus passes types at run time, types are computationally irrelevant: we prove that a type-erasing semantics reaches the same results. The second form is an implicitly-typed variant that aligns with the semantics of polymorphic functional languages.
supports capability-style modules that combine dynamic module composition with polymorphism and manifest type components. Environment fragments remain first-class and compositional, supporting dynamic assembly, while boxes run code under explicit local environments, supporting sandboxing. Manifest type components make type information transparently available across module boundaries, so this form of capability-style modularity extends beyond the simply typed setting. isolates how first-class environments scale to polymorphism through explicit local typing assumptions, manifest type components, and type equivalence. is thus a System F-level core for polymorphic instantiation, dynamic composition, and sandboxing through first-class environments. Contributions. This paper makes the following contributions:
-
A polymorphic first-class-environment calculus that gives a uniform object-level account of polymorphic instantiation, transparent type components, and environment-based execution, while conservatively extending System F with a substitution-free small-step semantics.
-
Box types for explicit local typing assumptions, and manifest types with two-sided type equivalence, which express type-level instantiation without substitution and support transparent type components in environments and modules.
-
Type soundness, normalization, and decidable type equivalence (with reflexivity, symmetry, and transitivity), conservativity over System F, and a substitution-free metatheory based on instantiation lemmas rather than substitution lemmas.
-
A full Rocq mechanization of the metatheory, covering the explicit calculus, an implicitly-typed variant aligned with the semantics of polymorphic functional languages, and type-preserving elaboration of simple form of first-class modules into , plus a prototype implementation.
The mechanization and implementation are available online. The examples can be run and modified in our online playground: https://jam-khan.github.io/EnvML/
2.1 Background: First-class Environments and
The calculus [Tan and Oliveira 2024] is a call-by-value statically typed calculus that provides first-class environments for the Simply Typed Lambda Calculus (STLC). The principle of introducing first-class environments in is to model typing contexts as types, and runtime environments as values. Therefore, the box expression , which runs an expression under an environment , can be easily supported in . Moreover, unlike conventional calculi that typically employ a small-step semantics with substitution, adopts a substitution-free environment-based semantics. As a result, de Bruijn indices [De Bruijn 1972] for variable representation work well in , as one does not need to define or reason about substitution. To incorporate the environment-based semantics, also supports function closures , which represents a lambda abstraction closed under the environment . Since de Bruijn indices are used in the binders are nameless (i.e. without an explicit variable name). The typing rules of boxes and closures are defined as follows:
To type check a box expression , we first type check the environment against its type , which represents the typing context for . Then, we type check the body expression under the context . Similarly, the type of the value environment in a closure provides the typing context for the function . Note that in a box or closure, the body expression may bind variables from the local context . However, in a setting with simple types, the type of the body expression does not depend on , as types do not contain type variables in .
Small-step environment semantics. While environment-based semantics is commonly presented with a big-step semantics [Kahn 1987], employs a small-step semantics. In particular, just like term application in STLC, box evaluation in also follows left-to-right reduction:
The evaluation of boxes fits well with the environment-based reduction . The local environment is evaluated to a value environment under the global environment first (rule STEP-BOXL). As seen in rule STEP-BOXR the global environment is replaced by , when evaluating . Therefore cannot refer to bindings in and boxes provide a sandboxing mechanism where computations execute within an isolated and controlled environment . In rule STEP-BOXV, when both the environment and body are values, the box reduces to the body's value.
https://github.com/tjhao/PolyFirstClassEnvs
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
Importantly, besides enabling first-class environments, the box construct is the key device that naturally enables the environment-based semantics to be small-step in . A standard big-step environment-based semantics specifies the entire transition from an expression to a final value in one big step. Instead, the beta reduction in breaks down the evaluation into smaller steps with the help of the box construct:
Instead of evaluating the application directly to a value, stores the intermediate result as a box: the body expression e is boxed by the environment that extends with the argument value v. The box will then be further reduced through the box reduction rules. This design allows to maintain a small-step semantics, while avoiding substitution.
2.2 Three Forms of Substitution in System F
System F [Girard 1972; Reynolds 1974] exhibits greater expressive power than the STLC by introducing parametric polymorphism through type abstraction and type application. Moreover, System F is also more interesting regarding formalization. This is primarily due to its inclusion of type variables, which are bound within the environment. When type checking a type abstraction, one type variable binding is added to the context. Therefore, the typing context in System F contains both term variable bindings and type variable bindings:
(Named representation)
(De Bruijn representation)
Above are two representations of typing contexts in System F, where unifies term and type bindings in a single context structure. The conventional named representation contains term variable bindings , and type variable bindings , . In the de Bruijn representation, variables are nameless: , is a term variable binding with type , and a type variable binding is just a tag . and its metatheory adopt the de Bruijn representation throughout.
The introduction of polymorphism gives rise to more forms of substitution. The distinct forms of substitution required in System F are illustrated by the following rules (written in a de Bruijn style):
To summarize, in System F we have:
-
term-into-term substitution: replacing a term variable with a term, as in , which occurs during beta reduction.
-
type-into-term substitution: replacing a type variable with a type in a term, as in , which occurs during type application when reducing .
-
type-into-type substitution: replacing a type variable with a type within a type, as in B[0 A], which is needed to compute the result type of a type application.
The first form of substitution arises from term-level beta reduction, and the calculus already provides a solution to eliminate this form of substitution. Nevertheless, the second and third forms of substitution come from type application and they are unique to polymorphic calculi. This proliferation of substitution forms significantly complicates the metatheory of polymorphic calculi. Our first goal is to eliminate all three forms of substitution from the calculus, replacing them with an environment-based approach that enables first-class environments.
2.3 Bringing First-class Environments to System F
Contexts as types. Following , which views typing contexts as types, to extend System F with first-class environments, we first extend the syntax of types to include typing contexts:
Types
Contexts
In the above syntax, a type variable is represented by the de Bruijn index . The type syntax now also includes contexts: the empty context , a term binding , , and a type-variable binding . The typing contexts of System F then form a subset of the types. Including contexts into types is a first-step to incorporate first-class environments into System F. However, more changes are necessary to eliminate all forms of substitution in System F.
A hint notation for de Bruijn indices. The formal calculus uses de Bruijn indices for both term and type variables. Raw de Bruijn examples are hard to read, so we use a lightweight hint notation in examples. Greek letters hint type indices: denotes index 0, denotes index 1, and so on; roman letters play the analogous role for term indices. These hints are not names and are not part of the formal syntax. Binder annotations are shown in gray only to help the reader see which binder an occurrence is intended to refer to. Deleting the gray annotations and replacing each hinted variable by its corresponding index recovers the formal de Bruijn term.
Because the hints follow de Bruijn indices rather than binders, the notation is partial. A single binder may be represented by different indices in different scopes, in which case no single hint can name it consistently. Conversely, the same index may refer to different binders in different scopes. In examples we may use subscripts such as and only to distinguish these occurrences for the reader, although both are still index 0 formally. The table below shows the cases that matter for the examples in the paper.
| pure de Bruijn notation | hint notation | |
|---|---|---|
| unambiguous | ||
| irrelevant | ||
| disambiguated | ||
| irrepresentable | - |
The unambiguous case is the usual one: each hinted occurrence refers to a binder at a consistent index. In the irrelevant case, the outer binder is unused, so any gray hint for it is harmless. The disambiguated case shows that one index can refer to different binders in different scopes. The subscripts separate these reader hints, not formal indices. The irrepresentable case shows the limitation of the notation: the outer binder is seen as index 0 before the inner binder and as index 1 under it, so it would need to be displayed both as and as . Every hinted example used in the paper is representable. A table in Appendix A gives the corresponding raw de Bruijn forms.
From term-level substitutions to environments. The elimination of term-into-term substitution is already achieved by . Now we consider type-into-term substitution. It is natural to apply the same recipe that uses for term abstractions/applications also for type abstractions and type applications. Specifically, for type abstractions , we introduce type abstraction closures that capture the current runtime environment . Furthermore, type application reduces to a box whose local environment combines the closure's environment with the type argument. For instance, suppose that . id is a polymorphic identity function and id is a lambda expression of type . The evaluation of type application . id) Int proceeds:
Here type argument Int is pushed into the box as part of the local environment. At this point, the local environment contains all the concrete type information that the body relies on. The box will then be further evaluated to a closure, where id is closed with the environment containing the type argument . Since type application introduces concrete type arguments into environments, the syntax of types and contexts needs to be extended for concrete type information:
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
Types A, B ::= ... | , [A]
Contexts
Besides term bindings ( , A), now we have two kinds of type variable bindings: , represents an abstract type binding (like a universally quantified type parameter with no definition), and , [A] represents a manifest type binding (a type variable bound to a concrete definition A). Manifest type bindings serve as explicit type equalities, enabling visible type definitions in a typing context.
Typing boxes and closures. While the dynamic semantics for applications can be adapted from , typing for closures and boxes requires some care. Now that runtime environments contain type entries, the types of closures and boxes need to be closed under their corresponding typing contexts, which may contain type variable bindings. Take as an example. Expression id has type , and type variable should refer to the entry stored in the environment. Therefore, the type of the closure is supposed to be closed with respect to this type information. To achieve this, we extend the syntax of types by introducing box types:
Intuitively, box types act analogously to function closures, in the sense that they are enclosed over their defining context . For example, closure has the box type , indicating that within the box, type variable is defined to be Int.
Manifest types. Since we have manifest type binding [A] entries in the environment, it is natural to have a type that corresponds to such entries. Such a type is a manifest type [A]B, extending the syntax of types as follows:
The manifest type B represents “B where type variable is instantiated to A” and is the type-level analogue of extending a context with the manifest binding [A] and then reading B under that extended context. We will see in the next section how this construct eliminates type-level substitution from type application.
2.4 Eliminating Type-level Substitutions
This subsection explains how manifest types record type instantiations at the object level, while type equivalence recovers the usual instantiated types.
Typing type application with manifest types. With manifest types, the typing rule for type application uses no meta-level substitution:
Similar to universal types, manifest types reserve a slot for the type argument. However, while universal types bind type variables abstractly (with ), manifest types bind them concretely (with [A]). Thus type application can instantiate type variable directly within the body type. We examine the above typing rule with type application ( ) Int, where the type of id is . The outer type application instantiates to Int, and the inner type application ( instantiates to . The typing derivation of this example is:
From the outer type application, we know that will be instantiated to Int. However, when typing the inner type application ( .id) , type variable is open, in that it is abstractly bound by instead of being associated with any concrete type instantiation. In the second line of the derivation, manifest type keeps open and assigns to . Then, after the outer type application, manifest type further instantiates with Int. Hence, concrete type information propagates naturally, without requiring meta-level substitution.
Type equivalence. Semantically, contains sufficient manifest bindings to ensure that it is essentially equivalent to . Nevertheless, the two types are syntactically distinct, so recovering the instantiated type requires a notion of type equivalence. Importantly, this need is not created by our treatment of type application: unlike System F, needs type equivalence in any case, since manifest type bindings and box types already relate syntactically different types. For instance, the type variable is equivalent to under the context , , and the box type of the closure in Section 2.3 is just . Type equivalence is also key for modeling modules with transparent type components (Section 2.5). The type equivalence judgment relates a type A under a context to a type B under a context . The judgment is two-sided because the two types may be read under different contexts: discharging a manifest type extends the context on one side with a manifest binding, and comparing a box type switches to its local context on one side. Concrete type variables are resolved by fetching their manifest bindings. These rules, together with standard structural rules, form the full relation (Section 3.2). Typing employs equivalence through rule TYP-TEQ, which replaces the type of an expression with an equivalent one:
Manifest types as the sole mechanism for type substitution. Keeping System F’s meta-level substitution for type application (Section 2.2) alongside manifest types would yield two mechanisms for type instantiation in the same calculus: manifest types [A]B express “B with index 0 instantiated to A” at the object level, while meta-level substitution B[0 A] expresses the same at the meta-level. Maintaining both would require proving that the two mechanisms interact correctly—in particular, that substituting into equivalent types preserves equivalence:
Proving such a lemma would require the full machinery of de Bruijn substitution—generalized statements over decomposed contexts, weakening, renaming, and shifting—on top of the type equivalence development.
We avoid this redundancy by using manifest types as the sole mechanism for type substitution. Because manifest types are an object-level construct, they participate directly in the type equivalence relation that requires anyway. Discharging a manifest type is just a rule of the equivalence judgment, not a lemma about the interaction of two distinct mechanisms. The result is a simpler calculus and a lighter metatheory.
Substitution-free metatheory. In System F, substitution lemmas are central to proving type preservation and other metatheoretical properties. In particular, for type application, we need the following substitution lemma to deal with type substitution:
LEMMA 2.1 (SUBSTITUTION LEMMA). If and , then .
The first premise arises from the typing rule for type abstractions, which extends the context with an abstract type binding when checking a type abstraction against a universal type . The conclusion states that type application preserves typing by type substitution in both the body
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
expression e and body type B. Essentially, the substitution lemma guarantees that the instantiation of type variables with concrete types does not violate type safety.
In our calculus, the substitution lemma is replaced by an instantiation lemma that directly captures the essence of type variable instantiation without involving substitution:
LEMMA 2.2 (INSTANTIATION LEMMA). If and , then .
Rather than performing meta-level substitution, instantiation is achieved directly through manifest type bindings: an expression well-typed under an abstract type binding remains well-typed when that binding is replaced by a manifest binding. Due to the presence of type equivalence, we also need an instantiation lemma for type equivalence. Two types that are equivalent under an abstract binding remain equivalent when the binding is replaced by equivalent manifest bindings.
LEMMA 2.3 (INSTANTIATION). If and , then .
Traditional approaches reason about syntactic equality between meta-level substitutions [Vouillon 2012]. reasons about definitional equivalence between object-level types.
2.5 Applications: Sandboxed Modules
This subsection illustrates that enables a form of sandboxed modules. Three key features are illustrated: 1) first-class modules can be passed to and returned from functions; 2) module fragments can be composed dynamically, at run time, and this composition still preserves the dependencies of later entries on earlier ones; and 3) the modules are sandboxed and cannot access definitions in the ambient environment. The last point is what enables a capability-style programming discipline [Miller 2006; Miller et al. 2000, 2008]: any capability a module needs must be passed to it explicitly [Melicher et al. 2017]. Features 2) and 3) are what set apart from classical module systems such as ML modules [Leroy 1994; MacQueen 1984; Milner et al. 1997; Rossberg 2018; Rossberg and Dreyer 2013]. There, composition is static: functors are applied to arguments that match fixed signatures. In , modules are first-class values composed dynamically. Independently written fragments are merged at run time while preserving the dependencies of later components on earlier ones—something that a (dependent) record, whose fields are fixed at definition time, cannot express. Sandboxing, likewise, is not part of the classical module picture.
The calculus already provides simple sandboxed modules [Tan and Oliveira 2024]: a module that takes other modules as arguments is boxed under the empty environment, so it acts only through the arguments passed to it. inherits boxes—and thus sandboxing—from , and adds polymorphism and manifest type components.
Manifest type bindings enable modules with transparent type components. 's environments are , where is a term component and a type component. Environments are ordered: a later entry may depend on earlier ones, and the typing rules capture this directly:
Each entry is typechecked under the combined context , where collects the types of preceding entries. A type definition introduces a manifest type binding. Later entries can refer to the defined type at the type level. Our concrete examples use an ML-like surface syntax (module type, sig, struct) only because it is familiar. Our focus is not on ML features such as opaque type components or sealing (which does not support), but on 's runtime-composable environments with type entries that this syntax elaborates into.
Modules as first-class environments. Consider a data-access system whose access policies control how query results are returned—which elements, in what order—without inspecting the data. A policy is polymorphic in the element type, so its module type module type ACCESS_POLICY = forall t. sig val reshape : List<t> → List<t>; end;
translates in to a universal type over a one-entry context, . More generally, a signature translates to a context and a module implementation to an environment. Modules are first-class: makeQuery turns a policy into an integer-specialized query module,
module makeQuery (policy : ACCESS_POLICY) : (sig type a = Int; val query : List<a> → List<a>; end) = struct type a = Int; let query : List<a> → List<a> = (policy @ a).reshape; end;
whose output type is the context ·, [α = Int], {query : List<α> → List<α>}. Here the type component a is transparently equal to Int, and query instantiates the policy at a and takes its reshape.
Dynamic composition. Beyond building a single module, supports dynamically composing modules. The module assemble takes a query module and an audit module , concatenates them, and appends a report function that feeds 's query result to 's decide:
module assemble (m1 : sig type a = Int; val query : List<a> → List<a>; end) (m2 : sig type b = Bool; val decide : List<Int> → b; end) = m1 + m2 + struct let report : List<Int> → Bool = fun (xs) → m2.decide(m1.query(xs)); end;
Concretely, the operator + concatenates the two fragments' environments. It appends the entries of the second environment after those of the first, forming a single environment. The composition is dynamic: m1 and m2 are unknown when assemble is defined and are supplied only at application time. We use assemble to compose two concrete modules. First, previewPolicy keeps only the first two elements as a preview window, and makeQuery turns it into the query module previewQuery:
module previewPolicy : ACCESS_POLICY = (type t) → struct let reshape : List<t> → List<t> = take(2); end; module previewQuery = makeQuery(previewPolicy);
We then define an audit module audit that decides whether a result list is non-empty, and compose previewQuery and audit into previewProcessor using assemble:
module audit = struct type b = Bool; let decide : List<Int> → b = fun (xs) → length(xs) > 0; end; module previewProcessor = assemble(previewQuery)(audit);
In , previewProcessor corresponds to the dependent environment
Dependencies are preserved after composition: query still refers to the type component a and decide to b, and the appended report builds on both.
Sandboxing. Composition and sandboxing work together: a sandboxed module runs with no ambient bindings, so its authority is exactly the capabilities passed as arguments. Handing the assembled previewProcessor to a sandboxed module thus grants it precisely the authority it was assembled from, and nothing else. Suppose queries run for external clients and must not reach sensitive global resources such as database credentials, audit logs, or administrative APIs. The module executeQuery below takes a query processor proc as its only argument and runs its report:
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
De Bruijn indices
Types
A, B, C ::= Int | N | A → B | ∀A | Γ ▷ A | [A]B | · | Γ, A | Γ,★ | Γ, [A]
Contexts
Γ ::= · | Γ, A | Γ,★ | Γ, [A]
Expressions
e ::= i | n | λe | e₁ e₂ | ∧e | e A | ⟨δ | λe⟩ | ⟨δ | ∧e⟩ | e₁ ▷ e₂ | · | e₁, e₂ | e, [A]
Environments
Δ ::= · | Δ, e | Δ, [A]
Values
v ::= i | ⟨δ | λe⟩ | ⟨δ | ∧e⟩ | · | v₁, v₂ | v, [Γ ▷ A]
Value environments
δ ::= · | δ, v | δ, [Γ ▷ A]
Frames
F ::= [ ] e | v [ ] | [ ] A | [ ] ▷ e | [ ], e | [ ], [A]
Fig. 1. Syntax of the calculus.
module executeQuery (proc : sig type a = Int; val query : List<a> → List<a>; type b = Bool; val decide : List<Int> → b; val report : List<Int> → Bool; end) = struct let input : List<Int> = [3, 1, 2]; let result : Bool = proc.report(input); end;
Since executeQuery is sandboxed, the only binding it can reach is proc; ambient resources are invisible. An ambient secret : Int, say, would be out of scope, so proc.report([secret, 1, 2]) is statically rejected. We can now apply executeQuery to the previous composed module previewProcessor and obtain the result of its report via executeQuery(previewProcessor).result.
The authority of executeQuery is fixed entirely by the processor it is handed, so swapping the processor swaps the authority. Testing with mocks then follows immediately: we compose a mockProcessor from a mockPolicy that returns its list unchanged and a mockAudit whose decide returns false, and pass it to the same executeQuery.
module mockProcessor = assemble(makeQuery(mockPolicy))(mockAudit); let mockResult : Bool = executeQuery(mockProcessor).result;
The same sandboxed module yields a different result purely by the capabilities it is granted: composition assembles the capabilities, and the module is confined to them.
We have a prototype implementation of with a surface language in conventional named syntax, inspired by OCaml's modules, that runs and type-checks all the examples above and elaborates into our de Bruijn core. The examples also use records with named fields, a lightweight extension of that we formalize in Section 6.1. Section 6.2 presents a small source language for these module constructs and proves that its elaboration preserves typing. Beyond the core calculus, the implementation also supports practical conveniences such as built-in lists (used in the examples). These are orthogonal to first-class environments and are not part of the formal development.
3 The Calculus: Syntax, Typing and Semantics
This section introduces the calculus: a polymorphic calculus with first-class environments.
3.1 Syntax and Well-formedness
The syntax of the calculus is shown in Figure 1. The calculus uses a de Bruijn [De Bruijn 1972] encoding for both term and type variables, thus all binders are nameless. To keep the de Bruijn notation more manageable, we separate indices for type variables (greek letters , , ...) and term variables (roman letters a, b, c, ...). Note that these letters are not names but de Bruijn indices 0, 1, 2, ... in alphabetical order ( , , and so on). Figure 2 shows how such mixed environments are read. Term entries (lighter gray) and type entries (darker gray) form one ordered sequence, but each variable resolves within its own namespace, counting only entries of that kind:

Positions of type entries
Positions of term entries
Fig. 2. Visualization of an environment with de Bruijn indices.
for example (index 0) is the nearest preceding type binding and (index 1) the second-nearest. The arrows and the two rows beneath the sequence make these positions explicit.
Types and contexts. Meta-variables A, B and C range over types. Types include base types (Int), type variables (de Bruijn indices N), arrow types (A → B), universal types (∀A), box types (Γ ▷ A), manifest types ([A]B), and contexts. A context (Γ) is either empty (⋅) or extends one with a term binding (Γ, A), an abstract type binding (Γ, ★), or a manifest type binding (Γ, [A]).
Expressions. Meta-variables e range over expressions, which include: integer literals (i), variables (de Bruijn indices n), lambda abstractions ( ), applications ( ), type abstractions ( ), type applications (e A), closures for abstractions , closures for type abstractions , boxes , and sequence expressions formed by comma-separated entries. Environment expressions are the subset of expressions with this sequence shape, starting with and extending with either an expression e or a manifest type definition [A]. Note that the environment entries may refer to term or type variables bound in . Thus environments are dependent [Tan and Oliveira 2023]. In contrast to where there are only term dependencies, in there can be type dependencies as well. For instance, in , , the term component instantiates the polymorphic identity at the type variable bound by the earlier type entry , so its type depends on that entry. Composition is the concatenation of entries, and it preserves these dependencies of later entries on earlier ones.
Values and frames. Meta-variables v range over values. Values include integer literals (i), closures for abstractions , closures for type abstractions , and sequence values formed by comma-separated entries. Value environments are the subset of values that have this sequence shape, starting with and extending with a value or a box type. A value environment can contain both values and manifest box-type definitions. In contrast to environment expressions, value environments are not ordered: an entry in does not have dependencies on previous entries. In other words, all the entries in are closed and merges in value environments are not dependent. Frames (F) specify evaluation contexts for applications, type applications, boxes, environments.
Well-formedness. Most well-formedness rules (Figure 3, top) are standard, and the auxiliary judgments they use—context membership , type variable lookup , well-formed contexts , context concatenation , and rigidity —are given in Appendix B. A type variable is well-formed when it points to an abstract binding (rule WFT-VAR) or a concrete one (rule WFT-VAREQ), and environment types are checked entrywise under the concatenation of the global and local contexts (rule WFT-EDEF, rule WFT-TDEF). One interesting rule is rule WFT-BOX. For a box type , the body A must be well-formed and rigid in (written ), meaning that A does not refer to abstract type variables in . Rigidity mirrors environments and values, which carry only manifest (concrete) type bindings, never abstract ones. When we build a box , the type of is a concrete context without abstract variables, and any type under such a context is rigid.
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira

Fig. 3. Well-formedness of types (top) and 's type system (bottom).
3.2 Typing and Type Equivalence
Typing. Figure 3 (bottom) shows the type system. The typing rules for term variables (rule TYP-VAR, in which term variable lookup is defined in Appendix B), term abstractions (rule TYP-ABS), applications (rule TYP-APP) and type abstractions (rule TYP-TABS) are standard. For type applications, instead of using a meta-level substitution, we utilize a manifest type [A]B to represent the instantiation of type variable ( ) in B with type A (rule TYP-TAPP). Together with rule TYP-TEQ, type application can check against some expected type using the type equivalence relation. For example, by rule TYP-TAPP we know that type application ( ) Int has type . Then, by rule TYP-TEQ, we can conclude that it also has an equivalent type Int Int. We will explain the type equivalence relation in detail later in this subsection.
Rule TYP-BOX is the typing rule for term-level boxes. A box expression has a box type. To typecheck a box , the local environment is first typed under the global context , giving an environment type . The body is then typed under , so that if has type A then the box has type . Rule TYP-CLOS and rule TYP-BCLOS are rules for closures of term abstractions and type abstractions. These two rules are similar to rule TYP-ABS and rule TYP-TABS respectively, except that the term/type abstractions are checked under the type of the local value environment , and the types of closures are also box types. Moreover, since is a sequence of values and it is closed, the typing context for it can be empty in these two rules.
For typing an environment, the older environment is first type-checked under the global context , and then the last element is checked under the concatenation of and the older local context
(Type Equivalence)
\begin{aligned}&\frac{\mathrm{TEQ-INT}}{\vdash\Gamma_{1}\quad\vdash\Gamma_{2}}\quad\frac{\mathrm{TEQ-TVAR}}{\vdash\Gamma_{1}\quad\vdash\Gamma_{2}\quad N\in\Gamma_{1}\quad N\in\Gamma_{2}}\\&\frac{\Gamma_{1}\vdash\mathrm{Int}\sim\mathrm{Int}\dashv\Gamma_{2}}{\mathrm{TEQ-EQR}}\quad\frac{\Gamma_{1}\vdash N\sim N\dashv\Gamma_{2}}{\mathrm{TEQ-MANIL}}\\&\frac{\Gamma_{1}\vdash\mathsf{A}\sim\mathsf{B}\dashv\Gamma_{2}\quad\Gamma_{2}[N]=\mathsf{B}}{\Gamma_{1}\vdash\mathsf{A}\sim N\dashv\Gamma_{2}}\\&\frac{\mathrm{TEQ-BOXL}}{\Gamma_{1}\vdash\Gamma_{3}\triangleright\mathsf{A}\quad\Gamma_{3}\vdash\mathsf{A}\sim\mathsf{B}\dashv\Gamma_{2}}\\&\frac{\Gamma_{1}\vdash\Gamma_{3}\triangleright\mathsf{A}\sim\mathsf{B}\dashv\Gamma_{2}}{\mathrm{TEQ-ARR}}\\&\frac{\Gamma_{1}\vdash\mathsf{A}\sim\mathsf{C}\dashv\Gamma_{2}\quad\Gamma_{1}\vdash\mathsf{B}\sim\mathsf{D}\dashv\Gamma_{2}}{\Gamma_{1}\vdash\mathsf{A}\rightarrow\mathsf{B}\sim\mathsf{C}\rightarrow\mathsf{D}\dashv\Gamma_{2}}\\&\frac{\mathrm{TEQ-EDF}}{\Gamma_{1}\vdash\Gamma_{3}\sim\Gamma_{4}\dashv\Gamma_{2}\quad\Gamma_{1}+\Gamma_{3}\vdash\mathsf{A}\sim\mathsf{B}\dashv\Gamma_{2}+\Gamma_{4}}\\&\frac{\Gamma_{1}\vdash\Gamma_{3},\mathsf{A}\sim\Gamma_{4},\mathsf{B}\dashv\Gamma_{2}}{\end{aligned}Fig. 4. Type equivalence.
. If the last element is an expression e, it is type-checked under the extended context (rule TYP-EDEF). Otherwise it is a type A, which must be well-formed under the extended context, and the environment type is extended with a concrete binding [A] (rule TYP-TDEF).
Type equivalence. Figure 4 shows the definition of type equivalence. The judgment is written . It compares a type A under a context with a type B under a context . The two contexts may differ, and are needed for box types. A box type is self-contained under its own local context. Comparing one therefore switches to that local context on a single side (rule TEQ-BOXL and rule TEQ-BOXR). The two types are then read under different contexts. A single shared context could not express this. Everywhere else the contexts stay aligned: a type variable of a given de Bruijn index refers to corresponding binders on both sides. This alignment is an important invariant for the metatheory of type equivalence (Section 4). An abstract type variable N is equivalent to itself when it is well-scoped in both and (rule TEQ-TVAR). For concrete type variables, the corresponding type is fetched from the context and equivalence is checked against that type (rule TEQ-EQL and rule TEQ-EQR). Rule TEQ-FORALL adds an abstract type binding to both sides, preserving the alignment. A manifest type [A]B creates a concrete type binding [A] in the context for B, so that type variable in B refers to this newly created binding. Since this binder is added on only one side, rule TEQ-MANIL and rule TEQ-MANIR restore the alignment by weakening the other side with an extra abstract binding and shifting its type, so that its de Bruijn indices step over the added binding. For environment types, elements in an environment can depend on not only the global context, but also the older local context. Thus, when checking for equivalence of two environment types, we need to check the equivalence of each corresponding element under the extended contexts. Our relation for type equivalence has the following properties.
THEOREM 3.1 (REFLEXIVITY). If then .
THEOREM 3.2 (SYMMETRY). If then .
THEOREM 3.3 (TRANSITIVITY). If and then .
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
(Small-step Operational Semantics)
STEP-BOX
STEP-BOXV
STEP-BETA
STEP-CLOS
STEP-EDEF
STEP-TDEF
Fig. 5. Dynamic semantics.
3.3 Environment-based Semantics
Figure 5 shows 's call-by-value small-step environment-based semantics, with the form of where denotes the runtime environment. The semantics passes types explicitly at run time, keeping type information in both terms and environments. Rule STEP-VAR looks up the value of a variable from the runtime environment via the lookup function defined as:
Similarly to the semantics of [Tan and Oliveira 2024], an application evaluates to a closure , then to a value , and finally applies the closure to the argument by adding into the lexical environment for the closure, using the updated environment to evaluate the function body (rule STEP-BETA).
For type abstractions, uses weak reduction, following treatments of System F in standard textbooks [Harper 2016; Pierce 2002]. Reduction never proceeds under the binder for , and the body is evaluated when a type argument is supplied. An alternative is to reduce under the binder, extending the runtime environment with an abstract binding for the bound variable, reducing the body, and reading the result back into a term, as in the Crégut machine [Crégut 2007] (a full-reduction variant of the Krivine machine [Krivine 2007]). This needs extra machinery such as de Bruijn levels, so we adopt weak reduction for simplicity.
For type applications, we use a similar strategy as in term applications, to avoid using meta-level substitution. A type application first evaluates to a closure , and then the type argument is pushed into for evaluating the body . However, since type can depend on the global environment, we need to make the type argument closed before pushing it into the lexical environment: we turn into a box type which is always closed, and then push the box type into the lexical environment (rule STEP-TAPP). In this rule, the operation extracts the type information from the global environment for . Then it constructs a concrete local context to form the box type. The definition of is given in Appendix B.
Rule STEP-BOX evaluates a box : is first evaluated to a value environment , and then is reduced under environment . Rule STEP-BOXV extracts the value from the box after evaluation reaches a value. Evaluation of an environment is also from left to right. The older environment is first evaluated to a value environment . Then, if the last element is an expression , it is evaluated under the concatenation (rule STEP-EDEF). The operation + (defined in Appendix B) appends the entries of the second environment to the first, so the bindings of both are in scope. When the last element is a type then, if is a box type, the environment is already a value. Otherwise, type may depend on the global environment or the previous elements, and thus we make the type definition closed by turning it into a box type (rule STEP-TDEF).
Computational irrelevance of types. The semantics of Figure 5 is type-passing: type arguments are carried at runtime and appear as entries in runtime environments (rule STEP-TAPP), so reduction does some computation on types. Types, however, are only needed for static checking and do not affect the result. We make this precise with a type-erasing semantics that drops all types from terms and environments, along with the associated runtime computation (Appendix C). An erase function removes types from expressions, following TAPL [Pierce 2002], and we mark the type-erasing semantics with the subscript . We prove that it reaches the same (erased) values as the type-passing semantics (Theorem 3.4).
THEOREM 3.4 (COMPUTATIONAL IRRELEVANCE OF TYPES). If then .
The type-passing and type-erasing semantics are two presentations of the same calculus, differing only in whether types are kept at run time. We adopt the type-passing semantics as primary: it is the proof vehicle for conservativity of the dynamics, which must match System F's runtime type substitution (Section 4). Section 5 further discusses an implicitly-typed variant, where a polymorphic value is used directly without type abstraction or application, as in Haskell and OCaml.
4 Metatheory of
This section develops the metatheory of . The environment semantics yields instantiation lemmas that replace the conventional substitution lemmas, and we use them to prove type soundness, conservativity with respect to System F, normalization, and decidability of type equivalence.
4.1 Instantiation Lemmas and Decidability of Type Equivalence
The instantiation lemma for type equivalence states that, if types A and B are equivalent, and if we instantiate abstract type bindings with two equivalent types in the contexts, then type equivalence between A and B still holds under the concretized contexts.
LEMMA 4.1 (INSTANTIATION). If and , then .
To prove this lemma, a naive induction on does not work, since during the process of checking type equivalence, it cannot be guaranteed that the last elements on both sides of the contexts are always abstract type bindings. For example, in rule TEQ-MANIL and rule TEQ-MANIR, a concrete type binding is added to the context. Hence, we need to generalize the lemma to allow additional context elements after the abstract type bindings.
LEMMA 4.2 (GENERALIZED INSTANTIATION). If and and , then .
In this generalized form, denotes the number of type bindings in context . The lemma requires that both sides of the contexts have the same number of additional type bindings. Importantly, this invariant is maintained for most cases of the type equivalence checking, and thus we can prove the lemma by induction on the generalized judgment. For example, when checking the equivalence for universal types (rule TEQ-FORALL) and manifest types (rule TEQ-MANIL and rule TEQ-MANIR), each of these three rules extends both contexts by exactly one type binding, so the numbers of additional type bindings on both sides stay equal. Furthermore, when checking the equivalence of two non-empty environment types , _ and , _ (rule TEQ-EDEF, rule TEQ-STAR, and rule TEQ-TDEF), the equivalence of older environments and is checked. The following lemma ensures that the numbers of type bindings in the older environments are equal. Hence, after the concatenation of two environments, the invariant still holds.
LEMMA 4.3. If , then .
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
The box cases require special consideration. In rule TEQ-BOXL and rule TEQ-BOXR, the local context replaces the global context for checking the equivalence for the body type. This way, the invariant requiring that the numbers of additional type bindings on both sides are equal can fail. For example, with rule TEQ-BOXL, to check , we need to check . Now the left side has two type bindings while the right side has three. However, this case is not problematic. The body type of a box does not refer to any abstract type binding of its local context, as it is required to be rigid by the well-formedness condition for box types. Moreover, type equivalence preserves rigidity: whenever one side is rigid, so is the other. Thus it is safe to instantiate the abstract binding on the right-hand side to a concrete one without affecting the equivalence, as formalized in the following lemma.
LEMMA 4.4. If and and , then .
We also prove a generalized instantiation lemma for typing, by induction on the typing derivation and using the type-equivalence instantiation lemma in the TYP-TEQ case.
LEMMA 4.5 (GENERALIZED INSTANTIATION FOR TYPING). If and , then .
By picking to be empty, we have the following form of instantiation lemma for typing.
LEMMA 4.6 (INSTANTIATION FOR TYPING). If and , then .
Decidability of type equivalence. The type equivalence relation is decidable. To establish this, we define size measures on types and on contexts, both parameterized by a measure context defined as . Intuitively, the measure context keeps track of the sizes of bindings in the typing context, where is for term variable bindings and is for type variable bindings. Here gives the size of a type , using to supply the sizes of 's free type variables. The context measure computes the size of each binding of , returning a list of sizes which is itself a measure context. The context measure takes as a parameter because an environment type can depend on the surrounding context: a binding of may mention type variables bound outside , whose sizes are supplied by . The definitions of and are given in Appendix D. These two measures yield the lemma below; decidability is then a corollary.
LEMMA 4.7. If , then it is decidable whether holds.
COROLLARY 4.8 (DECIDABILITY). is decidable.
4.2 Type Soundness and Normalization
Syntactic type soundness. We first prove type soundness via progress and preservation [Wright and Felleisen 1994]. Since the type equivalence rule is included, the proofs of progress and preservation cannot be based solely on case analysis of the typing derivation. Instead, they require appropriate inversion lemmas for values. We have the following inversion lemmas for term and type abstractions; besides the canonical forms, they give typing derivations and type-equivalence information.
LEMMA 4.9 (INVERSION LEMMA FOR TERM ABSTRACTIONS). If , then there exist , , , , , and and , and and .
LEMMA 4.10 (INVERSION LEMMA FOR TYPE ABSTRACTIONS). If , then there exist , , , , and and , and , , .
Lookup lemmas. Since the semantics is environment-based, we also prove progress and preservation for the lookup function: if the runtime environment is well-typed, any variable lookup in succeeds and preserves the type.
LEMMA 4.11 (PROGRESS OF LOOKUP). If and , then there exists s.t. .
LEMMA 4.12 (PRESERVATION OF LOOKUP). If , , and , then .
Progress and preservation. We have the following generalized progress and preservation theorems, which have the form similar to the ones in previous work [Tan and Oliveira 2024] on small-step environment-based semantics. The generalized form of theorems considers an arbitrary well-typed runtime environment instead of the empty environment.
THEOREM 4.13 (GENERALIZED PROGRESS). If and , then either is a value or .
THEOREM 4.14 (GENERALIZED PRESERVATION). If and and then .
The generalized progress theorem follows by canonical forms of values, which handle the application and type application cases. For other cases, the proof follows a standard structure. The generalized preservation theorem is proved by first doing induction on the typing derivation and then inversion on the reduction relation . The proof of preservation follows similar reasoning to that of Tan and Oliveira [2024]. In particular, the reduction rules for closures and boxes in are quite similar. However, reasoning is more involved due to the more powerful type system of . Closures and boxes now have box types in , thus the preservation proof for them requires type equivalence reasoning. In rule STEP-CLOS, a lambda abstraction of type is converted to a closure of type , where is the type of the runtime environment. Since and are equivalent under , we can use the typing rule for type equivalence (rule TYP-TEQ) to conclude that the closure preserves the type. Similar reasoning applies to rule STEP-BCLOS for closures of type abstraction. Moreover, rule STEP-BOXV extracts the body value from a box. The box has type , while has type . The following lemma ensures that the type of a value can be boxed with the type of its runtime environment . Thus rule STEP-BOXV also preserves the type.
LEMMA 4.15. If and and , then .
Next we focus on the most interesting case, which is the one for type applications (rule STEP-TAPP). Suppose that and , we want to show that . From the typing judgment for the type application, we have the typing judgment for the closure . Moreover, by the inversion lemma (Lemma 4.10), there exist and C such that
According to the typing rule for boxes (rule TYP-BOX), we need to make sure that is well-typed, and construct a box type that is equivalent to so that the box can typecheck via rule TYP-TEQ. To be concrete, we need:
-
instantiation lemma for typing, to fill the gap between the inversion lemma and the typing rule for boxes. From (1), we know that the local environment , in the box has type , by rule TYP-TDEF. Then we need to show that the body in the box is well-typed under the local context , . From (2), is well-typed under an uninstantiated context , . By the instantiation lemma for typing, we have , .
-
instantiation lemma for type equivalence, to handle the equivalence between the manifest type and the box type. From above we know that the box has type . It remains to show that this type is equivalent to under . With the type equivalence rules for manifest types and box types, it suffices to show that , , . This comes from (3) and the instantiation lemma for type equivalence. Note that the types used for instantiation must be equivalent. Here we need to prove , which reduces to .
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
The context may differ from , but the two are equivalent: they contain equivalent types at corresponding positions. Reflexivity therefore holds across them, as formalized below.
LEMMA 4.16. If and , then .
Standard progress and preservation theorems now follow as corollaries:
THEOREM 4.17 (PROGRESS). If , then either is a value or .
THEOREM 4.18 (PRESERVATION). If and , then .
Semantic typing and normalization. We also provide semantic typing, through a unary logical relation in the style of reducibility [Girard 1972; Tait 1967]. The relation interprets every type A as a set of values and every typing context as a set of well-typed runtime environments. A term is semantically well-typed, written , if under every runtime environment that realizes it reduces to a value in the interpretation of A. The fundamental theorem of the relation shows that syntactic typing implies semantic typing, and is proved by induction on the typing derivation with one compatibility lemma per typing rule.
THEOREM 4.19 (FUNDAMENTAL THEOREM). If , then .
Our definition of semantic typing entails that evaluation reaches a value, so the fundamental theorem yields normalization.
COROLLARY 4.20 (NORMALIZATION). If , then for some value .
Here reduction is call-by-value and never goes under or binders. The corollary states that closed, well-typed terms evaluate to a value, which is weaker than strong normalization of full reduction. The logical relation and semantic typing ( ) are presented in detail in Appendix E.
4.3 Conservativity
Our calculus is capable of simulating and expressing different aspects of the semantics of System F. In what follows, we relate to System F. For avoiding ambiguity, we use , , and : A to denote typing contexts, expressions, types, and the typing judgment respectively in System F. We first show that the type system of is complete with respect to System F typing. That is, any typing judgment derivable in System F is also derivable in .
THEOREM 4.21 (COMPLETENESS W.R.T. TYPING). If , then .
The interesting case in proving this theorem is for type application. One key difference between and System F is that, for type application, System F uses meta-level type substitution, while uses manifest types to delay the substitution. Hence, we need to relate meta-level substitution and manifest type via type equivalence, as formalized in the following lemma.
LEMMA 4.22 (EQUIVALENCE FOR TYPE SUBSTITUTION). If , and , then .
Conservativity of typing. Now we turn to the reverse direction. For typing contexts, expressions, and types in System F, if the typing relation is valid in , then it should also be valid in System F.
THEOREM 4.23 (CONSERVATIVITY W.R.T. TYPING). If , , , and , then .
The reasoning is trickier in this direction, since there is type equivalence in the type system of . When deriving from , if we do induction on the typing relation, then for the type equivalence case (rule TYP-TEQ), we will reach some type that is not in System F. Consider the following simple example:
(Value Correspondence)
Fig. 6. Value relation between and System F.
In this example, : Int does not mention types in , but the typing subderivation : contains an type . Therefore, the induction hypothesis cannot be applied, as condition cannot be satisfied. This problem is addressed by proving the theorem via two steps: first proving a relaxed form of lemma that does not require types to be in System F, and then using this lemma to derive the original theorem. The lemma is stated as following:
LEMMA 4.24 (RELAXED CONSERVATIVITY). If , and : A, then there exists B, s.t., and : B and .
Compared with Theorem 4.23, this lemma allows type A not to be in System F. Instead, it finds a System F type B that is equivalent to A under . This way, we can do induction on without worrying about encountering types that are not in System F. Moreover, if A is already in System F, then by the following uniqueness lemma (Lemma 4.25), we know that any equivalent type B in System F must be syntactically the same as A. Hence, conservativity theorem follows as a corollary of Lemma 4.24.
LEMMA 4.25 (UNIQUENESS). If , , , and , then .
In proving Lemma 4.24, the interesting case is again type application, where we rely on Lemma 4.22 to relate manifest types and meta-level substitutions under type equivalence.
Conservativity of the dynamic semantics. We connect our semantics (Section 3.3) with System F's call-by-value, substitution-based semantics. The type-passing semantics is essential here: System F evaluates a type application such as Int by substituting Int into the body, which contains the free variable . To model this without meta-level substitution, we must keep type information in the runtime environment. A type-erasing semantics discards it and cannot capture System F's substitution behavior.
Tan and Oliveira [2024] relate to the STLC via an operation that closes a expression under : it replaces each free term variable of by its value in , treating the innermost variables as bound. A closure then corresponds to the STLC abstraction with . We extend this to type variables and type-abstraction closures in with a companion operation that closes the types occurring in : it resolves each free type variable against the type entries of , and when such an entry is a box type it recursively closes under to yield a plain System type. With and we define the value relation between an value and a System value (Figure 6). For a closure body we first close its types with and then its term variables with . Since type and term variables are indexed separately, for the depth is 0 for and 1 for (the body sits under a binder), and for it is 1 for and 0 for . We prove that 's dynamic semantics is complete and conservative with respect to System .
THEOREM 4.26 (COMPLETENESS W.R.T. DYNAMICS). If and , then there exists s.t. and .
THEOREM 4.27 (CONSERVATIVITY W.R.T. DYNAMICS). If , and , then there exists s.t. and .
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
Expressions
Environments
Values
Value environments
Frames
Fig. 7. Syntax of the implicitly-typed variant. Types and contexts are as in Figure 1.
5 Implicit Polymorphism
The calculus in Section 3 has explicit terms for type abstraction and type application. This choice keeps the substitution-free machinery working for explicit polymorphism where there are three forms of substitution, but our environment-based approach is not tied to it. We also develop an implicitly-typed variant of , whose terms carry no type information: type abstraction and type application are no longer term constructs, but typing coercions that leave the term unchanged. In the explicitly-typed calculus a type abstraction blocks until a type argument is supplied. In contrast, the implicitly-typed variant has no such term, so polymorphic expressions reduce immediately, as in languages such as Haskell and OCaml. Types, well-formedness, and type equivalence are as in the explicitly-typed calculus; only the term syntax, the typing judgment, and the reduction relation change.
The implicitly-typed variant relates to as Curry-style System F relates to System F. Curry-style System F has no type-into-term substitution (Section 2.2), but it still substitutes terms into terms in -reduction and types into types in its instantiation rule. As in the explicit calculus, the variant eliminates both, through its environment-based semantics and manifest types.
5.1 Syntax
Figure 7 shows the syntax of the implicitly-typed variant. It is the syntax of (Figure 1) with all type-level constructs removed from terms: there is no type abstraction, no type application, and no type definitions in environments.
Types and contexts. Types and contexts are those of . Universal types , manifest types , and manifest bindings , remain, but are now introduced by typing coercions (Section 5.2) rather than by terms. Well-formedness (Figure 3, top) and type equivalence (Figure 4) are unchanged, as are their properties.
Expressions. Expressions are those of without type abstractions , type applications , closures for type abstractions , and type definitions , . Environments thus contain only expressions, but they remain dependent: the type of an entry may refer to type bindings that occur only in the environment's type (Section 5.2).
Values and frames. Values no longer include closures for type abstractions, and value environments are plain sequences of values, since no type ever enters a runtime environment. Nor do frames include A or , [A]. Unlike the type-erasing semantics of (Appendix C), which removes types but keeps type abstractions and a dummy application , the variant has no type abstractions to block evaluation.
5.2 Typing
Figure 8 shows the type system of the implicitly-typed variant. Every rule coincides with its counterpart in Figure 3, except for three coercions, ITYP-GEN, ITYP-INST, and ITYP-MANI, which leave the term untouched and take the place of the rules for the term forms , , and , [A].
(Typing)
Fig. 8. Type system of the implicitly-typed variant.
Generalization and instantiation. Polymorphism is handled by the first two coercions:
Rule ITYP-GEN introduces a polymorphic type ∀A by checking the term under one additional abstract type binding ★, just as the explicitly-typed calculus does when typing a type abstraction. The term needs no adjustment under the new binding: it contains no types, and since term and type variables are indexed separately (Section 3), the binding ★ does not shift the indices of its term variables. Rule ITYP-INST instantiates a polymorphic type ∀B at a well-formed type A while leaving the term unchanged, since the variant has no term-level type application. Crucially, rather than substituting A into B at the meta level, rule ITYP-INST records the instantiation as the manifest type [A]B and leaves the actual unfolding to the type-equivalence relation. The implicitly-typed variant is therefore substitution-free, just like the explicitly-typed calculus.
To see the two coercions at work, recall the type application from Section 2.4, where id is the identity function . a. Its implicitly-typed counterpart is just id, which can be given the same type. Omitting well-formedness premises, the derivation is:
The topmost judgment follows by rule ITYP-GEN from typing id at under one more abstract binding. The derivation has the same shape as the explicit one in Section 2.4, with rules ITYP-GEN and ITYP-INST in place of TYP-TABS and TYP-TAPP, and it yields the same manifest type, but the term stays id throughout. As in the explicit calculus, rule ITYP-TEQ then turns this type into the equivalent type Int Int, so that, for instance, id 1 has type Int by rule ITYP-APP. Type equivalence thus does the work that type substitution does in the instantiation rule of Curry-style System F.
Manifest bindings in environments. The third coercion, rule ITYP-MANI, plays the role of rule TYP-TDEF: it extends the type of an environment with a manifest binding [A], which exists only in the type, as the environment has no type entries. Later entries may refer to this binding (rule ITYP-CONS),
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
(Reduction)
Fig. 9. Dynamic semantics of the implicitly-typed variant.
so environments can still have types with transparent type components (Section 2.5). For instance, , . a has the type of the dependent environment , , of Section 3:
Here the entry . a is typed under the binding by rules ITYP-GEN and ITYP-INST, as in the previous derivation.
Coercions and type equivalence. Unlike rule ITYP-TEQ, which replaces a type with an equivalent one, the coercions change the type itself, and they apply to terms of any shape. A term may therefore have several types that are not equivalent: the identity . a, for instance, has both and . . Generalization is also not limited to abstractions: applying the identity to another identity, , has type . . Here the applied identity is typed at and its argument at , and rule ITYP-GEN abstracts the free variable . As with Curry-style System F, typability in this variant is undecidable [Wells 1999], and we make no type-inference claims.
5.3 Environment-based Semantics
Figure 9 shows the call-by-value, environment-based reduction relation of the implicitly-typed variant. It is the semantics of Figure 5 without the rules that compute on types (STEP-TAPP, STEP-BCLOS, and STEP-TDEF), so evaluation never blocks on a type abstraction; the remaining rules are unchanged up to their names. Since runtime environments contain only values, the extraction is not needed, and types play no role at run time by construction, whereas the explicitly-typed passes types at run time, and Theorem 3.4 shows that they do not affect the result.
Evaluation under type abstraction. The coercions are what let evaluation proceed under type abstraction. Consider again , which has type (Section 5.2). It evaluates as follows:
(ISTEP-EVAL, ISTEP-LAM)
(ISTEP-EVAL, ISTEP-LAM)
(ISTEP-BETA)
(ISTEP-BOX, ISTEP-VAR)
(ISTEP-BOXV)
To have this type in the explicitly-typed calculus, the same program must be written under a type abstraction, . This term evaluates to a closure by rule STEP-BCLOS and stops there: its body is not evaluated until a type is supplied, and it is evaluated again for every type argument supplied (rule STEP-TAPP), so the inner redex stays frozen under . The implicitly-typed variant has no type abstraction in terms, so the redex is free to reduce and evaluation is not held up by polymorphism.
Polymorphic entries in environments. Polymorphic values can also be stored in first-class environments and used at different types, without any type information at run time. In the box , the local environment holds the identity, typed at by rule ITYP-GEN. In the body, rules ITYP-INST and ITYP-TEQ instantiate the first occurrence of at and the second at . Hence the body has type , and so does the box, by rules ITYP-BOX and ITYP-TEQ. The box evaluates as follows:
Inside the box, both occurrences of a are looked up in the local environment (rule ISTEP-VAR), and the same closure serves at both types. In the explicitly-typed , the program would be , and each of its two type applications would first reduce, by rule STEP-TAPP, to a box whose local environment stores the type argument, before the identity could be applied.
5.4 Metatheory
Type soundness and normalization. Type soundness is established semantically, through a unary logical relation analogous to the one for the explicit calculus (Appendix E). The fundamental theorem shows that syntactic typing implies semantic typing , which yields normalization, and hence type soundness: a closed well-typed term never gets stuck.
THEOREM 5.1 (FUNDAMENTAL THEOREM). If , then .
COROLLARY 5.2 (NORMALIZATION). If , then for some value .
The interesting case of the proof is rule ITYP-GEN, which leaves the term unchanged; it relies on reduction being deterministic, so that e evaluates to the same value under every interpretation of the new abstract binding.
Conservativity over implicitly-typed System F. The variant is also a conservative extension of implicitly-typed System F, whose terms are those of the λ-calculus with integer literals and whose reduction is the standard call-by-value reduction. With the notation of Section 4 (Γ ⊥_F e : A, e ↪* v_F, ⊥_F Γ, ⊥_F e, ⊥_F A, and v ~ v_F), we prove completeness and conservativity with respect to implicitly-typed System F, for both typing and the dynamic semantics, in the same form as for the explicit calculus.
THEOREM 5.3 (COMPLETENESS W.R.T. TYPING). If , then .
THEOREM 5.4 (CONSERVATIVITY W.R.T. TYPING). If , and , then .
THEOREM 5.5 (COMPLETENESS W.R.T. DYNAMICS). If and , then there exists s.t. and .
THEOREM 5.6 (CONSERVATIVITY W.R.T. DYNAMICS). If and , then there exists s.t. and .
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
As in Section 4, in the proof of completeness, instantiation in System F, which substitutes into the type, is matched by rule ITYP-INST followed by rule ITYP-TEQ. Since values carry no types, the value relation needs only rule VREL-LIT and rule VREL-ABS without the type-closing operation T.
This variant and all of the results above are fully formalized in Rocq.
6 Discussion and Extensions
We extend with records and use them to elaborate a source language of first-class modules. We then discuss subtyping and sealing as directions for future work.
6.1 Extension to Records
Similarly to [Tan and Oliveira 2024], we add extensible (and dependent) records as a lightweight extension, following Reynolds's Forsythe encoding [Reynolds 1997]: a multi-field record is a concatenation of single-field records. Thus, records add only labels and field selection, which are reached by name, through a separate lookup, and on top of environments. The added rules appear in Figure 10. Records are useful to model programs that access components by a nominal label, such as the modules of Section 2.5.
Syntax. The syntax for records in the extended calculus is as follows:
Types
A, B, C ::= ... | {l : A}
Expressions
Values
Frames
Syntactic sugar
The syntax adds single-field record types , single-field record terms , and field selection e.l. A multi-field record is their concatenation, at both the type and term levels. Records leverage 's existing concatenation mechanism. The encoding fits almost for free, since 's environments are already ordered, concatenable sequences. A multi-field record is simply such a sequence, with both the dependencies among its fields and the means to concatenate them coming from the existing environment rules. What is new is the kind of dependency. 's records depend on earlier term entries, and inherits this. 's environments, however, also carry manifest type components. A field's type can therefore depend on a type entry declared earlier in the same record. Reynolds's records are not dependent at all, and 's not on type entries. These transparent, dependent type components are thus new to .
A consequence of this encoding—again inherited from Reynolds—is that the syntax does not, by itself, distinguish record fields from other entries. A sequence such as , , mixing a labelled field with an ordinary type, is well-formed. We regard this as a property of the general mechanism, not a defect: records are one disciplined fragment of it, sitting alongside ordinary bindings and manifest type components. The source language in Section 6.2 restricts the signatures of merge operands to labelled fields and manifest type entries, allowing both in the same signature while excluding unlabelled term entries.
Typing. Rule TYP-REC types a single-field record, while rule TYP-SEL types field projection using label lookup . The type of e.l is A when looking up label l in the type of e yields A. Since rule TYP-TEQ allows typing to use type equivalence, the type equivalence relation is also extended with rule TEQ-RCD which compares record types by comparing their fields.
(Label Lookup on Environment Types)
LOOKUP-RCD
LOOKUP-ANDL
LOOKUP-ANDR
LOOKUP-TDEF
(Typing)
\begin{aligned}&\frac{\mathrm{TYP-REC}}{\Gamma\vdash e:\mathsf{A}}\\&\frac{\Gamma\vdash\{l=e\}:\{l:\mathsf{A}\}}{\end{aligned} \begin{aligned}&\frac{\mathrm{TYP-SEL}}{\Gamma\vdash e:\Gamma_{1}\qquad l:\mathsf{A}\in\Gamma_{1}}\\&\frac{\Gamma\vdash e.l:\mathsf{A}}{\end{aligned}
(Type Equivalence)
TEQ-RCD
(Selection)
SEL-REC
SEL-DEFL
SEL-DEFR
SEL-TDEFL
(Operational Semantics)
STEP-SEL
Fig. 10. Extension to records.
Note that label lookup, used in rule TYP-SEL raises an interesting problem since may have manifest type bindings that are not in scope in : a naive lookup could result in an ill-scoped type. Therefore the label lookup relation does not simply yield the type associated with label in . Instead, since environment types are dependent, it also collects the type information required by the associated type. For example, for in rule LOOKUP-RCD, may depend on the previous environment and the label lookup needs to account for the dependency to ensure that the result is well-scoped. Instead of returning directly, a wrapped type is returned. The definition of the wrapping operation is given as follows:
Intuitively, constructs a manifest type along the way of traversing the environment type, so that all the type dependencies on the previous environment are properly captured. For instance, environment , , , can have environment type , , , , where function toBool converts an integer to a boolean and its type depends on the previous two type definitions. When looking up label , the result is . This way, the type of toBool correctly reflects its dependencies on the previous type definitions. Furthermore, with type equivalence, toBool also has type . Note that labels can also be accessed from the global context. Rather than introducing a separate lookup mechanism for this purpose, we use the de Bruijn index to retrieve the corresponding labelled entry from the context, and then apply the projection to the variable. This approach keeps the calculus minimal while still supporting flexible access patterns.
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
Reduction. Dynamically, a projection e.l first evaluates e to a value environment . The selection relation then searches this value environment for the field labelled l and returns its associated value. It skips unrelated record fields and type definitions, and it continues through value environments until the labelled value is found. Thus rule STEP-SEL reduces to the value v selected by this relation.
Metatheory. The metatheory scales to this extension. The new rules add record-specific cases to theorems, but they do not change the central structure of the proofs. Thus the same environment-based reasoning, manifest bindings, and type equivalence infrastructure developed earlier continue to apply in the presence of records.
6.2 Dynamic Module Composition and Elaboration
We formalize a small source language for the modules of Section 2.5, with signatures given by core types. The judgment elaborates a module to an expression of type in with records; declaration blocks elaborate similarly. Figure 11 gives the rules for adding a field and composing two modules. In rule ELABD-VAL, the context includes the preceding declarations, so the new field may refer to earlier type definitions.
ELAB-MERGE
Fig. 11. Elaboration of value declarations and module composition.
Rule ELAB-MERGE binds the two operands before rebuilding their components. Each operand must have a closed signature consisting of labelled fields and manifest type entries (sig( )), with no repeated labels (uniq( )). Inside the two abstractions, the operands occupy indices 1 and 0. The expansion premises build from left to right, projecting fields and copying manifest type bindings. Label lookup wraps the projected types with their manifest definitions, preserving their dependencies (Section 6.1). The signatures determine which entries to rebuild; the operands may be computed at run time and are each evaluated once. We prove in Rocq that elaboration preserves typing for both modules and declarations. The complete rules and preservation theorem appear in Appendix F.
6.3 Future Work: Subtyping and Sealing
provides a substitution-free foundation for first-class modules, with dynamic composition and sandboxing. ML module systems are a mature, well-developed area [Leroy 1994; MacQueen 1984; Milner et al. 1997; Rossberg 2018; Rossberg and Dreyer 2013] with a different focus. Nevertheless, their features are a rich source of ideas for extending . The interesting question is how to bring these ideas into a substitution-free setting. Below we sketch two directions, partly inspired by features of ML modules: subtyping and sealing.
Subtyping. One way to incorporate subtyping into is to replace type equivalence by a subtyping relation , and recover type equivalence as a special case where the two types are mutual subtypes. Accordingly, the subsumption rule in the type system would have the form:
Since our environment types are dependent—an entry can depend on preceding entries—traditional notions of width and depth subtyping must be generalized to account for dependencies between type and term components. This leads to more sophisticated subtyping rules for environment types. We expect that the work by Kopylov [2003] will help formulate subtyping for dependent environment types, since Kopylov presents a standard subtyping judgment of the form for subtyping between dependent intersections. However, Kopylov's rules rely on meta-level substitution and are not directly applicable to our substitution-free setting. Thus, adapting subtyping to this setting requires further study.
Sealing. Moreover, sealing [Dreyer 2005; Harper and Lillibridge 1994; Rossberg and Dreyer 2013] is a key abstraction mechanism in ML modules, allowing internal type information to be hidden behind an abstract interface. To illustrate, consider the following ML-style module:
signature API = sig type a; val id : a → a end
structure M_int :> API = struct type a = Int; fun id x = x end
Here, the module M_int internally knows that a = Int, but externally exposes only the abstract type a. This is achieved via sealing (opaque ascription). A natural path to encode sealing is via subtyping between type contexts:
where the manifest type information is hidden in the supertype. This allows us to recover existential abstraction without introducing explicit existential quantifiers. In other words, sealing becomes a subtyping coercion, which would yield a more uniform account of abstraction in . This change is not simple, as subtyping would replace type equivalence. One immediate problem is that, unlike type equivalence, subtyping is not symmetric. This loss of symmetry would require substantial changes to the metatheory.
7 Related Work
First-class environments. Gelernter et al. [1987] introduced first-class environments in the research literature with Symmetric Lisp, a language that extends Lisp by making environments first-class values that programmers can inspect and manipulate at runtime. This pioneering work inspired a line of research on first-class environments for dynamically typed languages [Jagannathan 1994a,b; Miller and Rozas 1991; Queinnec and Roure 1996; Shutt 2010]. There is also some work on first-class environments for statically typed calculi. Sato et al. [2001] introduced a simply typed calculus called with environments as first-class values, under the setting of full reduction. Nishizaki [1994] proposed another typed calculus with first-class environments, called , which is based on the weak reduction of the calculus [Curien et al. 1996]. The use of explicit substitutions [Abadi et al. 1991] allows the above calculi to internalize substitution operations within the calculus itself. However, with first-class environments, explicit substitutions complicate both the dynamic semantics and the metatheory of these calculi. More recently, Tan and Oliveira [2023] proposed a simply typed calculus that supports dependent merges and first-class environments, with a call-by-value semantics. In , variables are encoded as label names and thus alpha conversion is not allowed on variables bound by a function. Following the calculus, the calculus proposed by Tan and Oliveira [2024] adopts de Bruijn indices for variable representation for binders, simplifying the representation of binding and the metatheory. The design of follows the design of , but it tackles the addition of polymorphism and type components.
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
Among typed calculi with first-class environments there is limited work on polymorphism. The most mature line of work is Nishizaki’s extension of , [Nishizaki 2000]. His work is focused on Hindley–Milner type schemes (rank-1 polymorphism) and type inference. The typing contexts carry only term-variable bindings. Nishizaki’s short paper on a second-order type theory [Nishizaki 2017] proposes a type system and reduction rules, but proves no metatheory. Moreover, like , the calculus is based on explicit substitutions. Its contexts and environments contain only term-variable entries. By contrast, brings full System F to a small-step, substitution-free environment semantics in the lineage [Tan and Oliveira 2024]. Contexts in mix term and type bindings, so terms may depend on types. At the term level, supports manifest type components, which lacks. Amin and Rompf [2017] proposed a big-step, call-by-value environment semantics for definitional interpreters with polymorphism. However, their environments are not first-class values, and their type system still relies on meta-level type substitution.
Modules with transparent type components. Many mainstream languages provide transparent type components without ML-style sealing. The distinction between transparent and opaque type components originates with translucent sums [Harper and Lillibridge 1994] and manifest types [Leroy 1994]. A transparent type component is exposed together with its definition. A client may then use the type and its definition interchangeably. Haskell's module system traditionally supports only transparent type components through type synonyms [Marlow 2010]. Its Backpack extension is an exception, retrofitting the language with signatures and sealing [Kilpatrick et al. 2014]. Rust and Go likewise only provide transparent type aliases in their module systems [The Go Team 2024; The Rust Team 2020]. Transparent type components are therefore useful on their own. enables transparent components via manifest types, and studies them in a substitution-free setting. Thus, it could serve as a foundation for module systems with transparent type components.
ML-style module systems. ML-style module systems package terms and type members behind signatures and functors [MacQueen 1984; Milner et al. 1997]. They relate to through two shared features: the transparent type components discussed above, and first-class modules. obtains both directly from first-class environments, capturing transparency with manifest type bindings and type equivalence. First-class modules have likewise been studied in ML, from early proposals in the ML literature [Russo 1998, 2000] to the unifying 1ML perspective [Rossberg 2018]. In practice, OCaml has provided first-class modules since version 3.12 [Frisch and Garrigue 2010; Leroy et al. 2011; Yallop 2010].
Beyond these shared features, rests on a different foundation. The ML-modules line explains modules by elaboration into a polymorphic core with a substitution-based metatheory, from higher-order and applicative or generative functors [Dreyer 2005; MacQueen and Tofte 1994] to unifying accounts such as MixML [Rossberg and Dreyer 2013], the F-ing method [Rossberg et al. 2014], and 1ML [Rossberg 2018]. By contrast, following [Tan and Oliveira 2024], models modules as first-class environments, with no separate notion of signatures or functors required, which immediately yields first-class modules. In , environments are values, and module composition is the dynamic, run-time concatenation of dependency-carrying fragments. A record calculus does not model this: an ordinary record, even a dependent one, fixes its fields at definition time, whereas composes separately-built fragments at run time while preserving dependency. A box additionally sandboxes a module from ambient bindings. Thus, dynamic composition and sandboxing are the primary emphasis of , and orthogonal to the ML-modules line.
The metatheory is moreover substitution-free: manifest type bindings together with a type-equivalence judgment let type variables be replaced by their manifest definitions during type checking. This unifies two traditionally distinct mechanisms. ML module calculi [Harper and
Lillibridge 1994; Leroy 1994] typically require both type equivalence (or subtyping) and meta-level substitution, whereas relies solely on type equivalence for both module components and polymorphic instantiation. This makes especially apt when modules group related definitions behind transparent type components.
does not provide sealing [Dreyer 2005; Harper and Lillibridge 1994; Rossberg and Dreyer 2013], subtyping, propagation of type equalities [Harper and Lillibridge 1994], or recursive modules [Dreyer 2005, 2007]. We treat these as optional extensions toward ML-style abstraction, not requirements of our contribution, and leave them to future work.
Explicit substitutions. Explicit substitutions [Abadi et al. 1991; Curien et al. 1996] were introduced to close the gap between the theory and implementation of the lambda calculus. Unlike the standard lambda calculus, explicit substitutions represent substitutions as syntactic entities, defined mutually inductively with terms. Typically, these substitution primitives include identity substitution (id), extension (e · s), shifting (↑), and composition (s ○ t). Abadi et al. [1991] showed that explicit substitutions calculus λσ can be extended with a polymorphic type system. In this setting, explicit substitutions also appear at the type level, and type application instantiates a universal type by extending a substitution. However, the mutual definition of types and substitutions significantly complicates the formulation and metatheory. Type equivalence must also be defined mutually with substitution equivalence, and must account for the semantics of each substitution primitive, resulting in a proliferation of equivalence rules. Our calculus takes a more lightweight and straightforward approach. We eliminate type-level substitution without introducing any substitution primitives. Instead, we use manifest types as a single, uniform mechanism for type instantiation. Our type equivalence judgment handles manifest types simply by discharging them into the context as manifest bindings, without needing to reason about various substitution primitives. This design is both simple and easy to mechanize.
Staged computation. Davies and Pfenning [2001] proposed a type-theoretic foundation for staged computation grounded in the intuitionistic modal logic S4. The box modality □A denotes closed code to be evaluated at a later stage. The construct box(e) encapsulates e for future execution, and requires the enclosed code to be closed. Contextual modal type theory [Nanevski et al. 2008] generalizes this to contextual modalities. A contextual type [Ψ]A types code that may refer to the term bindings listed in Ψ, through the construct box Ψ.e. A parallel line of work uses environment classifiers [Calcagno et al. 2004; Taha and Nielsen 2003; Tsukada and Igarashi 2010] to regulate staging. Classifiers record the term bindings that code may rely on across stage boundaries. The construct run is permitted only when those dependencies are satisfied.
Our boxes resemble both lines of work, since each carries an explicit environment of bindings. The difference is what the environment holds. Contextual modalities and classifiers track the term bindings that code may use, and they regulate when code runs. instead tracks type information in box types. Our box expression packages a term-level environment, and box type carries the type context needed to type A. We use manifest bindings and a two-sided type-equivalence judgment to internalize type instantiation and thereby eliminate substitution. Our boxes therefore do not control when code runs. They make environments explicit at the value and type level.
8 Conclusion
We have presented , showing that a polymorphic calculus with first-class environments can be constructed without relying on the meta-level substitution traditionally used in System F. A key insight of this work is that manifest types combined with type equivalence provide a sufficient mechanism to handle type instantiation, effectively internalizing it within the environment semantics.
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
This shift simplifies mechanization of the metatheory by replacing substitution and substitution lemmas with instantiation lemmas, and is fully mechanized in Rocq.
On the practical side, demonstrates that the benefits of first-class environments extend to languages with polymorphism. The calculus naturally supports: polymorphic first-class modules with type components that are transparently exposed to clients; robust sandboxing, where code execution is strictly isolated within explicit local environments; and dynamic composition of environments and modules. Future work incorporating subtyping can extend this foundation to support features such as opaque sealing, further bridging the gap between first-class environments and full-scale module systems.
Data-Availability Statement
The mechanization, implementation, and example code are available at https://github.com/tjhao/PolyFirstClassEnvs. Parts of the Rocq mechanization were carried out with the assistance of large language models.
References
Martín Abadi, Luca Cardelli, Pierre-Louis Curien, and Jean-Jacques Lévy. 1991. Explicit Substitutions. J. Funct. Program. 1, 4 (1991), 375–416. doi:10.1017/S0956796800000186
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). Association for Computing Machinery, 666–679.
Nada Amin, Tiark Rompf, and Martin Odersky. 2014. Foundations of Path-Dependent Types. In Proceedings of the 2014 ACM SIGPLAN Conference on Object-Oriented Programming, Systems, Languages, and Applications (OOPSLA). ACM, 233–249. doi:10.1145/2660193.2660216
Cristiano Calcagno, Eugenio Moggi, and Walid Taha. 2004. ML-Like Inference for Classifiers. In Programming Languages and Systems (ESOP 2004) (Lecture Notes in Computer Science, Vol. 2986). Springer, 79–93. doi:10.1007/978-3-540-24725-8_7
Pierre Crégut. 2007. Strongly reducing variants of the Krivine abstract machine. Higher-Order and Symbolic Computation 20, 3 (2007), 209–230.
Pierre-Louis Curien, Thérèse Hardin, and Jean-Jacques Lévy. 1996. Confluence Properties of Weak and Strong Calculi of Explicit Substitutions. J. ACM 43, 2 (1996), 362–397. doi:10.1145/226643.226675
Rowan Davies and Frank Pfenning. 2001. A modal analysis of staged computation. J. ACM 48, 3 (2001), 555–604. doi:10.1145/382780.382785
Nicolaas Govert De Bruijn. 1972. Lambda calculus notation with nameless dummies, a tool for automatic formula manipulation, with application to the Church-Rosser theorem. In Indagationes mathematicae (proceedings), Vol. 75. Elsevier, 381–392.
Derek Dreyer. 2005. Understanding and Evolving the ML Module System. Ph.D. Thesis. Carnegie Mellon University, Pittsburgh, PA, USA. https://people.mpi-sws.org/~dreyer/thesis/main.pdf
Derek Dreyer. 2007. A type system for recursive modules. In Proceedings of the 12th ACM SIGPLAN International Conference on Functional Programming, ICFP 2007, Freiburg, Germany, October 1-3, 2007, Ralf Hinze and Norman Ramsey (Eds.). ACM, 289–302. doi:10.1145/1291151.1291196
Alain Frisch and Jacques Garrigue. 2010. First-class modules and composable signatures in Objective Caml 3.12. In Proceedings of the 2010 ACM SIGPLAN Workshop on ML (ML'10). Baltimore, MD, USA. https://www.math.nagoya-u.ac.jp/~garrigue/papers/ml2010.pdf Extended abstract.
David Gelernter, Suresh Jagannathan, and Thomas London. 1987. Environments as First Class Objects. In Conference Record of the Fourteenth Annual ACM Symposium on Principles of Programming Languages, Munich, Germany, January 21-23, 1987. ACM Press, 98–110. doi:10.1145/41625.41634
Jean-Yves Girard. 1972. Interprétation fonctionnelle et élimination des coupures de l'arithmétique d'ordre supérieur. Ph.D. Dissertation. Université Paris 7.
Robert Harper. 2016. Practical Foundations for Programming Languages. Cambridge University Press.
Robert Harper and Mark Lillibridge. 1994. A type-theoretic approach to higher-order modules with sharing. In Proceedings of the 21st ACM SIGPLAN-SIGACT symposium on Principles of programming languages. 123–137.
Suresh Jagannathan. 1994a. Dynamic Modules in Higher-Order Languages. In Proceedings of the IEEE Computer Society 1994 International Conference on Computer Languages, May 16-19, 1994, Toulouse, France, Henri E. Bal (Ed.). IEEE Computer Society, 74–87. doi:10.1109/ICCL.1994.288391
Suresh Jagannathan. 1994b. Metalevel Building Blocks for Modular Systems. ACM Trans. Program. Lang. Syst. 16, 3 (1994), 456–492. doi:10.1145/177492.177578
Gilles Kahn. 1987. Natural semantics. In Annual symposium on theoretical aspects of computer science. Springer, 22–39.
Scott Kilpatrick, Derek Dreyer, Simon L. Peyton Jones, and Simon Marlow. 2014. Backpack: retrofitting Haskell with interfaces. In The 41st Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, POPL '14, San Diego, CA, USA, January 20-21, 2014, Suresh Jagannathan and Peter Sewell (Eds.). ACM, 19–32. doi:10.1145/2535838.2535884
Alexei Kopylov. 2003. Dependent Intersection: A New Way of Defining Records in Type Theory. In 18th IEEE Symposium on Logic in Computer Science (LICS 2003), 22-25 June 2003, Ottawa, Canada, Proceedings. IEEE Computer Society, 86–95. doi:10.1109/LICS.2003.1210048
Jean-Louis Krivine. 2007. A call-by-name lambda-calculus machine. Higher-order and symbolic computation 20, 3 (2007), 199–207.
Xavier Leroy. 1994. Manifest Types, Modules, and Separate Compilation. In Proceedings of the 21st ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL). ACM, 109–122. https://inria.hal.science/hal-01499976/document
Xavier Leroy, Damien Doligez, Alain Frisch, Jacques Garrigue, Didier Rémy, and Jérôme Vouillon. 2011. The OCaml system, release 3.12: Documentation and user's manual. INRIA. https://ocaml.org/releases/3.12/ocaml-3.12-refman.pdf
David B. MacQueen. 1984. Modules for Standard ML. In Proceedings of the 1984 ACM Conference on LISP and Functional Programming. ACM, 198–207. doi:10.1145/800055.802036
David B. MacQueen and Mads Tofte. 1994. A Semantics for Higher-Order Functors. In Programming Languages and Systems — ESOP '94 (Lecture Notes in Computer Science, Vol. 788). Springer, 409–423. doi:10.1007/3-540-57880-3_27
Simon Marlow. 2010. Haskell 2010 Language Report. https://api.semanticscholar.org/CorpusID:62028548
Darya Melicher, Yangqingwei Shi, Alex Potanin, and Jonathan Aldrich. 2017. A Capability-Based Module System for Authority Control. In ECOOP (LIPics, Vol. 74). Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 20:1–20:27.
James S. Miller and Guillermo Juan Rozas. 1991. Free Variables and First-Class Environments. LISP Symb. Comput. 4, 2 (1991), 107–141.
Mark Miller. 2006. Robust composition: Towards a unified approach to access control and concurrency control. Johns Hopkins University.
Mark S. Miller, Chip Morningstar, and Bill Frantz. 2000. Capability-Based Financial Instruments. In Financial Cryptography, 4th International Conference, FC 2000 Anguilla, British West Indies, February 20-24, 2000, Proceedings (Lecture Notes in Computer Science, Vol. 1962), Yair Frankel (Ed.). Springer, 349–378. doi:10.1007/3-540-45472-1_24
Mark S Miller, Mike Samuel, Ben Laurie, Ihab Awad, and Mike Stay. 2008. Safe active content in sanitized JavaScript. Google, Inc., Tech. Rep (2008).
Robin Milner, Mads Tofte, Robert Harper, and David MacQueen. 1997. The Definition of Standard ML (Revised). MIT Press.
Aleksandar Nanevski, Frank Pfenning, and Brigitte Pientka. 2008. Contextual modal type theory. ACM Transactions on Computational Logic (TOCL) 9, 3 (2008), 1–49.
Shin-ya Nishizaki. 1994. Simply Typed Lambda Calculus with First-Class Environments. Publications of the Research Institute for Mathematical Sciences 30, 6 (1994), 1055–1121.
Shin-ya Nishizaki. 2000. A Polymorphic Environment Calculus and its Type-Inference Algorithm. High. Order Symb. Comput. 13, 3 (2000), 239–278. doi:10.1023/A:1010010314528
Shin-ya Nishizaki. 2017. Second-order type theory for first-class environment. In AIP Conference Proceedings, Vol. 1839. AIP Publishing LLC, 020143.
Benjamin C. Pierce. 2002. Types and programming languages. MIT Press.
Christian Queinnc and David De Roure. 1996. Sharing Code Through First-Class Environments. In Proceedings of the 1996 ACM SIGPLAN International Conference on Functional Programming (ICFP 1996). ACM, Philadelphia, Pennsylvania, USA, 251–261. doi:10.1145/232627.232653
John C. Reynolds. 1974. Towards a Theory of Type Structure. In Programming Symposium (Colloque sur la Programmation) (Lecture Notes in Computer Science, Vol. 19). Springer, 408–425.
John C Reynolds. 1997. Design of the programming language Forsythe. In ALGOL-like languages. Birkhauser Boston Inc., 173–233.
Andreas Rossberg. 2018. 1ML: Core and Modules United. Journal of Functional Programming 28 (2018), e17. doi:10.1017/S0956796818000180
Andreas Rossberg and Derek Dreyer. 2013. Mixin' Up the ML Module System. ACM Transactions on Programming Languages and Systems 35, 1, Article 2 (2013), 2:1–2:84 pages. doi:10.1145/2422068.2422070
Andreas Rossberg, Claudio Russo, and Derek Dreyer. 2014. F-ing modules. Journal of Functional Programming (JFP) 24, 05 (2014), 529–607.
Claudio V. Russo. 1998. Types for Modules. Ph. D. Dissertation. University of Edinburgh, Edinburgh, UK. http://hdl.handle.net/1842/385 LFCS Thesis ECS-LFCS-98-389.
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
Claudio V. Russo. 2000. First-Class Structures for Standard ML. In Proceedings of the European Symposium on Programming (ESOP 2000) (Lecture Notes in Computer Science, Vol. 1782), Gert Smolka (Ed.). Springer-Verlag, 336–350. doi:10.1007/3-540-46425-5_22
Masahiko Sato, Takafumi Sakurai, and Rod M. Burstall. 2001. Explicit Environments. Fundamenta Informaticae 45, 1-2 (2001), 79–115. http://content.iospress.com/articles/fundamenta-informaticae/fi45-1-2-05
Masahiko Sato, Takafumi Sakurai, and Yukiyoshi Kameyama. 2002. A Simply Typed Context Calculus with First-Class Environments. Journal of Functional and Logic Programming (2002). http://danae.uni-muenster.de/lehre/kuchen/JFLP/articles/2002/S02-01/JFLP-A02-04.pdf
John N. Shutt. 2010. Fexprs as the basis of Lisp function application; or, $vau: the ultimate abstraction. Ph.D. Dissertation. Worcester Polytechnic Institute, Worcester, MA. Ph.D. Dissertation.
Walid Taha and Michael Florentin Nielsen. 2003. Environment Classifiers. In POPL '03: Proceedings of the 30th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages. ACM, New Orleans, LA, USA, 26–37. doi:10.1145/640128.604134
William W. Tait. 1967. Intensional Interpretations of Functionals of Finite Type I. J. Symb. Log. 32, 2 (1967), 198–212. doi:10.2307/2271658
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.
Jinhao Tan and Bruno C. d. S. Oliveira. 2024. A Case for First-Class Environments. Proc. ACM Program. Lang. 8, OOPSLA2 (2024), 2521–2550. doi:10.1145/3689800
The Go Team. 2024. The Go Programming Language Specification. https://go.dev/ref/spec
The Rust Team. 2020. The Rust Programming Language. https://rust-lang.org
Takeshi Tsukada and Atsushi Igarashi. 2010. A Logical Foundation for Environment Classifiers. Logical Methods in Computer Science 6, 4 (2010), 1–43. doi:10.2168/LMCS-6(4:8)2010
Jérôme Vouillon. 2012. A solution to the poplmark challenge based on de bruijn indices. Journal of Automated Reasoning 49, 3 (2012), 327–362.
J. B. Wells. 1999. Typability and Type Checking in System F Are Equivalent and Undecidable. Annals of Pure and Applied Logic 98, 1–3 (1999), 111–156.
A.K. Wright and M. Felleisen. 1994. A Syntactic Approach to Type Soundness. Information and Computation 115, 1 (1994), 38–94.
Jeremy Yallop. 2010. First-class modules: hidden power and tantalizing promises. https://okmij.org/ftp/ML/first-class-modules/first-class-modules.pdf. Practice-oriented paper with examples (with Oleg Kiselyov).
A From Hint Notation to de Bruijn Notation
The examples in the paper use the hint notation. Deleting the gray binder annotations and replacing each hinted variable by the corresponding index recovers the formal de Bruijn term. The following table lists the hinted examples used in the paper together with their de Bruijn forms.
| hint notation | pure de Bruijn notation |
|---|---|
B Auxiliary Definitions
This section gives the auxiliary operations omitted from the main paper. For each, we point to the rules in which it is used.
Context membership. The membership condition (used in rule WFT-VAR) holds when the N-th type entry is an abstract type binding:
(1) if
(2) if
(3)
(4) if
Type-variable lookup. The lookup (used in rule WFT-VAREQ, rule TEQ-EQL, and rule TEQ-EQR) holds when the N-th type entry is a concrete binding of type . Note that denotes the
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
shifting of type A, which is applied when a lookup descends past a type binding.
(1) if
(2) if
(3)
(4) if
Term-variable lookup. The lookup (used in rule TYP-VAR) retrieves the type A of the n-th term entry. Similarly to type-variable lookup, the shifting operation is necessary when the context is extended with a type binding.
(1) if
(2) if
(3)
(4) if
Well-formed contexts. The judgment states that a context is well-formed. The empty context is well-formed; an abstract type binding extends a well-formed context; and a term binding or a manifest type binding requires its type to be well-formed under the preceding context.
WFE-NIL
WFE-EDEF
WFE-STAR
WFE-TDEF
Context concatenation. The operation (used in well-formedness, typing, and type equivalence for environment types) appends the entries of to . It recurses on its right operand:
(1)
(2)
(3)
(4)
Rigidity. The rigidity judgment is used for the well-formedness of box types (rule WFT-BOX). A type is rigid in a context at depth when each of its free type variables is either bound by one of the innermost binders or pinned to a concrete (manifest) definition that is itself rigid. Formally, the depth-indexed judgment is defined as:
R-INT
R-AVAR
R-CVAR
R-RCD
R-MANI
R-ALL
R-EDEF
R-TDEF
R-STAR
R-BOX
Here is the number of type bindings in . We define as , i.e. rigidity at depth 0.
Extraction. The operation (used in rule STEP-TAPP and rule STEP-TDEF) extracts the type information from a value environment:
(1)
(2)
(3) , [A]
Environment concatenation. The operation (used in rule STEP-EDEF and rule STEP-TDEF) appends the entries of environment to . Similar to , it recurses on its right operand :
(1)
(2)
(3)
C Type-Erasing Semantics of
The syntax and reduction rules for the type-erasing semantics are given in Figure 12. Type entries are removed from environments and value environments. Moreover, a dummy application e_
Expressions
Environments
Values
Value environments
Frames
(Type-erasing Semantics)
ESTEP-EVAL
ESTEP-VAR
ESTEP-BOX
ESTEP-BOXV
ESTEP-DUMMY
ESTEP-BETA
ESTEP-CLOS
ESTEP-BCLOS
ESTEP-EDEF
Fig. 12. Syntax and reduction rules for the type-erasing semantics.
replaces the original type application e A. Hence, there is no type information in the erased syntax. To be distinguishable, we use the subscript to represent the type-erasing semantics. The reduction rules for the type-erasing semantics are mostly the same as in the original semantics. Nevertheless, rule STEP-TAPP is replaced with rule ESTEP-DUMMY. In this rule, the dummy application consumes the type abstraction closure, and simply returns a boxed expression e along with the environment captured by the closure. Furthermore, rule STEP-TDEF that performs runtime type computation for environments is removed, since in the erased syntax there is no type entries in environments.
Importantly, we show that the type-erasing semantics reduces to the same (erased) values as the type-passing semantics. The erasure function is defined as:
This erasure function is similar to the one used in TAPL [Pierce 2002] to show the erasure of System F terms. In particular, the erasure of type application is defined as , which is a dummy application that does not carry any type information. Moreover, in our setting, we also erase types from environments , since environments in are first-class and they can contain type entries.
D Measures for Deciding Type Equivalence
To establish the decidability of our type equivalence relation, we define measures for types and typing contexts, both parameterized by a measure context defined as . Intuitively, the measure context keeps track of the sizes of bindings bound in the typing context, where is for term variable bindings and is for type variable bindings. The definitions of measures are given next.
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
Definition D.1 (Measures for Decidability). The measure for types and for contexts are:
The measure for types is a natural number that is the size of type A with respect to the measure context . Moreover, measure is producing a list of natural numbers, which is essentially a measure context. These two measures are defined mutually.
Unlike System F, a context in can be used as a first-class environment type, and thus it can depend on the global context. Hence, is equipped with a measure context , which acts as the global measure context. To compute the measure of context , A with , the measure of is first computed by . Moreover, since A can depend on , the size of A should be computed with , the concatenation of global measure context and the measure for . Moreover, for an abstract type variable binding , the measure context is extended with . For a concrete type variable binding , the measure is computed similarly to term variable bindings, except that the measure context is extended with , signaling that the size is for a type variable binding.
The size measure for types is defined according to the structure of types. The size of a type variable is determined by looking up the measure context at index , which gives the size of the type bound to that type variable. The size of a manifest type is computed by first computing the size of , which is a natural number , and then computing the size of with the measure context extended with . Moreover, for a box type , the size is computed by computing the size of , with respect to the measure context derived from with an empty measure context, since the local context in a box is closed. Finally, when computing the size of an environment type, the size of a term binding or a concrete type binding is computed with respect to the measure context extended with .
E Semantic Typing and Normalization for
We prove normalization of through a unary logical relation that interprets each type as a set of values (a reducibility candidate). The relation yields a notion of semantic typing. By the fundamental theorem, every well-typed term is semantically well-typed, and normalization follows as a corollary. The development is mechanized in Rocq.
A candidate R is a set of values, and serves as the semantic interpretation of types. A semantic environment (defined as ) assigns a candidate to each de Bruijn type variable. The logical relation relies on two auxiliary operations on candidates and environments: . if then else , which conses a candidate R at slot 0 of , and . , which drops slot 0 of .
Figure 13 shows the definition of the logical relation. Judgment is the type interpretation: A is a type formed in a context interpreted by the semantic environment . The interpretation for integers, type variables, and function types is standard. In the clause of manifest types , the type variable is assigned the interpretation , and the body B is read with at slot 0. In the clause, a polymorphic value is reducible iff, for every candidate R, the
Type interpretation :
i.e. set of all integer literals
Context interpretation :
Realizer-free interpretation :
Fig. 13. The logical relation, comprising the type interpretation , context interpretation , and realizer-free interpretation .
body produces a value in . Hence, the abstract variable is interpreted by the arbitrary , and the type argument actually stored in the runtime environment is irrelevant. In particular, ranges over the empty candidate, so . is uninhabited.
The uninhabitedness of is why the box clause is realizer-free: rather than demanding a value environment that realizes the local context , it reads the body A under some environment in realizer-free agreement with , written . Realizer-free interpretation constrains only the manifest type entries of : a manifest binding fixes slot 0 to the interpretation of its definition. For abstract type bindings, the interpretation is unconstrained because of the rigidity requirement: a rigid type A formed in context cannot refer to the abstract bindings. For term bindings, realization demands an inhabitant and so can fail: type equivalence identifies box types whose local context has no realizer, for instance , where realizing would require a value of the uninhabited , yet the box type must stay inhabited like Int. With realizer-free interpretation, such box types whose local context contains uninhabited types remain inhabited.
For an environment type, its own internal type bindings are not entries of the ambient environment , so the clauses for environment types existentially provide a combined environment whose low slots carry 's own type bindings (ensured by the context interpretation ) and whose high part is (encoded as ). The manifest and abstract clauses are identical: in both, the newly stored entry is a type definition , on which the type interpretation imposes no condition. The definition A only fixes how the type variable it introduces is interpreted, and that variable is read only when the environment is used as a context, by the later types formed under it.
Jinhao Tan, Jam Kabeer Ali Khan, and Bruno C. d. S. Oliveira
Judgment is the interpretation for contexts: it holds when the environment realizes entry by entry under . The low slots of hold 's type bindings, one per slot, and the recursive clauses reach them by recurring under . Because these slots already carry 's bindings, a type well-formed in is interpreted at this same : its de Bruijn indices into point to exactly these slots.
Semantic typing and normalization. With the interpretation of types and contexts, we define semantic typing as follows: for every value environment that interprets , the evaluation of under produces a value in the interpretation of .
We prove the following fundamental theorem, which states that every syntactically well-typed term is also semantically well-typed.
THEOREM E.1 (FUNDAMENTAL THEOREM). If then .
The proof is by induction on the typing derivation, with one compatibility lemma per typing rule. In particular, because the typing judgment contains a type-equivalence rule, we need to prove the following compatibility lemma, which shows that equivalent types have the same interpretation in the semantic typing:
LEMMA E.2 (SOUNDNESS OF TYPE EQUIVALENCE). If and then .
With the fundamental theorem, we can prove the normalization theorem as a corollary by instantiating the typing judgment with the empty context.
COROLLARY E.3 (NORMALIZATION). If , then for some value .
F A Source Language and its Elaboration
This appendix gives the full source language and elaboration outlined in Section 6.2, formalizing the module constructs illustrated in Section 2.5. Figure 14 gives its syntax, the elaboration rules for module expressions and declarations, and the expansion of merge operands; Theorem F.5 states that elaboration preserves typing.
LEMMA F.1 (CLOSED TYPES ARE SHIFT-INVARIANT). If , then .
LEMMA F.2 (ENVIRONMENT GROWTH). If and , then .
LEMMA F.3 (EXISTENCE OF LABEL LOOKUP). If , and , then for some B.
LEMMA F.4 (SOUNDNESS OF EXPANSION). If ; and , then .
THEOREM F.5 (ELABORATION PRESERVES TYPING). If , then ; and if , then .
Module expressions
Declarations
\begin{aligned}&\frac{\mathrm{ELAB-APP}}{\Gamma\vdash\mathsf{M}_{1}\rightsquigarrow e_{1}\colon\mathsf{A}\to\mathsf{B}}\qquad\Gamma\vdash\mathsf{M}_{2}\rightsquigarrow e_{2}\colon\mathsf{A}}{\Gamma\vdash\mathsf{M}_{1}\mathsf{M}_{2}\rightsquigarrow e_{1}e_{2}\colon\mathsf{B}}\quad&\frac{\mathrm{ELAB-TAPP}}{\Gamma\vdash\mathsf{M}\rightsquigarrow e\colon\forall\mathsf{B}}\qquad\Gamma\vdash\mathsf{A}}{\Gamma\vdash\mathsf{M}\mathsf{A}\rightsquigarrow e\mathsf{A}:[\mathsf{A}]\mathsf{B}}\end{aligned} \begin{aligned}&\frac{\mathrm{EXP-NIL}}{\Gamma;\mathsf{k}:\Gamma_{1}\vdash\Delta:\Gamma_{2}\xrightarrow{\cdot}\Delta:\Gamma_{2}}\quad&\frac{\mathrm{EXP-RCD}}{\Gamma;\mathsf{k}:\Gamma_{1}\vdash\Delta:\Gamma_{2}\xrightarrow{\Gamma_{3}}\Delta_{1}:\Gamma_{4}\qquad l\colon\mathsf{B}\in\Gamma_{1}}\\&\quad\frac{\mathrm{EXP-TDEF}}{\Gamma;\mathsf{k}:\Gamma_{1}\vdash\Delta:\Gamma_{2}\xrightarrow{\Gamma_{3}}\Delta_{1}:\Gamma_{4}\qquad\Gamma+\Gamma_{4}\vdash\mathsf{A}}\\&\quad\frac{\Gamma;\mathsf{k}:\Gamma_{1}\vdash\Delta:\Gamma_{2}\xrightarrow{\Gamma_{3},[\mathsf{A}]}\Delta_{1},[\mathsf{A}]:\Gamma_{4},[\mathsf{A}]}\end{aligned}Fig. 14. The source language: its syntax, the elaboration of module expressions and of declarations , and the expansion of a merge operand (from top to bottom).