lawspec 0.29.2 → 0.31.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.
- package/CHANGELOG.md +407 -1
- package/README.md +9 -3
- package/api.mjs +1 -0
- package/beam-doctor.mjs +2 -2
- package/bin/lawspec.mjs +100 -102
- package/build.json +503 -411
- package/component-packages.mjs +339 -0
- package/component.d.ts +46 -0
- package/component.mjs +208 -0
- package/core.wasm +2 -2
- package/core_jsffi.js +5 -5
- package/examples/native-payments/clojure/lawspec.edn +48 -0
- package/examples/native-payments/clojure/src/domain/payments.clj +1 -1
- package/examples/native-payments/clojure/test/domain/payment_generators.clj +1 -1
- package/examples/native-payments/csharp/lawspec.edn +48 -0
- package/examples/native-payments/elixir/lawspec.edn +123 -0
- package/examples/native-payments/erlang/lawspec.edn +128 -0
- package/examples/native-payments/fsharp/lawspec.edn +123 -0
- package/examples/native-payments/gleam/lawspec.edn +123 -0
- package/examples/native-payments/go/lawspec.edn +123 -0
- package/examples/native-payments/groovy/lawspec.edn +123 -0
- package/examples/native-payments/haskell/lawspec.edn +123 -0
- package/examples/native-payments/java/lawspec.edn +123 -0
- package/examples/native-payments/javascript/lawspec.edn +123 -0
- package/examples/native-payments/kotlin/lawspec.edn +123 -0
- package/examples/native-payments/prolog/lawspec.edn +48 -0
- package/examples/native-payments/python/lawspec.edn +123 -0
- package/examples/native-payments/rust/lawspec.edn +124 -0
- package/examples/native-payments/scala/lawspec.edn +123 -0
- package/examples/native-payments/swift/lawspec.edn +123 -0
- package/examples/native-payments/typescript/lawspec.edn +123 -0
- package/examples/packages/orders/lawspec.edn +25 -0
- package/examples/packages/shop-domain/lawspec.edn +13 -0
- package/examples/packages/shop-tax-1/lawspec.edn +9 -0
- package/examples/packages/shop-tax-2/lawspec.edn +9 -0
- package/examples/specs/handler_bindings.lawspec +2 -2
- package/examples/specs/harness_testing.lawspec +1 -1
- package/files.mjs +2 -1
- package/go.mod +4 -0
- package/index.d.ts +145 -8
- package/input-files.mjs +47 -0
- package/launcher.mjs +33 -13
- package/lsp.mjs +10 -5
- package/native-evidence.mjs +58 -19
- package/native-examples.mjs +8 -7
- package/native-host.mjs +71 -0
- package/package.json +8 -3
- package/proof.d.ts +8 -2
- package/proof.mjs +186 -34
- package/scala-build-state.mjs +59 -0
- package/templates.mjs +242 -2
- package/test-command.mjs +193 -61
- package/builtin-data-names.mjs +0 -73
- package/examples/native-payments/clojure/lawspec.json +0 -62
- package/examples/native-payments/csharp/lawspec.json +0 -62
- package/examples/native-payments/elixir/lawspec.json +0 -160
- package/examples/native-payments/erlang/lawspec.json +0 -159
- package/examples/native-payments/fsharp/lawspec.json +0 -178
- package/examples/native-payments/gleam/lawspec.json +0 -160
- package/examples/native-payments/go/lawspec.json +0 -147
- package/examples/native-payments/groovy/lawspec.json +0 -176
- package/examples/native-payments/haskell/lawspec.json +0 -160
- package/examples/native-payments/java/lawspec.json +0 -176
- package/examples/native-payments/javascript/lawspec.json +0 -160
- package/examples/native-payments/kotlin/lawspec.json +0 -176
- package/examples/native-payments/prolog/lawspec.json +0 -20
- package/examples/native-payments/python/lawspec.json +0 -160
- package/examples/native-payments/rust/lawspec.json +0 -178
- package/examples/native-payments/scala/lawspec.json +0 -176
- package/examples/native-payments/swift/lawspec.json +0 -165
- package/examples/native-payments/typescript/lawspec.json +0 -160
- package/examples/packages/orders/lawspec.json +0 -27
- package/examples/packages/shop-domain/lawspec-package.json +0 -7
- package/examples/packages/shop-tax-1/lawspec-package.json +0 -5
- package/examples/packages/shop-tax-2/lawspec-package.json +0 -5
- package/explain.mjs +0 -114
- package/expression-presentation.mjs +0 -333
- package/positional-fields.mjs +0 -13
- package/typed-presentation.mjs +0 -165
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,410 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.31.0] - 2026-10-26
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- The installed npm package declares its own Go module boundary, so a host
|
|
14
|
+
application's `go test ./...` does not collect the bundled example adapters
|
|
15
|
+
before those examples have been generated.
|
|
16
|
+
- Rust groups block-like operands where its statement grammar requires it,
|
|
17
|
+
including comparisons between record fields lowered to `match` expressions.
|
|
18
|
+
- Persistent layout caches preserve shared document graphs when loading them,
|
|
19
|
+
avoiding the memory expansion caused by decoding each use as a separate
|
|
20
|
+
tree. Existing compiler cache entries are recomputed; generated code and
|
|
21
|
+
semantic identities are unchanged.
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
|
|
25
|
+
- Complete and bounded scoped searches share one typed candidate body and enumerate
|
|
26
|
+
their domain at runtime. Their ordered, three-outcome execution preserves
|
|
27
|
+
short-circuiting and incomplete results. Finite quantifier and witness proof
|
|
28
|
+
lowering likewise keeps candidate data and one scoped predicate instead of
|
|
29
|
+
copying the predicate per candidate. Source comments retain the original
|
|
30
|
+
checked proposition, independently of its execution plan.
|
|
31
|
+
- All 18 executable targets use compact finite test plans: ordered shared
|
|
32
|
+
prefixes, value lists and inclusive integer ranges, with one shared check
|
|
33
|
+
body per law. Cases retain stable indices, fresh attempt values, selection
|
|
34
|
+
and failure context. Native runners register cases individually where their
|
|
35
|
+
APIs support it; Rust uses runtime row loops with indexed failure reports.
|
|
36
|
+
In the handler-bindings suite, the JavaScript test file shrinks from 1,096,011
|
|
37
|
+
lines to 2,355 and Python from 1,127,192 to 2,535, preserving all 8,012 cases
|
|
38
|
+
and rejecting both adapter mutations. Haskell shrinks from 92,352 to 2,235
|
|
39
|
+
lines and Rust from 42,006 to 1,905. Generated test size is checked against
|
|
40
|
+
source-relative byte and line limits, including compact layouts.
|
|
41
|
+
- Prolog registers individual PLUnit cases from the Python host's collected
|
|
42
|
+
case metadata. Exact selection executes only the selected provider case;
|
|
43
|
+
unknown, duplicate and incomplete results cannot supply completed evidence.
|
|
44
|
+
Ordered Swift tests report individual starts and completions under a fresh
|
|
45
|
+
run identity, checked against the native Swift Testing aggregate result.
|
|
46
|
+
- **Content identity.** Every type, declaration, handler, ability and law
|
|
47
|
+
has a semantic hash of its checked structure and a presentation hash of its
|
|
48
|
+
names, docs and spans ([Content identity](docs/explanation/content-identity.md)).
|
|
49
|
+
Binders are positions, references are hashes, and mutually recursive groups
|
|
50
|
+
are hashed together. Identity is structural: equivalent calculations can
|
|
51
|
+
still have different hashes. Presentation-bearing plans and emitted chunks
|
|
52
|
+
retain both hashes; pure execution and proof results can survive renames,
|
|
53
|
+
line moves and doc edits when their other inputs remain unchanged.
|
|
54
|
+
- `lawspec test` keys results on semantic identity, compiler build, target,
|
|
55
|
+
toolchain, adapters and execution settings, rather than generated file
|
|
56
|
+
bytes. Native interfaces and recorded comparisons also retain the public
|
|
57
|
+
names they can observe. A constructor rename that changes portable ordering
|
|
58
|
+
changes semantic identity. Changed presentation is validated before execution
|
|
59
|
+
reuse; mandatory definition validation remains independent of optional proofs.
|
|
60
|
+
- **Breaking in 0.31: proof tasks.** `programFingerprint` is replaced by a
|
|
61
|
+
per-law `lawFingerprint` over semantic dependencies, encoding, machine width
|
|
62
|
+
and proof settings. Receipts from public 0.30.0 and earlier must be recomputed.
|
|
63
|
+
The lawspec-smtlib-v1 byte freeze is replaced by semantic invariance checks;
|
|
64
|
+
this does not add a new proof backend or a kernel-checked certificate.
|
|
65
|
+
- **Breaking in 0.31: remote content hashes** are `blake3-semantic-1:` then
|
|
66
|
+
the semantic hash, replacing `sha3-256:`. A 0.31 node cannot exchange remote
|
|
67
|
+
definition identities with a 0.30 or earlier node. There is no pre-1.0
|
|
68
|
+
identity migration.
|
|
69
|
+
- Acceptance records exact generated-byte hits separately from semantic
|
|
70
|
+
execution hits. Reuse still requires matching compiler, toolchain, adapters,
|
|
71
|
+
mutants and execution context; changed presentation is formatted and
|
|
72
|
+
compiled/parsed before an earlier execution result is reused.
|
|
73
|
+
- BLAKE3 follows goforge's blake3sum design: unboxed words, an unrolled
|
|
74
|
+
compression function and a batch `hashMany`. It is 9.2 times faster on
|
|
75
|
+
20,000 48-byte inputs (97.5 ms to 10.6 ms) and 22 times faster on 4 MiB
|
|
76
|
+
(432 ms to 19 ms), and agrees with the official vectors and blake3sum.
|
|
77
|
+
|
|
78
|
+
- **Breaking: generated Python names.** Generated Python is written to be
|
|
79
|
+
read. Locals keep their source names, checked definitions are named after
|
|
80
|
+
the definition (`_definitions.fee_model`, `lawspec_typed.settings`, with
|
|
81
|
+
`_2` only on a clash) and typed helpers after their type (`to_settings`).
|
|
82
|
+
Tests are named after the law and the example
|
|
83
|
+
(`test_normalizers_agree__spaces_become_hyphens_punctuation_is_preserved`),
|
|
84
|
+
and boundaries are numbered from 1. Anonymous records have a name from
|
|
85
|
+
where they are used (`DeclinedDetails`) instead of `Record<digest>`.
|
|
86
|
+
Adapters and native code that use the old names must be renamed.
|
|
87
|
+
- Generated Python writes text and bytes as Python literals, names the
|
|
88
|
+
machine width (`MACHINE_BITS`) and the integers' draw limit once per
|
|
89
|
+
module, imports only what it uses, and makes a case's `symbols` only when
|
|
90
|
+
the case uses them. Each law's comment gives its name, source line, what it
|
|
91
|
+
says and the statement its tests check, with source names and real
|
|
92
|
+
characters; each test, definition and helper links to its source line.
|
|
93
|
+
Assertion messages name the law and example and point at the expectation's
|
|
94
|
+
line instead of repeating its text.
|
|
95
|
+
- Generated Python is laid out as `ruff format` (0.17.2, default settings)
|
|
96
|
+
lays it out, at 88 columns rather than PEP 8's 79, and the Python runtimes
|
|
97
|
+
are formatted the same way. Acceptance runs `ruff format --check` on every
|
|
98
|
+
generated Python project (the formatted step).
|
|
99
|
+
- **Breaking: generated JavaScript and TypeScript names.** Locals keep their
|
|
100
|
+
source names; checked definitions are named after the definition
|
|
101
|
+
(`_definitions.feeModel` instead of `_definitions.evaluate0`), typed
|
|
102
|
+
functions after the definition (`modelPeek` instead of
|
|
103
|
+
`Def_modelPeek_a0205a6d`), typed classes after their type (`Pair` instead
|
|
104
|
+
of `T_Pair`) and typed helpers after their kind and type
|
|
105
|
+
(`fromPairInt64Int64` instead of `from_<digest>`). Anonymous records have a
|
|
106
|
+
name from where they are used, and a data name that is still taken gets
|
|
107
|
+
`_2`. Adapters and native code that use the old names must be renamed.
|
|
108
|
+
- Generated JavaScript and TypeScript are laid out as Prettier (3.9.10,
|
|
109
|
+
default settings) lays them out, and the web runtimes and default handlers
|
|
110
|
+
are formatted the same way. LawSpec prints the code itself, from a syntax
|
|
111
|
+
tree, with a port of Prettier's printer; acceptance runs
|
|
112
|
+
`prettier --check` on every generated JavaScript and TypeScript project.
|
|
113
|
+
Text is written as string literals (never split mid-word), small integers
|
|
114
|
+
and booleans as literals, `MACHINE_BITS` is named once per module, modules
|
|
115
|
+
import only what they use, and each test, definition and class links to
|
|
116
|
+
its source line. Each law's comment gives its name, source line, what it
|
|
117
|
+
says and the statement its tests check. The assertion helpers, the seed
|
|
118
|
+
option and the data generators' scalar table are the runtime's
|
|
119
|
+
(`ls.check`, `ls.checkData`, `ls.seeded`, `primitiveGenerators`), so a
|
|
120
|
+
test module holds only its laws.
|
|
121
|
+
|
|
122
|
+
- **Breaking: artifact and Prolog names.** HCL variables are named after their
|
|
123
|
+
declarations (`settings`, and `type_settings` for a type-only variable)
|
|
124
|
+
instead of `value_<identity>_<digest>`; schema `$defs`, ANTLR rules and
|
|
125
|
+
manifest keys are named after their types (`settings`, `listText`,
|
|
126
|
+
`boxUint8`) instead of `t_<digest>`, in spec order; ANTLR entry rules are
|
|
127
|
+
`<type>Document`; manifest `types` are written as LawSpec writes them.
|
|
128
|
+
Prolog modules are named after their unit (`example_payments`,
|
|
129
|
+
`example_payments_model`) instead of `lawspec_<digest>`, PLUnit units after
|
|
130
|
+
their test file, and the bridge's Python functions after their definitions.
|
|
131
|
+
Adapters that name the old modules must be renamed.
|
|
132
|
+
- Artifacts are laid out to be read: YAML in block style (yamllint's
|
|
133
|
+
defaults), JSON indented as `json.dumps(indent=2)` writes it, HCL as
|
|
134
|
+
`tofu fmt` writes it with one validation block and message per restriction,
|
|
135
|
+
ANTLR rules in the grammars-v4 layout, and a generated-file header on the
|
|
136
|
+
Makefile. Prolog is printed as SWI-Prolog's `portray_clause/2` prints it, and
|
|
137
|
+
the Prolog runtime is reformatted the same way; the Prolog project's Python
|
|
138
|
+
host files and runtimes follow `ruff format`. Each entry, variable, rule and
|
|
139
|
+
predicate links to its source line. The artifact validator and Prolog
|
|
140
|
+
acceptance check these layouts (yamllint 1.37.1, OpenTofu 1.13.1, SWI-Prolog
|
|
141
|
+
10.0.2, ruff 0.17.2).
|
|
142
|
+
- **Breaking: generated Go names.** Generated Go is written to be read and
|
|
143
|
+
held to `gofmt`. Tests are named after the law and the example
|
|
144
|
+
(`TestNormalizersAgree_SpacesBecomeHyphensPunctuationIsPreserved`,
|
|
145
|
+
`_Boundary1` from 1, `_Property`), locals keep their source names, a
|
|
146
|
+
checked definition's evaluator is `lawSpecEvaluateFeeModel` and its typed
|
|
147
|
+
function `lsfFeeModel` (no digest suffix), typed helpers are named after
|
|
148
|
+
their type (`lsfToValueSettings`), and anonymous records are named from
|
|
149
|
+
where they are used (`PushDetails`) instead of `Record<digest>`; data names
|
|
150
|
+
that still meet take `_2`. Native code that uses the old names must be
|
|
151
|
+
renamed.
|
|
152
|
+
- Generated Go writes text as Go string literals and characters as rune
|
|
153
|
+
literals, links each test and law to its source line, names a failing
|
|
154
|
+
assertion's law and example and its expectation's line, shows text as text
|
|
155
|
+
in failures, and leaves out unused `symbols`, `_ = x` markers and wrapper
|
|
156
|
+
helpers. Every generated Go file, runtime copies included, starts with
|
|
157
|
+
`// Code generated by LawSpec. DO NOT EDIT.`. Acceptance runs the `gofmt`
|
|
158
|
+
of a pinned Go release (1.26.5, `test/locks/go/gofmt.txt`) in check mode on
|
|
159
|
+
every generated Go project, and the Go runtimes are formatted with it.
|
|
160
|
+
- **Breaking: generated F# and C# names.** Generated .NET code is written to
|
|
161
|
+
be read. Parameters, inputs and binders keep their source names, typed
|
|
162
|
+
definitions are named after the definition (`LawSpec.TypedProgram.settings`,
|
|
163
|
+
`Settings` in C#, with `_2` only on a clash), and each example's test is
|
|
164
|
+
named after its law and example
|
|
165
|
+
(`lawNormalizersAgree_spacesBecomeHyphensPunctuationIsPreserved`).
|
|
166
|
+
Anonymous records have a name from where they are used (`DeclinedDetails`)
|
|
167
|
+
instead of `Record<digest>`. Adapters and native code that use the old
|
|
168
|
+
names must be renamed.
|
|
169
|
+
- Generated F# and C# write text as string literals, link each test, law and
|
|
170
|
+
typed definition to its source line, and drop helpers that only forward
|
|
171
|
+
(a law's scoped case when it has no handlers, resources or policies).
|
|
172
|
+
Remote serving and evaluation, a typed operation's Result, a codec built
|
|
173
|
+
by an expression and a model's callbacks are runtime functions the
|
|
174
|
+
generated code calls (`Remote.serveDefinitions`, `Typed.tryResult`,
|
|
175
|
+
`Codec.toNative`, `Model.call1`).
|
|
176
|
+
- Generated F# is laid out as Fantomas (8.1.0, default settings) lays it
|
|
177
|
+
out, and the .NET runtime is formatted the same way; generated C# is what
|
|
178
|
+
`dotnet format` leaves unchanged. Acceptance runs `fantomas --check` and,
|
|
179
|
+
for C#, `dotnet format whitespace --verify-no-changes` on every generated
|
|
180
|
+
.NET project.
|
|
181
|
+
- **Breaking: generated Erlang, Elixir and Gleam names.** BEAM output is
|
|
182
|
+
written to be read. `lawspec_definitions` functions are named after their
|
|
183
|
+
definitions (`fee_model`, not `evaluate_3`), `lawspec_abilities` functions
|
|
184
|
+
after their abilities and handlers (`gateway_production`, not
|
|
185
|
+
`ability_0_production`), and `lawspec_typed` functions and conversions
|
|
186
|
+
after their definitions and types (`settings`, `from_dynamic_settings`),
|
|
187
|
+
with `_2` only on a clash; a specialised copy is named from its definition
|
|
188
|
+
and argument types. Binders keep their source names as Erlang variables.
|
|
189
|
+
Each law's cases are functions named after the law and the case
|
|
190
|
+
(`law_normalizers_agree__spaces_become_hyphens_punctuation_is_preserved`),
|
|
191
|
+
boundaries are numbered from 1, ExUnit tests are named for their cases,
|
|
192
|
+
and Gleeunit tests for the law and the case instead of `__case_N`.
|
|
193
|
+
Anonymous records have a name from where they are used (a payload of
|
|
194
|
+
`Declined` is the tag `declined_details`, the struct
|
|
195
|
+
`LawSpec.Data.DeclinedDetails` and the Gleam type `DeclinedDetails`)
|
|
196
|
+
instead of `Record<digest>`. Adapters and native code that use the old
|
|
197
|
+
names must be renamed.
|
|
198
|
+
- Generated BEAM code writes text as binaries (`<<"café"/utf8>>`) and
|
|
199
|
+
scalars through their runtime constructors instead of code-unit maps,
|
|
200
|
+
integer arithmetic and comparison as Erlang's operators and other
|
|
201
|
+
operations as named runtime functions (`lawspec_beam_scalar:add/4`), and
|
|
202
|
+
a let as `bind(Value, fun(X) -> ... end)`. A law's identity is a macro
|
|
203
|
+
written once, each law has the shared comment block, and every case,
|
|
204
|
+
definition and typed function links to its source line; test modules
|
|
205
|
+
name their specification in their header. ExUnit test modules name only
|
|
206
|
+
their laws (`law/4` in the new `LawSpec.Beam.ExUnitCases` test runtime).
|
|
207
|
+
- Generated Erlang is laid out as `erlfmt` 1.8.0 lays it out, Elixir as
|
|
208
|
+
`mix format` (Elixir 1.20.4) and Gleam as `gleam format` 1.19.0, each with
|
|
209
|
+
its default settings, and the BEAM runtimes are formatted the same way.
|
|
210
|
+
Acceptance runs each in check mode on every generated BEAM project (the
|
|
211
|
+
formatted step), pinned in `test/locks/beam-formatters.txt`.
|
|
212
|
+
- **Breaking: generated Haskell names.** Generated Haskell is written to be
|
|
213
|
+
read. Binders keep their source names, checked definitions are named after
|
|
214
|
+
the definition (`Definitions.feeModel`, `Typed.feeModel`, with `_2` only on
|
|
215
|
+
a clash), spec handlers after the handler (`fakeGatewayHandler`), typed
|
|
216
|
+
conversions after their type (`toPayment`, `fromNativeListInt32`), and
|
|
217
|
+
model and remote definitions take their arguments through `LS.uncurried`.
|
|
218
|
+
Tests are named after the law and the example
|
|
219
|
+
(`lawNormalizersAgree_spacesBecomeHyphensPunctuationIsPreserved`), and
|
|
220
|
+
boundaries are numbered from 1 (`_boundary1`). Anonymous records have a
|
|
221
|
+
name from where they are used (`PushDetails`) instead of `Record<digest>`.
|
|
222
|
+
Adapters and native code that use the old names must be renamed.
|
|
223
|
+
- Generated Haskell is printed by precedence, with no parentheses around
|
|
224
|
+
atoms, and laid out as `ormolu` (0.9.0.0) lays it out; the Haskell runtimes
|
|
225
|
+
and default handlers are formatted the same way. Acceptance runs
|
|
226
|
+
`ormolu --mode check` on every generated Haskell project (the formatted
|
|
227
|
+
step), remembering files it has passed by their content. Text is a Haskell
|
|
228
|
+
string literal (`LS.textScalar "café"`), never one code point per line.
|
|
229
|
+
- Generated Haskell tests hold only their laws: the assertion, the seeded
|
|
230
|
+
Hedgehog check (`LawSpecTesting.holds`), checked values
|
|
231
|
+
(`Schema.checked`, `Schema.literal`, `Schema.built`, `Schema.same`) and
|
|
232
|
+
adapter calls (`Codec.call1` to `call8`, `perform1` to `perform8`) are in
|
|
233
|
+
the runtime. A test module names its machine width, schema, scalar codecs
|
|
234
|
+
and the integers' draw limit once, imports only what it uses, and each
|
|
235
|
+
law's comment, test, definition and handler links to its source line.
|
|
236
|
+
- **Breaking: generated Swift names.** Generated Swift is written to be
|
|
237
|
+
read. A law's inputs, a definition's arguments and every binder keep their
|
|
238
|
+
source names; typed definitions are named after the definition
|
|
239
|
+
(`LawSpec.TypedProgram.settings`, a specialised copy `countListInt32`,
|
|
240
|
+
with `_2` only on a clash) instead of carrying a digest; specialised and
|
|
241
|
+
compiler-made entries lose their digests too. Tests are named after the law
|
|
242
|
+
and the example (`lawNormalizersAgree_spacesBecomeHyphensPunctuationIsPreserved`,
|
|
243
|
+
with readable `@Test` display names), and a law's statement is a helper
|
|
244
|
+
named after the law. Anonymous records have a name from where they are used
|
|
245
|
+
(`DeclinedDetails`), and acronyms in lowerCamelCase names are lowercased
|
|
246
|
+
whole (the case `usd`, not `uSD`). Adapters and native code that use the
|
|
247
|
+
old names must be renamed.
|
|
248
|
+
- Generated Swift writes text as Swift string literals, a long machine or
|
|
249
|
+
scenario spec as a multiline literal, and the crypto vectors as one
|
|
250
|
+
multiline literal. Each law's comment gives its name, source line, what it
|
|
251
|
+
says and the statement its tests check; each test, definition, data type,
|
|
252
|
+
typed function and spec handler links to its source line, and assertion
|
|
253
|
+
messages name the law and example and point at the expectation's line.
|
|
254
|
+
Files start with `Generated by LawSpec from <spec>. Do not edit.` and a
|
|
255
|
+
blank line, then sorted imports. Dead values (`_ = Value.bool(true)`) and
|
|
256
|
+
a law's case that only forwards to its statement are gone.
|
|
257
|
+
- Generated Swift is laid out as `swift-format` (6.3.0, from the Swift
|
|
258
|
+
toolchain, default configuration) lays it out: two-space indentation, 100
|
|
259
|
+
columns, one item a line when a call, array or signature does not fit,
|
|
260
|
+
trailing closures and grouped integer literals. The Swift runtime and the
|
|
261
|
+
`Package.swift` scaffold are formatted the same way. Acceptance formats a
|
|
262
|
+
copy of every generated Swift project with `swift format` and fails on any
|
|
263
|
+
difference (the formatted step).
|
|
264
|
+
|
|
265
|
+
- **Breaking: generated Rust names and tests.** Each Rust law is a module
|
|
266
|
+
named after it. Examples remain native `#[test]` functions, such as
|
|
267
|
+
`law_normalizers_agree::spaces_become_hyphens_punctuation_is_preserved`.
|
|
268
|
+
Boundary and exhaustive tests walk a compact cover at runtime, with stable
|
|
269
|
+
row indices and values in failures; generated cases use the `property` test.
|
|
270
|
+
`lawspec test` selects a law's tests by its module. Inputs and binders keep
|
|
271
|
+
their source names; checked definitions, typed functions and operation
|
|
272
|
+
bridges are named after what
|
|
273
|
+
they implement in snake case (`fee_model`, `count_list_int32`,
|
|
274
|
+
`perform_store_text_save`) instead of `evaluate_<n>` and digest suffixes;
|
|
275
|
+
anonymous records are named from where they are used (`DeclinedDetails`);
|
|
276
|
+
a handler from the context is typed by its binding. Adapters and native
|
|
277
|
+
code that use the old names must be renamed. Actors' handler methods are
|
|
278
|
+
snake case too (`withdraw_all`, `tell_withdraw_all`). The tests of one
|
|
279
|
+
generated file run one at a time (`ls::with_stack`), as a law's cases
|
|
280
|
+
share what they acquire; tests the harness orders run on `ls::on_stack`.
|
|
281
|
+
- Generated Rust writes text as Rust string literals, never split, links each
|
|
282
|
+
law, test, adapter call and definition to its source line, and gives each
|
|
283
|
+
law a comment with its name, what it says and the statement its tests
|
|
284
|
+
check. A failing expectation names its law, its example and its line, and
|
|
285
|
+
the runtime says how the values differ (`ls::expect_equal`, `ls::called`).
|
|
286
|
+
Seed and failure-database settings, handler locking, remote definitions,
|
|
287
|
+
served actor messages (`ls::net::message`), resource brackets
|
|
288
|
+
(`ls::bracket`) and session listening move into the runtimes. Generated Rust carries no
|
|
289
|
+
blanket `allow` attributes and builds without warnings.
|
|
290
|
+
- Generated Rust is laid out as `rustfmt` (1.97.1, edition 2024, default
|
|
291
|
+
settings) lays it out, by a Rust layout module that follows rustfmt's
|
|
292
|
+
rules for calls, chains, match arms and lets, and the Rust runtimes are
|
|
293
|
+
formatted the same way. Acceptance runs `rustfmt --check` on every
|
|
294
|
+
generated Rust project.
|
|
295
|
+
|
|
296
|
+
- **Breaking: generated JVM names.** Java, Kotlin, Scala and Groovy keep
|
|
297
|
+
the specification's names: locals keep their source names in camel case,
|
|
298
|
+
checked definitions and typed helpers are named after the definition
|
|
299
|
+
instead of `evaluateN`, tests after the law and the example
|
|
300
|
+
(`normalizersAgree_spacesBecomeHyphensPunctuationIs`), and anonymous
|
|
301
|
+
records after where they are used (`PushDetails`) instead of
|
|
302
|
+
`Record<digest>`. Adapters and native code that use the old names must be
|
|
303
|
+
renamed.
|
|
304
|
+
- Generated Java uses Allman braces with Google Java Style's other rules;
|
|
305
|
+
Kotlin is laid out as ktfmt 0.64 (kotlinlang style) lays it out; Scala as
|
|
306
|
+
scalafmt 3.11.5 (default configuration) accepts it; Groovy specifications
|
|
307
|
+
use Allman braces and pass CodeNarc; Clojure is laid out as cljfmt lays it
|
|
308
|
+
out. Acceptance checks each with its formatter (the formatted step):
|
|
309
|
+
Checkstyle 14.3.0, ktfmt, scalafmt, CodeNarc 4.0.0 and cljfmt 0.16.6.
|
|
310
|
+
- JVM tests write text as the language's string literals, name the machine
|
|
311
|
+
width and schema once per file, and point each assertion at its source
|
|
312
|
+
line; each law's comment gives its name, source line and statement. The
|
|
313
|
+
Kotlin and Scala tests' scalar generators and checks moved into the
|
|
314
|
+
runtime (`LawSpecScalars`, `LawSpecTesting`), so a test file holds only its
|
|
315
|
+
laws. Groovy's Spock specifications are generated from the plan instead of
|
|
316
|
+
rewritten from the Java tests, and Clojure's tests show the law's
|
|
317
|
+
statement.
|
|
318
|
+
- JVM property draws are flat: each sub-draw of a harness strategy is a
|
|
319
|
+
named function defined before its use (`gridCandidate`, `rowsOption1`),
|
|
320
|
+
drawn through `LawSpecDraws.oneOf`, `frequency` and `suchThat` (Kotlin,
|
|
321
|
+
Scala) or named suppliers (Java), instead of one nested closure per step.
|
|
322
|
+
Lets leave constructor arguments, match scrutinees and (in Java) strict
|
|
323
|
+
argument lists, and Java builds a value with its fields last
|
|
324
|
+
(`SCHEMA.construct(type, tag, bits, symbols, fields...)`), so nested
|
|
325
|
+
values indent once per level.
|
|
326
|
+
- A Scala unit whose tests would exceed 20,000 lines gets a file per law
|
|
327
|
+
(`<Unit><Law>Law.scala`) beside its `<Unit>LawSpecTest` object, and a long
|
|
328
|
+
chain of one boolean operator is `LawSpecScala.anyOf`/`allOf`, which
|
|
329
|
+
scalafmt can lay out.
|
|
330
|
+
- Acceptance's formatted step reads `acceptance/<suite>/<target>/unformatted.txt`:
|
|
331
|
+
a generated file it lists (path, then the reason) is not checked, and the
|
|
332
|
+
step reports it. Keywords' Java stub uses it: its `_class` adapter, the
|
|
333
|
+
documented escape of a Java keyword, is not a name Checkstyle's Google
|
|
334
|
+
rules accept.
|
|
335
|
+
|
|
336
|
+
- Swift codecs, Java actor/mailbox/session layout, Groovy stubs and the
|
|
337
|
+
Clojure bridge consume structured documents and interface metadata instead
|
|
338
|
+
of re-reading generated source. Definition source links use source names,
|
|
339
|
+
and labelled-law display names no longer carry an internal quote marker.
|
|
340
|
+
- Scala calls constructors with no non-`Unit` arguments directly from Scala,
|
|
341
|
+
avoiding the unnecessary Java-to-provider-Scala edge in the asynchronous
|
|
342
|
+
binding fixture. Constructors with values retain the Java bridge where raw
|
|
343
|
+
generic casts are needed. Scala build failures capture commands, Bloop
|
|
344
|
+
configuration and class inventories before cleanup; this is not a general
|
|
345
|
+
Bloop race fix.
|
|
346
|
+
- Replace project and package JSON manifests with `lawspec.edn`. The component
|
|
347
|
+
and published contract identities are explicit; obsolete JSON is rejected.
|
|
348
|
+
- Native runtimes, editor discovery, examples and test tooling use the same
|
|
349
|
+
manifest. Optional verification still leaves definition validation mandatory.
|
|
350
|
+
|
|
351
|
+
### Added
|
|
352
|
+
|
|
353
|
+
- Shared foundations for readable output on every target: a naming service,
|
|
354
|
+
per-target string escaping tables, source links from Core origins, record
|
|
355
|
+
display names, and per-target layout profiles (brace style, indent, width,
|
|
356
|
+
trailing commas, blank lines, import order), with display widths and
|
|
357
|
+
printability from pinned Unicode 17.0.0 tables.
|
|
358
|
+
- `LawSpec.Code.Doc.flatReserve`: columns a flat layout keeps free without
|
|
359
|
+
printing anything, as swift-format keeps one for the trailing comma an
|
|
360
|
+
array gains when it breaks.
|
|
361
|
+
- **Breaking:** `lawspec explain` has three views: `--view eng` (plain
|
|
362
|
+
English, the default), `--view math` (mathematical notation) and `--view dev`
|
|
363
|
+
(LawSpec notation with types, examples and native conformance). The values
|
|
364
|
+
`developer`, `business`, `formal` and `evidence` are removed. Each one is an
|
|
365
|
+
error that names its replacement: `dev`, `eng`, `math`, or
|
|
366
|
+
`lawspec evidence <unit>::<law>`.
|
|
367
|
+
- `lawspec explain --json` prints the chosen view as records with `view`,
|
|
368
|
+
`law`, `name` and ordered `sections` of `lines`. The text output is derived
|
|
369
|
+
from them. Records no longer copy the typed assertion, inputs, examples or
|
|
370
|
+
evidence; `check --json` and `lawspec evidence --json` report those.
|
|
371
|
+
- The compiler words explanations. The new `explain` method is in the API,
|
|
372
|
+
with `ExplainRequest`, `ExplainResult` and `Explanation` types. The CLI calls
|
|
373
|
+
it, so CLI and API give the same text, and the native and WASM compilers
|
|
374
|
+
agree byte for byte.
|
|
375
|
+
- The dev view brackets terms only where LawSpec's precedence needs them, for
|
|
376
|
+
example `a > 0 and b implies f a = X`.
|
|
377
|
+
- Local, Git-tag/revision and SHA-256 HTTPS archive contract dependencies,
|
|
378
|
+
`lawspec.lock.edn`, fetch/update and locked/offline execution.
|
|
379
|
+
- Deterministic contract archives and the checked `lawspec/component` SDK and
|
|
380
|
+
`lawspec describe --json` descriptor for CALM consumers.
|
|
381
|
+
- Completed evidence can identify a component independently of its contracts,
|
|
382
|
+
retaining architecture, implementation and selected contract content digests.
|
|
383
|
+
|
|
384
|
+
## [0.30.0] - 2026-10-23
|
|
385
|
+
|
|
386
|
+
### Added
|
|
387
|
+
|
|
388
|
+
- Triple-double-quoted multiline text literals (`"""..."""`) support ordinary
|
|
389
|
+
quotes within their content and share existing text escapes. Literal
|
|
390
|
+
whitespace, newlines and Unicode are preserved without implicit indentation
|
|
391
|
+
removal. Parser recovery, formatting and editor highlighting recognize the
|
|
392
|
+
same delimiters.
|
|
393
|
+
|
|
394
|
+
### Changed
|
|
395
|
+
|
|
396
|
+
- Acknowledged law mismatches are called **known discrepancies**. Use
|
|
397
|
+
`known discrepancy "reason"` in harnesses, `knownDiscrepancy` in API fields,
|
|
398
|
+
and `known-discrepancy` in evidence and native observations. The prior
|
|
399
|
+
`known failing` vocabulary is replaced in this pre-1.0 interface.
|
|
400
|
+
- A known discrepancy assigns no fault to the specification or implementation;
|
|
401
|
+
human review determines whether either or both need correction. Unexpected
|
|
402
|
+
passing checks still fail the run and request review before removing the
|
|
403
|
+
annotation. Concrete execution failures and proof refutations retain their
|
|
404
|
+
meanings, and mandatory definition validation is unchanged.
|
|
405
|
+
|
|
406
|
+
### Fixed
|
|
407
|
+
|
|
408
|
+
- Current observation reports use neutral discrepancy wording for older stored
|
|
409
|
+
runs while preserving the archived receipt and its freshness status.
|
|
410
|
+
- Formatting preserves trailing whitespace on the opening line of a multiline
|
|
411
|
+
literal, retaining its exact text value across repeated formatting.
|
|
412
|
+
|
|
9
413
|
## [0.29.2] - 2026-10-22
|
|
10
414
|
|
|
11
415
|
### Fixed
|
|
@@ -1944,7 +2348,9 @@ A maintenance release. The language, generated code and API are unchanged from
|
|
|
1944
2348
|
machine-sized bindings reject an architecture mismatch. Rust adapters take
|
|
1945
2349
|
owned values.
|
|
1946
2350
|
|
|
1947
|
-
[Unreleased]: https://github.com/brain-fuel/lawspec/compare/v0.
|
|
2351
|
+
[Unreleased]: https://github.com/brain-fuel/lawspec/compare/v0.31.0...HEAD
|
|
2352
|
+
[0.31.0]: https://github.com/brain-fuel/lawspec/compare/v0.30.0...v0.31.0
|
|
2353
|
+
[0.30.0]: https://github.com/brain-fuel/lawspec/compare/v0.29.2...v0.30.0
|
|
1948
2354
|
[0.29.2]: https://github.com/brain-fuel/lawspec/compare/v0.29.1...v0.29.2
|
|
1949
2355
|
[0.29.1]: https://github.com/brain-fuel/lawspec/compare/v0.29.0...v0.29.1
|
|
1950
2356
|
[0.29.0]: https://github.com/brain-fuel/lawspec/compare/v0.28.0...v0.29.0
|
package/README.md
CHANGED
|
@@ -54,7 +54,7 @@ npx lawspec doctor
|
|
|
54
54
|
|
|
55
55
|
New projects start with `verification.layers: []`: intrinsic definition checks
|
|
56
56
|
run, and no law verification is selected. Set `verification.layers` to
|
|
57
|
-
`[
|
|
57
|
+
`[:property :examples]` in `lawspec.edn`, then run `npx lawspec generate`.
|
|
58
58
|
Implement `src/example/codec.mjs`, then run `npm test`:
|
|
59
59
|
|
|
60
60
|
```javascript
|
|
@@ -91,12 +91,18 @@ end law
|
|
|
91
91
|
end unit
|
|
92
92
|
```
|
|
93
93
|
|
|
94
|
-
`lawspec explain`
|
|
94
|
+
`lawspec explain` says what the law checks, in plain English:
|
|
95
95
|
|
|
96
96
|
```text
|
|
97
|
-
|
|
97
|
+
Law: round trip
|
|
98
|
+
applying {itoa} and then {atoi} recovers the original integer
|
|
99
|
+
For every x (an Int32):
|
|
100
|
+
The atoi for the itoa for this x must be this x.
|
|
98
101
|
```
|
|
99
102
|
|
|
103
|
+
`--view dev` shows the expanded property `atoi (itoa x) = x` with its
|
|
104
|
+
examples. `--view math` uses mathematical notation.
|
|
105
|
+
|
|
100
106
|
The generated tests check the example, signed 32-bit boundary cases and
|
|
101
107
|
randomized inputs against your `itoa` and `atoi`, on whichever targets you
|
|
102
108
|
configure.
|
package/api.mjs
CHANGED
|
@@ -7,6 +7,7 @@ export async function createCompiler() {
|
|
|
7
7
|
format: (input) => call({schemaVersion: 5, ...input, method: 'format'}),
|
|
8
8
|
check: (input) => call({schemaVersion: 5, ...input, method: 'check'}),
|
|
9
9
|
expand: (input) => call({schemaVersion: 5, ...input, method: 'expand'}),
|
|
10
|
+
explain: (input) => call({schemaVersion: 5, ...input, method: 'explain'}),
|
|
10
11
|
proofTasks: (input) =>
|
|
11
12
|
call({schemaVersion: 5, ...input, method: 'proofTasks'}),
|
|
12
13
|
planGeneration: (input) =>
|
package/beam-doctor.mjs
CHANGED
|
@@ -5,8 +5,8 @@ import path from "node:path";
|
|
|
5
5
|
|
|
6
6
|
// These are the same sources the compiler emits, including the NIF loader.
|
|
7
7
|
const runtime = {
|
|
8
|
-
"formatter": "# Observe ExUnit's real skip events; excluded tests are not reported as run.\n# ref:REQ-harness-units ref:DEC-native-property-frameworks\ndefmodule LawSpec.Beam.ExUnitFormatter do\n @moduledoc false\n use GenServer\n\n def init(_options), do: {:ok, :lawspec_beam_report.open()}\n\n def handle_cast({:test_finished, %{state: {:skipped, _}, tags: %{lawspec_skip: {law, reason}}}}
|
|
9
|
-
"native": "%% @doc The seed and vector bridge to the same OpenSSL ABI as OTP crypto.\n%% Build with escript lawspec_crypto_build.escript; ship the resulting priv/.\n%% ref:DEC-typed-core-boundary\n-module(lawspec_beam_crypto_native).\n-on_load(init/0).\n-export([expand/2, encapsulate_test/2, sign_context/5, verify_context/5]).\n\ninit() ->\n [{<<\"OpenSSL\">>, Version, _}] = crypto:info_lib(),\n BeamDir = filename:dirname(code:which(?MODULE)),\n %% Application layouts (Rebar, Mix, Gleam and releases) put ebin beside\n %% priv. The second path supports a standalone erlc output directory.\n Candidates = [filename:join([filename:dirname(BeamDir), \"priv\", \"lawspec_crypto_native\"]),\n filename:join([BeamDir, \"priv\", \"lawspec_crypto_native\"])],\n case [Path || Path <- Candidates, filelib:is_regular(Path ++ extension())] of\n [Library | _]
|
|
8
|
+
"formatter": "# Observe ExUnit's real skip events; excluded tests are not reported as run.\n# ref:REQ-harness-units ref:DEC-native-property-frameworks\ndefmodule LawSpec.Beam.ExUnitFormatter do\n @moduledoc false\n use GenServer\n\n def init(_options), do: {:ok, :lawspec_beam_report.open()}\n\n def handle_cast(\n {:test_finished, %{state: {:skipped, _}, tags: %{lawspec_skip: {law, reason}}}},\n state\n ) do\n :lawspec_beam_harness.skip(law, reason)\n {:noreply, state}\n end\n\n def handle_cast({:test_finished, %{state: {:excluded, _}}}, state), do: {:noreply, state}\n def handle_cast({:test_finished, %{state: {:skipped, _}}}, state), do: {:noreply, state}\n\n def handle_cast({:test_finished, test}, state) do\n :lawspec_beam_report.event(state, %{\n event: \"test\",\n name: Atom.to_string(test.name),\n classname: inspect(test.module),\n identity: Map.get(test.tags, :lawspec_identity, \"\"),\n status: if(test.state == nil, do: \"passed\", else: \"failed\"),\n time: (test.time || 0) / 1_000_000,\n failure:\n if(test.state == nil,\n do: \"\",\n else: inspect(test.state, limit: :infinity, printable_limit: :infinity)\n )\n })\n\n {:noreply, state}\n end\n\n def handle_cast({:suite_finished, _}, state) do\n :lawspec_beam_report.finish(state)\n {:noreply, state}\n end\n\n def handle_cast(_event, state), do: {:noreply, state}\nend\n",
|
|
9
|
+
"native": "%% @doc The seed and vector bridge to the same OpenSSL ABI as OTP crypto.\n%% Build with escript lawspec_crypto_build.escript; ship the resulting priv/.\n%% ref:DEC-typed-core-boundary\n-module(lawspec_beam_crypto_native).\n-on_load(init/0).\n-export([expand/2, encapsulate_test/2, sign_context/5, verify_context/5]).\n\ninit() ->\n [{<<\"OpenSSL\">>, Version, _}] = crypto:info_lib(),\n BeamDir = filename:dirname(code:which(?MODULE)),\n %% Application layouts (Rebar, Mix, Gleam and releases) put ebin beside\n %% priv. The second path supports a standalone erlc output directory.\n Candidates = [\n filename:join([filename:dirname(BeamDir), \"priv\", \"lawspec_crypto_native\"]),\n filename:join([BeamDir, \"priv\", \"lawspec_crypto_native\"])\n ],\n case [Path || Path <- Candidates, filelib:is_regular(Path ++ extension())] of\n [Library | _] ->\n erlang:load_nif(Library, Version bsr 28);\n [] ->\n {error,\n {load_failed,\n \"LawSpec crypto bridge is missing; run escript lawspec_crypto_build.escript before compiling and ship priv/ with the application\"}}\n end.\n\nextension() ->\n case os:type() of\n {win32, _} -> \".dll\";\n _ -> \".so\"\n end.\n\nexpand(_, _) -> erlang:nif_error(lawspec_crypto_native_not_loaded).\nencapsulate_test(_, _) -> erlang:nif_error(lawspec_crypto_native_not_loaded).\nsign_context(_, _, _, _, _) -> erlang:nif_error(lawspec_crypto_native_not_loaded).\nverify_context(_, _, _, _, _) -> erlang:nif_error(lawspec_crypto_native_not_loaded).\n",
|
|
10
10
|
"c": "/* OpenSSL operations not exposed by OTP 29's crypto API: compact key seeds,\n * signature contexts and deterministic known-answer tests. Ordinary random\n * encapsulation, signing, verification and AEAD use OTP directly.\n * ref:DEC-typed-core-boundary\n */\n#include <erl_nif.h>\n#include <openssl/crypto.h>\n#include <openssl/evp.h>\n#include <openssl/err.h>\n#include <openssl/params.h>\n#include <openssl/core_names.h>\n#include <string.h>\n\n#if OPENSSL_VERSION_NUMBER < 0x30500000L\n#error \"LawSpec crypto requires OpenSSL 3.5 or newer\"\n#endif\n#if !defined(LAWSPEC_OPENSSL_MAJOR) || OPENSSL_VERSION_MAJOR != LAWSPEC_OPENSSL_MAJOR\n#error \"Build LawSpec crypto with the same OpenSSL major version as Erlang/OTP\"\n#endif\n\ntypedef struct {\n const char *tag, *name;\n size_t seed, public_key, private_key, signature;\n} Algorithm;\n\nstatic const Algorithm algorithms[] = {\n {\"mlkem768\", \"ML-KEM-768\", 64, 1184, 2400, 0},\n {\"mldsa65\", \"ML-DSA-65\", 32, 1952, 4032, 3309},\n {\"slh_dsa_shake_128f\", \"SLH-DSA-SHAKE-128f\", 48, 32, 64, 17088}\n};\n\nstatic const Algorithm *algorithm(ErlNifEnv *env, ERL_NIF_TERM term) {\n char tag[32];\n size_t i;\n if (!enif_get_atom(env, term, tag, sizeof(tag), ERL_NIF_LATIN1)) return NULL;\n for (i = 0; i < sizeof(algorithms) / sizeof(algorithms[0]); ++i)\n if (!strcmp(tag, algorithms[i].tag)) return &algorithms[i];\n return NULL;\n}\n\n/* No key material or provider error strings enter diagnostics. OpenSSL's\n * per-thread error queue must not leak between jobs on a dirty scheduler. */\nstatic ERL_NIF_TERM failure(ErlNifEnv *env, const char *operation) {\n ERR_clear_error();\n return enif_raise_exception(env, enif_make_tuple2(env,\n enif_make_atom(env, \"lawspec_crypto_failure\"), enif_make_atom(env, operation)));\n}\n\nstatic EVP_PKEY *import_key(const Algorithm *alg, const char *parameter,\n const ErlNifBinary *bytes, int selection) {\n EVP_PKEY *key = NULL;\n EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_from_name(NULL, alg->name, NULL);\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(parameter, bytes->data, bytes->size),\n OSSL_PARAM_construct_end()\n };\n if (!ctx || EVP_PKEY_fromdata_init(ctx) <= 0\n || EVP_PKEY_fromdata(ctx, &key, selection, params) <= 0) {\n EVP_PKEY_free(key);\n key = NULL;\n }\n EVP_PKEY_CTX_free(ctx);\n return key;\n}\n\nstatic ERL_NIF_TERM expand(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {\n const Algorithm *alg;\n ErlNifBinary seed, pub = {0}, priv = {0};\n EVP_PKEY_CTX *ctx = NULL;\n EVP_PKEY *key = NULL;\n size_t written;\n int pub_allocated = 0, priv_allocated = 0, ok = 0;\n ERL_NIF_TERM result;\n if (argc != 2 || !(alg = algorithm(env, argv[0]))\n || !enif_inspect_binary(env, argv[1], &seed) || seed.size != alg->seed)\n return enif_make_badarg(env);\n ERR_clear_error();\n if (alg == &algorithms[2]) {\n /* SLH's seed parameter is used only for the NIST key-generation tests. */\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(\"seed\", seed.data, seed.size),\n OSSL_PARAM_construct_end()\n };\n ctx = EVP_PKEY_CTX_new_from_name(NULL, alg->name, NULL);\n if (!ctx || EVP_PKEY_keygen_init(ctx) <= 0\n || EVP_PKEY_CTX_set_params(ctx, params) <= 0\n || EVP_PKEY_generate(ctx, &key) <= 0) goto done;\n } else {\n key = import_key(alg, \"seed\", &seed, EVP_PKEY_KEYPAIR);\n if (!key) goto done;\n }\n if (!(pub_allocated = enif_alloc_binary(alg->public_key, &pub))\n || !(priv_allocated = enif_alloc_binary(alg->private_key, &priv))) goto done;\n if (!EVP_PKEY_get_octet_string_param(key, OSSL_PKEY_PARAM_PUB_KEY,\n pub.data, pub.size, &written) || written != pub.size\n || !EVP_PKEY_get_octet_string_param(key, OSSL_PKEY_PARAM_PRIV_KEY,\n priv.data, priv.size, &written) || written != priv.size) goto done;\n ok = 1;\ndone:\n EVP_PKEY_free(key);\n EVP_PKEY_CTX_free(ctx);\n if (ok) {\n result = enif_make_tuple2(env, enif_make_binary(env, &pub), enif_make_binary(env, &priv));\n ERR_clear_error();\n return result;\n }\n if (pub_allocated) enif_release_binary(&pub);\n if (priv_allocated) { OPENSSL_cleanse(priv.data, priv.size); enif_release_binary(&priv); }\n return failure(env, \"expand_seed\");\n}\n\n/* FIPS 203 deterministic encapsulation for known-answer tests only. */\nstatic ERL_NIF_TERM encapsulate_test(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {\n ErlNifBinary pub, randomness, ciphertext = {0}, secret = {0};\n EVP_PKEY *key = NULL;\n EVP_PKEY_CTX *ctx = NULL;\n size_t ciphertext_size = 1088, secret_size = 32;\n int ciphertext_allocated = 0, secret_allocated = 0, ok = 0;\n ERL_NIF_TERM result;\n if (argc != 2 || !enif_inspect_binary(env, argv[0], &pub) || pub.size != 1184\n || !enif_inspect_binary(env, argv[1], &randomness) || randomness.size != 32)\n return enif_make_badarg(env);\n ERR_clear_error();\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(OSSL_KEM_PARAM_IKME, randomness.data, randomness.size),\n OSSL_PARAM_construct_end()\n };\n key = import_key(&algorithms[0], OSSL_PKEY_PARAM_PUB_KEY, &pub, EVP_PKEY_PUBLIC_KEY);\n if (!key || !(ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL))\n || EVP_PKEY_encapsulate_init(ctx, params) <= 0) goto done;\n if (!(ciphertext_allocated = enif_alloc_binary(ciphertext_size, &ciphertext))\n || !(secret_allocated = enif_alloc_binary(secret_size, &secret))) goto done;\n if (EVP_PKEY_encapsulate(ctx, ciphertext.data, &ciphertext_size, secret.data, &secret_size) <= 0\n || ciphertext_size != ciphertext.size || secret_size != secret.size) goto done;\n ok = 1;\ndone:\n EVP_PKEY_CTX_free(ctx);\n EVP_PKEY_free(key);\n if (ok) {\n result = enif_make_tuple2(env, enif_make_binary(env, &ciphertext), enif_make_binary(env, &secret));\n ERR_clear_error();\n return result;\n }\n if (ciphertext_allocated) enif_release_binary(&ciphertext);\n if (secret_allocated) { OPENSSL_cleanse(secret.data, secret.size); enif_release_binary(&secret); }\n return failure(env, \"encapsulate_test\");\n}\n\nstatic ERL_NIF_TERM sign_context(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {\n const Algorithm *alg;\n ErlNifBinary secret, message, context, signature = {0};\n EVP_PKEY *key = NULL;\n EVP_PKEY_CTX *ctx = NULL;\n EVP_SIGNATURE *scheme = NULL;\n int deterministic, allocated = 0, ok = 0;\n size_t length;\n ERL_NIF_TERM result;\n if (argc != 5 || !(alg = algorithm(env, argv[0])) || !alg->signature\n || !enif_inspect_binary(env, argv[1], &secret)\n || secret.size != (alg == &algorithms[1] ? alg->seed : alg->private_key)\n || !enif_inspect_binary(env, argv[2], &message)\n || !enif_inspect_binary(env, argv[3], &context) || context.size > 255)\n return enif_make_badarg(env);\n if (enif_is_identical(argv[4], enif_make_atom(env, \"true\"))) deterministic = 1;\n else if (enif_is_identical(argv[4], enif_make_atom(env, \"false\"))) deterministic = 0;\n else return enif_make_badarg(env);\n ERR_clear_error();\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, context.data, context.size),\n OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_DETERMINISTIC, &deterministic),\n OSSL_PARAM_construct_end()\n };\n key = import_key(alg, alg == &algorithms[1] ? \"seed\" : OSSL_PKEY_PARAM_PRIV_KEY,\n &secret, EVP_PKEY_KEYPAIR);\n if (!key || !(ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL))\n || !(scheme = EVP_SIGNATURE_fetch(NULL, alg->name, NULL))\n || EVP_PKEY_sign_message_init(ctx, scheme, params) <= 0) goto done;\n length = alg->signature;\n if (!(allocated = enif_alloc_binary(length, &signature))) goto done;\n if (EVP_PKEY_sign(ctx, signature.data, &length, message.data, message.size) <= 0\n || length != signature.size) goto done;\n ok = 1;\ndone:\n EVP_SIGNATURE_free(scheme);\n EVP_PKEY_CTX_free(ctx);\n EVP_PKEY_free(key);\n if (ok) {\n result = enif_make_binary(env, &signature);\n ERR_clear_error();\n return result;\n }\n if (allocated) enif_release_binary(&signature);\n return failure(env, \"sign_context\");\n}\n\nstatic ERL_NIF_TERM verify_context(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {\n const Algorithm *alg;\n ErlNifBinary pub, message, signature, context;\n EVP_PKEY *key = NULL;\n EVP_PKEY_CTX *ctx = NULL;\n EVP_SIGNATURE *scheme = NULL;\n int verified = -1;\n if (argc != 5 || !(alg = algorithm(env, argv[0])) || !alg->signature\n || !enif_inspect_binary(env, argv[1], &pub)\n || !enif_inspect_binary(env, argv[2], &message)\n || !enif_inspect_binary(env, argv[3], &signature)\n || !enif_inspect_binary(env, argv[4], &context)) return enif_make_badarg(env);\n if (pub.size != alg->public_key || signature.size != alg->signature || context.size > 255)\n return enif_make_atom(env, \"false\");\n ERR_clear_error();\n OSSL_PARAM params[] = {\n OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, context.data, context.size),\n OSSL_PARAM_construct_end()\n };\n key = import_key(alg, OSSL_PKEY_PARAM_PUB_KEY, &pub, EVP_PKEY_PUBLIC_KEY);\n if (!key || !(ctx = EVP_PKEY_CTX_new_from_pkey(NULL, key, NULL))\n || !(scheme = EVP_SIGNATURE_fetch(NULL, alg->name, NULL))\n || EVP_PKEY_verify_message_init(ctx, scheme, params) <= 0) goto done;\n verified = EVP_PKEY_verify(ctx, signature.data, signature.size, message.data, message.size);\ndone:\n EVP_SIGNATURE_free(scheme);\n EVP_PKEY_CTX_free(ctx);\n EVP_PKEY_free(key);\n if (verified < 0) return failure(env, \"verify_context\");\n ERR_clear_error();\n return enif_make_atom(env, verified == 1 ? \"true\" : \"false\");\n}\n\nstatic int load(ErlNifEnv *env, void **private_data, ERL_NIF_TERM info) {\n unsigned int expected;\n (void)private_data;\n return !enif_get_uint(env, info, &expected) || expected != OPENSSL_VERSION_MAJOR\n || OPENSSL_version_major() != expected || OpenSSL_version_num() < 0x30500000L;\n}\n\n/* Cover restores the original Erlang module after instrumentation. The\n * bridge holds no private state or resource types across calls, so each\n * module instance can use the same library after the ordinary ABI check. */\nstatic int upgrade(ErlNifEnv *env, void **private_data, void **old_private_data, ERL_NIF_TERM info) {\n (void)old_private_data;\n return load(env, private_data, info);\n}\n\nstatic ErlNifFunc functions[] = {\n {\"expand\", 2, expand, ERL_NIF_DIRTY_JOB_CPU_BOUND},\n {\"encapsulate_test\", 2, encapsulate_test, ERL_NIF_DIRTY_JOB_CPU_BOUND},\n {\"sign_context\", 5, sign_context, ERL_NIF_DIRTY_JOB_CPU_BOUND},\n {\"verify_context\", 5, verify_context, ERL_NIF_DIRTY_JOB_CPU_BOUND}\n};\nERL_NIF_INIT(lawspec_beam_crypto_native, functions, load, NULL, upgrade, NULL)\n",
|
|
11
11
|
"build": "#!/usr/bin/env escript\n%%! -noshell\n%% Build once before Rebar/Mix/Gleam compilation; no compiler runs at application\n%% startup. CC names one executable. LAWSPEC_OPENSSL_PREFIX selects a development\n%% installation matching OTP's OpenSSL major version (3.5+).\n%% ref:DEC-typed-core-boundary\n-mode(compile).\n\nmain(Arguments) ->\n try\n Project = case Arguments of\n [] -> filename:dirname(filename:absname(escript:script_name()));\n [Directory] -> filename:absname(Directory);\n _ -> fail(\"usage: escript lawspec_crypto_build.escript [project-directory]\")\n end,\n build(Project)\n catch\n throw:{build_error, Message} -> io:format(standard_error, \"LawSpec crypto: ~ts~n\", [Message]), halt(1);\n error:Reason -> io:format(standard_error, \"LawSpec crypto build failed: ~tp~n\", [Reason]), halt(1)\n end.\n\nbuild(Project) ->\n case list_to_integer(erlang:system_info(otp_release)) >= 29 of\n true -> ok;\n false -> fail(\"Erlang/OTP 29 or newer is required\")\n end,\n [{<<\"OpenSSL\">>, Version, Description}] = crypto:info_lib(),\n Major = Version bsr 28,\n MissingAlgorithms = lists:append([Expected -- crypto:supports(Kind) || {Kind, Expected} <-\n [{kems, [mlkem768]}, {public_keys, [mldsa65, slh_dsa_shake_128f]},\n {hashs, [sha3_256, shake256]}, {ciphers, [aes_256_gcm]}]]),\n case MissingAlgorithms of\n [] -> ok;\n Missing -> fail(io_lib:format(\"OTP crypto lacks ~tp; install OTP with OpenSSL 3.5+\", [Missing]))\n end,\n Compiler = executable(env(\"CC\", \"cc\")),\n {Include, Library, ProviderVersion} = openssl(Major),\n OtpInclude = filename:join([code:root_dir(), \"usr\", \"include\"]),\n Source = filename:join([Project, \"priv\", \"lawspec_crypto_native.c\"]),\n Output = filename:join([Project, \"priv\", \"lawspec_crypto_native.so\"]),\n Stamp = Output ++ \".build\",\n SourceBytes = read(Source),\n Args = [\"-std=c11\", \"-O2\", \"-Wall\", \"-Wextra\", \"-Werror\", \"-fPIC\", \"-shared\"] ++\n platform_flags() ++ [\"-DLAWSPEC_OPENSSL_MAJOR=\" ++ integer_to_list(Major),\n \"-I\" ++ OtpInclude, \"-I\" ++ Include, Source, \"-L\" ++ Library,\n \"-Xlinker\", \"-rpath\", \"-Xlinker\", Library, \"-lcrypto\"],\n Fingerprint = crypto:hash(sha3_256, term_to_binary({SourceBytes,\n read(escript:script_name()), read(filename:join(Include, \"openssl/opensslv.h\")),\n read(filename:join(OtpInclude, \"erl_nif.h\")),\n erlang:system_info(system_architecture), erlang:system_info(nif_version),\n Version, Description, ProviderVersion, Compiler, Args})),\n case current(Stamp, Output, Fingerprint) of\n true -> ok;\n false ->\n %% A failed or concurrent build cannot replace a working library.\n Temporary = Output ++ \".\" ++ os:getpid() ++ \".tmp\",\n try\n checked(Compiler, Args ++ [\"-o\", Temporary]),\n ok = file:rename(Temporary, Output),\n ok = file:write_file(Stamp, term_to_binary({Fingerprint, crypto:hash(sha3_256, read(Output))})),\n io:format(\"Built LawSpec crypto bridge (~ts).~n\", [Description])\n after\n file:delete(Temporary)\n end\n end.\n\nplatform_flags() ->\n case os:type() of\n {unix, darwin} -> [\"-undefined\", \"dynamic_lookup\"];\n {unix, _} -> [];\n _ -> fail(\"the crypto bridge build requires a Unix C toolchain; use WSL on Windows\")\n end.\n\nopenssl(Major) ->\n case os:getenv(\"LAWSPEC_OPENSSL_PREFIX\") of\n false -> discover_openssl(Major);\n Prefix -> prefix(Prefix, \"explicit prefix\")\n end.\n\ndiscover_openssl(Major) ->\n case os:find_executable(\"pkg-config\") of\n false -> homebrew_openssl(Major);\n Pkg ->\n case run(Pkg, [\"--modversion\", \"libcrypto\"]) of\n {0, Text} ->\n Version = string:trim(binary_to_list(Text)),\n case string:prefix(Version, integer_to_list(Major) ++ \".\") of\n nomatch -> homebrew_openssl(Major);\n _ -> {query(Pkg, [\"--variable=includedir\", \"libcrypto\"]),\n query(Pkg, [\"--variable=libdir\", \"libcrypto\"]), Version}\n end;\n _ -> homebrew_openssl(Major)\n end\n end.\n\nhomebrew_openssl(Major) ->\n case os:find_executable(\"brew\") of\n false -> missing_openssl(Major);\n Brew ->\n case run(Brew, [\"--prefix\", \"openssl@\" ++ integer_to_list(Major)]) of\n {0, Text} -> prefix(string:trim(binary_to_list(Text)), \"Homebrew\");\n _ -> missing_openssl(Major)\n end\n end.\n\nprefix(Prefix, Origin) ->\n Absolute = filename:absname(Prefix),\n Include = filename:join(Absolute, \"include\"),\n case filelib:is_regular(filename:join(Include, \"openssl/evp.h\")) of\n true ->\n Libraries = [filename:join(Absolute, Subdir) || Subdir <- [\"lib\", \"lib64\"],\n lists:any(fun(Name) -> filelib:is_regular(filename:join([Absolute, Subdir, Name])) end,\n [\"libcrypto.so\", \"libcrypto.dylib\"])],\n case Libraries of\n [Library | _] -> {Include, Library, Origin};\n [] -> fail(\"OpenSSL shared library missing under \" ++ Absolute)\n end;\n false -> fail(\"OpenSSL headers missing under \" ++ Absolute)\n end.\n\nmissing_openssl(Major) -> fail(io_lib:format(\n \"install pkg-config and OpenSSL ~B development headers/libraries (3.5+), or set LAWSPEC_OPENSSL_PREFIX to that installation\", [Major])).\n\ncurrent(Stamp, Output, Fingerprint) ->\n case {file:read_file(Stamp), file:read_file(Output)} of\n {{ok, StampBytes}, {ok, OutputBytes}} ->\n try binary_to_term(StampBytes, [safe]) =:= {Fingerprint, crypto:hash(sha3_256, OutputBytes)}\n catch error:badarg -> false end;\n _ -> false\n end.\n\nenv(Key, Default) -> case os:getenv(Key) of false -> Default; Value -> Value end.\nexecutable(Name) -> case os:find_executable(Name) of\n false -> fail(\"executable not found: \" ++ Name ++ \" (CC must name one compiler executable)\");\n Path -> Path\nend.\n\nread(Path) -> case file:read_file(Path) of\n {ok, Bytes} -> Bytes;\n {error, Reason} -> fail(io_lib:format(\"cannot read ~ts: ~tp\", [Path, Reason]))\nend.\n\nquery(Command, Args) -> string:trim(binary_to_list(checked(Command, Args))).\nchecked(Command, Args) -> case run(Command, Args) of\n {0, Output} -> Output;\n {Status, Output} -> fail(io_lib:format(\"~ts exited ~B:~n~ts\", [Command, Status, Output]))\nend.\n\n%% Argument arrays, never a shell: project and installation paths may contain\n%% spaces, quotes, dollar signs or other shell metacharacters.\nrun(Command, Args) ->\n Port = open_port({spawn_executable, Command}, [binary, exit_status, use_stdio, stderr_to_stdout, {args, Args}]),\n collect(Port, []).\n\ncollect(Port, Parts) ->\n receive\n {Port, {data, Bytes}} -> collect(Port, [Bytes | Parts]);\n {Port, {exit_status, Status}} -> {Status, iolist_to_binary(lists:reverse(Parts))}\n end.\n\nfail(Message) -> throw({build_error, lists:flatten(Message)}).\n"
|
|
12
12
|
};
|