Algorithm Search⌘K

Algorithmresearch

Type-directed program synthesis

Also called synthesis from refinement types.

Searches for a program top-down by the goal type, using examples or refinement types to prune each partial program early.

Time
O(w b^2) one bankO((2b)^d w b^2) worst case whole search
Space
O((2b)^d w b) worst case whole search
Where
b = the number of kept E-terms in one bank; d = the bound on nested conditionals; w = the number of examples
Properties
deterministicrecursive
Origin
Peter Michael Osera, Steve Zdancewic, 2015

Type-directed program synthesis searches for a program from the top down, guided by the type of the goal. At a function type it adds an abstraction and moves the examples inside it. At a data type it either guesses a term built from the variables in scope, or it splits the goal by a case analysis and solves each case. Each step follows a typing rule, so every partial program is well typed, and the examples or a refined type remove a wrong partial program before its holes are filled. Myth (Osera and Zdancewic 2015) uses examples and the types of a functional language with algebraic data types. Synquid (Polikarpova and others 2016) uses refinement types, such as "a list whose length is n", as the whole specification. The code on this page is a small instance on integers in the toy lambda language of the Algorithm W page.

In plain words

Say you want a function from a number to a number, and you know its value at 0, 1, 2, 3 and 4. The type says that the program starts with "take a number x". Inside, the search knows x and the wanted result for each example.

First it tries short formulas in x. If none gives all the results, it splits the examples into "x is 0" and "x is not 0", and solves the two parts on their own. In the second part it may call the function itself on x minus 1. It does not run that call: it looks up the answer in the examples, since the value at x minus 1 is one of them.

The types keep the search small. A number is built only from numbers, and a test from two numbers, so no term of the wrong kind is made.

The problem

Input. A goal type τ=int→⋯→int\tau = \mathrm{int} \rightarrow \cdots \rightarrow \mathrm{int} with one to three arguments, and examples (a,o)(a, o) of argument tuples and outputs.

Output. A closed term pp of type τ\tau in the toy language with p a1⋯an=op\ a_1 \cdots a_n = o for every example, or "none" if no program in the bounded space fits.

The space. The program is fix f x→fun y→⋯→B\mathbf{fix}\ f\ x \rightarrow \mathbf{fun}\ y \rightarrow \cdots \rightarrow B. A body BB is an E-term, or a conditional if c then B else B\mathbf{if}\ c\ \mathbf{then}\ B\ \mathbf{else}\ B. An E-term is an argument, 0, 1, a sum, difference or product of E-terms, or a recursive call f (x−1) e2⋯enf\ (x - 1)\ e_2 \cdots e_n. A condition is e1<e2e_1 < e_2 or e1=e2e_1 = e_2 for E-terms, or the guard x<1x < 1. The guard is the match of a natural number on zero and successor: a call of ff is allowed only in its false branch, and the guard appears at most once on each path. The size of an E-term is its number of nodes, where the call f (x−1)f\ (x - 1) counts 2 and each further argument counts its own size. The bounds are KK on the size of E-terms and conditions, and DD on the nesting of conditionals.

Trace completeness. The search reads the value of a recursive call from the examples. So the examples should hold every call that the wanted program makes on an example input. For a function of one argument this means: if nn is an example input, so are n−1,…,0n - 1, \ldots, 0.

The algorithm

  1. SYNTHESIZE(τ, examples)
  2. 1T ← the examples as a table from argument tuples to outputs
  3. 2for k = 1, 2, …, K do
  4. 3for d = 0, 1, …, D do
  5. 4B ← REFINE(the examples as worlds, k, d, none)
  6. 5if B ≠ none then return fix f x → fun y → … → B ▷ the introduction for the arrow type τ
  7. 6return none
  8. REFINE(W, k, d, m) ▷ m is none, base or step
  9. 7look bottom-up for an int E-term of size ≤ k that gives the wanted output in every world of W ▷ calls only if m = step, read from T
  10. 8if one is found then return it
  11. 9if d = 0 then return none
  12. 10if m = none then split W by x < 1 into W0 and W1, with W1 non-empty, and solve REFINE(W0, k, d - 1, base) and REFINE(W1, k, d - 1, step)
  13. 11if both are found then return if x < 1 then B0 else B1
  14. 12for each kept bool E-term c of size ≤ k that splits W into non-empty W⊤ and W⊥ do
  15. 13solve REFINE(W⊤, k, d - 1, m) and REFINE(W⊥, k, d - 1, m)
  16. 14if both are found then return if c then B⊤ else B⊥
  17. 15return none

Introduction by the type (line L5). The goal type is an arrow, so the program must be an abstraction. With recursion it is fix f x\mathbf{fix}\ f\ x, and further arguments add fun\mathbf{fun}. Each example (a,o)(a, o) becomes a world: the values of x,y,…x, y, \ldots and the wanted output of the body. This is how Myth pushes examples through the introduction rule of the function type.

Guessing E-terms (lines L7 and L8). E-terms are elimination forms: they use the variables in scope, the operators and ff. The search builds them bottom-up by size, as in bottom-up enumerative synthesis, with their vectors of values over the worlds, and keeps one term for each vector. The vector of a call f (x−1) e2f\ (x - 1)\ e_2 in a world is the output of the example (x−1,e2)(x - 1, e_2) in TT, or "undefined" if there is no such example. An undefined entry never matches.

Refinement by cases (lines L10 to L14). If no E-term fits, the body becomes a conditional. The guard x<1x < 1 splits the worlds into base and step cases, and only the step branch may call ff. A guessed condition splits the worlds by its vector. Each part becomes a smaller problem with fewer worlds, so it is easier to fit by an E-term. Only one condition is kept for each distinct split.

Iterative deepening (lines L2 and L3). The outer loops raise the size bound and the nesting bound, so a program with small parts is found before one with large parts.

Example

The examples are 0↦00 \mapsto 0, 1↦11 \mapsto 1, 2↦32 \mapsto 3, 3↦63 \mapsto 6 and 4↦104 \mapsto 10, of type int →\rightarrow int. They are trace complete.

  • k≤2k \le 2. The kept E-terms are xx, 0 and 1, with the vectors (0,1,2,3,4)(0, 1, 2, 3, 4), (0,0,0,0,0)(0, 0, 0, 0, 0) and (1,1,1,1,1)(1, 1, 1, 1, 1). None fits, and there are no conditions yet.
  • k=3k = 3. There are 11 kept E-terms and 6 conditions, and none of the E-terms gives (0,1,3,6,10)(0, 1, 3, 6, 10). The guard splits the worlds into {0}\{0\} and {1,2,3,4}\{1, 2, 3, 4\}. The base branch is fitted by xx. In the step branch f (x−1)f\ (x - 1) has the vector (0,1,3,6)(0, 1, 3, 6), read from the examples, but no term of size 3 gives (1,3,6,10)(1, 3, 6, 10). The guessed conditions do not help either.
  • k=4k = 4, d=1d = 1. In the step branch, x+f (x−1)x + f\ (x - 1) has size 4 and the vector (1,3,6,10)(1, 3, 6, 10).

The result is

fix f x→if x<1 then x else x+f (x−1),\mathbf{fix}\ f\ x \rightarrow \mathbf{if}\ x < 1\ \mathbf{then}\ x\ \mathbf{else}\ x + f\ (x - 1),

after 51 calls of REFINE. Type inference gives int →\rightarrow int, and the interpreter gives 15 on 5 and 21 on 6. The code finds, in the same way, x×f (x−1)x \times f\ (x - 1) with base 1 from the values 1, 1, 2, 6, 24 of the factorial, f (x−1)+x×xf\ (x - 1) + x \times x from 0, 1, 5, 14, 30, and for two arguments if x<y then y else x\mathbf{if}\ x < y\ \mathbf{then}\ y\ \mathbf{else}\ x from five examples of the maximum.

What the examples do not decide. The Fibonacci numbers 0, 1, 1, 2, 3, 5 on 0 to 5 need a call on x−2x - 2, which is not in the space. The search still meets all six examples. Below the guard it finds the condition 1<f (x−1)1 < f\ (x - 1), with f (x−1)−(1−f (x−1))f\ (x - 1) - (1 - f\ (x - 1)) in its true branch and x−f (x−1)x - f\ (x - 1) in its false branch. This program gives 9 on 6 and 17 on 7, where Fibonacci gives 8 and 13. The test file checks this case.

Correctness

The proof is in proofs/correctness.md. Every term is built at a known type from parts of known types, so the result has the goal type, and Hindley-Milner inference confirms it; when an argument is not used, the inferred type is more general and has the goal type as an instance. The vectors give the exact value of each term when calls are read from the table, so a returned body meets every world. Every call has a first argument that is one smaller and lies in the table, so by induction on the first argument the real run of the program gives the same values as the table. The calls happen only when x≥1x \ge 1, so the program stops on every integer input. Within the bounds the search is complete for trace complete examples: an E-term or a condition that works has a kept twin with the same vector, so the same split and the same leaves are found.

Proof: The synthesized function is well typed, meets the examples, and always terminatesfull

Setting. The goal type is τn=int→⋯→int\tau_n = \mathrm{int} \rightarrow \cdots \rightarrow \mathrm{int} with n∈{1,2,3}n \in \{1, 2, 3\} arguments x,y,zx, y, z. The examples are pairs (a,o)(a, o) of an argument tuple a=(a1,…,an)a = (a_1, \ldots, a_n) of integers and an integer output, with no two examples for the same aa. TT is the table from aa to oo. Line numbers refer to the pseudocode on the page.

The terms that the search builds are:

  • E-terms of type int: the arguments, 0, 1, e1ope2e_1 \mathbin{op} e_2 with op∈{+,−,×}op \in \{+, -, \times\}, and the call f (x−1) e2⋯enf\ (x - 1)\ e_2 \cdots e_n with E-terms e2,…,ene_2, \ldots, e_n.
  • Conditions of type bool: e1<e2e_1 < e_2 and e1=e2e_1 = e_2 for E-terms e1,e2e_1, e_2.
  • Bodies: an E-term, or if c then B1 else B2\mathbf{if}\ c\ \mathbf{then}\ B_1\ \mathbf{else}\ B_2 for a condition cc or for the guard x<1x < 1.

The result is fix f x→fun y→⋯→B\mathbf{fix}\ f\ x \rightarrow \mathbf{fun}\ y \rightarrow \cdots \rightarrow B. On each path from the root of BB, the guard x<1x < 1 appears at most once, and a call of ff appears only below its false branch. The flag mm of REFINE records this: "none" above the guard, "base" below its true branch and "step" below its false branch.

The value modulo the table. For a body BB and an argument tuple aa, let [ ⁣[B] ⁣]T(a)[\![B]\!]_T(a) be the value of BB when the arguments are aa and a call f v1⋯vnf\ v_1 \cdots v_n gives T(v1,…,vn)T(v_1, \ldots, v_n) if this tuple is in TT, and the marker ⊥\bot otherwise. An operator with an argument ⊥\bot gives ⊥\bot. This is the value that the vectors of the search compute at line L7, one entry for each world.

Lemma 1: the vectors are exact

Claim. For every E-term or condition tt kept by the bank on the worlds WW, its vector is ([ ⁣[t] ⁣]T(a))(a,o)∈W([\![t]\!]_T(a))_{(a, o) \in W}. The bank keeps no condition with a ⊥\bot entry.

Proof. By induction on the size of tt. Arguments and constants are read off directly. The vector of e1ope2e_1 \mathbin{op} e_2 is computed entry by entry from the vectors of e1e_1 and e2e_2, with ⊥\bot if one entry is ⊥\bot. The vector of a call is computed from the value a1−1a_1 - 1 and the vectors of e2,…,ene_2, \ldots, e_n by a lookup in TT, with ⊥\bot for a tuple not in TT. Line L12 skips conditions with a ⊥\bot entry, because the code does not keep them. □\square

Theorem 1: the result type-checks at the goal type

Claim. If SYNTHESIZE returns pp, then pp has the type τn\tau_n in the type system of the toy language.

Proof. Assume f:τnf : \tau_n and x,y,z:intx, y, z : \mathrm{int}. By induction on terms: arguments and constants are int; ++, −-, ×\times take two ints and give an int; << and == take two ints and give a bool; x−1x - 1 is an int, and ff applied to nn ints is an int; a conditional with a bool condition and two int branches is an int. So B:intB : \mathrm{int}, the n−1n - 1 abstractions give τn−1\tau_{n-1} in the scope of xx and ff, and the rule for fix gives p:τnp : \tau_n. Hindley-Milner inference returns the principal type of pp, which is τn\tau_n or, when an argument does not occur in BB, a more general type that has τn\tau_n as an instance. □\square

This is the type-directed part: every term is built at a known type from parts of known types, so no ill-typed candidate is ever built.

Theorem 2: the result meets every example

Lemma 2. If REFINE(W,k,d,m)(W, k, d, m) returns BB, then [ ⁣[B] ⁣]T(a)=o[\![B]\!]_T(a) = o for every world (a,o)∈W(a, o) \in W.

Proof. By induction on dd. If BB comes from line L8, its vector equals the wanted outputs, and Lemma 1 gives the claim. If B=if c then B1 else B2B = \mathbf{if}\ c\ \mathbf{then}\ B_1\ \mathbf{else}\ B_2 comes from line L11 or L14, the worlds where cc is true went to B1B_1 and the others to B2B_2, by the vector of cc (Lemma 1, with no ⊥\bot), or by a1<1a_1 < 1 for the guard. By induction B1B_1 and B2B_2 meet their worlds, so BB meets all of WW. □\square

Claim. If SYNTHESIZE returns pp, then for each example (a,o)(a, o), running p a1⋯anp\ a_1 \cdots a_n in the interpreter gives the value oo.

Proof. By Lemma 2 with WW = all examples, [ ⁣[B] ⁣]T(a)=o[\![B]\!]_T(a) = o for every example. Now show by induction on a1a_1 that the interpreter gives oo. The real run of BB on aa differs from [ ⁣[B] ⁣]T(a)[\![B]\!]_T(a) only at calls of ff. A call happens only in the branch where a1<1a_1 < 1 is false, so a1≥1a_1 \ge 1, and its first argument is a1−1a_1 - 1. Since [ ⁣[B] ⁣]T(a)=o≠⊥[\![B]\!]_T(a) = o \ne \bot, every call whose value is used gives a tuple v=(a1−1,v2,…,vn)v = (a_1 - 1, v_2, \ldots, v_n) that is in TT, so (v,T(v))(v, T(v)) is an example with a smaller first argument. By induction the real call returns T(v)T(v). So the real run computes the same values as [ ⁣[B] ⁣]T(a)[\![B]\!]_T(a) and returns oo. The interpreter is call by value, so it also evaluates calls in E-terms whose value is used. □\square

This proof needs no assumption on the examples. Trace completeness, the condition that every call that the wanted program makes on an example input is again an example, matters only for completeness below: without it, the call in the wanted program has a ⊥\bot entry and cannot be found.

Theorem 3: the result terminates on every input

Claim. For all integers a1,…,ana_1, \ldots, a_n, the run of p a1⋯anp\ a_1 \cdots a_n stops.

Proof. By induction on max⁡(a1,0)\max(a_1, 0). Apart from calls of ff, the body is a finite term of operators and conditionals, so it takes finitely many steps. If a1<1a_1 < 1, the guard sends the run into a branch with no calls, or there is no guard on the path and there is no call. If a1≥1a_1 \ge 1, each call has the first argument a1−1a_1 - 1, and max⁡(a1−1,0)<max⁡(a1,0)\max(a_1 - 1, 0) < \max(a_1, 0), so each call stops by induction. □\square

Theorem 4: completeness for the bounded space

Claim. Let a body B∗B^\ast exist with [ ⁣[B∗] ⁣]T(a)=o[\![B^\ast]\!]_T(a) = o for all worlds of WW, whose E-terms and conditions have size at most kk, with at most dd nested conditionals, and which respects the flag mm. Then REFINE(W,k,d,m)(W, k, d, m) returns a body.

Proof. By induction on the number of conditionals in B∗B^\ast. If B∗B^\ast is an E-term, the bank keeps, by the lemma of bottom-up enumerative synthesis, an E-term of size at most kk with the same vector, since the vector of a term is a function of the vectors of its parts (Lemma 1). So line L8 returns. Otherwise B∗=if c then B1 else B2B^\ast = \mathbf{if}\ c\ \mathbf{then}\ B_1\ \mathbf{else}\ B_2 and d≥1d \ge 1.

  • The guard, mm = none. Line L10 makes the same split, also when no world has a1<1a_1 < 1; then any term fits the empty base branch. By induction REFINE finds bodies for the two sides with depth d−1d - 1, because B1B_1 fits the first side with flag "base" and B2B_2 fits the second with flag "step".
  • A condition with both sides non-empty. The bank keeps a condition with the same vector, so the same split is tried at line L12, and by induction both sides are found.
  • A condition with an empty side. Then one branch, say B1B_1, alone fits WW with the same flag and fewer conditionals, and its depth is at most dd. By induction REFINE(W,k,d,m)(W, k, d, m) returns a body.

The guard cannot occur below another guard, and a call cannot occur above the guard, by the flag, so these cases cover all bodies. □\square

So with trace complete examples, SYNTHESIZE returns a result whenever a body with E-terms of size at most KK and at most DD nested conditionals meets the examples. It tries the pairs (k,d)(k, d) in the order of lines L2 and L3, so the result has the least kk among such bodies, and the least dd for that kk.

Complexity

Let bb be the number of kept E-terms in one bank, ww the number of examples, and dd the bound on nested conditionals. A bank combines O(b2)O(b^2) pairs of kept terms, at O(w)O(w) per vector, so it takes O(wb2)O(w b^2) time and O(wb)O(w b) space. A call of REFINE tries the guard and up to bb conditions, each with two recursive calls, so the search tree has O((2b)d)O((2b)^d) nodes. Each node builds a bank for its set of worlds, and banks are shared between equal sets. The worst case is O((2b)dwb2)O((2b)^d w b^2) time for one pair (k,d)(k, d). The number bb is bounded by the number of distinct vectors and grows exponentially with kk.

The general problem is hard even with no examples: finding any closed term of a given simple type is the same as finding a proof in intuitionistic propositional logic, by the Curry-Howard correspondence, and that is PSPACE-complete (Statman 1979).

Properties

  • Well typed by construction. No ill-typed term is built, so the search never wastes time on one.
  • Sound for the examples. The result meets every example, with no assumption on the examples.
  • Total. The result stops on every input, because each call is structural.
  • Complete within the bounds for trace complete examples, and it returns a body with the least size bound kk.
  • Not a smallest program. Iterative deepening bounds the size of each part, not of the whole program.

Variants and improvements

  • Algebraic data types. Myth works on lists and trees. The match rule splits the worlds by the constructor of a variable, and each branch binds the fields, such as the head and the tail of a list, which are then allowed as arguments of recursive calls.
  • Higher-order examples. Myth allows examples of functions as partial functions, so a goal like "map" can be given by examples of its argument and its result.
  • Refinement types. Synquid takes a type such as "a list of the same length, sorted" as the specification. It checks each partial program against the type with liquid type inference, and moves the conditions from the goal into the types of the holes, so a wrong partial program fails early with no examples.
  • Combinators with deduction. λ² (Feser and others 2015) fills hypotheses such as "map of a hole" or "fold of a hole", and deduces from the examples the examples of the hole, or that no term can fill it.
  • Relaxed trace completeness. Escher (Albarghouthi and others 2013) also answers recursive calls from the examples, and asks the user for the missing ones.

When to use it

Use it for small functional programs with recursion over a data type, when the user can give a few examples that include the recursive cases, or a precise refinement type. The types cut the search at every step, which matters most for programs with several data types and higher-order functions. For flat expressions over one type, plain bottom-up enumerative synthesis is simpler. For a specification as a logical formula with a known structure, use deductive program synthesis or a solver.

Pitfalls

  • Missing examples for recursive calls. If the example for x−1x - 1 is missing, the call is undefined in that world, and the intended recursive program cannot be found. Give examples for all smaller inputs, or for all inputs that the intended program calls.
  • Overfitting with conditionals. With enough nested conditionals, the search fits any finite set of examples, as the Fibonacci case shows. Keep the nesting bound small and prefer programs with few cases.
  • Unused arguments. A result that ignores an argument has a more general principal type. Check it against the goal type by unification, not by equality of types.
  • Negative inputs. A match on zero and successor is only meaningful on natural numbers. The guard x<1x < 1 keeps the result total on negative inputs, but the examples say nothing about them.
  • Growth with the size bound. Each step of kk can multiply the bank, and each level of dd multiplies the number of splits. Small examples with small numbers keep vectors short and banks small.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

toylam.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy lambda language: terms, types, call-by-value small steps.

Terms are tuples:
    ("var", x)              a variable, x is a str
    ("lam", x, e)           fun x -> e
    ("app", e1, e2)         e1 e2
    ("let", x, e1, e2)      let x = e1 in e2
    ("int", k)              an integer constant, k is a Python int
    ("bool", b)             true or false, b is a Python bool
    ("if", e1, e2, e3)      if e1 then e2 else e3
    ("prim", op, e1, e2)    e1 op e2, op is one of + - * < ==
    ("fix", f, x, e)        a recursive function: f is the function itself, x its argument

Types are tuples:
    ("int",)  ("bool",)  ("fun", t1, t2)  ("tv", n)   with n an int

Values are int and bool constants, lambdas and fix terms. The semantics is
call by value, left to right. step(e) returns the next term when e can step,
e itself when e is a value, and the marker "stuck" otherwise. A free
variable, an application of a non-function, a non-boolean condition and an
operator on non-integers are stuck. Substitution only ever puts closed values
into terms, because evaluation starts from closed terms, so no renaming is
needed.
"""

STUCK = "stuck"

PRIMS = ("+", "-", "*", "<", "==")


def is_value(e):
    return e[0] in ("int", "bool", "lam", "fix")


def free_vars(e):
    """The set of free term variables of e."""
    tag = e[0]
    if tag == "var":
        return {e[1]}
    if tag == "lam":
        return free_vars(e[2]) - {e[1]}
    if tag == "app":
        return free_vars(e[1]) | free_vars(e[2])
    if tag == "let":
        return free_vars(e[2]) | (free_vars(e[3]) - {e[1]})
    if tag in ("int", "bool"):
        return set()
    if tag == "if":
        return free_vars(e[1]) | free_vars(e[2]) | free_vars(e[3])
    if tag == "prim":
        return free_vars(e[2]) | free_vars(e[3])
    if tag == "fix":
        return free_vars(e[3]) - {e[1], e[2]}
    raise ValueError(f"not a term: {e!r}")


def subst(e, x, v):
    """Replace the free occurrences of x in e by the closed value v."""
    tag = e[0]
    if tag == "var":
        return v if e[1] == x else e
    if tag == "lam":
        return e if e[1] == x else ("lam", e[1], subst(e[2], x, v))
    if tag == "app":
        return ("app", subst(e[1], x, v), subst(e[2], x, v))
    if tag == "let":
        body = e[3] if e[1] == x else subst(e[3], x, v)
        return ("let", e[1], subst(e[2], x, v), body)
    if tag in ("int", "bool"):
        return e
    if tag == "if":
        return ("if", subst(e[1], x, v), subst(e[2], x, v), subst(e[3], x, v))
    if tag == "prim":
        return ("prim", e[1], subst(e[2], x, v), subst(e[3], x, v))
    if tag == "fix":
        if x in (e[1], e[2]):
            return e
        return ("fix", e[1], e[2], subst(e[3], x, v))
    raise ValueError(f"not a term: {e!r}")


def _prim(op, a, b):
    if op == "+":
        return ("int", a + b)
    if op == "-":
        return ("int", a - b)
    if op == "*":
        return ("int", a * b)
    if op == "<":
        return ("bool", a < b)
    if op == "==":
        return ("bool", a == b)
    raise ValueError(f"unknown operator {op!r}")


def step(e):
    """One call-by-value step: the next term, e itself if e is a value, or STUCK."""
    if is_value(e):
        return e
    tag = e[0]
    if tag == "var":
        return STUCK
    if tag == "app":
        f, a = e[1], e[2]
        if not is_value(f):
            f2 = step(f)
            return STUCK if f2 == STUCK else ("app", f2, a)
        if not is_value(a):
            a2 = step(a)
            return STUCK if a2 == STUCK else ("app", f, a2)
        if f[0] == "lam":
            return subst(f[2], f[1], a)
        if f[0] == "fix":
            return subst(subst(f[3], f[1], f), f[2], a)
        return STUCK
    if tag == "let":
        if not is_value(e[2]):
            e1 = step(e[2])
            return STUCK if e1 == STUCK else ("let", e[1], e1, e[3])
        return subst(e[3], e[1], e[2])
    if tag == "if":
        c = e[1]
        if not is_value(c):
            c2 = step(c)
            return STUCK if c2 == STUCK else ("if", c2, e[2], e[3])
        if c[0] == "bool":
            return e[2] if c[1] else e[3]
        return STUCK
    if tag == "prim":
        a, b = e[2], e[3]
        if not is_value(a):
            a2 = step(a)
            return STUCK if a2 == STUCK else ("prim", e[1], a2, b)
        if not is_value(b):
            b2 = step(b)
            return STUCK if b2 == STUCK else ("prim", e[1], a, b2)
        if a[0] == "int" and b[0] == "int":
            return _prim(e[1], a[1], b[1])
        return STUCK
    raise ValueError(f"not a term: {e!r}")


def evaluate(e, fuel=10000):
    """Run e. Returns ("value", v), ("stuck", t) with the stuck term t, or ("fuel",)."""
    for _ in range(fuel):
        if is_value(e):
            return ("value", e)
        nxt = step(e)
        if nxt == STUCK:
            return ("stuck", e)
        e = nxt
    return ("value", e) if is_value(e) else ("fuel",)


NAMES = ("x", "y", "z", "f", "g")


def random_term(rng, depth, scope=()):
    """A random term of height at most depth whose free variables are in scope.

    With the default empty scope the term is closed. rng is a random.Random.
    """
    scope = tuple(scope)
    if depth <= 0 or rng.random() < 0.15:
        r = rng.random()
        if scope and r < 0.6:
            return ("var", rng.choice(scope))
        if r < 0.8:
            return ("int", rng.randint(0, 3))
        return ("bool", rng.random() < 0.5)
    d = depth - 1
    kind = rng.choice(("var", "lam", "lam", "app", "app", "let", "let", "if", "prim", "fix"))
    if kind == "var" and scope:
        return ("var", rng.choice(scope))
    if kind == "lam" or kind == "var":
        x = rng.choice(NAMES)
        return ("lam", x, random_term(rng, d, scope + (x,)))
    if kind == "app":
        return ("app", random_term(rng, d, scope), random_term(rng, d, scope))
    if kind == "let":
        x = rng.choice(NAMES)
        return ("let", x, random_term(rng, d, scope), random_term(rng, d, scope + (x,)))
    if kind == "if":
        return ("if", random_term(rng, d, scope), random_term(rng, d, scope), random_term(rng, d, scope))
    if kind == "prim":
        return ("prim", rng.choice(PRIMS), random_term(rng, d, scope), random_term(rng, d, scope))
    f, x = rng.sample(NAMES, 2)
    return ("fix", f, x, random_term(rng, d, scope + (f, x)))


def size(e):
    """The number of nodes of the syntax tree of e."""
    tag = e[0]
    if tag in ("var", "int", "bool"):
        return 1
    if tag == "lam":
        return 1 + size(e[2])
    if tag == "app":
        return 1 + size(e[1]) + size(e[2])
    if tag == "let":
        return 1 + size(e[2]) + size(e[3])
    if tag == "if":
        return 1 + size(e[1]) + size(e[2]) + size(e[3])
    if tag == "prim":
        return 1 + size(e[2]) + size(e[3])
    if tag == "fix":
        return 1 + size(e[3])
    raise ValueError(f"not a term: {e!r}")


def show(e):
    """The surface syntax: fun x -> e, e1 e2, let x = e1 in e2."""
    tag = e[0]
    if tag == "var":
        return e[1]
    if tag == "int":
        return str(e[1])
    if tag == "bool":
        return "true" if e[1] else "false"
    if tag == "lam":
        return f"(fun {e[1]} -> {show(e[2])})"
    if tag == "app":
        return f"({show(e[1])} {show(e[2])})"
    if tag == "let":
        return f"(let {e[1]} = {show(e[2])} in {show(e[3])})"
    if tag == "if":
        return f"(if {show(e[1])} then {show(e[2])} else {show(e[3])})"
    if tag == "prim":
        return f"({show(e[2])} {e[1]} {show(e[3])})"
    if tag == "fix":
        return f"(fix {e[1]} {e[2]} -> {show(e[3])})"
    raise ValueError(f"not a term: {e!r}")


def type_vars(t):
    """The type variables of t, in order of first occurrence, left to right."""
    out = []

    def go(u):
        if u[0] == "tv":
            if u[1] not in out:
                out.append(u[1])
        elif u[0] == "fun":
            go(u[1])
            go(u[2])

    go(t)
    return out


def rename_type(t, mapping):
    if t[0] == "tv":
        return ("tv", mapping.get(t[1], t[1]))
    if t[0] == "fun":
        return ("fun", rename_type(t[1], mapping), rename_type(t[2], mapping))
    return t


def normalize_type(t):
    """Rename the type variables of t to 0, 1, 2, ... in order of first occurrence."""
    return rename_type(t, {v: i for i, v in enumerate(type_vars(t))})


def type_size(t):
    """The number of nodes of t as a tree."""
    if t[0] == "fun":
        return 1 + type_size(t[1]) + type_size(t[2])
    return 1


def show_type(t):
    """int, bool, a, b, ... with right-associative arrows."""
    if t[0] == "int":
        return "int"
    if t[0] == "bool":
        return "bool"
    if t[0] == "tv":
        n = t[1]
        return chr(ord("a") + n) if 0 <= n < 26 else f"t{n}"
    left = show_type(t[1])
    if t[1][0] == "fun":
        left = f"({left})"
    return f"{left} -> {show_type(t[2])}"
type_directed_synthesis.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/type-directed-synthesis/. The authors are listed in prov/3WFWA4.jsonl.
"""Type-directed synthesis of recursive functions on the toy lambda language.

The goal type is int -> int or int -> int -> int, and the specification is a
list of examples (args, out). The synthesizer works top-down by the type:

- At a function type it introduces fix f x -> fun y -> ..., so the body has
  the arguments in scope, and each example becomes a world: the values of
  the arguments and the wanted output.
- At int it first guesses an E-term (variables, 0, 1, + - * and a recursive
  call) that gives the wanted output in every world. E-terms are built
  bottom-up by size, one per distinct vector of values over the worlds.
- If no E-term fits, it refines: it splits the worlds by "x < 1" (the match
  of a natural number on zero and successor), or by a guessed bool E-term
  (< and == of int E-terms), and solves each part.

The recursive call is f (x - 1) a2 ... and is allowed only in the branch where
x < 1 is false. Its value in a world is read from the examples, so the
examples must be trace complete: every call that the wanted program makes on
an example input must be an example too. The outer loop deepens the size of
E-terms k and the number of nested splits d.
"""

from toylam import show  # noqa: F401  (re-exported for callers)

ARGS = ("x", "y", "z")


def var(n):
    return ("var", n)


def num(k):
    return ("int", k)


def rec_call(arity, rest):
    """The term f (x - 1) a2 ... an."""
    t = ("app", var("f"), ("prim", "-", var("x"), num(1)))
    for a in rest:
        t = ("app", t, a)
    return t


def guard():
    return ("prim", "<", var("x"), num(1))


def wrap(arity, body):
    """fix f x -> fun y -> ... -> body, a term of type int -> ... -> int."""
    for name in reversed(ARGS[1:arity]):
        body = ("lam", name, body)
    return ("fix", "f", "x", body)


def _bank(worlds, k, allow_rec, arity, table, memo):
    """The kept int and bool E-terms of size at most k, with their vectors."""
    key = (worlds, k, allow_rec)
    if key in memo:
        return memo[key]
    ints = {}   # size -> list of (term, vector)
    bools = []  # list of (term, vector)
    seen_i, seen_b = set(), set()

    def add_int(s, t, vec):
        if vec not in seen_i:  # observational equivalence over the worlds
            seen_i.add(vec)
            ints.setdefault(s, []).append((t, vec))

    for s in range(1, k + 1):
        if s == 1:
            for i in range(arity):
                add_int(1, var(ARGS[i]), tuple(w[i] for w in worlds))
            add_int(1, num(0), tuple(0 for _ in worlds))
            add_int(1, num(1), tuple(1 for _ in worlds))
        if allow_rec:
            for parts in _arg_tuples(ints, arity - 1, s - 2):
                vec = []
                for j, w in enumerate(worlds):
                    vals = (w[0] - 1,) + tuple(v[j] for _, v in parts)
                    vec.append(None if None in vals else table.get(vals))
                add_int(s, rec_call(arity, [t for t, _ in parts]), tuple(vec))
        for s1 in range(1, s - 1):
            for p, u in list(ints.get(s1, ())):
                for q, v in list(ints.get(s - 1 - s1, ())):
                    for op in ("+", "-", "*"):
                        vec = tuple(None if a is None or b is None else
                                    (a + b if op == "+" else a - b if op == "-" else a * b)
                                    for a, b in zip(u, v))
                        add_int(s, ("prim", op, p, q), vec)
                    for op in ("<", "=="):
                        vec = tuple(None if a is None or b is None else
                                    (a < b if op == "<" else a == b)
                                    for a, b in zip(u, v))
                        if None not in vec and vec not in seen_b:
                            seen_b.add(vec)
                            bools.append((("prim", op, p, q), vec))
    memo[key] = (ints, bools)
    return ints, bools


def _arg_tuples(ints, n, total):
    """All tuples of n kept int E-terms whose sizes add up to total."""
    if n == 0:
        if total == 0:
            yield ()
        return
    for s in range(1, total - n + 2):
        for t in list(ints.get(s, ())):
            for rest in _arg_tuples(ints, n - 1, total - s):
                yield (t,) + rest


def _refine(worlds, k, d, m, ctx):
    """A body of type int that fits all worlds, or None.

    worlds is a tuple of (args, out); m is "none" before the split on x < 1,
    "base" in its true branch and "step" in its false branch.
    """
    arity, table, memo = ctx
    args = tuple(a for a, _ in worlds)
    target = tuple(o for _, o in worlds)
    ints, bools = _bank(args, k, m == "step", arity, table, memo)
    for s in range(1, k + 1):  # @line L7
        for t, vec in ints.get(s, ()):
            if vec == target:
                return t  # @line L8
    if d == 0:  # @line L9
        return None
    if m == "none":  # @line L10
        w0 = tuple(w for w in worlds if w[0][0] < 1)
        w1 = tuple(w for w in worlds if w[0][0] >= 1)
        if w1:  # with no world in w0, any term fits the base branch
            e0 = _refine(w0, k, d - 1, "base", ctx)
            e1 = _refine(w1, k, d - 1, "step", ctx) if e0 is not None else None
            if e1 is not None:
                return ("if", guard(), e0, e1)  # @line L11
    for c, vec in bools:  # @line L12
        wt = tuple(w for w, b in zip(worlds, vec) if b)
        wf = tuple(w for w, b in zip(worlds, vec) if not b)
        if not wt or not wf:
            continue
        et = _refine(wt, k, d - 1, m, ctx)  # @line L13
        ef = _refine(wf, k, d - 1, m, ctx) if et is not None else None
        if ef is not None:
            return ("if", c, et, ef)  # @line L14
    return None  # @line L15


def synthesize(arity, examples, max_size=7, max_splits=2):
    """A term fix f x -> ... of type int -> ... -> int that meets the examples, or None.

    examples is a list of (args, out) with args a tuple of arity ints.
    """
    table = {tuple(a): o for a, o in examples}  # @line L1
    worlds = tuple((tuple(a), o) for a, o in examples)
    ctx = (arity, table, {})
    for k in range(1, max_size + 1):  # @line L2
        for d in range(0, max_splits + 1):  # @line L3
            body = _refine(worlds, k, d, "none", ctx)  # @line L4
            if body is not None:
                return wrap(arity, body)  # @line L5
    return None  # @line L6
test_type_directed_synthesis.py 217 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/type-directed-synthesis/. The authors are listed in prov/3WFWA4.jsonl.

import random

import toylam
from type_directed_synthesis import synthesize

INT, BOOL = ("int",), ("bool",)


def fun(a, b):
    return ("fun", a, b)


# Type inference for the toy language by unification, written for this test:
# toylam.py has the terms and the interpreter, but no inference.


class Infer:
    def __init__(self):
        self.sub = {}
        self.n = 0

    def fresh(self):
        self.n += 1
        return ("tv", self.n)

    def find(self, t):
        while t[0] == "tv" and t[1] in self.sub:
            t = self.sub[t[1]]
        return t

    def resolve(self, t):
        t = self.find(t)
        if t[0] == "fun":
            return fun(self.resolve(t[1]), self.resolve(t[2]))
        return t

    def occurs(self, v, t):
        t = self.find(t)
        if t[0] == "tv":
            return t[1] == v
        if t[0] == "fun":
            return self.occurs(v, t[1]) or self.occurs(v, t[2])
        return False

    def unify(self, a, b):
        a, b = self.find(a), self.find(b)
        if a == b:
            return
        if a[0] == "tv":
            if self.occurs(a[1], b):
                raise TypeError("occurs check")
            self.sub[a[1]] = b
            return
        if b[0] == "tv":
            self.unify(b, a)
            return
        if a[0] == "fun" and b[0] == "fun":
            self.unify(a[1], b[1])
            self.unify(a[2], b[2])
            return
        raise TypeError(f"cannot unify {a} and {b}")

    def infer(self, env, e):
        tag = e[0]
        if tag == "var":
            if e[1] not in env:
                raise TypeError(f"unbound {e[1]}")
            return env[e[1]]
        if tag == "int":
            return INT
        if tag == "bool":
            return BOOL
        if tag == "lam":
            a = self.fresh()
            return fun(a, self.infer({**env, e[1]: a}, e[2]))
        if tag == "app":
            tf = self.infer(env, e[1])
            ta = self.infer(env, e[2])
            r = self.fresh()
            self.unify(tf, fun(ta, r))
            return r
        if tag == "if":
            self.unify(self.infer(env, e[1]), BOOL)
            t = self.infer(env, e[2])
            self.unify(t, self.infer(env, e[3]))
            return t
        if tag == "prim":
            self.unify(self.infer(env, e[2]), INT)
            self.unify(self.infer(env, e[3]), INT)
            return INT if e[1] in ("+", "-", "*") else BOOL
        if tag == "fix":
            a, r = self.fresh(), self.fresh()
            self.unify(self.infer({**env, e[1]: fun(a, r), e[2]: a}, e[3]), r)
            return fun(a, r)
        raise TypeError(f"unsupported term {e!r}")


def type_of(e):
    inf = Infer()
    return toylam.normalize_type(inf.resolve(inf.infer({}, e)))


def has_type(e, t):
    """e type-checks at t: its inferred type unifies with t."""
    inf = Infer()
    inf.unify(inf.infer({}, e), t)
    return inf.resolve(t) == t


def goal_type(arity):
    t = INT
    for _ in range(arity):
        t = fun(INT, t)
    return t


def run(p, args):
    t = p
    for a in args:
        t = ("app", t, ("int", a))
    return toylam.evaluate(t, 200000)


def check(p, arity, examples):
    assert p is not None
    assert toylam.free_vars(p) == set()
    # The principal type is the goal type, or more general when an argument is unused.
    assert has_type(p, goal_type(arity)), toylam.show(p)
    for args, out in examples:
        assert run(p, args) == ("value", ("int", out)), (toylam.show(p), args, out)


def test_inference_itself():
    assert type_of(("lam", "x", ("var", "x"))) == fun(("tv", 0), ("tv", 0))
    assert type_of(("fix", "f", "x", ("prim", "+", ("var", "x"), ("int", 1)))) == fun(INT, INT)
    try:
        type_of(("prim", "+", ("bool", True), ("int", 1)))
        assert False
    except TypeError:
        pass


def test_classic_tasks():
    tasks = [
        (1, [((n,), n * (n + 1) // 2) for n in range(5)]),
        (1, [((0,), 1), ((1,), 1), ((2,), 2), ((3,), 6), ((4,), 24)]),
        (1, [((n,), 2 ** n) for n in range(5)]),
        (1, [((n,), sum(i * i for i in range(n + 1))) for n in range(5)]),
        (2, [((1, 2), 2), ((3, 1), 3), ((2, 2), 2), ((0, 5), 5), ((4, 0), 4)]),
    ]
    for arity, examples in tasks:
        check(synthesize(arity, examples), arity, examples)


def random_eterm(rng, size, leaves):
    if size <= 1:
        return rng.choice(leaves)
    s1 = rng.randrange(1, size - 1, 2) if size > 2 else 1
    return (rng.choice("+-*"), random_eterm(rng, s1, leaves), random_eterm(rng, size - 1 - s1, leaves))


def value(t, env):
    if isinstance(t, str):
        return env[t]
    a, b = value(t[1], env), value(t[2], env)
    return a + b if t[0] == "+" else a - b if t[0] == "-" else a * b


def test_random_recursive_targets():
    # f 0 = c and f n = g(n, f (n - 1)): trace complete examples on 0 .. 4.
    rng = random.Random(5)
    for _ in range(25):
        c = rng.choice((0, 1))
        g = random_eterm(rng, rng.choice((3, 5)), ["x", "r", "0", "1"])
        outs = [c]
        for n in range(1, 5):
            outs.append(value(g, {"x": n, "r": outs[-1], "0": 0, "1": 1}))
        examples = [((n,), outs[n]) for n in range(5)]
        check(synthesize(1, examples), 1, examples)


def test_random_conditional_targets():
    rng = random.Random(6)
    for _ in range(25):
        a = random_eterm(rng, 1, ["x", "y", "0", "1"])
        b = random_eterm(rng, 1, ["x", "y", "0", "1"])
        e1 = random_eterm(rng, rng.choice((1, 3)), ["x", "y", "0", "1"])
        e2 = random_eterm(rng, rng.choice((1, 3)), ["x", "y", "0", "1"])
        examples = []
        for _ in range(5):
            env = {"x": rng.randint(0, 4), "y": rng.randint(0, 4), "0": 0, "1": 1}
            out = value(e1, env) if value(a, env) < value(b, env) else value(e2, env)
            examples.append(((env["x"], env["y"]), out))
        table = {}
        for args, out in examples:
            table.setdefault(args, out)
        examples = sorted(table.items())
        check(synthesize(2, examples, max_size=5, max_splits=1), 2, examples)


def test_none_within_bounds():
    examples = [((n,), n ** 3) for n in range(5)]
    assert synthesize(1, examples, max_size=3, max_splits=0) is None
    check(synthesize(1, examples, max_size=5, max_splits=0), 1, examples)


def test_underspecified_fibonacci():
    # Fibonacci needs two recursive calls on n - 1 and n - 2, which are not in the
    # language. The search still meets every example, and differs from Fibonacci later.
    fib = [0, 1, 1, 2, 3, 5]
    examples = [((n,), fib[n]) for n in range(6)]
    p = synthesize(1, examples)
    check(p, 1, examples)
    assert run(p, (6,)) != ("value", ("int", 8))

History

Type inhabitation, the search for a term of a given type, is old: Statman (1979) showed that it is PSPACE-complete for simple types. Albarghouthi, Gulwani and Kincaid (2013) answered recursive calls from the examples in Escher. Osera and Zdancewic (2015) combined types and examples in Myth: examples move through the typing rules, elimination terms are guessed, and introduction forms and matches refine the goal. In the same year Feser, Chaudhuri and Dillig built λ² on typed higher-order combinators. Polikarpova, Kuraj and Solar-Lezama (2016) replaced the examples by refinement types in Synquid, which checks partial programs against the type as they grow.

References

  1. Peter-Michael Osera and Steve Zdancewic, Type-and-example-directed program synthesis, Programming Language Design and Implementation (PLDI 2015), pp. 619-630, the refinement of examples into worlds by the typing rules, the split into introduction and elimination terms, the match rule, structural recursion and trace completeness
  2. Nadia Polikarpova, Ivan Kuraj and Armando Solar-Lezama, Program synthesis from polymorphic refinement types, Programming Language Design and Implementation (PLDI 2016), pp. 522-538, Synquid, the round-trip type checking of partial programs against refinement types, with liquid type inference
  3. John K. Feser, Swarat Chaudhuri and Isil Dillig, Synthesizing data structure transformations from input-output examples, Programming Language Design and Implementation (PLDI 2015), pp. 229-239, hypotheses with holes typed by higher-order combinators, and deduction that rules out a hole from the examples
  4. Aws Albarghouthi, Sumit Gulwani and Zachary Kincaid, Recursive program synthesis, Computer Aided Verification (CAV 2013), pp. 934-950, recursive calls answered from the examples, and the closure condition on the examples
  5. Richard Statman, Intuitionistic propositional logic is polynomial-space complete, Theoretical Computer Science 9(1), 1979, pp. 67-72, the PSPACE-completeness of provability, and so of type inhabitation in the simply typed lambda calculus
  6. Sumit Gulwani, Oleksandr Polozov and Rishabh Singh, Program Synthesis, Foundations and Trends in Programming Languages 4(1-2), 2017, the parts on top-down enumeration and on type-directed search

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.one bank
  • a full proof of time.whole search
  • a full proof of space.whole search
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example