Independent scholarship · Open accessThe monthly digest

Full manuscript · browser edition

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

Continuous, single-column reading. Equations, tables, proofs, references and appendices stay in document order.

Contents · 19 sections

Typed Rewriting Under Binders

Abstract. A rewrite rule can inspect a binding construct and specify exactly which local variables an unknown subterm may use. We introduce this idea through typed query optimization and develop its semantics in a presheaf topos of contexts. A match at a metavariable is a unique factorization through a variable projection. Typed rule instances give directed 2-cells in cartesian closed 2-categorical models. The account distinguishes structural matching, object-level β\beta-reduction, and the observable order of effects. We implement the language, Scope, in Mercury and write a command shell in Scope itself. Its lexically scoped pipeline definitions use the same contextual substitution as the optimizer. The shell occupies 44 application lines and 93 lines with its two libraries. Independent Python and Go implementations occupy 138 and 244 lines. Executable comparisons, negative matches and finite-model checks accompany the mathematical proofs.

A predicate inside a join

Suppose a query joins customers cc with orders oo. Its condition has the form P(c) ∧ (Q(o)∧J(c,o)).P(c)\ \wedge\ \bigl(Q(o)\wedge J(c,o)\bigr). The customer table can be filtered by PP and the order table by QQ before the join. An optimizer must recognize this shape even when PP, QQ, and JJ are large expressions. It must also reject the proposed move when the first predicate uses oo. Matching a node named conjunction settles neither question.

In Scope the expression (?L x) in a pattern denotes an unknown term with one permitted local argument. A match of (?L x) inside two binders for xx and yy requires the subject subtree to be independent of yy. Ambient variables outside the rule instance remain available. The right-hand side (?L u) instantiates the same term at uu. These two occurrences account for the dependency test and the change of binder in one 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)))))

Here fn introduces a binder whose type is fixed by the surrounding declaration. The ? prefix distinguishes a metavariable of the rule from a variable of the query. If the first conjunct is (same x y), the flexible occurrence (?L x) fails. A subsequent fallback rule returns the original query. The dependency test also applies inside a nested predicate with its own lambda.

There are two dimensions to the example. A higher-order pattern can refer to a term with open parameters. A higher-categorical model also represents the transformations between terms. The first notion supplies a programming construct. The second determines which composites of transformations have the same interpretation.

The surface language

Types are generated by declared base sorts ss and arrows A→BA\to B. A monomorphic declaration c:(A1,…,An)→Bc:(A_1,\ldots,A_n)\to B fixes a symbol’s arity and result type. Constructors and user operations have the same application syntax. A program declares its symbols, gives an ordered list of rules for each defined head, and chooses an entry term. Imports are relative to their enclosing source file.

Form Interpretation
(data O a (p O O)) Base sort with a point and a binary constructor.
(sig f O O) Unary operation from OO to OO.
(lam x O t) Abstraction over a variable of sort OO.
(fn x t) Abstraction checked against an expected arrow.
(ap A B f t) Apply f:A→Bf:A\to B to t:At:A.
(?M x y) A dependency list on the left, an instantiation on the right.
(= l r) An ordered rule with a generated trace label.
(rule tag l r) A rule with an explicit label.

Strings have type Text. The notation ["use" ?n] expands to a two-element list of texts. The pattern ["echo" | ?rest] allows an arbitrary tail. A wildcard _ can occur in any left-hand argument. Its match is discarded.

For example, λy. (λx.y) y\lambda y.\,(\lambda x.y)\,y reduces to the identity. A more revealing test applies λx.λy.x\lambda x.\lambda y.x to an outer yy. The result under that outer binder is λy.λz.y\lambda y.\lambda z.y. Character replacement can change the referent of yy. Scope translates bound occurrences to de Bruijn indices before matching [4].

Two contexts in a rule

Write Γ⊢t:A\Gamma\mathbin{\vdash}t:A for an ordinary term judgment. A metavariable declaration M:(A1,…,Ak)⇒BM:(A_1,\ldots,A_k)\Rightarrow B describes a body of type BB with kk formal positions. The metavariable context Θ\Theta contains such declarations. At a pattern occurrence, MM takes pairwise distinct variables from binders crossed since the rule root. On a right-hand side, MM takes arbitrary expressions of the declared types. Profiles must agree across occurrences. A rule head is a user-declared rigid symbol. Every right-hand metavariable must occur on the left.

Scope infers each profile from the expected result type and local argument types at its first left-hand occurrence. The second occurrence can impose an equality test. For example, (p ?M ?M) matches two structurally equal subtrees. The form (?M x x) is rejected in a pattern. Equality of two occurrences of a metavariable and repetition of a variable in one occurrence’s argument list are different constraints.

Equality at match time

Rigid constructors, application nodes, and text literals compare structurally. Abstractions compare after erasing binder names. Scope implements one-sided, structural matching modulo α\alpha on explicitly represented typed terms. Its allowed left-hand spines are the distinct-variable spines of the higher-order pattern fragment [1, 2]. Object-level β\beta-contraction is a separate executable step. General matching modulo βη\beta\eta is outside this calculus. For example, an application with a lambda head and its contractum have different rigid shapes at match time. Both shapes can therefore occur in an observable reduction trace.

Contexts as a presheaf topos

Fix the set of base sorts and a signature. Let R\mathcal R have finite lists of typed variables as objects. A morphism σ:Δ→Γ\sigma:\Delta\to\Gamma assigns to each variable of Γ\Gamma a variable of the same type in Δ\Delta. A term at Γ\Gamma can therefore be renamed to a term at Δ\Delta. Substitution of these variable assignments defines composition. With this variance convention, R^=[Rop,Set]\widehat{\mathcal R}=[\mathcal R^{\mathrm{op}},\mathbf{Set}] is a presheaf topos. For each type AA, let TA(Γ)T_A(\Gamma) be the set of typed α\alpha-classes of raw terms in Γ\Gamma. The action t↦t[σ]t\mapsto t[\sigma] defines a presheaf TAT_A. The unit and composition equations hold by induction on terms. At an abstraction the induction uses the extended renaming σ+:Δ,x:B→Γ,x:B\sigma^+:\Delta,x:B\to\Gamma,x:B. This is the context-indexed treatment of binding developed for signatures with substitution by Fiore, Plotkin and Turi [5]. Parameterized metavariables also occur explicitly in second-order algebraic theories [6].

Definition 1. An occurrence below local binders Λ\Lambda with spine π=(xi1,…,xik)\pi=(x_{i_1},\ldots,x_{i_k}) determines a formal context Ξ=(z1:Ai1,…,zk:Aik)\Xi=(z_1:A_{i_1},\ldots,z_k:A_{i_k}). For each ambient Γ\Gamma its variable projection is the map pπ:Γ,Λ⟶Γ,Ξp_\pi:\Gamma,\Lambda\longrightarrow\Gamma,\Xi with pπ(zj)=xijp_\pi(z_j)=x_{i_j} and pπ∣Γ=1p_\pi|_\Gamma=1.

A subject subtree s∈TB(Γ,Λ)s\in T_B(\Gamma,\Lambda) matches M(π)M(\pi) precisely when it has a preimage under TB(pπ)T_B(p_\pi). For Λ=(x,y)\Lambda=(x,y) and π=(x)\pi=(x) the term active(x)\mathsf{active}(x) has preimage active(z1)\mathsf{active}(z_1). The term same(x,y)\mathsf{same}(x,y) has no preimage. The term flag(a)\mathsf{flag}(a) for a∈Γa\in\Gamma has the constant-in-z1z_1 preimage flag(a)\mathsf{flag}(a).

Lemma 2 (Support and unique factorization). The function TB(pπ)T_B(p_\pi) is injective. Its image consists exactly of terms whose free occurrences from Λ\Lambda belong to the spine π\pi.

Proof. Choose distinct formal names fresh for the ambient context. Starting at the root of ss, copy literals and rigid nodes. Replace each occurrence of a selected local by its formal name in spine order. Retain ambient occurrences and occurrences bound strictly inside ss, using fresh names under abstractions. An occurrence of an unselected local is the unique source of failure in this traversal. Reapplying pπp_\pi recovers ss modulo α\alpha. In the opposite direction, the traversal applied to u[pπ]u[p_\pi] recovers uu, because the selected variables are distinct and disjoint from Γ\Gamma. These two identities prove the image description and injectivity. ◻

The square for an open match

Changing the surrounding context from Γ\Gamma to Δ\Delta by σ\sigma leaves the local spine fixed. Reindexing and projection commute. image Here [σ+Ξ][\sigma+\Xi] acts as σ\sigma on ambient variables and as the identity on locals. The equality around the square follows on variables from the definition of pπp_\pi, and extends to all terms. An existing match is stable under ambient renaming. A noninjective renaming can make two previously distinct subtrees equal and thereby enable a new nonlinear rule.

Theorem 3 (Structural matching). For a checked pattern and equally typed subject at a fixed ambient context, the matching traversal terminates. It succeeds exactly when there is a valuation for the pattern modulo α\alpha. On success its values for all named metavariables occurring in the pattern are unique.

Proof. At a rigid node check the symbol and arity and descend pairwise. At a variable or literal check equality. At an abstraction extend the local context by its argument type. At each M(π)M(\pi) apply Lemma 2. Store the preimage for the first occurrence. Every later occurrence requires equality of the new preimage with the stored body in the same formal context. Necessity follows by inversion of a satisfying valuation. Sufficiency follows by reconstructing the subject at every occurrence. A wildcard can be expanded to a fresh metavariable applied to all surrounding locals and then discarded. Every descent traverses a finite subtree. Comparing stored finite bodies and processing finite spines terminate. ◻

The theorem concerns a typed subject free of metavariables, which may contain ambient ordinary variables. Unification problems with unknowns on both sides require a different procedure.

Reindexing in executable terms

Number bound occurrences outwards from zero. At a flexible occurrence let dd be the number of intervening rule-local binders, kk the spine length, and cc the number of additional binders crossed inside the subject subtree. A subject index i<ci<c remains ii. For i=c+ji=c+j the abstraction pass has the following cases. c+ℓj<d, πℓ=j,0≤ℓ<k,failurej<d, j∉π,c+k+(j−d)j≥d.\begin{array}{ll} c+\ell & j<d,\ \pi_\ell=j,\quad 0\leq\ell<k,\\ \text{failure} & j<d,\ j\notin\pi,\\ c+k+(j-d)&j\geq d. \end{array} The argument slots of a stored body are numbered in written spine order. For example, under λx.λy\lambda x.\lambda y, the local indices for (x,y)(x,y) are (1,0)(1,0). The subject edge(y,x)\mathsf{edge}(y,x) abstracts to a body with slots (1,0)(1,0) as arguments of edge\mathsf{edge}. Applying this body to (a,b)(a,b) yields edge(b,a)\mathsf{edge}(b,a).

For instantiation at right-hand local depth d′d', supply arguments a0,…,ak−1a_0,\ldots,a_{k-1}. An index below the current internal depth cc again stays fixed. A slot c+ℓc+\ell, ℓ<k\ell<k, becomes aℓa_\ell weakened by cc. An ambient index c+k+hc+k+h becomes c+d′+hc+d'+h. The operation is simultaneous, so an inserted argument cannot undergo substitution by a later argument. In the source, abstract_var implements the first pass and fill_var the second. Object-level β\beta uses the second pass with one actual argument and d′=0d'=0.

Proposition 4 (Preservation). If a checked rule rewrites ss to tt in ambient Γ\Gamma and Γ⊢s:B\Gamma\mathbin{\vdash}s:B, then Γ⊢t:B\Gamma\mathbin{\vdash}t:B. Object β\beta-contraction and replacement in a typed one-hole context preserve the same judgment.

Proof. The recovered body for MM has its profile result type in Γ,Ξ\Gamma,\Xi, by the typed inverse renaming in Lemma 2. Induct on the checked right-hand side. At a metavariable, weaken its body for the local context, then apply the simultaneous substitution lemma to its typed actuals. That lemma follows by induction on the body, extending the substitution under each lambda. The rigid, application and abstraction cases follow their typing rules. The same substitution lemma proves the β\beta case. Induction on a typed one-hole context proves its replacement property. ◻

In hoist.scope, a conjunct inside an existential depends only on an outer aa and moves out. In the second test the corresponding conjunct uses the quantified xx and stays inside. ∃x (N(a,x)∧R(a)) ⟼ (∃x N(a,x))∧R(a),∃x (N(a,x)∧R(x)) ⟼ ∃x (N(a,x)∧R(x)).\begin{aligned} \exists x\,(N(a,x)\land R(a))&\ \longmapsto\ (\exists x\,N(a,x))\land R(a),\\ \exists x\,(N(a,x)\land R(x))&\ \longmapsto\ \exists x\,(N(a,x)\land R(x)). \end{aligned} The second line records the fallback result. The first equivalence holds in ordinary predicate semantics, including an empty domain for xx. Moving R(x)R(x) out in the second line would create an unbound occurrence.

Directed transformations as 2-cells

Start with a category with chosen finite products and exponentials. Interpret Γ\Gamma by a product and a judgment Γ⊢t:A\Gamma\mathbin{\vdash}t:A by an arrow [ ⁣[Γ] ⁣]→[ ⁣[A] ⁣][\![\Gamma]\!]\to[\![A]\!]. Application uses evaluation and lambda abstraction uses currying. A valuation for M:(A1,…,Ak)⇒BM:(A_1,\ldots,A_k)\Rightarrow B is a body in Γ,Ξ\Gamma,\Xi. By currying it gives an arrow [ ⁣[Γ] ⁣]⟶[[ ⁣[A1] ⁣]×⋯×[ ⁣[Ak] ⁣],[ ⁣[B] ⁣]].[\![\Gamma]\!]\longrightarrow [[\![A_1]\!]\times\cdots\times[\![A_k]\!],[\![B]\!]]. For a nullary metavariable the exponential by the terminal object is canonically isomorphic to [ ⁣[B] ⁣][\![B]\!]. Collect these exponential objects in a product VΘV_\Theta. A rule with no free ordinary variables at its root determines parallel arrows [ ⁣[L] ⁣],[ ⁣[R] ⁣]:VΘ→[ ⁣[B] ⁣][\![L]\!],[\![R]\!]:V_\Theta\to[\![B]\!]. Expand each wildcard as in Theorem 3 before constructing these arrows.

Take a strict 2-category with chosen cartesian closed structure in the Cat-enriched sense. A model of a signature with directed rules assigns to each rule rr a specified 2-cell ρr:[ ⁣[L] ⁣]⟹[ ⁣[R] ⁣].\rho_r:[\![L]\!]\Longrightarrow[\![R]\!] . Existence of these cells is a condition on the model. A valuation v:[ ⁣[Γ] ⁣]→VΘv:[\![\Gamma]\!]\to V_\Theta gives an instance by precomposition, or whiskering, ρr∗v:[ ⁣[L] ⁣] v⇒[ ⁣[R] ⁣] v\rho_r*v:[\![L]\!]\,v\Rightarrow[\![R]\!]\,v. Vertical composition interprets successive steps. Applying a typed surrounding operation interprets contextual replacement, using product functoriality, evaluation and currying on hom-categories. In the standard example Cat\mathbf{Cat}, types are categories, terms are functors, and a rule has a natural transformation as its interpretation.

Proposition 5 (Interpretation of a pure derivation). For every such model, each finite path of compatible pure rule steps has a 2-cell between the interpretations of its endpoints, provided interpreted primitive computations respect their specified equations. Paths differing by the exchange of steps in distinct arguments of a rigid operation induce the same 2-cell.

Proof. Use ρr∗v\rho_r*v at a rule root. The substitution lemma for the cartesian closed interpretation identifies its source and target. For a surrounding one-hole context, the structural operation on the appropriate hom-category is functorial. For an empty path take the identity and for concatenated paths take the vertical composite. For two distinct arguments apply the interchange law in the product hom-category, then postcompose with the operation. Object-level β\beta has identically interpreted endpoints by the chosen exponential law and maps to an identity cell. ◻

For example, let an operation hh combine two inputs and take steps α:f⇒f′\alpha:f\Rightarrow f' and β:g⇒g′\beta:g\Rightarrow g'. Before applying hh, the exchange square is image Its two composites are the pair (α,β)(\alpha,\beta). A computational step can have a noninvertible interpretation. In Cat\mathbf{Cat}, take the category 0→10\to1, two functors from the terminal category selecting its two objects, and the transformation given by its unique nonidentity arrow. Replacing that transformation by equality of the selected objects would change the model.

Hirschowitz constructs a free cartesian closed 2-category for a higher-order rewrite presentation and proves soundness and completeness for the corresponding permutation equivalence [7]. The proposition above gives the sound interpretation required here. Extensional cartesian closed interpretation identifies βη\beta\eta-equal arrows. Raw runtime syntax distinguishes them, and a trace includes β\beta steps. Completeness for the runtime’s choice of steps would be a separate claim.

One further dimension has an explicit construction. Quotient paths at a fixed context and type by the congruence generated by disjoint exchange. Their objects and arrows form a category. Its ordinary nerve has terms as vertices, paths as edges, and composable pairs together with their composite as 2-simplices. For pure user rules and β\beta, the unrestricted relation and disjoint exchange reindex under ambient renamings, so this construction also applies objectwise to obtain simplicial presheaves. Invertibility of reductions and user-specified higher rewrites between derivations require additional structure.

A deterministic implementation

The front end parses declarations, validates sorts and arities, checks both sides at one result type, and indexes rules by their rigid heads. The matcher is a Mercury semidet predicate on a ground pattern and a ground subject. The instantiator is deterministic on checked right-hand sides and completed valuations. Mercury’s mode and determinism declarations specify allowed argument instantiations and success cardinalities [13]. Proposition 4 concerns typing in Scope.

There are two executable orders. norm contracts the first available root rule or β\beta step and otherwise searches children left to right, including lambda bodies. trace emits these same contractions. eval first reduces children left to right, treats lambdas as values, and then tries the root. Both choose the first applicable rule at a user-defined head. run uses the second order up to each I/O request. Only the outer I/O driver executes that request, then supplies the result to its continuation. Effects under an uncalled lambda remain suspended. Stuck I/O and exhausted rewrite fuel produce distinct diagnostics. Arbitrary user rules can loop, overlap or leave terms irreducible.

The difference in order is observable without I/O. Use the ordered rules f(a)→bf(a)\to b and f(M)→af(M)\to a. For the entry f((λz.z) a)f((\lambda z.z)\,a), norm selects the fallback immediately and returns aa. Under eval the argument first contracts to aa, so the result is bb. Deterministic execution therefore does not imply confluence.

A related distinction appears under renaming. Give hh the rules h(M,M)→ah(M,M)\to a and h(M,N)→bh(M,N)\to b in that order. In context x,yx,y, the expression h(x,y)h(x,y) selects bb. After identifying the two variables by a context morphism it selects aa. Each positive rule instance still reindexes to an instance in the unrestricted relation. The operation of selecting the first applicable rule fails to commute with this renaming.

Programs with open subterms

Fusing a map into a fold

A sequence expression can contain map⁡(f,map⁡(g,X))\operatorname{map}(f,\operatorname{map}(g,X)). The fuse rule returns map⁡(λz.f(g(z)),X)\operatorname{map}(\lambda z.f(g(z)),X). Here f,gf,g stand for arbitrary bodies under lambda binders. A second rule absorbs a map into a left fold. fold(H,a,map(F,X))⟶fold(λb.λt.H(b,F(t)),a,X).\begin{aligned} &\mathrm{fold}(H,a,\mathrm{map}(F,X))\\ &\qquad\longrightarrow \mathrm{fold}(\lambda b.\lambda t.H(b,F(t)),a,X). \end{aligned} For finite lists under pure total interpretations, induction on XX proves equality. At the empty list both sides return aa. At head xx both update the accumulator to H(a,F(x))H(a,F(x)). Apply the induction hypothesis to the tail and that new accumulator. For the entry in fusion.scope, the strong strategy applies absorption twice. Its output is a single fold of λb.λt.add⁡(b,sq⁡(inc⁡(t)))\lambda b.\lambda t.\operatorname{add}(b,\operatorname{sq}(\operatorname{inc}(t))). A separate test exercises the map-to-map rule directly. In a first-order representation of syntax, the corresponding optimizer must account for the accumulator and element positions and substitute a map body below the accumulator binder.

Predicate pushdown and converse

For tables L,RL,R and pure total predicates, membership of a pair (l,r)(l,r) in the original join is equivalent to l∈L∧r∈R∧P(l)∧Q(r)∧J(l,r).l\in L\land r\in R\land P(l)\land Q(r)\land J(l,r). This is exactly the membership test after independent filtering. For ordered lists with duplicates, enumerate left rows then right rows and use stable filtering. Each accepted pair of occurrences keeps its relative position. The support test is necessary for this implementation of pushdown. For example, P(l,r)=(l=r)P(l,r)=(l=r) cannot be evaluated from ll alone when rr ranges over {0,1}\{0,1\}.

Converse of a binary relation exchanges its arguments. The executable pattern in transpose.scope lists its variables in the opposite order to their binding.

(rule flip
  (converse (relation (lam x Row (lam y Row
    (?P y x)))))
  (relation (lam a Row (lam b Row (?P a b)))))

The input body (edge x y) yields (edge v1 v0) under output binders v0,v1. With (?P x y) in the pattern, the same right-hand side would preserve argument order. Reading off the two spines suffices to derive both results.

An executable shell written in Scope

The shell and both its imports consist of Scope declarations and rules. commandline.scope parses text into argument vectors and a pipeline tree. plans.scope gives a pure effect syntax and its handlers. The application supplies command meaning, lexical environments, error recovery and the read loop. Built-ins include echo, ASCII upper and lower, cd, quit, def, use and twice. Other names invoke executables on the process search path. The host receives an argument vector through POSIX posix_spawnp.

From characters to commands

A quoted word containing | and an unquoted pipeline separator have distinct constructors. Quotes can occur inside a word, empty quotes form an empty argument, and adjacent quoted fragments concatenate. Single quotes preserve every interior character. Outside single quotes a backslash escapes the following character. Space and tab delimit unquoted words. The parser rejects an empty pipeline stage and propagates lexical errors before executing the line.

(= (quoted ?q [?q | ?r] ?a) (token ?r ?a))
(= (parse (bar _) [])
   (invalid "empty pipeline stage"))

The repeated metavariable in the first rule requires the closing character to equal the opening delimiter. That rule has priority over the ordinary-character case. A successful parse produces either a final argument vector or one vector followed by another pipeline.

A plan and its continuation

With SS the set of texts, WW argument vectors and EE diagnostic texts, the well-founded effect trees with result set XX form the free tree construction PX=μY.(X+E+(W×S)×YS).P X=\mu Y.\bigl(X+E+(W\times S)\times Y^S\bigr). A leaf returns a value or an error. A request contains arguments, input text, and a continuation branch for each successful output. Scope specializes the result type to Text and represents definable continuations by lambda syntax. The construction uses operations and their interpretations in the sense of algebraic effects [12]. Recursive user rules extend beyond the well-founded fragment.

Sequential composition grafts a continuation at the successful leaves.

(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))))

In the third rule yy is fresh, and any free variables of the incoming continuation ?h remain free after insertion. For well-founded trees, left and right unit and associativity of grafting follow by induction. For associativity at a request the two sides have identical labels and have equal branches by the induction hypothesis at each s∈Ss\in S. At a failed leaf both sides return the same diagnostic. These are equalities of trees up to pointwise equality of continuations. Observing a tree against a process environment records a particular sequence of requests. Exchanging two external commands can change that sequence and its result.

Lexical pipeline definitions

A binding stores a pipeline as a function from input text to a plan. The captured environment is the one in force at definition time. A lookup hit uses one rule.

(rule expand
  (lookup ?n (binding ?n (fn x (?Body x)) _) ?s)
  (?Body ?s))

The repeated ?n enforces name equality. The metavariable ?Body captures an open program below the input binder. Its right-hand occurrence substitutes the current input and preserves all other bindings. twice composes two calls of a stage, passing the output of the first as input of the second.

In this session, lines prefixed by > are commands.

> 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

Dynamic lookup of tag during use saved would produce new:row. An error short-circuits the remaining pipeline, prints a diagnostic, and returns to the read loop. Child stderr remains attached to the caller. Each stage buffers its entire stdout in a seekable temporary file and accepts at most 4 MiB of successful output as UTF-8 text without NUL. The resulting shell supports finite text transformations. Concurrent streaming, background jobs, redirection syntax and POSIX shell compatibility are outside its command language.

Evidence and source size

We compiled five Mercury modules with Mercury 22.01.8 in grade hlc.gc on x86-64 Linux. The archive includes a native executable, source build instructions, a checksum-pinned runtime installer, two independent reference shells and a test runner. One set of fixtures exercises identical commands, stdout, stderr and exit status for Scope, Python 3.12.14 and Go 1.27.4. Each implementation also runs a session on a pseudoterminal with a prompt, a pipeline and an explicit exit.

Source Lines Nonspace Bytes
Scope application 44 1,756 2,218
Scope imports 49 1,811 2,487
Scope total 93 3,567 4,705
Python shell 138 2,926 4,740
Go shell 244 4,288 5,640

Lines are physical source lines excluding blanks, shebangs and full-line comments, including declarations and brace-only lines. Nonspace counts non-whitespace characters on those lines. Bytes are complete UTF-8 files. The complete shell is 32.6% shorter by lines than the Python implementation and 61.9% shorter than the Go implementation. Python uses fewer non-whitespace characters. Python uses structural pattern matching and dictionary snapshots. Go uses argument slices and environment snapshots. Both use standard subprocess and file libraries. The Scope total includes both user-space libraries. Language implementations and standard libraries are excluded on every side. The separately reported implementation cost is 544 Mercury lines plus 68 lines in the POSIX C header. The Mercury count includes the foreign declarations. These measurements describe the supplied programs. They establish neither a minimum implementation size nor a speed advantage.

Executed check Count
Scoped subject/spine instances 1,220
Accepted / rejected by support 872 / 348
Two-row interpretations of query pushdown 4,096
Finite inputs for fold absorption 121
Batch / terminal sessions per shell 52 / 1

The binder matrix enumerates local depths zero through three, every ordered subset of those local variables, and a fixed family of subject trees containing constants, ambient variables, pairs and nested abstractions. An independent named-variable oracle computes the allowed free-variable set and simultaneously replaces the selected variables by distinct constants. The executable must produce the oracle result or a fallback marker. Other fixtures check repeated metavariables under reordered and differently nested binders, capture during β\beta-contraction, malformed spines, type errors, fuel exhaustion and include cycles.

For the query example, the test runner reads the input and the optimizer’s emitted normal form. It interprets both on every pair of subsets of a two-row universe, every pair of unary predicates, and every binary predicate. The count is 42⋅42⋅16=40964^2\cdot 4^2\cdot16=4096. The fold test enumerates the 1+3+9+27+81=1211+3+9+27+81=121 lists of length at most four over three elements. Both checks compare denotations. Shell sessions cover quoting, empty arguments, lexical shadowing, repeated external stages, persistent changes of directory, exit status, invalid UTF-8, size limits, errors and EOF. A separate test launches the shell file directly. Finite agreement supports the implementation claims. The general statements in Sections 3 and 5 depend on their mathematical hypotheses and proofs.

Prior work and scope

Miller’s LλL_\lambda isolates a decidable class of higher-order unification problems with most general unifiers [1]. Nipkow uses restricted left-hand sides over simply typed lambda terms and develops higher-order critical pairs [2]. Klop, van Oostrom and van Raamsdonk survey combinatory reduction systems with binders and metavariables, including orthogonal systems [3]. Rose used CRSX to specify parsing, optimization and code emission for a query language [9]. The Teyjus implementation of λ\lambdaProlog uses pattern unification in a logic-programming abstract machine [10]. Scope uses one-sided matching, structural equality and ordered rules. For confluence and critical-pair arguments the matching equality, the rule class and the treatment of overlap must be fixed separately.

The presheaf presentation draws on Fiore, Plotkin and Turi’s binding algebras and Fiore and Mahmoud’s second-order algebraic theories [5, 6]. Hirschowitz gives the directly relevant 2-categorical permutation semantics [7]. Beluga provides contextual objects, higher-order abstract syntax and dependent programming for deductive systems [8]. Saillard’s account of rewriting modulo β\beta in the λΠ\lambda\Pi-calculus modulo treats a different equality and its interaction with dependent types [11]. The journal’s Caprice study treats ordered byte-string matching with captured text, backreferences and specialization [14]. Scope’s metavariable arguments refer to bound variables in terms.

The contribution here is the connection from a typed projection to executable contextual matching, tested transformations and a complete application in the object language. A subsequent Lean mechanization can establish the inverse laws for the two index traversals, then derive matcher correctness and preservation against the executable calculus. Trace equivalence for effectful programs additionally requires specifying the observations and process model.

Reproduction.

In the archive, make runtime installs two pinned runtime packages locally on Debian 13 x86-64. Run make shell for the interactive program, make test for the full suite and make compare for the size table. With the Mercury compiler installed, make build compiles from source. The README gives dependencies and individual example commands.

Authorship.

Anonymous responsible author. AI assistance was used for formulation, drafting, implementation and execution of the tests. The reported measurements were obtained by running the delivered sources.

References

  1. D. Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation 1(4), 497–536, 1991. Author’s report and publication record.

  2. T. Nipkow. Higher-order critical pairs. LICS, 342–349, 1991. Conference record. Full technical report.

  3. J. W. Klop, V. van Oostrom, and F. van Raamsdonk. Combinatory reduction systems: introduction and survey. Theoretical Computer Science 121, 279–308, 1993. CWI full text.

  4. N. G. de Bruijn. Lambda calculus notation with nameless dummies, a tool for automatic formula manipulation, with application to the Church–Rosser theorem. Indagationes Mathematicae (Proceedings) 75(5), 381–392, 1972. Publisher record.

  5. M. Fiore, G. Plotkin, and D. Turi. Abstract syntax and variable binding. LICS, 193–202, 1999. Authors’ publication page.

  6. M. Fiore and O. Mahmoud. Second-order algebraic theories. MFCS, 368–380, 2010. Open manuscript.

  7. T. Hirschowitz. Cartesian closed 2-categories and permutation equivalence in higher-order rewriting. Logical Methods in Computer Science 9(3), article 10, 2013. Journal article.

  8. B. Pientka and J. Dunfield. Beluga: a framework for programming and reasoning with deductive systems. IJCAR, 15–21, 2010. Authors’ publication page.

  9. K. H. Rose. Higher-order rewriting for executable compiler specifications. EPTCS 49, 31–45, 2011. Open manuscript.

  10. G. Nadathur. Teyjus: a λ\lambdaProlog implementation. Association for Logic Programming, 2010. Article. Project.

  11. R. Saillard. Rewriting modulo β\beta in the λΠ\lambda\Pi-calculus modulo. LFMTP, 2015. Open manuscript.

  12. G. Plotkin and J. Power. Algebraic operations and generic effects. Applied Categorical Structures 11, 69–94, 2003. Publication record.

  13. The Mercury Project. Mercury Language Reference Manual, ch. 6. Determinism categories. Compiler and runtime packages.

  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.

Complete flattened LaTeX source
\documentclass[10pt,letterpaper,twocolumn]{article}
\usepackage[margin=0.76in,top=0.78in,bottom=0.77in,headheight=14pt,headsep=13pt,footskip=29pt]{geometry}

\usepackage[T1]{fontenc}

\usepackage{lmodern,textcomp,microtype,amsmath,amssymb,amsthm,booktabs,array,tabularx}

\usepackage{xcolor,listings,fancyhdr,tikz-cd,flushend,needspace}

\usepackage[colorlinks=true,linkcolor=teal!52!black,citecolor=teal!55!black,urlcolor=teal!55!black]{hyperref}

\definecolor{ink}{HTML}{153B42}\definecolor{paperblue}{HTML}{F0F5F5}
\hypersetup{pdftitle={Typed Rewriting Under Binders},pdfauthor={Anonymous author},pdfsubject={Higher-order patterns, categorical semantics, and an executable shell}}
\setlength{\columnsep}{0.27in}\setlength{\parindent}{1em}\setlength{\emergencystretch}{1.1em}
\raggedbottom
\pagestyle{fancy}\fancyhf{}
\fancyhead[L]{\small\sffamily\color{ink}Typed Rewriting Under Binders}
\fancyhead[R]{\small\sffamily\color{ink}Anonymous author}
\fancyfoot[C]{\small\thepage}\renewcommand{\headrulewidth}{0.35pt}
\lstset{basicstyle=\ttfamily\scriptsize,columns=fullflexible,keepspaces=true,showstringspaces=false,upquote=true,
  backgroundcolor=\color{paperblue},frame=single,framerule=0pt,framesep=4pt,
  xleftmargin=4pt,xrightmargin=4pt,aboveskip=7pt,belowskip=7pt,
  breaklines=true,breakatwhitespace=true}
\newtheorem{theorem}{Theorem}[section]\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{proposition}[theorem]{Proposition}
\theoremstyle{definition}\newtheorem{definition}[theorem]{Definition}
\newcommand{\R}{\mathcal R}\newcommand{\Set}{\mathbf{Set}}\newcommand{\Cat}{\mathbf{Cat}}
\newcommand{\den}[1]{[\![#1]\!]}\newcommand{\ctx}{\mathbin{\vdash}}
\newcommand{\code}[1]{\texttt{#1}}\newcommand{\term}[1]{\mathsf{#1}}
\begin{document}
\twocolumn[{
\begin{center}
{\sffamily\bfseries\color{ink}\fontsize{26}{30}\selectfont Typed Rewriting Under Binders\par}
\vspace{5pt}{\large Higher-order patterns, categorical semantics, and an executable shell in Scope\par}
\vspace{7pt}{\normalsize Anonymous author}\par
\end{center}
\begin{center}\begin{minipage}{0.91\textwidth}
\small\noindent\textbf{Abstract.} A rewrite rule can inspect a binding construct and specify exactly which local variables an unknown subterm may use. We introduce this idea through typed query optimization and develop its semantics in a presheaf topos of contexts. A match at a metavariable is a unique factorization through a variable projection. Typed rule instances give directed 2-cells in cartesian closed 2-categorical models. The account distinguishes structural matching, object-level $\beta$-reduction, and the observable order of effects. We implement the language, Scope, in Mercury and write a command shell in Scope itself. Its lexically scoped pipeline definitions use the same contextual substitution as the optimizer. The shell occupies 44 application lines and 93 lines with its two libraries. Independent Python and Go implementations occupy 138 and 244 lines. Executable comparisons, negative matches and finite-model checks accompany the mathematical proofs.
\end{minipage}\end{center}\vspace{9pt}
}]
\thispagestyle{plain}
\section{A predicate inside a join}
Suppose a query joins customers $c$ with orders $o$. Its condition has the form
\[
     P(c)\ \wedge\ \bigl(Q(o)\wedge J(c,o)\bigr).
\]
The customer table can be filtered by $P$ and the order table by $Q$ before the join. An optimizer must recognize this shape even when $P$, $Q$, and $J$ are large expressions. It must also reject the proposed move when the first predicate uses $o$. Matching a node named \emph{conjunction} settles neither question.

In Scope the expression \code{(?L x)} in a pattern denotes an unknown term with one permitted local argument. A match of \code{(?L x)} inside two binders for $x$ and $y$ requires the subject subtree to be independent of $y$. Ambient variables outside the rule instance remain available. The right-hand side \code{(?L u)} instantiates the same term at $u$. These two occurrences account for the dependency test and the change of binder in one rule.
\begin{lstlisting}
(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)))))
\end{lstlisting}
Here \code{fn} introduces a binder whose type is fixed by the surrounding declaration. The \code{?} prefix distinguishes a metavariable of the rule from a variable of the query. If the first conjunct is \code{(same x y)}, the flexible occurrence \code{(?L x)} fails. A subsequent fallback rule returns the original query. The dependency test also applies inside a nested predicate with its own lambda.

There are two dimensions to the example. A higher-order pattern can refer to a term with open parameters. A higher-categorical model also represents the transformations \emph{between} terms. The first notion supplies a programming construct. The second determines which composites of transformations have the same interpretation.

\section{The surface language}
Types are generated by declared base sorts $s$ and arrows $A\to B$. A monomorphic declaration $c:(A_1,\ldots,A_n)\to B$ fixes a symbol's arity and result type. Constructors and user operations have the same application syntax. A program declares its symbols, gives an ordered list of rules for each defined head, and chooses an entry term. Imports are relative to their enclosing source file.
\begin{center}\small
\begin{tabularx}{\columnwidth}{@{}lX@{}}
\toprule
Form & Interpretation\\ \midrule
\code{(data O a (p O O))} & Base sort with a point and a binary constructor.\\
\code{(sig f O O)} & Unary operation from $O$ to $O$.\\
\code{(lam x O t)} & Abstraction over a variable of sort $O$.\\
\code{(fn x t)} & Abstraction checked against an expected arrow.\\
\code{(ap A B f t)} & Apply $f:A\to B$ to $t:A$.\\
\code{(?M x y)} & A dependency list on the left, an instantiation on the right.\\
\code{(= l r)} & An ordered rule with a generated trace label.\\
\code{(rule tag l r)} & A rule with an explicit label.\\
\bottomrule
\end{tabularx}
\end{center}
Strings have type \code{Text}. The notation \code{["use" ?n]} expands to a two-element list of texts. The pattern \code{["echo" | ?rest]} allows an arbitrary tail. A wildcard \code{\_} can occur in any left-hand argument. Its match is discarded.

For example, $\lambda y.\,(\lambda x.y)\,y$ reduces to the identity. A more revealing test applies $\lambda x.\lambda y.x$ to an outer $y$. The result under that outer binder is $\lambda y.\lambda z.y$. Character replacement can change the referent of $y$. Scope translates bound occurrences to de Bruijn indices before matching \cite{debruijn}.

\subsection{Two contexts in a rule}
Write $\Gamma\ctx t:A$ for an ordinary term judgment. A metavariable declaration $M:(A_1,\ldots,A_k)\Rightarrow B$ describes a body of type $B$ with $k$ formal positions. The metavariable context $\Theta$ contains such declarations. At a pattern occurrence, $M$ takes pairwise distinct variables from binders crossed since the rule root. On a right-hand side, $M$ takes arbitrary expressions of the declared types. Profiles must agree across occurrences. A rule head is a user-declared rigid symbol. Every right-hand metavariable must occur on the left.

Scope infers each profile from the expected result type and local argument types at its first left-hand occurrence. The second occurrence can impose an equality test. For example, \code{(p ?M ?M)} matches two structurally equal subtrees. The form \code{(?M x x)} is rejected in a pattern. Equality of two occurrences of a metavariable and repetition of a variable in one occurrence's argument list are different constraints.

\subsection{Equality at match time}
Rigid constructors, application nodes, and text literals compare structurally. Abstractions compare after erasing binder names. Scope implements one-sided, structural matching modulo $\alpha$ on explicitly represented typed terms. Its allowed left-hand spines are the distinct-variable spines of the higher-order pattern fragment \cite{miller,nipkow}. Object-level $\beta$-contraction is a separate executable step. General matching modulo $\beta\eta$ is outside this calculus. For example, an application with a lambda head and its contractum have different rigid shapes at match time. Both shapes can therefore occur in an observable reduction trace.


\section{Contexts as a presheaf topos}\label{sec:factor}
Fix the set of base sorts and a signature. Let $\R$ have finite lists of typed variables as objects. A morphism $\sigma:\Delta\to\Gamma$ assigns to each variable of $\Gamma$ a variable of the same type in $\Delta$. A term at $\Gamma$ can therefore be renamed to a term at $\Delta$. Substitution of these variable assignments defines composition. With this variance convention,
\[
          \widehat{\R}=[\R^{\mathrm{op}},\Set]
\]
is a presheaf topos. For each type $A$, let $T_A(\Gamma)$ be the set of typed $\alpha$-classes of raw terms in $\Gamma$. The action $t\mapsto t[\sigma]$ defines a presheaf $T_A$. The unit and composition equations hold by induction on terms. At an abstraction the induction uses the extended renaming $\sigma^+:\Delta,x:B\to\Gamma,x:B$. This is the context-indexed treatment of binding developed for signatures with substitution by Fiore, Plotkin and Turi \cite{fpt}. Parameterized metavariables also occur explicitly in second-order algebraic theories \cite{fioremahmoud}.

\begin{definition}
An occurrence below local binders $\Lambda$ with spine $\pi=(x_{i_1},\ldots,x_{i_k})$ determines a formal context $\Xi=(z_1:A_{i_1},\ldots,z_k:A_{i_k})$. For each ambient $\Gamma$ its variable projection is the map
\[
 p_\pi:\Gamma,\Lambda\longrightarrow\Gamma,\Xi
\]
with $p_\pi(z_j)=x_{i_j}$ and $p_\pi|_\Gamma=1$.
\end{definition}
A subject subtree $s\in T_B(\Gamma,\Lambda)$ matches $M(\pi)$ precisely when it has a preimage under $T_B(p_\pi)$. For $\Lambda=(x,y)$ and $\pi=(x)$ the term $\term{active}(x)$ has preimage $\term{active}(z_1)$. The term $\term{same}(x,y)$ has no preimage. The term $\term{flag}(a)$ for $a\in\Gamma$ has the constant-in-$z_1$ preimage $\term{flag}(a)$.

\begin{lemma}[Support and unique factorization]\label{lem:support}
The function $T_B(p_\pi)$ is injective. Its image consists exactly of terms whose free occurrences from $\Lambda$ belong to the spine $\pi$.
\end{lemma}
\begin{proof}
Choose distinct formal names fresh for the ambient context. Starting at the root of $s$, copy literals and rigid nodes. Replace each occurrence of a selected local by its formal name in spine order. Retain ambient occurrences and occurrences bound strictly inside $s$, using fresh names under abstractions. An occurrence of an unselected local is the unique source of failure in this traversal. Reapplying $p_\pi$ recovers $s$ modulo $\alpha$. In the opposite direction, the traversal applied to $u[p_\pi]$ recovers $u$, because the selected variables are distinct and disjoint from $\Gamma$. These two identities prove the image description and injectivity.
\end{proof}

\subsection{The square for an open match}
Changing the surrounding context from $\Gamma$ to $\Delta$ by $\sigma$ leaves the local spine fixed. Reindexing and projection commute.
\[
\begin{tikzcd}[column sep=small,row sep=large]
T_B(\Gamma,\Xi) \arrow[r,"T(p_\pi)"] \arrow[d,"{[\sigma+\Xi]}"'] &
T_B(\Gamma,\Lambda) \arrow[d,"{[\sigma+\Lambda]}"] \\
T_B(\Delta,\Xi) \arrow[r,"T(p_\pi)"'] & T_B(\Delta,\Lambda).
\end{tikzcd}
\]
Here $[\sigma+\Xi]$ acts as $\sigma$ on ambient variables and as the identity on locals. The equality around the square follows on variables from the definition of $p_\pi$, and extends to all terms. An existing match is stable under ambient renaming. A noninjective renaming can make two previously distinct subtrees equal and thereby enable a new nonlinear rule.

\begin{theorem}[Structural matching]\label{thm:match}
For a checked pattern and equally typed subject at a fixed ambient context, the matching traversal terminates. It succeeds exactly when there is a valuation for the pattern modulo $\alpha$. On success its values for all named metavariables occurring in the pattern are unique.
\end{theorem}
\begin{proof}
At a rigid node check the symbol and arity and descend pairwise. At a variable or literal check equality. At an abstraction extend the local context by its argument type. At each $M(\pi)$ apply Lemma~\ref{lem:support}. Store the preimage for the first occurrence. Every later occurrence requires equality of the new preimage with the stored body in the same formal context. Necessity follows by inversion of a satisfying valuation. Sufficiency follows by reconstructing the subject at every occurrence. A wildcard can be expanded to a fresh metavariable applied to all surrounding locals and then discarded. Every descent traverses a finite subtree. Comparing stored finite bodies and processing finite spines terminate.
\end{proof}
The theorem concerns a typed subject free of metavariables, which may contain ambient ordinary variables. Unification problems with unknowns on both sides require a different procedure.

\section{Reindexing in executable terms}\label{sec:index}
Number bound occurrences outwards from zero. At a flexible occurrence let $d$ be the number of intervening rule-local binders, $k$ the spine length, and $c$ the number of additional binders crossed \emph{inside the subject subtree}. A subject index $i<c$ remains $i$. For $i=c+j$ the abstraction pass has the following cases.
\[
\begin{array}{ll}
c+\ell & j<d,\ \pi_\ell=j,\quad 0\leq\ell<k,\\
\text{failure} & j<d,\ j\notin\pi,\\
c+k+(j-d)&j\geq d.
\end{array}
\]
The argument slots of a stored body are numbered in written spine order. For example, under $\lambda x.\lambda y$, the local indices for $(x,y)$ are $(1,0)$. The subject $\term{edge}(y,x)$ abstracts to a body with slots $(1,0)$ as arguments of $\term{edge}$. Applying this body to $(a,b)$ yields $\term{edge}(b,a)$.

For instantiation at right-hand local depth $d'$, supply arguments $a_0,\ldots,a_{k-1}$. An index below the current internal depth $c$ again stays fixed. A slot $c+\ell$, $\ell<k$, becomes $a_\ell$ weakened by $c$. An ambient index $c+k+h$ becomes $c+d'+h$. The operation is simultaneous, so an inserted argument cannot undergo substitution by a later argument. In the source, \code{abstract\_var} implements the first pass and \code{fill\_var} the second. Object-level $\beta$ uses the second pass with one actual argument and $d'=0$.

\begin{proposition}[Preservation]\label{prop:preservation}
If a checked rule rewrites $s$ to $t$ in ambient $\Gamma$ and $\Gamma\ctx s:B$, then $\Gamma\ctx t:B$. Object $\beta$-contraction and replacement in a typed one-hole context preserve the same judgment.
\end{proposition}
\begin{proof}
The recovered body for $M$ has its profile result type in $\Gamma,\Xi$, by the typed inverse renaming in Lemma~\ref{lem:support}. Induct on the checked right-hand side. At a metavariable, weaken its body for the local context, then apply the simultaneous substitution lemma to its typed actuals. That lemma follows by induction on the body, extending the substitution under each lambda. The rigid, application and abstraction cases follow their typing rules. The same substitution lemma proves the $\beta$ case. Induction on a typed one-hole context proves its replacement property.
\end{proof}
In \code{hoist.scope}, a conjunct inside an existential depends only on an outer $a$ and moves out. In the second test the corresponding conjunct uses the quantified $x$ and stays inside.
\[
\begin{aligned}
 \exists x\,(N(a,x)\land R(a))&\ \longmapsto\
     (\exists x\,N(a,x))\land R(a),\\
 \exists x\,(N(a,x)\land R(x))&\ \longmapsto\
     \exists x\,(N(a,x)\land R(x)).
\end{aligned}
\]
The second line records the fallback result. The first equivalence holds in ordinary predicate semantics, including an empty domain for $x$. Moving $R(x)$ out in the second line would create an unbound occurrence.

\section{Directed transformations as 2-cells}\label{sec:cells}
Start with a category with chosen finite products and exponentials. Interpret $\Gamma$ by a product and a judgment $\Gamma\ctx t:A$ by an arrow $\den\Gamma\to\den A$. Application uses evaluation and lambda abstraction uses currying. A valuation for $M:(A_1,\ldots,A_k)\Rightarrow B$ is a body in $\Gamma,\Xi$. By currying it gives an arrow
\[
 \den\Gamma\longrightarrow
 [\den{A_1}\times\cdots\times\den{A_k},\den B].
\]
For a nullary metavariable the exponential by the terminal object is canonically isomorphic to $\den B$. Collect these exponential objects in a product $V_\Theta$. A rule with no free ordinary variables at its root determines parallel arrows $\den L,\den R:V_\Theta\to\den B$. Expand each wildcard as in Theorem~\ref{thm:match} before constructing these arrows.

Take a strict 2-category with chosen cartesian closed structure in the Cat-enriched sense. A model of a signature with directed rules assigns to each rule $r$ a specified 2-cell
\[
       \rho_r:\den L\Longrightarrow\den R .
\]
Existence of these cells is a condition on the model. A valuation $v:\den\Gamma\to V_\Theta$ gives an instance by precomposition, or \emph{whiskering}, $\rho_r*v:\den L\,v\Rightarrow\den R\,v$. Vertical composition interprets successive steps. Applying a typed surrounding operation interprets contextual replacement, using product functoriality, evaluation and currying on hom-categories. In the standard example $\Cat$, types are categories, terms are functors, and a rule has a natural transformation as its interpretation.

\begin{proposition}[Interpretation of a pure derivation]
For every such model, each finite path of compatible pure rule steps has a 2-cell between the interpretations of its endpoints, provided interpreted primitive computations respect their specified equations. Paths differing by the exchange of steps in distinct arguments of a rigid operation induce the same 2-cell.
\end{proposition}
\begin{proof}
Use $\rho_r*v$ at a rule root. The substitution lemma for the cartesian closed interpretation identifies its source and target. For a surrounding one-hole context, the structural operation on the appropriate hom-category is functorial. For an empty path take the identity and for concatenated paths take the vertical composite. For two distinct arguments apply the interchange law in the product hom-category, then postcompose with the operation. Object-level $\beta$ has identically interpreted endpoints by the chosen exponential law and maps to an identity cell.
\end{proof}
For example, let an operation $h$ combine two inputs and take steps $\alpha:f\Rightarrow f'$ and $\beta:g\Rightarrow g'$. Before applying $h$, the exchange square is
\[
\begin{tikzcd}[row sep=large,column sep=large]
(f,g) \arrow[r,"{(\alpha,1)}"] \arrow[d,"{(1,\beta)}"'] &
(f',g) \arrow[d,"{(1,\beta)}"]\\
(f,g') \arrow[r,"{(\alpha,1)}"'] & (f',g').
\end{tikzcd}
\]
Its two composites are the pair $(\alpha,\beta)$. A computational step can have a noninvertible interpretation. In $\Cat$, take the category $0\to1$, two functors from the terminal category selecting its two objects, and the transformation given by its unique nonidentity arrow. Replacing that transformation by equality of the selected objects would change the model.

Hirschowitz constructs a free cartesian closed 2-category for a higher-order rewrite presentation and proves soundness and completeness for the corresponding permutation equivalence \cite{hirschowitz}. The proposition above gives the sound interpretation required here. Extensional cartesian closed interpretation identifies $\beta\eta$-equal arrows. Raw runtime syntax distinguishes them, and a trace includes $\beta$ steps. Completeness for the runtime's choice of steps would be a separate claim.

One further dimension has an explicit construction. Quotient paths at a fixed context and type by the congruence generated by disjoint exchange. Their objects and arrows form a category. Its ordinary nerve has terms as vertices, paths as edges, and composable pairs together with their composite as 2-simplices. For pure user rules and $\beta$, the unrestricted relation and disjoint exchange reindex under ambient renamings, so this construction also applies objectwise to obtain simplicial presheaves. Invertibility of reductions and user-specified higher rewrites between derivations require additional structure.



\section{A deterministic implementation}
The front end parses declarations, validates sorts and arities, checks both sides at one result type, and indexes rules by their rigid heads. The matcher is a Mercury \code{semidet} predicate on a ground pattern and a ground subject. The instantiator is deterministic on checked right-hand sides and completed valuations. Mercury's mode and determinism declarations specify allowed argument instantiations and success cardinalities \cite{mercury}. Proposition~\ref{prop:preservation} concerns typing in Scope.

There are two executable orders. \code{norm} contracts the first available root rule or $\beta$ step and otherwise searches children left to right, including lambda bodies. \code{trace} emits these same contractions. \code{eval} first reduces children left to right, treats lambdas as values, and then tries the root. Both choose the first applicable rule at a user-defined head. \code{run} uses the second order up to each I/O request. Only the outer I/O driver executes that request, then supplies the result to its continuation. Effects under an uncalled lambda remain suspended. Stuck I/O and exhausted rewrite fuel produce distinct diagnostics. Arbitrary user rules can loop, overlap or leave terms irreducible.

The difference in order is observable without I/O. Use the ordered rules $f(a)\to b$ and $f(M)\to a$. For the entry $f((\lambda z.z)\,a)$, \code{norm} selects the fallback immediately and returns $a$. Under \code{eval} the argument first contracts to $a$, so the result is $b$. Deterministic execution therefore does not imply confluence.

A related distinction appears under renaming. Give $h$ the rules $h(M,M)\to a$ and $h(M,N)\to b$ in that order. In context $x,y$, the expression $h(x,y)$ selects $b$. After identifying the two variables by a context morphism it selects $a$. Each positive rule instance still reindexes to an instance in the unrestricted relation. The operation of selecting the first applicable rule fails to commute with this renaming.

\section{Programs with open subterms}
\subsection{Fusing a map into a fold}
A sequence expression can contain $\operatorname{map}(f,\operatorname{map}(g,X))$. The \code{fuse} rule returns $\operatorname{map}(\lambda z.f(g(z)),X)$. Here $f,g$ stand for arbitrary bodies under lambda binders. A second rule absorbs a map into a left fold.
\[
\begin{aligned}
 &\mathrm{fold}(H,a,\mathrm{map}(F,X))\\
 &\qquad\longrightarrow
   \mathrm{fold}(\lambda b.\lambda t.H(b,F(t)),a,X).
\end{aligned}
\]
For finite lists under pure total interpretations, induction on $X$ proves equality. At the empty list both sides return $a$. At head $x$ both update the accumulator to $H(a,F(x))$. Apply the induction hypothesis to the tail and that new accumulator. For the entry in \code{fusion.scope}, the strong strategy applies absorption twice. Its output is a single fold of $\lambda b.\lambda t.\operatorname{add}(b,\operatorname{sq}(\operatorname{inc}(t)))$. A separate test exercises the map-to-map rule directly. In a first-order representation of syntax, the corresponding optimizer must account for the accumulator and element positions and substitute a map body below the accumulator binder.

\subsection{Predicate pushdown and converse}
For tables $L,R$ and pure total predicates, membership of a pair $(l,r)$ in the original join is equivalent to
\[
 l\in L\land r\in R\land P(l)\land Q(r)\land J(l,r).
\]
This is exactly the membership test after independent filtering. For ordered lists with duplicates, enumerate left rows then right rows and use stable filtering. Each accepted pair of occurrences keeps its relative position. The support test is necessary for this implementation of pushdown. For example, $P(l,r)=(l=r)$ cannot be evaluated from $l$ alone when $r$ ranges over $\{0,1\}$.

Converse of a binary relation exchanges its arguments. The executable pattern in \code{transpose.scope} lists its variables in the opposite order to their binding.
\begin{lstlisting}
(rule flip
  (converse (relation (lam x Row (lam y Row
    (?P y x)))))
  (relation (lam a Row (lam b Row (?P a b)))))
\end{lstlisting}
The input body \code{(edge x y)} yields \code{(edge v1 v0)} under output binders \code{v0,v1}. With \code{(?P x y)} in the pattern, the same right-hand side would preserve argument order. Reading off the two spines suffices to derive both results.

\section{An executable shell written in Scope}
The shell and both its imports consist of Scope declarations and rules. \code{commandline.scope} parses text into argument vectors and a pipeline tree. \code{plans.scope} gives a pure effect syntax and its handlers. The application supplies command meaning, lexical environments, error recovery and the read loop. Built-ins include \code{echo}, ASCII \code{upper} and \code{lower}, \code{cd}, \code{quit}, \code{def}, \code{use} and \code{twice}. Other names invoke executables on the process search path. The host receives an argument vector through POSIX \code{posix\_spawnp}.

\subsection{From characters to commands}
A quoted word containing \code{|} and an unquoted pipeline separator have distinct constructors. Quotes can occur inside a word, empty quotes form an empty argument, and adjacent quoted fragments concatenate. Single quotes preserve every interior character. Outside single quotes a backslash escapes the following character. Space and tab delimit unquoted words. The parser rejects an empty pipeline stage and propagates lexical errors before executing the line.
\begin{lstlisting}
(= (quoted ?q [?q | ?r] ?a) (token ?r ?a))
(= (parse (bar _) [])
   (invalid "empty pipeline stage"))
\end{lstlisting}
The repeated metavariable in the first rule requires the closing character to equal the opening delimiter. That rule has priority over the ordinary-character case. A successful parse produces either a final argument vector or one vector followed by another pipeline.

\subsection{A plan and its continuation}
With $S$ the set of texts, $W$ argument vectors and $E$ diagnostic texts, the well-founded effect trees with result set $X$ form the free tree construction
\[
         P X=\mu Y.\bigl(X+E+(W\times S)\times Y^S\bigr).
\]
A leaf returns a value or an error. A request contains arguments, input text, and a continuation branch for each successful output. Scope specializes the result type to \code{Text} and represents definable continuations by lambda syntax. The construction uses operations and their interpretations in the sense of algebraic effects \cite{plotkin}. Recursive user rules extend beyond the well-founded fragment.

Sequential composition grafts a continuation at the successful leaves.
\begin{lstlisting}
(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))))
\end{lstlisting}
In the third rule $y$ is fresh, and any free variables of the incoming continuation \code{?h} remain free after insertion. For well-founded trees, left and right unit and associativity of grafting follow by induction. For associativity at a request the two sides have identical labels and have equal branches by the induction hypothesis at each $s\in S$. At a failed leaf both sides return the same diagnostic. These are equalities of trees up to pointwise equality of continuations. Observing a tree against a process environment records a particular sequence of requests. Exchanging two external commands can change that sequence and its result.

\subsection{Lexical pipeline definitions}
A binding stores a pipeline as a function from input text to a plan. The captured environment is the one in force at definition time. A lookup hit uses one rule.
\begin{lstlisting}
(rule expand
  (lookup ?n (binding ?n (fn x (?Body x)) _) ?s)
  (?Body ?s))
\end{lstlisting}
The repeated \code{?n} enforces name equality. The metavariable \code{?Body} captures an open program below the input binder. Its right-hand occurrence substitutes the current input and preserves all other bindings. \code{twice} composes two calls of a stage, passing the output of the first as input of the second.

\Needspace{10\baselineskip}
In this session, lines prefixed by \code{>} are commands.
\begin{lstlisting}
> 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
\end{lstlisting}
Dynamic lookup of \code{tag} during \code{use saved} would produce \code{new:row}. An error short-circuits the remaining pipeline, prints a diagnostic, and returns to the read loop. Child stderr remains attached to the caller. Each stage buffers its entire stdout in a seekable temporary file and accepts at most 4 MiB of successful output as UTF-8 text without NUL. The resulting shell supports finite text transformations. Concurrent streaming, background jobs, redirection syntax and POSIX shell compatibility are outside its command language.



\section{Evidence and source size}
We compiled five Mercury modules with Mercury 22.01.8 in grade \code{hlc.gc} on x86-64 Linux. The archive includes a native executable, source build instructions, a checksum-pinned runtime installer, two independent reference shells and a test runner. One set of fixtures exercises identical commands, stdout, stderr and exit status for Scope, Python 3.12.14 and Go 1.27.4. Each implementation also runs a session on a pseudoterminal with a prompt, a pipeline and an explicit exit.

\begin{center}\small
\begin{tabular}{@{}lrrr@{}}
\toprule
Source & Lines & Nonspace & Bytes\\ \midrule
Scope application & 44 & 1,756 & 2,218\\
Scope imports & 49 & 1,811 & 2,487\\
\textbf{Scope total} & \textbf{93} & \textbf{3,567} & \textbf{4,705}\\
Python shell & 138 & 2,926 & 4,740\\
Go shell & 244 & 4,288 & 5,640\\ \bottomrule
\end{tabular}
\end{center}
Lines are physical source lines excluding blanks, shebangs and full-line comments, including declarations and brace-only lines. Nonspace counts non-whitespace characters on those lines. Bytes are complete UTF-8 files. The complete shell is 32.6\% shorter by lines than the Python implementation and 61.9\% shorter than the Go implementation. Python uses fewer non-whitespace characters. Python uses structural pattern matching and dictionary snapshots. Go uses argument slices and environment snapshots. Both use standard subprocess and file libraries. The Scope total includes both user-space libraries. Language implementations and standard libraries are excluded on every side. The separately reported implementation cost is 544 Mercury lines plus 68 lines in the POSIX C header. The Mercury count includes the foreign declarations. These measurements describe the supplied programs. They establish neither a minimum implementation size nor a speed advantage.

\begin{center}\small
\begin{tabularx}{\columnwidth}{@{}Xr@{}}
\toprule
Executed check & Count\\ \midrule
Scoped subject/spine instances & 1,220\\
\quad Accepted / rejected by support & 872 / 348\\
Two-row interpretations of query pushdown & 4,096\\
Finite inputs for fold absorption & 121\\
Batch / terminal sessions per shell & 52 / 1\\
\bottomrule
\end{tabularx}
\end{center}

The binder matrix enumerates local depths zero through three, every ordered subset of those local variables, and a fixed family of subject trees containing constants, ambient variables, pairs and nested abstractions. An independent named-variable oracle computes the allowed free-variable set and simultaneously replaces the selected variables by distinct constants. The executable must produce the oracle result or a fallback marker. Other fixtures check repeated metavariables under reordered and differently nested binders, capture during $\beta$-contraction, malformed spines, type errors, fuel exhaustion and include cycles.

For the query example, the test runner reads the input and the optimizer's emitted normal form. It interprets both on every pair of subsets of a two-row universe, every pair of unary predicates, and every binary predicate. The count is $4^2\cdot 4^2\cdot16=4096$. The fold test enumerates the $1+3+9+27+81=121$ lists of length at most four over three elements. Both checks compare denotations. Shell sessions cover quoting, empty arguments, lexical shadowing, repeated external stages, persistent changes of directory, exit status, invalid UTF-8, size limits, errors and EOF. A separate test launches the shell file directly. Finite agreement supports the implementation claims. The general statements in Sections~\ref{sec:factor} and~\ref{sec:cells} depend on their mathematical hypotheses and proofs.

\section{Prior work and scope}
Miller's $L_\lambda$ isolates a decidable class of higher-order unification problems with most general unifiers \cite{miller}. Nipkow uses restricted left-hand sides over simply typed lambda terms and develops higher-order critical pairs \cite{nipkow}. Klop, van Oostrom and van Raamsdonk survey combinatory reduction systems with binders and metavariables, including orthogonal systems \cite{klop}. Rose used CRSX to specify parsing, optimization and code emission for a query language \cite{rose}. The Teyjus implementation of $\lambda$Prolog uses pattern unification in a logic-programming abstract machine \cite{teyjus}. Scope uses one-sided matching, structural equality and ordered rules. For confluence and critical-pair arguments the matching equality, the rule class and the treatment of overlap must be fixed separately.

The presheaf presentation draws on Fiore, Plotkin and Turi's binding algebras and Fiore and Mahmoud's second-order algebraic theories \cite{fpt,fioremahmoud}. Hirschowitz gives the directly relevant 2-categorical permutation semantics \cite{hirschowitz}. Beluga provides contextual objects, higher-order abstract syntax and dependent programming for deductive systems \cite{beluga}. Saillard's account of rewriting modulo $\beta$ in the $\lambda\Pi$-calculus modulo treats a different equality and its interaction with dependent types \cite{saillard}. The journal's Caprice study treats ordered byte-string matching with captured text, backreferences and specialization \cite{caprice}. Scope's metavariable arguments refer to bound variables in terms.

The contribution here is the connection from a typed projection to executable contextual matching, tested transformations and a complete application in the object language. A subsequent Lean mechanization can establish the inverse laws for the two index traversals, then derive matcher correctness and preservation against the executable calculus. Trace equivalence for effectful programs additionally requires specifying the observations and process model.

\paragraph{Reproduction.} In the archive, \code{make runtime} installs two pinned runtime packages locally on Debian 13 x86-64. Run \code{make shell} for the interactive program, \code{make test} for the full suite and \code{make compare} for the size table. With the Mercury compiler installed, \code{make build} compiles from source. The README gives dependencies and individual example commands.

\paragraph{Authorship.} Anonymous responsible author. AI assistance was used for formulation, drafting, implementation and execution of the tests. The reported measurements were obtained by running the delivered sources.

\begin{thebibliography}{12}\small
\bibitem{miller} D. Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. \emph{Journal of Logic and Computation} 1(4), 497--536, 1991. \href{https://www.lfcs.inf.ed.ac.uk/reports/91/ECS-LFCS-91-159/}{Author's report and publication record}.
\bibitem{nipkow} T. Nipkow. Higher-order critical pairs. \emph{LICS}, 342--349, 1991. \href{https://lics.siglog.org/1991/Nipkow-Higherordercritical.html}{Conference record}. \href{https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-218.html}{Full technical report}.
\bibitem{klop} J. W. Klop, V. van Oostrom, and F. van Raamsdonk. Combinatory reduction systems: introduction and survey. \emph{Theoretical Computer Science} 121, 279--308, 1993. \href{https://ir.cwi.nl/pub/1501/1501D.pdf}{CWI full text}.
\bibitem{debruijn} N. G. de Bruijn. Lambda calculus notation with nameless dummies, a tool for automatic formula manipulation, with application to the Church--Rosser theorem. \emph{Indagationes Mathematicae (Proceedings)} 75(5), 381--392, 1972. \href{https://doi.org/10.1016/1385-7258(72)90034-0}{Publisher record}.
\bibitem{fpt} M. Fiore, G. Plotkin, and D. Turi. Abstract syntax and variable binding. \emph{LICS}, 193--202, 1999. \href{https://www.dcs.ed.ac.uk/home/dt/abstractsyn.html}{Authors' publication page}.
\bibitem{fioremahmoud} M. Fiore and O. Mahmoud. Second-order algebraic theories. \emph{MFCS}, 368--380, 2010. \href{https://arxiv.org/abs/1308.5409}{Open manuscript}.
\bibitem{hirschowitz} T. Hirschowitz. Cartesian closed 2-categories and permutation equivalence in higher-order rewriting. \emph{Logical Methods in Computer Science} 9(3), article 10, 2013. \href{https://lmcs.episciences.org/1132}{Journal article}.
\bibitem{beluga} B. Pientka and J. Dunfield. Beluga: a framework for programming and reasoning with deductive systems. \emph{IJCAR}, 15--21, 2010. \href{https://research.cs.queensu.ca/home/jana/papers/beluga-system/}{Authors' publication page}.
\bibitem{rose} K. H. Rose. Higher-order rewriting for executable compiler specifications. \emph{EPTCS} 49, 31--45, 2011. \href{https://arxiv.org/abs/1102.3732}{Open manuscript}.
\bibitem{teyjus} G. Nadathur. Teyjus: a $\lambda$Prolog implementation. \emph{Association for Logic Programming}, 2010. \href{https://logicprogramming.org/2010/03/teyjus-a-lprolog-implementation/}{Article}. \href{https://teyjus.cs.umn.edu/}{Project}.
\bibitem{saillard} R. Saillard. Rewriting modulo $\beta$ in the $\lambda\Pi$-calculus modulo. \emph{LFMTP}, 2015. \href{https://arxiv.org/abs/1507.08055}{Open manuscript}.
\bibitem{plotkin} G. Plotkin and J. Power. Algebraic operations and generic effects. \emph{Applied Categorical Structures} 11, 69--94, 2003. \href{https://researchportal.bath.ac.uk/en/publications/algebraic-operations-and-generic-effects/}{Publication record}.
\bibitem{mercury} The Mercury Project. \emph{Mercury Language Reference Manual}, ch.~6. \href{https://mercurylang.org/information/doc-release/mercury_ref/Determinism-categories.html}{Determinism categories}. \href{https://dl.mercurylang.org/deb/}{Compiler and runtime packages}.
\bibitem{caprice} Anonymous author. Caprice: Higher-Categorical Semantics of Capture-Aware Partial Evaluation and JIT Matching. \emph{Higher Categorical Semantics}, 25 October 2026. Editorially reviewed. \href{https://higher-categorical-semantics.pages.dev/research/caprice-higher-categorical-semantics-of-capture-aware-partial-evaluation-and-jit-matching-1b0789bf}{Journal article}.
\end{thebibliography}


\end{document}

End of manuscript · Back to top ↑