Auto select follows the paper as you scroll. Hover over a marked phrase to preview its Lean and see how the two compare. Click a phrase to keep it selected in Manual.
Contextual Embeddings: Implementing Bound Variables Through Instance Resolution
Links, titles and notes made with AI. Full credit. Open PDF, 27 pages.
Representing bound variables in embedded languages is a challenging problem, often requiring painful trade-offs between expressivity and usability. On the one hand, first-order representations using de Bruijn indices have many nice properties, but quickly become difficult to read and write. On the other hand, higher-order representations can piggy-back on the host language’s binders to offer a more ergonomic interface, at a variety of costs depending on the technique. The current state-of-the-art is unembedding, i.e. a translation from the higher-order representation to the first-order and back again to get the best of both worlds. Unfortunately, the fact that this translation is type-safe relies on external metatheoretic arguments, holding unembedding back from its true potential. We solve this problem with a new embedding technique that uses instance resolution to define a context-directed isomorphism between an ergonomic higher-order interface and a first-order representation. Unlike previous techniques, this also applies to embedded languages with modal and substructural (e.g. linear) type systems, making unembedding relevant for modern languages.
CCS Concepts: • Software and its engineering → Functional languages; Domain specific languages; Language features; Formal software verification.
Additional Key Words and Phrases: embedded domain specific languages, binding, higher-order abstract syntax, interactive proof assistants
ACM Reference Format:
Samantha Frohlich, Jessica Foster, G. A. Kavvos, and Meng Wang. 2026. Contextual Embeddings: Implementing Bound Variables Through Instance Resolution. Proc. ACM Program. Lang. 10, PLDI, Article 191 (June 2026), 27 pages. https://doi.org/10.1145/3808269
Authors’ Contact Information: Samantha Frohlich, University of Bristol, Bristol, United Kingdom, samantha.frohlich@bristol.ac.uk; Jessica Foster, University of Bristol, Bristol, United Kingdom, jess.foster@bristol.ac.uk; G. A. Kavvos, University of Bristol, Bristol, United Kingdom, alex.kavvos@bristol.ac.uk; Meng Wang, University of Bristol, Bristol, United Kingdom, meng.wang@bristol.ac.uk.
This work is licensed under a Creative Commons Attribution 4.0 International License.
© 2026 Copyright held by the owner/author(s).
ACM 2475-1421/2026/6-ART191 https://doi.org/10.1145/3808269
1 Introduction
Programming languages are the tool we reach for to solve computational problems. We take pride in designing languages specialised to different tasks and joy in finding the level of abstraction that’s just right for the task at hand. However, the implementation of a new language—no matter how small—is always a tiresome task: lexing, parsing, and interpreting can be an impediment to rapid prototyping. A well-known and effective solution to this problem is to embed the new (guest or object) language into an existing one (the host or meta language) [Hudak 1996].
One common difficulty is the embedding of binding constructs (those that abstract over variables, for example let or a -abstraction, increasing the language’s expressivity). Implementing binders from scratch can be cumbersome, due to fiddly issues such as scope, name duplication, and capture-avoiding substitution [Pfenning and Elliott 1988]. As such, embedding languages with binders is a well-explored area [Atkey 2009; Carette et al. 2009; Chlipala 2008; Despeyroux, Felty, et al. 1995; Despeyroux and Hirschowitz 1994; Despeyroux, Pfenning, et al. 1997; Huet and Lang 1978; Matsuda, Frohlich, et al. 2023; Washburn and Weirich 2008].
The problem of implementing binders for embedded languages is further complicated as interest extends beyond languages with structural—which support weakening, contraction, and exchange— to type systems to those where restrictions are placed on the usage of bound variables. In modal type systems, the types can specify when a variable can be used. This is useful for guiding the correct programming of staged computation [Davies and Pfenning 2001] and ensuring that data does not flow in an undesirable manner [Kavvos 2019; Tune et al. 2026]. In modal and substructural type systems, the types can specify how many times a variable can be used. Such systems are already used in influential languages like Rust [Matsakis and Klock 2014], which uses affine typing to control the use of mutable variables, and Haskell, which now has linear functions that ensure their input is used exactly once [Bernardy, Boespflug, et al. 2018]. Linear type systems in particular have become increasingly relevant as quantum computing develops, with qubits being non-clonable and non-discardable resources [Heunen and Vicary 2019, §4]. Hence, a modern embedding technique is required to support modal and substructural type systems.
The simplest approach to implement binders is a first-order embedding that explicitly represents binding, often using de Bruijn [1972] indices. For example, in Haskell we would write:
tt = Lambda (Lambda (Var One)) -- \xy.x, Church encoding of 'true'
ff = Lambda (Lambda (Var Zero)) -- \xy.y, Church encoding of 'false'
Unfortunately, de Bruijn indices (and first-order representations in general) are not particularly user-friendly. Explicit representations of binding are less intuitive to programmers, and error-prone. For example, consider how easy it would be to accidentally define tt instead of ff.
To solve this, functional programmers follow the ethos of reuse by developing Higher-Order Abstract Syntax (HOAS) [Huet and Lang 1978; Pfenning and Elliott 1988], which uses the host language’s binders to implement guest binders. This technique is central to logical frameworks [Avron et al. 1987; Harper et al. 1993; Miller and Nadathur 2012].
Using HOAS we may encode the previous examples in a more ergonomic way:
data HOAS = Lam (HOAS -> HOAS) | App HOAS HOAS
tt = Lam (\x -> Lam (\y -> x)) :: HOAS -- \xy.x, Church encoding of 'true'
ff = Lam (\x -> Lam (\y -> y)) :: HOAS -- \xy.y, Church encoding of 'false'
However, HOAS can introduce a number of issues. For example, the simple implementation above admits exotic terms, i.e. elements that do not correspond to an embedded program. Additionally, HOAS directly supports only program transformations that can be defined as folds. However, in the back-end of the embedded language we often wish to express more complex program transformations, such as closure conversion or shrinking reduction optimisations, which are not easily written as folds [Atkey et al. 2009]. This prompts us to transform programs to a first-order representation, in a process called unembedding [Atkey et al. 2009]. Thus, the current state-of-the-art amounts to using HOAS in the front-end, which is then unembedded to obtain a more versatile first-order representation in the back-end.
The importance of unembedding as an implementation technique was highlighted by Matsuda, Frohlich, et al. [2023], who systematically applied it to languages with more complex semantics. For example, they used unembedding to embed HoBiT [Matsuda and Wang 2018], a bidirectional lens language that uses expressive binders instead of combinators. Previous implementations were challenging, relying on techniques developed specifically for each domain.
Implementing unembedding in a type-safe manner is surprisingly hard, even in languages with cutting-edge type systems [Grenrus 2025]. Current implementations [Atkey et al. 2009; Keuchel and Jeuring 2012; Matsuda, Frohlich, et al. 2023; McDonell et al. 2013] rely on externally justified operations (fromJust, postulate, unsafeCoerce, and a dynamic lookup, respectively) whose safety cannot be verified by the host language’s type system. Atkey [2009] dedicates a whole paper to this proof, which is reused / adapted carefully by Matsuda, Frohlich, et al. [2023], McDonell et al. [2013], and Keuchel and Jeuring [2012]. [Chlipala \2008, §3.1] encounters a similar problem in the setting of theorem provers with his work on Parametric Higher-Order Abstract Syntax (PHOAS): he finds it necessary to assert an additional axiom—an instance of internal parametricity—which is not readily available in current theorem provers.
This paper advances the state-of-the-art by presenting a new embedding technique which is evidently type-safe, allows unembedding, supports modal/substructural type systems, and incurs reasonable compile time and run time overheads. In summary:
-
We present Contextual Embeddings (§3), a technique for embedding languages with binders that combines the precision of first-order representations (§2) with an ergonomic interface.
-
We demonstrate the core ideas by embedding the Simply-Typed -Calculus (STLC) (§3.2).
-
We justify the embedding with a proof that it is isomorphic to its first-order representation via a type-safe conversion, without requiring parametricity (§3.3).
-
We argue that this is a flexible and applicable technique in any language with GADTs, type-level data (e.g. dependent types or Haskell DataKinds), and a suitable type class system (§3.5).
-
We explore its performance (§3.6) and usability (§3.7), finding that it incurs reasonable costs, composes well, and does not require explicit type annotations.
-
We argue that the technique is general by presenting embeddings of structural (§3.2), modal (§4), and substructural (§5) languages, without requiring modal or substructural features in the host language. To our knowledge, this is the first technique to encompass all of these categories.
-
We develop a simplified version of our technique that can uniformly tackle all three categories of type systems (§6, §7, §8). The cost of this simplification is slightly reduced canonicity of the first-order embedding through the addition of some redundant type information, which we argue is a reasonable engineering solution.
Loading the paper…