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.
- checksums.yaml +4 -4
- data/README.ja.md +91 -1
- data/README.md +41 -4
- data/examples/shelf/shelf.qnt +37 -0
- data/examples/shelf/shelf.rb +37 -0
- data/exe/quint_driver +41 -0
- data/lib/quint_driver/hegel.rb +18 -7
- data/lib/quint_driver/hold.rb +88 -0
- data/lib/quint_driver/model.rb +21 -3
- data/lib/quint_driver/outline.rb +70 -0
- data/lib/quint_driver/quint.rb +91 -45
- data/lib/quint_driver/spec.rb +24 -2
- data/lib/quint_driver/steps.rb +202 -0
- data/lib/quint_driver/targets.rb +175 -0
- data/lib/quint_driver/trace.rb +33 -16
- data/lib/quint_driver/version.rb +1 -1
- data/lib/quint_driver.rb +45 -5
- data/skills/quint_driver/SKILL.md +296 -3
- metadata +11 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 2dc5e4b80860482ff81dea18ae8af3eb091ab26b3feb5a5d053cbd5c4c4e6634
|
|
4
|
+
data.tar.gz: 8914a9ae7c049b21b12d7d1c82596ec4ad2381ee30d1a68d3df333448c6ca907
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 87058dcd6e203c12170103b168d77aff1cd0fd61ca7d9a4a60bd64e76b98a60fa9608ef7fb3f7881581bb839556e47e9261d24edfb0bf772e17644764e635d52
|
|
7
|
+
data.tar.gz: a48ad29a95b2b78081d894cbaa98b4851c5fe95ff0a157360b477fcd615f34ba2bb6c1ca6f8c3a21adaa125d5a98d792bdf61cb805be77e05ebc4002e40fe7a6
|
data/README.ja.md
CHANGED
|
@@ -34,6 +34,8 @@ quint_driver には Ruby 3.3 以降が必要です。
|
|
|
34
34
|
最近のコミットが状態を変えたモデルから始めるとよいでしょう。
|
|
35
35
|
仕様がその変更を確かめるからです。
|
|
36
36
|
そのようなコミットは `git log --oneline -- app/models` で一覧できます。
|
|
37
|
+
いくつもの入り口にまたがるバグを探すなら、[バグを探す](#バグを探す)を見てください。
|
|
38
|
+
`bundle exec quint_driver targets` は、アプリの中で探す価値が高いファイルを順に並べます。
|
|
37
39
|
|
|
38
40
|
下の手順では `Loan` を使います。
|
|
39
41
|
新しいローンは `"pending"` で、`Loan#approve(officer)` はそれを `"approved"` にします。
|
|
@@ -352,6 +354,58 @@ Finished in 1.22 seconds (files took 0.91182 seconds to load)
|
|
|
352
354
|
|
|
353
355
|
セーブポイントの代わりにドライバーの `init` で行を消す方法と、セーブポイントを joinable にしてはいけない理由は、[スキル](skills/quint_driver/SKILL.md)にあります。
|
|
354
356
|
|
|
357
|
+
## バグを探す
|
|
358
|
+
|
|
359
|
+
1 つのモデルを固めるのでなくバグを探すときは、仕様に 2 種類のものを書きます。
|
|
360
|
+
action には、癖も含めていまのコードの動きを書きます。
|
|
361
|
+
そうすれば、アプリはどのトレースにも従います。
|
|
362
|
+
外のサービスを呼ぶ action には、どの呼び出しが失敗するかを選ぶ引数を持たせます。
|
|
363
|
+
そうすれば、トレースはアプリの rescue も通ります。
|
|
364
|
+
真偽値の `val` には、運用する人が期待することを書きます。
|
|
365
|
+
コードはこちらを破るかもしれません。
|
|
366
|
+
そして期待ごとに `violate:` で Quint のトレースをそこへ向け、同じ名前を `invariants:` に渡してトレースを再生します。
|
|
367
|
+
|
|
368
|
+
```ruby
|
|
369
|
+
expectations.each do |expectation|
|
|
370
|
+
it "keeps #{expectation} on the traces Quint aims at it" do
|
|
371
|
+
simulation = QuintDriver::Quint.simulate(qnt, traces: 200, max_steps: 12, seed: "1", violate: expectation) do |path|
|
|
372
|
+
rolled_back { QuintDriver::Trace.replay(path, driver, spec:, invariants: [ expectation ], ignore:) }
|
|
373
|
+
end
|
|
374
|
+
expect(simulation.never).to be_empty
|
|
375
|
+
end
|
|
376
|
+
end
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
`test/fixture/depot` は宅配ロッカーの小さな Rails アプリで、バグを 4 つ仕込んであります。
|
|
380
|
+
その `spec/quint/` が、この形でバグを探します。
|
|
381
|
+
どのバグも `QuintDriver::Violated` で失敗します。
|
|
382
|
+
アプリはどのステップでも仕様と一致したのに、運用する人の期待が成り立っていない、という意味です。
|
|
383
|
+
|
|
384
|
+
```text
|
|
385
|
+
quint: the system agreed with the spec at every step, and the expectation `free_compartment_has_no_code` does not hold after step 2 `release` {"offline" => 1, "p" => "p3"}
|
|
386
|
+
steps:
|
|
387
|
+
init {}
|
|
388
|
+
assignParcel {"offline" => 2, "p" => "p3"}
|
|
389
|
+
release {"offline" => 1, "p" => "p3"}
|
|
390
|
+
state:
|
|
391
|
+
everDone: {}
|
|
392
|
+
intake: "none"
|
|
393
|
+
live: {1}
|
|
394
|
+
place: {"p1" => "Waiting", "p2" => "Waiting", "p3" => "Collected"}
|
|
395
|
+
row: {"p1" => "", "p2" => "", "p3" => ""}
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
ここでは荷物は受け取られ、ボックスは空いたのに、ロッカーの制御装置はまだそのボックスの暗証番号を持っています。
|
|
399
|
+
受け取りのページが、制御装置のタイムアウトをトランザクションの中で rescue したからです。
|
|
400
|
+
`Violated` はバグの候補です。
|
|
401
|
+
探しているときの `Mismatch` は、たいてい仕様かドライバーの誤りです。
|
|
402
|
+
失敗を 1 つの example に固めるには、その `steps:` の下の文字列を `QuintDriver.replay_steps(spec, driver, <<~STEPS, invariants: [...])` に貼ります。
|
|
403
|
+
quint も Hegel も使わずに、その手順をもう一度動かします。
|
|
404
|
+
Quint のトレースにはいらない手順が混ざるので、`QuintDriver.shrink_steps` で同じ期待が破れるまま手順を減らしてから貼ります。
|
|
405
|
+
探す場所、候補の確かめ方、やめどきは、[スキル](skills/quint_driver/SKILL.md#hunt-for-bugs)にあります。
|
|
406
|
+
読み込みと書き込みの間に別のリクエストが入って更新が消えるバグは、`QuintDriver::Hold` でリクエストを途中で止めて探します。
|
|
407
|
+
書き方はスキルの [A request another one comes between](skills/quint_driver/SKILL.md#a-request-another-one-comes-between) にあります。
|
|
408
|
+
|
|
355
409
|
## アプリなしで試す
|
|
356
410
|
|
|
357
411
|
### インストール
|
|
@@ -588,6 +642,9 @@ ln -s "$(bundle info --path quint_driver)/skills/quint_driver" .agents/skills/qu
|
|
|
588
642
|
## ドライバーを書く
|
|
589
643
|
|
|
590
644
|
ドライバーは、仕様のアクションをシステムで動かし、システムの状態を仕様の言葉で読み戻します。
|
|
645
|
+
`bundle exec quint_driver outline spec.qnt` は、書き始めるためのドライバーを出力します。
|
|
646
|
+
各アクションと受け取る選択、`state` が返す各変数とその値の Ruby での形、そして期待が並びます。
|
|
647
|
+
どのドライバーも step アクションを動かせないときは、理由を出して終了コード 1 で終わります。
|
|
591
648
|
|
|
592
649
|
```ruby
|
|
593
650
|
class LoansDriver
|
|
@@ -721,6 +778,9 @@ Quint は `not(two_on_loan)` を不変条件として確かめ、それが破れ
|
|
|
721
778
|
例えば `quint: reach names borrow, an action with parameters of loans; reach takes a predicate, a boolean val or def without parameters, such as nothing_on_loan, one_book_each, two_on_loan` です。
|
|
722
779
|
モジュールが宣言もインポートもしていない名前を渡すと、quint が動いたあとに同じ形で `ArgumentError` を投げます。
|
|
723
780
|
例えば `quint: step names borow, which loans neither declares nor imports; step takes an action without parameters, such as step` です。
|
|
781
|
+
`reach:` には既定の `backend: "rust"` が必要です。
|
|
782
|
+
quint 0.33.0 の typescript バックエンドは、定義が初めて成り立つ状態を過ぎてもトレースを続け、そこに至らないトレースも至ったものとして示します。
|
|
783
|
+
そのため、`backend: "typescript"` と一緒に `reach:` を渡すと、quint を動かす前に `ArgumentError` を投げます。
|
|
724
784
|
トレースも、モデルも、マシンも、quint の既定と同じく `init` という名前のアクションから始まります。
|
|
725
785
|
`init` のないモジュールは `ArgumentError` を投げます。
|
|
726
786
|
例えば ``quint: begins neither declares nor imports an action named init; quint_driver starts every trace and every model at init, so declare `action init = ...` with what starts begins`` です。
|
|
@@ -729,6 +789,32 @@ quint_driver はほかの名前を受け取りません。
|
|
|
729
789
|
代わりに、モジュールに `action init = begin` を足してください。
|
|
730
790
|
quint_driver が投げる `ArgumentError` のバックトレースは、それを呼んだあなたの行から始まり、その前に quint_driver のフレームはありません。
|
|
731
791
|
|
|
792
|
+
期待(expectation)とは、すべての状態で成り立つべき述語です。
|
|
793
|
+
例えば `val one_book_each = MEMBERS.forall(m => BOOKS.filter(b => holder.get(b) == m).size() <= 1)` です。
|
|
794
|
+
その名前を、`spec:` と一緒に `Trace.replay` の `invariants:` に渡します。
|
|
795
|
+
各ステップでドライバーが仕様と一致したことを確かめたあと、モデルがそのステップの状態で期待を評価します。
|
|
796
|
+
偽になったときは `QuintDriver::Violated` を投げます。
|
|
797
|
+
これは `Mismatch` ではないので、`rescue QuintDriver::Mismatch` では捕まえません。
|
|
798
|
+
システムはどのステップでも仕様と一致したのに、それでも期待が成り立たない、という意味です。
|
|
799
|
+
メッセージは、``quint: the system agreed with the spec at every step, and the expectation `one_book_each` does not hold after step 4 `borrow` {"b" => "b3", "m" => "m2"}`` のように期待とステップを示します。
|
|
800
|
+
続けて `Mismatch` と同じく `init` からの手順を並べ、その状態での仕様の変数を `state:` の下に示し、同じ `trace:` の行で終わります。
|
|
801
|
+
述語でない名前を渡すと、最初のステップの前に `ArgumentError` を投げます。
|
|
802
|
+
`spec:` なしで `invariants:` を渡したときも同じです。
|
|
803
|
+
|
|
804
|
+
期待を破るトレースを quint に探させるには、その名前を `Quint.simulate` の `violate:` に渡します。
|
|
805
|
+
quint はそれを不変条件として検査します。
|
|
806
|
+
各トレースは期待が初めて偽になる状態で終わり、`Quint.simulate` は期待を破ったトレースだけを渡します。
|
|
807
|
+
渡されたトレースは、`invariants:` に同じ名前を渡して再生します。
|
|
808
|
+
システムがトレースと一致すれば、最後のステップで `QuintDriver::Violated` を投げます。
|
|
809
|
+
`reach:` と違い、どのトレースも期待を保ったときは、何も渡さず、何も投げません。
|
|
810
|
+
`Quint.simulate` は `QuintDriver::Quint::Simulation` を返します。
|
|
811
|
+
その `traces` は quint が動かしたトレースの数で、`violated` はそのうち期待を破ったトレースの数です。
|
|
812
|
+
`violate:` を渡さないときの `violated` は `nil` です。
|
|
813
|
+
`actions` はすべてのトレースで各アクションが取られた回数で、`never` は step アクションのうちどのトレースも取らなかったアクションの一覧です。
|
|
814
|
+
例えば `Quint.simulate("loans.qnt", traces: 50, max_steps: 20, seed: "1", violate: "one_book_each")` は `#<data QuintDriver::Quint::Simulation traces=50, violated=0, actions={"borrow" => 214, "borrow_refused" => 283, "give_back" => 161, "give_back_refused" => 342}, never=[]>` を返します。
|
|
815
|
+
`violate:` は `reach:` と同じく述語を受け取り、同じ理由で `backend: "rust"` を必要とします。
|
|
816
|
+
`reach:` と `violate:` を一緒に渡すと、quint を動かす前に `ArgumentError` を投げます。
|
|
817
|
+
|
|
732
818
|
`Quint.test(path, "lendTest", seed: "1") { |trace| ... }` は、`run lendTest = init.then(borrow("m1", "b1")).then(give_back("b1"))` のような名前付きの run のトレースを書き、そのファイルを渡します。
|
|
733
819
|
run がファイルの別のモジュールにあるときは `main:` を渡します。
|
|
734
820
|
quint test は `mbt::actionTaken` を書かないので、仕様は各ステップが取ったアクションを自分で記録する必要があります。
|
|
@@ -756,7 +842,11 @@ quint の中で run そのものが失敗したときは、quint の報告を添
|
|
|
756
842
|
`QuintDriver.machine` のオプションは次のとおりです。
|
|
757
843
|
|
|
758
844
|
- `step:` は手の一覧を持つアクションで、既定は `"step"` です。各手は名前のあるアクションを呼ぶ必要があります。引数は `nondet x = S.oneOf()` から取ります。選択肢と `any` を一つの `all` で囲んだ手(`all { nondet x = S.oneOf() any { add(x), sub(x) } }` など)は、`any` のアクションで手を進めます。モジュールにないアクションを `step:` に渡すと、モジュールのアクションを並べた `ArgumentError` を投げます(`quint: no action is named steps; the module has counting, init, step`)。
|
|
759
|
-
- `invariants:`
|
|
845
|
+
- `invariants:` は期待、つまりすべての状態で成り立つべき仕様の述語の名前で、`Trace.replay` と同じように受け取ります。
|
|
846
|
+
Hegel は `init` と毎手のあとに、その手で仕様と一致したことを確かめてから期待を評価します。
|
|
847
|
+
偽になった期待は、縮めた手順を添えて `QuintDriver::Violated` を投げます。
|
|
848
|
+
例えば ``quint: the system agreed with the spec at every step, and the expectation `one_book_each` does not hold after step 2 `borrow` {"b" => "b2", "m" => "m1"}`` です。
|
|
849
|
+
述語でない名前を渡すと、`QuintDriver.machine` が `ArgumentError` を投げます。
|
|
760
850
|
- `choose:` は Hegel が手を引く方法です。`:rule`(既定)はアクションを選び、仕様が許さなければ捨てます。最短の手順まで縮みます。`:rotate` は許されないアクションの番を次の許されるアクションに回します。少ないテストケースで深い状態に届きますが、縮めた手順に余分な手が残ることがあります。
|
|
761
851
|
Hegel の失敗の報告は、引いた値を nondet の選択値の名前で示します。
|
|
762
852
|
`:rotate` では `rule` と `move` です。
|
data/README.md
CHANGED
|
@@ -22,7 +22,7 @@ quint_driver needs Ruby 3.3 or later. It calls the `quint` command that `QUINT`
|
|
|
22
22
|
|
|
23
23
|
### Pick a first model
|
|
24
24
|
|
|
25
|
-
Pick a model with a status column, such as `state` or `status`, and a method that changes it, such as `Order#cancel` or `Loan#approve`. A model whose status a recent commit changed is a good start, because the spec then checks that change: `git log --oneline -- app/models` lists those commits.
|
|
25
|
+
Pick a model with a status column, such as `state` or `status`, and a method that changes it, such as `Order#cancel` or `Loan#approve`. A model whose status a recent commit changed is a good start, because the spec then checks that change: `git log --oneline -- app/models` lists those commits. To hunt for bugs across several entry points instead, see [Hunt for bugs](#hunt-for-bugs); `bundle exec quint_driver targets` ranks the files of your app where a hunt pays.
|
|
26
26
|
|
|
27
27
|
The steps below use `Loan`. A new loan is `"pending"`, and `Loan#approve(officer)` makes it `"approved"`. Replace `Loan`, the record that the driver's `init` creates, the method, and the state names with yours.
|
|
28
28
|
|
|
@@ -320,6 +320,39 @@ Each of the 50 traces ran on the real models and the test database, and rolled b
|
|
|
320
320
|
|
|
321
321
|
To delete the rows in the driver's `init` instead of a savepoint, and for the reason the savepoint must not be joinable, see the [skill](skills/quint_driver/SKILL.md).
|
|
322
322
|
|
|
323
|
+
## Hunt for bugs
|
|
324
|
+
|
|
325
|
+
To find bugs, not to pin one model, write two things in the spec. Actions describe what the code does now, quirks included, so the app follows every trace. Give an action that calls an outside service a pick that says which call fails, so a trace also runs the app's rescue. Boolean `val`s describe what the operator expects, and the code may break them. Then aim Quint at each expectation with `violate:`, and replay its traces with the same name in `invariants:`:
|
|
326
|
+
|
|
327
|
+
```ruby
|
|
328
|
+
expectations.each do |expectation|
|
|
329
|
+
it "keeps #{expectation} on the traces Quint aims at it" do
|
|
330
|
+
simulation = QuintDriver::Quint.simulate(qnt, traces: 200, max_steps: 12, seed: "1", violate: expectation) do |path|
|
|
331
|
+
rolled_back { QuintDriver::Trace.replay(path, driver, spec:, invariants: [ expectation ], ignore:) }
|
|
332
|
+
end
|
|
333
|
+
expect(simulation.never).to be_empty
|
|
334
|
+
end
|
|
335
|
+
end
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
`test/fixture/depot` is a small Rails app of parcel lockers with four bugs planted in it, and its `spec/quint/` hunts for them this way. Each bug fails as a `QuintDriver::Violated`: the app agreed with the spec at every step, and the operator's expectation still does not hold.
|
|
339
|
+
|
|
340
|
+
```text
|
|
341
|
+
quint: the system agreed with the spec at every step, and the expectation `free_compartment_has_no_code` does not hold after step 2 `release` {"offline" => 1, "p" => "p3"}
|
|
342
|
+
steps:
|
|
343
|
+
init {}
|
|
344
|
+
assignParcel {"offline" => 2, "p" => "p3"}
|
|
345
|
+
release {"offline" => 1, "p" => "p3"}
|
|
346
|
+
state:
|
|
347
|
+
everDone: {}
|
|
348
|
+
intake: "none"
|
|
349
|
+
live: {1}
|
|
350
|
+
place: {"p1" => "Waiting", "p2" => "Waiting", "p3" => "Collected"}
|
|
351
|
+
row: {"p1" => "", "p2" => "", "p3" => ""}
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
Here the parcel is collected and the compartment is free, but the locker controller still holds its code: the release page rescued the controller's time-out inside its transaction. A `Violated` is a bug suspect, and a `Mismatch` in a hunt is most often an error in the spec or the driver. To pin a failure as one example, paste the text under its `steps:` into `QuintDriver.replay_steps(spec, driver, <<~STEPS, invariants: [...])`, which runs those steps again with no quint run and no Hegel. Quint's trace holds steps the failure does not need, so `QuintDriver.shrink_steps` takes them out first while the same expectation still breaks. The [skill](skills/quint_driver/SKILL.md#hunt-for-bugs) has the full loop: where to look, how to confirm a suspect, and when to stop. To find an update lost between a read and a write, hold a request part way with `QuintDriver::Hold`, as the skill's [A request another one comes between](skills/quint_driver/SKILL.md#a-request-another-one-comes-between) shows.
|
|
355
|
+
|
|
323
356
|
## Try it without an app
|
|
324
357
|
|
|
325
358
|
### Install
|
|
@@ -525,7 +558,7 @@ ln -s "$(bundle info --path quint_driver)/skills/quint_driver" .agents/skills/qu
|
|
|
525
558
|
|
|
526
559
|
## Write a driver
|
|
527
560
|
|
|
528
|
-
A driver runs the spec's actions on your system and reads the system back in the spec's terms.
|
|
561
|
+
A driver runs the spec's actions on your system and reads the system back in the spec's terms. `bundle exec quint_driver outline spec.qnt` prints one to start from: each action with the picks it receives, each variable `state` must report with the Ruby shape of its value, and the expectations. It exits 1 with the reason when no driver can run the step action.
|
|
529
562
|
|
|
530
563
|
```ruby
|
|
531
564
|
class LoansDriver
|
|
@@ -581,7 +614,11 @@ An error a step raises comes out as `QuintDriver::StepRaised`, not as a `Mismatc
|
|
|
581
614
|
|
|
582
615
|
`Quint.simulate` runs the module named after the file. Pass `main:` to run another module of that file, the same name `Spec.new` takes. When quint fails or is not installed, `Spec.new` and `Quint.simulate` raise `QuintDriver::QuintFailed` with quint's reason. Its backtrace starts at the line of yours that called the gem, with no frame of quint_driver before it.
|
|
583
616
|
|
|
584
|
-
To test the steps that lead to one state, pass `reach:` the name of a definition that holds there, such as `reach: "two_on_loan"` for `val two_on_loan = BOOKS.filter(b => onLoan(holder, b)).size() == 2`. Each trace then ends at the first state where the definition holds, and `Quint.simulate` yields only the traces that get there. Quint checks `not(two_on_loan)` as the invariant and stops a trace where it breaks. When no trace gets there, it raises `QuintDriver::QuintFailed`, such as `quint: no trace of 20 reached two_on_loan within 1 steps; raise max_steps or traces`. `reach:` takes a predicate, a boolean `val` or `def` without parameters, and `step:` an action without parameters. A name of another kind raises `ArgumentError` before quint runs, such as `quint: reach names borrow, an action with parameters of loans; reach takes a predicate, a boolean val or def without parameters, such as nothing_on_loan, one_book_each, two_on_loan`. A name the module neither declares nor imports raises `ArgumentError` the same way once quint has run, such as `quint: step names borow, which loans neither declares nor imports; step takes an action without parameters, such as step`. Every trace, every model, and every machine starts at the action named `init`, as quint does by default. A module without one raises `ArgumentError`, such as ``quint: begins neither declares nor imports an action named init; quint_driver starts every trace and every model at init, so declare `action init = ...` with what starts begins``. quint_driver takes no other name for it: a trace names its first step after that action, and the driver and the model read that step as `init`. Add `action init = begin` to the module instead. The backtrace of each `ArgumentError` quint_driver raises starts at the line of yours that called it, with no frame of quint_driver before it.
|
|
617
|
+
To test the steps that lead to one state, pass `reach:` the name of a definition that holds there, such as `reach: "two_on_loan"` for `val two_on_loan = BOOKS.filter(b => onLoan(holder, b)).size() == 2`. Each trace then ends at the first state where the definition holds, and `Quint.simulate` yields only the traces that get there. Quint checks `not(two_on_loan)` as the invariant and stops a trace where it breaks. When no trace gets there, it raises `QuintDriver::QuintFailed`, such as `quint: no trace of 20 reached two_on_loan within 1 steps; raise max_steps or traces`. `reach:` takes a predicate, a boolean `val` or `def` without parameters, and `step:` an action without parameters. A name of another kind raises `ArgumentError` before quint runs, such as `quint: reach names borrow, an action with parameters of loans; reach takes a predicate, a boolean val or def without parameters, such as nothing_on_loan, one_book_each, two_on_loan`. A name the module neither declares nor imports raises `ArgumentError` the same way once quint has run, such as `quint: step names borow, which loans neither declares nor imports; step takes an action without parameters, such as step`. `reach:` needs the default `backend: "rust"`. quint 0.33.0's typescript backend runs a trace on past the state where the definition first holds, and marks traces that never get there as ones that do, so `reach:` with `backend: "typescript"` raises `ArgumentError` before quint runs. Every trace, every model, and every machine starts at the action named `init`, as quint does by default. A module without one raises `ArgumentError`, such as ``quint: begins neither declares nor imports an action named init; quint_driver starts every trace and every model at init, so declare `action init = ...` with what starts begins``. quint_driver takes no other name for it: a trace names its first step after that action, and the driver and the model read that step as `init`. Add `action init = begin` to the module instead. The backtrace of each `ArgumentError` quint_driver raises starts at the line of yours that called it, with no frame of quint_driver before it.
|
|
618
|
+
|
|
619
|
+
An expectation is a predicate that should hold in every state, such as `val one_book_each = MEMBERS.forall(m => BOOKS.filter(b => holder.get(b) == m).size() <= 1)`. Pass its name in `invariants:` to `Trace.replay`, with `spec:`. The model evaluates it in each state of the trace, after the step's agreement check, and one that is false raises `QuintDriver::Violated`. That is not a `Mismatch`, and `rescue QuintDriver::Mismatch` does not catch it: the system agreed with the spec at every step, and the expectation still does not hold. The message names the expectation and the step, such as ``quint: the system agreed with the spec at every step, and the expectation `one_book_each` does not hold after step 4 `borrow` {"b" => "b3", "m" => "m2"}``. It lists the steps from `init` as a `Mismatch` does, gives the spec's variables in that state under `state:`, and ends with the same `trace:` line. A name that is no predicate raises `ArgumentError` before the first step, and so does `invariants:` without `spec:`.
|
|
620
|
+
|
|
621
|
+
To have quint search for the traces that break an expectation, pass its name as `violate:` to `Quint.simulate`. Quint checks it as its invariant, each trace ends at the first state where it is false, and only the traces that break it are yielded. Replay each with the same name in `invariants:`, and a system that agrees with the trace raises `QuintDriver::Violated` at its last step. Unlike `reach:`, a simulation where every trace keeps the expectation yields nothing and raises nothing. `Quint.simulate` returns a `QuintDriver::Quint::Simulation`, whose `traces` is how many traces quint ran and whose `violated` is how many of them broke the expectation, or `nil` without `violate:`, whose `actions` counts the steps each action took across every trace, and whose `never` lists the actions of the step action that no trace took, such as `#<data QuintDriver::Quint::Simulation traces=50, violated=0, actions={"borrow" => 214, "borrow_refused" => 283, "give_back" => 161, "give_back_refused" => 342}, never=[]>` for `Quint.simulate("loans.qnt", traces: 50, max_steps: 20, seed: "1", violate: "one_book_each")`. `violate:` takes a predicate as `reach:` does and needs `backend: "rust"` for the same reason. `reach:` and `violate:` together raise `ArgumentError` before quint runs.
|
|
585
622
|
|
|
586
623
|
`Quint.test(path, "lendTest", seed: "1") { |trace| ... }` writes the trace of a named run, such as `run lendTest = init.then(borrow("m1", "b1")).then(give_back("b1"))`, and yields its file; pass `main:` when the run is in another module of the file. quint test writes no `mbt::actionTaken`, so the spec has to record the action each step took, as a [Choreo](https://github.com/informalsystems/choreo) spec does: a variable that holds a sum type whose tag names the action and whose record holds its picks, such as `taken: Borrow({ m: m, b: b })`. Pass the path to that variable as `action:` to `Trace.replay`. When the state the driver answers for sits inside a variable, such as the `system` field of a Choreo spec's one variable, pass its path as `state:`; the driver's `state` then returns that record or map. `test/recorded.qnt` is a small spec of this shape, and `RecordedDriver` in `test/trace_test.rb` is its driver:
|
|
587
624
|
|
|
@@ -596,7 +633,7 @@ The driver gets `step("Init", {})`, then `step("Borrow", { "m" => "m1", "b" => "
|
|
|
596
633
|
`QuintDriver.machine` takes these options:
|
|
597
634
|
|
|
598
635
|
- `step:` is the action that lists the moves, `"step"` by default. Each move must call a named action. Arguments come from `nondet x = S.oneOf()`. A step that is one `all` around its picks and an `any`, such as `all { nondet x = S.oneOf() any { add(x), sub(x) } }`, moves by the actions of the `any`. A `step:` that is no action of the module raises `ArgumentError` with the actions it has, such as `quint: no action is named steps; the module has counting, init, step`.
|
|
599
|
-
- `invariants:` names
|
|
636
|
+
- `invariants:` names expectations, predicates of the spec that should hold in every state, as `Trace.replay` takes them. Hegel checks them at `init` and after every move, after the move's agreement check. One that is false raises `QuintDriver::Violated` with the shrunk steps, such as ``quint: the system agreed with the spec at every step, and the expectation `one_book_each` does not hold after step 2 `borrow` {"b" => "b2", "m" => "m1"}``. A name that is no predicate raises `ArgumentError` from `QuintDriver.machine`.
|
|
600
637
|
- `choose:` is how Hegel draws a move. `:rule` (the default) picks an action and rejects it when the spec disables it. It shrinks to the shortest sequence. `:rotate` passes a disabled action's turn to the next enabled one. It reaches deep states with fewer test cases, but a shrunk sequence can keep extra moves. Hegel's failure report names each draw after the nondet pick it chose, or `rule` and `move` under `:rotate`. A label drawn more than once in a test case is numbered in draw order (`m_1 = "m2"`, `m_2 = "m1"`); a label drawn once prints bare (`m = "m2"`).
|
|
601
638
|
|
|
602
639
|
Each test case starts a new system through the driver's `init` when the machine starts, before Hegel's first step, so a driver that fails at `init` fails with no step in Hegel's report. A sequence of moves that the system already agreed on is not run again, because shrinking asks for the same sequence many times. This assumes that the system answers the same sequence the same way each time. A disagreement always runs on the system again.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// A shelf of three items, and reservations that each read the stock, then
|
|
2
|
+
// write it back one lower. The spec splits a reservation into the step that
|
|
3
|
+
// reads and the step that writes, so another reservation can come between.
|
|
4
|
+
module shelf {
|
|
5
|
+
pure val REQUESTS = Set("r1", "r2")
|
|
6
|
+
|
|
7
|
+
var stock: int
|
|
8
|
+
var reserved: int
|
|
9
|
+
var loaded: str -> int // the stock each reservation read and has not written yet
|
|
10
|
+
|
|
11
|
+
// What the owner expects: every reservation takes one item off the shelf.
|
|
12
|
+
val every_reservation_takes_one = stock + reserved == 3
|
|
13
|
+
|
|
14
|
+
action init = all {
|
|
15
|
+
stock' = 3,
|
|
16
|
+
reserved' = 0,
|
|
17
|
+
loaded' = Map(),
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
action load(r: str): bool = all {
|
|
21
|
+
not(loaded.keys().contains(r)),
|
|
22
|
+
loaded' = loaded.put(r, stock),
|
|
23
|
+
stock' = stock, reserved' = reserved,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
action save(r: str): bool = all {
|
|
27
|
+
loaded.keys().contains(r),
|
|
28
|
+
stock' = loaded.get(r) - 1,
|
|
29
|
+
reserved' = reserved + 1,
|
|
30
|
+
loaded' = loaded.keys().exclude(Set(r)).mapBy(k => loaded.get(k)),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
action step = any {
|
|
34
|
+
nondet r = REQUESTS.oneOf()
|
|
35
|
+
any { load(r), save(r) },
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# The system the tests hold to shelf.qnt, and a driver that stops each
|
|
2
|
+
# reservation between its read and its write with QuintDriver::Hold.
|
|
3
|
+
class Shelf
|
|
4
|
+
attr_accessor :stock, :reserved
|
|
5
|
+
|
|
6
|
+
def initialize
|
|
7
|
+
@stock = 3
|
|
8
|
+
@reserved = 0
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
# Reads the stock, then writes it back one lower, with no lock between.
|
|
12
|
+
def reserve
|
|
13
|
+
left = stock
|
|
14
|
+
self.stock = left - 1
|
|
15
|
+
self.reserved += 1
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
class ShelfDriver
|
|
20
|
+
SPEC = File.expand_path("shelf.qnt", __dir__)
|
|
21
|
+
|
|
22
|
+
def step(action, picks)
|
|
23
|
+
case action
|
|
24
|
+
when "init"
|
|
25
|
+
@hold = QuintDriver::Hold.new
|
|
26
|
+
@shelf = Shelf.new
|
|
27
|
+
hold = @hold
|
|
28
|
+
# The pause point: right after the reservation reads the stock.
|
|
29
|
+
@shelf.define_singleton_method(:stock) { super().tap { hold.pause(_1) } }
|
|
30
|
+
@loaded = {}
|
|
31
|
+
when "load" then @loaded[picks["r"]] = @hold.start(picks["r"]) { @shelf.reserve }
|
|
32
|
+
when "save" then @hold.finish(picks["r"]).then { @loaded.delete(picks["r"]) }
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def state = { "stock" => @shelf.stock, "reserved" => @shelf.reserved, "loaded" => @loaded }
|
|
37
|
+
end
|
data/exe/quint_driver
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# The quint_driver command.
|
|
3
|
+
# `quint_driver targets [APP]` ranks the files of an app where a hunt pays,
|
|
4
|
+
# with the lines to read first. `quint_driver outline SPEC.qnt` prints a
|
|
5
|
+
# driver to start from: the actions with their picks, the variables state
|
|
6
|
+
# reports with the shape of each value, and the expectations. It exits 1
|
|
7
|
+
# with the reason when the spec does not compile or its step action cannot
|
|
8
|
+
# be driven.
|
|
9
|
+
require "optparse"
|
|
10
|
+
require_relative "../lib/quint_driver"
|
|
11
|
+
|
|
12
|
+
usage = <<~USAGE
|
|
13
|
+
usage: quint_driver targets [APP] [--top N]
|
|
14
|
+
quint_driver outline SPEC.qnt [--main MODULE] [--step ACTION]
|
|
15
|
+
USAGE
|
|
16
|
+
options = { step: "step", top: 10 }
|
|
17
|
+
parser = OptionParser.new(usage) do |o|
|
|
18
|
+
o.on("--main MODULE", "outline: the module to read; the file's name by default") { options[:main] = _1 }
|
|
19
|
+
o.on("--step ACTION", "outline: the step action; step by default") { options[:step] = _1 }
|
|
20
|
+
o.on("--top N", Integer, "targets: how many files to show; 10 by default") { options[:top] = _1 }
|
|
21
|
+
end
|
|
22
|
+
command, path = parser.parse(ARGV)
|
|
23
|
+
|
|
24
|
+
case command
|
|
25
|
+
when "targets"
|
|
26
|
+
root = path || "."
|
|
27
|
+
abort "quint: no directory #{root}" unless File.directory?(root)
|
|
28
|
+
begin
|
|
29
|
+
print QuintDriver::Targets.report(root, top: options[:top])
|
|
30
|
+
rescue ArgumentError => e
|
|
31
|
+
abort e.message
|
|
32
|
+
end
|
|
33
|
+
when "outline"
|
|
34
|
+
abort usage unless path
|
|
35
|
+
begin
|
|
36
|
+
print QuintDriver::Spec.new(path, main: options[:main] || File.basename(path, ".qnt")).outline(options[:step])
|
|
37
|
+
rescue QuintDriver::Unsupported, QuintDriver::QuintFailed, ArgumentError => e
|
|
38
|
+
abort e.message
|
|
39
|
+
end
|
|
40
|
+
else abort usage
|
|
41
|
+
end
|
data/lib/quint_driver/hegel.rb
CHANGED
|
@@ -21,11 +21,14 @@ module QuintDriver
|
|
|
21
21
|
# +observe+ names definitions of the spec, as Trace.replay takes them: the
|
|
22
22
|
# driver reports each one in its state, held to the model's value.
|
|
23
23
|
# +ignore+ names variables the driver does not report, as Trace.replay
|
|
24
|
-
# takes them.
|
|
24
|
+
# takes them. +invariants+ names predicates of the spec, expectations
|
|
25
|
+
# that have to hold in every state, as Trace.replay takes them: one that
|
|
26
|
+
# is false where the system agreed raises Violated.
|
|
25
27
|
def self.machine(spec, driver:, step: "step", invariants: [], choose: :rule, observe: [], ignore: [])
|
|
26
28
|
rules = spec.rules(step)
|
|
27
|
-
observe, ignore = observe.map(&:to_s), ignore.map(&:to_s)
|
|
29
|
+
observe, ignore, invariants = observe.map(&:to_s), ignore.map(&:to_s), invariants.map(&:to_s)
|
|
28
30
|
spec.observable!(observe)
|
|
31
|
+
spec.predicates!(invariants, "invariants")
|
|
29
32
|
Agreement.ignorable!(ignore, spec.declarations.select { _1["kind"] == "var" }.map { _1["name"] }, "the spec's variables")
|
|
30
33
|
# Many draws map to one sequence of moves, so the shrinker asks for the
|
|
31
34
|
# same sequence thousands of times: on one failure, 8818 test cases held
|
|
@@ -129,11 +132,19 @@ module QuintDriver
|
|
|
129
132
|
else Agreement.refuse "quint: choose is :rule or :rotate"
|
|
130
133
|
end
|
|
131
134
|
|
|
132
|
-
# Hegel
|
|
133
|
-
#
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
135
|
+
# Hegel checks an invariant before the first move and after the last,
|
|
136
|
+
# and between moves only when it samples one, unless always_run is
|
|
137
|
+
# set, as it is here. A move checks its own agreement before Hegel
|
|
138
|
+
# checks the expectations, so a disagreement stays a Mismatch. One
|
|
139
|
+
# Hegel invariant holds them all, so expectations that break in one
|
|
140
|
+
# state are named together, as on a replay.
|
|
141
|
+
unless invariants.empty?
|
|
142
|
+
invariant("invariants", always_run: true) do
|
|
143
|
+
broken = invariants.reject { @model.value(_1) }
|
|
144
|
+
next if broken.empty?
|
|
145
|
+
|
|
146
|
+
last = @moves.empty? ? at.(0, init) : at.(@numbers.last, @moves.last)
|
|
147
|
+
Agreement.violated!(last, broken, steps: [ init, *@moves ], state: @model.state)
|
|
137
148
|
end
|
|
138
149
|
end
|
|
139
150
|
end
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
module QuintDriver
|
|
2
|
+
# Stops a call part way and lets it go on in a later step, so a spec can
|
|
3
|
+
# split one request into the step that loads and the step that saves, and
|
|
4
|
+
# put another request between them. The code under test calls #pause at
|
|
5
|
+
# the point to stop, usually through a stub the driver installs; outside a
|
|
6
|
+
# held call #pause does nothing, so the same stub is harmless elsewhere.
|
|
7
|
+
#
|
|
8
|
+
# A held call runs in a Fiber on the same thread, so it shares the
|
|
9
|
+
# thread's database connection: a test that rolls back rolls the held call
|
|
10
|
+
# back too, and no second connection is needed. On one connection the
|
|
11
|
+
# transactions of two held calls nest, so pause where the call holds no
|
|
12
|
+
# open transaction, such as after its read and before the transaction
|
|
13
|
+
# that writes. Two calls held inside their transactions and finished in
|
|
14
|
+
# the order they started leave ActiveRecord rolling back a transaction
|
|
15
|
+
# SQLite no longer has.
|
|
16
|
+
#
|
|
17
|
+
# The block runs as a Fiber, so it ends with `next`, not `return` or
|
|
18
|
+
# `break`, and it does not call Fiber.yield itself. A pause from a Fiber
|
|
19
|
+
# inside the held call, such as one Enumerator#next runs, cannot stop the
|
|
20
|
+
# call, so it raises instead of letting the call run through unheld.
|
|
21
|
+
class Hold
|
|
22
|
+
def initialize
|
|
23
|
+
@held = {}
|
|
24
|
+
@ours = Set.new
|
|
25
|
+
@running = nil
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Runs the block until it calls #pause, and returns the value given to
|
|
29
|
+
# #pause. When the block ends without a pause, nothing is held and the
|
|
30
|
+
# block's value is returned. An error the block raises comes out here.
|
|
31
|
+
def start(name, &block)
|
|
32
|
+
raise ArgumentError, "quint: #{name.inspect} is already held; finish it first" if held?(name)
|
|
33
|
+
|
|
34
|
+
fiber = Fiber.new { [ :done, block.call ] }
|
|
35
|
+
@ours << fiber
|
|
36
|
+
@held[name] = fiber
|
|
37
|
+
run(name, fiber)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Lets the call held as +name+ run to its end, through any later pause,
|
|
41
|
+
# and returns the block's value. An error the call raises comes out here.
|
|
42
|
+
def finish(name)
|
|
43
|
+
fiber = @held[name] or raise ArgumentError, "quint: nothing is held as #{name.inspect}; held: #{held.inspect}"
|
|
44
|
+
value = run(name, fiber) while held?(name)
|
|
45
|
+
value
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def held?(name) = @held.key?(name)
|
|
49
|
+
|
|
50
|
+
# The names of the calls that are stopped now, in the order they started.
|
|
51
|
+
def held = @held.keys
|
|
52
|
+
|
|
53
|
+
# Called by the code under test where a held call stops. +value+ is what
|
|
54
|
+
# #start returns, such as the row the call loaded.
|
|
55
|
+
def pause(value = nil)
|
|
56
|
+
if @ours.include?(Fiber.current)
|
|
57
|
+
Fiber.yield([ :paused, value ])
|
|
58
|
+
elsif @running
|
|
59
|
+
raise ArgumentError, "quint: #{@running.inspect} paused in a Fiber of its own, such as one Enumerator#next runs; " \
|
|
60
|
+
"pause where the held call runs, outside that Fiber"
|
|
61
|
+
end
|
|
62
|
+
nil
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
private
|
|
66
|
+
def run(name, fiber)
|
|
67
|
+
outer, @running = @running, name
|
|
68
|
+
answer = fiber.resume
|
|
69
|
+
kind, value = answer
|
|
70
|
+
unless %i[paused done].include?(kind) && answer.is_a?(Array)
|
|
71
|
+
raise ArgumentError, "quint: #{name.inspect} called Fiber.yield itself; a held call stops only at pause"
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
forget(name, fiber) if kind == :done
|
|
75
|
+
value
|
|
76
|
+
rescue Exception
|
|
77
|
+
forget(name, fiber)
|
|
78
|
+
raise
|
|
79
|
+
ensure
|
|
80
|
+
@running = outer
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def forget(name, fiber)
|
|
84
|
+
@held.delete(name)
|
|
85
|
+
@ours.delete(fiber)
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
data/lib/quint_driver/model.rb
CHANGED
|
@@ -13,6 +13,18 @@ module QuintDriver
|
|
|
13
13
|
# body cannot evaluate is reported where the spec writes it.
|
|
14
14
|
Closure = Struct.new(:params, :body, :env, :within)
|
|
15
15
|
|
|
16
|
+
# A `val` inside an action, evaluated on its first read. Quint's
|
|
17
|
+
# evaluator reads one only when the action needs it, so a `val c =
|
|
18
|
+
# m.get(r)` above the guard that makes `r` a key is fine in Quint, and
|
|
19
|
+
# an eager model would refuse the disabled move Hegel tries.
|
|
20
|
+
Deferred = Struct.new(:compute) do
|
|
21
|
+
def value
|
|
22
|
+
return @value if defined?(@value)
|
|
23
|
+
|
|
24
|
+
@value = compute.call
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
16
28
|
# Spec#model is the one way to build a model: the evaluator trusts the
|
|
17
29
|
# shape of quint's compiled IR and checks none of it.
|
|
18
30
|
private_class_method :new
|
|
@@ -129,7 +141,9 @@ module QuintDriver
|
|
|
129
141
|
when "lambda" then Closure.new(node["params"].map { _1["name"] }, node["expr"], env, @within)
|
|
130
142
|
when "let"
|
|
131
143
|
definition = node["opdef"]
|
|
132
|
-
|
|
144
|
+
within = @within
|
|
145
|
+
deferred = Deferred.new(-> { inside(within) { eval(definition["expr"], env) } })
|
|
146
|
+
eval(node["expr"], env.merge(definition["name"] => deferred))
|
|
133
147
|
when "app" then apply(node["opcode"], node["args"], env)
|
|
134
148
|
else refuse("IR kind #{node['kind']}")
|
|
135
149
|
end
|
|
@@ -137,7 +151,7 @@ module QuintDriver
|
|
|
137
151
|
|
|
138
152
|
# Quint reserves Bool, Int and Nat, so no definition shadows them.
|
|
139
153
|
def lookup(name, env)
|
|
140
|
-
return env[name] if env.key?(name)
|
|
154
|
+
return env[name].is_a?(Deferred) ? env[name].value : env[name] if env.key?(name)
|
|
141
155
|
return @state.fetch(name) if @vars.include?(name)
|
|
142
156
|
return BOOL if name == "Bool"
|
|
143
157
|
|
|
@@ -173,7 +187,8 @@ module QuintDriver
|
|
|
173
187
|
end
|
|
174
188
|
|
|
175
189
|
def refuse(what, why = nil)
|
|
176
|
-
raise Unsupported, "quint: no evaluation for #{what} #{@within ? "in #{@within}" : 'outside any definition'}#{"; #{why}" if why}"
|
|
190
|
+
raise Unsupported, "quint: no evaluation for #{what} #{@within ? "in #{@within}" : 'outside any definition'}#{"; #{why}" if why}",
|
|
191
|
+
Agreement.outside(caller_locations)
|
|
177
192
|
end
|
|
178
193
|
|
|
179
194
|
# Quint's builtin docs leave these undefined, and its two evaluators do
|
|
@@ -206,6 +221,9 @@ module QuintDriver
|
|
|
206
221
|
when "implies" then !eval(args[0], env) || eval(args[1], env)
|
|
207
222
|
when "ite" then eval(args[eval(args[0], env) ? 1 : 2], env)
|
|
208
223
|
when "assign" then @next[args[0]["name"]] = eval(args[1], env); true
|
|
224
|
+
# A `def` with parameters inside an action or another def is a let
|
|
225
|
+
# whose value is a lambda, and a call of it names it as the operator.
|
|
226
|
+
when *env.keys then call(lookup(op, env), args.map { eval(_1, env) })
|
|
209
227
|
else operate(op, args.map { eval(_1, env) })
|
|
210
228
|
end
|
|
211
229
|
end
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
module QuintDriver
|
|
2
|
+
class Spec
|
|
3
|
+
# A driver for this module to start from, as Ruby source: one `when` per
|
|
4
|
+
# action the step action can take, with the picks it receives, and one
|
|
5
|
+
# key per variable `state` must report, with the Ruby shape of its value.
|
|
6
|
+
# The expectations, the boolean vals and defs without parameters, are
|
|
7
|
+
# listed for invariants: and violate:. Raises Unsupported, as a replay
|
|
8
|
+
# would, when the step action has a shape the driver protocol cannot run,
|
|
9
|
+
# so the outline is also the check that a driver can be written at all.
|
|
10
|
+
def outline(step = "step")
|
|
11
|
+
picks = rules(step).each_with_object({ "init" => {} }) do |rule, actions|
|
|
12
|
+
(actions[rule.action] ||= {}).merge!(rule.domains.transform_values { shape(@types.dig(_1["id"].to_s, "type", "elem")) })
|
|
13
|
+
end
|
|
14
|
+
variables = declarations.sort_by { _1["id"] }.select { _1["kind"] == "var" }
|
|
15
|
+
name = @main.split(/[^A-Za-z0-9]+/).map { _1[0].upcase + _1[1..] }.join
|
|
16
|
+
[ "# A driver for the module #{@main}, whose step action is #{step}.",
|
|
17
|
+
"# Expectations, for invariants: or violate:",
|
|
18
|
+
*expectations.map { "# #{_1}" }.then { _1.empty? ? [ "# none yet: write what the operator expects as boolean vals" ] : _1 },
|
|
19
|
+
"class #{name}Driver",
|
|
20
|
+
" def step(action, picks)",
|
|
21
|
+
" case action",
|
|
22
|
+
*picks.map { |action, given| " when #{action.dump}#{" # #{given.map { "picks[#{_1.dump}]: #{_2}" }.join(', ')}" unless given.empty?}" },
|
|
23
|
+
" end",
|
|
24
|
+
" end",
|
|
25
|
+
"",
|
|
26
|
+
" # A variable the system does not keep, such as a pick the spec",
|
|
27
|
+
" # remembers, goes in ignore: instead of here.",
|
|
28
|
+
" def state",
|
|
29
|
+
" {",
|
|
30
|
+
*variables.map { " #{_1['name'].dump} => nil, # #{shape(_1['typeAnnotation'])}" },
|
|
31
|
+
" }",
|
|
32
|
+
" end",
|
|
33
|
+
"end",
|
|
34
|
+
"" ].join("\n")
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
private
|
|
38
|
+
# The Ruby value a driver reports for a Quint type, as `state` and the
|
|
39
|
+
# picks take them: see "Write the driver" in the skill.
|
|
40
|
+
def shape(type, seen = Set.new)
|
|
41
|
+
case type&.fetch("kind")
|
|
42
|
+
when "int" then "Integer"
|
|
43
|
+
when "str" then "String"
|
|
44
|
+
when "bool" then "true or false"
|
|
45
|
+
when "set" then "Set of #{shape(type['elem'], seen)}"
|
|
46
|
+
when "list" then "Array of #{shape(type['elem'], seen)}"
|
|
47
|
+
when "fun" then "Hash of #{shape(type['arg'], seen)} => #{shape(type['res'], seen)}"
|
|
48
|
+
when "tup" then "[#{type.dig('fields', 'fields').map { shape(_1['fieldType'], seen) }.join(', ')}]"
|
|
49
|
+
when "rec" then "{#{type.dig('fields', 'fields').map { "#{_1['fieldName'].dump} => #{shape(_1['fieldType'], seen)}" }.join(', ')}}"
|
|
50
|
+
when "sum" then cases(type.dig("fields", "fields"), seen)
|
|
51
|
+
when "const"
|
|
52
|
+
typedef = declarations.find { _1["kind"] == "typedef" && _1["name"] == type["name"] && _1["type"] }
|
|
53
|
+
typedef && !seen.include?(type["name"]) ? shape(typedef["type"], seen | [ type["name"] ]) : type["name"]
|
|
54
|
+
else type ? type["kind"] : "any value"
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def cases(fields, seen)
|
|
59
|
+
tags = fields.map { _1["fieldName"] }
|
|
60
|
+
if tags.sort == %w[None Some]
|
|
61
|
+
return "nil or #{shape(fields.find { _1['fieldName'] == 'Some' }['fieldType'], seen)}"
|
|
62
|
+
end
|
|
63
|
+
each = fields.map do |field|
|
|
64
|
+
empty = field.dig("fieldType", "kind") == "tup" && field.dig("fieldType", "fields", "fields").empty?
|
|
65
|
+
empty ? field["fieldName"].dump : "[#{field['fieldName'].dump}, #{shape(field['fieldType'], seen)}]"
|
|
66
|
+
end
|
|
67
|
+
each.size > 1 ? "#{each[0..-2].join(', ')} or #{each[-1]}" : each.first
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|