gdp-wired 0.31.1 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/check.js +20 -6
- package/dist/core/cli.d.ts +76 -0
- package/dist/core/cli.js +636 -0
- package/dist/core/dsl.d.ts +6 -4
- package/dist/core/dsl.js +30 -16
- package/dist/core/effect.d.ts +6 -4
- package/dist/core/effect.js +48 -10
- package/dist/core/ex/harness.exs +177 -0
- package/dist/core/ex/json.exs +46 -0
- package/dist/core/ex/reader.exs +462 -0
- package/dist/core/exists.d.ts +3 -0
- package/dist/core/exists.js +19 -5
- package/dist/core/extract-c.d.ts +35 -0
- package/dist/core/extract-c.js +424 -0
- package/dist/core/extract-check.js +27 -6
- package/dist/core/extract-ex.d.ts +16 -0
- package/dist/core/extract-ex.js +33 -0
- package/dist/core/extract-go-check.d.ts +28 -0
- package/dist/core/extract-go-check.js +639 -0
- package/dist/core/extract-go.d.ts +231 -0
- package/dist/core/extract-go.js +1166 -0
- package/dist/core/extract-jvm.d.ts +23 -0
- package/dist/core/extract-jvm.js +220 -0
- package/dist/core/extract-print.js +17 -7
- package/dist/core/extract-py.d.ts +15 -0
- package/dist/core/extract-py.js +31 -0
- package/dist/core/extract-rb.d.ts +17 -0
- package/dist/core/extract-rb.js +31 -0
- package/dist/core/extract-read.d.ts +20 -0
- package/dist/core/extract-read.js +46 -6
- package/dist/core/extract-rs.d.ts +12 -0
- package/dist/core/extract-rs.js +306 -0
- package/dist/core/extract-shapes.d.ts +2 -0
- package/dist/core/extract-shapes.js +6 -5
- package/dist/core/extract-step.d.ts +806 -0
- package/dist/core/extract-step.js +4141 -0
- package/dist/core/extract-swift.d.ts +27 -0
- package/dist/core/extract-swift.js +484 -0
- package/dist/core/extract-xstate.d.ts +10 -3
- package/dist/core/extract-xstate.js +50 -4
- package/dist/core/extract.d.ts +22 -3
- package/dist/core/extract.js +107 -18
- package/dist/core/go/go.mod +3 -0
- package/dist/core/go/reader.go +901 -0
- package/dist/core/infer.d.ts +4 -0
- package/dist/core/infer.js +1838 -69
- package/dist/core/jvm/Harness.java +361 -0
- package/dist/core/jvm/JavaReader.java +825 -0
- package/dist/core/jvm/Jvm.java +332 -0
- package/dist/core/jvm/KtReader.java +960 -0
- package/dist/core/jvm/Rt.java +10 -0
- package/dist/core/laws.d.ts +83 -0
- package/dist/core/laws.js +623 -0
- package/dist/core/machine.d.ts +2 -0
- package/dist/core/machine.js +87 -0
- package/dist/core/py/harness.py +328 -0
- package/dist/core/py/reader.py +447 -0
- package/dist/core/rb/harness.rb +233 -0
- package/dist/core/rb/reader.rb +375 -0
- package/dist/core/relational.d.ts +49 -0
- package/dist/core/relational.js +345 -0
- package/dist/core/rs/Cargo.lock +108 -0
- package/dist/core/rs/Cargo.toml +14 -0
- package/dist/core/rs/src/main.rs +681 -0
- package/dist/core/swift/Harness.swift +124 -0
- package/dist/core/swift/Main.swift +34 -0
- package/dist/core/swift/Package.swift +13 -0
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
- package/dist/interchange/check.d.ts +16 -0
- package/dist/interchange/check.js +111 -0
- package/dist/interchange/format.d.ts +150 -0
- package/dist/interchange/format.js +678 -0
- package/dist/kernel/epr.d.ts +40 -0
- package/dist/kernel/epr.js +1882 -0
- package/dist/kernel/kernel.d.ts +45 -1
- package/dist/kernel/kernel.js +138 -13
- package/dist/kernel/prove.d.ts +45 -0
- package/dist/kernel/prove.js +658 -51
- package/dist/lean-kernel/emit.d.ts +17 -2
- package/dist/lean-kernel/emit.js +87 -7
- package/package.json +57 -2
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
# The extractor's Elixir reader (core/extract-ex.ts): a module read through Elixir's own parser (Code.string_to_quoted)
|
|
2
|
+
# and lowered into the shared step IR (core/extract-step.ts's SModule, as JSON on stdout). Elixir's state is a value a
|
|
3
|
+
# function returns: a GenServer's handle_call ({:reply, r, state}) and handle_cast ({:noreply, state}), an Agent's
|
|
4
|
+
# update and get, or a plain function from the state to the new one. The reader lowers each to the executor's own
|
|
5
|
+
# shape, an object whose fields are the state's: the state a handler is given is the object, the one it returns is
|
|
6
|
+
# written back to its fields, field by field. Function clauses, case and cond are branches on their patterns and
|
|
7
|
+
# guards; a field's type is inferred from its default and what the module puts in it, an argument's from what it is
|
|
8
|
+
# compared with or computed into. Only nil and false are false.
|
|
9
|
+
#
|
|
10
|
+
# elixir core/ex/reader.exs '{"file": <file>, "module": "Mod.Name"}'
|
|
11
|
+
Code.require_file("json.exs", __DIR__)
|
|
12
|
+
|
|
13
|
+
defmodule GdpReader do
|
|
14
|
+
@arith %{+: "+", -: "-", *: "*"}
|
|
15
|
+
@cmp %{<: "<", <=: "<=", >: ">", >=: ">=", ==: "==", !=: "!=", ===: "==", !==: "!="}
|
|
16
|
+
@clock [{[:System], :monotonic_time}, {[:System], :system_time}, {[:System], :os_time}, {[:DateTime], :utc_now}, {:os, :system_time}, {:erlang, :system_time}, {:erlang, :monotonic_time}]
|
|
17
|
+
|
|
18
|
+
def run(req) do
|
|
19
|
+
file = req["file"]
|
|
20
|
+
src = File.read!(file)
|
|
21
|
+
ast = Code.string_to_quoted!(src, columns: true, file: file)
|
|
22
|
+
base = Path.basename(file)
|
|
23
|
+
Process.put(:base, base)
|
|
24
|
+
mods = modules(ast, [])
|
|
25
|
+
# (no name: the file's one module, or its one GenServer or Agent: the entry inferred)
|
|
26
|
+
name = req["module"] || (case Enum.filter(mods, fn {_, b} -> length(mods) == 1 or Enum.any?(b, &match?({:use, _, [{:__aliases__, _, [k]} | _]} when k in [:GenServer, :Agent], &1)) end) do [{n, _}] -> n; _ -> "" end)
|
|
27
|
+
case Enum.find(mods, fn {n, _} -> n == name end) || Enum.find(mods, fn {n, _} -> String.ends_with?(n, "." <> name) end) do
|
|
28
|
+
nil -> %{"lang" => "elixir", "file" => base, "path" => Path.expand(file), "module" => name, "root" => Path.dirname(Path.expand(file)), "entries" => [%{"k" => "missing", "name" => name}], "recs" => %{}, "funcs" => %{}}
|
|
29
|
+
{q, body} -> lower(q, body, file, base)
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
defp modules({:defmodule, _, [alias, [do: body]]}, nest) do
|
|
34
|
+
q = Enum.join(nest ++ [alias_name(alias)], ".")
|
|
35
|
+
[{q, stmts(body)} | Enum.flat_map(stmts(body), &modules(&1, nest ++ [alias_name(alias)]))]
|
|
36
|
+
end
|
|
37
|
+
defp modules({:__block__, _, xs}, nest), do: Enum.flat_map(xs, &modules(&1, nest))
|
|
38
|
+
defp modules(_, _), do: []
|
|
39
|
+
defp alias_name({:__aliases__, _, parts}), do: Enum.map_join(parts, ".", &to_string/1)
|
|
40
|
+
defp alias_name(a) when is_atom(a), do: inspect(a)
|
|
41
|
+
defp stmts({:__block__, _, xs}), do: xs
|
|
42
|
+
defp stmts(nil), do: []
|
|
43
|
+
defp stmts(x), do: [x]
|
|
44
|
+
|
|
45
|
+
def p(meta), do: "#{Process.get(:base)}:#{meta[:line] || 0}:#{meta[:column] || 0}"
|
|
46
|
+
def text(x), do: (s = x |> Macro.to_string() |> String.split() |> Enum.join(" "); if String.length(s) <= 60, do: s, else: String.slice(s, 0, 57) <> "...")
|
|
47
|
+
def meta({_, m, _}) when is_list(m), do: m
|
|
48
|
+
def meta(_), do: []
|
|
49
|
+
def no(x, why), do: %{"e" => "no", "why" => why, "p" => p(meta(x))}
|
|
50
|
+
|
|
51
|
+
# --- the module: its state, its handlers ---------------------------------------------------------------------------
|
|
52
|
+
defp lower(q, body, file, base) do
|
|
53
|
+
defs = for {k, m, [head, [do: b]]} <- body, k in [:def, :defp] do
|
|
54
|
+
{name, args, guard} = head_of(head)
|
|
55
|
+
{name, length(args), %{args: args, guard: guard, body: b, meta: m, private: k == :defp}}
|
|
56
|
+
end
|
|
57
|
+
defs = defs ++ for {k, m, [head]} <- body, k in [:def, :defp], {name, args, _} = head_of(head), do: {name, length(args), %{args: args, guard: nil, body: nil, meta: m, bodiless: true}}
|
|
58
|
+
attrs = for {:@, _, [{n, _, [v]}]} <- body, into: %{}, do: {n, v}
|
|
59
|
+
Process.put(:attrs, attrs)
|
|
60
|
+
Process.put(:mod, q)
|
|
61
|
+
struct_kw = Enum.find_value(body, fn {:defstruct, _, [kw]} -> kw; _ -> nil end)
|
|
62
|
+
groups = Enum.group_by(defs, fn {n, a, _} -> {n, a} end, fn {_, _, c} -> c end) |> Enum.map(fn {k, cs} -> {k, Enum.reject(cs, & &1[:bodiless])} end) |> Map.new()
|
|
63
|
+
Process.put(:groups, groups)
|
|
64
|
+
Process.put(:body, body)
|
|
65
|
+
shape = cond do
|
|
66
|
+
Map.has_key?(groups, {:handle_call, 3}) or Map.has_key?(groups, {:handle_cast, 2}) -> :genserver
|
|
67
|
+
Enum.any?(defs, fn {_, _, c} -> agent_call(c.body) != nil end) -> :agent
|
|
68
|
+
true -> :pure
|
|
69
|
+
end
|
|
70
|
+
{fields, init} = state_of(shape, struct_kw, groups)
|
|
71
|
+
Process.put(:fields, Enum.map(fields, &elem(&1, 0)))
|
|
72
|
+
Process.put(:struct, Map.new(fields))
|
|
73
|
+
fns = for {{n, a}, cs} <- groups, n not in [:handle_call, :handle_cast, :init] and cs != [], into: %{}, do: {"#{q}.#{n}/#{a}", func("#{q}.#{n}/#{a}", to_string(n), a, cs, :ret)}
|
|
74
|
+
{methods, msgs, mfns} = handlers(shape, q, groups)
|
|
75
|
+
types = infer(fields, body)
|
|
76
|
+
rec = %{"name" => q, "short" => q |> String.split(".") |> List.last(), "fields" => Enum.map(fields, fn {f, _} -> %{"name" => to_string(f), "t" => Map.get(types, f, %{"k" => "any"})} end),
|
|
77
|
+
"methods" => Map.put(methods, "__init__", "#{q}.__init__"),
|
|
78
|
+
"kinds" => [], "own" => true, "module" => q, "p" => "#{base}:1:1"}
|
|
79
|
+
funcs = fns |> Map.merge(mfns) |> Map.put("#{q}.__init__", init.(q))
|
|
80
|
+
%{"lang" => "elixir", "file" => base, "path" => Path.expand(file), "module" => q, "root" => Path.dirname(Path.expand(file)), "truth" => "nil-false", "shape" => to_string(shape), "msgs" => msgs,
|
|
81
|
+
"init" => Process.get(:init_shape, %{}), "entries" => [%{"k" => "class", "rec" => q}], "recs" => %{q => rec}, "funcs" => funcs}
|
|
82
|
+
end
|
|
83
|
+
defp head_of({:when, _, [{n, _, args}, g]}), do: {n, args || [], g}
|
|
84
|
+
defp head_of({n, _, args}), do: {n, args || [], nil}
|
|
85
|
+
|
|
86
|
+
# The state's fields and the constructor: a GenServer's init's {:ok, %{...}}, else the struct's defaults.
|
|
87
|
+
defp state_of(:genserver, kw, groups) do
|
|
88
|
+
case groups[{:init, 1}] do
|
|
89
|
+
[c | _] ->
|
|
90
|
+
{arg_names, shape} = case c.args do
|
|
91
|
+
[{:{}, _, xs}] -> {Enum.map(xs, &var_name/1), "tuple"}
|
|
92
|
+
[{a, b}] -> {[var_name(a), var_name(b)], "tuple"}
|
|
93
|
+
[x] -> {[var_name(x)], "one"}
|
|
94
|
+
end
|
|
95
|
+
Process.put(:init_shape, %{"k" => shape, "names" => Enum.map(arg_names, &to_string/1)})
|
|
96
|
+
m = Enum.find_value(stmts(c.body) |> Enum.reverse(), fn {:ok, {:%{}, _, kv}} -> kv; {:ok, {:%, _, [_, {:%{}, _, kv}]}} -> kv; _ -> nil end)
|
|
97
|
+
if m == nil, do: {[], fn q -> fn_of("#{q}.__init__", "init", [], [%{"s" => "no", "p" => p(c.meta), "why" => "init: a state other than a map literal returned as {:ok, %{...}}"}]) end},
|
|
98
|
+
else: {Enum.map(m, fn {k, v} -> {k, v} end), fn q ->
|
|
99
|
+
pre = Enum.flat_map(Enum.reverse(tl(Enum.reverse(stmts(c.body)))), &stmt(&1, :expr))
|
|
100
|
+
# (an argument kept in a field: the field's type)
|
|
101
|
+
ftype = fn n -> Enum.find_value(m, fn {k, {^n, _, c}} when is_atom(c) -> Map.get(spec_types(Process.get(:body)), k); _ -> nil end) end
|
|
102
|
+
params = for n <- arg_names, not String.starts_with?(to_string(n), "_"), do: %{"name" => to_string(n), "t" => ftype.(n) || int_use(n)}
|
|
103
|
+
fn_of("#{q}.__init__", "init", params, pre ++ Enum.map(m, fn {k, v} -> set_field(k, expr(v), c.meta) end))
|
|
104
|
+
end}
|
|
105
|
+
_ -> {struct_fields(kw), struct_init(kw)}
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
defp state_of(_, kw, _), do: {struct_fields(kw), struct_init(kw)}
|
|
109
|
+
defp struct_fields(nil), do: []
|
|
110
|
+
defp struct_fields(kw), do: Enum.map(kw, fn {k, v} -> {k, v}; k -> {k, nil} end)
|
|
111
|
+
defp struct_init(kw), do: fn q -> fn_of("#{q}.__init__", "new", [], Enum.map(struct_fields(kw), fn {k, v} -> set_field(k, expr(v), []) end)) end
|
|
112
|
+
defp var_name({n, _, ctx}) when is_atom(n) and is_atom(ctx), do: n
|
|
113
|
+
defp var_name(_), do: :_
|
|
114
|
+
|
|
115
|
+
# --- the handlers: each message (or Agent function, or plain function) a method --------------------------------------
|
|
116
|
+
defp handlers(:genserver, q, groups) do
|
|
117
|
+
for {kind, ar} <- [{:handle_call, 3}, {:handle_cast, 2}], cs = groups[{kind, ar}] || [], cs != [], reduce: {%{}, %{}, %{}} do
|
|
118
|
+
{ms, msgs, fs} ->
|
|
119
|
+
by = Enum.group_by(cs, fn c -> msg_key(hd(c.args)) end)
|
|
120
|
+
Enum.reduce(by, {ms, msgs, fs}, fn {{tag, n}, ccs}, {ms, msgs, fs} ->
|
|
121
|
+
name = if Enum.count(by, fn {{t, _}, _} -> t == tag end) > 1 and n > 0, do: "#{tag}_#{n}", else: to_string(tag)
|
|
122
|
+
fid = "#{q}.#{kind}:#{name}"
|
|
123
|
+
params = arg_names(msg_args(hd(hd(ccs).args)), "m")
|
|
124
|
+
# (a handler's atom replies: one choice)
|
|
125
|
+
Process.put(:replies, for(c <- ccs, {:reply, r, _} <- stmts_tails(c.body), is_atom(r) and not is_boolean(r) and r != nil, uniq: true, do: Atom.to_string(r)))
|
|
126
|
+
body = clauses(ccs, Enum.map(params, &var/1), fn c -> [msg_args(hd(c.args)), List.last(c.args)] end, if(kind == :handle_call, do: :reply, else: :noreply), "#{kind} #{name}")
|
|
127
|
+
{Map.put(ms, name, fid), Map.put(msgs, name, %{"kind" => to_string(kind), "tag" => to_string(tag), "n" => n, "atom" => is_atom(hd(hd(ccs).args))}),
|
|
128
|
+
Map.put(fs, fid, fn_of(fid, name, Enum.zip(params, arg_types(msg_args(hd(hd(ccs).args)))) |> Enum.map(fn {n2, t} -> %{"name" => n2, "t" => t} end), body))}
|
|
129
|
+
end)
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
defp handlers(:agent, q, groups) do
|
|
133
|
+
for {{n, a}, [c | _] = cs} <- groups, !c.private, (ag = agent_call(c.body)) != nil, reduce: {%{}, %{}, %{}} do
|
|
134
|
+
{ms, msgs, fs} ->
|
|
135
|
+
{op, fun} = ag
|
|
136
|
+
{:fn, _, [{:->, _, [[sv], fb]}]} = fun
|
|
137
|
+
[pid | rest] = c.args
|
|
138
|
+
# (an argument that defaults to nil, of no type the code states: its default, the harness giving none)
|
|
139
|
+
{given, nils} = Enum.split_with(rest, fn {:\\, _, [_, nil]} -> false; _ -> true end)
|
|
140
|
+
params = Enum.map(given, fn {:\\, _, [v, _]} -> var_name(v); v -> var_name(v) end)
|
|
141
|
+
pre = Enum.map(nils, fn {:\\, _, [v, _]} -> %{"s" => "set", "p" => "#{Process.get(:base)}:0:0", "to" => var(to_string(var_name(v))), "x" => %{"e" => "none", "p" => p(c.meta)}} end)
|
|
142
|
+
bind = %{"s" => "set", "p" => "#{Process.get(:base)}:0:0", "to" => var(to_string(var_name(sv))), "x" => var("self")}
|
|
143
|
+
_ = {pid, cs}
|
|
144
|
+
body = pre ++ [bind] ++ block(stmts(fb), if(op == :update, do: :state, else: :ret))
|
|
145
|
+
fid = "#{q}.#{n}/#{a}"
|
|
146
|
+
{Map.put(ms, to_string(n), fid), Map.put(msgs, to_string(n), %{"kind" => "agent", "fun" => to_string(n), "n" => length(params)}),
|
|
147
|
+
Map.put(fs, fid, fn_of(fid, to_string(n), Enum.map(params, &%{"name" => to_string(&1), "t" => param_type(to_string(&1), fb)}), body))}
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
defp handlers(:pure, q, groups) do
|
|
151
|
+
for {{n, a}, [c | _] = cs} <- groups, !c.private, a >= 1, reduce: {%{}, %{}, %{}} do
|
|
152
|
+
{ms, msgs, fs} ->
|
|
153
|
+
params = tl(arg_names({:{}, [], c.args}, "a"))
|
|
154
|
+
fid = "#{q}.#{n}/#{a}"
|
|
155
|
+
body = clauses(cs, [var("self") | Enum.map(params, &var/1)], & &1.args, :pure, "#{n}/#{a}")
|
|
156
|
+
{Map.put(ms, to_string(n), fid), Map.put(msgs, to_string(n), %{"kind" => "pure", "fun" => to_string(n), "n" => a - 1}),
|
|
157
|
+
Map.put(fs, fid, fn_of(fid, to_string(n), Enum.zip(params, tl(arg_types({:{}, [], c.args}))) |> Enum.map(fn {n2, t} -> %{"name" => n2, "t" => t} end), body))}
|
|
158
|
+
end
|
|
159
|
+
end
|
|
160
|
+
# The names of a clause's arguments: its variables', else a#i.
|
|
161
|
+
defp arg_names({:{}, _, xs}, pre), do: xs |> Enum.with_index(1) |> Enum.map(fn {x, i} -> nm = to_string(var_name(x)); if String.starts_with?(nm, "_"), do: "#{pre}#{i}", else: nm end)
|
|
162
|
+
# The tails a body may end in (through if, case and cond).
|
|
163
|
+
defp stmts_tails(b) do
|
|
164
|
+
case stmts(b) |> List.last() do
|
|
165
|
+
{:if, _, [_, kw]} -> stmts_tails(kw[:do]) ++ stmts_tails(kw[:else])
|
|
166
|
+
{:case, _, [_, [do: cs]]} -> Enum.flat_map(cs, fn {:->, _, [_, x]} -> stmts_tails(x) end)
|
|
167
|
+
{:cond, _, [[do: cs]]} -> Enum.flat_map(cs, fn {:->, _, [_, x]} -> stmts_tails(x) end)
|
|
168
|
+
{:{}, _, [:reply, r, st]} -> [{:reply, r, st}]
|
|
169
|
+
x -> [x]
|
|
170
|
+
end
|
|
171
|
+
end
|
|
172
|
+
# The types of a clause's arguments: each variable's by its name's use in the module (a literal: none needed).
|
|
173
|
+
defp arg_types({:{}, _, xs}), do: Enum.map(xs, fn x -> case var_name(x) do :_ -> %{"k" => "any"}; n -> int_use(n) end end)
|
|
174
|
+
defp agent_call(b) do
|
|
175
|
+
case stmts(b) |> List.last() do
|
|
176
|
+
{{:., _, [{:__aliases__, _, [:Agent]}, op]}, _, [_, {:fn, _, _} = f]} when op in [:update, :get] -> {op, f}
|
|
177
|
+
_ -> nil
|
|
178
|
+
end
|
|
179
|
+
end
|
|
180
|
+
defp msg_key(a) when is_atom(a), do: {a, 0}
|
|
181
|
+
defp msg_key({a, _}) when is_atom(a), do: {a, 1}
|
|
182
|
+
defp msg_key({:{}, _, [a | r]}) when is_atom(a), do: {a, length(r)}
|
|
183
|
+
defp msg_key(_), do: {:other, 0}
|
|
184
|
+
defp msg_args(a) when is_atom(a), do: {:{}, [], []}
|
|
185
|
+
defp msg_args({_, x}), do: {:{}, [], [x]}
|
|
186
|
+
defp msg_args({:{}, m, [_ | r]}), do: {:{}, m, r}
|
|
187
|
+
|
|
188
|
+
# Clauses: each one's patterns matched (bindings, then its conditions and guard), the first that matches taken.
|
|
189
|
+
defp clauses(cs, subjects, pats_of, sink, what) do
|
|
190
|
+
Enum.reduce(Enum.reverse(cs), [%{"s" => "fail", "p" => "#{Process.get(:base)}:0:0", "why" => "no clause of #{what} matches (a FunctionClauseError)"}], fn c, rest ->
|
|
191
|
+
pats = pats_of.(c)
|
|
192
|
+
pats = case pats do [{:{}, _, xs}, st] -> Enum.zip(xs, subjects) ++ [{st, var("self")}]; _ -> Enum.zip(pats, subjects) end
|
|
193
|
+
{binds, conds} = Enum.reduce(pats, {[], []}, fn {pat, sub}, {b, k} -> {b2, k2} = match(pat, sub); {b ++ b2, k ++ k2} end)
|
|
194
|
+
conds = conds ++ if(c.guard, do: [expr(c.guard)], else: [])
|
|
195
|
+
body = block(stmts(c.body), sink)
|
|
196
|
+
binds ++ if(conds == [], do: body, else: [%{"s" => "if", "p" => "#{Process.get(:base)}:0:0", "c" => %{"e" => "and", "xs" => conds, "p" => p(c.meta)}, "then" => body, "else" => rest}])
|
|
197
|
+
end)
|
|
198
|
+
end
|
|
199
|
+
# A pattern against a value: the names it binds and the conditions it tests.
|
|
200
|
+
defp match({:_, _, _}, _), do: {[], []}
|
|
201
|
+
defp match({:=, _, [a, b]}, s) do
|
|
202
|
+
{b1, k1} = match(a, s)
|
|
203
|
+
{b2, k2} = match(b, s)
|
|
204
|
+
{b1 ++ b2, k1 ++ k2}
|
|
205
|
+
end
|
|
206
|
+
defp match({:^, _, [v]}, s), do: {[], [%{"e" => "cmp", "op" => "==", "x" => s, "y" => expr(v), "p" => p(meta(v)), "text" => text(v)}]}
|
|
207
|
+
defp match({n, m, ctx} = v, s) when is_atom(n) and is_atom(ctx) do
|
|
208
|
+
_ = v
|
|
209
|
+
if String.starts_with?(to_string(n), "_"), do: {[], []}, else: {[%{"s" => "set", "p" => p(m), "to" => var(to_string(n)), "x" => s}], []}
|
|
210
|
+
end
|
|
211
|
+
defp match({:%{}, _, kv}, s), do: match_kv(kv, s)
|
|
212
|
+
defp match({:%, _, [_, {:%{}, _, kv}]}, s), do: match_kv(kv, s)
|
|
213
|
+
defp match(lit, s) when is_integer(lit) or is_atom(lit) or is_binary(lit) do
|
|
214
|
+
{[], [if(lit == nil, do: %{"e" => "cmp", "op" => "is", "x" => s, "y" => %{"e" => "none", "p" => s["p"]}, "p" => s["p"], "text" => inspect(lit)}, else: %{"e" => "cmp", "op" => "==", "x" => s, "y" => expr(lit), "p" => s["p"], "text" => inspect(lit)})]}
|
|
215
|
+
end
|
|
216
|
+
defp match(pat, s), do: {[], [no(pat, "#{text(pat)}: a pattern outside the subset") |> Map.put("p", s["p"])]}
|
|
217
|
+
defp match_kv(kv, s), do: Enum.reduce(kv, {[], []}, fn {k, pat}, {b, c} -> {b2, c2} = match(pat, get(s, k, [])); {b ++ b2, c ++ c2} end)
|
|
218
|
+
|
|
219
|
+
# --- statements: the last expression's value goes to the sink ------------------------------------------------------
|
|
220
|
+
# :ret (a function's result), :reply ({:reply, r, state}: the state written, r the result), :noreply, :state (an
|
|
221
|
+
# Agent's update: the new state), :pure (a plain function's: the new state, {:ok, state} too; {:error, _} fails).
|
|
222
|
+
def block([], sink), do: tail(nil, sink, [])
|
|
223
|
+
def block(xs, sink) do
|
|
224
|
+
{init, [last]} = Enum.split(xs, -1)
|
|
225
|
+
Enum.flat_map(init, &stmt(&1, :expr)) ++ stmt(last, sink)
|
|
226
|
+
end
|
|
227
|
+
def stmt({:=, m, [pat, v]}, sink) do
|
|
228
|
+
{binds, conds} = match(pat, expr(v))
|
|
229
|
+
tmp = if(conds == [], do: [], else: [%{"s" => "if", "p" => p(m), "c" => %{"e" => "and", "xs" => conds, "p" => p(m)}, "then" => [], "else" => [%{"s" => "fail", "p" => p(m), "why" => "#{text(pat)} doesn't match (a MatchError)"}]}])
|
|
230
|
+
binds ++ tmp ++ if(sink == :expr, do: [], else: tail(pat, sink, m))
|
|
231
|
+
end
|
|
232
|
+
def stmt({:if, m, [c, kw]}, sink) when sink != :expr or true do
|
|
233
|
+
[%{"s" => "if", "p" => p(m), "c" => expr(c), "then" => block(stmts(kw[:do]), sink), "else" => block(stmts(kw[:else]), sink)}]
|
|
234
|
+
end
|
|
235
|
+
def stmt({:unless, m, [c, kw]}, sink), do: stmt({:if, m, [{:!, m, [c]}, kw]}, sink)
|
|
236
|
+
def stmt({:cond, m, [[do: cs]]}, sink) do
|
|
237
|
+
Enum.reduce(Enum.reverse(cs), [%{"s" => "fail", "p" => p(m), "why" => "no cond clause is true (a CondClauseError)"}], fn {:->, cm, [[c], b]}, rest ->
|
|
238
|
+
if c == true, do: block(stmts(b), sink), else: [%{"s" => "if", "p" => p(cm), "c" => expr(c), "then" => block(stmts(b), sink), "else" => rest}]
|
|
239
|
+
end)
|
|
240
|
+
end
|
|
241
|
+
def stmt({:case, m, [x, [do: cs]]}, sink) do
|
|
242
|
+
tmp = "$case#{m[:line]}_#{m[:column]}"
|
|
243
|
+
[%{"s" => "set", "p" => p(m), "to" => var(tmp), "x" => expr(x)}] ++
|
|
244
|
+
Enum.reduce(Enum.reverse(cs), [%{"s" => "fail", "p" => p(m), "why" => "no case clause matches (a CaseClauseError)"}], fn {:->, cm, [[pat], b]}, rest ->
|
|
245
|
+
{pat, guard} = case pat do {:when, _, [pt, g]} -> {pt, g}; pt -> {pt, nil} end
|
|
246
|
+
{binds, conds} = match(pat, var(tmp))
|
|
247
|
+
conds = conds ++ if(guard, do: [expr(guard)], else: [])
|
|
248
|
+
binds ++ if(conds == [], do: block(stmts(b), sink), else: [%{"s" => "if", "p" => p(cm), "c" => %{"e" => "and", "xs" => conds, "p" => p(cm)}, "then" => block(stmts(b), sink), "else" => rest}])
|
|
249
|
+
end)
|
|
250
|
+
end
|
|
251
|
+
def stmt({:raise, m, _} = x, _), do: [%{"s" => "fail", "p" => p(m), "why" => text(x)}]
|
|
252
|
+
def stmt({:__block__, _, xs}, sink), do: block(xs, sink)
|
|
253
|
+
def stmt(x, :expr), do: [%{"s" => "expr", "p" => p(meta(x)), "x" => expr(x)}]
|
|
254
|
+
def stmt(x, sink), do: tail(x, sink, meta(x))
|
|
255
|
+
# The value at the end of a handler, to its sink.
|
|
256
|
+
def tail(_, :expr, _), do: []
|
|
257
|
+
def tail(x, :ret, m), do: [%{"s" => "ret", "p" => p(m), "x" => if(x == nil, do: %{"e" => "none", "p" => p(m)}, else: expr(x))}]
|
|
258
|
+
# (the reply evaluated before the state is written back: it reads the state the handler was given)
|
|
259
|
+
def tail({:reply, r, st}, :reply, m), do: [%{"s" => "set", "p" => p(m), "to" => var("$reply"), "x" => reply(r)} | write_state(st, m)] ++ [%{"s" => "ret", "p" => p(m), "x" => var("$reply")}]
|
|
260
|
+
def tail({:{}, _, [:reply, r, st]}, :reply, m), do: tail({:reply, r, st}, :reply, m)
|
|
261
|
+
defp reply(r) do
|
|
262
|
+
rs = Process.get(:replies) || []
|
|
263
|
+
if is_atom(r) and length(rs) > 1 and Atom.to_string(r) in rs, do: %{"e" => "variant", "v" => Atom.to_string(r), "values" => rs, "p" => "#{Process.get(:base)}:0:0"}, else: expr(r)
|
|
264
|
+
end
|
|
265
|
+
def tail({:noreply, st}, sink, m) when sink in [:reply, :noreply], do: write_state(st, m) ++ [%{"s" => "ret", "p" => p(m)}]
|
|
266
|
+
def tail({:ok, st}, :pure, m), do: write_state(st, m) ++ [%{"s" => "ret", "p" => p(m)}]
|
|
267
|
+
def tail({:error, e}, :pure, m), do: [%{"s" => "fail", "p" => p(m), "why" => "{:error, #{text(e)}} returned"}]
|
|
268
|
+
def tail(st, sink, m) when sink in [:state, :pure], do: write_state(st, m) ++ [%{"s" => "ret", "p" => p(m)}]
|
|
269
|
+
def tail(x, sink, m) when sink in [:reply, :noreply] do
|
|
270
|
+
# (a handler's tuple made elsewhere, by a function of the module: taken apart where it returns)
|
|
271
|
+
tmp = "$tail#{m[:line]}_#{m[:column]}"
|
|
272
|
+
ks = if sink == :reply, do: ["$tag", "$r", tmp], else: ["$tag", tmp]
|
|
273
|
+
[%{"s" => "set", "p" => p(m), "to" => %{"e" => "tuple", "xs" => Enum.map(ks, &var/1), "p" => p(m)}, "x" => expr(x)}] ++ write_state({String.to_atom(tmp), [], nil}, m) ++
|
|
274
|
+
[Map.merge(%{"s" => "ret", "p" => p(m)}, if(sink == :reply, do: %{"x" => var("$r")}, else: %{}))]
|
|
275
|
+
end
|
|
276
|
+
defp write_state(st, m) do
|
|
277
|
+
v = "$state#{m[:line]}_#{m[:column]}"
|
|
278
|
+
[%{"s" => "set", "p" => p(m), "to" => var(v), "x" => expr(st)} | Enum.map(Process.get(:fields), fn f -> set_field(f, get(var(v), f, m), m) end)]
|
|
279
|
+
end
|
|
280
|
+
defp set_field(f, x, m), do: %{"s" => "set", "p" => (if m == [], do: "#{Process.get(:base)}:0:0", else: p(m)), "to" => get(var("self"), f, m), "x" => x}
|
|
281
|
+
def var(n), do: %{"e" => "var", "n" => n, "p" => "#{Process.get(:base)}:0:0"}
|
|
282
|
+
def get(x, f, m), do: %{"e" => "get", "x" => x, "f" => to_string(f), "p" => p(m), "text" => to_string(f)}
|
|
283
|
+
def fn_of(fid, name, params, body), do: %{"id" => fid, "name" => name, "cls" => Process.get(:mod), "p" => "#{Process.get(:base)}:1:1", "span" => [Process.get(:base), 1, 1], "params" => [%{"name" => "self", "t" => %{"k" => "any"}, "self" => true} | params], "ret" => %{"k" => "any"}, "body" => body, "decorators" => []}
|
|
284
|
+
# A function of the module, its clauses on its arguments.
|
|
285
|
+
defp func(fid, name, a, cs, sink) do
|
|
286
|
+
params = for i <- 1..a//1, do: "a#{i}"
|
|
287
|
+
f = fn_of(fid, name, Enum.map(params, &%{"name" => &1, "t" => %{"k" => "any"}}), clauses(cs, Enum.map(params, &var/1), & &1.args, sink, "#{name}/#{a}"))
|
|
288
|
+
Map.put(f, "params", tl(f["params"])) |> Map.put("static", true)
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
# --- expressions --------------------------------------------------------------------------------------------------
|
|
292
|
+
def expr(x) when is_integer(x), do: %{"e" => "int", "v" => Integer.to_string(x), "p" => "#{Process.get(:base)}:0:0"}
|
|
293
|
+
def expr(x) when is_float(x), do: (if x == Float.floor(x), do: %{"e" => "int", "v" => Integer.to_string(trunc(x)), "float" => true, "p" => "#{Process.get(:base)}:0:0"}, else: %{"e" => "no", "why" => "#{x}: a float that isn't whole", "p" => "#{Process.get(:base)}:0:0"})
|
|
294
|
+
def expr(x) when is_boolean(x), do: %{"e" => "bool", "v" => x, "p" => "#{Process.get(:base)}:0:0"}
|
|
295
|
+
def expr(nil), do: %{"e" => "none", "p" => "#{Process.get(:base)}:0:0"}
|
|
296
|
+
def expr(x) when is_atom(x), do: %{"e" => "str", "v" => Atom.to_string(x), "p" => "#{Process.get(:base)}:0:0"}
|
|
297
|
+
def expr(x) when is_binary(x), do: %{"e" => "str", "v" => x, "p" => "#{Process.get(:base)}:0:0"}
|
|
298
|
+
def expr({a, b}), do: %{"e" => "tuple", "xs" => [expr(a), expr(b)], "p" => "#{Process.get(:base)}:0:0"}
|
|
299
|
+
def expr({:{}, m, xs}), do: %{"e" => "tuple", "xs" => Enum.map(xs, &expr/1), "p" => p(m)}
|
|
300
|
+
def expr({:__block__, _, [x]}), do: expr(x)
|
|
301
|
+
def expr({:@, m, [{n, _, nil}]}), do: (case Process.get(:attrs)[n] do nil -> %{"e" => "no", "why" => "@#{n}: an attribute the reader can't read", "p" => p(m)}; v -> expr(v) end)
|
|
302
|
+
def expr({:__MODULE__, m, _}), do: %{"e" => "no", "why" => "__MODULE__ as a value", "p" => p(m)}
|
|
303
|
+
def expr({n, m, ctx}) when is_atom(n) and is_atom(ctx), do: %{"e" => "var", "n" => to_string(n), "p" => p(m)}
|
|
304
|
+
def expr({:|>, m, [a, {f, fm, args}]}), do: expr({f, fm, [a | args || []]}) |> Map.put("p", p(m))
|
|
305
|
+
def expr({op, m, [a, b]}) when is_map_key(@arith, op), do: %{"e" => "bin", "op" => @arith[op], "x" => expr(a), "y" => expr(b), "p" => p(m), "text" => text({op, m, [a, b]})}
|
|
306
|
+
def expr({op, m, [a, b]} = x) when is_map_key(@cmp, op), do: %{"e" => "cmp", "op" => @cmp[op], "x" => expr(a), "y" => expr(b), "p" => p(m), "text" => text(x)}
|
|
307
|
+
def expr({op, m, [a, b]}) when op in [:and, :&&], do: %{"e" => "and", "xs" => [expr(a), expr(b)], "p" => p(m)}
|
|
308
|
+
def expr({op, m, [a, b]}) when op in [:or, :||], do: %{"e" => "or", "xs" => [expr(a), expr(b)], "p" => p(m)}
|
|
309
|
+
def expr({op, m, [a]}) when op in [:not, :!], do: %{"e" => "not", "x" => expr(a), "p" => p(m)}
|
|
310
|
+
def expr({:-, m, [a]}), do: %{"e" => "neg", "x" => expr(a), "p" => p(m)}
|
|
311
|
+
def expr({:/, m, _} = x), do: %{"e" => "no", "why" => "#{text(x)}: a float division (the subset reads trunc(a / k), div and rem)", "p" => p(m)}
|
|
312
|
+
def expr({:if, m, [c, kw]}), do: %{"e" => "ite", "c" => expr(c), "a" => expr(single(kw[:do], m)), "b" => expr(single(kw[:else], m)), "p" => p(m)}
|
|
313
|
+
def expr({:%{}, m, [{:|, _, [s, kv]}]}), do: upd(expr(s), kv, m)
|
|
314
|
+
def expr({:%, m, [_, {:%{}, _, kv}]}), do: struct_new(kv, m)
|
|
315
|
+
def expr({:%{}, m, _} = x), do: %{"e" => "no", "why" => "#{text(x)}: a map literal (a state is updated: %{s | f: v})", "p" => p(m)}
|
|
316
|
+
def expr({{:., m, [v, f]}, km, []}) when is_atom(f) and not is_tuple(elem(v, 0)) and is_list(km), do: (if km[:no_parens], do: get(expr(v), f, m), else: call_expr(v, f, [], m))
|
|
317
|
+
def expr({{:., m, [mod, f]}, _, args}), do: call_expr(mod, f, args, m)
|
|
318
|
+
def expr({:fn, m, _}), do: %{"e" => "no", "why" => "an anonymous function (a closure)", "p" => p(m)}
|
|
319
|
+
def expr({f, m, args} = x) when is_atom(f) and is_list(args) do
|
|
320
|
+
a = length(args)
|
|
321
|
+
cond do
|
|
322
|
+
f in [:div, :rem] and a == 2 -> %{"e" => "bin", "op" => (if f == :div, do: "/", else: "%"), "ovf" => "wrap", "x" => expr(Enum.at(args, 0)), "y" => expr(Enum.at(args, 1)), "p" => p(m), "text" => text(x)}
|
|
323
|
+
f == :trunc and a == 1 and match?({:/, _, [_, _]}, hd(args)) -> (fn {:/, dm, [p1, p2]} -> %{"e" => "bin", "op" => "/", "ovf" => "wrap", "x" => expr(p1), "y" => expr(p2), "p" => p(dm), "text" => text(x)} end).(hd(args))
|
|
324
|
+
f in [:min, :max, :abs] -> %{"e" => "call", "f" => %{"e" => "builtin", "n" => to_string(f), "p" => p(m)}, "args" => Enum.map(args, &expr/1), "kw" => [], "p" => p(m), "text" => text(x)}
|
|
325
|
+
f in [:raise, :throw, :exit] -> %{"e" => "no", "why" => "#{text(x)} as a value", "p" => p(m)}
|
|
326
|
+
Map.has_key?(Process.get(:groups), {f, a}) -> %{"e" => "call", "f" => %{"e" => "fn", "id" => "#{Process.get(:mod)}.#{f}/#{a}", "p" => p(m)}, "args" => Enum.map(args, &expr/1), "kw" => [], "p" => p(m), "text" => text(x)}
|
|
327
|
+
true -> %{"e" => "no", "why" => "#{text(x)}: #{f}/#{a}, a function the module doesn't define", "p" => p(m)}
|
|
328
|
+
end
|
|
329
|
+
end
|
|
330
|
+
def expr(x), do: no(x, "#{text(x)}: outside the subset")
|
|
331
|
+
defp single(nil, m), do: {:__block__, m, [nil]}
|
|
332
|
+
defp single(b, m), do: (case stmts(b) do [x] -> x; _ -> {:__block__, m, [{:raise, m, ["several statements as a value"]}]} end)
|
|
333
|
+
defp upd(s, kv, m), do: %{"e" => "upd", "x" => s, "fields" => Enum.map(kv, fn {k, v} -> [to_string(k), expr(v)] end), "p" => p(m), "text" => "%{... | ...}"}
|
|
334
|
+
defp struct_new(kv, m) do
|
|
335
|
+
defaults = Process.get(:struct)
|
|
336
|
+
fs = Enum.map(Process.get(:fields), fn f -> [to_string(f), expr(Keyword.get(kv, f, defaults[f]))] end)
|
|
337
|
+
%{"e" => "new", "rec" => Process.get(:mod), "fields" => fs, "p" => p(m), "text" => "%struct{}"}
|
|
338
|
+
end
|
|
339
|
+
defp call_expr(mod, f, args, m) do
|
|
340
|
+
key = case mod do {:__aliases__, _, parts} -> parts; a when is_atom(a) -> a; _ -> nil end
|
|
341
|
+
x = {{:., m, [mod, f]}, m, args}
|
|
342
|
+
cond do
|
|
343
|
+
{key, f} in @clock -> %{"e" => "call", "f" => %{"e" => "lib", "q" => "time.time", "p" => p(m)}, "args" => [], "kw" => [], "p" => p(m), "text" => text(x)}
|
|
344
|
+
key == [:DateTime] and f == :diff and (length(args) == 2 or Enum.at(args, 2) == :second) -> %{"e" => "bin", "op" => "-", "x" => expr(Enum.at(args, 0)), "y" => expr(Enum.at(args, 1)), "p" => p(m), "text" => text(x)}
|
|
345
|
+
key == [:Map] and f == :put and match?([_, k, _] when is_atom(k), args) -> upd(expr(Enum.at(args, 0)), [{Enum.at(args, 1), Enum.at(args, 2)}], m)
|
|
346
|
+
key == [:Map] and f == :merge and match?([_, {:%{}, _, _}], args) -> upd(expr(Enum.at(args, 0)), elem(Enum.at(args, 1), 2), m)
|
|
347
|
+
key == [:Map] and f == :get and match?([_, k] when is_atom(k), args) -> get(expr(Enum.at(args, 0)), Enum.at(args, 1), m)
|
|
348
|
+
# (another module's code: at the boundary where it is inferred; its arguments are values, which it can't change)
|
|
349
|
+
is_atom(mod) or is_tuple(mod) and elem(mod, 0) == :__aliases__ -> %{"e" => "no", "why" => "#{text(x)}: another module's code", "p" => p(m), "ext" => "#{text(mod)}.#{f}", "names" => [], "patch" => %{"mod" => text(mod), "path" => [to_string(f)]}}
|
|
350
|
+
true -> %{"e" => "no", "why" => "#{text(x)}: a call outside the subset", "p" => p(m)}
|
|
351
|
+
end
|
|
352
|
+
end
|
|
353
|
+
|
|
354
|
+
# --- types, inferred from the defaults and what the module puts in each field --------------------------------------
|
|
355
|
+
defp infer(fields, body) do
|
|
356
|
+
puts = collect(body, %{})
|
|
357
|
+
spec = spec_types(body)
|
|
358
|
+
Map.new(fields, fn {f, dflt} -> {f, spec[f] || case type_of([dflt | Map.get(puts, f, [])]) do %{"k" => "any"} -> int_use(f); t -> t end} end)
|
|
359
|
+
end
|
|
360
|
+
# The types the code states: a @type (or @typep) of a map or a struct with the state's fields, field by field.
|
|
361
|
+
defp spec_types(body) do
|
|
362
|
+
fields = Process.get(:fields) || []
|
|
363
|
+
Enum.find_value(body, %{}, fn
|
|
364
|
+
{:@, _, [{k, _, [{:"::", _, [_, t]}]}]} when k in [:type, :typep] ->
|
|
365
|
+
kv = case t do {:%{}, _, kv} -> kv; {:%, _, [_, {:%{}, _, kv}]} -> kv; _ -> [] end
|
|
366
|
+
if kv != [] and Enum.all?(fields, &Keyword.has_key?(kv, &1)), do: spec_kv(kv)
|
|
367
|
+
_ -> nil
|
|
368
|
+
end)
|
|
369
|
+
end
|
|
370
|
+
defp spec_kv(kv), do: for({k, t} <- kv, is_atom(k), (st = spec_t(t)) != nil, into: %{}, do: {k, st})
|
|
371
|
+
defp spec_t({:|, _, [a, b]}) do
|
|
372
|
+
ts = [a, b] |> Enum.flat_map(fn {:|, _, xs} -> xs; x -> [x] end)
|
|
373
|
+
{nils, rest} = Enum.split_with(ts, &(&1 == nil))
|
|
374
|
+
atoms = Enum.filter(rest, &(is_atom(&1) and not is_boolean(&1)))
|
|
375
|
+
t = cond do
|
|
376
|
+
atoms != [] and length(atoms) == length(rest) -> %{"k" => "choice", "values" => Enum.map(atoms, &Atom.to_string/1), "sym" => true}
|
|
377
|
+
length(rest) == 1 -> spec_t(hd(rest))
|
|
378
|
+
true -> nil
|
|
379
|
+
end
|
|
380
|
+
if t && nils != [], do: %{"k" => "opt", "of" => t}, else: t
|
|
381
|
+
end
|
|
382
|
+
# (written bare, a type parses as a variable)
|
|
383
|
+
defp spec_t({n, _, a}) when n in [:integer, :non_neg_integer, :pos_integer, :neg_integer, :timeout] and (a == [] or is_atom(a)), do: %{"k" => "int"}
|
|
384
|
+
defp spec_t({n, _, a}) when n in [:boolean] and (a == [] or is_atom(a)), do: %{"k" => "bool"}
|
|
385
|
+
defp spec_t({{:., _, [{:__aliases__, _, [:DateTime]}, :t]}, _, []}), do: %{"k" => "int", "dt" => true}
|
|
386
|
+
defp spec_t(_), do: nil
|
|
387
|
+
defp collect(ast, acc) do
|
|
388
|
+
{_, acc} = Macro.prewalk(ast, acc, fn
|
|
389
|
+
{:%{}, _, [{:|, _, [_, kv]}]} = n, a -> {n, add_kv(kv, a)}
|
|
390
|
+
{:%, _, [_, {:%{}, _, kv}]} = n, a -> {n, add_kv(kv, a)}
|
|
391
|
+
{{:., _, [{:__aliases__, _, [:Map]}, :merge]}, _, [_, {:%{}, _, kv}]} = n, a -> {n, add_kv(kv, a)}
|
|
392
|
+
{{:., _, [{:__aliases__, _, [:Map]}, :put]}, _, [_, k, v]} = n, a when is_atom(k) -> {n, add_kv([{k, v}], a)}
|
|
393
|
+
{:ok, {:%{}, _, kv}} = n, a -> {n, add_kv(kv, a)}
|
|
394
|
+
{:=, _, [{v, _, ctx}, val]} = n, a when is_atom(v) and is_atom(ctx) -> {n, Map.update(a, {:local, v}, [val], &[val | &1])}
|
|
395
|
+
n, a -> {n, a}
|
|
396
|
+
end)
|
|
397
|
+
acc |> Enum.map(fn {k, vs} -> {k, Enum.flat_map(vs, fn v -> resolve(v, acc, 0) end)} end) |> Map.new()
|
|
398
|
+
end
|
|
399
|
+
defp add_kv(kv, a), do: Enum.reduce(kv, a, fn {k, v}, a2 when is_atom(k) -> Map.update(a2, k, [v], &[v | &1]); _, a2 -> a2 end)
|
|
400
|
+
defp resolve({v, _, ctx}, acc, d) when is_atom(v) and is_atom(ctx) and d < 4, do: Enum.flat_map(Map.get(acc, {:local, v}, []), &resolve(&1, acc, d + 1))
|
|
401
|
+
defp resolve({:if, _, [_, kw]}, acc, d), do: resolve(single(kw[:do], []), acc, d) ++ resolve(single(kw[:else], []), acc, d)
|
|
402
|
+
defp resolve(x, _, _), do: [x]
|
|
403
|
+
defp kind(x) when is_integer(x), do: "int"
|
|
404
|
+
defp kind(x) when is_float(x), do: "float"
|
|
405
|
+
defp kind(x) when is_boolean(x), do: "bool"
|
|
406
|
+
defp kind(nil), do: "none"
|
|
407
|
+
defp kind(x) when is_atom(x), do: {:sym, Atom.to_string(x)}
|
|
408
|
+
defp kind(x) when is_binary(x), do: "str"
|
|
409
|
+
defp kind({op, _, [_, _]}) when is_map_key(@arith, op) or op in [:div, :rem], do: "int"
|
|
410
|
+
defp kind({op, _, [_, _]}) when is_map_key(@cmp, op) or op in [:and, :or, :&&, :||], do: "bool"
|
|
411
|
+
defp kind({op, _, [_]}) when op in [:not, :!], do: "bool"
|
|
412
|
+
defp kind({f, _, [_ | _]}) when f in [:min, :max, :abs, :div, :rem, :trunc], do: "int"
|
|
413
|
+
defp kind({{:., _, [mod, f]}, _, _}) do
|
|
414
|
+
key = case mod do {:__aliases__, _, parts} -> parts; a -> a end
|
|
415
|
+
cond do
|
|
416
|
+
key == [:DateTime] and f == :utc_now -> "dt"
|
|
417
|
+
{key, f} in @clock or (key == [:DateTime] and f == :diff) -> "int"
|
|
418
|
+
true -> nil
|
|
419
|
+
end
|
|
420
|
+
end
|
|
421
|
+
defp kind(_), do: nil
|
|
422
|
+
defp type_of(vs) do
|
|
423
|
+
ks = vs |> Enum.map(&kind/1) |> Enum.reject(&is_nil/1) |> Enum.uniq()
|
|
424
|
+
{syms, rest} = Enum.split_with(ks, &is_tuple/1)
|
|
425
|
+
# (a DateTime from the clock: a number of seconds, the harness converting)
|
|
426
|
+
dt = "dt" in rest
|
|
427
|
+
rest = Enum.uniq(Enum.map(rest, fn "dt" -> "int"; k -> k end))
|
|
428
|
+
none = "none" in rest
|
|
429
|
+
rest = rest -- ["none"]
|
|
430
|
+
t = cond do
|
|
431
|
+
syms != [] and rest == [] -> %{"k" => "choice", "values" => Enum.map(syms, &elem(&1, 1)), "sym" => true}
|
|
432
|
+
syms == [] and length(rest) == 1 -> Map.merge(%{"k" => hd(rest)}, if(dt, do: %{"dt" => true}, else: %{}))
|
|
433
|
+
syms == [] and Enum.sort(rest) == ["float", "int"] -> %{"k" => "float"}
|
|
434
|
+
true -> nil
|
|
435
|
+
end
|
|
436
|
+
cond do t == nil -> %{"k" => "any"}; none -> %{"k" => "opt", "of" => t}; true -> t end
|
|
437
|
+
end
|
|
438
|
+
# A name the module computes with or orders anywhere (as a field's, an argument's or a pattern's variable): a number.
|
|
439
|
+
defp int_use(n) do
|
|
440
|
+
{_, k} = Macro.prewalk(Process.get(:body), false, fn
|
|
441
|
+
{op, _, [a, b]} = x, acc when op in [:+, :-, :*, :<, :<=, :>, :>=, :div, :rem] -> {x, acc or Enum.any?([a, b], &named?(&1, n))}
|
|
442
|
+
{f, _, [a, b]} = x, acc when f in [:div, :rem] -> {x, acc or Enum.any?([a, b], &named?(&1, n))}
|
|
443
|
+
x, acc -> {x, acc}
|
|
444
|
+
end)
|
|
445
|
+
if k, do: %{"k" => "int"}, else: %{"k" => "any"}
|
|
446
|
+
end
|
|
447
|
+
defp named?({m, _, ctx}, n) when is_atom(m) and is_atom(ctx), do: m == n
|
|
448
|
+
defp named?({{:., _, [_, f]}, km, []}, n) when is_list(km), do: f == n
|
|
449
|
+
defp named?(_, _), do: false
|
|
450
|
+
# An argument's type: what its function compares it with or computes it into.
|
|
451
|
+
defp param_type(name, body) do
|
|
452
|
+
n = String.to_atom(name)
|
|
453
|
+
{_, k} = Macro.prewalk(body, nil, fn
|
|
454
|
+
{op, _, [a, b]} = x, acc when is_map_key(@cmp, op) or is_map_key(@arith, op) -> {x, acc || (if match?({^n, _, c} when is_atom(c), a) or match?({^n, _, c} when is_atom(c), b), do: %{"k" => "int"})}
|
|
455
|
+
x, acc -> {x, acc}
|
|
456
|
+
end)
|
|
457
|
+
k || %{"k" => "any"}
|
|
458
|
+
end
|
|
459
|
+
end
|
|
460
|
+
|
|
461
|
+
[arg] = System.argv()
|
|
462
|
+
IO.puts(GdpJson.encode(GdpReader.run(GdpJson.decode(arg))))
|
package/dist/core/exists.d.ts
CHANGED
|
@@ -19,6 +19,9 @@ export type SomeReport = Report & {
|
|
|
19
19
|
};
|
|
20
20
|
export declare function proveSome(m: Machine, laws: Law[], opts?: {
|
|
21
21
|
rounds?: number;
|
|
22
|
+
whole?: (m: Machine, laws: Law[]) => Report & {
|
|
23
|
+
laws?: Law[];
|
|
24
|
+
};
|
|
22
25
|
}): SomeReport;
|
|
23
26
|
export declare function showE(e: E): string;
|
|
24
27
|
export declare function showC(c: C): string;
|
package/dist/core/exists.js
CHANGED
|
@@ -156,19 +156,31 @@ function solved(atoms, g) {
|
|
|
156
156
|
// Whether ∃ vars. P holds where env and st give every other value, with a witness: exact when the bound values are one
|
|
157
157
|
// natural or one integer read linearly (P's truth changes only next to the values its atoms solve for, so those, their
|
|
158
158
|
// neighbours, 0 and one past them are every case); otherwise found among those points, or undefined.
|
|
159
|
+
// (what P is, apart from the state: its groups, atoms and shape, read once a law; a run reads a law with "there exists"
|
|
160
|
+
// at every tuple of its keys at every state, and P's atoms are quadratic in its size to read)
|
|
161
|
+
const shapes = new WeakMap();
|
|
162
|
+
const shapeOf = (body, vars) => {
|
|
163
|
+
let byVars = shapes.get(body);
|
|
164
|
+
if (!byVars)
|
|
165
|
+
shapes.set(body, (byVars = new Map()));
|
|
166
|
+
const id = vars.join(','), had = byVars.get(id);
|
|
167
|
+
if (had)
|
|
168
|
+
return had;
|
|
169
|
+
const bound = new Set(vars), out = { groups: groupsOf(vars), atoms: atomsOf(body, bound), linearOnly: linearIn(body, bound), reads: JSON.stringify(body).includes('"op":"get"') };
|
|
170
|
+
byVars.set(id, out);
|
|
171
|
+
return out;
|
|
172
|
+
};
|
|
159
173
|
export function someHolds(body, vars, env, st, m) {
|
|
160
|
-
const groups
|
|
174
|
+
const { groups, atoms, linearOnly, reads } = shapeOf(body, vars);
|
|
161
175
|
const value = (e) => { try {
|
|
162
176
|
return evalE(e, env, st, m);
|
|
163
177
|
}
|
|
164
178
|
catch {
|
|
165
179
|
return undefined;
|
|
166
180
|
} };
|
|
167
|
-
const atoms = atomsOf(body, bound);
|
|
168
|
-
const linearOnly = linearIn(body, bound);
|
|
169
181
|
// A bound natural read as a map's key: the cells the maps hold, and one past them, are every case a read gives.
|
|
170
182
|
const cells = new Set();
|
|
171
|
-
if (
|
|
183
|
+
if (reads)
|
|
172
184
|
for (const c of Object.values(st.maps))
|
|
173
185
|
for (const key of c.keys())
|
|
174
186
|
cells.add(key);
|
|
@@ -435,6 +447,8 @@ function firstFit(lists, ok, from, cap = 20000) {
|
|
|
435
447
|
}
|
|
436
448
|
// The laws with existentials proven through witnesses: chosen per law by the counterexamples the kernel gives, then the
|
|
437
449
|
// whole set proven as plain laws of the machine with its ghosts.
|
|
450
|
+
// (`whole`: the whole set's prover over the ghosted machine, proveLaws by default; a search's trial proof passes
|
|
451
|
+
// kernel/prove.ts's proveSetFast, which reuses the decisions made over that machine and checks its trees with checkLaws)
|
|
438
452
|
export function proveSome(m, laws, opts = {}) {
|
|
439
453
|
const cases = casesOf(m), mapsRead = (l) => readsMaps(l.holds) || !!m.maps || !!m.inputMaps;
|
|
440
454
|
// Each law's bound naturals named apart from the machine's names and from each other's (each may become a ghost).
|
|
@@ -545,7 +559,7 @@ export function proveSome(m, laws, opts = {}) {
|
|
|
545
559
|
}
|
|
546
560
|
for (let pass = 1;; pass++) {
|
|
547
561
|
const { machine, laws: plain, ghosts } = current(), t0 = performance.now();
|
|
548
|
-
const out = proveLaws(machine, plain), done = { ...out, laws: out.laws ?? plain, machine, ghosts, witnesses: Object.fromEntries([...plans.values()].map(p => [p.law.name, describe(p, cases)])) };
|
|
562
|
+
const out = (opts.whole ?? proveLaws)(machine, plain), done = { ...out, laws: out.laws ?? plain, machine, ghosts, witnesses: Object.fromEntries([...plans.values()].map(p => [p.law.name, describe(p, cases)])) };
|
|
549
563
|
if (log)
|
|
550
564
|
console.error(`exists: pass ${pass} the whole set: ${out.proven ? 'proven' : `${out.failed?.goal} ${out.failed?.stuck}`} (${Math.round(performance.now() - t0)} ms)`);
|
|
551
565
|
const j = out.proven || !out.failed || pass > 8 ? undefined : [...plans.keys()].find(k => out.failed.goal.startsWith(`${laws[k].name} @`));
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type Extraction } from './extract.js';
|
|
2
|
+
import { type FileURL } from './extract-read.js';
|
|
3
|
+
import type { Rule } from './dsl.js';
|
|
4
|
+
import type { Sorts } from './extract-print.js';
|
|
5
|
+
import { type GoRead } from './extract-go.js';
|
|
6
|
+
import { type GoCheckOptions, type GoEvidence, type GoLeaf } from './extract-go-check.js';
|
|
7
|
+
import { type CRead } from './c/reader.js';
|
|
8
|
+
export { proveRule, proveSteps } from './dsl.js';
|
|
9
|
+
export type COptions = {
|
|
10
|
+
entry?: string;
|
|
11
|
+
methods?: string[];
|
|
12
|
+
/** @deprecated methods (the same: the struct's functions read as its requests) */
|
|
13
|
+
functions?: string[];
|
|
14
|
+
strict?: boolean;
|
|
15
|
+
flags?: string[];
|
|
16
|
+
compileCommands?: string;
|
|
17
|
+
clang?: string;
|
|
18
|
+
root?: string;
|
|
19
|
+
fails?: Record<string, string>;
|
|
20
|
+
onError?: 'refuse' | 'discard';
|
|
21
|
+
domains?: Record<string, 'nat' | 'int'>;
|
|
22
|
+
check?: GoCheckOptions;
|
|
23
|
+
};
|
|
24
|
+
export declare function readCFile(file: string, opts: COptions, cpp?: boolean): {
|
|
25
|
+
c: CRead;
|
|
26
|
+
flags: string[];
|
|
27
|
+
};
|
|
28
|
+
export declare function extractC(at: string | FileURL, given?: COptions, cpp?: boolean): Extraction & {
|
|
29
|
+
leaves?: GoLeaf[];
|
|
30
|
+
};
|
|
31
|
+
export declare const extractCpp: (at: string | FileURL, opts?: COptions) => Extraction & {
|
|
32
|
+
leaves?: GoLeaf[];
|
|
33
|
+
};
|
|
34
|
+
export declare function harnessC(file: string, c: CRead, read: GoRead, opts: COptions, cpp: boolean): string;
|
|
35
|
+
export declare function checkC(file: string, flags: string[], c: CRead, read: GoRead, r: Rule, sorts: Sorts, opts: COptions, cpp: boolean): GoEvidence;
|