Notes on redesign of the Swarm type system [000U]
- November 2, 2025
These notes are currently under construction, but I've made them public on purpose since it forces me to think things through more carefully. Comments welcome!
Motivation [000T]
- November 2, 2025
Currently, Swarm has a relatively standard Hindley-Milner type system, with an extra requirements analysis bolted on top. The goal of the requirements analysis is to decide what capabilities (and hence what devices) are required to execute some code, and to facilitate automatically installing necessary devices on newly built robots.
However, the bolted-on requirements analysis is fundamentally broken, and has led to a number of bugs. For example, see the following issues:
- Umbrella issue
- Wrong requirements for `let`-bound variables
- Wrong requirements context to `build`
- Using recursive functions doesn't require proper capabilities
- Making `dictionary` devices more meaningful
- Automatic equipment requirement checks don't work when using functions from a nested import
Fundamentally, the problem is that a proper requirements analysis must be done statically (requirements analysis for programs passed to the build command are currently done dynamically, at runtime, leading to a number of bugs), and can't be separated from type analysis (e.g. to be able to deal properly with requirements of higher-order functions).
The goal of this work is to design a unified type-and-requirements system that handles things properly, using the lessons learned over the past few years of struggling with the current implementation.
Capabilities, entities, and devices [000X]
- November 3, 2025
Definition Entities [001C]
- November 13, 2025
We assume a globally fixed set of entities \mathbf {E}. Entities represent types of objects in the game, and can be either naturally occurring (such as trees and rocks) or manufactured (such as branch predictors).
Definition Capabilities [001D]
- November 13, 2025
We also assume a globally fixed set of capabilities \mathbf {C}. A capability represents the ability of a robot to do a particular thing: for example, to add, to move, make use of recursive functions, etc. For each built-in command c there is a capability \mathsf {Exc}(c) which represents the capability to use command c, but there are other capabilities as well.
Definition Devices [001E]
- November 13, 2025
Some entities provide one or more capabilities when they are equipped; such entities are known as devices. For example, a branch predictor device provides the \mathsf {Exc}(\mathsf {if}) capability, which allows robots to evaluate conditional expressions.
Devices \to capabilities [001F]
- November 13, 2025
We assume a fixed function \mathsf {caps} : \mathbf {E} \to \mathcal {P}(\mathbf {C}) which maps each entity to the set (possibly empty) of capabilities it provides. In a standard abuse of notation, if D \subseteq \mathbf {E} is a set of entities, we write \mathsf {caps}(D) to denote the image of D under \mathsf {caps}, that is, \mathsf {caps}(D) = \bigcup _{d \in D} \mathsf {caps}(d).
Capabilities \to devices oracle [001G]
- November 13, 2025
Of course we can invert the \mathsf {caps} function to yield a function \mathsf {caps}^{-1} : \mathbf {C} \to \mathcal {P}(\mathbf {E}) which maps a capability to the set of entities which provide it. More interesting, however, is that we also assume the existence of a provisioning oracle \mathsf {provision} : \mathcal {P}(\mathbf {C}) \times \mathcal {P}(\mathbf {E}) \to \mathcal {P}(\mathbf {E}) which calculates a set of devices which together provides (at least) the given set of capabilities, and is a superset of the given set of entities. That is, it must be the case that for any capability set \Delta and any set of devices D, D \subseteq \mathsf {provision}(\Delta , D) and \Delta \subseteq \mathsf {caps}(\mathsf {provision}(\Delta , D)). Simply defining \mathsf {provision}(\Delta , D) = D \cup \bigcup _{c \in \Delta } \mathsf {caps}^{-1}(c) would fit the bill, but would be unsatisfying, since its output would typically contain many redundant devices. Ideally we want some sort of "minimal" device set for a given set of capabilities. Solving this exactly is NP-hard, but there are various heuristics that can give approximate solutions. The precise algorithm used by the provisioning oracle does not matter for our purposes here; we simply assume that it exists and has the required properties.
Robots [0014]
- November 4, 2025
Each robot has:
In order to confer capabilities, a device must be equipped, that is, moved from the robot's general inventory to the special set of equipped devices. Entities can be moved between the inventory and equipped set via the \mathsf {equip} and \mathsf {unequip} commands.Set and bag expressions [001Y]
- November 20, 2025
Since types can be polymorphic in capabilities and entities, it's not enough to just keep track of e.g. literal capability sets; we need to keep track of variables that can stand for unknown collections, with the ability to combine them with other collections.
Collection expressions [00GY]
- June 12, 2026
A collection expression is one of:
- the empty collection \varnothing ,
- a collection variable \delta (in general, different metavariables are used for different types of collections),
- a singleton collection, denoted \{e\}, or
- the union of two collection expressions, \Delta _1 \cup \Delta _2,
but quotiented by the assumption that \varnothing is the identity for \cup , and \cup is associative, commutative and idempotent. For example, (\varnothing \cup \delta ) \cup (\{\mathsf {Lambda}\} \cup \delta ) = \delta \cup \{\mathsf {Lambda}\}. We also write set literals like \{\mathsf {Exc}(\mathsf {if}), \mathsf {Lambda}\} as an abbreviation for \{\mathsf {Exc}(\mathsf {if})\} \cup \{\mathsf {Lambda}\}.
Swarm polytypes [001N]
- November 14, 2025
Most generally, a Swarm polytype is of the form \forall \overline {\alpha }; \overline {\delta }.\; \Delta \Rightarrow \tau where \overline {\alpha } is a sequence of type variables, \overline {\delta } is a sequence of capability set variables, \Delta is a capability set expression, and \tau is a monotype. Such a type is ascribed to expressions which, under any substitutions [\overline {\alpha } \mapsto \overline {\tau }] and [\overline {\delta } \mapsto \overline {\Delta }], can be evaluated by a robot with capabilities \Delta , producing either a value of type \tau or \bot (due to either an exception or nontermination).
Note that in the case that there are no capability set variables \delta , we often omit them from the syntax, writing simply \forall \overline {\alpha }.\; \Delta \Rightarrow \tau as an abbreviation for \forall \overline {\alpha }; \varnothing .\; \Delta \Rightarrow \tau . Moreover, we also omit writing \Delta \Rightarrow in the case when \Delta is \varnothing , and omit writing \forall when there are no variables being quantified over.
XXX need variables for capsets, devsets, inventory?
Swarm typing judgments [000V]
- November 3, 2025
Swarm has two basic typing judgments: a top-level judgment that assigns capability-annotated polytypes, and a basic judgment that assigns monotypes to terms and collects the capabilities needed to evaluate them.
Definition Top-level typing judgment [001M]
- November 14, 2025
The top-level typing judgment is of the form \Gamma \vdash t : \sigma which simply says that term t has polytype \sigma in context \Gamma . Here \Gamma is a type context associating variables with their types. The polytype \sigma quantifies over type and capability variables, and contains a set of capbilities needed to evaluate the term t.
Definition Monomorphic typing judgment [001O]
- November 14, 2025
The basic typing judgment for the Swarm language has the form \Gamma \vdash t : \tau \;[\Delta ] where \Gamma is a type context, t is a term, \tau is a monotype (which could contain type variables), and \Delta is a capability set expression. This should intuitively be read as saying that t has type \tau in context \Gamma , and can be evaluated given capabilities \Delta . In this judgment \Gamma and t are considered inputs, \Delta is considered an output, and \tau can be either an input or an output depending on whether we are in checking or inference mode. In practice, the typing rules are implemented in an explicitly bidirectional style, but are presented here as undirected rules for simplicity.
Remark [001Q]
- November 14, 2025
Note that the basic typing judgment only says something about the capabilities required to evaluate t. Further use of the resulting value may require additional capabilities: for example, evaluating the application of t to an argument, if it is a function; or executing t, if it is a command. As a rule, the capabilities needed for such uses beyond evaluation are recorded in the type \tau .
Remark [001R]
- November 14, 2025
At the level of the basic typing judgment, the capability set \Delta is not part of the monotype \tau , but rather part of the judgment. The reason is that we want to maintain the invariant that polytypes only record a single, top-level capability set, and other capability sets are recorded at appropriate points within the type (e.g. as annotations on function arrows) rather than being sprinkled on every single subterm of the type.
Subtyping [00GV]
- June 11, 2026
We have a mild form of subtyping, in that we can always weaken a judgment by adding more capabilities:
Generalization and instantiation [001P]
- November 14, 2025
XXX add capability set variables and describe. Where can the different kinds of variables occur? (Hence, where do we need to apply substitutions?)
Pure fragment of the Swarm language [001T]
- November 18, 2025
First, we go through the various types and constructs in the pure fragment of the language. Expressions in the pure fragment can be evaluated and have no side effects, in contrast to the command monad, which embeds effectful, sequenced imperative programs. Note that evaluating an expression can result in an exception being thrown or nontermination, which one might consider effects; but both of these result, semantically, in a value of \bot . Evaluating an expression cannot have side effects in the sense of computing a value successfully while also causing extra effects.
For each type or family of types, we explain typing rules for introduced and elimination forms, as well as related built-in constants.
Undefined [00GR]
- June 9, 2026
There is a built-in constant \mathsf {undefined}, with type \forall \alpha .\; \alpha . Semantically, it corresponds to \bot ; operationally, trying to evaluate \mathsf {undefined} causes an exception to be thrown.
\mathsf {Void} and \mathsf {Unit} [001V]
- November 18, 2025
Swarm has a built-in \mathsf {Void} type with zero inhabitants, and a \mathsf {Unit} type with one inhabitant (written \mathsf {()}). Their associated typing rules are standard, and no special capabilities are needed to use them.
Note that there is no built-in eliminator for \mathsf {Void}; it is easy to implement one using undefined, as in \mathsf {absurd} : \forall \alpha .\; \mathsf {Void} \to \alpha = \lambda x.\; \mathsf {undefined}.
\mathsf {Delay} [00GS]
- June 10, 2026
If \tau is a type, then \mathsf {Delay}^{\Delta }\;\tau is a type representing delayed expressions of type \tau . The annotation \Delta represents the capabilities needed to force evaluation of the contained expression.
The delay type comes with two built-in constants, \mathsf {delay} and \mathsf {force}, representing introduction and elimination forms, with typing rules as follows:
Remark [00GT]
- June 10, 2026
Note that in surface syntax for Swarm, the delay type and introduction form are both written with curly braces; we choose not to use that syntax in this formal development since it could be easily confused with syntax for capability sets.
Functions [00GU]
- June 10, 2026
If \tau _1 and \tau _2 are types, and \Delta is a capability set expression, the type \tau _1 \xrightarrow {\Delta } \tau _2 represents functions which, when applied to an argument of type \tau _1, produce a result of type \tau _2 using capabilities \Delta . We use \tau _1 \to \tau _2 as an abbreviation for \tau _1 \xrightarrow {\varnothing } \tau _2, a function which requires no capabilities to apply.
Typing rules for functions [001A]
- November 9, 2025
The typing rule for lambdas is straightforward:
Here is the typing rule for function application:
Booleans [001W]
- November 18, 2025
The \mathsf {Bool} type is standard, with values \mathsf {true} and \mathsf {false}; no special capabilities are needed to use Boolean values themselves.
The eliminator for \mathsf {Bool} values is a built-in function \mathsf {if} with type \mathsf {if} : \forall \alpha .\; \{\mathsf {Exc}(\mathsf {if})\} \Rightarrow \mathsf {Bool} \to \mathsf {Delay}^{\delta _1}\;\alpha \to \mathsf {Delay}^{\delta _2}\;\alpha \xrightarrow {\delta _1 \cup \delta _2} \alpha This says that \mathsf {if} takes a boolean value and two delayed expressions of the same type \alpha , and produces a value of type \alpha . It also tells us that evaluating the constant \mathsf {if} itself requires capability \mathsf {Exc}(\mathsf {if}), and that evaluating its full application to a boolean and two delayed expressions requires capabilities \delta _1 \cup \delta _2—whatever capabilities are required to evaluate the two branches. Of course, only one of \delta _1 or \delta _2 will actually be needed, but since we can't know which until runtime, we must conservatively require their union.
Other base types: \mathsf {Int}, \mathsf {Text}, \mathsf {Dir}, \mathsf {Key}, \mathsf {Actor} [001X]
- November 18, 2025
Swarm has various other base types such as \mathsf {Int}, \mathsf {Text}, \mathsf {Dir}, \mathsf {Key}, and \mathsf {Actor}. All of these have various types of literals as well as built-in functions for manipulating them. As just one example, the addition operator is a built-in constant with the type \{\mathsf {Exc}(+)\} \Rightarrow \mathsf {Int} \to \mathsf {Int} \to \mathsf {Int}. The details of all the other introduction forms and operators, though important, are largely straightforward and not central to the story here.
Algebraic types [00GW]
- June 11, 2026
Swarm also has algebraic types, in the form of sum types \tau _1 + \tau _2, product types \tau _1 \times \tau _2, and record types [x_1: \tau _1, \dots , x_k: \tau _k].
XXX describe each one in turn. Need to mention elim forms in particular.
Equirecursive types [00GX]
- June 11, 2026
The type \mu X.\; \tau [X] represents the recursive type which is the least solution to \mu X.\; \tau [X] = \tau [\mu X.\; \tau [X]]. Since recursive types in Swarm are equirecursive, there are no special introduction or elimination forms; a recursive type is simply equal to its unfolding. For example, the type of polymorphic lists is given by \mu L.\; \mathsf {Unit} + \alpha \times L; in order to use a list, one can simply use \mathsf {case} to pattern-match on the sum type.
Inventories and requirement contexts [000W]
- November 3, 2025
In order to be able to properly express typing rules for the command monad, we first need to develop some additional machinery.
XXX note inventories are kind of like the free commutative monoid over entities, but with possibility of infinite cardinality. Like a free "star-commutative monoid". Star commutative monoid = commutative monoid with an additional operation a^* satisfying the axiom a^* = aa^*?
Definition Extended natural numbers [0013]
- November 4, 2025
We write \mathbb {N}_\infty = \mathbb {N} \cup \{\infty \} to denote the natural numbers extended with a special positive infinity value.
- Addition on \mathbb {N}_\infty satisfies n + \infty = \infty + n = \infty for all n \in \mathbb {N}_\infty , and is standard on \mathbb {N}.
- a \leq b if and only if there exists c \in \mathbb {N}_\infty such that a + c = b. In other words, \leq is standard on \mathbb {N}, and n \leq \infty for all n.
- Multiplication is standard on \mathbb {N}, with 0 \times \infty = \infty \times 0 = 0 and n \times \infty = \infty \times n = \infty for n > 0.
Under these definitions, (\mathbb {N}_\infty , +, 0, \times , 1) forms a (naturally ordered) commutative semiring.
Definition Inventories [0012]
- November 4, 2025
An inventory is a multiset of entities, that is, a function \mathbf {E} \to \mathbb {N}_\infty assigning a nonnegative (possibly infinite) multiplicity to each entity.
Definition Inventory union [001H]
- November 13, 2025
We define the union of inventories, I \cup J, as the inventory \lambda e.\; I(e) + J(e), the componentwise sum of inventories I and J. Inventories form a monoid under union, with the empty inventory \lambda e.\; 0 as the identity element.
Definition Inventory ordering [001I]
- November 13, 2025
If I and J are inventories, we write I \subseteq J to mean that I(e) \leq J(e) for every e \in \mathbf {E}, that is, J contains at least as many copies of each entity e as I does. Equivalently, I \subseteq J iff there exists an inventory K such that I \cup K = J.
Definition Inventory replication [001J]
- November 13, 2025
If k \in \mathbb {N}_\infty and I is an inventory, we define k \cdot I as the inventory \lambda e.\; k \times I(e); that is, intuitively, k \cdot I consists of the union of k copies of I. The inventory monoid together with this action by \mathbb {N}_\infty forms a left semimodule.
Notation Converting sets to inventories [00H3]
- June 12, 2026
If E \subseteq \mathbf {E} is a set of entities, then we write \lceil E\rceil to denote the inventory with exactly one copy of every element of E.
Definition Requirement contexts [000Z]
- November 3, 2025
A requirement context \Phi is a triple (\Delta ,D,I) where
- \Delta \subseteq \mathbf {C} is a set expression over capabilities, representing a set of capabilities that a robot should have;
- D \subseteq \mathbf {E} is a set expression over entities, representing a set of devices that should be equipped;
- I is a bag expression over entities, representing the inventory that a robot should possess.
Definition Requirement context notation [001K]
- November 13, 2025
We write \varnothing for the empty requirement context (\varnothing , \varnothing , \lambda e.\; 0). Also, for convenience, we sometimes write a bare set of capabilities \Delta to denote the requirement context (\Delta , \varnothing , \lambda e.\; 0), or a bare capability c to denote (\{c\}, \varnothing , \lambda e.\; 0); and likewise for bare entity sets or inventories.
Definition Requirement context satisfaction [0010]
- November 3, 2025
A robot with equipped device set Q and inventory V satisfies the requirement context \Phi = (\Delta ,D,I) if \Delta \subseteq \mathsf {caps}(Q), D \subseteq Q, and I \subseteq V. In other words, a robot satisfies a requirement context if its equipped devices provide at least the required capabilities, it has all the required devices equipped, and its inventory contains at least the required entity counts.
XXX need to take expressions into account.
Remark Requirement context motivation [0011]
- November 3, 2025
It's worth discussing the motivation for each of the components of a requirement context.
- The capability set \Delta is used to record capabilities needed to execute certain commands, use certain language constructs, and so on.
The device set D is used to record specific devices required by a
requiredirective. For example, theboatdevice confers the capability to traverse water, and does not correspond to a specific command or language construct, so the programmer needs a way to require it specifically. Also, since multiple devices may provide a given capability, the programmer may have reasons for requiring a specific device rather than letting the system choose.One might still wonder why we need both \Delta and D; wouldn't it be simpler to just have a set of required devices D? However, since the relationship between devices and capabilities can be many-to-many, we cannot reliably pick a concrete device for a required capability in a nicely compositional way. We prefer to wait until the last possible minute to pick a concrete set of devices to provide a given set of capabilities (using the provisioning oracle).
- The inventory I has several purposes. One is simply to record inventory required by a
stockdirective. For example,stock 10 "rock"requires a robot to have 10 rocks in its inventory. More importantly, however, thebuildcommand (which constructs a robot to execute a given program) turns device requirements into inventory requirements. That is, if executing programPrequires having device d equipped, then executingbuild {P}will require possessing d in the inventory (in order to equip the device on the newly constructed robot).
Requirement context union [0016]
- November 5, 2025
We define the union of requirement contexts componentwise, that is, \Phi _1 \cup \Phi _2 = (\Delta _1, D_1, I_1) \cup (\Delta _2, D_2, I_2) = (\Delta _1 \cup \Delta _2, D_1 \cup D_2, I_1 \cup I_2), where the first two unions are set union, and the last is inventory (multiset) union.
Also, as a notational convenience, when \Delta _1 is a capability set and \Phi _2 = (\Delta _2, D_2, I_2) is a requirement context, we write \Delta _1 \cup \Phi _2 as a shorthand for (\Delta _1 \cup \Delta _2, D_2, I_2).
Definition Requirement context replication [001L]
- November 13, 2025
For k \in \mathbb {N}_\infty we can also define k \cdot \Phi = k \cdot (\Delta ,D,I) = (k \cdot \Delta , k \cdot D, k \cdot I), where k \cdot I is inventory replication, and for any set S we define 0 \cdot S = \varnothing and k \cdot S = S for k > 0. Again, the idea is that k \cdot \Phi represents the union of k copies of \Phi .
Swarm command monad [001U]
- November 18, 2025
If \tau is a type, \mathsf {Cmd}^{\Phi }\;\tau is the type of commands which can be executed in requirement context \Phi , might have some effects, and will ultimately result in a value of type \tau .
Built-in commands [0018]
- November 9, 2025
Many built-in commands have simple typing rules like the following:
Some built-in commands take arguments, but they typically have a similar typing rule, with no capabilities on the arrows. For example, no special capabilities are required to evaluate the application \mathsf {turn}\; \mathsf {left}.
Bind [0019]
- November 9, 2025
The basic rule for bind (aka sequencing) in the \mathsf {Cmd} monad is as follows:
Note that this rule corresponds to a particular evaluation strategy, namely, evaluating c_1 and c_2 lazily, at the time c_1;\; c_2 is executed. If we instead wanted to evaluate c_1 and c_2 eagerly, we would need a different rule:
def f : Int -> Cmd Unit = ... end def g : Dir -> Cmd Unit = ... end def example = f 3; g north endWhen are
f 3 and g north evaluated? Under the first rule above, they would be re-evaluated every time example is executed. Under the second rule, they must be evaluated eagerly, when the definition of example is evaluated.As another example, consider the standard definition
def doN : Int -> Cmd a -> Cmd Unit = \n. \c.
if (n == 0) {} {c ; doN (n-1) c}
end
Under a lazy evaluation semantics for sequencing, a call to doN 10 move expands lazily, expanding one step each time the next move is executed. Under an eager semantics, a call to doN 10 move expands immediately into a fully unrolled sequence of 10 move instructions. There are certainly scenarios where we would want this eager unrolling (for efficiency, or in order to pass a fully unrolled program to a child robot that therefore does not need any complex devices to run it), but lazy evaluation is probably the better default, perhaps with a special "eager sequence" operation provided as well. Consider the example of a forever function that calls the same command in an infinite loop: under eager evaluation, this would simply go into an infinite loop generating an infinite program without ever executing anything!
However, we can also bind the result of c_1 in c_2, in which case we do not even have the option to evaluate c_2 eagerly (unless we wanted to implement partial evaluation of open terms). The rule for x \leftarrow c_1;\; c_2 is therefore:
Require [00GZ]
- June 12, 2026
There is a special \mathsf {require} directive which requires a specific device to be equipped. Given the framework for requirements tracking, the typing rule is straightforward:
Stock [00H0]
- June 12, 2026
Similarly, there is a special \mathsf {stock} directive which requires a certain number of a specific entity to be in the inventory, with a similarly straightforward typing rule:
Build [00H1]
- June 12, 2026
When a robot (the "parent") wishes to build another robot, it can execute \mathsf {build}\;p in order to create a robot (the "child") running program p. There are several things to take into consideration here:
- Of course, the parent robot must have the capability to execute \mathsf {build}.
- The child robot should be the one to evaluate and execute p.
- The child robot must have the capabilities needed to evaluate and execute p. Hence, it must have a set of equipped devices which provide the necessary capabilities, and hence the parent robot must take these devices from its inventory and equip them on the child robot at build time.
- The program to be run by the child robot may also explicitly require certain devices to be installed, and certain inventory to be present. The parent robot must also provide these things to the child robot from its inventory at build time.
These considerations lead us to the following typing rule for \mathsf {build}:
- First, the premise states that p must be a delayed command. The reason for requiring the command to be wrapped in a delay is to make clear that any evaluation of the command is to be carried out by the child robot.
- The conclusion states that \mathsf {build}\;p is a command, producing a value of type \mathsf {Actor} (a reference to the child robot). The only capabilities needed by the parent robot to evaluate \mathsf {build}\;p are \Delta _1, the capabilities needed to evaluate p.
- The only capability needed to execute \mathsf {build}\;p is \mathsf {Exc}(\mathsf {build}).
- Executing the \mathsf {build} command does not require any specific devices to be equipped; any device which provides the \mathsf {Exc}(\mathsf {build}) capability will do.
- Executing the \mathsf {build} command does require inventory. In particular:
- The child robot will require capabilities \Delta _2 (to evaluate the delayed command) and \Delta _3 (to execute the command); and it specifically must have devices D equipped. Thus we use the provisioning oracle \mathsf {provision}(\Delta _2 \cup \Delta _3, D) to compute a set of devices to install.
- We convert this to an inventory, and union it with the inventory I specifically required to execute p.
- The result is the inventory required of the parent robot to execute \mathsf {build}\;p, since it will need to be transferred to the child robot.
Equip/unequip [00H2]
- June 12, 2026
As discussed previously, the \mathsf {equip} and \mathsf {unequip} commands allow robots to move devices between their inventory and equipped set. Unlike \mathsf {stock} and \mathsf {require}, to allow for necessary flexibility, these commands take an arbitrary expression that evaluates to the name of a device. So, conservatively, we must use generic typing rules that do not interact with the requirements system at all.