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
- Model
- Word RAM
- Properties
- deterministicrecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 with one to three arguments, and examples of argument tuples and outputs.
Output. A closed term of type in the toy language with for every example, or "none" if no program in the bounded space fits.
The space. The program is . A body is an E-term, or a conditional . An E-term is an argument, 0, 1, a sum, difference or product of E-terms, or a recursive call . A condition is or for E-terms, or the guard . The guard is the match of a natural number on zero and successor: a call of 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 counts 2 and each further argument counts its own size. The bounds are on the size of E-terms and conditions, and 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 is an example input, so are .
The algorithm
SYNTHESIZE(τ, examples)- 1
T ← the examples as a table from argument tuples to outputs - 2
for k = 1, 2, …, K do - 3
for d = 0, 1, …, D do - 4
B ← REFINE(the examples as worlds, k, d, none) - 5
if B ≠ none then return fix f x → fun y → … → B ▷ the introduction for the arrow type τ - 6
return none REFINE(W, k, d, m) ▷ m is none, base or step- 7
look 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 - 8
if one is found then return it - 9
if d = 0 then return none - 10
if 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) - 11
if both are found then return if x < 1 then B0 else B1 - 12
for each kept bool E-term c of size ≤ k that splits W into non-empty W⊤ and W⊥ do - 13
solve REFINE(W⊤, k, d - 1, m) and REFINE(W⊥, k, d - 1, m) - 14
if both are found then return if c then B⊤ else B⊥ - 15
return none
Introduction by the type (line L5). The goal type is an arrow, so the program must be an abstraction. With recursion it is , and further arguments add . Each example becomes a world: the values of 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 . 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 in a world is the output of the example in , 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 splits the worlds into base and step cases, and only the step branch may call . 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 , , , and , of type int int. They are trace complete.
- . The kept E-terms are , 0 and 1, with the vectors , and . None fits, and there are no conditions yet.
- . There are 11 kept E-terms and 6 conditions, and none of the E-terms gives . The guard splits the worlds into and . The base branch is fitted by . In the step branch has the vector , read from the examples, but no term of size 3 gives . The guessed conditions do not help either.
- , . In the step branch, has size 4 and the vector .
The result is
after 51 calls of REFINE. Type inference gives int int, and the interpreter gives 15 on 5 and 21 on 6. The code finds, in the same way, with base 1 from the values 1, 1, 2, 6, 24 of the factorial, from 0, 1, 5, 14, 30, and for two arguments 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 , which is not in the space. The search still meets all six examples. Below the guard it finds the condition , with in its true branch and 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 , 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 with arguments . The examples are pairs of an argument tuple of integers and an integer output, with no two examples for the same . is the table from to . 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, with , and the call with E-terms .
- Conditions of type bool: and for E-terms .
- Bodies: an E-term, or for a condition or for the guard .
The result is . On each path from the root of , the guard appears at most once, and a call of appears only below its false branch. The flag 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 and an argument tuple , let be the value of when the arguments are and a call gives if this tuple is in , and the marker otherwise. An operator with an argument gives . 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 kept by the bank on the worlds , its vector is . The bank keeps no condition with a entry.
Proof. By induction on the size of . Arguments and constants are read off directly. The vector of is computed entry by entry from the vectors of and , with if one entry is . The vector of a call is computed from the value and the vectors of by a lookup in , with for a tuple not in . Line L12 skips conditions with a entry, because the code does not keep them.
Theorem 1: the result type-checks at the goal type
Claim. If SYNTHESIZE returns , then has the type in the type system of the toy language.
Proof. Assume and . By induction on terms: arguments and constants are int; , , take two ints and give an int; and take two ints and give a bool; is an int, and applied to ints is an int; a conditional with a bool condition and two int branches is an int. So , the abstractions give in the scope of and , and the rule for fix gives . Hindley-Milner inference returns the principal type of , which is or, when an argument does not occur in , a more general type that has as an instance.
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 returns , then for every world .
Proof. By induction on . If comes from line L8, its vector equals the wanted outputs, and Lemma 1 gives the claim. If comes from line L11 or L14, the worlds where is true went to and the others to , by the vector of (Lemma 1, with no ), or by for the guard. By induction and meet their worlds, so meets all of .
Claim. If SYNTHESIZE returns , then for each example , running in the interpreter gives the value .
Proof. By Lemma 2 with = all examples, for every example. Now show by induction on that the interpreter gives . The real run of on differs from only at calls of . A call happens only in the branch where is false, so , and its first argument is . Since , every call whose value is used gives a tuple that is in , so is an example with a smaller first argument. By induction the real call returns . So the real run computes the same values as and returns . The interpreter is call by value, so it also evaluates calls in E-terms whose value is used.
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 entry and cannot be found.
Theorem 3: the result terminates on every input
Claim. For all integers , the run of stops.
Proof. By induction on . Apart from calls of , the body is a finite term of operators and conditionals, so it takes finitely many steps. If , 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 , each call has the first argument , and , so each call stops by induction.
Theorem 4: completeness for the bounded space
Claim. Let a body exist with for all worlds of , whose E-terms and conditions have size at most , with at most nested conditionals, and which respects the flag . Then REFINE returns a body.
Proof. By induction on the number of conditionals in . If is an E-term, the bank keeps, by the lemma of bottom-up enumerative synthesis, an E-term of size at most 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 and .
- The guard, = none. Line L10 makes the same split, also when no world has ; then any term fits the empty base branch. By induction REFINE finds bodies for the two sides with depth , because fits the first side with flag "base" and 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 , alone fits with the same flag and fewer conditionals, and its depth is at most . By induction REFINE 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.
So with trace complete examples, SYNTHESIZE returns a result whenever a body with E-terms of size at most and at most nested conditionals meets the examples. It tries the pairs in the order of lines L2 and L3, so the result has the least among such bodies, and the least for that .
Complexity
Let be the number of kept E-terms in one bank, the number of examples, and the bound on nested conditionals. A bank combines pairs of kept terms, at per vector, so it takes time and space. A call of REFINE tries the guard and up to conditions, each with two recursive calls, so the search tree has nodes. Each node builds a bank for its set of worlds, and banks are shared between equal sets. The worst case is time for one pair . The number is bounded by the number of distinct vectors and grows exponentially with .
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 .
- 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 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 keeps the result total on negative inputs, but the examples say nothing about them.
- Growth with the size bound. Each step of can multiply the bank, and each level of 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.
# 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
- 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3WFWA4 Edit this page History Report an error Markdown