gdp-wired 0.31.0 → 0.32.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.
Files changed (73) hide show
  1. package/README.md +82 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/cli.d.ts +66 -0
  5. package/dist/core/cli.js +582 -0
  6. package/dist/core/dsl.d.ts +4 -2
  7. package/dist/core/dsl.js +22 -12
  8. package/dist/core/effect.d.ts +6 -4
  9. package/dist/core/effect.js +48 -10
  10. package/dist/core/ex/harness.exs +177 -0
  11. package/dist/core/ex/json.exs +46 -0
  12. package/dist/core/ex/reader.exs +462 -0
  13. package/dist/core/exists.d.ts +3 -0
  14. package/dist/core/exists.js +3 -1
  15. package/dist/core/extract-c.d.ts +35 -0
  16. package/dist/core/extract-c.js +424 -0
  17. package/dist/core/extract-check.js +27 -6
  18. package/dist/core/extract-ex.d.ts +16 -0
  19. package/dist/core/extract-ex.js +33 -0
  20. package/dist/core/extract-go-check.d.ts +28 -0
  21. package/dist/core/extract-go-check.js +639 -0
  22. package/dist/core/extract-go.d.ts +231 -0
  23. package/dist/core/extract-go.js +1166 -0
  24. package/dist/core/extract-jvm.d.ts +23 -0
  25. package/dist/core/extract-jvm.js +220 -0
  26. package/dist/core/extract-print.js +17 -7
  27. package/dist/core/extract-py.d.ts +15 -0
  28. package/dist/core/extract-py.js +31 -0
  29. package/dist/core/extract-rb.d.ts +17 -0
  30. package/dist/core/extract-rb.js +31 -0
  31. package/dist/core/extract-read.d.ts +20 -0
  32. package/dist/core/extract-read.js +46 -6
  33. package/dist/core/extract-rs.d.ts +12 -0
  34. package/dist/core/extract-rs.js +306 -0
  35. package/dist/core/extract-shapes.d.ts +2 -0
  36. package/dist/core/extract-shapes.js +6 -5
  37. package/dist/core/extract-step.d.ts +806 -0
  38. package/dist/core/extract-step.js +4141 -0
  39. package/dist/core/extract-swift.d.ts +27 -0
  40. package/dist/core/extract-swift.js +484 -0
  41. package/dist/core/extract-xstate.d.ts +10 -3
  42. package/dist/core/extract-xstate.js +50 -4
  43. package/dist/core/extract.d.ts +22 -3
  44. package/dist/core/extract.js +107 -18
  45. package/dist/core/go/go.mod +3 -0
  46. package/dist/core/go/reader.go +901 -0
  47. package/dist/core/infer.js +1770 -52
  48. package/dist/core/jvm/Harness.java +361 -0
  49. package/dist/core/jvm/JavaReader.java +825 -0
  50. package/dist/core/jvm/Jvm.java +332 -0
  51. package/dist/core/jvm/KtReader.java +960 -0
  52. package/dist/core/jvm/Rt.java +10 -0
  53. package/dist/core/laws.d.ts +66 -0
  54. package/dist/core/laws.js +522 -0
  55. package/dist/core/py/harness.py +328 -0
  56. package/dist/core/py/reader.py +447 -0
  57. package/dist/core/rb/harness.rb +233 -0
  58. package/dist/core/rb/reader.rb +375 -0
  59. package/dist/core/rs/Cargo.lock +108 -0
  60. package/dist/core/rs/Cargo.toml +14 -0
  61. package/dist/core/rs/src/main.rs +681 -0
  62. package/dist/core/swift/Harness.swift +124 -0
  63. package/dist/core/swift/Main.swift +34 -0
  64. package/dist/core/swift/Package.swift +13 -0
  65. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  66. package/dist/kernel/cdcl.js +43 -18
  67. package/dist/kernel/epr.d.ts +35 -0
  68. package/dist/kernel/epr.js +1676 -0
  69. package/dist/kernel/prove.d.ts +44 -0
  70. package/dist/kernel/prove.js +668 -54
  71. package/dist/lean-kernel/emit.d.ts +1 -0
  72. package/dist/lean-kernel/emit.js +21 -4
  73. package/package.json +53 -6
@@ -0,0 +1,233 @@
1
+ # The Ruby side of the extractor's check (core/extract-step.ts's checkStep): the file loaded as it ships, its object
2
+ # made, set to a state, called with the rule's requests and read back, one JSON line a request over two named pipes.
3
+ # The clock is the request's time: Time.now, Process.clock_gettime and a clock object the caller stated (its
4
+ # current_time and now) read it. Line events (TracePoint) count the branch arms reached. A library the file requires
5
+ # and this Ruby lacks is skipped (only the class read runs).
6
+ #
7
+ # ruby core/rb/harness.rb <in-fifo> <out-fifo>
8
+ require 'json'
9
+
10
+ NOW = [0]
11
+ HIT = {}
12
+ S = {}
13
+ OBJS = {}
14
+
15
+ module GdpClock
16
+ def now(*) = Time.at(NOW[0])
17
+ end
18
+ Time.singleton_class.prepend(GdpClock)
19
+ module GdpMono
20
+ def clock_gettime(*a) = a.length > 1 && a[1] != :float_second ? NOW[0] : NOW[0].to_f
21
+ end
22
+ Process.singleton_class.prepend(GdpMono)
23
+ # A clock object the caller stated: its time is the request's.
24
+ class GdpStatedClock
25
+ def current_time = NOW[0]
26
+ def now = NOW[0]
27
+ end
28
+
29
+ def enc_num(v)
30
+ return v if v == true || v == false
31
+ return v.to_s if v.is_a?(Integer)
32
+ return (v.finite? && v == v.floor && v.abs < 2**63 ? v.to_i.to_s : "f:#{v}") if v.is_a?(Float)
33
+ "?:#{v.class}"
34
+ end
35
+ def tag(v)
36
+ return v if v.nil? || v == true || v == false
37
+ return {'n' => enc_num(v)} if v.is_a?(Numeric)
38
+ return {'s' => v.to_s} if v.is_a?(String) || v.is_a?(Symbol)
39
+ {'o' => v.class.name}
40
+ end
41
+ # An answered call's value: the request's input for it (core/extract-step.ts's answers), None where it says so.
42
+ CUR = {}
43
+ def answer(key) = (a = CUR[key]).nil? || a['none'] ? nil : build(a)
44
+ def stub(key) = proc { |*_a, **_k| answer(key) }
45
+ # A store (stated, or an injected dependency inferred): get, set and delete over a Hash that keeps what is set; its
46
+ # other methods answered.
47
+ class GdpStore
48
+ attr_reader :data
49
+ def initialize(name, decl)
50
+ @data = {}
51
+ {'get' => %w[get], 'set' => %w[set], 'delete' => %w[delete]}.each do |kind, dflt|
52
+ (decl[kind] || dflt).each do |m|
53
+ define_singleton_method(m) do |*a, **k|
54
+ key = k[:key] || a[0]
55
+ case kind
56
+ when 'get' then @data[key]
57
+ when 'set' then @data[key] = k.key?(:value) ? k[:value] : a[1]
58
+ else @data.delete(key)
59
+ end
60
+ end
61
+ end
62
+ end
63
+ # (a method left out: nothing, as the rule takes it; any other is no method of this store, and fails)
64
+ (decl['skip'] || []).each { |m| define_singleton_method(m) { |*_a, **_k| nil } }
65
+ S['answers'].each { |x| define_singleton_method(x['patch']['path'][-1], &stub(x['key'])) if x['patch']['store'] == name }
66
+ end
67
+ end
68
+ # (each object's stores, by its id; the one being made's in $stores)
69
+ SOBJ = {}
70
+ $stores = {}
71
+ def tpl_match(tpl, key)
72
+ pre, post = tpl.split('{}', 2)
73
+ return (key == tpl ? '' : nil) if post.nil?
74
+ key.is_a?(String) && key.start_with?(pre) && key.end_with?(post) && key.length >= pre.length + post.length ? key[pre.length...(key.length - post.length)] : nil
75
+ end
76
+ def sym?(t) = t.is_a?(Hash) && (t['sym'] || (t['k'] == 'opt' && t['of'].is_a?(Hash) && t['of']['sym']))
77
+ def build(spec)
78
+ return nil if spec['none']
79
+ return ($stores[spec['store']] ||= GdpStore.new(spec['store'], S['stores'][spec['store']] || {})) if spec['store']
80
+ if spec.key?('in')
81
+ v = spec['in']
82
+ return v.to_sym if spec['sym'] && v.is_a?(String)
83
+ return spec['float'] ? Integer(v).to_f : (v.is_a?(String) && v =~ /\A-?\d+\z/ ? Integer(v) : v)
84
+ end
85
+ raise ArgumentError, "an argument spec #{spec}"
86
+ end
87
+ def walk(o, path) = path.reduce(o) { |x, p| x.instance_variable_get(p) }
88
+ def put(o, path, v) = walk(o, path[0..-2]).instance_variable_set(path[-1], v)
89
+
90
+ def state_of(obj)
91
+ S['leaves'].each_with_object({}) do |l, s|
92
+ k = l['kind']
93
+ if l['store']
94
+ s[l['name']] = (SOBJ[obj.object_id]&.[](l['store'])&.data || {}).each_with_object({}) { |(key, v), c| h = tpl_match(l['tpl'], key); c[h] = {'value' => enc_num(v)} if h }
95
+ next
96
+ end
97
+ next if k == 'frame' || k == 'map'
98
+ v = walk(obj, l['path'])
99
+ s[l['name']] = case k
100
+ when 'none' then v.nil?
101
+ when 'num' then v.nil? ? '0' : enc_num(v)
102
+ when 'str', 'choice' then v.nil? ? '' : v.to_s
103
+ when 'bool' then v.nil? ? false : v
104
+ end
105
+ end
106
+ end
107
+ def set_state(obj, st)
108
+ S['leaves'].each do |l|
109
+ k, v = l['kind'], st[l['name']]
110
+ if l['store'] && (d = SOBJ[obj.object_id]&.[](l['store'])&.data)
111
+ d.delete_if { |key, _| tpl_match(l['tpl'], key) }
112
+ pre, post = l['tpl'].split('{}', 2)
113
+ (v || {}).each { |h, c| d[post.nil? ? l['tpl'] : "#{pre}#{h}#{post}"] = l['float'] ? Integer(c['value']).to_f : Integer(c['value']) }
114
+ next
115
+ end
116
+ case k
117
+ when 'num' then put(obj, l['path'], l['float'] ? Integer(v).to_f : Integer(v))
118
+ when 'str', 'choice' then put(obj, l['path'], sym?(l['t']) ? v.to_sym : v)
119
+ when 'bool' then put(obj, l['path'], v)
120
+ end
121
+ end
122
+ S['leaves'].each { |l| put(obj, l['path'], nil) if l['kind'] == 'none' && st[l['name']] == true }
123
+ end
124
+ def frames(obj)
125
+ S['leaves'].select { |l| l['kind'] == 'frame' && !l['cls'] }.each_with_object({}) do |l, out|
126
+ out[l['path'].join('.')] = (walk(obj, l['path']).inspect rescue nil)
127
+ end
128
+ end
129
+ # The arguments, by the method's own parameters: positional ones in order, keywords by name; a stated clock given.
130
+ def call_args(m, specs)
131
+ given = specs.to_h
132
+ pos, kw = [], {}
133
+ m.parameters.each do |kind, name|
134
+ n = name.to_s
135
+ if S['clocks'].include?(n) && %i[key keyreq].include?(kind) then kw[name] = GdpStatedClock.new; next end
136
+ spec = given[n]
137
+ next if spec.nil? || spec['dflt'] || spec['inert']
138
+ if spec['store'] && %i[key keyreq].include?(kind) then kw[name] = build(spec); next end
139
+ %i[key keyreq].include?(kind) ? kw[name] = build(spec) : pos << build(spec)
140
+ end
141
+ [pos, kw]
142
+ end
143
+ def traced
144
+ tp = TracePoint.new(:line) { |t| HIT[t.lineno] = true if t.path == S['path'] }
145
+ tp.enable { yield }
146
+ end
147
+
148
+ def hello(req)
149
+ S.update(req)
150
+ S['path'] = File.realpath(req['path'])
151
+ S['clocks'] ||= []
152
+ $LOAD_PATH.unshift(req['root'])
153
+ # (a library the file requires that this Ruby lacks: taken as loaded, the class read being the code's own)
154
+ tries = 0
155
+ begin
156
+ [*S['loads'], S['path']].each { |f| load f }
157
+ rescue LoadError => e
158
+ raise if (tries += 1) > 20 || !e.path
159
+ $LOADED_FEATURES << "#{e.path}.rb"
160
+ retry
161
+ end
162
+ S['cls'] = Object.const_get(req['cls'])
163
+ # (an answered call of another class's code: the stub prepended to that class's method, as the clock's is; the class
164
+ # made where a library is missing)
165
+ S['answers'].each do |a|
166
+ next unless (mod = a['patch']['mod'])
167
+ c = mod.split('::').reject(&:empty?).reduce(Object) { |o, n| o.const_defined?(n, false) ? o.const_get(n, false) : o.const_set(n, Module.new) }
168
+ m, st = a['patch']['path'][-1], stub(a['key'])
169
+ c.singleton_class.prepend(Module.new { define_method(m, &st) })
170
+ end
171
+ {'ok' => true}
172
+ end
173
+ def make(specs)
174
+ $stores = {}
175
+ pos, kw = call_args(S['cls'].instance_method(:initialize), specs)
176
+ obj = traced { S['cls'].new(*pos, **kw) }
177
+ SOBJ[obj.object_id] = $stores
178
+ OBJS[OBJS.length + 1] = obj
179
+ OBJS.length
180
+ end
181
+ def call(req)
182
+ obj = OBJS[req['id']]
183
+ NOW[0] = Integer(req['now'] || 0)
184
+ CUR.replace(req['answers'] || {})
185
+ m = obj.method(req['m'])
186
+ pos, kw = call_args(m, req['a'])
187
+ before = frames(obj)
188
+ snap = S['discard'] ? state_of(obj) : nil
189
+ out, err = nil, nil
190
+ begin
191
+ out = traced { m.call(*pos, **kw) }
192
+ rescue StandardError => e
193
+ err = "#{e.class}: #{e.message}"[0, 300]
194
+ end
195
+ set_state(obj, snap) if err && snap
196
+ after = frames(obj)
197
+ before.each { |k, v| return {'frame' => k} if after[k] != v }
198
+ {'out' => tag(out), **(err ? {'err' => err} : {})}
199
+ end
200
+
201
+ fin, fout = File.open(ARGV[0], 'r'), File.open(ARGV[1], 'w')
202
+ fin.each_line do |line|
203
+ req = JSON.parse(line)
204
+ op = req['op']
205
+ res = begin
206
+ NOW[0] = Integer(req['now'] || 0) if %w[new at].include?(op)
207
+ case op
208
+ when 'hello' then hello(req)
209
+ when 'new'
210
+ begin
211
+ {'id' => make(req['a'])}
212
+ rescue StandardError => e
213
+ {'err' => "#{e.class}: #{e.message}"[0, 300]}
214
+ end
215
+ when 'at'
216
+ begin
217
+ i = make(req['a'])
218
+ set_state(OBJS[i], req['state'])
219
+ {'id' => i}
220
+ rescue StandardError => e
221
+ {'bad' => "#{e.class}: #{e.message}"[0, 300]}
222
+ end
223
+ when 'get' then {'state' => state_of(OBJS[req['id']])}
224
+ when 'call' then call(req)
225
+ when 'coverage' then {'hit' => HIT.keys.sort.map { |n| [File.basename(S['path']), n] }}
226
+ else {'error' => "no op #{op}"}
227
+ end
228
+ rescue StandardError, ScriptError => e
229
+ {'error' => "#{e.class}: #{e.message}"[0, 500]}
230
+ end
231
+ fout.write("#{JSON.generate(res)}\n")
232
+ fout.flush
233
+ end
@@ -0,0 +1,375 @@
1
+ # The extractor's Ruby reader (core/extract-rb.ts): a file read through Ruby's own parser (Prism) and lowered into the
2
+ # shared step IR (core/extract-step.ts's SModule, as JSON on stdout), which one TypeScript executor runs into the rule.
3
+ # Nothing here decides what is in the subset beyond the syntax: a construct the IR has no node for becomes
4
+ # {"e": "no"} or {"s": "no"} with the reason, refused by the executor only where a step reaches it. Ruby states no
5
+ # types, so the reader infers them from the code itself: a field's from what is assigned to it (symbols a choice, nil
6
+ # with numbers an optional number), an argument's from what it is compared with or computed into. The check runs the
7
+ # code, so a type inferred wrong is a refusal, never a rule that lies. A method's last expression is its result, a
8
+ # field read before it is set is nil, and only nil and false are false.
9
+ #
10
+ # ruby core/rb/reader.rb '{"root": <dir>, "file": <file>, "names": ["Mod::Class"], "clocks": ["clock"]}'
11
+ require 'json'
12
+ require 'prism'
13
+
14
+ class Reader
15
+ ARITH = %i[+ - * / %].freeze
16
+ CMP = {:< => '<', :<= => '<=', :> => '>', :>= => '>=', :== => '==', :!= => '!='}.freeze
17
+
18
+ def initialize(req)
19
+ @root, @file, @clocks = File.expand_path(req['root']), File.expand_path(req['file']), req['clocks'] || []
20
+ @base = File.basename(@file)
21
+ @consts = {}
22
+ Dir.glob(File.join(@root, '**', '*.rb')).each { |f| index_consts(f) rescue nil }
23
+ @recs, @funcs, @loads = {}, {}, []
24
+ end
25
+
26
+ # --- constants of the code: Mod::NAME = literal, from every file under the root -----------------------------------
27
+ def index_consts(f)
28
+ walk = lambda do |n, nest|
29
+ case n
30
+ when Prism::ModuleNode, Prism::ClassNode then n.body&.body&.each { |m| walk.(m, nest + [n.constant_path.slice]) }
31
+ when Prism::ConstantWriteNode
32
+ v = n.value
33
+ lit = case v
34
+ when Prism::SymbolNode then {'e' => 'str', 'v' => v.unescaped, 'sym' => true}
35
+ when Prism::IntegerNode then {'e' => 'int', 'v' => v.value.to_s}
36
+ when Prism::StringNode then {'e' => 'str', 'v' => v.unescaped}
37
+ when Prism::TrueNode, Prism::FalseNode then {'e' => 'bool', 'v' => v.is_a?(Prism::TrueNode)}
38
+ end
39
+ @consts[(nest + [n.name.to_s]).join('::')] = lit.merge('file' => f) if lit
40
+ end
41
+ end
42
+ Prism.parse_file(f).value.statements.body.each { |n| walk.(n, []) }
43
+ end
44
+ # A constant's literal, and the file defining it kept (the check loads it before the file read).
45
+ def const(n, nest)
46
+ full = n.slice.sub(/\A::/, '')
47
+ c = nest.length.downto(0).lazy.map { |i| @consts[(nest[0, i] + [full]).join('::')] }.find(&:itself) || @consts.find { |k, _| k.end_with?("::#{full}") }&.last
48
+ (@loads << c['file'] unless @loads.include?(c['file']) || c['file'] == @file) if c
49
+ c
50
+ end
51
+ attr_reader :loads
52
+
53
+ def where(n) = "#{@base}:#{n.location.start_line}:#{n.location.start_column + 1}"
54
+ def text(n) = (s = n.slice.split.join(' ')).length <= 60 ? s : "#{s[0, 57]}..."
55
+ def no(n, why) = {'e' => 'no', 'why' => why, 'p' => where(n)}
56
+ # The locals a node mentions, and self where it reads the object's state.
57
+ def mentioned(ns)
58
+ out, q = [], ns.dup
59
+ while (m = q.shift)
60
+ out << m.name.to_s if m.is_a?(Prism::LocalVariableReadNode)
61
+ out << 'self' if m.is_a?(Prism::InstanceVariableReadNode) || m.is_a?(Prism::SelfNode)
62
+ q.concat(m.compact_child_nodes)
63
+ end
64
+ out.uniq
65
+ end
66
+
67
+ # --- the classes --------------------------------------------------------------------------------------------------
68
+ def classes
69
+ out = {}
70
+ walk = lambda do |n, nest|
71
+ case n
72
+ when Prism::ModuleNode then n.body&.body&.each { |m| walk.(m, nest + [n.constant_path.slice]) }
73
+ when Prism::ClassNode
74
+ q = (nest + [n.constant_path.slice]).join('::')
75
+ out[q] = [n, nest + [n.constant_path.slice]]
76
+ n.body&.body&.each { |m| walk.(m, nest + [n.constant_path.slice]) }
77
+ end
78
+ end
79
+ Prism.parse_file(@file).value.statements.body.each { |n| walk.(n, []) }
80
+ out
81
+ end
82
+
83
+ def rec_of(q, cdef, nest)
84
+ @nest, @cls = nest, q
85
+ defs, attrs = {}, {}
86
+ (cdef.body&.body || []).each do |n|
87
+ n = n.arguments.arguments.first if n.is_a?(Prism::CallNode) && %i[private protected public].include?(n.name) && n.arguments&.arguments&.first.is_a?(Prism::DefNode)
88
+ if n.is_a?(Prism::DefNode) && !n.receiver then defs[n.name.to_s] = n
89
+ elsif n.is_a?(Prism::CallNode) && !n.receiver && %i[attr_reader attr_writer attr_accessor].include?(n.name)
90
+ (n.arguments&.arguments || []).each { |a| attrs[a.unescaped] = [n.name, n] if a.is_a?(Prism::SymbolNode) }
91
+ end
92
+ end
93
+ @defs, @attrs = defs, attrs
94
+ # Every field the class assigns, and what each is: the state's types (a field read before it is set is nil).
95
+ @ivars, @lvars = {}, {}
96
+ each_node(cdef) do |n|
97
+ case n
98
+ when Prism::LocalVariableWriteNode then (@lvars[n.name.to_s] ||= []) << n.value
99
+ when Prism::InstanceVariableWriteNode then (@ivars[n.name.to_s] ||= []) << n.value
100
+ when Prism::InstanceVariableOperatorWriteNode, Prism::InstanceVariableOrWriteNode then (@ivars[n.name.to_s] ||= []) << :int
101
+ when Prism::CallNode
102
+ w = n.name.to_s.chomp('=')
103
+ if n.name.to_s.end_with?('=') && n.receiver.is_a?(Prism::SelfNode) && attrs[w] && n.arguments then (@ivars["@#{w}"] ||= []) << n.arguments.arguments.first end
104
+ # (a field computed with or ordered against: a number)
105
+ if (ARITH.include?(n.name) || %i[< <= > >=].include?(n.name)) && n.receiver && n.arguments&.arguments&.length == 1
106
+ [n.receiver, n.arguments.arguments.first].each { |x| iv = field_read(x); (@ivars[iv] ||= []) << :int if iv }
107
+ end
108
+ end
109
+ end
110
+ fields = @ivars.map { |iv, _| {'name' => iv, 't' => ivar_type(iv)} }
111
+ methods, z = {}, "#{@base}:0:0"
112
+ attrs.each do |name, (kind, node)|
113
+ if kind != :attr_writer && !defs[name]
114
+ fid = "#{q}##{name}"; methods[name] = fid
115
+ @funcs[fid] = fn_of(fid, name, node, [], [{'s' => 'ret', 'p' => z, 'x' => ivar("@#{name}", node)}])
116
+ end
117
+ next if kind == :attr_reader || defs["#{name}="]
118
+ fid = "#{q}##{name}="; methods["#{name}="] = fid
119
+ @funcs[fid] = fn_of(fid, "#{name}=", node, [{'name' => 'v', 't' => {'k' => 'any'}}], [{'s' => 'set', 'p' => z, 'to' => ivar("@#{name}", node), 'x' => {'e' => 'var', 'n' => 'v', 'p' => where(node)}}, {'s' => 'ret', 'p' => z, 'x' => {'e' => 'var', 'n' => 'v', 'p' => where(node)}}])
120
+ end
121
+ defs.each do |name, d|
122
+ key = name == 'initialize' ? '__init__' : name
123
+ fid = "#{q}##{name}"; methods[key] = fid
124
+ @funcs[fid] = func(fid, d, name == 'initialize' ? fields.map { |f| f['name'] } : nil)
125
+ end
126
+ # (no initialize: every field nil, as Ruby's are)
127
+ unless defs['initialize'] || fields.empty?
128
+ fid = "#{q}#initialize"; methods['__init__'] = fid
129
+ @funcs[fid] = fn_of(fid, 'initialize', cdef, [], fields.map { |f| {'s' => 'set', 'p' => z, 'to' => ivar(f['name'], cdef), 'x' => {'e' => 'none', 'p' => where(cdef)}} })
130
+ end
131
+ @recs[q] = {'name' => q, 'short' => q.split('::').last, 'fields' => fields, 'methods' => methods, 'kinds' => [], 'own' => true, 'module' => q, 'p' => where(cdef)}
132
+ q
133
+ end
134
+ # The field an expression reads: @x, or x / self.x of an attribute reader.
135
+ def field_read(x)
136
+ return x.name.to_s if x.is_a?(Prism::InstanceVariableReadNode)
137
+ "@#{x.name}" if x.is_a?(Prism::CallNode) && (!x.receiver || x.receiver.is_a?(Prism::SelfNode)) && !x.arguments && @attrs[x.name.to_s] && @attrs[x.name.to_s][0] != :attr_writer
138
+ end
139
+ def each_node(n, &b)
140
+ yield n
141
+ n.compact_child_nodes.each { |c| each_node(c, &b) }
142
+ end
143
+
144
+ # --- types, inferred ----------------------------------------------------------------------------------------------
145
+ def kind(v, locals = {})
146
+ return 'int' if v == :int
147
+ case v
148
+ when Prism::NilNode then 'none'
149
+ when Prism::IntegerNode then 'int'
150
+ when Prism::FloatNode then 'float'
151
+ when Prism::TrueNode, Prism::FalseNode then 'bool'
152
+ when Prism::StringNode, Prism::InterpolatedStringNode then 'str'
153
+ when Prism::SymbolNode then [:sym, v.unescaped]
154
+ when Prism::ConstantReadNode, Prism::ConstantPathNode
155
+ c = const(v, @nest)
156
+ c && (c['sym'] ? [:sym, c['v']] : c['e'] == 'int' ? 'int' : c['e'] == 'bool' ? 'bool' : 'str')
157
+ when Prism::LocalVariableReadNode
158
+ # (a local: what the class assigns to one of its name)
159
+ locals[v.name.to_s] || (locals.key?(:seen) ? nil : (@lvars[v.name.to_s] || []).map { |w| kind(w, {seen: true}) }.compact.uniq.then { |ks| ks.length == 1 ? ks[0] : nil })
160
+ when Prism::InstanceVariableReadNode
161
+ # (another field: what the class assigns to it)
162
+ locals.key?(:fields) ? nil : (@ivars[v.name.to_s] || []).map { |w| kind(w, {fields: true}) }.compact.reject { |k| k == 'none' }.uniq.then { |ks| ks.length == 1 ? ks[0] : nil }
163
+ when Prism::ParenthesesNode then kind(v.body&.body&.last, locals)
164
+ when Prism::IfNode then [kind(v.statements&.body&.last, locals), kind(else_of(v), locals)]
165
+ when Prism::CallNode
166
+ return 'int' if clock?(v) || (ARITH.include?(v.name) && v.receiver) || %i[min max abs to_i size length count].include?(v.name)
167
+ return 'bool' if CMP.key?(v.name) || v.name.to_s.end_with?('?')
168
+ nil
169
+ end
170
+ end
171
+ def else_of(n)
172
+ e = n.respond_to?(:subsequent) ? n.subsequent : n.consequent
173
+ e.is_a?(Prism::ElseNode) ? e.statements&.body&.last : e
174
+ end
175
+ # The kinds a field is given: symbols a choice, nil an option, the others one scalar type (or none known).
176
+ def ivar_type(iv)
177
+ ks = (@ivars[iv] || []).flat_map { |v| k = kind(v, {}); k.is_a?(Array) && k[0] != :sym ? k : [k] }.compact
178
+ syms = ks.select { |k| k.is_a?(Array) }.map(&:last).uniq
179
+ rest = ks.reject { |k| k.is_a?(Array) }.uniq
180
+ none = rest.delete('none')
181
+ t = if syms.any? && rest.empty? then {'k' => 'choice', 'values' => syms, 'sym' => true}
182
+ elsif syms.empty? && rest.length == 1 then {'k' => rest[0]}
183
+ elsif syms.empty? && rest.sort == %w[float int] then {'k' => 'float'}
184
+ end
185
+ return {'k' => 'any'} unless t
186
+ none ? {'k' => 'opt', 'of' => t} : t
187
+ end
188
+ # An argument's type: what the method compares it with, computes it into, or its default.
189
+ def param_type(d, name, dflt)
190
+ syms, ints = [], false
191
+ each_node(d) do |n|
192
+ if n.is_a?(Prism::CaseNode) && n.predicate.is_a?(Prism::LocalVariableReadNode) && n.predicate.name.to_s == name
193
+ n.conditions.each { |w| w.conditions.each { |c| k = kind(c); syms << k[1] if k.is_a?(Array) } }
194
+ elsif n.is_a?(Prism::CallNode) && n.receiver && n.arguments&.arguments&.length == 1
195
+ a, b = n.receiver, n.arguments.arguments.first
196
+ [[a, b], [b, a]].each do |x, y|
197
+ next unless x.is_a?(Prism::LocalVariableReadNode) && x.name.to_s == name
198
+ k = kind(y)
199
+ if k.is_a?(Array) && %i[== !=].include?(n.name) then syms << k[1]
200
+ elsif ARITH.include?(n.name) || CMP.key?(n.name) then ints = true
201
+ end
202
+ end
203
+ end
204
+ end
205
+ return {'k' => 'choice', 'values' => syms.uniq, 'sym' => true} if syms.any?
206
+ k = dflt && kind(dflt)
207
+ return {'k' => k} if %w[int float bool str].include?(k)
208
+ return {'k' => 'int'} if ints
209
+ # (one the method keeps in a field: the field's type)
210
+ each_node(d) { |n| return ivar_type(n.name.to_s) if n.is_a?(Prism::InstanceVariableWriteNode) && n.value.is_a?(Prism::LocalVariableReadNode) && n.value.name.to_s == name }
211
+ {'k' => 'any'}
212
+ end
213
+
214
+ # --- methods ------------------------------------------------------------------------------------------------------
215
+ def fn_of(fid, name, node, params, body)
216
+ {'id' => fid, 'name' => name, 'cls' => @cls, 'p' => where(node), 'span' => [@base, node.location.start_line, node.location.end_line],
217
+ 'params' => [{'name' => 'self', 't' => {'k' => 'any'}, 'self' => true}, *params], 'ret' => {'k' => 'any'}, 'body' => body, 'decorators' => []}
218
+ end
219
+ def func(fid, d, nil_fields)
220
+ params, ps = [], d.parameters
221
+ if ps
222
+ ps.requireds.each { |x| params << {'name' => x.name.to_s, 't' => param_type(d, x.name.to_s, nil)} }
223
+ ps.optionals.each { |x| params << {'name' => x.name.to_s, 't' => param_type(d, x.name.to_s, x.value), 'dflt' => expr(x.value)} }
224
+ ps.keywords.each do |x|
225
+ dflt = x.respond_to?(:value) ? x.value : nil
226
+ clock = @clocks.include?(x.name.to_s)
227
+ params << {'name' => x.name.to_s, 't' => clock ? {'k' => 'opaque', 'why' => "#{x.name}, the clock (stated)"} : param_type(d, x.name.to_s, dflt), 'kw' => true,
228
+ **(clock ? {'dflt' => {'e' => 'opaque', 'why' => "#{x.name}, the clock (stated): read as the request's time", 'p' => where(x)}} : dflt ? {'dflt' => expr(dflt)} : {})}
229
+ end
230
+ params << {'name' => '*', 't' => {'k' => 'opaque', 'why' => '*args'}, 'star' => 1} if ps.rest
231
+ params << {'name' => '**', 't' => {'k' => 'opaque', 'why' => '**kwargs'}, 'star' => 2} if ps.keyword_rest
232
+ end
233
+ stmts = d.body.is_a?(Prism::StatementsNode) ? d.body.body : d.body ? [d.body] : []
234
+ # (a constructor: every field nil until it is set, as Ruby's are)
235
+ # (synthesized statements are at line 0: no line of the code to count)
236
+ pre = (nil_fields || []).map { |f| {'s' => 'set', 'p' => "#{@base}:0:0", 'to' => ivar(f, d), 'x' => {'e' => 'none', 'p' => where(d)}} }
237
+ fn_of(fid, d.name.to_s, d, params, pre + block(stmts, !nil_fields))
238
+ end
239
+
240
+ # --- statements: the last one's value is the method's (or the branch's) result -------------------------------------
241
+ def block(ss, tail)
242
+ ss.each_with_index.flat_map { |s, i| stmt(s, tail && i == ss.length - 1) }.then { |out| tail && ss.empty? ? [{'s' => 'ret', 'p' => "#{@base}:0:0"}] : out }
243
+ end
244
+ def body_of(n) = n.is_a?(Prism::StatementsNode) ? n.body : n.is_a?(Prism::ElseNode) ? (n.statements&.body || []) : n ? [n] : []
245
+ def stmt(s, tail)
246
+ p = where(s)
247
+ ret = ->(x) { tail ? [{'s' => 'ret', 'p' => p, 'x' => x}] : [{'s' => 'expr', 'p' => p, 'x' => x}] }
248
+ case s
249
+ when Prism::IfNode, Prism::UnlessNode
250
+ th = block(body_of(s.statements), tail)
251
+ el = block(body_of(s.is_a?(Prism::IfNode) ? (s.respond_to?(:subsequent) ? s.subsequent : s.consequent) : s.else_clause), tail)
252
+ c = expr(s.predicate)
253
+ [{'s' => 'if', 'p' => p, 'c' => s.is_a?(Prism::UnlessNode) ? {'e' => 'not', 'x' => c, 'p' => p} : c, 'then' => th, 'else' => el}]
254
+ when Prism::CaseNode
255
+ return [{'s' => 'no', 'p' => p, 'why' => 'case without a value'}] unless s.predicate
256
+ subj = expr(s.predicate)
257
+ s.conditions.reverse.reduce(block(body_of(s.else_clause), tail)) do |rest, w|
258
+ c = {'e' => 'or', 'xs' => w.conditions.map { |x| {'e' => 'cmp', 'op' => '==', 'x' => subj, 'y' => expr(x), 'p' => where(x), 'text' => text(x)} }, 'p' => where(w)}
259
+ # (at line 0: Ruby counts no line at a when)
260
+ [{'s' => 'if', 'p' => "#{@base}:0:0", 'c' => c, 'then' => block(body_of(w.statements), tail), 'else' => rest}]
261
+ end
262
+ when Prism::ReturnNode
263
+ a = s.arguments&.arguments || []
264
+ [{'s' => 'ret', 'p' => p, **(a.length == 1 ? {'x' => expr(a[0])} : a.empty? ? {} : {'x' => no(s, 'a return of several values')})}]
265
+ when Prism::LocalVariableWriteNode then [{'s' => 'set', 'p' => p, 'to' => {'e' => 'var', 'n' => s.name.to_s, 'p' => p}, 'x' => expr(s.value)}, *(tail ? ret.({'e' => 'var', 'n' => s.name.to_s, 'p' => p}) : [])]
266
+ when Prism::InstanceVariableWriteNode then [{'s' => 'set', 'p' => p, 'to' => ivar(s.name.to_s, s), 'x' => expr(s.value)}, *(tail ? ret.(ivar(s.name.to_s, s)) : [])]
267
+ when Prism::InstanceVariableOperatorWriteNode, Prism::LocalVariableOperatorWriteNode
268
+ t = s.is_a?(Prism::LocalVariableOperatorWriteNode) ? {'e' => 'var', 'n' => s.name.to_s, 'p' => p} : ivar(s.name.to_s, s)
269
+ op = s.respond_to?(:binary_operator) ? s.binary_operator : s.operator
270
+ [{'s' => 'set', 'p' => p, 'to' => t, 'x' => binop(op, t, expr(s.value), s)}, *(tail ? ret.(t) : [])]
271
+ when Prism::CallNode
272
+ if s.name == :raise && !s.receiver then return [{'s' => 'fail', 'p' => p, 'why' => "raise #{text(s.arguments || s)}".sub(/raise raise/, 'raise')}] end
273
+ if s.name == :synchronize && s.block.is_a?(Prism::BlockNode) && s.receiver
274
+ return [{'s' => 'with', 'p' => p, 'items' => [{'x' => expr(s.receiver)}], 'body' => block(body_of(s.block.body), tail)}]
275
+ end
276
+ ret.(expr(s))
277
+ when Prism::ParenthesesNode then block(body_of(s.body), tail)
278
+ when Prism::WhileNode, Prism::UntilNode, Prism::ForNode then [{'s' => 'no', 'p' => p, 'why' => 'a loop'}]
279
+ when Prism::BeginNode then [{'s' => 'no', 'p' => p, 'why' => 'begin/rescue (an exception caught: the subset reads one only as the step\'s failure)'}]
280
+ when Prism::DefNode, Prism::ClassNode, Prism::ModuleNode then [{'s' => 'no', 'p' => p, 'why' => 'a definition inside a method'}]
281
+ else ret.(expr(s))
282
+ end
283
+ end
284
+ def ivar(name, n) = {'e' => 'get', 'x' => {'e' => 'var', 'n' => 'self', 'p' => where(n)}, 'f' => name, 'p' => where(n), 'text' => name}
285
+ def binop(op, a, b, n)
286
+ o = {:+ => '+', :- => '-', :* => '*', :/ => '//', :% => '%'}[op.to_sym]
287
+ return no(n, "#{text(n)}: #{op} (outside the subset)") unless o
288
+ return no(n, "#{text(n)}: a float division (the subset reads whole numbers)") if o == '//' && (a['float'] || b['float'])
289
+ {'e' => 'bin', 'op' => o, 'x' => a, 'y' => b, 'p' => where(n), 'text' => text(n)}
290
+ end
291
+ def clock?(n)
292
+ return false unless n.is_a?(Prism::CallNode)
293
+ r = n.receiver
294
+ (%i[current_time now].include?(n.name) && r && @clocks.include?(r.slice.delete_prefix('@').delete_prefix('self.'))) ||
295
+ (%i[to_i to_f].include?(n.name) && r.is_a?(Prism::CallNode) && r.name == :now && r.receiver&.slice == 'Time') ||
296
+ (n.name == :clock_gettime && r&.slice == 'Process')
297
+ end
298
+
299
+ # --- expressions --------------------------------------------------------------------------------------------------
300
+ def call(f, args, n) = {'e' => 'call', 'f' => f, 'args' => args, 'kw' => [], 'p' => where(n), 'text' => text(n)}
301
+ def self_call(name, args, n) = call({'e' => 'get', 'x' => {'e' => 'var', 'n' => 'self', 'p' => where(n)}, 'f' => name, 'p' => where(n), 'text' => name}, args, n)
302
+ def expr(x)
303
+ p = where(x)
304
+ case x
305
+ when Prism::IntegerNode then {'e' => 'int', 'v' => x.value.to_s, 'p' => p}
306
+ when Prism::FloatNode then x.value == x.value.floor && x.value.abs < 2**53 ? {'e' => 'int', 'v' => x.value.to_i.to_s, 'float' => true, 'p' => p} : no(x, "#{text(x)}: a float that isn't whole (a binary fraction)")
307
+ when Prism::StringNode then {'e' => 'str', 'v' => x.unescaped, 'p' => p}
308
+ when Prism::SymbolNode then {'e' => 'str', 'v' => x.unescaped, 'p' => p}
309
+ when Prism::TrueNode, Prism::FalseNode then {'e' => 'bool', 'v' => x.is_a?(Prism::TrueNode), 'p' => p}
310
+ when Prism::NilNode then {'e' => 'none', 'p' => p}
311
+ when Prism::SelfNode then {'e' => 'var', 'n' => 'self', 'p' => p}
312
+ when Prism::LocalVariableReadNode then {'e' => 'var', 'n' => x.name.to_s, 'p' => p}
313
+ when Prism::InstanceVariableReadNode then ivar(x.name.to_s, x)
314
+ when Prism::ConstantReadNode, Prism::ConstantPathNode then (c = const(x, @nest)) ? c.reject { |k, _| %w[sym file].include?(k) }.merge('p' => p) : no(x, "#{text(x)}: a constant the reader can't resolve to a literal")
315
+ when Prism::ParenthesesNode then (b = body_of(x.body)).length == 1 ? expr(b[0]) : no(x, "#{text(x)}: several statements as a value")
316
+ when Prism::AndNode, Prism::OrNode then {'e' => x.is_a?(Prism::AndNode) ? 'and' : 'or', 'xs' => [expr(x.left), expr(x.right)], 'p' => p}
317
+ when Prism::IfNode
318
+ el = else_of(x)
319
+ return no(x, "#{text(x)}: an if of several statements as a value") if (x.statements&.body || []).length > 1
320
+ {'e' => 'ite', 'c' => expr(x.predicate), 'a' => x.statements ? expr(x.statements.body.last) : {'e' => 'none', 'p' => p}, 'b' => el ? expr(el) : {'e' => 'none', 'p' => p}, 'p' => p}
321
+ when Prism::InterpolatedStringNode
322
+ {'e' => 'fstr', 'parts' => x.parts.map { |q| q.is_a?(Prism::StringNode) ? q.unescaped : {'x' => q.statements&.body&.length == 1 ? expr(q.statements.body[0]) : no(q, 'an interpolation'), 'plain' => true} }, 'p' => p, 'text' => text(x)}
323
+ when Prism::CallNode then call_expr(x)
324
+ else no(x, "#{text(x)}: #{x.type} (outside the subset)")
325
+ end
326
+ end
327
+ def call_expr(x)
328
+ p, r, n, args = where(x), x.receiver, x.name, x.arguments&.arguments || []
329
+ return no(x, "#{text(x)}: a block (a closure)") if x.block.is_a?(Prism::BlockNode)
330
+ return no(x, "#{text(x)}: &. (a call on a value that may be nil)") if x.safe_navigation?
331
+ return {'e' => 'call', 'f' => {'e' => 'lib', 'q' => 'time.time', 'p' => p}, 'args' => [], 'kw' => [], 'p' => p, 'text' => text(x)} if clock?(x)
332
+ return self_call(n.to_s, args.map { |a| expr(a) }, x) if !r || r.is_a?(Prism::SelfNode)
333
+ rv = r.is_a?(Prism::ArrayNode) ? nil : expr(r)
334
+ return binop(n, rv, expr(args[0]), x) if ARITH.include?(n) && args.length == 1
335
+ return {'e' => 'cmp', 'op' => CMP[n], 'x' => rv, 'y' => expr(args[0]), 'p' => p, 'text' => text(x)} if CMP.key?(n) && args.length == 1
336
+ case n
337
+ when :! then {'e' => 'not', 'x' => rv, 'p' => p}
338
+ when :-@ then {'e' => 'neg', 'x' => rv, 'p' => p}
339
+ when :nil? then {'e' => 'cmp', 'op' => 'is', 'x' => rv, 'y' => {'e' => 'none', 'p' => p}, 'p' => p, 'text' => text(x)}
340
+ when :zero?, :positive?, :negative?
341
+ {'e' => 'cmp', 'op' => {zero?: '==', positive?: '>', negative?: '<'}[n], 'x' => rv, 'y' => {'e' => 'int', 'v' => '0', 'p' => p}, 'p' => p, 'text' => text(x)}
342
+ when :abs then call({'e' => 'builtin', 'n' => 'abs', 'p' => p}, [rv], x)
343
+ when :to_i, :to_f, :to_int then call({'e' => 'builtin', 'n' => 'int', 'p' => p}, [rv], x)
344
+ when :min, :max
345
+ return call({'e' => 'builtin', 'n' => n.to_s, 'p' => p}, r.elements.map { |e| expr(e) }, x) if r.is_a?(Prism::ArrayNode) && args.empty?
346
+ no(x, "#{text(x)}: #{n} of a collection")
347
+ when :clamp
348
+ return no(x, "#{text(x)}: clamp of a range") unless args.length == 2
349
+ call({'e' => 'builtin', 'n' => 'max', 'p' => p}, [expr(args[0]), call({'e' => 'builtin', 'n' => 'min', 'p' => p}, [rv, expr(args[1])], x)], x)
350
+ when :new
351
+ return {'e' => 'call', 'f' => {'e' => 'lib', 'q' => 'threading.Lock', 'p' => p}, 'args' => [], 'kw' => [], 'p' => p, 'text' => text(x)} if r.slice =~ /\A(::)?(Thread::)?(Mutex|Monitor)\z/
352
+ no(x, "#{text(x)}: an object of another class made")
353
+ else
354
+ return no(x, "#{text(x)}: a method of an array") if r.is_a?(Prism::ArrayNode)
355
+ # (another class's code: at the boundary where it is inferred, with the names its arguments mention)
356
+ return no(x, "#{text(x)}: #{r.slice}, another class's code").merge('ext' => "#{r.slice}.#{n}", 'names' => mentioned(args), 'patch' => {'mod' => r.slice, 'path' => [n.to_s]}) if r.is_a?(Prism::ConstantReadNode) || r.is_a?(Prism::ConstantPathNode)
357
+ call({'e' => 'get', 'x' => rv, 'f' => n.to_s, 'p' => p, 'text' => text(x)}, args.map { |a| expr(a) }, x)
358
+ end
359
+ end
360
+ end
361
+
362
+ req = JSON.parse(ARGV[0])
363
+ r = Reader.new(req)
364
+ cls = r.classes
365
+ out = {'lang' => 'ruby', 'file' => File.basename(req['file']), 'path' => File.expand_path(req['file']), 'module' => File.basename(req['file'], '.rb'),
366
+ 'root' => File.expand_path(req['root']), 'truth' => 'nil-false', 'entries' => []}
367
+ # (no names: every class of the file, for the entry inferred)
368
+ (req['names'].empty? ? cls.keys : req['names']).each do |n|
369
+ key = cls.key?(n) ? n : cls.keys.find { |k| k.end_with?("::#{n}") }
370
+ out['entries'] << (key ? {'k' => 'class', 'rec' => r.rec_of(key, *cls[key])} : {'k' => 'missing', 'name' => n})
371
+ end
372
+ out['recs'] = r.instance_variable_get(:@recs)
373
+ out['funcs'] = r.instance_variable_get(:@funcs)
374
+ out['loads'] = r.loads
375
+ puts JSON.generate(out)