Independent scholarship · Open accessThe monthly digest

Editorially reviewed

Typed Rewriting Under Binders: Higher-Order Patterns, Categorical Semantics, and an Executable Shell in Scope

A typed higher-order pattern determines a unique contextual factorization. We connect the structural matcher to cartesian closed 2-categorical semantics, implement Scope in Mercury, and write a lexical pipeline shell in Scope. Its 93 source lines are compared with 138 in Python and 244 in Go using identical session tests.

Anonymous author← All research

1. The rule that motivates the calculus

Consider a join of customers $c$ and orders $o$ with condition $P(c)\land(Q(o)\land J(c,o))$. Moving the two unary predicates to the inputs requires recognizing unknown predicate bodies, checking which bound variables they use, and reinstantiating each under a new binder. In the implemented language Scope this is a single typed rule.

(rule push-filters
  (optimize (joinOn ?l ?r (fn x (fn y
    (andP (?L x) (andP (?R y) (?J x y)))))))
  (joinOn (keep (fn u (?L u)) ?l)
          (keep (fn v (?R v)) ?r)
          (fn u (fn v (?J u v)))))

At the first flexible occurrence, (?L x) admits a subtree depending on $x$ and ambient variables. A subtree with a free occurrence of the second local variable $y$ fails this match. The right-hand expression (?L u) reinstantiates the recovered body. This paper gives a categorical account of that operation, a Mercury implementation, several running transformations, and an interactive shell programmed entirely in Scope. The attached two-column PDF contains the full exposition and diagrams.

2. Types, bindings and matches

Types are declared sorts and arrows $A\to B$. A rigid symbol has a fixed finite list of argument types and a result type. Terms include variables, text literals, operations, typed abstraction and explicit application. A rule has a rigid user-defined head, an equally typed right-hand side, and a context of metavariables. A metavariable $M:(A_1,\ldots,A_k)\Rightarrow B$ denotes an open body with $k$ ordered formal positions. On the left each argument must be a distinct variable bound since the rule root. On the right the arguments may be arbitrary terms of the formal types. Repeated occurrences of $M$ require a common abstracted body. A wildcard discards one match.

The evaluator supports (lam x A t) and the expected-type form (fn x t). For example, (p ?M ?M) expresses equality of two subjects. The left-hand spine (?M x x) is ill formed. Profiles are inferred from the first left-hand occurrence and checked at every subsequent occurrence. Structural equality is modulo alpha. An explicit object-level beta contraction is a separate rewrite. In particular, the structural matcher does not implement general matching modulo beta and eta.

3. Factorization in a presheaf topos

Let $\mathcal R$ have finite typed contexts as objects. A map $\sigma:\Delta\to\Gamma$ assigns to each variable of $\Gamma$ a variable of the same type in $\Delta$. The term sets $T_A(\Gamma)$ of alpha-classes of raw terms define a presheaf in $[\mathcal R^{op},\mathbf{Set}]$ by renaming. The presheaf laws follow by structural induction, extending each renaming under binders.

Suppose a flexible pattern occurs under rule-local binders $\Lambda$, outside of which there is an ambient context $\Gamma$. The selected spine $\pi=(x_{i_1},\ldots,x_{i_k})$ gives a formal context $\Xi=(z_1,\ldots,z_k)$ with matching types. The variable projection $p_\pi:\Gamma,\Lambda\to\Gamma,\Xi$ fixes $\Gamma$ and sends $z_j$ to $x_{i_j}$.

Support lemma. $T_B(p_\pi)$ is injective, with image exactly the terms whose free occurrences from $\Lambda$ belong to $\pi$.

Proof. Traverse the subject. Retain variables bound inside the subject and variables in the ambient context. Replace a selected local by its formal variable and fail on any unselected local. Rigid nodes are copied recursively, taking fresh names under abstractions. Applying $p_\pi$ to a successful result recovers the subject. Conversely, abstracting $u[p_\pi]$ recovers $u$, since the spine has distinct entries disjoint from the ambient context. These are both inverse identities on the specified image.

Thus a match $M(\pi)=s$ has exactly one possible assignment for $M$, the preimage of $s$. The square for ambient $\sigma$ commutes by variable substitution, so an existing match survives reindexing.

Matcher theorem. For well-typed patterns and equally typed subjects free of metavariables, the structural matcher terminates and succeeds exactly for satisfying valuations. Its assignments for all named metavariables occurring in the pattern are unique.

Proof. Descend pairwise through equal rigid nodes. Check literals and variables directly and extend the local context at a lambda. At a metavariable use the support lemma. Store the preimage on its first occurrence, then compare all subsequent preimages in the common formal context. This derives every assignment required by a solution. Conversely, a successful traversal reconstructs the subject at each occurrence. Expand each wildcard to a fresh metavariable applied to all local binders and discard its assignment. The subject traversals, spine checks and structural comparisons are finite.

4. The two index operations and preservation

Bound occurrences are de Bruijn indices, with zero nearest. Let $d$ be the number of rule-local binders, $k$ the spine length, and $c$ the additional depth inside the candidate subtree. An index $i<c$ refers to an internal binder and is copied. For $i=c+j$ with $j<d$, write $c+\ell$ if $\pi_\ell=j$ and reject if $j$ is absent. For $j\geq d$, write $c+k+j-d$. This places formal slots in written order above the ambient indices.

On a right-hand side at local depth $d'$, a formal slot $c+\ell$ is replaced by actual argument $a_\ell$ weakened by $c$. An ambient variable $c+k+h$ becomes $c+d'+h$. These simultaneous operations implement capture-avoiding substitution. Object beta uses the same instantiation with one actual argument. For example, evaluating $\lambda y.((\lambda x.\lambda y.x)\,y)$ strongly gives $\lambda v_0.\lambda v_1.v_0$.

Subject reduction. Checked rule instances, beta contraction and replacement in a typed surrounding context preserve the result type. The support lemma gives each stored body its declared type in $\Gamma,\Xi$. Induction on the right-hand side reduces the metavariable case to typed simultaneous substitution, proved by induction on the body with lifted substitution under lambda. The same lemma types the beta case. Induction on the one-hole context completes the proof.

5. Transformations between terms

In a cartesian closed interpretation, $\Gamma\vdash t:A$ denotes an arrow $[\![\Gamma]\!]\to[\![ A]\!]$. By currying, a contextual metavariable of profile $(A_1,\ldots,A_k)\Rightarrow B$ is interpreted in the exponential $[\prod_i[\![ A_i]\!],[\![ B]\!]]$. Let $V_\Theta$ be the product of these objects. The left and right sides of a rule are parallel arrows from $V_\Theta$ to $[\![ B]\!]$.

In a strict cartesian closed 2-category with chosen Cat-enriched structure, a model must supply a 2-cell $\rho_r:[\![ L]\!]\Rightarrow[\![ R]\!]$ for each directed rule. A valuation $v:[\![\Gamma]\!]\to V_\Theta$ gives its instance by whiskering $\rho_r*v$. Consecutive steps compose vertically. Placing a step in a typed context uses functoriality of products, evaluation and currying. In $\mathbf{Cat}$ these 2-cells are natural transformations. For the category $0\to1$ its nonidentity arrow is a noninvertible transformation between functors from the terminal category.

Sound interpretation. A finite path of compatible pure steps yields a 2-cell between the interpretations of its endpoints, assuming primitive computations respect their equations. At a rule root use whiskering, at a contextual step use the operations on hom-categories, and concatenate by vertical composition. Beta has equal interpretations at both endpoints and maps to an identity. For steps in distinct arguments, the two composites in the product hom-category are the same pair $(\alpha,\beta)$. Postcomposition with the operation preserves that equality. Hirschowitz's free cartesian closed 2-category gives an established soundness and completeness result for permutation equivalence in its own rewrite presentation [7].

At a fixed context and type, quotient compatible paths by disjoint exchange. The ordinary nerve of this category has terms, paths and composable pairs with their composites in degrees zero, one and two. Ambient renaming acts on unrestricted pure paths and their exchanges. The deterministic scheduler has a different property. With ordered rules $h(M,M)\to a$ and $h(M,N)\to b$, the expression $h(x,y)$ selects $b$, but identifying $x,y$ enables the earlier rule and selects $a$. Every positive match reindexes even though first-match selection fails to commute with this renaming.

6. Evaluation and programs

The Mercury implementation contains a reader, static checker, de Bruijn representation, semideterministic matcher, deterministic instantiation, two reduction strategies and an effect driver. The strong norm order tries a root contraction first, then visits children and lambda bodies. The weak eval order reduces arguments from left to right before the root and suspends lambda bodies. run uses weak evaluation until an outer I/O action is available. Only the driver performs the action and passes its result to the continuation. A fuel limit bounds pure contractions and reports exhaustion. Determinism does not imply confluence. For the ordered rules $f(a)\to b$, $f(M)\to a$, strong evaluation of $f((\lambda z.z)\,a)$ gives $a$, and weak evaluation gives $b$.

The sequence optimizer fuses nested maps and absorbs a map into a left fold. Its rule replaces $\mathrm{fold}(H,a,\mathrm{map}(F,X))$ by $\mathrm{fold}(\lambda b.\lambda t.H(b,F(t)),a,X)$. For finite lists and total pure interpretations, induction on the list proves equality. At a head $x$ both sides update to $H(a,F(x))$. The output of the sample program fuses increment and square into the body of a single fold.

The query transformation in Section 1 preserves each accepted pair of rows, its multiplicity and its order under stable filtering and left-major iteration. The condition on both sides is $l\in L\land r\in R\land P(l)\land Q(r)\land J(l,r)$. The converse example permutes two bound arguments while preserving all internal bindings. The hoisting example moves $R(a)$ out of $\exists x.(N(a,x)\land R(a))$ for ambient $a$ and rejects the same move when the conjunct is $R(x)$.

7. The shell is written in Scope

The command lexer, parser, read loop, dispatch, lexical definitions, sequencing and recovery are all rewrite rules. Mercury provides generic text and I/O primitives. Foreign code launches an argv directly with POSIX posix_spawnp. The application accepts quoted and escaped words, literal bars, pipelines, external commands, cd, quit, echo, ASCII casing, lexical pipeline definitions and repeated stages.

An effect plan either yields text, fails with a diagnostic, or requests an external process with arguments, input and an output-dependent continuation. For texts $S$, argument vectors $W$, errors $E$ and returns $X$, well-founded plans have the polynomial-with-exponent tree presentation $P X=\mu Y.(X+E+(W\times S)\times Y^S)$. The executable is specialized to $X=S$ and uses representable lambda bodies. Its sequencing rules are

(rule return (bind (yield ?v) (fn x (?K x))) (?K ?v))
(rule abort (bind (bad ?e) _) (bad ?e))
(rule through (bind (ask ?a ?s (fn x (?K x))) ?h)
  (ask ?a ?s (fn y (bind (?K y) ?h))))

For well-founded trees, substitution at successful leaves has the two unit laws and associates, by induction and pointwise equality at continuations. Commands remain ordered along each observed execution.

A pipeline definition stores a function from text to plans with its definition-time environment. The rule (lookup ?n (binding ?n (fn x (?Body x)) _) ?s) → (?Body ?s) checks name equality and substitutes the current input into the recovered open program. The following session distinguishes lexical and dynamic lookup.

> def tag sed 's/^/old:/'
> def saved use tag
> def tag sed 's/^/new:/'
> echo row | use saved
old:row
> echo row | twice use tag
new:new:row

A failed stage cancels subsequent stages in its pipeline. External stderr is inherited. Each successful stdout is buffered, limited to 4 MiB and checked for UTF-8 text without NUL. Stages execute sequentially. This shell has finite text pipelines, without concurrent streaming or job control.

8. Reproducibility and measurements

The bundle contains a Linux x86-64 executable and a Mercury 22.01.8 source build, the Scope libraries and programs, independent Python and Go shells, the test runner, the measurement code and the typesetting sources. On Debian 13 x86-64, make runtime obtains two checksum-verified runtime packages locally. make shell runs the program. make test executes the comparisons and make compare reproduces the counts.

ImplementationSource linesNon-whitespace charactersRaw bytes
Scope application441,7562,218
Two imported Scope libraries491,8112,487
Complete Scope shell933,5674,705
Python1382,9264,740
Go2444,2885,640

Lines exclude blanks, shebangs and full-line comments. Brace-only lines and declarations count. Raw bytes include formatting and comments. The reduction in complete source lines is 32.6% relative to the supplied Python program and 61.9% relative to Go. Python uses fewer non-whitespace characters. The language runtime is accounted for separately, with 544 Mercury lines and 68 lines in the POSIX C header. Source size does not measure runtime speed or human effort.

The three shells passed the same 52 batch sessions and one interactive pseudoterminal session apiece. The matcher passed 1,220 depth/spine/subject cases, with 872 accepted and 348 rejected. The independent oracle calculates free variables on named terms and performs simultaneous replacement. Query denotations before and after optimization agree in all 4,096 interpretations of two tables, two unary predicates and a binary predicate on a two-row universe. Fold denotations agree on all 121 lists of length at most four over three elements. The tests also cover alpha-renaming, ambient references, repeated metavariables, permutation, rule priority, malformed rules and exact fuel boundaries. The proofs in the PDF establish the general syntactic results. Lean mechanization is a follow-up.

9. Prior work

Miller proved decidability and existence of most general unifiers in a restricted higher-order fragment [1]. Nipkow introduced higher-order critical pairs for systems with pattern left-hand sides [2]. Combinatory reduction systems support object-level binding and substitution in rules [3]. Fiore, Plotkin and Turi gave initial models with compatible substitution structures [5]. Fiore and Mahmoud connected second-order algebraic presentations with categorical theories [6]. Hirschowitz treated permutation equivalence through cartesian closed 2-categories [7]. Executable precedents include Beluga's contextual objects [8], Rose's CRSX compiler transformations [9], and the Teyjus implementation of lambda Prolog [10]. Saillard studied rewriting modulo beta in a dependent logical framework [11]. The journal's Caprice paper deals with captures of text in byte-string patterns [14]. Here the captured object is a typed open term.

Anonymous responsible author. AI assistance supported drafting, formulation, implementation and execution of the tests.

References

1. D. Miller, A Logic Programming Language with Lambda-Abstraction, Function Variables, and Simple Unification, JLC 1 (1991), 497–536. Report and publication record. 2. T. Nipkow, Higher-Order Critical Pairs, LICS (1991), 342–349. Conference record. 3. J. W. Klop, V. van Oostrom and F. van Raamsdonk, Combinatory Reduction Systems: Introduction and Survey, TCS 121 (1993), 279–308. CWI text. 4. N. G. de Bruijn, Lambda Calculus Notation with Nameless Dummies, 1972. Publisher record. 5. M. Fiore, G. Plotkin and D. Turi, Abstract Syntax and Variable Binding, LICS (1999), 193–202. Authors' page. 6. M. Fiore and O. Mahmoud, Second-Order Algebraic Theories, MFCS (2010), 368–380. Open manuscript. 7. T. Hirschowitz, Cartesian Closed 2-Categories and Permutation Equivalence in Higher-Order Rewriting, LMCS 9(3), 2013. Journal article. 8. B. Pientka and J. Dunfield, Beluga: A Framework for Programming and Reasoning with Deductive Systems, IJCAR (2010), 15–21. Authors' page. 9. K. H. Rose, Higher-order Rewriting for Executable Compiler Specifications (2011). Open manuscript. 10. G. Nadathur, Teyjus: A λProlog Implementation (2010). Article. 11. R. Saillard, Rewriting Modulo β in the λΠ-Calculus Modulo, LFMTP (2015). Open manuscript. 12. G. Plotkin and J. Power, Algebraic Operations and Generic Effects, ACS 11 (2003), 69–94. Publication record. 13. The Mercury Project, Mercury Language Reference Manual, ch. 6. Determinism. 14. Anonymous author, Caprice: Higher-Categorical Semantics of Capture-Aware Partial Evaluation and JIT Matching, Higher Categorical Semantics, 25 October 2026. Editorially reviewed. Journal article.

Reproducibility artifacts

typed-rewriting-under-binders.pdf · 503,208 bytes · Download
SHA-256 c64358ecb7f15d87821076ffaf245d71a79dcbda532915b42f7604740f1c2ae0

scope-rewriting-artifacts-1.0.zip · 589,487 bytes · Read in browser · Download
SHA-256 7c9a5d3f7a2e69a98e31c4a0e9a834bdcd63c7d3c031bf95e1b01b442d7d5fff

scope-shell.scope · 4,639 bytes · Download
SHA-256 6418ec95d9bc9fb78ce34098cd18455f1963c30c3f3b1674a2dc6bf658b1fa35

Discussion

Open a careful, constructive conversation about this note.

Comments appear after editorial approval.