arXiv:2610.25741cs.PLOct 2026

Manuscript Offprint

arXiv:2610.25741

Compiling Environment Classifiers to Contextual Modal Types

Tianyu Chen, Darshal Shetty, Jeremy G. Siek, Chao-Hong Chen, Weixi Ma, Arnaud Venet, Rocky Liu

Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.

Tianyu Chen 1^{1} ID^{ID}, Darshal Shetty 1^{1} ID^{ID}, Jeremy G. Siek 1^{1} ID^{ID}

Chao-Hong Chen 2^{2} ID^{ID}, Weixi Ma 2^{2} ID^{ID}, Arnaud Venet 2^{2} ID^{ID}, and Rocky Liu 2^{2}

1^{1} Indiana University, Bloomington, IN, USA

{chen512,dcshetty,jsiek}@iu.edu

2^{2} 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]

( λ∘\lambda^{\circ}: open code, but no run)

A modal analysis of staged computation.

Davies and Pfenning 1996 [8]

( λ□\lambda^{\Box}: run, but only closed code)

Environment Classifiers

Environment classifiers.

Taha and Nielsen

2003 [25]

( λα\lambda^{\alpha}: open code and run)

Refined environment classifiers.

Kiselyov, Kameyama, and Sudo

2016 [15]

(<NJ>: mutable references)

Refined 2^{2} environment classifiers.

Murase and Igarashi

2026 [18]

(R 2^{2}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]

( λ∀[]\lambda_{\forall}[]: context polymorphism)

Contextual MetaML.

Yin, Murawski, and Ong

2026 [29]

(mutable references)

This paper

λRefα→compileλRefCtx\lambda_{\text{Ref}}^{\alpha} \xrightarrow{\text{compile}} \lambda_{\text{Ref}}^{\text{Ctx}}

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 λ□\lambda^{\Box} of Davies and Pfenning [8, 9] is based on the necessity operator □\Box of the intuitionistic modal logic S4: a term of type □A\Box A is closed code of type A, which can safely be evaluated, but the calculus manipulates closed code only. On the other hand, the calculus λ◯\lambda^{\bigcirc} of Davies [6, 7] is based on the “next” operator ◯\bigcirc of linear-time temporal logic: a term of type ◯A\bigcirc A is code that may contain free variables. Thus λ◯\lambda^{\bigcirc} enables the manipulation of open code, which makes it a foundation for the partial evaluation of functional languages [7]. However, λ◯\lambda^{\bigcirc} 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 λ◯\lambda^{\bigcirc} and add run; contextual modal types start from λ□\lambda^{\Box} and add support for open code.

Environment classifiers. The research on environment classifiers, the left arrow of Figure 1, grows out of λ◯\lambda^{\bigcirc} 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 ⟨T⟩α\langle T\rangle^{\alpha} records the classifier α\alpha 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 λ□\lambda^{\Box}. 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 [Ψ]A[\Psi]A lists the context Ψ\Psi 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 Ψ\Psi. 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. λ∀[]\lambda_{\forall[]} [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 λ◯\lambda^{\bigcirc}, restricted to two levels, into λ∀[]\lambda_{\forall[]}. 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 λ[1]\lambda^{[1]} 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 ... α\alpha for a quotation with classifier α\alpha and a tilde ( ∼\sim) 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 λ\lambda-abstraction in code and carries the context y:Int, which binds y (line 1, highlighted), and is then spliced under the abstraction λ\lambda (x:Int).

1 let c = ~y:Int ⊥ y * 2" in 2 ~∅ ⊥ (λ (x:Int). ~c{y=x}) 21"

Reconnecting binders in CMTT

The substitution {y=x}\{y=x\} reconnects the variable y of c to the variable x bound by the abstraction (line 2, highlighted), and metaevaluation produces the closed code ¬∅⊢(λ(x:Int).x∗2)21′′\neg\emptyset \vdash (\lambda (x:Int). x * 2) 21''.

This program has no counterpart in EC, where the code y∗2y * 2 can only be written within the scope of a λ\lambda that binds y and can only be spliced into code

T. Chen et al.

within that scope. It can never be constructed outside any λ\lambda 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, λRefα\lambda_{\text{Ref}}^{\alpha}, is a metaprogramming calculus with refined environment classifiers and mutable references, extended with unrestricted subtyping and subtype-bounded classifier polymorphism. The target language, λRefCtx\lambda_{\text{Ref}}^{\text{Ctx}}, combines features of recent extensions of contextual modal type theory. The λRefCtx\lambda_{\text{Ref}}^{\text{Ctx}} calculus is a two-level metaprogramming language that supports mutable references and polymorphic contexts. To these, λRefCtx\lambda_{\text{Ref}}^{\text{Ctx}} adds first-class substitutions in support of the compilation. Both λRefα\lambda_{\text{Ref}}^{\alpha} and λRefCtx\lambda_{\text{Ref}}^{\text{Ctx}} 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 λRefα\lambda_{\text{Ref}}^{\alpha} to λRefCtx\lambda_{\text{Ref}}^{\text{Ctx}} 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 β\beta, the compilation recovers the context Γβ\Gamma_{\beta} of the scope that the binder introduces by following EC subtyping outwards. The binder lies in the scope of an enclosing classifier α\alpha, so Γβ\Gamma_{\beta} is Γα\Gamma_\alpha extended with the variable that the binder binds, and the chain ends at the empty classifier ε\varepsilon, whose context is empty. The compiler calculates the context for each classifier: Γα=x:Int\Gamma_\alpha = x:\text{Int}, Γβ=(x:Int,y:Int)\Gamma_\beta = (x:\text{Int}, y:\text{Int}), and Γε=∅\Gamma_\varepsilon = \emptyset. Every classifier annotation of the source is then replaced by the context that it corresponds to, shown in matching colors: α\alpha corresponds to x:Int\mathbf{x}:\text{Int} and β\beta to x:Int\mathbf{x}:\text{Int}, y:Int\mathbf{y}:\text{Int}. The quotation ¬x+y′β\neg\mathbf{x} + \mathbf{y}' \beta becomes a quotation annotated with x:Int\mathbf{x}:\text{Int}, y:Int\mathbf{y}:\text{Int}, and the outer quotation, of the empty classifier ε\varepsilon, is annotated with the empty context ∅\emptyset. The code-level abstractions lose their classifiers, since the contexts now carry that information. The interesting part is the framed occurrence of x\mathbf{x}, which is bound in the scope named α\alpha but used in code of classifier β\beta. This is allowed because the scope named by β\beta lies within the scope named by α\alpha. In the target, this occurrence compiles to a quotation of x\mathbf{x} in its own context x:Int\mathbf{x}:\text{Int}, spliced into the larger context (x:Int,y:Int)(\mathbf{x}:\text{Int}, \mathbf{y}:\text{Int}) under the substitution {x=x}\{x=x\}. Scope nesting therefore becomes context weakening, witnessed by a substitution. Finally, the splice around the let-expression gains the substitution {x=x,y=y}\{x=x, y=y\}, which maps the two variables of the quotation's context to the ones bound by the λ\lambda-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.

  1. We present λRefCtx\lambda_{\mathrm{Ref}}^{\mathrm{Ctx}}, 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].

  2. We define a type-directed compilation from λRefα\lambda_{\mathrm{Ref}}^{\alpha} to λRefCtx\lambda_{\mathrm{Ref}}^{\mathrm{Ctx}}, thereby establishing the connection between the nominal scopes of environment classifiers and the structural contexts of contextual modal types.

  3. 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 λRefα\lambda_{\mathrm{Ref}}^{\alpha} and λRefCtx\lambda_{\mathrm{Ref}}^{\mathrm{Ctx}}, 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.