The module calculus¶
QVR programs are assembled from modules: files, modules declared inside modules, signatures, functors and their applications, sealed modules, package holes and the modules linked into them, and the packages a build selects. This chapter states what that assembly means as a whole. Its central claim is that the module layer is a calculus that is interpreted away: every module expression is evaluated, before any code is generated, to a module identity, and every name to a declaration of one flat program. The checked core, the reference machine, and every transpile target thus see no modules at all, and the module layer adds no term to the Quivers Indexed Effect Core (QIEC).
The chapter gives the overall construction and the invariants that hold across its parts. The pages it links state each part precisely:
| Part | Page |
|---|---|
| files, imports, scopes, and the flat program | Modules and static interpretation |
| signatures, functors, sealing, sharing, module parameters | Signatures, functors, and their static interpretation |
| package holes, linking, sample sites across instances | Linking and sites |
| builds, lockfiles, interfaces, dependency lenses | Packages and dependency lenses |
| content hashes of declarations and structures | Content identity |
| theories composed by colimit | Theories, views, and models |
| deductions composed from signatures and lexicon modules | Composable deductions and rule schemata |
1. The pipeline¶
Loading a root module runs five stages. The first three belong to the module layer; the last two are the compiler every program goes through, with or without modules.
flowchart TB
F["Source files<br/><small>a root and every module it imports</small>"] -->|"load and resolve"| G["Module graph<br/><small>acyclic; each module checked against its imports' interfaces</small>"]
G -->|"evaluate module expressions"| E["Module values and identities<br/><small>signatures, applications, sealings, linked holes</small>"]
E -->|"realize every name"| C["Checking program<br/><small>skolems for abstract items, witnesses for matches</small>"]
E -->|"realize every name"| R["Run-time program<br/><small>every item realized by its declaration</small>"]
C -->|"compile and check"| K["Checked core of the checking program"]
R -->|"compile"| Q["QIEC module"]
Q --> M["Reference machine"]
Q --> T["Transpile targets"]
class F qv-input
class G,E,C,R,K,Q qv-checked
class M,T qv-output
- Loading.
loadandloadsfollow imports from the root, refuse an import cycle with its path, and check each module against the interfaces of the modules it imports, never their bodies (modules §scopes). - Evaluation. Every module expression (a path, an application
F(A, B), a sealingM :> S, a hole) is evaluated to a module value: an identity, an interface, and, for a functor, its parameters. Matching a module against a signature computes a realization of the signature's items by the module's declarations (§3). - Realization. Every name is realized as a declaration of a flat program, in two ways at once: as a skolem where only a signature describes the item, and as the realizing declaration where the program runs. This yields the checking program and the run-time program (§3).
- Checking.
check_module_languagecompiles the checking program, which checks every functor body once at its parameters' signatures, client code against sealed signatures alone, and every match through generated code.check_signature_lawsthen checks each module matched against a signature with laws as a model of those laws. - Compilation. The run-time program, assembled by
interpretinto oneFlatProgram, is compiled to QIEC like any single-file program. ItsSourceMapmaps each line back to its module's file, so diagnostics name the file and line the author wrote.
The checking program exists only when the graph uses signatures, functors, sealing, holes, or module parameters. A graph of plain files and imports has one program, and its static interpretation is an alpha-renaming of the modules into one namespace (modules §static interpretation).
2. Identities¶
A module identity says which module a name belongs to. Its grammar,
has one form per way a module comes to exist: a source module at path \(p\), the package hole \(?p\),
a module \(x\) declared in \(\iota\), the parameter \(x\) of the functor \(\iota\), an applicative
application, a generative application at the binding site \(s\), and a sealing at the site \(s\)
(functors §module identities). Every declaration of the program is a
symbol \((\iota, x)\), and its flat name is a function of the symbol alone. The rendering
module_display is injective, so distinct symbols have
distinct flat names, and no generated name can equal an authored one.
The identity is the unit of sharing. Two references to one identity are one module, so a module reached along two import paths, an applicative functor applied twice to the same arguments, and a module needing the same holes under the same fillings each contribute their declarations once. Two distinct identities are two modules, however alike their bodies, so two generative applications of one functor have distinct declarations, parameters, and abstract families.
3. Elaboration with existentials¶
Following F-ing modules (Rossberg et al., 2014), a signature \(S\) with abstract families
\(\overline{\alpha}\) and remaining items \(\Sigma\) denotes the existential type
\(\exists \overline{\alpha}.\, \Sigma[\overline{\alpha}]\), a manifest family or a sharing
constraint with family T = τ substitutes \(\tau\) for \(T\) instead of quantifying it
(Leroy, 1994), and a functor denotes a function from its parameters' existentials to its
body's.
QIEC has no existential types. It needs none, because QVR's modules are second class: a module is never a run-time value, so every existential is opened at a place the elaborator knows, and each opening is eliminated in one of two ways.
- Kept abstract, to check. In the checking program each abstract family of a functor parameter, a hole, or a sealed module is a fresh family with a single constructor that no source can name, and each computation item is a postulate with its specified type and effect row. QIEC's families are nominal, so a fresh family is equal to itself and to nothing else: it is an exact stand-in for a quantified type variable. Code checked against these skolems is checked against the signature alone.
- Instantiated, to run. In the run-time program every item is realized by the declaration that the argument, the filler, or the sealed module provides, so no skolem and no postulate is ever compiled for use.
Ascription is a coercion, and the coercion is code. A module \(M\) matches \(S\) when each abstract family of \(S\) is realized by a family of \(M\), every manifest item and sharing constraint holds, and each computation item \(f\) of type \(\forall \overline{\beta}.\, \overline{A} \to B \,!\{\varepsilon\}\) is witnessed by a generated computation
which the QIEC checker checks with the rest of the checking program. The witness checks exactly
when \(M.f\) can be called at the specified type with no effect outside \(\varepsilon\), so the
kernel's own subtyping of calls decides the match, and a failed match is reported against the
item it concerns (signature-mismatch). A signature that states a deduction by its header is
matched by the header alone, and a signature's equations block adds a law obligation: once the
run-time program is compiled, the matching module is checked as a finite model of the laws at
every assignment of its families' values, or the obligation is recorded as assumed when a family
is not finite (theories §models).
The two programs differ only in the skolems, the postulates, the witnesses, and the single instance of each functor body that the checking program holds at its own parameters. The soundness argument, that checking the first licenses running the second, is given in functors §soundness: instantiation preserves typing, every realization the run-time program uses has been matched, and client code of a sealed module is well typed for every realization of the sealed signature.
4. Applicative and generative application¶
Whether two applications of one functor to the same arguments are the same module is read off the functor body's effects, in the spirit of treating generativity as an effect (Dreyer et al., 2003). Instantiating a body allocates when one of its declarations
- is a computation whose effect row holds an instance of
Random(it names sample sites) or ofParam(it reads learned parameters), - is a program (it performs through the built-in
randominstance), or - owns learned parameters: a morphism that is neither
observednorlet, a deduction with learnable rule weights or latent lexical categories, an encoder, or a decoder.
| Applicative functor | Generative functor | |
|---|---|---|
| Body | allocates nothing | allocates sample sites or learned parameters |
Identity of F(A) |
\(F(\iota_A)\), the same wherever written | \(F(\iota_A)\#s\), one per binding site \(s\) |
| Families of two applications | equal | distinct, unless sharing is declared |
| Parameters and sites | none to keep apart | distinct, addressed through the identity |
| F-ing reading | pure functor, \(\forall \ldots \exists \overline{\alpha}\) hoisted | impure functor, \(\forall \ldots \exists \overline{\alpha}\) per application |
The rule is syntactic and conservative: a functor whose body declares a Random effect it never
performs is generative all the same, since the effect row is the body's declared interface. The
cost of the conservative reading is only that two such applications have distinct families. A
generative application's sites and parameters stay distinct by name and by
site identity, and share x with y ties two of them
back together, checked for one family, one plate, and one support (linking §sharing).
A computation with module parameters, define f(module R : S, ...), is a functor whose body is a
single declaration, applied at each call. Its specialization is named by the call's module
arguments, and a specialization that would recur at ever larger module arguments is refused
(module-recursion), so specialization terminates. An implicit parameter {module M : S} is
filled by the unique implicit module, or implicit functor application, in scope at the call that
solves \(S\) and its constraints. Resolution is coherent (two solutions are refused, never chosen
between) and tabled (a goal met again while it is being solved has no solution along that path),
which turns modular implicits into modular explicits before checking [@white2015modular;
@selsam2020tabled].
5. Sealing¶
Transparent ascription M : S keeps \(M\)'s identity and exports only the items of \(S\), so the
realization of \(S\)'s abstract families stays visible to clients (Leroy, 1995). Sealing
M :> S is the coercion followed by packing: the result is the new identity \((\iota_M :> S)\#s\),
whose abstract families are, in the checking program, skolems. A client of a sealed module is thus
checked against \(S\) alone, and code that uses a sealed family as the type its realization happens
to be is refused (module-abstraction).
This is the property that sealing buys. Since the client is well typed at every realization of \(S\), replacing the sealed module by another module that matches \(S\) cannot make the client ill-typed, and by parametricity for modules (Crary, 2017; Sterling and Harper, 2021) a client cannot distinguish two implementations related at \(S\). The run-time program still names the sealed module's own declarations, so sealing costs nothing at run time: it constrains what is checked, not what is compiled.
6. Static interpretation¶
The run-time program is assembled by visiting the module identities in dependency order and emitting each identity's declarations once, under flat names, with every resolved token replaced by the flat name of its symbol. Imports, opens, signatures, functors, and the exports of every module but the root disappear. Each kind of module expression leaves a fixed trace:
| Expression | Trace in the flat program |
|---|---|
import and open |
none: names are already resolved to symbols |
| a module declared in a module | its declarations, under the nested identity |
F(A, B) |
the body of F, walked once per identity with its parameters substituted |
M : S, M :> S |
none at run time; skolems and witnesses in the checking program |
a hole ?h linked to f |
each module needing h, applied to its fillings, once per distinct filling |
define f(module R : S, ...) |
one specialization of f per tuple of module arguments |
a module reached only by meta import |
its meta-phase declarations; nothing reaches run time |
This is the static interpretation of higher-order modules that Futhark performs before compilation (Elsman et al., 2018), with two consequences that shape the rest of quivers. The checked core needs no module construct, since every module has been interpreted before QIEC is built. And every consumer of QIEC (the compiled runtime, the reference machine, each transpile target) agrees on what a modular program means, because each sees the same flat program.
The price is specialization. A functor applied at \(n\) distinct argument tuples is compiled \(n\) times, and generic code cannot be compiled once and linked against separately compiled arguments. The compiled code stays first order, which every target needs, and the incremental build keeps the cost of repeated specialization down by keying each module's elaboration on its imports' interfaces.
7. Composition by colimit, identity by origin¶
Every way QVR combines parts follows one principle. Each element of a part (a declaration, an atom, a rule, a sort, a law, a module instance) has an origin: the declaration or the application that introduced it. Parts combine by a colimit of the inclusions between them, in which two elements are identified exactly when they have one origin, never because their names coincide (Burstall and Goguen, 1977). A part reached along two paths is thereby contributed once, and two distinct elements under one name are refused with both sources named, never merged and never silently renamed.
| Composition | Elements | Origin | Two origins under one name |
|---|---|---|---|
| imports and re-exports | declarations | the symbol \((\iota, x)\) | an unqualified use is refused as ambiguous; one exported name for two symbols is refused (export-clash) |
deduction G extends S, T with lexicon L |
atoms, binders, rules, lexical entries | the deduction signature, lexicon module, or deduction that introduces it | refused, naming both declarations (composable deductions §2) |
include, A + B over C, instantiation of a generic theory |
sorts, operations, laws | the theory declaration or theory expression | refused by panproto's colimit, naming both sources (theories §composition) |
| linking holes | module instances | the module applied to its fillings | none: equal identities are one instance (linking) |
| package builds | packages | the package, at the version minimal version selection picks | two pinned sources for one package are refused (packages §builds) |
The principle explains several behaviors that might otherwise look arbitrary. A diamond of imports, of signature extensions, of theory inclusions, or of package dependencies is never a conflict, since the shared part has one origin. A rename of a declaration changes no composition, since nothing is identified by spelling. And a composite always means its parts: a composed deduction runs exactly as the monolithic deduction with the same atoms, rules, and entries, and a composed theory has exactly the laws of its parts.
8. Identity of instances and identity of content¶
The module calculus distinguishes two notions of identity, which answer different questions.
- A module identity answers which instance: two generative applications of one functor are two instances even when their bodies are equal, so their parameters and sites are kept apart.
- A content hash answers what it means: a declaration's content hash is invariant under renaming, reordering, and layout, so a refactor that splits a file into modules leaves every hash unchanged.
The two meet in site identities, which combine the declaring declaration's content hash with its ordinal among declarations of that hash: renaming a module, a declaration, or a site keeps every stored run readable, while the two instances of a generative functor stay apart. Packages pin each module by both, its core digest and its interface digest, so a lockfile fails exactly when a meaning or a public name changes (packages §pins).
9. Guarantees and limits¶
The module layer makes four guarantees.
- Checked once. A functor body, a computation with module parameters, and a package with holes are each checked once, against signatures alone, whether or not they are ever applied or linked.
- Checked generic code runs. If the checking program compiles, the run-time program compiles and means the generic code applied to the arguments it names.
- Abstraction. Client code of a sealed module, a functor parameter, or a hole cannot depend on a realization the signature hides.
- No name-based merging. No two declarations, atoms, rules, sorts, or laws are identified unless they have one origin.
The limits follow from the design. Modules are second class, so a program cannot choose a module at run time; a choice among implementations is a choice among values of a module's types or a link made before loading. Recursion between modules is admitted only through links whose declarations are well founded (linking §recursive links). Generativity is decided by declared effects, which may treat a functor as generative that allocates nothing in practice. And signature laws are decided only on finite carriers; over an infinite family they are recorded as assumed, never as checked.
Cited sources¶
Andreas Rossberg, Claudio V. Russo, and Derek Dreyer. F-ing Modules. Journal of Functional Programming, 24(5):529–607, 2014. doi:10.1017/S0956796814000264.
Xavier Leroy. Manifest Types, Modules, and Separate Compilation. In Proceedings of the 21st ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 109–122. 1994. doi:10.1145/174675.176926.
Derek Dreyer, Karl Crary, and Robert Harper. A Type System for Higher-Order Modules. In Proceedings of the 30th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 236–249. 2003. doi:10.1145/604131.604151.
Xavier Leroy. Applicative Functors and Fully Transparent Higher-Order Modules. In Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 142–153. 1995. doi:10.1145/199448.199476.
Karl Crary. Modules, Abstraction, and Parametric Polymorphism. In Proceedings of the 44th ACM SIGPLAN Symposium on Principles of Programming Languages, 100–113. 2017. doi:10.1145/3009837.3009892.
Jonathan Sterling and Robert Harper. Logical Relations as Types: Proof-Relevant Parametricity for Program Modules. Journal of the ACM, 68(6):41:1–41:47, 2021. doi:10.1145/3474834.
Martin Elsman, Troels Henriksen, Danil Annenkov, and Cosmin E. Oancea. Static Interpretation of Higher-Order Modules in Futhark: Functional GPU Programming in the Large. Proceedings of the ACM on Programming Languages, 2(ICFP):97:1–97:30, 2018. doi:10.1145/3236792.
Rod M. Burstall and Joseph A. Goguen. Putting Theories Together to Make Specifications. In Proceedings of the 5th International Joint Conference on Artificial Intelligence (IJCAI). 1977. URL: https://www.ijcai.org/proceedings/1977/0234.pdf.