sigmold 0.1.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.
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "yaml"
5
+ require_relative "typecheck"
6
+ require_relative "holes"
7
+ require_relative "strict"
8
+ require_relative "surface_check"
9
+ require_relative "calls"
10
+
11
+ module Sigmold
12
+ # Runs every check of the mold in one go, as `sigmold.yml` in the current
13
+ # folder describes the project:
14
+ #
15
+ # namespace: Shop # the module sig/ shapes
16
+ # require: shop # what loads it, from lib/
17
+ # sig: [sig] # the signature folders
18
+ # test: ruby -Ilib test/cart_test.rb # what runs its tests
19
+ #
20
+ # A project passes when no hole is left, nothing lets the code past its
21
+ # types, sig/ shows the real surface, and the tests pass, call that
22
+ # surface, and call all of it. `gaps` and `pour` stay apart: they need
23
+ # rewrites.
24
+ module Check
25
+ FILE = "sigmold.yml"
26
+
27
+ # @rbs out: IO
28
+ def self.run(out) #: bool
29
+ config = File.exist?(FILE) ? YAML.safe_load_file(FILE) : {} #: Hash[String, untyped]
30
+ namespace = config["namespace"] or raise ArgumentError, "#{FILE}: name the namespace"
31
+ sig = Array(config.fetch("sig", "sig"))
32
+ typecheck = Typecheck.new(".")
33
+ results = [
34
+ section(out, "holes") { Holes.within(typecheck).then { [_1.empty?, Holes.report(_1)] } },
35
+ section(out, "strict") { Strict.within(typecheck).then { [_1.empty?, Strict.report(_1)] } },
36
+ section(out, "surface") { surface(namespace, config["require"], sig) },
37
+ section(out, "calls") { calls(namespace, config["test"], sig) }
38
+ ]
39
+ results.all?
40
+ end
41
+
42
+ # @rbs out: IO
43
+ # @rbs name: String
44
+ # @rbs &: () -> [bool, String]
45
+ def self.section(out, name) #: bool
46
+ ok, text = yield
47
+ out.puts "== #{name}: #{ok ? 'ok' : 'found'}"
48
+ out.print text
49
+ ok
50
+ end
51
+
52
+ # @rbs namespace: String
53
+ # @rbs feature: String?
54
+ # @rbs sig: Array[String]
55
+ # @rbs return: [bool, String]
56
+ def self.surface(namespace, feature, sig)
57
+ $LOAD_PATH.unshift(File.expand_path("lib"))
58
+ require(feature || namespace.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase)
59
+ found = SurfaceCheck.gaps(Object.const_get(namespace), sig:, lib: "lib")
60
+ [found.empty?, SurfaceCheck.report(found)]
61
+ end
62
+
63
+ # @rbs namespace: String
64
+ # @rbs test: String?
65
+ # @rbs sig: Array[String]
66
+ # @rbs return: [bool, String]
67
+ def self.calls(namespace, test, sig)
68
+ return [false, "#{FILE} names no test command, so nothing shows the tests stay on sig/\n"] unless test
69
+
70
+ seen, status = Calls.record(namespace, ["sh", "-c", test], out: File::NULL)
71
+ note = status.success? ? "" : "the tests failed (exit #{status.exitstatus})\n"
72
+ return [false, "#{note}the tests called nothing in #{namespace}\n"] if seen.empty?
73
+
74
+ found = Calls.gaps(seen, Signature.new(sig), namespace)
75
+ [found.empty? && status.success?, note + Calls.report(found)]
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require_relative "signature"
5
+
6
+ module Sigmold
7
+ # Reads which classes each class's public signature names, the way a
8
+ # reader of C++ headers read the includes. A class that names another in
9
+ # its public methods depends on it; a cycle means neither can be read,
10
+ # tested, or poured alone.
11
+ module Deps
12
+ # Each module or class the signatures declare, with the others of
13
+ # those signatures that its public methods name.
14
+ #
15
+ # @rbs signature: Signature
16
+ # @rbs return: Hash[String, Array[String]]
17
+ def self.edges(signature)
18
+ own = signature.own_modules
19
+ own.to_h do |owner|
20
+ named = signature.entries(owner).flat_map { |e| e.types.flat_map { names(_1) } }
21
+ [owner, (named.map { _1.delete_prefix("::") }.uniq & own) - [owner]]
22
+ end
23
+ end
24
+
25
+ # @rbs node: untyped
26
+ # @rbs return: Array[String]
27
+ def self.names(node)
28
+ own = node.respond_to?(:name) && node.name.respond_to?(:namespace) ? [node.name.to_s] : [] #: Array[String]
29
+ inner = [] #: Array[untyped]
30
+ node.each_type { inner << _1 } if node.respond_to?(:each_type)
31
+ node.type.then { inner << _1 } if node.respond_to?(:type) && node.type && !node.respond_to?(:each_type)
32
+ own + inner.flat_map { names(_1) }
33
+ end
34
+
35
+ # The cycles among +edges+, each from its smallest name.
36
+ #
37
+ # @rbs edges: Hash[String, Array[String]]
38
+ # @rbs return: Array[Array[String]]
39
+ def self.cycles(edges)
40
+ found = [] #: Array[Array[String]]
41
+ walk = lambda do |path|
42
+ edges.fetch(path.last, []).each do |nxt|
43
+ if nxt == path.first then found << path
44
+ elsif !path.include?(nxt) && nxt > path.first then walk.([*path, nxt])
45
+ end
46
+ end
47
+ end
48
+ edges.keys.sort.each { walk.([_1]) }
49
+ found
50
+ end
51
+
52
+ # @rbs edges: Hash[String, Array[String]]
53
+ # @rbs return: String
54
+ def self.report(edges)
55
+ lines = edges.sort.map { |owner, uses| "#{owner} -> #{uses.empty? ? '(nothing)' : uses.sort.join(', ')}" }
56
+ lines += cycles(edges).map { "cycle: #{[*_1, _1.first].join(' -> ')}" }
57
+ lines.join("\n") + "\n"
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,443 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require_relative "signature"
5
+
6
+ module Sigmold
7
+ # An explorer built from a class's signature, so `gaps` needs no explorer
8
+ # written by hand. It makes one instance with `new`, then calls the
9
+ # public instance methods with values drawn from their parameter types,
10
+ # and observes each return value, each raised error, and each block call.
11
+ #
12
+ # Values stay plain data in the plan (a class in the namespace is a
13
+ # `[:build, name, args, keywords]` node), so a plan prints, shrinks, and
14
+ # replays on every implementation the same way. A method whose parameter
15
+ # type it cannot draw is left out and named in +skipped+.
16
+ class Explore
17
+ # Text is drawn from pieces, so spaces, runs of spaces, newlines, long
18
+ # words, and the empty string all come up.
19
+ PIECES = ["a", "bc", "tea", "words", " ", " ", "\n", "-", "1"].freeze
20
+ SYMBOLS = %i[a b].freeze
21
+ # A type variable stands for keys and names more often than for
22
+ # numbers, and two names must sometimes collide.
23
+ VARIABLES = [:a, :b, "c"].freeze
24
+ DEPTH = 2
25
+
26
+ attr_reader :skipped #: Array[String]
27
+
28
+ # The steps the signature leaves free, such as "new -> raises
29
+ # ArgumentError": `%a{sigmold:free: <step>}` above the class, or
30
+ # `%a{sigmold:free: <outcome>}` on a method, such as "returns".
31
+ attr_reader :free #: Array[String]
32
+
33
+ FREE = "sigmold:free:"
34
+
35
+ # +const+ is the class to explore under its full name, such as
36
+ # "Shop::Cart"; +root+ is the module the implementation file opens.
37
+ #
38
+ # @rbs signature: Signature
39
+ # @rbs const: String
40
+ # @rbs root: String
41
+ # @rbs length: Range[Integer]
42
+ # @rbs messages: bool
43
+ def initialize(signature, const, root:, length: 1..8, messages: false) #: void
44
+ @messages = messages
45
+ @signature = signature
46
+ @const = const
47
+ @root = root
48
+ @length = length
49
+ entries = signature.entries(const)
50
+ # A module has no instance: its calls are its own singleton methods.
51
+ @made = signature.class_named?(const)
52
+ @new = entries.find { _1.singleton && _1.name == :new }
53
+ callable = entries.reject { _1.singleton && _1.name == :new }
54
+ @methods, skipped = callable.partition { |e| e.types.any? { drawable?(_1) } }
55
+ @skipped = skipped.map(&:id)
56
+ # What a `void` method returns is nobody's contract.
57
+ @void = entries.select { |e| e.types.all? { _1.type.return_type.to_s == "void" } }.map { op_name(_1) }
58
+ # Zero-argument methods that return something: what an object of the
59
+ # namespace shows when a call returns one.
60
+ @readers = {} #: Hash[String, Array[Symbol]]
61
+ own = entries.flat_map { |e| e.annotations.filter_map { "#{op_name(e)} -> #{_1.delete_prefix(FREE).strip}" if _1.start_with?(FREE) } }
62
+ @free = signature.annotations_of(const).filter_map { _1.delete_prefix(FREE).strip if _1.start_with?(FREE) } + own
63
+ end
64
+
65
+ # @rbs random: Random
66
+ # @rbs return: Array[untyped]
67
+ def plan(random)
68
+ made = @new && @new.types.select { drawable?(_1) }.sample(random:)
69
+ nothing = [[], {}, nil] #: [Array[untyped], Hash[String, untyped], untyped]
70
+ first = @made ? [[:new, *(made ? arguments(made, random) : nothing)]] : [] #: Array[untyped]
71
+ calls = Array.new(random.rand(@length)) do
72
+ entry = @methods.sample(random:) or break []
73
+ type = entry.types.select { drawable?(_1) }.sample(random:)
74
+ args, keywords, block = arguments(type, random)
75
+ # A block sometimes calls back into the object it was given to, the
76
+ # way a callback does; that is where implementations part most.
77
+ block = [*block, inner_call(random)] if block && random.rand(3).zero?
78
+ [op_name(entry), args, keywords, block]
79
+ end
80
+ [*first, *calls]
81
+ end
82
+
83
+ # One entry per operation: what it returned or raised, and what the
84
+ # block it was given saw.
85
+ #
86
+ # @rbs klass: untyped
87
+ # @rbs ops: Array[untyped]
88
+ # @rbs return: Array[untyped]
89
+ def run(klass, ops)
90
+ space = klass.name.delete_suffix(@const.delete_prefix(@root))
91
+ resolve = ->(name) { Object.const_get(name.sub(/\A#{Regexp.escape(@root)}(?=::|\z)/, space)) }
92
+ subject = nil #: untyped
93
+ value_of = ->(node) { build(node, resolve, subject) }
94
+ ops.map do |name, args, keywords, block|
95
+ yielded = [] #: Array[untyped]
96
+ # An argument that cannot be built, such as an object of the
97
+ # namespace its own `new` refuses, says nothing about this call.
98
+ values = [] #: Array[untyped]
99
+ options = {} #: Hash[Symbol, untyped]
100
+ built = attempt(subject) do
101
+ values = value_of.(args)
102
+ options = value_of.(keywords).transform_keys(&:to_sym)
103
+ end
104
+ next [name, :argument, *built.drop(1)] if built[0] == :err
105
+
106
+ outcome = attempt(subject) do
107
+ proc = block && lambda do |*given|
108
+ yielded << observe(given, subject)
109
+ if (inner = block[2])
110
+ yielded << [:inside, inner[0], *attempt(subject) do
111
+ extra = value_of.(inner[2]).transform_keys(&:to_sym) #: Hash[Symbol, untyped]
112
+ result = (inner[0].is_a?(String) ? klass : subject).public_send(inner[0].to_sym, *value_of.(inner[1]), **extra)
113
+ @void.include?(inner[0]) ? :void : result
114
+ end]
115
+ end
116
+ value_of.(block[1])
117
+ end
118
+ if name == :new
119
+ subject = klass.new(*values, **options, &proc)
120
+ :made
121
+ else
122
+ result = (name.is_a?(String) ? klass : subject).public_send(name.to_sym, *values, **options, &proc)
123
+ @void.include?(name) ? :void : result
124
+ end
125
+ end
126
+ yielded.empty? ? [name, *outcome] : [name, *outcome, [:yielded, yielded]]
127
+ end
128
+ end
129
+
130
+ # Shrinking keeps the call that makes the object: without it every
131
+ # later call would fail on nil, which says nothing about the class.
132
+ #
133
+ # @rbs op: Array[untyped]
134
+ def kept?(op) = op[0] == :new #: bool
135
+
136
+ # @rbs step: untyped
137
+ def telling?(step) = step.is_a?(Array) && step[1] == :argument #: bool
138
+
139
+ # Each operation is a step, so a key names the first call that parts.
140
+ #
141
+ # @rbs observation: Array[untyped]
142
+ # @rbs return: Array[untyped]
143
+ def steps(observation) = observation
144
+
145
+ # @rbs step: untyped
146
+ # @rbs return: String
147
+ def label(step)
148
+ return "end of run" if step.nil?
149
+
150
+ text = case step[1]
151
+ when :ok then "#{step[0]} -> returns"
152
+ when :argument then "an argument of #{step[0]} -> raises #{step[2]}"
153
+ else "#{step[0]} -> raises #{step[2]}"
154
+ end
155
+ # A call the block makes back into the object is its own question.
156
+ yielded = step.find { _1.is_a?(Array) && _1[0] == :yielded }
157
+ inside = yielded && yielded[1].find { _1.is_a?(Array) && _1[0] == :inside }
158
+ inside ? "#{text}, its block calls #{inside[1]}" : text
159
+ end
160
+
161
+ # The operations as Ruby a person reads, one call per line.
162
+ #
163
+ # @rbs ops: Array[untyped]
164
+ # @rbs return: Array[String]
165
+ def describe(ops)
166
+ me = @const.split("::").last.to_s.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase
167
+ ops.map do |name, args, keywords, block|
168
+ call = if name == :new then "#{me} = #{@const}.new"
169
+ elsif name.is_a?(String) then "#{@const}.#{name}"
170
+ else "#{me}.#{name}"
171
+ end
172
+ list = [*args.map { ruby(_1, me) }, *keywords.map { "#{_1}: #{ruby(_2, me)}" }]
173
+ call += "(#{list.join(', ')})" unless list.empty?
174
+ if block
175
+ inner = block[2] && "#{block[2][0].is_a?(String) ? @const : me}.#{block[2][0]}(#{[*block[2][1].map { ruby(_1, me) }, *block[2][2].map { "#{_1}: #{ruby(_2, me)}" }].join(', ')}); "
176
+ call += " { #{inner}#{ruby(block[1], me)} }"
177
+ end
178
+ call
179
+ end
180
+ end
181
+
182
+ private
183
+
184
+ # @rbs node: untyped
185
+ # @rbs me: String
186
+ # @rbs return: String
187
+ def ruby(node, me)
188
+ if node == [:subject] then me
189
+ elsif node.is_a?(Array) && node[0] == :build
190
+ _, name, args, keywords = node
191
+ list = [*args.map { ruby(_1, me) }, *keywords.map { "#{_1}: #{ruby(_2, me)}" }]
192
+ "#{name}.new(#{list.join(', ')})"
193
+ elsif node.is_a?(Array) then "[#{node.map { ruby(_1, me) }.join(', ')}]"
194
+ elsif node.is_a?(Hash) then "{#{node.map { "#{ruby(_1, me)} => #{ruby(_2, me)}" }.join(', ')}}"
195
+ else node.inspect
196
+ end
197
+ end
198
+
199
+ # A call the block makes on the object, without a block of its own.
200
+ #
201
+ # @rbs random: Random
202
+ # @rbs return: Array[untyped]?
203
+ def inner_call(random)
204
+ entry = @methods.reject { |e| e.types.all? { _1.block&.required } }.sample(random:) or return nil
205
+ type = entry.types.select { drawable?(_1) && !_1.block&.required }.sample(random:) or return nil
206
+ args, keywords, = arguments(type, random)
207
+ [op_name(entry), args, keywords]
208
+ end
209
+
210
+ # An instance method's operation is its Symbol, a singleton method's
211
+ # its String, so one plan holds both.
212
+ #
213
+ # @rbs entry: Signature::Entry
214
+ # @rbs return: Symbol | String
215
+ def op_name(entry)
216
+ entry.singleton ? entry.name.to_s : entry.name
217
+ end
218
+
219
+ # @rbs owner: String
220
+ # @rbs return: Array[Symbol]
221
+ def readers_of(owner)
222
+ @signature.entries(owner).reject(&:singleton).filter_map do |e|
223
+ e.name if e.types.any? { |t| params_of(t).empty? && t.block.nil? && t.type.return_type.to_s != "void" } &&
224
+ !e.name.end_with?("!") && !%i[hash dup clone freeze].include?(e.name)
225
+ end
226
+ end
227
+
228
+ # @rbs type: untyped
229
+ def drawable?(type) #: bool
230
+ function = type.type
231
+ return false unless function.respond_to?(:required_positionals)
232
+
233
+ params = params_of(type)
234
+ block = type.block
235
+ block_ok = block.nil? || draw?(block.type.return_type, 0)
236
+ params.all? { draw?(_1.type, 0) } && block_ok
237
+ end
238
+
239
+ # @rbs type: untyped
240
+ # @rbs depth: Integer
241
+ def draw?(type, depth) #: bool
242
+ case kind(type)
243
+ when :base, :literal, :instance, :variable then true
244
+ when :union then type.types.all? { draw?(_1, depth) }
245
+ when :optional then draw?(type.type, depth)
246
+ when :tuple then type.types.all? { draw?(_1, depth) }
247
+ when :record then type.fields.values.all? { draw?(_1, depth) }
248
+ when :generic then type.args.all? { draw?(_1, depth) }
249
+ when :build
250
+ return false if depth >= DEPTH
251
+
252
+ made = @signature.entries(name_of(type)).find { _1.singleton && _1.name == :new }
253
+ !made.nil? && made.types.any? { |t| params_of(t).all? { draw?(_1.type, depth + 1) } }
254
+ else false
255
+ end
256
+ end
257
+
258
+ # @rbs type: untyped
259
+ # @rbs random: Random
260
+ # @rbs return: [Array[untyped], Hash[String, untyped], untyped]
261
+ def arguments(type, random)
262
+ function = type.type
263
+ args = function.required_positionals.map { draw(_1.type, random, 0) }
264
+ # Ruby fills trailing positionals first, so optional ones go in only
265
+ # when there are none after them.
266
+ if function.trailing_positionals.empty?
267
+ function.optional_positionals.each { |p| random.rand(2).zero? ? (break) : args << draw(p.type, random, 0) }
268
+ end
269
+ args += function.trailing_positionals.map { draw(_1.type, random, 0) }
270
+ keywords = function.required_keywords.to_h { [_1.to_s, draw(_2.type, random, 0)] }
271
+ function.optional_keywords.each { |k, p| keywords[k.to_s] = draw(p.type, random, 0) if random.rand(2).zero? }
272
+ # A block is a node of its own, so one whose drawn value is nil or
273
+ # false is still given.
274
+ block = type.block && (type.block.required || random.rand(2).zero?) ? [:block, draw(type.block.type.return_type, random, 0)] : nil
275
+ [args, keywords, block]
276
+ end
277
+
278
+ # @rbs type: untyped
279
+ # @rbs random: Random
280
+ # @rbs depth: Integer
281
+ # @rbs return: untyped
282
+ def draw(type, random, depth)
283
+ case kind(type)
284
+ when :literal then type.literal
285
+ when :union then draw(type.types.sample(random:), random, depth)
286
+ when :optional then random.rand(4).zero? ? nil : draw(type.type, random, depth)
287
+ when :tuple then type.types.map { draw(_1, random, depth) }
288
+ when :record then type.fields.to_h { [_1, draw(_2, random, depth)] }
289
+ when :generic then generic(type, random, depth)
290
+ when :build then build_node(type, random, depth)
291
+ when :instance then [:subject]
292
+ when :variable then VARIABLES.sample(random:)
293
+ else base(type, random)
294
+ end
295
+ end
296
+
297
+ # @rbs type: untyped
298
+ # @rbs random: Random
299
+ # @rbs return: untyped
300
+ def base(type, random)
301
+ case type.to_s
302
+ when "::Integer" then random.rand(-2..12)
303
+ when "::Float" then random.rand(-2..12) / 2.0
304
+ when "::String" then Array.new(random.rand(0..5)) { PIECES.sample(random:) }.join
305
+ when "::Symbol" then SYMBOLS.sample(random:)
306
+ when "bool", "boolish" then random.rand(2).zero?
307
+ when "nil", "void" then nil
308
+ else [nil, 0, "a", :a, true].sample(random:)
309
+ end
310
+ end
311
+
312
+ # @rbs type: untyped
313
+ # @rbs random: Random
314
+ # @rbs depth: Integer
315
+ # @rbs return: untyped
316
+ def generic(type, random, depth)
317
+ size = random.rand(0..3)
318
+ case type.name.to_s
319
+ when "::Array" then Array.new(size) { draw(type.args[0], random, depth) }
320
+ when "::Hash" then Array.new(size) { [draw(type.args[0], random, depth), draw(type.args[1], random, depth)] }.to_h
321
+ end
322
+ end
323
+
324
+ # @rbs type: untyped
325
+ # @rbs random: Random
326
+ # @rbs depth: Integer
327
+ # @rbs return: untyped
328
+ def build_node(type, random, depth)
329
+ made = @signature.entries(name_of(type)).find { _1.singleton && _1.name == :new } or raise "no new"
330
+ usable = made.types.select { |t| params_of(t).all? { draw?(_1.type, depth + 1) } }
331
+ args, keywords, = arguments(usable.sample(random:), random)
332
+ [:build, name_of(type), args, keywords]
333
+ end
334
+
335
+ BASE = %w[::Integer ::Float ::String ::Symbol bool boolish nil void untyped].freeze
336
+
337
+ # @rbs type: untyped
338
+ # @rbs return: Symbol
339
+ def kind(type)
340
+ class_name = type.class.name.to_s.split("::").last
341
+ case class_name
342
+ when "Literal" then :literal
343
+ when "Union" then :union
344
+ when "Optional" then :optional
345
+ when "Tuple" then :tuple
346
+ when "Record" then :record
347
+ when "Bool", "Nil", "Void", "Top" then :base
348
+ when "Instance", "Self" then :instance
349
+ when "Variable" then :variable
350
+ when "ClassInstance"
351
+ name = type.name.to_s
352
+ if %w[::Array ::Hash].include?(name) then :generic
353
+ elsif BASE.include?(name) then :base
354
+ elsif in_root?(name.delete_prefix("::")) then :build
355
+ else :other
356
+ end
357
+ else BASE.include?(type.to_s) ? :base : :other
358
+ end
359
+ end
360
+
361
+ # @rbs type: untyped
362
+ # @rbs return: String
363
+ def name_of(type)
364
+ type.name.to_s.delete_prefix("::")
365
+ end
366
+
367
+ # @rbs type: untyped
368
+ # @rbs return: Array[untyped]
369
+ def params_of(type)
370
+ f = type.type
371
+ params = f.required_positionals + f.optional_positionals + f.trailing_positionals + f.required_keywords.values +
372
+ f.optional_keywords.values
373
+ f.rest_positionals ? params + [f.rest_positionals] : params
374
+ end
375
+
376
+ # @rbs name: String
377
+ def in_root?(name) #: bool
378
+ name == @root || name.start_with?("#{@root}::")
379
+ end
380
+
381
+ # Turns plan data into values for one implementation. `[:subject]`
382
+ # stands for the instance under test, where a parameter wants one.
383
+ #
384
+ # @rbs node: untyped
385
+ # @rbs resolve: ^(String) -> untyped
386
+ # @rbs subject: untyped
387
+ # @rbs return: untyped
388
+ def build(node, resolve, subject)
389
+ again = ->(inner) { build(inner, resolve, subject) }
390
+ if node == [:subject]
391
+ subject
392
+ elsif node.is_a?(Array) && node[0] == :build
393
+ _, name, args, keywords = node
394
+ options = again.(keywords).transform_keys(&:to_sym) #: Hash[Symbol, untyped]
395
+ resolve.(name).new(*again.(args), **options)
396
+ elsif node.is_a?(Array)
397
+ node.map(&again)
398
+ elsif node.is_a?(Hash)
399
+ node.to_h { [again.(_1), again.(_2)] }
400
+ else
401
+ node
402
+ end
403
+ end
404
+
405
+ # @rbs subject: untyped
406
+ # @rbs &block: () -> untyped
407
+ # @rbs return: Array[untyped]
408
+ def attempt(subject, &block)
409
+ [:ok, observe(block.call, subject)]
410
+ rescue Exception => e # rubocop:disable Lint/RescueException
411
+ # Tests pin the class of an error far more often than its words, so
412
+ # the words count only when asked for.
413
+ @messages ? [:err, e.class.name, e.message.gsub(/0x\h+/, "0x?")] : [:err, e.class.name]
414
+ end
415
+
416
+ # A plain value both implementations can be compared by. An object of
417
+ # the namespace shows its class and its public readers when it is Data.
418
+ #
419
+ # @rbs value: untyped
420
+ # @rbs subject: untyped
421
+ # @rbs depth: Integer
422
+ # @rbs return: untyped
423
+ def observe(value, subject, depth = 0)
424
+ case value
425
+ when Integer, Float, String, Symbol, nil, true, false then value
426
+ when Array then value.map { observe(_1, subject, depth) }
427
+ when Hash then value.to_h { [observe(_1, subject, depth), observe(_2, subject, depth)] }
428
+ else
429
+ return :self if subject && value.equal?(subject)
430
+ return [value.class.name, observe(value.to_h, subject)] if value.is_a?(Data)
431
+
432
+ # An object of the namespace shows what its readers return, so two
433
+ # versions compare by value; one level deep, so a cycle ends.
434
+ owner = value.class.name.to_s.sub(/\A[^:]+(?=::)/) { _1.start_with?("SigmoldImpl") ? @root : _1 }
435
+ none = [] #: Array[Symbol]
436
+ readers = depth.zero? ? (@readers[owner] ||= @signature.declared?(owner) ? readers_of(owner) : none) : none
437
+ return [:object, value.class.name] if readers.empty?
438
+
439
+ [value.class.name, readers.to_h { |m| [m, attempt(subject) { observe(value.public_send(m), subject, depth + 1) }] }]
440
+ end
441
+ end
442
+ end
443
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module Sigmold
5
+ # The type of a hole. No other type accepts it, so Steep names the type
6
+ # each hole must become ("Cannot allow method body have type ::Sigmold::Hole
7
+ # because declared as type ::Integer"), where `raise NotImplementedError`
8
+ # would pass in silence.
9
+ class Hole
10
+ end
11
+
12
+ # Write `Sigmold.hole("name")` where code is still to be poured in.
13
+ #
14
+ # @rbs name: String
15
+ # @rbs return: Hole
16
+ def self.hole(name = "")
17
+ raise NotImplementedError, "sigmold: the hole #{name} is not filled"
18
+ end
19
+
20
+ # Put it in the `else` of a `case/when` that names every case. When a case
21
+ # is left, Steep names its type ("Cannot pass a value of type ::Tri as an
22
+ # argument of type bot"). Steep does not type `case/in`, so use `case/when`.
23
+ #
24
+ # @rbs value: bot
25
+ # @rbs return: bot
26
+ def self.absurd(value)
27
+ shown = value #: untyped
28
+ raise ArgumentError, "sigmold: a case the signature rules out was reached: #{shown.inspect}"
29
+ end
30
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require_relative "typecheck"
5
+
6
+ module Sigmold
7
+ # Lists the holes of a project, each with the type it must become and the
8
+ # local variables in scope there, as Steep infers them.
9
+ module Holes
10
+ Found = Data.define(
11
+ :path, #: String
12
+ :line, #: Integer
13
+ :name, #: String
14
+ :wanted, #: String?
15
+ :locals, #: Hash[String, String]
16
+ :self_type #: String
17
+ )
18
+
19
+ # @rbs root: String
20
+ # @rbs return: Array[Found]
21
+ def self.find(root)
22
+ within(Typecheck.new(root))
23
+ end
24
+
25
+ # @rbs check: Typecheck
26
+ # @rbs return: Array[Found]
27
+ def self.within(check)
28
+ check.sources.flat_map do |checked|
29
+ Nodes.each(checked.typing.source.node).select { hole_call?(_1) }.map do |node|
30
+ range = node.location.expression
31
+ wanted = checked.typing.errors.select { |e| e.respond_to?(:expected) && covers?(e, range) }
32
+ .min_by { _1.node.location.expression.size }
33
+ context = check.context_at(checked, range.begin_pos)
34
+ Found.new(
35
+ path: checked.path, line: range.line,
36
+ name: node.children[2]&.children&.first.to_s,
37
+ wanted: wanted&.expected&.to_s,
38
+ locals: context ? context.type_env.local_variable_types.to_h { |k, v| [k.to_s, v[0].to_s] } : {},
39
+ self_type: context&.self_type.to_s
40
+ )
41
+ end
42
+ end
43
+ end
44
+
45
+ # `Sigmold.hole(...)` or a bare `hole(...)`.
46
+ #
47
+ # @rbs node: untyped
48
+ def self.hole_call?(node) #: bool
49
+ return false unless node.type == :send && node.children[1] == :hole
50
+
51
+ receiver = node.children[0]
52
+ receiver.nil? || (receiver.type == :const && receiver.children[1] == :Sigmold)
53
+ end
54
+
55
+ # @rbs error: untyped
56
+ # @rbs range: untyped
57
+ def self.covers?(error, range) #: bool
58
+ node = error.respond_to?(:node) && error.node or return false
59
+ outer = node.location.expression
60
+ outer.begin_pos <= range.begin_pos && range.end_pos <= outer.end_pos
61
+ end
62
+
63
+ # @rbs found: Array[Found]
64
+ # @rbs return: String
65
+ def self.report(found)
66
+ return "no holes\n" if found.empty?
67
+
68
+ found.map do |f|
69
+ locals = f.locals.map { "#{_1}: #{_2}" }.join(", ")
70
+ "#{f.path}:#{f.line} ?#{f.name}\n wanted: #{f.wanted || '(Steep names no type here)'}\n in scope: #{locals.empty? ? '(none)' : locals}\n self: #{f.self_type}\n"
71
+ end.join
72
+ end
73
+ end
74
+
75
+ # Walks a Parser AST, which Steep's typing holds.
76
+ module Nodes
77
+ # @rbs node: untyped
78
+ # @rbs return: Array[untyped]
79
+ def self.each(node)
80
+ return [] unless node.respond_to?(:children) && node.respond_to?(:type)
81
+
82
+ [node, *node.children.flat_map { each(_1) }]
83
+ end
84
+ end
85
+ end