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,88 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "pathname"
5
+
6
+ module Sigmold
7
+ # Type checks a project the way its Steepfile says and hands back each
8
+ # Ruby file's typing. It drives Steep's type check service, which is not a
9
+ # public API, so this file is the one place that touches it.
10
+ class Typecheck
11
+ # One Ruby file Steep checked: its typing, and every diagnostic at every
12
+ # level. A Steepfile may hide a diagnostic as a hint; sigmold still sees it.
13
+ Checked = Data.define(
14
+ :path, #: String
15
+ :text, #: String
16
+ :typing, #: untyped
17
+ :target #: untyped
18
+ )
19
+
20
+ attr_reader :root #: String
21
+ attr_reader :project #: untyped
22
+ attr_reader :service #: untyped
23
+
24
+ # @rbs root: String
25
+ def initialize(root) #: void
26
+ require "steep"
27
+ @root = root
28
+ @steep = Object.const_get(:Steep) #: untyped
29
+ steepfile = Pathname(File.expand_path("Steepfile", root))
30
+ @project = @steep::Project.new(steepfile_path: steepfile)
31
+ @steep::Project::DSL.parse(@project, steepfile.read, filename: steepfile.to_s)
32
+ @service = @steep::Services::TypeCheckService.new(project: @project)
33
+ @service.update(changes: changes)
34
+ end
35
+
36
+ # The Ruby files the Steepfile checks.
37
+ #
38
+ # @rbs return: Array[Checked]
39
+ def sources
40
+ @sources ||= @files.select { _1.extname == ".rb" }.sort.filter_map do |path|
41
+ target = @project.target_for_source_path(path) or next
42
+ @service.typecheck_source(path: path, target: target)
43
+ typing = @service.source_files.fetch(path).typing or next
44
+ Checked.new(path: path.to_s, text: File.read(File.expand_path(path.to_s, @root)), typing:, target:)
45
+ end
46
+ end
47
+
48
+ # The signature folders the Steepfile names, relative to the root.
49
+ #
50
+ # @rbs return: Array[String]
51
+ def signature_dirs
52
+ @project.targets.flat_map { _1.signature_pattern.prefixes }.uniq
53
+ end
54
+
55
+ # The Ruby folders the Steepfile checks, relative to the root.
56
+ #
57
+ # @rbs return: Array[String]
58
+ def source_dirs
59
+ @project.targets.flat_map { _1.source_pattern.prefixes }.uniq
60
+ end
61
+
62
+ # The type environment at one position, as the editor's hover sees it.
63
+ #
64
+ # @rbs checked: Checked
65
+ # @rbs position: Integer
66
+ # @rbs return: untyped
67
+ def context_at(checked, position)
68
+ subtyping = @service.signature_services.fetch(checked.target.name).current_subtyping or return nil
69
+ source = @steep::Source.parse(checked.text, path: Pathname(checked.path), factory: subtyping.factory)
70
+ resolver = Object.const_get(:RBS)::Resolver::ConstantResolver.new(builder: subtyping.factory.definition_builder)
71
+ @steep::Services::TypeCheckService.type_check(source:, subtyping:, constant_resolver: resolver, cursor: position)
72
+ .cursor_context.context
73
+ end
74
+
75
+ private
76
+
77
+ # A Steepfile may name a signature folder outside the project, such as a
78
+ # gem's own sig/ beside an example, so the folders come from it.
79
+ #
80
+ # @rbs return: Hash[Pathname, untyped]
81
+ def changes
82
+ dirs = (source_dirs + signature_dirs).uniq
83
+ @files = dirs.flat_map { |dir| File.file?(File.expand_path(dir, @root)) ? [dir] : Dir.glob(File.join(dir, "**/*.{rb,rbs}"), base: @root) }.uniq.map { Pathname(_1) }
84
+ .select { |path| @project.targets.any? { _1.possible_source_file?(path) || _1.possible_signature_file?(path) } }
85
+ @files.to_h { [_1, [@steep::Services::ContentChange.string(File.read(File.expand_path(_1.to_s, @root)))]] }
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module Sigmold
5
+ VERSION = "0.1.0" #: String
6
+ end
data/lib/sigmold.rb ADDED
@@ -0,0 +1,308 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # Sigmold finds behavior that a class's signature and tests do not state.
5
+ #
6
+ # An agent rewrites a class from its public RBS and its tests only. Sigmold
7
+ # loads the original and each rewrite side by side, runs the same random
8
+ # operation sequences on all of them, and reports where they differ. A
9
+ # difference is behavior nobody wrote down: the owner either makes it a
10
+ # contract (adds a test) or marks it free (adds its key to the free list).
11
+ #
12
+ # The operations come from an explorer, a Ruby file the user writes for one
13
+ # class: `plan(random)` returns an operation list, and `run(klass, ops)`
14
+ # returns a plain observation (Integer, String, Symbol, nil, true, false,
15
+ # Array, Hash). Sigmold owns loading, comparing, shrinking, and grouping.
16
+ require_relative "sigmold/version"
17
+ require_relative "sigmold/surface"
18
+ require_relative "sigmold/hole"
19
+
20
+ module Sigmold
21
+
22
+
23
+ # One implementation of the class, loaded under a module of its own so
24
+ # several versions of the same file live in one process.
25
+ class Impl
26
+ attr_reader :label #: String
27
+ attr_reader :klass #: untyped
28
+
29
+ # +root+ is the top-level module the file opens, such as "QuintDriver";
30
+ # +const+ is the class path below it, such as "Hold".
31
+ #
32
+ # @rbs label: String
33
+ # @rbs path: String
34
+ # @rbs root: String
35
+ # @rbs const: String
36
+ def initialize(label, path, root:, const:) #: void
37
+ @label = label
38
+ space = "SigmoldImpl#{label.gsub(/[^A-Za-z0-9]/, '_').capitalize}#{object_id}"
39
+ source = File.read(path).gsub(/\b(module|class) #{Regexp.escape(root)}\b/, "\\1 #{space}")
40
+ Object.const_set(space, Module.new)
41
+ Object.class_eval(source, path)
42
+ @klass = const.split("::").reduce(Object.const_get(space)) { _1.const_get(_2) }
43
+ @space = space
44
+ end
45
+
46
+ # An error message names the module it was raised in; take that off so
47
+ # two implementations compare by what they say.
48
+ #
49
+ # @rbs value: untyped
50
+ # @rbs return: untyped
51
+ def plain(value)
52
+ case value
53
+ when String then value.gsub("#{@space}::", "")
54
+ when Array then value.map { plain(_1) }
55
+ when Hash then value.to_h { [plain(_1), plain(_2)] }
56
+ else value
57
+ end
58
+ end
59
+ end
60
+
61
+ # Where two implementations first disagree on one operation sequence.
62
+ Difference = Data.define(
63
+ :key, #: String
64
+ :ops, #: Array[untyped]
65
+ :seen #: Hash[String, untyped]
66
+ )
67
+
68
+ # Runs an explorer against implementations and collects the differences.
69
+ class Comparison
70
+ # @rbs explorer: untyped
71
+ # @rbs impls: Array[Impl]
72
+ # @rbs free: Array[String]
73
+ def initialize(explorer, impls, free: []) #: void
74
+ @explorer = explorer
75
+ @impls = impls
76
+ @free = free
77
+ end
78
+
79
+ # Groups by key; each group keeps its shortest shrunk case.
80
+ #
81
+ # @rbs runs: Integer
82
+ # @rbs seed: Integer
83
+ # @rbs return: Hash[String, Array[Difference]]
84
+ def run(runs:, seed:)
85
+ random = Random.new(seed)
86
+ found = Hash.new { |h, k| h[k] = [] } #: Hash[String, Array[Difference]]
87
+ freed = [] #: Array[String]
88
+ runs.times do
89
+ ops = @explorer.plan(random)
90
+ diff = differ(ops) or next
91
+ # A free step frees it whichever versions part there.
92
+ step, split = diff.key.split(": ", 2)
93
+ next freed << split.to_s if @free.include?(diff.key) || @free.include?(step)
94
+
95
+ found[diff.key] << diff
96
+ end
97
+ # An argument a freed step could not build is free with it.
98
+ found.reject! { |key, _| key.start_with?(FOLLOWS) && freed.include?(key.split(": ", 2).last) }
99
+ found.transform_values { |cases| [shrink(cases.min_by { _1.ops.inspect.size } || raise)] + cases.drop(1) }
100
+ end
101
+
102
+ # @rbs ops: Array[untyped]
103
+ # @rbs return: Difference?
104
+ def differ(ops)
105
+ seen = @impls.to_h { [_1.label, observe(_1, ops)] }
106
+ return nil if seen.values.uniq.size == 1
107
+
108
+ Difference.new(key: key_of(seen), ops:, seen:)
109
+ end
110
+
111
+ private
112
+
113
+ # @rbs impl: Impl
114
+ # @rbs ops: Array[untyped]
115
+ # @rbs return: untyped
116
+ def observe(impl, ops)
117
+ impl.plain(@explorer.run(impl.klass, ops))
118
+ rescue Exception => e # rubocop:disable Lint/RescueException
119
+ impl.plain([:crashed, e.class.name, e.message])
120
+ end
121
+
122
+ # The key names the first step where the observations part, and which
123
+ # implementations agree there, so one key is one question for the owner.
124
+ #
125
+ # @rbs seen: Hash[String, untyped]
126
+ # @rbs return: String
127
+ def key_of(seen)
128
+ firsts = seen.transform_values { @explorer.respond_to?(:steps) ? @explorer.steps(_1) : [_1] }
129
+ length = firsts.values.map(&:size).max || 0
130
+ index = (0...length).find { |i| firsts.values.map { _1[i] }.uniq.size > 1 } || length
131
+ at = firsts.values.map { _1[index] }
132
+ # The step one version names most exactly, such as an argument it could
133
+ # not build, names the question better than the first version's.
134
+ named = (@explorer.respond_to?(:telling?) && at.find { @explorer.telling?(_1) }) || at.first
135
+ step = @explorer.respond_to?(:label) ? @explorer.label(named) : "step #{index}"
136
+ groups = firsts.group_by { |_, steps| steps[index] }.values.map { |pairs| pairs.map(&:first).sort.join("=") }
137
+ "#{step}: #{groups.sort.join(' | ')}"
138
+ end
139
+
140
+ # Drops operations one at a time while the same difference remains.
141
+ #
142
+ # @rbs diff: Difference
143
+ # @rbs return: Difference
144
+ def shrink(diff)
145
+ loop do
146
+ smaller = diff.ops.each_index.lazy.filter_map do |i|
147
+ # An explorer can keep an operation the rest depend on, such as
148
+ # the call that makes the object.
149
+ next if @explorer.respond_to?(:kept?) && @explorer.kept?(diff.ops[i])
150
+
151
+ ops = diff.ops.dup.tap { _1.delete_at(i) }
152
+ again = differ(ops)
153
+ again if again && again.key == diff.key
154
+ end.first
155
+ return diff unless smaller
156
+
157
+ diff = smaller
158
+ end
159
+ end
160
+ end
161
+
162
+ # The key of a step whose argument could not be built (Explore#label).
163
+ FOLLOWS = "an argument of "
164
+
165
+ # Writes the report: one section per key, most frequent first, with the
166
+ # shrunk operations and what each implementation did.
167
+ #
168
+ # @rbs found: Hash[String, Array[Difference]]
169
+ # @rbs impls: Array[Impl]
170
+ # @rbs runs: Integer
171
+ # @rbs explorer: untyped
172
+ # @rbs return: String
173
+ def self.report(found, impls, runs:, explorer: nil)
174
+ # An argument that one version could not build, such as an object its
175
+ # `new` refused, follows from the question about that `new` when the
176
+ # versions split the same way; it is no question of its own.
177
+ split = ->(key) { key.split(": ", 2).last }
178
+ follows = found.keys.select do |k|
179
+ k.start_with?(FOLLOWS) && found.keys.any? { |o| !o.start_with?(FOLLOWS) && split.(o) == split.(k) }
180
+ end
181
+ asked = found.reject { |k, _| follows.include?(k) }
182
+ lines = ["#{runs} runs, #{found.values.sum(&:size)} differ, #{asked.size} questions"]
183
+ asked.sort_by { -_2.size }.each_with_index do |(key, cases), n|
184
+ first = cases.first or next
185
+ also = follows.select { split.(_1) == split.(key) }.map do |k|
186
+ " the same split stops #{found.fetch(k).size} more runs: #{k.split(': ', 2).first}"
187
+ end
188
+ if explorer.respond_to?(:describe)
189
+ lines << "" << "#{n + 1}. What should the last line do? #{cases.size} runs part here."
190
+ lines.concat(question(explorer.describe(first.ops), first.seen, key, impls, also:))
191
+ else
192
+ lines << "" << "#{n + 1}. [#{cases.size}] #{key}"
193
+ lines << " #{triage(key, impls)}"
194
+ lines << " ops: #{first.ops.inspect}"
195
+ first.seen.each { |label, seen| lines << " #{label}: #{seen.inspect}" }
196
+ lines.concat(also)
197
+ end
198
+ end
199
+ lines.join("\n") + "\n"
200
+ end
201
+
202
+ # One question as its owner reads it: the calls, what each version did,
203
+ # and the test that makes each answer the contract, or the line that
204
+ # leaves it free. Each step is the same up to the last call, so only the
205
+ # last call's outcome differs.
206
+ #
207
+ # @rbs calls: Array[String]
208
+ # @rbs seen: Hash[String, untyped]
209
+ # @rbs key: String
210
+ # @rbs impls: Array[Impl]
211
+ # @rbs also: Array[String] -- runs the same split stops, already worded
212
+ # @rbs return: Array[String]
213
+ def self.question(calls, seen, key, impls, also: [])
214
+ answers = seen.group_by { |_, s| outcome(s) }.map { |text, pairs| [pairs.map(&:first), text, pairs.first&.last] }
215
+ *setup, last = calls
216
+ expr = last.to_s.sub(/\A\w+ = /, "")
217
+ [
218
+ *calls.map { " #{_1}" },
219
+ *answers.map { |labels, text, _| " #{labels.join(', ')}: #{text}" },
220
+ " #{triage(key, impls)}",
221
+ *also,
222
+ " To make one the contract, a test:",
223
+ *answers.flat_map do |labels, _, s|
224
+ [" like #{labels.join(', ')}:", *setup.map { " #{_1}" }, " #{assertion(last.to_s, expr, s)}"]
225
+ end,
226
+ " To leave it free, write this above the class in sig/:",
227
+ " %a{sigmold:free: #{key.split(': ', 2).first}}"
228
+ ]
229
+ end
230
+
231
+ # @rbs call: String -- the last line as describe wrote it
232
+ # @rbs expr: String -- that line without an assignment
233
+ # @rbs seen: untyped
234
+ # @rbs return: String
235
+ def self.assertion(call, expr, seen)
236
+ step = seen.is_a?(Array) ? seen.last : seen
237
+ return "# #{call} => #{seen.inspect}" unless step.is_a?(Array)
238
+
239
+ _, kind, *rest = step
240
+ last = rest.last
241
+ saw = last.is_a?(Array) && last[0] == :yielded ? rest.pop && last[1] : nil
242
+ note = saw ? " # the block saw #{saw.inspect}" : ""
243
+ return "assert_raises(#{rest.first}) { #{expr} }#{note}" unless kind == :ok
244
+
245
+ value = rest.first
246
+ text = if %i[made void self].include?(value) then call
247
+ elsif value.nil? then "assert_nil(#{expr})"
248
+ elsif plain?(value) then "assert_equal(#{value.inspect}, #{expr})"
249
+ else "#{call} # returns #{value.inspect}"
250
+ end
251
+ text + note
252
+ end
253
+
254
+ # A value a test can write as a literal. An object of the namespace is
255
+ # observed as its class name and readers, which is no literal.
256
+ #
257
+ # @rbs value: untyped
258
+ def self.plain?(value, top: true) #: bool
259
+ case value
260
+ when Integer, Float, String, true, false, nil then true
261
+ when Symbol then !%i[made void self].include?(value)
262
+ when Array then value.all? { !_1.is_a?(Hash) && plain?(_1, top: false) }
263
+ when Hash then top && value.all? { plain?(_1, top: false) && plain?(_2, top: false) }
264
+ else false
265
+ end
266
+ end
267
+
268
+ # The last step of an observation, as a person reads it.
269
+ #
270
+ # @rbs seen: untyped
271
+ # @rbs return: String
272
+ def self.outcome(seen)
273
+ step = seen.is_a?(Array) ? seen.last : seen
274
+ return seen.inspect unless step.is_a?(Array)
275
+
276
+ _, kind, *rest = step
277
+ last = rest.last
278
+ saw = last.is_a?(Array) && last[0] == :yielded ? rest.pop && last[1] : nil
279
+ text = if kind != :ok then "raises #{rest.join(': ')}"
280
+ else { made: "makes the object", void: "returns, and the signature says the value is not used", self: "returns itself" }
281
+ .fetch(rest.first) { "=> #{rest.first.inspect}" }
282
+ end
283
+ saw ? "#{text}, the block saw #{saw.inspect}" : text
284
+ end
285
+
286
+ # The first label is the original. When every rewrite agrees and only the
287
+ # original differs, the original may hold an accident; when rewrites
288
+ # disagree with each other, the spec is open.
289
+ #
290
+ # @rbs key: String
291
+ # @rbs impls: Array[Impl]
292
+ # @rbs return: String
293
+ def self.triage(key, impls)
294
+ groups = key.split(": ", 2).last.to_s.split(" | ").map { _1.split("=") }
295
+ original = impls.first&.label
296
+ rewrites = impls.drop(1).map(&:label)
297
+ # Poured from a mold with no code yet, every version is a rewrite.
298
+ return "the rewrites disagree: open spec, decide contract or free" if original.to_s.start_with?("rewrite")
299
+
300
+ if rewrites.size > 1 && groups.any? { |g| g.sort == rewrites.sort }
301
+ "the rewrites agree and the original differs: check the original"
302
+ elsif rewrites.size > 1 && groups.none? { |g| (rewrites - g).empty? }
303
+ "the rewrites disagree: open spec, decide contract or free"
304
+ else
305
+ "#{original} and the rewrite differ: decide contract or free"
306
+ end
307
+ end
308
+ end
@@ -0,0 +1,47 @@
1
+ # Generated from lib/sigmold/calls.rb with RBS::Inline
2
+
3
+ module Sigmold
4
+ # Runs the tests with a recorder and compares what they call with what the
5
+ # signature declares. A test that calls past sig/ pins a method a reader
6
+ # of sig/ cannot see, and a rewrite from sig/ cannot know. A declared
7
+ # method no test calls is shape the tests leave open.
8
+ module Calls
9
+ class Gap < Data
10
+ attr_reader id(): String
11
+
12
+ attr_reader where(): :outside_sig | :untested
13
+
14
+ attr_reader at(): String?
15
+
16
+ def self.new: (String id, :outside_sig | :untested where, String? at) -> instance
17
+ | (id: String, where: :outside_sig | :untested, at: String?) -> instance
18
+
19
+ def self.members: () -> [ :id, :where, :at ]
20
+
21
+ def members: () -> [ :id, :where, :at ]
22
+ end
23
+
24
+ # Owners mark a declared method that tests need not call with this
25
+ # annotation, such as an `inspect` kept for people.
26
+ ALLOW: ::String
27
+
28
+ # Runs +command+ with the recorder loaded and returns what it called.
29
+ #
30
+ # @rbs namespace: String
31
+ # @rbs command: Array[String]
32
+ # @rbs from: String
33
+ # @rbs out: (String | IO)?
34
+ # @rbs return: [Hash[String, String], Process::Status]
35
+ def self.record: (String namespace, Array[String] command, ?from: String, ?out: untyped) -> [ Hash[String, String], Process::Status ]
36
+
37
+ # @rbs seen: Hash[String, String]
38
+ # @rbs signature: Signature
39
+ # @rbs namespace: String
40
+ # @rbs return: Array[Gap]
41
+ def self.gaps: (Hash[String, String] seen, Signature signature, String namespace) -> Array[Gap]
42
+
43
+ # @rbs gaps: Array[Gap]
44
+ # @rbs return: String
45
+ def self.report: (Array[Gap] gaps) -> String
46
+ end
47
+ end
@@ -0,0 +1,22 @@
1
+ # Generated from lib/sigmold/calls_recorder.rb with RBS::Inline
2
+
3
+ # Loaded with `-r` into a test process that `sigmold calls` starts. It
4
+ # records each method of one namespace that code under one folder calls,
5
+ # and writes the list when the process ends. It loads nothing else, so it
6
+ # changes no load order in the process it watches.
7
+ module Sigmold
8
+ module CallsRecorder
9
+ # @rbs namespace: String
10
+ # @rbs from: String
11
+ # @rbs out: String
12
+ # @rbs lib: String
13
+ def self.start: (String namespace, String from, untyped out, String lib) -> void
14
+
15
+ # The name of the module a method belongs to, when it is in the namespace.
16
+ #
17
+ # @rbs mod: Module
18
+ # @rbs namespace: String
19
+ # @rbs return: String | false
20
+ def self.owner_name: (Module mod, String namespace) -> (String | false)
21
+ end
22
+ end
@@ -0,0 +1,39 @@
1
+ # Generated from lib/sigmold/check.rb with RBS::Inline
2
+
3
+ module Sigmold
4
+ # Runs every check of the mold in one go, as `sigmold.yml` in the current
5
+ # folder describes the project:
6
+ #
7
+ # namespace: Shop # the module sig/ shapes
8
+ # require: shop # what loads it, from lib/
9
+ # sig: [sig] # the signature folders
10
+ # test: ruby -Ilib test/cart_test.rb # what runs its tests
11
+ #
12
+ # A project passes when no hole is left, nothing lets the code past its
13
+ # types, sig/ shows the real surface, and the tests pass, call that
14
+ # surface, and call all of it. `gaps` and `pour` stay apart: they need
15
+ # rewrites.
16
+ module Check
17
+ FILE: ::String
18
+
19
+ # @rbs out: IO
20
+ def self.run: (untyped out) -> bool
21
+
22
+ # @rbs out: IO
23
+ # @rbs name: String
24
+ # @rbs &: () -> [bool, String]
25
+ def self.section: (untyped out, String name) { () -> [ bool, String ] } -> bool
26
+
27
+ # @rbs namespace: String
28
+ # @rbs feature: String?
29
+ # @rbs sig: Array[String]
30
+ # @rbs return: [bool, String]
31
+ def self.surface: (String namespace, String? feature, Array[String] sig) -> [ bool, String ]
32
+
33
+ # @rbs namespace: String
34
+ # @rbs test: String?
35
+ # @rbs sig: Array[String]
36
+ # @rbs return: [bool, String]
37
+ def self.calls: (String namespace, String? test, Array[String] sig) -> [ bool, String ]
38
+ end
39
+ end
@@ -0,0 +1,30 @@
1
+ # Generated from lib/sigmold/deps.rb with RBS::Inline
2
+
3
+ module Sigmold
4
+ # Reads which classes each class's public signature names, the way a
5
+ # reader of C++ headers read the includes. A class that names another in
6
+ # its public methods depends on it; a cycle means neither can be read,
7
+ # tested, or poured alone.
8
+ module Deps
9
+ # Each module or class the signatures declare, with the others of
10
+ # those signatures that its public methods name.
11
+ #
12
+ # @rbs signature: Signature
13
+ # @rbs return: Hash[String, Array[String]]
14
+ def self.edges: (Signature signature) -> Hash[String, Array[String]]
15
+
16
+ # @rbs node: untyped
17
+ # @rbs return: Array[String]
18
+ def self.names: (untyped node) -> Array[String]
19
+
20
+ # The cycles among +edges+, each from its smallest name.
21
+ #
22
+ # @rbs edges: Hash[String, Array[String]]
23
+ # @rbs return: Array[Array[String]]
24
+ def self.cycles: (Hash[String, Array[String]] edges) -> Array[Array[String]]
25
+
26
+ # @rbs edges: Hash[String, Array[String]]
27
+ # @rbs return: String
28
+ def self.report: (Hash[String, Array[String]] edges) -> String
29
+ end
30
+ end