programming languages

Taming Scope Extrusion in Gradual Imperative Metaprogramming

arXiv:2602.19951

summary

The paper introduces a gradual metaprogramming language that supports mutable references while guaranteeing scope safety, using dynamic enforcement of environment classifiers via a novel cast calculus and mechanized proofs in Agda.

Abstract

Metaprogramming enables the generation of performant code, while gradual typing facilitates the smooth migration from untyped scripts to robust statically typed programs. However, combining these features with imperative state - specifically mutable references - introduces the classic peril of scope extrusion, where code fragments containing free variables escape their defining lexical context. While static type systems have employed environment classifiers to successfully tamed this interaction, enforcing these invariants in a gradual language remains an open challenge. This paper presents , the first gradual metaprogramming language that supports mutable references while guaranteeing scope safety. To put on a firm foundation, we also develop its statically typed sister language, , which introduces unrestricted subtyping for environment classifiers. We mechanize the proof of scope safety for , contributing the first mechanized proof of scope safety for a statically typed language. Our key innovation, however, is the dynamic enforcement of the environment classifier discipline in , enabling the language to mediate between statically verified scopes and dynamically verified scopes. The dynamic enforcement is carried out in a novel cast calculus that uses an extension of Henglein's Coercion Calculus to handle code types, classifier polymorphism, and subtype constraints. We prove that satisfies type safety and scope safety. Finally, we provide a space-efficient implementation strategy for the dynamic scope checks, ensuring that the runtime overhead remains practical. All of our results are fully mechanized in Agda.

52 pages, 36 figures

Topics & keywords

#gradual typing#metaprogramming#mutable references#scope safety#environment classifiers#cast calculusλ^α,⋆_Refenvironment classifierscoercion calculusAgda mechanizationsubtypingdynamic scope checks
Taming Scope Extrusion in Gradual Imperative Metaprogramming · wovepaper