Manuscript Offprint
arXiv:2610.25741Compiling Environment Classifiers to Contextual Modal Types
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Tianyu Chen , Darshal Shetty , Jeremy G. Siek
Chao-Hong Chen , Weixi Ma , Arnaud Venet , and Rocky Liu
Indiana University, Bloomington, IN, USA
{chen512,dcshetty,jsiek}@iu.edu
Meta, Menlo Park, CA, USA
{chaohong,mavc,ajv,rockyliu4}@meta.com
Abstract. Type systems for metaprogramming take one of two approaches to safeguarding the scopes of variables in generated code. They either use Environment Classifiers (EC) to identify scopes by name (Taha and Nielsen, 2003), or they use Contextual Modal Type Theory (CMTT) to match scopes by structure (Nanevski, Pfenning, and Pientka, 2008). In this paper, we connect these two approaches by compiling a calculus with polymorphic environment classifiers, subtyping, and mutable references to a CMTT-based calculus with polymorphic contexts, mutable references, and first-class substitutions. The key idea is to map each environment classifier to a context. We prove that the compilation preserves types and that compilation preserves the behavior of metaprograms. Both proofs are mechanized in Agda. The compilation shows that CMTT is at least as expressive as environment classifiers. We conjecture that the converse compilation is difficult, because environment classifiers impose a stricter regime on the metaprogram.
Keywords: Metaprogramming · Multi-stage programming · Environment classifiers · Contextual modal types · Mechanized metatheory
1 Introduction
Metaprogramming is the paradigm in which a program in a metalanguage generates a program in a code language. In this paper, we study the relationship between two typing disciplines for metaprogramming with open code, that is, code fragments with free variables: environment classifiers [25], which name the scope in which the code is meaningful, and contextual modal types [20], which spell out that scope as a typing context. Both guarantee that generated programs are well typed and well scoped, but they have been developed largely independently. We show that every scope named by a classifier can be translated into a context, define a compiler from a calculus with environment classifiers to one with contextual modal types, and prove that compilation preserves types and that source and target programs generate the same code.
In the tradition of MetaML [26, 27], the type system of the metalanguage tracks the type of quoted code, so that every generated program is well typed.
T. Chen et al.
A temporal-logic approach to binding-time analysis.
Davies 1996 [6]
( : open code, but no run)
A modal analysis of staged computation.
Davies and Pfenning 1996 [8]
( : run, but only closed code)
Environment Classifiers
Environment classifiers.
Taha and Nielsen
2003 [25]
( : open code and run)
Refined environment classifiers.
Kiselyov, Kameyama, and Sudo
2016 [15]
(<NJ>: mutable references)
Refined environment classifiers.
Murase and Igarashi
2026 [18]
(R EC: classifier polymorphism)
Contextual Modal Types
Contextual modal type theory.
Nanevski, Pfenning, and Pientka
2008 [20]
Contextual modal type theory
with polymorphic contexts.
Murase, Nishiwaki, and Igarashi
2023 [19]
( : context polymorphism)
Contextual MetaML.
Yin, Murawski, and Ong
2026 [29]
(mutable references)
This paper
Fig. 1. Two approaches to the scopes of generated code: environment classifiers (left) and contextual modal types (right). Both lines descend from the modal and temporal analyses of staged computation and are connected through compilation in this paper.
The difficulty lies with open code: the free variables of a fragment are bound by binders of the code language outside the fragment, so the type system must also record the scope in which the fragment is meaningful. Otherwise the fragment may leave that scope, through run or through a mutable reference, and the generated program ends up with unbound variables, a failure known as scope extrusion [14–16].
Two lines of research (Figure 1) have developed type systems that track open code fragments and keep generated code well scoped in the presence of run or mutable references. Both lines descend from the Curry–Howard-style analyses of staged computation. The calculus of Davies and Pfenning [8, 9] is based on the necessity operator of the intuitionistic modal logic S4: a term of type is closed code of type A, which can safely be evaluated, but the calculus manipulates closed code only. On the other hand, the calculus of Davies [6, 7] is based on the “next” operator of linear-time temporal logic: a term of type is code that may contain free variables. Thus enables the manipulation of open code, which makes it a foundation for the partial evaluation of functional languages [7]. However, does not include run because its type system would not be able to prevent scope extrusion in that case [7, 25].
Practical metaprogramming needs both the manipulation of open code and run. Environment classifiers start from and add run; contextual modal types start from and add support for open code.
Environment classifiers. The research on environment classifiers, the left arrow of Figure 1, grows out of and MetaML, the latter of which combines open code with run [17, 26, 27]. As an early solution, Calcagno et al. [3, 4] propose closed types, which single out the code types whose values are known to be closed. They restrict run to code of closed type, and similarly for constructing mutable references to code. Taha and Nielsen [25] then introduce Environment Classifiers (EC). An environment classifier is a name of a scope, and a code type records the classifier of the scope in which its code, possibly open, is meaningful. The type system checks by name that a code fragment only mentions variables, and only splices code, of the same classifier. It permits run only on code whose classifier is universally quantified, which guarantees that the code is closed. Early versions of MetaOCaml adopted this discipline [5, 24], and Tsukada and Igarashi [28] give it a logical foundation through a Curry–Howard correspondence with a multi-modal logic.
Refined environment classifiers. Mutable references reintroduce the scope extrusion problem, because open code can be smuggled out of its scope by storing it in a reference. Kiselyov, Kameyama, and Sudo [15] rule out such scope extrusions statically with refined environment classifiers, which mark every code-level binder with its own classifier, ordered by the nesting of the binders, so that storing code in a reference cell with an incompatible classifier is a type error. Isoda et al. [11] add algebraic effects and handlers to refined environment classifiers, and Murase and Igarashi [18] extend them to multi-level staging with run, cross-stage persistence, and polymorphism over classifiers.
Contextual modal types. The research on contextual modal types, the right arrow of Figure 1, grows out of . Building on the judgmental reconstruction of modal logic by Pfenning and Davies [21], Nanevski, Pfenning, and Pientka [20] restrict the necessity modality to an explicit context and obtain Contextual Modal Type Theory (CMTT). A contextual code type lists the context in which its code is well typed, so open code becomes expressible, and using the code in another context requires an explicit substitution [1] that provides a term for every variable in . Contextual modal types thus give a uniform account of code with free variables and of the substitutions that instantiate those variables. CMTT has been extended in directions relevant to our paper: Moebius [12] combines it with System F and pattern matching on code. [19] adds polymorphic contexts. Contextual MetaML [29] adds higher-order references that may hold open code and establishes full abstraction via operational game semantics. Closely related to our work, Murase et al. [19] translate , restricted to two levels, into . There are two insights from their translation that we use in our compilation from EC to CMTT. First, quote and splice are translated by constructing code contexts and explicit substitutions, respectively. Second, code contexts are made explicit by following the binding structure of generated code.
T. Chen et al.
Two other type systems index code types by the typing context, independently of CMTT. Kim, Yi, and Calcagno [13] let the surrounding context capture variables by name, so code may be spliced into any context that binds at least its free variables, whereas the calculus of Rhiger [23] binds them lexically.
Both EC and CMTT record information about the scope of open code in the code type and support manipulating open code in the presence of mutable references. However, they differ in how code variables are bound, as observed by Murase and Igarashi [18]. We elaborate on the difference using examples.
Variable binding in environment classifiers. Consider the following program in a metalanguage with environment classifiers. It assembles two pieces of code, c1 and c2, and splices them into a third. We write ... for a quotation with classifier and a tilde ( ) for a splice. Variable bindings are highlighted.
1 ~(λ (x:Int) α. λ (y:Int) β. Environment classifiers (EC) 2 ~(let c1 = ~x * 2"α in /* the scope of α contains x / 3 let c2 = ~x + y"β in / the scope of β contains x and y */ 4 ~c1 - ~c2"β)) 5 43 1"ε
In a calculus with environment classifiers, a code variable is bound by a λ-abstraction in its lexical scope, even though quotations and splices intervene. The occurrences of x in c1 and c2 are bound by λ (x:Int) α (red arrow), and the y in c2 by λ (y:Int) β (blue arrow). This binding structure is inherited from λ〇 [6, 7]. Scopes of binders in code are identified by names such as α and β. The abstraction λ (x:Int) α binds both the code variable x and the classifier α that names its scope (line 1), and the inner abstraction λ (y:Int) β binds y and β. The scope named by β lies within the scope named by α, so the type system introduces the subtyping α <: β. Both quotes and their code types are annotated with classifiers, so c1 (line 2) has type ~Int"α and c2 has type ~Int"β. Due to the subtyping in this example, a piece of code with classifier α may be spliced wherever classifier α or β is expected such as the splice of c1 (line 4), and β may be spliced wherever β is expected, such as c2 (line 3). A calculus based on EC thus relates scopes through their names and the subtyping between those names. We therefore refer to environment classifiers as a nominal approach to ensuring scope safety. The type system ensures that metaevaluation ultimately produces closed code, in this example ~(λ (x:Int) α. λ (y:Int) β. (x * 2) - (x + y)) 43 1"ε, where ε is the classifier of the empty scope.
Variable binding in contextual modal types. Here is the same program in a metalanguage with contextual modal types. Variable bindings are highlighted.
1 ~∅ ⊥ (λ (x:Int). λ (y:Int). Contextual modal types (CMTT) 2 ~(let c1 = ~x:Int ⊥ x * 2" in 3 let c2 = ~x:Int, y:Int ⊥ x + y" in 4 ~x:Int, y:Int ⊥ ~c1{x=x} - ~c2{x=x,y=y}'') {x=x,y=y} 5 43 1"
In a calculus with contextual modal types, each piece of code carries a typing context, such as x:Int and (x:Int, y:Int), which identifies the scope of the code by spelling out the variables that the code may mention together with their types. In CMTT, it is this context annotation on a quotation that binds the variables of the quoted code, not an enclosing λ-abstraction. The annotation x:Int of c1 binds the x in x * 2 (red arrow, line 2), and the annotation (x:Int, y:Int) of c2 binds both x (yellow arrow) and y (blue arrow) in x + y (line 3). The x in c1, the x in c2, and the x bound by λ (x:Int) (line 1) are therefore three different variables, so every splice must say how the variables of the spliced code relate to those of the surrounding context. The splice ~c1{x=x} (line 4) applies to c1 an explicit substitution of type (x:Int) ⇒ (x:Int, y:Int), which maps the x of c1, bound by its context annotation, to the x of the surrounding context (x:Int, y:Int). Similarly, the splice ~c2{x=x, y=y} substitutes the two variables of c2, and the outermost splice applies {x=x, y=y}, which maps the variables of the annotation on line 4 to the ones bound by the two λ-abstractions. The program makes each substitution explicit, and the type system checks that it provides a term for every variable of the context. Whether code of one context can be used in another thus depends only on the variable names and their types. We therefore call CMTT the structural approach to scopes. Code types mention contexts, so c1 has type ~x:Int ⊥ Int" and c2 has type ~x:Int, y:Int ⊥ Int". Metaevaluation performs the substitutions and produces the closed code ~∅ ⊥ (λ (x:Int). λ (y:Int). (x * 2) - (x + y)) 43 1", where ∅ is the empty context.
In CMTT, code fragments can be assembled even if their scopes are not nested, which EC cannot express. In the following program, c is constructed outside any -abstraction in code and carries the context y:Int, which binds y (line 1, highlighted), and is then spliced under the abstraction (x:Int).
1 let c = ~y:Int ⊥ y * 2" in 2 ~∅ ⊥ (λ (x:Int). ~c{y=x}) 21"
Reconnecting binders in CMTT
The substitution reconnects the variable y of c to the variable x bound by the abstraction (line 2, highlighted), and metaevaluation produces the closed code .
This program has no counterpart in EC, where the code can only be written within the scope of a that binds y and can only be spliced into code
T. Chen et al.
within that scope. It can never be constructed outside any and rewired to a binder of an unrelated scope. The difference between the two approaches mirrors the one between nominal and structural type systems [22]: a nominal type system relates two types only when the program declares their names related, whereas a structural one relates them whenever their types match.
Environment classifiers identify the scope of code by a name, whereas contextual modal types identify it by the typing context. We observe that a classifier can be compiled into a code-level context that includes the variables and types in scope at the classifier. This intuition leads to the main contribution of our paper: compiling EC into CMTT, and thereby connecting the nominal and structural approaches to scopes.
This paper: compiling from EC to CMTT. Our compilation extends the translation of Murase et al. [19], discussed above, to a source language with environment classifiers and mutable references. The source language, , is a metaprogramming calculus with refined environment classifiers and mutable references, extended with unrestricted subtyping and subtype-bounded classifier polymorphism. The target language, , combines features of recent extensions of contextual modal type theory. The calculus is a two-level metaprogramming language that supports mutable references and polymorphic contexts. To these, adds first-class substitutions in support of the compilation. Both and are restricted to two levels, because going beyond two levels with mutable references in CMTT is an open problem [29]. We do not include run, because mutable references already make scope safety nontrivial, and the mechanism that tracks open code fragments for typing run is analogous to the one for references. We define a type-directed compilation from to and prove that it preserves types and that source and target programs generate the same code. This connects the nominal scopes of EC to the structural contexts of CMTT, and it is the main contribution of this paper.
The key to our compilation is identifying the code-level context that an EC corresponds to. The following program and its compilation illustrate this idea.
~(λ (x:Int) α. λ (y:Int) β. ~(let c = ~x + y"β in c)) 41 1"
Source: EC
compiles to ↔
~ 0 | (λ (x:Int). λ (y:Int). ~(let c = ~x:Int, y:Int | ~x:Int | x''{x=x} + y'' in c){x=x,y=y}) 41 1''
Target: CMTT
For each code-level binder annotated with a classifier, such as , the compilation recovers the context of the scope that the binder introduces by following EC subtyping outwards. The binder lies in the scope of an enclosing classifier , so is extended with the variable that the binder binds, and the chain ends at the empty classifier , whose context is empty. The compiler calculates the context for each classifier: , , and . Every classifier annotation of the source is then replaced by the context that it corresponds to, shown in matching colors: corresponds to and to , . The quotation becomes a quotation annotated with , , and the outer quotation, of the empty classifier , is annotated with the empty context . The code-level abstractions lose their classifiers, since the contexts now carry that information. The interesting part is the framed occurrence of , which is bound in the scope named but used in code of classifier . This is allowed because the scope named by lies within the scope named by . In the target, this occurrence compiles to a quotation of in its own context , spliced into the larger context under the substitution . Scope nesting therefore becomes context weakening, witnessed by a substitution. Finally, the splice around the let-expression gains the substitution , which maps the two variables of the quotation's context to the ones bound by the -abstractions.
Metatheoretical results. We prove in Agda that the compilation preserves types and is semantically correct by a bisimulation between configurations of the source and the target. Contextual modal types are thus at least as expressive as environment classifiers, in that any scope described by a name can also be described by a context. We conjecture that the converse direction is difficult, because a classifier can only name a scope that arises from nested binders in code, whereas a contextual modal type may mention any context.
Technical Contributions. This paper makes the following contributions.
-
We present , a two-level CMTT calculus that adds first-class substitutions (to support the compilation) and combines support for mutable references [29] and polymorphic contexts [19].
-
We define a type-directed compilation from to , thereby establishing the connection between the nominal scopes of environment classifiers and the structural contexts of contextual modal types.
-
We prove that the compilation preserves types and that it is semantically correct: source and target programs generate the same code and agree on divergence. Both proofs are fully mechanized in Agda.
Section 2 introduces the compilation through examples, Sections 3 and 4 present and , Section 5 defines the compilation, Section 6 proves it type preserving and semantically correct, and Section 7 concludes. The Appendix, the Agda proof scripts, and the Haskell code for a prototype implementation of the compilation are all in the supplementary material of this paper.
T. Chen et al.
(§ 2.2), into substitutions and coercion functions in . Finally, we compile classifier polymorphism and subtype constraints into context polymorphism and first-class substitutions (§ 2.3).
2.1 Compiling Environment Classifiers to Contexts
In this section, we illustrate the basic pattern of our compilation, which has two parts. First, classifiers become contexts, so code types and quotations mention contexts instead of classifiers. Second, splices become splices under substitutions. We also preview the semantic correctness of the compilation.
Consider the following metaprogram, which generates the code of by squaring twice.
1 ~λ (x:Int) α. Source program (EC) 2 ~(let square = λ (c:~Int"α). ~~c * ~c"α 3 in square (square ~x"α)) "ε
The program uses a single classifier. The λ-abstraction on line 1 binds x and names its scope α. The metafunction square (line 2) takes code of classifier α and returns code of the same classifier that multiplies the argument of the function by itself. Applying square twice to ~x"α (line 3) produces the code ~λ (x:Int) α. (x * x) * (x * x)"ε.
The compilation first identifies the context of each classifier. The abstraction on line 1 binds x in the empty scope, so and . The compilation then replaces every classifier by its context and equips every splice with a substitution. In the listing below, contexts are highlighted in the color of their classifier, and substitutions are underlined.
1 ~∅ | λ (x:Int). Target program (CMTT) 2 ~(let square = λ (c:~x:Int | Int"). ~x:Int | ~c{x=x} * ~c{x=x}'' 3 in square (square ~x:Int | x')){x=x}''
Code types and quotations now mention contexts instead of classifiers. The type ~Int"α of the parameter c becomes ~x:Int | Int", and each quotation ~... "α becomes ~x:Int | ...". Every splice applies a substitution (underlined). Here every quotation is spliced into code of the same classifier α, so every substitution is the identity on Γα, written {x=x}. The substitutions connect different binders. On line 2, they map the x of the spliced code, bound by its context annotation x:Int, to the x bound by the context annotation of the surrounding quotation; on line 3, to the x bound by the λ-abstraction of line 1.
The target program metaevaluates to ~∅ | λ (x:Int). (x * x) * (x * x)'''. This example shows the basic pattern of the compilation: classifiers become contexts, and splices become splices with substitutions. Both the source metaprogram and the target produce λ (x:Int). (x * x) * (x * x). In general, we prove that the target always generates the same code as the source does with the semantic correctness theorem in § 6.2.
2.2 Compiling Subtyping
Code of an outer scope should be usable wherever code of an inner scope is expected, and allows this through subtyping. From to , we compile subtyping away through a coercion semantics [2, 22]. In the following subsections, we show that subtyping between classifiers compiles to a substitution, and subtyping between types compiles to a coercion function that applies the substitution through a splice.
Subtyping between classifiers. In the example of Section 1, a variable of an outer scope occurs in code of an inner scope, and the compilation moves it there by splicing it under a substitution and re-quoting it in the inner context. In general, a derivation of compiles to a substitution of type , where and are the contexts that and compile to. The following example demonstrates the compilation of subtyping between classifiers.
1 ~(λ (x:Int) α. λ (y:Int) β. λ (z:Int) γ. Source program (EC): subtyping 2 ~x + y"γ) 3 1 41 0"ε
We have from the three nested -abstractions. The quotation (line 2) mentions two variables of outer scopes. The variable is bound in the scope named by , so its occurrence requires . The variable is bound in the scope named by , so its occurrence requires , which holds by transitivity through . Here is the compilation of the program.
1 ~∅ ⊣ (λ (x:Int). λ (y:Int). λ (z:Int). Target program (CMTT) 2 ~x:Int, y:Int, z:Int ⊣ 3 ~x:Int ⊣ x'' ( {x=x} ○ {x=x,y=y}) + 4 ~x:Int, y:Int ⊣ y'' {x=x,y=y}'' 5 {x=x,y=y,z=z}) 6 1 41 0''
The contexts are , , and . The occurrence of is spliced under the substitution , which is of type (line 4, underlined). Transitivity of subtyping compiles to the composition of substitutions. The occurrence of is spliced under the substitution (line 3, underlined), which composes the substitution for with the one for and thus has type .
Subtyping between types. The following example demonstrates subtyping between types by storing code of classifier into a reference cell that expects code of classifier . We have from the nesting of -abstractions.
1 ~(λ (x:Int) α. λ (y:Int) β. Source program (EC): subtyping between types 2 ~(let r = ref ~0"β in /* r : Ref ~Int"β / 3 r := ~x"α; / ~Int"α <: ~Int"β */ 4 !r)) 5 42 24"ε
T. Chen et al.
The reference r holds code of classifier and has type Ref Int" (line 2). Line 3 assigns to it the code x" , which the type system accepts by subsumption. Line 4 reads the code back and splices it into the inner abstraction. Here is the compilation of the program.
1 ~0 | (λ (x:Int). λ (y:Int). Target program (CMTT) 2 ~(let r = ref ~x:Int, y:Int | 0" in 3 r := (λ (c:~x:Int | Int"). ~x:Int, y:Int | ~c{x=x}') 4 ~x:Int | x"; 5 !r){x=x,y=y} 6 42 24"
The reference holds code of type ~x:Int, y:Int | Int" (line 2), whereas the code assigned to it, ~x:Int | x" (line 4), has type ~x:Int | Int". The highlighted contexts correspond to β and α. To convert between the two types, the compilation inserts the framed function on line 3, which is the coercion that ~Int"α <: ~Int"β compiles to. It splices its argument under the substitution {x=x} and re-quotes the result in the context (x:Int, y:Int). In general, the coercion between two code types applies the substitution between their classifiers through a splice and re-quotes the result, and the compilation inserts it wherever the typing derivation of the source uses subsumption.
2.3 Compiling Bounded Quantification for Classifiers
expresses bounded quantification for classifiers with two features, classifier polymorphism and subtype constraints. We compile these language features separately. Classifier abstraction and application compile to context abstraction and application. Subtype constraint introduction and elimination compile to abstraction over and application to a first-class substitution, respectively.
A metafunction that manipulates code of a fixed classifier, such as square in § 2.1, can only be used in one scope. For reuse across scopes, supports classifier polymorphism, an idea that Kiselyov et al. [15] sketch informally and Murase and Igarashi [18] formalize. ( . M) abstracts over a classifier, and M[ ] instantiates the abstraction with . Subtype constraints let a polymorphic metafunction mention the variables of a specific scope. For example, in the term , where is a polymorphic classifier and the name of a scope, the constraint lets code of classifier in M use the variables of the scope named by . The elimination form M • discharges the subtype constraint in the type of M by checking that the subtyping holds.
The following example uses bounded quantification for classifiers, expressed as a classifier abstraction followed by a subtype constraint.
1 ~(λ (x:Int) α. λ (y:Int) β. Source program (EC): bounded quantification 2 ~(let 1 = Λ γ. β <: γ ⇒ ~x + y"γ in 3 1 [β] ●)) 4 42 0"ε
The function 1 (line 2) generates the code at the polymorphic classifier . Its body mentions and , bound in the scopes named by and , and both are visible in code of classifier thanks to the constraint . Line 3 instantiates 1 at and discharges the constraint, which reads after instantiation and holds by reflexivity. The result has type and is spliced into the inner abstraction of the same classification.
Here is the compilation. The frames of matching colors relate the constructs of the source to those of the target. We explain the compilation below.
1 ~∅ ⊥ (λ (x:Int). λ (y:Int). Target program (CMTT): context polymorphism 2 ~(let 1 = Λ γ. λ (s:(x:Int, y:Int) ⇒ γ). 3 ~γ ⊥ ~x:Int ⊥ x'' ( {x=x} ○ s) + 4 ~x:Int, y:Int ⊥ y'' s'' in 5 1 [x:Int, y:Int] {x=x, y=y} {x=x, y=y} 6 42 0''
Compiling classifier polymorphism. Classifier abstraction compiles to context abstraction (line 2, yellow box), and classifier application to context application (line 5, green box). To support the compilation, supports context polymorphism. The polymorphic classifier compiles to a context variable of the same name, so the quotation is now in the context (line 3, highlighted). The instantiation at becomes an instantiation at the context of , which is (x:Int, y:Int).
Compiling subtype constraints. Recall from § 2.2 that the coercion for subtyping between classifiers is a substitution. Consequently, a subtype constraint introduction compiles to a function that takes a substitution (line 2, red box). The function takes the substitution for the subtyping , so the argument is of type (x:Int, y:Int) . A constraint elimination compiles to a function application. In the example, the application passes the substitution for the subtyping that the elimination checks, which is after instantiation, so the argument is the identity substitution (line 5, blue box).
In summary, bounded quantification for classifiers compiles to context polymorphism and to abstraction over and application to first-class substitutions. To support compilation, substitutions must be first-class citizens in .
3 Source Language: with Environment Classifiers
In this section, we define , the source language of the compilation. is a two-level calculus with refined environment classifiers [15] and mutable references, so a code type records the classifier that names the scope in which
T. Chen et al.
base types code types EC variables ECs meta types contexts subtype contexts constants term variables code terms meta terms | \neg M^{\circ}''e \mid \text{ref } M \mid M := N \mid !M
Fig. 2. Syntax of
the code is meaningful, and a reference may hold open code. To these, adds unrestricted subtyping between types, and classifier polymorphism with bounded quantification in the style of [18]. We define the syntax in § 3.1, the type system in § 3.2, and the operational semantics in § 3.3.
3.1 Syntax of
Figure 2 defines the syntax of . It generates code in STLC, and the meta-language uses classifiers to ensure that the generated code is well scoped in the presence of mutable references. We describe the EC-specific features below.
Code and environment classifiers. Following Taha and Nielsen [25], a quotation “” and a code type “” carry an environment classifier , which represents the scope in which the code is meaningful. A classifier is either , which is the name of the empty scope, or a classifier variable . Following the refined environment classifiers of Kiselyov et al. [15], a code-level abstraction . binds both its parameter and the classifier that gives the scope of its body a name. A splice integrates the code that the meta term produces into the surrounding code.
Bounded quantification for classifiers. Following R²EC [18], supports bounded quantification over classifiers, which it expresses with two features, classifier polymorphism and subtype constraints. The universal type . A quantifies over classifiers. Classifier abstraction . M binds a classifier variable ( ), whereas classifier application instantiates it with a classifier (e). A subtype-constrained type introduces the constraint in the body type A. The subtype constraint introduction form assumes the constraint while typing M, and its elimination form discharges the constraint where the subtyping holds.
Fig. 3. Selected typing rules of (excerpt of Figure 13 of the Appendix).
3.2 Type System of
Figure 3 shows selected typing rules of ; the complete rules are in Figure 13 of the Appendix. All judgments carry a typing context , which binds classifiers, code and meta variables, and records subtype constraints. The typing judgment for meta terms takes the form . The typing judgment for code terms, , also carries the classifier of the nearest enclosing scope. The two judgments are mutually recursive through quotation and splice. Well-formedness and subtyping of types are straightforward. They are defined in Figures 11 and 12 of the Appendix, respectively.
Subtyping between classifiers. The subtyping judgment between classifiers, , is defined in Figure 3. It derives subtyping from a subtype context , which extracts from the subtype constraints in . The constraints in form the edges of a graph, with an edge from to every classifier. The subtyping holds when the graph has a path from to .
Typing code terms. The typing rule for code variables ( code-var) enforces that a variable may only occur where the nearest enclosing scope has the same classifier. The rule for code -abstractions ( code-abs) binds both a code variable x and the classifier . It also links to the enclosing scope by the constraint and types the body of the under the extended context (highlighted). A splice ( splice) types its meta term, which must produce code of the enclosing classifier. The subsumption rule between classifiers ( code-subenv) lets code typed under be used in the scope represented by when holds (highlighted).
T. Chen et al.
addresses
heap typing contexts
runtime code terms
runtime meta terms
code values
meta values
heaps
Fig. 4. Runtime language and selected reduction rules of (excerpt of Figures 14 and 15 of the Appendix).
Typing meta terms. A quotation ( quote) types its code term with the annotated classifier e as the enclosing scope. Classifier abstraction and application follow System F with classifiers in place of types, and their rules are in the Appendix. Subtype constraint introduction ( sub-intro) extends with the assumption (highlighted), and subtype constraint elimination ( sub-elim) discharges the assumption by checking that holds (highlighted).
3.3 Operational Semantics of
Figure 4 presents selected reduction rules for . Each configuration consists of a runtime context ( ), a term, and a heap ( ). The heap maps addresses to values. Code and meta reduction rules are mutually recursive through quotation and splice. We first define the runtime language, which extends with terms that arise at runtime. We then describe the reduction semantics. The full version of the reduction semantics is in Figure 15 of the Appendix.
Runtime language of . The runtime language extends with two terms that arise only at runtime, addresses and code abstraction values ( ). Their syntax and typing rules are defined at the top of Figure 4. A code abstraction value is a code abstraction whose classifier and parameter have been allocated in the global runtime context . Its typing rule ( code-abs-val) checks the allocated entries in (highlighted). The global allocation for code variables allows open code to be stored in the heap while keeping the heap well typed. An address is typed by the heap typing context ( addr), which the typing judgments of the runtime language carry in addition to .
Reducing code terms. The code reduction reduces a code term under the enclosing classifier . The reduction (1) eliminates splices and (2) allocates variables and classifiers of code -abstractions globally. A splice first reduces its sub-term by the meta reduction ( -splice). The splice then cancels against the quotation that the sub-term produces ( -splice). The code- rule performs the global allocation. It first allocates a fresh classifier for the scope and a fresh code variable . It then extends the runtime context with , the edge to the enclosing scope, and the code variable entry (highlighted). Finally, it turns the code -abstraction into a code abstraction value, renaming variables to globally allocated ones. A code abstraction value then reduces its body under its classifier annotation ( -code- ).
Reducing meta terms. The meta reduction takes the form . The reduction follows that of a call-by-value -calculus with references, except when the term contains a quotation or discharges a subtype constraint. A quotation reduces the code inside by turning to code reduction ( -quote). A constraint elimination reduces by simply discarding the subtype constraint, because the subtyping is already checked statically ( -sub).
4 Target Language: with Contextual Modal Types
In this section, we define , the target language of the compilation. is a two-level calculus based on CMTT [20], so a code type records the context of the variables that the code may mention, and a splice applies an explicit substitution from one context to another. To these, adds context polymorphism from [19], and general mutable references from Contextual MetaML [29]. To support compilation, also includes two additional language features: first-class substitutions and reference proxies. We define the syntax and types in § 4.1, the type system in § 4.2, and the operational semantics in § 4.3.
T. Chen et al.
context variables
code typing contexts
meta types
meta typing contexts
code terms
meta terms
\mid \Lambda \alpha. N \mid M[\Gamma^{\circ}] \mid \neg \Gamma^{\circ} \vdash M^{\circ}''
Fig. 5. Syntax of .
4.1 Types and Syntax of
Figure 5 defines the syntax of , where most language constructs resemble those in . We describe the CMTT-specific features of below.
Contexts in types and quotations. Standard in a CMTT-based calculus, a quotation “” and a code type “” carry a code context . We represent a code typing context as a binary tree whose leaves are the empty context, a single mapping , and context variables . The inner node , concatenates two contexts. We use a binary tree because this representation is closed under instantiating a context variable. Replacing the leaf by a context yields a context, and the rest of the tree is unchanged.
Polymorphism over contexts. We follow [19] and introduce context polymorphism to . The universal type . A quantifies over contexts. Context abstraction . N binds a context variable, and context application instantiates it with a context.
First-class substitutions. Standard in CMTT, a splice carries a substitution that maps the variables of the spliced code's context to code in the current context. Unique to , substitutions are first-class metalanguage terms to support the compilation of bounded quantification ( 2.3). A substitution term of type substitutes code in for the variables of . Its four introduction forms follow the calculus of explicit substitutions [1]. The identity maps every variable of to itself, the extension maps to and the other variables as does, the weakening lets target a context extended by , and the composition applies and then .
Reference proxies. Following Herman et al. [10], we introduce proxies of mutable references to to support the compilation of subtyping between reference types. We use the syntax proxy L M N, which wraps a reference L. The proxy applies the function M to every value read from L, and applies N to every value written to L.
Fig. 6. Selected typing rules of (excerpt of Figure 17 of the Appendix).
4.2 Type System of
Figure 6 shows selected typing rules of , and the complete rules are in Figure 17 of the Appendix. All judgments carry a meta typing context , which binds context and meta variables. The term typing judgments also carry a heap typing context , whose definition is standard, mapping addresses to types.
Well-formed types. A meta type is well formed, written ty, when every type and code context inside it is well formed. A code context is well formed, written ctx, when all its context variables are well scoped in . Their definitions are in Figure 16 of the Appendix.
Typing code terms. The typing judgment for code terms, , carries the code context . A code variable is typed by looking the variable up in ( code-var). The lookup relation finds the leaf in the tree . A code abstraction extends with its parameter for the abstraction's body ( code-abs). The rule for splice ( splice) is the one rule that connects two code contexts. Its first argument produces code in some context , and its second argument is a substitution from to the current context .
Typing meta terms. The typing judgment for meta terms takes the form . A quotation “ ” has type “ ” when has type in ( quote). Context abstraction and application follow System F with contexts in place of types, and their rules are in the Appendix. Now we discuss the typing of the new features in that support compilation: reference
T. Chen et al.
code values
meta values
Fig. 7. Selected reduction rules of (excerpt of Figure 18 of the Appendix).
proxies and first-class substitutions. A proxy of a reference of type Ref A, with an output function of and an input function of , has type Ref B ( proxy, highlighted in blue). The substitution rules, highlighted in green, type a substitution by its domain and codomain. The identity on goes from to itself ( id). Weakening the identity on empty gives the empty substitution into any context ( weaken-empty). A weakening keeps the domain of M and joins its codomain with ( weaken). An extension adds to the domain of M, where T is the type of ( ext). A composition chains two substitutions whose contexts match in the middle ( compose).
4.3 Operational Semantics of
Figure 7 shows selected reduction rules of , and the complete rules are in Figure 18 of the Appendix. The semantics consists of two mutually recursive reduction relations, one for code and the other for meta.
Values. A code value is a term in STLC with no remaining splice. The meta values are constants, addresses, abstractions, quotations of code values, proxies of values, and substitution values. A substitution value is built from the four substitution introduction forms, each with values in its sub-terms. Its meaning is given by the interpretation , defined in Figure 18 of the Appendix. The interpretation of V is a substitution that substitutes code for each variable in the domain of V. Applying to a code value performs the substitution.
Reducing code terms. The code reduction takes the form . Code reduces only to eliminate splices. A splice first reduces its meta term to a quotation and its substitution to a substitution value .
compilation contexts
Fig. 8. Compilation contexts, and selected compilation rules of classifiers and types (excerpt of Figure 19 of the Appendix).
The rule -splice is the heart of the semantics, highlighted in green. It reduces the splice of a quotation under a substitution value to , which is the quoted code with the substitution applied.
Reducing meta terms. The meta reduction takes the form . Meta terms reduce as in a call-by-value -calculus with references, except in three cases. The code attached to a substitution extension reduces when it contains splices ( -ext). Context application substitutes the context for the context variable in the body ( -ctx). A proxy forwards dereference and assignment to the reference it wraps, applying its output function to every value read (proxy-deref) and its input function to every value written (proxy-assign).
5 Compilation From to
In this section, we formally define the compilation from to . The compilation has three parts. First, classifiers compile to code contexts, and types compile accordingly ( 5.1). Second, subtyping between classifiers compiles to substitutions, and subtyping between types compiles to coercion functions ( 5.2). Third, terms compile according to their typing derivations, with classifier polymorphism becoming context polymorphism and subtype constraints becoming abstraction over and application to substitutions ( 5.3).
5.1 Compiling Classifiers and Types
Figure 8 shows selected compilation rules for classifiers and types. The complete compilation rules are in Figure 19 of the Appendix.
Compilation contexts. A compilation context , defined at the top of Figure 8, is a typing context of extended by the two highlighted entries. First, a compilation context distinguishes the two ways a classifier enters scope, because they compile differently. A classifier bound by a code abstraction is recorded as and compiles to a concrete context, whereas a classifier bound by a classifier
T. Chen et al.
abstraction is recorded as and compiles to a context variable. Second, it distinguishes the two kinds of subtype constraints. A constraint comes from a code abstraction, whereas a named constraint comes from a constraint introduction and binds the variable as evidence for the constraint.
Compiling classifiers to contexts. The judgment computes the context that corresponds to a classifier. The empty classifier compiles to the empty context ( empty), and a polymorphic classifier compiles to a context variable ( poly-ec). The interesting case is a classifier introduced by a code abstraction ( ec). Its context is calculated by following the subtyping in . We first include the code variable entry in the result context. We then follow the edge , which leads to the enclosing classifier . The context of is computed in turn. Following the edges up to or to a polymorphic classifier, we collect exactly the variables that the scope of may mention.
Compiling types. The judgment compiles types, and its rules mirror the well-formedness rules of types in . A code type e compiles to , where is the context of ( code). A subtype-constrained type compiles to the function type ( constraint). Its argument type is the type of the evidence for the constraint, computed by the judgment that we define in the next subsection. Its body is compiled to under extended with the evidence variable for the constraint. The remaining types compile recursively.
5.2 Compiling Subtyping
Figure 9 presents selected compilation rules of subtyping. The complete rules are in Figure 20 of the Appendix. The compilation follows the coercion semantics of subtyping [2, 22]. Subtyping between classifiers compiles to a first-class substitution, and subtyping between types compiles to a coercion function.
Compiling classifier subtyping to a substitution. The judgment compiles two classifiers and , the former a subtype of the latter, to a substitution . The type of is given by , which produces a substitution type from the compiled context of to that of . The rules of mirror the subtyping rules for classifiers in . The axiom compiles to the empty substitution into the context of ( sub-empty). Reflexivity compiles to the identity ( sub-refl). The two kinds of subtyping entries in compile differently. A subtyping entry , introduced by a code , compiles to the identity on the context of , weakened by the code variable bound by that code ( sub-ax). A named constraint, introduced by a subtype constraint, compiles to the variable for the evidence of that constraint ( sub-var). Transitivity compiles to composition ( sub-trans).
Compiling type subtyping to a coercion. The judgment compiles two types and , with a subtype of , to a coercion function . The compilation rules mirror the subtyping rules for types in . The coercion converts from the compiled type of to that of . It applies the substitution that the underlying classifier subtyping compiles to, and the rule for code types is the key ( sub-code). The subtyping compiles to a function
Fig. 9. Compilation of subtyping between classifiers and between types (excerpt of Figure 20 of the Appendix).
that takes code in the context that corresponds to, , and moves it to the context that corresponds to, . The body of the function splices the code under the substitution that compiles to (highlighted) and re-quotes the result in . A reference type is special, because a reference can be both read from and written to. Consequently, its coercion wraps the reference in a proxy whose output and input functions are the coercions in the two directions, read and write ( sub-ref). A subtype-constrained type also deserves a closer look ( sub-constraint). The types and compile to the function types and , where is the type of the evidence for the constraint, and are what compile to, respectively. The coercion is thus a function between function types, and the compilation follows the types. The coercion takes a function and evidence , applies to , and coerces the result. The remaining cases follow the standard coercion semantics.
T. Chen et al.
( sub-elim)
( subsumption)
Fig. 10. Selected compilation rules of terms (excerpt of Figure 21 of the Appendix).
5.3 Compiling Terms
Figure 10 shows selected compilation rules for code terms and meta terms. The complete compilation rules are in Figure 21 of the Appendix. The rules mirror the typing rules of and do two things. First, wherever a typing rule of mentions a classifier, the compilation rule converts it into the context that the classifier corresponds to (the green highlights). Second, wherever a typing rule of uses subtyping, the compiled term carries the substitution or coercion that the subtyping compiles to (the blue highlights). The remaining rules compile recursively, except that a code abstraction drops its classifier ( code-abs) and a splice gains the identity substitution that a splice of requires ( splice).
Converting classifiers into contexts. The three rules with green highlights replace a classifier by its context. The context is computed by of Figure 8. A quotation “ ” e compiles to “ ” ( quote). A classifier abstraction compiles to a context abstraction ( ). A classifier application compiles to a context application ( ).
Compiling subtyping. The four rules with blue highlights insert the substitution or coercion that a subtyping compiles to. Classifier subsumption from to quotes the code in the context of and splices it under the substitution for , which carries the code to the context of ( ). Subtype constraint introduction compiles to an abstraction over the evidence variable for the constraint, which has a substitution type, with the body compiled under extended with the named constraint ( ). Constraint elimination compiles to an application to the substitution for the discharged constraint ( ). Subsumption from to compiles to an application of the coercion for ( ). In summary, these four rules replace every use of subtyping in the typing derivation by an explicit term in .
6 Metatheoretical Results
In this section, we prove that the compilation of Section 5 preserves types ( 6.1) and is semantically correct ( 6.2). All lemmas and theorems in this section are mechanized in Agda. Table 1 of the Appendix maps each result to Agda.
6.1 Compilation Preserves Types
We first relate compilation contexts to typing contexts. We then define the well-formedness of compilation contexts. With the definitions in hand, we prove that the compilation from to preserves types (Theorem 1).
Relating the contexts. The lemmas that lead to type preservation involve three judgments: the typing judgment of , the compilation judgment , and the typing judgment of . Since each judgment has its own context, needs a reading in both languages. For the source language , the operator , defined in Figure 22 of the Appendix, turns into a typing context. It forgets the two annotations that only the compilation needs, namely which classifiers are polymorphic and which subtype constraints have evidence variables. For the target language , the judgment , also defined in Figure 22 of the Appendix, compiles the entries of the metalanguage in to a meta typing context . The code-level entries of are dropped, because the code context of a code term comes instead from its classifier.
Well-formed compilation contexts. The compilation lemmas require compilation contexts to be well formed. Intuitively, a compilation context is well formed when each scope has at most one parent scope, which may be empty ( ), and two distinct scopes do not share a classifier. Definition 1 of the Appendix formalizes this intuition, and every compilation context that the compilation in Section 5 builds is well formed.
Compilation preserves types. The first lemma shows that every well-formed classifier compiles to exactly one context, and every well-formed type to exactly one type, both of which are well formed in the target context.
T. Chen et al.
Lemma 1 (Compiled contexts and types are well formed).
Suppose and .
-
If , then and ctx for a unique .
-
If , then and ty for a unique .
The second lemma shows that the terms the compilation inserts for subtyping are well typed under the meta typing context that compiles to. The heap typing context is empty because the compilation does not produce addresses.
Lemma 2 (Subtyping compiles to well-typed terms).
Suppose and .
- If , , and ,
then .
- If , , and ,
then .
The main lemma shows that every well-typed term compiles, and that the compiled term is well typed in at the compiled type.
Lemma 3 (Compilation of code and meta terms preserves types).
Suppose and .
-
If and , then there exists an M^\circ' such that \Xi; e \vdash M^\circ : T \leadsto M^\circ', and \Gamma; \emptyset; \Gamma^\circ \vdash M^\circ' : T.
-
If , then there exist and such that and , and .
The type preservation theorem is a corollary of Lemma 3 for closed programs.
Theorem 1 (Compilation of programs to preserves types).
If a term M is well typed, ,
then there exist a type and a term in such that
.
6.2 Semantic Correctness of Compilation Through Bisimulation
We now prove the semantic correctness of compilation (Theorem 2). We first define reification, which turns code values of into STLC terms. We then prove bisimulation between and and obtain the theorem as a corollary.
Reification. The code value that a program generates contains globally allocated variables, because the code- rule allocates a global variable for each code abstraction. To obtain code in STLC, reification converts each global variable to a fresh lexical one, so that every code abstraction value ( ) becomes a lexical of STLC. Reification is defined in Figure 23 of the Appendix. The code values of do not need reification, because they are already STLC terms.
Bisimulation. The simulation relation on terms is similar to the compilation relation of Section 5, but it is closed under reduction. It relates a code or meta term of to one of under a compilation context and a heap typing context . The full simulation rules are in Figures 24 and 25 of the Appendix. The simulation relation differs from the compilation in two ways. First, it relates terms that arise only at runtime, such as code abstraction values ( ) and addresses. Second, it has value rules for catching up with a coercion. Once a subsumed source term is a value, the coerced target term still has to apply its coercion or substitution, in steps that the source does not take. The value simulation rules relate the source value to the value that the target reaches once it has caught up.
The embedding lemma says that a term is in simulation with its compilation.
Lemma 4 (Compilation embeds into simulation)
Let be any heap typing context.
-
If \Xi; e \vdash M^\circ : T \leadsto M^\circ', then \Sigma; \Xi; e \vdash M^\circ : T \sim M^\circ'.
-
If , then .
The simulation relation on configurations, written , relates a configuration of to a term and a heap of . The simulation context holds the classifiers, subtype constraints, and code variables that code abstractions add: . We write for the reflexive, transitive closure of a reduction relation and for inclusion of contexts viewed as sets. The next two lemmas establish a bisimulation.
Lemma 5 (Forward simulation)
If and ,
then there exist , and such that , and .
Lemma 6 (Backward simulation)
If and ,
then there exist , and such that ,
, and .
Semantic correctness. A configuration of diverges, written , if every configuration that reduces to can take a step, and likewise in . The semantic correctness theorem states that a closed program of code type and its compilation behave the same. If one of them evaluates to a quotation of a code value, so does the other, and the code value of reifies to the generated code of . The generated code is an STLC term of type . If one of them diverges, so does the other. The proof relates to by Lemma 4 and keeps them related by Lemmas 5 and 6 as either side reduces.
Theorem 2 (Semantic correctness)
Suppose a term M is well typed, .
Then there exists a well-typed term that M compiles to,
, such that the following hold.
- If for a value , then V = \neg V^\circ'' \varepsilon for a code value , and there exist a code value and a heap such that M' \mid \emptyset \longrightarrow^{m*} \neg \emptyset \vdash W^\circ'' \mid \mu' and reify .
T. Chen et al.
-
If M' \mid \emptyset \longrightarrow^{m*} \because \emptyset \vdash W^\circ'' \mid \mu' for a code value , then there exist a code value , a context , and a heap such that \langle \emptyset; M; \emptyset \rangle \longrightarrow^{m*} \langle \Gamma; \because V^\circ'' \varepsilon; \mu \rangle and .
-
if and only if .
In the first two cases, the generated code is a well-typed STLC term, .
7 Conclusion
This paper connects two approaches to the scopes of generated code, environment classifiers and contextual modal type theory, through a type-directed compilation. We proved in Agda that the compilation preserves types and behavior. CMTT is thus at least as expressive as environment classifiers. We conjecture that the converse compilation is hard, because environment classifiers impose a stricter regime on how the metaprogram scopes generated code.
References
-
Abadi, M., Cardelli, L., Curien, P.L., Levy, J.J.: Explicit substitutions. Journal of Functional Programming 1(4), 375–416 (1991)
-
Breazu-Tannen, V., Coquand, T., Gunter, C.A., Scedrov, A.: Inheritance as implicit coercion. Information and Computation 93(1), 172 – 221 (1991). https://doi.org/http://dx.doi.org/10.1016/0890-5401(91)90055-7, http://www.sciencedirect.com/science/article/pii/0890540191900557, selections from 1989 {IEEE} Symposium on Logic in Computer Science
-
Calcagno, C., Moggi, E., Sheard, T.: Closed types for a safe imperative metaml. J. Funct. Program. 13(3), 545–571 (May 2003). https://doi.org/10.1017/S0956796802004598, https://doi.org/10.1017/S0956796802004598
-
Calcagno, C., Moggi, E., Taha, W.: Closed types as a simple approach to safe imperative multi-stage programming. In: International Colloquium on Automata, Languages, and Programming. pp. 25–36. Springer (2000)
-
Calcagno, C., Taha, W., Huang, L., Leroy, X.: Implementing multi-stage languages using asts, gensym, and reflection. In: 2nd International Conference on Generative Programming and Component Engineering (GPCE'03) (2003)
-
Davies, R.: A temporal-logic approach to binding-time analysis. In: Proceedings 11th Annual IEEE Symposium on Logic in Computer Science. pp. 184–195. IEEE (1996)
-
Davies, R.: A temporal logic approach to binding-time analysis. J. ACM 64(1) (Mar 2017). https://doi.org/10.1145/3011069, https://doi.org/10.1145/3011069
-
Davies, R., Pfenning, F.: A modal analysis of staged computation. In: POPL '96: Proceedings of the 23rd ACM SIGPLAN-SIGACT symposium on Principles of programming languages. pp. 258–270. ACM Press, New York, NY, USA (1996)
-
Davies, R., Pfenning, F.: A modal analysis of staged computation. J. ACM 48(3), 555–604 (2001)
-
Herman, D., Tomb, A., Flanagan, C.: Space-efficient gradual typing. Higher-Order and Symbolic Computation 23(2), 167–189 (2010). https://doi.org/10.1007/s10990-011-9066-z
-
Isoda, K., Yokoyama, A., Kameyama, Y.: Type-safe code generation with algebraic effects and handlers. In: Proceedings of the 23rd ACM SIGPLAN International Conference on Generative Programming: Concepts and Experiences. pp. 53–65 (2024)
-
Jang, J., Gélineau, S., Monnier, S., Pientka, B.: Moebius: metaprogramming using contextual types: the stage where system f can pattern match on itself. Proc. ACM Program. Lang. 6(POPL) (Jan 2022). https://doi.org/10.1145/3498700, https://doi.org/10.1145/3498700
-
Kim, I.S., Yi, K., Calcagno, C.: A polymorphic modal type system for lisp-like multistaged languages. In: POPL '06: Conference record of the 33rd ACM SIGPLAN-SIGACT symposium on Principles of programming languages. pp. 257–268. ACM Press, New York, NY, USA (2006)
-
Kiselyov, O.: The design and implementation of ber metaocaml: System description. In: International Symposium on Functional and Logic Programming. pp. 86–102. Springer (2014)
-
Kiselyov, O., Kameyama, Y., Sudo, Y.: Refined environment classifiers: Type- and scope-safe code generation with mutable cells. In: Igarashi, A. (ed.) Programming Languages and Systems - 14th Asian Symposium, APLAS 2016, Proceedings. pp. 271–291. Lecture Notes in Computer Science (including subseries Lecture Notes in Artificial Intelligence and Lecture Notes in Bioinformatics), Springer Verlag, Germany (2016). https://doi.org/10.1007/978-3-319-47958-3_15, funding Information: We thank anonymous reviewers for many helpful comments. This work was partially supported by JSPS KAKENHI Grant Numbers 15K12007, 16K12409, 15H02681. Publisher Copyright: © Springer International Publishing AG 2016.; 14th Asian Symposium on Programming Languages and Systems, APLAS 2016; Conference date: 21-11-2016 Through 23-11-2016
-
Lee, M., Xie, N., Kiselyov, O., Yallop, J.: Handling scope checks: A comparative framework for dynamic scope extrusion checks. Proceedings of the ACM on Programming Languages 10(POPL), 1123–1152 (2026)
-
Moggi, E., Taha, W., Benaissa, Z.E.A., Sheard, T.: An idealized metaml: Simpler, and more expressive. In: European Symposium on Programming. pp. 193–207. Springer (1999)
-
Murase, Y., Igarashi, A.: Refined^ 2 environment classifiers. arXiv preprint arXiv:2608.07888 (2026)
-
Murase, Y., Nishiwaki, Y., Igarashi, A.: Contextual modal type theory with polymorphic contexts. In: European Symposium on Programming. pp. 281–308. Springer Nature Switzerland Cham (2023)
-
Nanevski, A., Pfenning, F., Pientka, B.: Contextual modal type theory. ACM Trans. Comput. Logic 9(3) (Jun 2008). https://doi.org/10.1145/1352582.1352591, https://doi.org/10.1145/1352582.1352591
-
Pfenning, F., Davies, R.: A judgmental reconstruction of modal logic. Mathematical. Structures in Comp. Sci. 11(4), 511–540 (Aug 2001). https://doi.org/10.1017/S0960129501003322, http://dx.doi.org/10.1017/S0960129501003322
-
Pierce, B.C.: Types and Programming Languages. MIT Press (2002)
-
Rhiger, M.: Staged computation with staged lexical scope. In: European Symposium on Programming. pp. 559–578. Springer (2012)
-
Taha, W., Calcagno, C., Leroy, X., Pizzi, E., Pasalic, E., Eckhardt, J.L., Kaiabachev, R., Kiselyov, O.: MetaOCaml: A compiled, type-safe multi-stage programming language. Available online from http://www.metaocaml.org/ (2004)
T. Chen et al.
-
Taha, W., Nielsen, M.F.: Environment classifiers. In: POPL '03: Proceedings of the 30th ACM SIGPLAN-SIGACT symposium on Principles of programming languages. pp. 26–37. ACM Press, New York, NY, USA (2003)
-
Taha, W., Sheard, T.: Multi-stage programming with explicit annotations. In: PEPM '97: Proceedings of the 1997 ACM SIGPLAN symposium on Partial evaluation and semantics-based program manipulation. pp. 203–217. ACM Press, New York, NY, USA (1997)
-
Taha, W., Sheard, T.: Metaml and multi-stage programming with explicit annotations. Theoretical computer science 248(1-2), 211–242 (2000)
-
Tsukada, T., Igarashi, A.: A logical foundation for environment classifiers. Logical Methods in Computer Science 6 (2010)
-
Yin, H., Murawski, A.S., Ong, C.H.L.: Contextual metaml: Syntax and full abstraction. arXiv preprint arXiv:2602.03033 (2026)
Appendix
The appendix is organized as follows.
-
Table 1 maps the metatheoretical results to their Agda mechanization.
-
Figure 11 defines the well-formedness for ECs and meta types of .
-
Figure 12 defines the subtyping rules of .
-
Figure 13 defines the typing rules of .
-
Figure 14 defines the typing rules for the runtime language of .
-
Figure 15 defines the reduction semantics of .
-
Figure 16 defines the well-formedness for code contexts and types of .
-
Figure 17 defines the typing rules of .
-
Figure 18 defines the reduction semantics of .
-
Figure 19 defines the compilation of classifiers and types.
-
Figure 20 defines the compilation of subtyping.
-
Figure 21 defines the compilation of code terms and meta terms.
-
Figure 22 maps a compilation context to a typing context of and to a meta typing context of .
-
Definition 1 defines well-formed compilation contexts.
-
Figure 23 defines the reification of the code values of into STLC terms.
-
Figure 24 defines the simulation relation on configurations, heaps, and code terms.
-
Figure 25 defines the simulation relation on meta terms.
-
Figure 26 defines the coerced value relation that the simulation relation uses.
T. Chen et al.
| Results | Agda identifiers | Agda files |
|---|---|---|
| Section 6.1: Compilation preserves types | ||
| Well-formed compilation context (Definition 1) | CompileCtxWF | CompileCtx.agda |
| Compiled contexts and types are well formed (Lemma 1) | ec-compiles, ec-unique, ec-wf, type-compiles, type-unique, type-wf | Compile.agda, CompilePres.agda |
| Subtyping compiles to well-typed terms (Lemma 2) | compile-ec-subtyping-preserves-types, compile-subtyping-preserves-types | CompilePres.agda |
| Compilation preserves types under a compilation context (Lemma 3) | compile-code, compile-meta | CompilePres.agda |
| Compilation preserves types (Theorem 1) | compile-preserves-types | CompilePres.agda |
| Section 6.2: Semantic correctness | ||
| Simulation relation (Figures 24–26) | _;_;|°_:~_,_;|m_:~_, |_<: _>_ | Simulation/Relation.agda, Simulation/Subtyping.agda |
| Compilation embeds into simulation (Lemma 4) | embed-code-compilation, embed-meta-compilation | Simulation/Relation.agda |
| Forward simulation (Lemma 5) | forward-simulation°, forward-simulation, forward-simulation* | ForwardSimulation.agda |
| Backward simulation (Lemma 6) | backward-simulation°, backward-simulation, backward-simulation* | BackwardSimulation.agda |
| Semantic correctness (Theorem 2) | semantic-preservation, semantic-reflection | CompilerCorrectness.agda |
Table 1. Mapping from metatheoretical results to their Agda mechanization. File paths are relative to the root of the Agda development (the Theories/ directory).
Auxiliary Definitions for
Fig. 11. Well-formedness for ECs and meta types of
\begin{array}{r} \left. \frac{\Theta \vdash A_{2} <: A_{1} \quad \Theta \vdash B_{1} <: B_{2}}{\Theta \vdash \iota <: \iota} \left(<: base\right) \quad \frac{\Theta \vdash A_{1} \to B_{1} <: A_{2} \to B_{2}}{(\text{>: fun})} \\ \frac{\Theta \vdash A <: B \quad \Theta \vdash B <: A}{\Theta \vdash \mathrm{Ref}\,A <: \mathrm{Ref}\,B} \left(<: ref\right) \quad \frac{\Theta \vdash e_{1} <: e_{2}}{\Theta \vdash \mathcal{T}''e_{1} <: \mathcal{T}''e_{2}} \left(<: code\right) \\ \frac{\Theta \vdash A <: B}{\Theta \vdash \forall \alpha. A <: \forall \alpha. B} \left(<: all\right) \quad \frac{\Theta, e_{1} <: e_{2} \vdash A <: B}{\Theta \vdash e_{1} <: e_{2} \Rightarrow A <: e_{1} <: e_{2} \Rightarrow B} \left(<: sub\right) \end{array}Fig. 12. Subtyping rules of .
T. Chen et al.
Fig. 13. Typing rules of .
Fig. 14. Typing rules for the runtime language of code frames
meta frames
Fig. 15. Operational semantics of .
T. Chen et al.
Auxiliary Definitions for
Fig. 16. Well-formedness of code contexts and meta types in .
Figure 16 defines the well-formedness judgments for code contexts and meta types of . A code context is well formed when every context variable in it is well scoped in . Three rules for meta types concern context variables and code contexts. The rule for . A binds the context variable in the body . The rule for code types requires to be well formed. The rule for substitution types requires both the domain and the codomain to be well formed.
Fig. 17. Typing rules of .
T. Chen et al.
code values
meta values
heaps
code frames
meta frames
Fig. 18. Operational semantics of .
Evaluation in is call by value and left to right, as the frames (non-recursive evaluation contexts) of Figure 18 specify. The congruence rules of each level are grouped into a single rule that reduces under a frame ( -code, -meta).
T. Chen et al.
Auxiliary Definitions for the Compilation From to
compilation contexts
\begin{array}{c}{\Xi\vdash A\rightsquigarrow A^{\prime}}\\{\hline}\\ \end{array}Fig. 19. Compilation contexts, and compilation of classifiers and types.
Fig. 20. Compilation of subtyping between classifiers and between types.
T. Chen et al.
\begin{aligned}&\frac{k:\iota}{\Xi;e\vdash k:\iota\leadsto k}\stackrel{(\leadsto code-const)}{\longrightarrow}\frac{(x:T)^{\alpha}\in\Xi}{\Xi;\alpha\vdash x:T\leadsto x}\stackrel{(\leadsto code-var)}{\longrightarrow}\\&\frac{\Xi,\alpha,e<:\alpha,(x:S)^{\alpha};\alpha\vdash N^{\circ}:T\leadsto N^{\circ\prime}\quad\alpha\notin\Xi}{\Xi;e\vdash\lambda(x:S)^{\alpha}.N^{\circ}:S\rightarrow T\leadsto\lambda(x:S).N^{\circ\prime}}\stackrel{(\leadsto code-abs)}{\longrightarrow}\\&\frac{\Xi;e\vdash L^{\circ}:S\rightarrow T\leadsto L^{\circ\prime}}{\Xi;e\vdash M^{\circ}:S\leadsto M^{\circ\prime}}\stackrel{(\leadsto code-app)}{\longrightarrow}\frac{\Xi\vdash M:\neg T^{\prime\prime}e\leadsto M^{\prime}}{\Xi\vdash e\leadsto\Gamma^{\circ}}\stackrel{(\leadsto splice)}{\longrightarrow}\\&\frac{\Xi;e\vdash L^{\circ}M^{\circ}:T\leadsto L^{\circ\prime}M^{\circ\prime}}{\Xi;e_{1}\vdash M^{\circ}:T\leadsto M^{\circ\prime}}\quad\Xi\vdash e_{1}\leadsto\Gamma^{\circ}\quad\Xi\vdash e_{1}<:e_{2}\leadsto M}\\&\quad\Xi;e_{2}\vdash M^{\circ}:T\leadsto\sim\neg\Gamma^{\circ}\vdash M^{\circ\prime\prime}M\end{aligned}Fig. 21. Compilation of code terms and meta terms.
Auxiliary Definitions for the Metatheoretical Results
Fig. 22. Mappings from a compilation context to a typing context of the source language, , and a meta typing context of the target language, .
Figure 22 defines the operator and the compilation of a compilation context.
The operator takes a compilation context and returns a typing context that corresponds to it. The operator turns a polymorphic classifier into the classifier and a named constraint into the constraint . It keeps every other entry.
The compilation turns a compilation context into a metalanguage typing context. The judgment turns a polymorphic classifier into a context variable ( ), gives a meta variable its compiled type ( ), and gives the evidence variable the substitution type that its subtype constraint compiles to ( ). A code abstraction adds three entries together, namely its classifier, the subtype constraint to its parent , and its code variable. All three are dropped ( ).
T. Chen et al.
The compilation lemmas of Section 6.1 require compilation contexts to be well formed.
Definition 1 (Well-formed compilation context). A compilation context is well formed, written , if the following hold.
- Every entry mentions only well-scoped classifiers and types:
- Every classifier has at most one parent:
if and then .
- Every classifier points to at most one code variable:
if and then and .
Reification turns a code value of into STLC.
STLC terms
reification environments
Fig. 23. Reification of the code values of into STLC terms.
simulation contexts
Fig. 24. Simulation of configurations, heaps, and code terms.
The simulation relation between and is defined in Figures 24, 25, and 26. The highlighted rules extend the compilation rules, so that the simulation relation is closed under reduction.
T. Chen et al.
Fig. 25. Simulation of meta terms.
Fig. 26. The coerced value relation.