quint_driver 0.1.0 → 0.2.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.
@@ -130,16 +130,41 @@ module QuintDriver
130
130
  import["qualifiedName"] ? declaration.merge("name" => "#{import['qualifiedName']}::#{declaration['name']}") : declaration
131
131
  end
132
132
 
133
- # Writes +traces+ traces of the spec's +step+ action and yields each file.
134
- # +main+ names the module to run; without it, quint runs the module named
135
- # after the file. +reach+ names a definition of the module that holds at
136
- # the state a test is after: each trace then ends at the first state where
137
- # it holds, and only the traces that get there are yielded.
138
- def self.simulate(path, traces:, max_steps:, seed:, main: nil, step: "step", backend: "rust", reach: nil)
133
+ # What a simulation ran: +traces+ is how many traces quint ran, and
134
+ # +violated+, when simulate was asked to violate a definition, how many
135
+ # of them broke it, each of which simulate yielded. Without violate it
136
+ # is nil. +actions+ counts the steps each action took across every trace
137
+ # quint ran, init left out, and +never+ lists the actions of the step
138
+ # action that no trace took, so a run that found nothing tells what it
139
+ # never tried. +never+ is nil when the step action has a shape the
140
+ # driver protocol cannot run.
141
+ Simulation = Data.define(:traces, :violated, :actions, :never)
142
+
143
+ # Writes +traces+ traces of the spec's +step+ action, yields each file,
144
+ # and returns a Simulation. +main+ names the module to run; without it,
145
+ # quint runs the module named after the file. +reach+ names a definition
146
+ # of the module that holds at the state a test is after: each trace then
147
+ # ends at the first state where it holds, and only the traces that get
148
+ # there are yielded. +violate+ names an expectation, a definition that
149
+ # should hold in every state: each trace then ends at the first state
150
+ # where it is false, and only the traces that break it are yielded, none
151
+ # when every trace keeps it.
152
+ def self.simulate(path, traces:, max_steps:, seed:, main: nil, step: "step", backend: "rust", reach: nil, violate: nil)
153
+ if reach && violate
154
+ Agreement.refuse "quint: simulate takes reach or violate, not both; each ends a trace where quint's one invariant breaks, " \
155
+ "so a trace it yielded could have met either"
156
+ end
157
+ # quint 0.33.0's typescript simulator counts violations across traces
158
+ # and stops a trace only when it cannot step, so a trace it marks a
159
+ # violation may never reach the definition, or never break it.
160
+ if (reach || violate) && backend == "typescript"
161
+ Agreement.refuse "quint: #{reach ? 'reach' : 'violate'} needs backend: \"rust\"; quint 0.33.0's typescript backend runs a trace on past the state " \
162
+ "where the invariant breaks, and marks every trace after the first violation as a violation too"
163
+ end
139
164
  Dir.mktmpdir("quint") do |dir|
140
- refuse_unfound = runnable!(path, main:, step:, reach:)
165
+ refuse_unfound = runnable!(path, main:, step:, reach:, violate:)
141
166
  evaluator = self.evaluator if backend == "rust"
142
- input = evaluator_input(path, traces:, max_steps:, seed:, main:, step:, reach:) if evaluator
167
+ input = evaluator_input(path, traces:, max_steps:, seed:, main:, step:, reach:, violate:) if evaluator
143
168
  if input
144
169
  write_traces(evaluator, input, dir)
145
170
  else
@@ -147,52 +172,70 @@ module QuintDriver
147
172
  "--n-traces", traces, "--seed", seed, "--step", step, "--out-itf", "#{dir}/trace_{seq}.itf.json", "--verbosity", 0 ]
148
173
  arguments += [ "--main", main ] if main
149
174
  # quint ends a trace where its invariant breaks, and exits 1 then.
150
- arguments += [ "--invariant", "not(#{reach})" ] if reach
175
+ arguments += [ "--invariant", reach ? "not(#{reach})" : violate ] if reach || violate
151
176
  output, status = capture(*arguments)
152
177
  refuse_unfound.(output)
153
- failed "quint run failed:\n#{output}" unless status.success? || reach && output.match?(/^error: invariant violated$/i)
178
+ failed "quint run failed:\n#{output}" unless status.success? || (reach || violate) && output.match?(/^error: invariant violated$/i)
154
179
  end
155
180
 
156
- # A trace that broke the invariant is one that reached +reach+.
157
- traces_written = Dir["#{dir}/trace_*.itf.json"].sort_by { _1[/(\d+)\.itf/, 1].to_i }
158
- traces_written.select! { JSON.parse(File.read(_1)).dig("#meta", "status") == "violation" } if reach
159
- if reach && traces_written.empty?
181
+ # A trace that broke the invariant is one that reached +reach+, or
182
+ # one that broke +violate+.
183
+ written = Dir["#{dir}/trace_*.itf.json"].sort_by { _1[/(\d+)\.itf/, 1].to_i }
184
+ yielded = (reach || violate) ? written.select { JSON.parse(File.read(_1)).dig("#meta", "status") == "violation" } : written
185
+ if reach && yielded.empty?
160
186
  failed "quint: no trace of #{traces} reached #{reach} within #{max_steps} steps; raise max_steps or traces"
161
187
  end
162
188
 
163
- written_by = call("simulate", path, traces:, max_steps:, seed:, main:, step:, backend:, reach:)
164
- yield_traces(traces_written, seed:, written_by:) { yield _1 }
189
+ actions = written.each_with_object(Hash.new(0)) do |trace, counts|
190
+ JSON.parse(File.read(trace)).fetch("states").drop(1).each { counts[_1["mbt::actionTaken"]] += 1 }
191
+ end
192
+ never = begin
193
+ Spec.new(path, main: main || File.basename(path, ".qnt")).rules(step).map(&:action).uniq.sort - actions.keys
194
+ rescue Unsupported
195
+ nil
196
+ end
197
+ simulation = Simulation.new(traces: written.size, violated: (yielded.size if violate), actions: actions.sort.to_h, never:)
198
+
199
+ written_by = call("simulate", path, traces:, max_steps:, seed:, main:, step:, backend:, reach:, violate:)
200
+ yield_traces(yielded, seed:, written_by:) { yield _1 }
201
+ simulation
165
202
  end
166
203
  end
167
204
 
168
205
  # Raises ArgumentError when +step+ names no action without parameters, or
169
- # +reach+ no predicate. quint finds that out only while it runs, and its
170
- # two evaluators each say "Expected boolean" in words of their own. A
171
- # name the module does not declare may be one it imports, which this IR
172
- # does not hold, so the check it returns reads quint's output for a name
173
- # quint did not find either.
174
- def self.runnable!(path, main:, step:, reach:)
206
+ # +reach+ or +violate+ no predicate. quint finds that out only while it
207
+ # runs, and its two evaluators each say "Expected boolean" in words of
208
+ # their own. A name the module does not declare may be one it imports,
209
+ # which this IR does not hold, so the check it returns reads quint's
210
+ # output for a name quint did not find either.
211
+ def self.runnable!(path, main:, step:, reach:, violate:)
175
212
  ir = compile(path, main:)
176
213
  declarations = ir.fetch("modules").find { _1["name"] == ir["main"] }.fetch("declarations")
177
214
  kinds = declarations.select { _1["name"] }.to_h { [ _1["name"], kind_of(_1, ir.fetch("types")) ] }
178
- wanted = { "step" => [ step, "an action", "an action without parameters" ],
179
- "reach" => [ reach, "a predicate", "a predicate, a boolean val or def without parameters" ] }
180
- refuse = lambda do |argument, what|
181
- name, kind, takes = wanted.fetch(argument)
182
- such_as = kinds.select { |of_name, of| of == kind && of_name != "init" && !of_name.start_with?("q::") }.keys.sort.join(", ")
183
- Agreement.refuse "quint: #{argument} names #{name}, #{what}; #{argument} takes #{takes}, such as #{such_as}"
184
- end
215
+ wanted = { "step" => [ step, "an action" ], "reach" => [ reach, "a predicate" ], "violate" => [ violate, "a predicate" ] }
185
216
  wanted.each do |argument, (name, kind)|
186
- refuse.(argument, "#{kinds[name]} of #{ir['main']}") if kinds.key?(name) && kinds[name] != kind
217
+ misnamed(argument, name, "#{kinds[name]} of #{ir['main']}", kind, kinds) if kinds.key?(name) && kinds[name] != kind
187
218
  end
188
219
  lambda do |output|
189
220
  unfound = output[/\[QNT404\] Name '(.+)' not found/, 1]
190
221
  Agreement.refuse(without_init(ir["main"])) if unfound == "init"
191
- argument, = wanted.find { |_, (name)| name == unfound } if unfound
192
- refuse.(argument, "which #{ir['main']} neither declares nor imports") if argument
222
+ argument, (name, kind) = wanted.find { |_, (wanted_name)| wanted_name == unfound } if unfound
223
+ misnamed(argument, name, "which #{ir['main']} neither declares nor imports", kind, kinds) if argument
193
224
  end
194
225
  end
195
226
 
227
+ # What an argument that names a declaration of +kind+ takes, in words.
228
+ TAKES = { "an action" => "an action without parameters", "a predicate" => "a predicate, a boolean val or def without parameters" }.freeze
229
+ private_constant :TAKES
230
+
231
+ # Raises ArgumentError: +argument+ names +name+, which is +what+, and
232
+ # takes a declaration of +kind+. +kinds+ holds the kind of each name of
233
+ # the module, so the message lists the names that fit.
234
+ def self.misnamed(argument, name, what, kind, kinds)
235
+ such_as = kinds.select { |of_name, of| of == kind && of_name != "init" && !of_name.start_with?("q::") }.keys.sort.join(", ")
236
+ Agreement.refuse "quint: #{argument} names #{name}, #{what}; #{argument} takes #{TAKES.fetch(kind)}, such as #{such_as}"
237
+ end
238
+
196
239
  # Quint's own --init could name another action, but a trace names its
197
240
  # first step after that action, the model and the machine step through
198
241
  # init, and a driver reads init: one name keeps the four alike.
@@ -201,10 +244,10 @@ module QuintDriver
201
244
  "and every model at init, so declare `action init = ...` with what starts #{main}"
202
245
  end
203
246
 
204
- # What a declaration is, as a step or a reach has to tell: a variant
205
- # quint declares as a val, or as a def when it carries a value. A val and
206
- # a def without parameters both read as a value: the keyword changes
207
- # nothing a step or a reach needs.
247
+ # What a declaration is, as a step, a reach, a violate, or an invariant
248
+ # has to tell: a variant quint declares as a val, or as a def when it
249
+ # carries a value. A val and a def without parameters both read as a
250
+ # value: the keyword changes nothing any of them needs.
208
251
  def self.kind_of(declaration, types)
209
252
  expr = declaration["expr"] || {}
210
253
  lambda = expr["kind"] == "lambda"
@@ -259,7 +302,7 @@ module QuintDriver
259
302
  traces.each do |trace|
260
303
  @written[trace] = { seed:, written_by: }
261
304
  yield trace
262
- rescue Mismatch, StepRaised => failure
305
+ rescue NamedTrace => failure
263
306
  name_trace(failure, trace)
264
307
  raise
265
308
  ensure
@@ -297,9 +340,9 @@ module QuintDriver
297
340
  end
298
341
 
299
342
  # What `quint run --mbt` sends the evaluator for this call, or nil when
300
- # +step+ is no action of the module or +reach+ no definition of it, so
301
- # `quint run` reports it.
302
- def self.evaluator_input(path, traces:, max_steps:, seed:, main:, step:, reach:)
343
+ # +step+ is no action of the module or +reach+ or +violate+ no definition
344
+ # of it, so `quint run` reports it.
345
+ def self.evaluator_input(path, traces:, max_steps:, seed:, main:, step:, reach:, violate:)
303
346
  ir = compile(path, main:)
304
347
  declarations = ir.fetch("modules").find { _1["name"] == ir["main"] }&.fetch("declarations") || []
305
348
  table = ir.fetch("table").dup
@@ -311,9 +354,10 @@ module QuintDriver
311
354
  table[(id += 1).to_s] = definition
312
355
  { "id" => id, "kind" => "name", "name" => action }
313
356
  end
314
- invariant = if reach
315
- table[(id += 1).to_s] = declarations.find { _1["kind"] == "def" && _1["name"] == reach } || return
316
- { id: id + 1, kind: "app", opcode: "not", args: [ { id:, kind: "name", name: reach } ] }
357
+ invariant = if reach || violate
358
+ name = reach || violate
359
+ table[(id += 1).to_s] = declarations.find { _1["kind"] == "def" && _1["name"] == name } || return
360
+ reach ? { id: id + 1, kind: "app", opcode: "not", args: [ { id:, kind: "name", name: } ] } : { id:, kind: "name", name: }
317
361
  else
318
362
  { id: id + 1, kind: "bool", value: true }
319
363
  end
@@ -343,7 +387,8 @@ module QuintDriver
343
387
  "it reads the #{EVALUATOR_VERSION} evaluator quint 0.33.0 runs. Set QUINT_EVALUATOR to that " \
344
388
  "evaluator, or to an empty string to simulate through `quint run`"
345
389
  end
346
- # A violation is only possible when simulate asks to reach a definition.
390
+ # A violation is only possible when simulate asks to reach or to
391
+ # violate a definition.
347
392
  unless %w[ok violation].include?(result["status"])
348
393
  failed "quint run failed:\n#{result.fetch('errors', []).map { "Error [#{_1['code']}]: #{_1['message']}" }.join("\n")}"
349
394
  end
@@ -371,6 +416,7 @@ module QuintDriver
371
416
  # caller's, so its frame leads, as a refused argument's does.
372
417
  def self.failed(message) = Agreement.refuse(message, QuintFailed)
373
418
 
374
- private_class_method :call, :capture, :compile_now, :evaluator_input, :failed, :imported_names, :kind_of, :name_trace, :renamed, :runnable!, :sources, :without_init, :write_traces, :yield_traces
419
+ private_class_method :call, :capture, :compile_now, :evaluator_input, :failed, :imported_names, :kind_of, :misnamed, :name_trace, :renamed, :runnable!,
420
+ :sources, :without_init, :write_traces, :yield_traces
375
421
  end
376
422
  end
@@ -12,14 +12,17 @@ module QuintDriver
12
12
 
13
13
  # The q:: definitions are what quint adds for --main, so only the module
14
14
  # a file compiled for first would have them. A module that imports reads
15
- # quint's flattened copy, where what it imports is its own.
16
- def initialize(path, main:)
15
+ # quint's flattened copy, where what it imports is its own. Without
16
+ # +main+ the module is the one named after the file, as Quint.simulate
17
+ # reads it, so the two agree when both leave it out.
18
+ def initialize(path, main: File.basename(path.to_s, ".qnt"))
17
19
  ir = Quint.compile(path, main:)
18
20
  declarations = ir.fetch("modules").find { _1["name"] == main }.fetch("declarations")
19
21
  ir = Quint.compile(path, main:, flat: true) if declarations.any? { %w[import instance export].include?(_1["kind"]) }
20
22
  @declarations = ir.fetch("modules").find { _1["name"] == main }.fetch("declarations")
21
23
  .reject { _1["name"].to_s.start_with?("q::") }
22
24
  @effects = ir.fetch("effects")
25
+ @types = ir.fetch("types")
23
26
  @main = main
24
27
  end
25
28
 
@@ -35,6 +38,25 @@ module QuintDriver
35
38
  Agreement.refuse "quint: observe names #{name}, which is no definition without parameters of #{@main}; it has #{observable.sort.join(', ')}"
36
39
  end
37
40
 
41
+ # Raises ArgumentError unless each of +names+ is a predicate, a boolean
42
+ # val or def without parameters, as +argument+, such as invariants,
43
+ # takes one. A name of another kind would read as an expectation that
44
+ # never holds, or that the model cannot evaluate.
45
+ def predicates!(names, argument)
46
+ @kinds ||= declarations.select { _1["name"] }.to_h { [ _1["name"], Quint.send(:kind_of, _1, @types) ] }
47
+ name = names.find { @kinds[_1] != "a predicate" } or return
48
+ what = @kinds.key?(name) ? "#{@kinds[name]} of #{@main}" : "which #{@main} neither declares nor imports"
49
+ Quint.send(:misnamed, argument, name, what, "a predicate", @kinds)
50
+ end
51
+
52
+ # The names invariants: and violate: take: every boolean val or def
53
+ # without parameters, in the order the module declares them, so a hunt
54
+ # that reads this list runs a val added later too.
55
+ def expectations
56
+ predicates!([], "invariants")
57
+ declarations.sort_by { _1["id"] }.filter_map { _1["name"] if @kinds[_1["name"]] == "a predicate" }.uniq
58
+ end
59
+
38
60
  # The definition that writes each IR node, by node id, so the model names
39
61
  # where a node is written when it cannot evaluate it.
40
62
  def owners
@@ -0,0 +1,202 @@
1
+ # Runs a list of steps, such as the steps: lines a failure printed, on a
2
+ # driver and on the spec's model side by side, and checks them as a replay
3
+ # checks a trace. It needs no quint command and no Hegel, so a failure found
4
+ # by either is pinned as one plain example.
5
+ module QuintDriver
6
+ # Runs +steps+ on +driver+ and on +spec+'s model, from init, and holds the
7
+ # driver to the model after each one: a disagreement raises Mismatch, and
8
+ # an expectation +invariants+ names that is false where the two agreed
9
+ # raises Violated, as Trace.replay does. +steps+ is the text under steps:
10
+ # of a failure, pasted as it is, or a list of [action, picks]; a first
11
+ # step named init may be left out. +step+ names the spec's step action, as
12
+ # QuintDriver.machine takes it. Returns the steps it ran.
13
+ def self.replay_steps(spec, driver, steps, step: "step", observe: [], ignore: [], invariants: [])
14
+ observe, ignore, invariants = observe.map(&:to_s), ignore.map(&:to_s), invariants.map(&:to_s)
15
+ steps = Steps.parse(steps) if steps.is_a?(String)
16
+ steps = steps.map { |action, picks| [ action.to_s, (picks || {}).transform_keys(&:to_s) ] }
17
+ steps.unshift([ "init", {} ]) unless steps.first&.first == "init"
18
+ spec.observable!(observe)
19
+ spec.predicates!(invariants, "invariants")
20
+ model = spec.model(step)
21
+ ran = []
22
+ steps.each_with_index do |(action, picks), index|
23
+ ran << [ action, picks ]
24
+ at = "step #{index} `#{action}` #{Agreement.show(picks)}"
25
+ begin
26
+ model.step(action, picks)
27
+ rescue Mismatch => refused
28
+ raise Mismatch, "#{refused.message}, at #{at}\n#{Agreement.ran(ran)}", Agreement.outside(caller_locations)
29
+ end
30
+ Agreement.ignorable!(ignore, model.state.keys, "the spec's variables") if index.zero?
31
+ actual = Agreement.drive(at, steps: ran) do
32
+ driver.step(action, picks)
33
+ driver.state
34
+ end
35
+ Agreement.check!(at, model.state.merge(model.observe(observe)), actual, by: "model", steps: ran, observe:, spec:, ignore:)
36
+ broken = invariants.reject { model.value(_1) }
37
+ Agreement.violated!(at, broken, steps: ran, state: model.state) if broken.any?
38
+ end
39
+ ran
40
+ end
41
+
42
+ # Takes steps out of a failure while the same expectations still break,
43
+ # and returns the shortest list it found as the text under steps:, to
44
+ # paste into replay_steps. The block runs one list of steps, as
45
+ # [action, picks] from init, and raises what replay_steps raises: it
46
+ # builds the driver and rolls the database back each time, since a list
47
+ # that keeps the failure is only known by running it. A list the spec
48
+ # does not allow (Mismatch), one whose step raises (StepRaised), or one
49
+ # that breaks other expectations does not keep the failure. Quint's first
50
+ # trace that breaks an expectation is seldom the shortest; Hegel shrinks
51
+ # its own.
52
+ def self.shrink_steps(steps, &run)
53
+ steps = Steps.parse(steps) if steps.is_a?(String)
54
+ steps = steps.map { |action, picks| [ action.to_s, (picks || {}).transform_keys(&:to_s) ] }
55
+ steps.shift if steps.first&.first == "init"
56
+ first = Steps.violated(steps, &run) or raise ArgumentError, "quint: shrink_steps needs steps that raise Violated; these do not"
57
+
58
+ expectations = first.expectations.sort
59
+ best = Steps.after_init(first.steps)
60
+ # Runs of steps come out together, longest first, since a step often
61
+ # needs the one before it: a save cannot go without its load.
62
+ loop do
63
+ shorter = best.size.downto(1).lazy.flat_map do |size|
64
+ (0..best.size - size).lazy.filter_map do |start|
65
+ candidate = best.dup.tap { _1.slice!(start, size) }
66
+ broken = Steps.violated(candidate, &run)
67
+ Steps.after_init(broken.steps) if broken && broken.expectations.sort == expectations
68
+ end
69
+ end.first
70
+ break unless shorter
71
+
72
+ best = shorter
73
+ end
74
+ Agreement.ran([ [ "init", {} ], *best ]) + "\n"
75
+ end
76
+
77
+ # Reads the steps: lines of a failure back into [action, picks]. Each line
78
+ # is an action's name and its picks as a failure prints a value: strings,
79
+ # integers, true, false, nil, [lists], {sets} and {hashes with =>}.
80
+ module Steps
81
+ # The Violated that running +steps+ raises, or nil when they keep every
82
+ # expectation, the spec refuses one of them, or one of them raises.
83
+ def self.violated(steps)
84
+ yield([ [ "init", {} ], *steps ])
85
+ nil
86
+ rescue Violated => broken
87
+ broken
88
+ rescue Mismatch, StepRaised
89
+ nil
90
+ end
91
+
92
+ def self.after_init(steps) = steps.first&.first == "init" ? steps.drop(1) : steps
93
+
94
+ def self.parse(text)
95
+ text.each_line.map(&:strip).reject { _1.empty? || _1 == "steps:" }.map do |line|
96
+ action, picks = line.split(" ", 2)
97
+ reader = Reader.new(picks.to_s.strip)
98
+ value = reader.value
99
+ raise ArgumentError, "quint: replay_steps reads `#{line}`, whose picks are no {...} a failure prints" unless value.is_a?(Hash) && reader.done?
100
+
101
+ [ action, value ]
102
+ end
103
+ end
104
+
105
+ # A small reader of Agreement.show's output; a set and a hash share
106
+ # braces and tell apart by the => after the first element.
107
+ class Reader
108
+ def initialize(text) = (@text, @at = text, 0)
109
+ def done? = (skip; @at == @text.size)
110
+
111
+ def value
112
+ skip
113
+ case @text[@at]
114
+ when '"' then string
115
+ when "[" then (@at += 1; list)
116
+ when "{" then braces
117
+ else word
118
+ end
119
+ end
120
+
121
+ private
122
+ def skip = (@at += 1 while @text[@at] == " ")
123
+
124
+ def take(token)
125
+ skip
126
+ raise ArgumentError, "quint: replay_steps expected #{token} at `#{@text[@at..]}`" unless @text[@at, token.size] == token
127
+
128
+ @at += token.size
129
+ end
130
+
131
+ def string
132
+ finish = @at + 1
133
+ finish += @text[finish] == "\\" ? 2 : 1 until @text[finish] == '"' || finish >= @text.size
134
+ literal = @text[@at..finish]
135
+ @at = finish + 1
136
+ literal.undump
137
+ end
138
+
139
+ def word
140
+ token = @text[@at..][/\A[^,\]\}\s]+/] or raise ArgumentError, "quint: replay_steps cannot read `#{@text[@at..]}`"
141
+ @at += token.size
142
+ case token
143
+ when "true" then true
144
+ when "false" then false
145
+ when "nil" then nil
146
+ when /\A-?\d+\z/ then Integer(token)
147
+ else raise ArgumentError, "quint: replay_steps cannot read #{token}"
148
+ end
149
+ end
150
+
151
+ def list
152
+ items = []
153
+ skip
154
+ until @text[@at] == "]"
155
+ raise ArgumentError, "quint: replay_steps expected ] at the end of `#{@text}`" if @at >= @text.size
156
+
157
+ items << value
158
+ skip
159
+ @at += 1 if @text[@at] == ","
160
+ skip
161
+ end
162
+ @at += 1
163
+ items
164
+ end
165
+
166
+ def braces
167
+ take("{")
168
+ skip
169
+ return (@at += 1; {}) if @text[@at] == "}"
170
+
171
+ first = value
172
+ skip
173
+ return set_from(first) unless @text[@at, 2] == "=>"
174
+
175
+ hash = {}
176
+ key = first
177
+ loop do
178
+ take("=>")
179
+ hash[key] = value
180
+ skip
181
+ break (@at += 1) if @text[@at] == "}"
182
+
183
+ take(",")
184
+ key = value
185
+ end
186
+ hash
187
+ end
188
+
189
+ def set_from(first)
190
+ items = [ first ]
191
+ until @text[@at] == "}"
192
+ take(",")
193
+ items << value
194
+ skip
195
+ end
196
+ @at += 1
197
+ items.to_set
198
+ end
199
+ end
200
+ end
201
+ private_constant :Steps
202
+ end
@@ -0,0 +1,175 @@
1
+ require "prism"
2
+
3
+ module QuintDriver
4
+ # The places in a Ruby app where a hunt pays: code where two writes must
5
+ # agree and something can fail between them. It reads the source only, so
6
+ # it names lines to read, never bugs: each hit is a pattern the bugs a hunt
7
+ # finds have had, such as a rescue inside a transaction or a save whose
8
+ # answer nobody reads. Files are ranked by how many kinds of hit they hold,
9
+ # since the bugs sat where several kinds meet.
10
+ #
11
+ # Prism, which ships with Ruby, reads each file, so comments, strings,
12
+ # heredocs and regexps are not matched, and the method a line sits in is
13
+ # the def that holds it, not the def above it.
14
+ module Targets
15
+ Hit = Data.define(:kind, :file, :line, :code)
16
+
17
+ SAVE = /\A\s*([@\w:.]+\.)?(save|update|create|destroy|update_attribute)([( ].*)?\z/
18
+ # A save whose answer the line itself reads, as in `save or raise`.
19
+ READ = /\s(or|and)\s|\|\||&&/
20
+ WRITE = /\.(save|update|create|destroy|update_attribute|update_columns?|increment|decrement)!?(\(|\s|\z)|\A\s*(save|update)!?(\(|\s|\z)/
21
+ LOCK = /\block\b|\bwith_lock\b|\block!/
22
+ KINDS = {
23
+ "transaction" => /\btransaction\b|\bwith_lock\b|\block!/,
24
+ "rescue" => /\A\s*rescue\b/,
25
+ "unchecked-save" => SAVE,
26
+ "answers-false" => /\A\s*false\s*\z|\breturn false\b/,
27
+ "skips-callbacks" => /\b(update_all|update_columns?|delete_all|insert_all|upsert_all|update_counters|increment_counter|decrement_counter)\b/,
28
+ "counter-write" => /\b(increment|decrement)!?\(\s*:\w+|\w+_count\s*[+-]=/,
29
+ "retry" => /\b(retry_on|discard_on)\b|\A\s*retry\b/,
30
+ # An outside call, or an error class of the app's own, which is how a
31
+ # service that calls out says it can fail.
32
+ "outside" => %r{Net::HTTP|Faraday|HTTParty|RestClient|\bClient\b|Api\b|_api\b|\.(post|get|put|patch|delete)\(\s*["'/]|broadcast|
33
+ \A\s*class\s+[\w:]+\s*<\s*([\w:]*Error|StandardError|RuntimeError)\b}x
34
+ }.freeze
35
+ # A method with one of these names is called on many receivers that are
36
+ # not its own, so a call counts only where it names the method's class.
37
+ COMMON = %w[call perform run process execute save update create destroy].freeze
38
+
39
+ # A def, with the lines of the checks in it that read stored state.
40
+ Def = Data.define(:name, :owner, :first, :last, :checks)
41
+
42
+ # Every hit under +root+'s app/ and lib/, the spec and test folders left
43
+ # out, comments and strings skipped, each write after a check in a
44
+ # method that takes no lock, as the kind "check-then-write", and each
45
+ # call that drops the answer of a method that can fail without raising,
46
+ # as the kind "dropped-result".
47
+ def self.scan(root)
48
+ files = Dir.glob(%w[app/**/*.rb lib/**/*.rb], base: root)
49
+ .reject { _1.match?(%r{(\A|/)(spec|test)/}) }.select { File.file?(File.join(root, _1)) }.sort
50
+ sources = files.to_h { [ _1, read(File.join(root, _1)) ] }
51
+ hits = sources.flat_map do |file, (lines, code, _)|
52
+ code.each_with_index.flat_map do |text, index|
53
+ KINDS.filter_map do |kind, pattern|
54
+ next if kind == "unchecked-save" && text.match?(READ)
55
+
56
+ Hit.new(kind, file, index + 1, lines[index].strip) if text.match?(pattern)
57
+ end
58
+ end
59
+ end
60
+ hits + checked(sources) + dropped(hits, sources)
61
+ end
62
+
63
+ # The files ranked, each with its hits, as the `quint_driver targets`
64
+ # command prints them.
65
+ def self.report(root, top: 10)
66
+ raise ArgumentError, "quint: top takes 1 or more, not #{top}" if top < 1
67
+
68
+ by_file = scan(root).group_by(&:file).sort_by { |file, hits| [ -hits.map(&:kind).uniq.size, -hits.size, file ] }
69
+ return none(root) if by_file.empty?
70
+
71
+ by_file.first(top).map do |file, hits|
72
+ kinds = hits.map(&:kind).uniq
73
+ [ "#{file}: #{kinds.join(', ')}", *hits.sort_by(&:line).map { " #{_1.line} #{_1.kind} #{_1.code}" } ].join("\n")
74
+ end.join("\n\n") + "\n#{"\n#{by_file.size - top} more #{by_file.size - top == 1 ? 'file' : 'files'} with fewer kinds; pass --top N to see them.\n" if by_file.size > top}"
75
+ end
76
+
77
+ # The lines of a file as written, the same lines with every comment,
78
+ # string, heredoc and regexp body blanked, and the defs it holds.
79
+ def self.read(path)
80
+ source = File.read(path, encoding: "UTF-8").scrub
81
+ code = source.b
82
+ Prism.lex(source).value.each do |token, _|
83
+ next unless %i[COMMENT EMBDOC_BEGIN EMBDOC_LINE EMBDOC_END STRING_CONTENT HEREDOC_END __END__].include?(token.type)
84
+
85
+ range = token.location.start_offset...token.location.end_offset
86
+ code[range] = code[range].gsub(/[^\n]/n, " ")
87
+ end
88
+ [ source.lines(chomp: true), code.force_encoding("UTF-8").scrub.lines(chomp: true), defs(Prism.parse(source).value) ]
89
+ end
90
+
91
+ def self.defs(node, owner = nil)
92
+ case node
93
+ when Prism::ClassNode, Prism::ModuleNode
94
+ name = node.constant_path.slice.split("::").last
95
+ node.compact_child_nodes.flat_map { defs(_1, name) }
96
+ when Prism::DefNode
97
+ writes = within(node).grep(Prism::LocalVariableWriteNode)
98
+ loaded = 2.times.reduce([]) { |known, _| writes.select { stored?(_1.value, known) }.map(&:name) }
99
+ checks = within(node).filter_map { _1.predicate if _1.is_a?(Prism::IfNode) || _1.is_a?(Prism::UnlessNode) }
100
+ .select { stored?(_1, loaded) }.map { _1.location.start_line }
101
+ [ Def.new(node.name.to_s, owner, node.location.start_line, node.location.end_line, checks),
102
+ *node.compact_child_nodes.flat_map { defs(_1, owner) } ]
103
+ else node.compact_child_nodes.flat_map { defs(_1, owner) }
104
+ end
105
+ end
106
+
107
+ # Every node of a def, its nested defs left out.
108
+ def self.within(node)
109
+ node.compact_child_nodes.flat_map { _1.is_a?(Prism::DefNode) ? [] : [ _1, *within(_1) ] }
110
+ end
111
+
112
+ # Whether a condition reads what the app stored, not only the method's
113
+ # arguments: an attribute, an instance variable, a query on a class, or
114
+ # a local the def loaded from one of those. A check of an argument alone
115
+ # cannot go stale between the read and the write, so it is no sign of a
116
+ # race.
117
+ def self.stored?(node, loaded)
118
+ case node
119
+ when Prism::InstanceVariableReadNode, Prism::ConstantReadNode, Prism::ConstantPathNode then true
120
+ when Prism::LocalVariableReadNode then loaded.include?(node.name)
121
+ when Prism::CallNode
122
+ node.receiver.nil? && node.variable_call? && !%i[params request].include?(node.name) ||
123
+ node.compact_child_nodes.any? { stored?(_1, loaded) }
124
+ else node.compact_child_nodes.any? { stored?(_1, loaded) }
125
+ end
126
+ end
127
+
128
+ # The innermost def that holds +line+.
129
+ def self.around(defs, line) = defs.select { _1.first <= line && line <= _1.last }.min_by { _1.last - _1.first }
130
+
131
+ # A write is a save, an update, a create or a destroy, or a call of a
132
+ # method of the app that holds one, such as `parcel.assign_to!(...)`.
133
+ def self.checked(sources)
134
+ writers = sources.values.flat_map do |_, code, defs|
135
+ defs.select { |method| (method.first..method.last).any? { code[_1 - 1].to_s.match?(WRITE) } }.map(&:name)
136
+ end.uniq - COMMON
137
+ write = writers.empty? ? WRITE : Regexp.union(WRITE, /\.(#{writers.map { Regexp.escape(_1) }.join('|')})(\(|\s|\z)/)
138
+ sources.flat_map do |file, (lines, code, defs)|
139
+ defs.flat_map do |method|
140
+ check = method.checks.min or next []
141
+ body = (method.first - 1...method.last).map { [ _1 + 1, code[_1].to_s ] }
142
+ next [] if body.any? { |_, text| text.match?(LOCK) }
143
+
144
+ body.select { |line, _| line > check }
145
+ .filter_map { |line, text| Hit.new("check-then-write", file, line, lines[line - 1].strip) if text.match?(write) }
146
+ end
147
+ end
148
+ end
149
+
150
+ def self.dropped(hits, sources)
151
+ methods = hits.select { %w[unchecked-save answers-false].include?(_1.kind) }.filter_map { around(sources[_1.file][2], _1.line) }.uniq
152
+ return [] if methods.empty?
153
+
154
+ sources.flat_map do |file, (lines, code, defs)|
155
+ code.each_with_index.filter_map do |text, index|
156
+ next if text.match?(/\A\s*def /)
157
+
158
+ called = methods.find do |method|
159
+ text.match?(/\A\s*([@\w:.()]+\.)?#{Regexp.escape(method.name)}(\(.*\))?\s*\z/) &&
160
+ (!COMMON.include?(method.name) || (method.owner && text.match?(/\b#{Regexp.escape(method.owner)}\b/)))
161
+ end
162
+ Hit.new("dropped-result", file, index + 1, lines[index].strip) if called
163
+ end
164
+ end
165
+ end
166
+
167
+ def self.none(root)
168
+ <<~TEXT
169
+ No hit under #{root}/app or #{root}/lib.
170
+ That says no line matched, not that a hunt cannot pay here. List the entry points (controllers, jobs, rake tasks), ask which of them write the same rows, and read where one of them calls a service that can fail.
171
+ TEXT
172
+ end
173
+ private_class_method :read, :defs, :within, :stored?, :around, :checked, :dropped, :none
174
+ end
175
+ end