lawspec 0.15.0 → 0.15.2

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/README.md CHANGED
@@ -2,142 +2,52 @@
2
2
 
3
3
  **State the law once. Check it everywhere.**
4
4
 
5
- LawSpec 0.13 compiles reusable laws into native property tests, executable examples,
6
- and implementation adapters. The compiler is Haskell, distributed as prebuilt
7
- WebAssembly with a Node CLI and an asynchronous, typed JavaScript API.
8
-
9
- ## Structural data and total definitions in 0.9.0
10
-
11
- LawSpec 0.9 adds `List`, algebraic `Maybe` and `Either`, named
12
- parameterized products and sums, and checked total definitions on all eight
13
- backends. See the [language reference](LANGUAGE.md),
14
- [collections](examples/specs/collections.lawspec),
15
- [data types](examples/specs/data_types.lawspec), and
16
- [total functions](examples/specs/total_functions.lawspec).
17
-
18
- Generated code is readable by default; `--minify` explicitly selects compact
19
- output. Python follows PEP 8. See the [0.9 release notes](RELEASE-0.9.md)
20
- and [API migration guide](API-MIGRATION.md).
21
-
22
- ## Rust and the typed front end in 0.8.0
23
-
24
- Rust joins Java, Python, JavaScript, TypeScript, Go, Haskell, and Kotlin. All
25
- eight backends consume the same typed core and testing plan. Source expressions
26
- retain their ranges, resolved identities, arithmetic evidence, and checked
27
- conversions. See the [Rust guide](RUST.md) and [language reference](LANGUAGE.md).
28
-
29
- The scalar catalog includes fixed and arbitrary integers, exact decimals and rationals,
30
- IEEE floats and complex values, Unicode and raw-text domains, bytes, symbols,
31
- and nested absence states on all eight targets. Integer arithmetic produces representation-independent
32
- `Integer` values; exact division returns Rational. See the [primitive reference](PRIMITIVES.md)
33
- for constructors, arithmetic, native bridges, and machine-width profiles.
34
-
35
- Compiler API consumers should read the [schema v3 migration guide](API-MIGRATION.md).
36
- Scalar values use tagged, lossless encodings; generated runtime placement is
37
- separate from artifact ownership. Java 25+ and Python 3.13+ baselines are unchanged.
38
-
39
- ## Native domain bindings in 0.10
40
-
41
- LawSpec 0.10 adds configuration for existing application products and sums,
42
- function bindings, checked conversion hooks, and native property-generator
43
- factories on all eight targets. Generators retain their framework's shrinkers;
44
- explicit examples, boundaries, and finite-domain checks remain independent.
45
- See the [native-binding reference and acceptance status](NATIVE-BINDINGS.md),
46
- the [release notes](RELEASE-0.10.md), and
47
- [schema 4 migration notes](API-MIGRATION.md#schema-4-native-bindings).
48
- Existing specifications without bindings retain their behavior.
49
-
50
- ## Natural-indexed families in 0.11
51
-
52
- LawSpec 0.11 adds data indexed by natural numbers, such as length-indexed
53
- vectors and size-indexed trees. Each constructor states its index equation;
54
- the compiler elaborates the family to ordinary native data, a checked measure,
55
- and a refinement. Dependent signatures like
56
- `append :: (xs :: Vec n a) -> (ys :: Vec m a) -> (r :: Vec (n + m) a)` become
57
- checked adapter contracts, and generators construct values with a required
58
- index instead of filtering for it. See the
59
- [language reference](LANGUAGE.md#natural-indexed-families), the
60
- [indexed example](examples/specs/indexed_families.lawspec), and the
61
- [release notes](RELEASE-0.11.md).
62
-
63
- ## Proved indices and evidence in 0.12
64
-
65
- LawSpec 0.12 proves the result indices of checked definitions statically, so a
66
- definition such as `concatV :: Vec n Int8 -> Vec m Int8 -> Vec (n + m) Int8`
67
- needs no runtime postcondition. Every contract obligation is reported as
68
- `proved` or `runtime-checked` by `lawspec check` and the API. See
69
- [proved indices](LANGUAGE.md#proved-indices-and-evidence) and the
70
- [release notes](RELEASE-0.12.md).
71
-
72
- ## Domain modeling in 0.13
73
-
74
- LawSpec 0.13 adds `wrapper` declarations for constrained primitives, such as a
75
- `UnitQuantity` that cannot hold 0, and `workflow` declarations for typed
76
- pipelines between domain states, with a generated law that the workflow is the
77
- railway composition of its steps. See
78
- [domain modeling](LANGUAGE.md#domain-modeling), the
79
- [example](examples/specs/domain_modeling.lawspec) and the
80
- [release notes](RELEASE-0.13.md).
81
-
82
- ## Imports and packages in 0.14
83
-
84
- LawSpec 0.14 lets units import each other and groups units into versioned
85
- packages. ``import shop.domain as domain (Money, `commutative`)`` brings in
86
- another unit's types, refinements, checked definitions and generic laws, qualified
87
- or by name. Names are scoped to their unit, so two units may both declare a
88
- `Currency`. A package is a directory with a `lawspec-package.json`; a project
89
- names the packages it depends on with semantic-version ranges, and implements
90
- and tests the adapters of the contracts they publish. See
91
- [imports and packages](LANGUAGE.md#imports-and-packages), the
92
- [package example](examples/packages) and the [release notes](RELEASE-0.14.md).
93
-
94
- ## Evidence and discharge in 0.15
95
-
96
- Every obligation now reports how it is discharged: `PROVED`, `EXHAUSTIVELY
97
- CHECKED`, `PROPERTY TESTED`, `RUNTIME CHECKED` or `ASSUMED / EXTERNAL`. Laws over
98
- checked definitions are proved by the compiler's linear-arithmetic prover or,
99
- on finite domains, evaluated for every input, and a false one is a compile
100
- error. Laws over adapters are exhaustively or property tested by the generated
101
- tests, and adapters, native functions and custom generators are listed as taken
102
- on trust. `lawspec evidence` shows each obligation and why. See
103
- [evidence and discharge](LANGUAGE.md#evidence-and-discharge) and the
104
- [release notes](RELEASE-0.15.md).
105
-
106
- ## Install and try it
107
-
108
- LawSpec has its own [syntax-highlighting grammar and VS Code extension](editors/vscode/README.md)
109
- for keywords, types, refinements, literals, and law names. GitHub needs upstream Linguist
110
- support to use it; GitHub currently uses the Haskell fallback.
111
-
112
- Install [LawSpec from npm](https://www.npmjs.com/package/lawspec):
5
+ LawSpec is a specification language for the laws your code must obey. It
6
+ compiles reusable laws and concrete examples into native property-based tests
7
+ and implementation adapters for Java, Python, JavaScript, TypeScript, Go,
8
+ Haskell, Kotlin and Rust. The compiler is written in Haskell and distributed on
9
+ npm as prebuilt WebAssembly, with a Node CLI and a typed JavaScript API.
10
+
11
+ ## Features
12
+
13
+ - **Reusable laws.** A prelude of [round-trip, equivalence and algebraic laws](docs/reference/prelude-algebra.md), and your own generic laws.
14
+ - **Examples with expected results** that [pin each law down](docs/reference/language/laws-and-examples.md).
15
+ - **Native tests** with each target's framework, generators and shrinkers: JetCheck, Hypothesis, fast-check, Rapid, Hedgehog, Kotest and Proptest.
16
+ - **A full scalar catalog** with [exact arithmetic](docs/reference/primitives.md) that never wraps.
17
+ - **Structural data**: [lists, `Maybe`, `Either`, products and sums](docs/reference/language/types-and-data.md).
18
+ - **Refinements and contracts** with [dependent generation](docs/reference/refinements.md) that constructs valid inputs.
19
+ - **Checked total definitions** that are [proved and generated](docs/reference/language/definitions.md) on every target.
20
+ - **Indexed families** such as [length-indexed vectors](docs/reference/language/indexed-families.md), with proved indices.
21
+ - **Domain modeling** with [wrappers and workflows](docs/reference/language/domain-modeling.md).
22
+ - **Imports and versioned packages** of [shared laws and types](docs/reference/language/imports-and-packages.md).
23
+ - **Evidence** for every obligation: [proved, exhaustively checked, property tested, runtime checked or assumed](docs/reference/language/evidence-and-discharge.md).
24
+ - **Native bindings** to [your existing domain types and generators](docs/how-to/bind-native-types.md).
25
+ - **Safe regeneration**: [your adapters and build files stay yours](docs/explanation/ownership-and-regeneration.md).
26
+
27
+ ## Install
28
+
29
+ Node 22+ and the selected target's build tools are required. No Haskell
30
+ toolchain is needed. The reference platforms are macOS and Linux.
113
31
 
114
32
  ```sh
115
- npm install --save-dev lawspec@0.15.0
33
+ npm install --save-dev lawspec@0.15.2
116
34
  npx lawspec --version
117
35
  ```
118
36
 
119
- Node 22+ and the selected target's build tools are required. No Haskell toolchain
120
- is needed to install or run LawSpec. The reference platforms are macOS and Linux.
121
- Use `npx lawspec` to run the locally installed CLI.
122
-
123
- To try it in a **new, empty directory**, initialize the starter before installing
124
- local dependencies so LawSpec can create its `package.json` and test script:
37
+ To try it in a **new, empty directory**, initialize before installing, so that
38
+ LawSpec can create `package.json` and its test script:
125
39
 
126
40
  ```sh
127
41
  mkdir lawspec-example
128
42
  cd lawspec-example
129
- npm exec --package=lawspec@0.15.0 -- lawspec init --target javascript
130
- npm install --save-dev lawspec@0.15.0
43
+ npm exec --package=lawspec@0.15.2 -- lawspec init --target javascript
44
+ npm install --save-dev lawspec@0.15.2
131
45
  npx lawspec check
132
46
  npx lawspec explain 'example.atoi_codec::itoa and then atoi yields a'
133
47
  npx lawspec doctor
134
48
  npx lawspec generate
135
49
  ```
136
50
 
137
- In an existing project, install LawSpec first, then run
138
- `npx lawspec init --target javascript`. Existing build files are preserved;
139
- apply the printed dependency and test-runner setup instructions before generation.
140
-
141
51
  Implement `src/example/atoi_codec.mjs`, then run `npm test`:
142
52
 
143
53
  ```javascript
@@ -145,96 +55,12 @@ export function itoa(value) { return String(value); }
145
55
  export function atoi(value) { return Number(value); }
146
56
  ```
147
57
 
148
- The starter adapters intentionally throw until implemented. Generated tests
149
- include the supplied examples, signed 32-bit boundary cases, and randomized
150
- properties with the selected framework's shrinking and failure reporting.
151
-
152
- ## Targets
153
-
154
- | Target | Build setup | Test libraries | Test command |
155
- | --- | --- | --- | --- |
156
- | `java` | Maven, JDK 25, release 25 | JetCheck 0.3.0, JUnit Jupiter 5.14.x | `mvn test` |
157
- | `python` | Python 3.13 or 3.14, pyproject | pytest 8.4.x, Hypothesis 6.135.26+ (6.x) | `python -m pytest` |
158
- | `javascript` | Node 22+, npm, ESM | fast-check 4.x, node:test | `npm test` |
159
- | `typescript` | Node 22+, npm, TypeScript 5.9.x, ESM | fast-check 4.x, node:test | `npm test` |
160
- | `go` | Go modules, Go 1.22–1.26 | Rapid 1.2.0, testing | `go test ./...` |
161
- | `haskell` | Stack, GHC 9.10, LTS 24.58 | Hspec 2.11, Hedgehog 1.5, hspec-hedgehog 0.3 | `stack test` |
162
- | `kotlin` | JDK/JVM 25, Gradle 9.1–9.3, Kotlin 2.3.21 | Kotest 5.9.1 | `gradle test` |
163
- | `rust` | Rust 1.85+, edition 2024, Cargo | Proptest 1.11.0 | `cargo test` |
164
-
165
- Java 25 and Python 3.13 are the minimum baselines. New JVM releases are admitted
166
- through compatibility profiles after testing; the current JVM profile certifies
167
- 25. Python templates declare `requires-python = ">=3.13"` and runtime checks
168
- currently recognize 3.13 and 3.14. Kotlin templates pin Gradle's supported build
169
- configuration to Kotlin 2.3.21 and target JVM 25.
170
-
171
- `npm/compatibility.json` records inclusive minimum/exclusive maximum dependency
172
- bounds. Unknown, prerelease, missing, and incompatible versions fail preflight.
173
- Build-tool probes inspect resolved dependencies, compiler settings, source roots,
174
- and runner configuration. Unverifiable custom filtering/configuration is rejected
175
- with setup instructions. Build tools may populate their normal caches while
176
- resolving dependencies; LawSpec does not run dependency installers during generation.
177
-
178
- ## Existing projects and configuration
179
-
180
- `init` creates `lawspec.json` and a starter specification. It creates build
181
- files only when no existing build setup is detected. Existing build files are
182
- preserved, and setup instructions describe the changes you need to make yourself.
183
-
184
- ```json
185
- {
186
- "version": 1,
187
- "sources": ["laws"],
188
- "targets": [
189
- {"language": "java", "root": "java"},
190
- {"language": "python", "root": "python", "python": ".venv/bin/python"},
191
- {"language": "haskell", "root": "haskell"}
192
- ]
193
- }
194
- ```
195
-
196
- Source entries are files or directories, relative to the configuration file.
197
- `dependencies` maps package names to version ranges, and `packages` lists the
198
- package directories to load (each with a `lawspec-package.json`); see
199
- [packages](LANGUAGE.md#packages).
200
- Directories are scanned for `.lawspec` files. Every target has its own project
201
- root. Use `init --target python --project python` to add a target; `--config`
202
- selects a different configuration file. Targets can override `sourceDir` and
203
- `testDir` with relative paths. Configure the native build to include those paths
204
- before generation. Go's source and test directories must be the same.
205
-
206
- Defaults are `src`/`test` for JS, TS and Haskell; `src`/`tests` for Python;
207
- `src/main/java`/`src/test/java` for Java; the corresponding Kotlin directories;
208
- and unit-based package directories at the Go project root. Python accepts a
209
- `python` interpreter override; Java accepts `maven`; Kotlin accepts `gradle` and
210
- otherwise uses a local `gradlew` or `gradle` on PATH.
211
-
212
- For Python, create and select a 3.13+ virtual environment and install the printed
213
- test dependencies. For Stack, run `stack build --test --no-run-tests` once before
214
- `doctor`; this resolves the snapshot and generates the Cabal description through
215
- Hpack. Doctor uses that existing description without rewriting it. Test discovery
216
- uses `test/Spec.hs` with `hspec-discover`.
217
-
218
- Commands:
219
-
220
- - `check`: parse, resolve, type-check and expand laws without target dependencies,
221
- and summarize how the obligations are discharged.
222
- - `evidence [unit | unit::declaration]`: list each obligation, its claim and how
223
- it is discharged, grouped by status.
224
- - `explain [unit::law]`: display expansions, example inputs, and expected results.
225
- - `doctor`: inspect selected native environments and print corrective instructions.
226
- - `generate`: check environments, validate every output, then write artifacts.
227
- - `generate --dry-run`: show proposed file operations without applying them.
228
- - `generate --check`: fail when generated files need updating, without writing.
229
- - `package [--project <directory>]`: check a package directory on its own and
230
- summarize its units, laws and data types.
231
-
232
- Use `--target <language>` to select a configured language, and `--json` for
233
- machine-readable check, explanation, doctor and generation output. Generation
234
- fails before writing if any selected target is incompatible or any output
235
- conflicts with file ownership.
58
+ In an existing project, install LawSpec first, then run
59
+ `npx lawspec init --target javascript`. Existing build files are preserved;
60
+ apply the printed setup instructions before generating. See
61
+ [Install LawSpec and create a project](docs/how-to/install-and-init.md).
236
62
 
237
- ## Language slice
63
+ ## Example
238
64
 
239
65
  ```lawspec
240
66
  unit example.atoi_codec
@@ -257,547 +83,40 @@ law `round trip` is
257
83
  end
258
84
  ```
259
85
 
260
- The implicit prelude defines `left inverse`, `round trip identity is preserved`,
261
- `equivalent`, and `idempotent`.
262
- A law may reference a local reusable law or a prelude law. The compiler performs
263
- capture-avoiding expansion and specializes types; it does not recognize codec
264
- function names specially. `explain` shows the final property:
86
+ `lawspec explain` shows the final property:
265
87
 
266
88
  ```text
267
89
  for all (x :: Int32) . atoi (itoa (x)) = x
268
90
  ```
269
91
 
270
- Reusable laws can declare typed unary function parameters and `requires Eq a`, numeric capabilities such as `requires Integer a`, and
271
- [parameterized refinements and executable contracts](REFINEMENTS.md).
272
- Definitions support law application, function application/composition, universal
273
- quantification, `implies`, Boolean predicates, scalar literals, and equality.
274
- Function signatures and quantified inputs support the [scalar catalog](PRIMITIVES.md)
275
- and [structural types](LANGUAGE.md), including mixed and multiple inputs.
276
- Generic variables are supported in reusable laws. Scalar and structural values
277
- can also be intermediate or compared results. Functions are synchronous and
278
- support curried signatures with any positive number of arguments. Text literals
279
- are double-quoted, with escapes such as `\"`, `\\`, `\n`, and `\t`; examples must
280
- bind each input to a concrete value of its declared type.
281
- Text values contain Unicode scalar values; surrogate code points are rejected.
92
+ The generated tests check the example, signed 32-bit boundary cases and
93
+ randomized inputs against your `itoa` and `atoi`, on whichever targets you
94
+ configure.
282
95
 
283
- Examples refer to the expanded input names, including names inherited from the
284
- prelude. Bind every input exactly once. Ambiguous names and out-of-range values
285
- are errors. Descriptions and rationales use `{function}` references; `{{` and `}}`
286
- produce literal braces. Law blocks use this order:
287
- definition, optional description, optional rationale, examples, optional references.
288
- `--` starts a line comment. Names that cannot be emitted portably are diagnosed.
289
-
290
- Collections beyond `List`, external law packages, cross-unit imports beyond the
291
- prelude, async functions and browser hosting remain outside the language.
292
- Direct existing-symbol bindings are part of LawSpec 0.10 described
293
- above; the published 0.9 release uses implementation adapters.
294
-
295
- ## Algebra and currying (0.6)
296
-
297
- Version 0.6 adds algebra laws, scalar law parameters, curried signatures,
298
- and conjunctions.
299
-
300
- ```lawspec
301
- unit example.addition
302
-
303
- add :: Int32 -> Int32 -> Int32
304
-
305
- law `addition commutes` is
306
- definition is
307
- `commutative` add
308
- end
309
-
310
- example `3 plus 5 and 5 plus 3 both produce 8` is
311
- x = 3
312
- y = 5
313
- expect add x y = 8
314
- expect add y x = 8
315
- end
316
- end
317
-
318
- law `zero is an identity on both sides` is
319
- definition is
320
- `identity` add 0
321
- end
322
-
323
- example `zero preserves 3 on either side` is
324
- x = 3
325
- expect add 0 x = 3
326
- expect add x 0 = 3
327
- end
328
- end
329
- ```
330
-
331
- Arrows associate to the right and application associates to the left:
332
- `f :: a -> b -> c` takes two arguments, and `f x y` means `(f x) y`.
333
- A partial application such as `add 1` can be passed to a reusable unary law;
334
- `sumFour 1 2` can be passed to a binary law. Partial applications also compose.
335
- The compiler specializes these expressions before emission. Java, Kotlin,
336
- Python, JavaScript, TypeScript and Go adapters take ordinary positional arguments
337
- (`add(x, y)`); Haskell adapters use native currying (`add x y`). Argument order
338
- and types are preserved, including mixtures of `Text`, `Bool` and `Int32`.
339
-
340
- Law parameters can also be scalar values: `(e :: a)` supplies an identity and
341
- `(zero :: a)` supplies an absorbing element. Pass literals directly, for example
342
- `left identity` with arguments `add 0`, or `absorbing element` with `multiply 0`.
343
- Functions declared by a unit take one or more scalar inputs and return a scalar;
344
- reusable laws accept these curried functions, their partial applications, and
345
- scalar parameters. Quantified test inputs remain scalar.
346
-
347
- The prelude defines the following laws. Every row has an executable example in
348
- [algebra.lawspec](https://github.com/brain-fuel/lawspec/blob/v0.15.0/examples/specs/algebra.lawspec), including both sides of every
349
- combined law. `f` and `g` are binary operations, `inverse` is unary, and `e` and
350
- `zero` are scalar parameters. All these laws require equality of the element type.
351
-
352
- | Law and arguments | Equations checked for every quantified input |
353
- | --- | --- |
354
- | `commutative f` | `f x y = f y x` |
355
- | `associative f` | `f (f x y) z = f x (f y z)` |
356
- | `left identity f e` | `f e x = x` |
357
- | `right identity f e` | `f x e = x` |
358
- | `identity f e` | Both identity equations |
359
- | `left absorbing element f zero` | `f zero x = zero` |
360
- | `right absorbing element f zero` | `f x zero = zero` |
361
- | `absorbing element f zero` | Both absorbing equations |
362
- | `left distributive f g` | `f x (g y z) = g (f x y) (f x z)` |
363
- | `right distributive f g` | `f (g x y) z = g (f x z) (f y z)` |
364
- | `distributive f g` | Both distributive equations |
365
- | `idempotent operation f` | `f x x = x` (the existing `idempotent` law is unary) |
366
- | `left inverse element f inverse e` | `f (inverse x) x = e` |
367
- | `right inverse element f inverse e` | `f x (inverse x) = e` |
368
- | `invertible f inverse e` | Both inverse equations |
369
- | `left division f divideLeft` | `f x (divideLeft x y) = y` and `divideLeft x (f x y) = y` |
370
- | `right division f divideRight` | `f (divideRight x y) y = x` and `divideRight (f x y) y = x` |
371
- | `divisible f divideLeft divideRight` | All four division equations |
372
- | `involution f` | `f (f x) = x` |
373
-
374
- Here **divisible** means algebraic left/right division. `divideLeft x y` solves
375
- `f x result = y`; `divideRight x y` solves `f result y = x`. The subtraction
376
- example deliberately uses a noncommutative operation: with `x = 3` and `y = 5`,
377
- the left solution is `-2` and the right solution is `8`. Recovery is checked in
378
- both directions. These are total laws; a partially defined division needs an
379
- explicit domain predicate and conditional equations.
380
-
381
- `invertible` checks the supplied inverse operation. Check `identity` and
382
- `associative` as well when specifying a group. The prelude states contracts;
383
- it does not supply arithmetic implementations or prove a structure from random
384
- tests. The algebra and numeric currying examples use mathematical `Integer`
385
- values and exact native arithmetic. Explicit expectations exceed Int32 and
386
- machine bounds, so wrapping or lossy adapters fail even when their modular
387
- arithmetic happens to satisfy the algebraic identities.
388
-
389
- Use `and` to require multiple conclusions in one law. For example:
390
-
391
- ```lawspec
392
- unit example.absorption
393
- multiply :: Int32 -> Int32 -> Int32
394
-
395
- law `zero absorbs on both sides` is
396
- definition is
397
- `for all` (x :: Int32) .
398
- multiply 0 x = 0 and multiply x 0 = 0
399
- end
400
-
401
- example `3 times zero and zero times 3 both produce zero` is
402
- x = 3
403
- expect multiply 0 x = 0
404
- expect multiply x 0 = 0
405
- end
406
- end
407
- ```
408
-
409
- Quantification and implication extend through the following conjunction:
410
- `p x implies A and B` guards both conclusions. Write `(p x implies A) and B`
411
- to guard only the first. A shared guard runs once per check; false guards skip
412
- their entire consequence. Every conjunct is type-checked and emitted. As with
413
- existing assertions, the first failure stops that individual test. `and` is now
414
- a reserved word.
415
-
416
- [Currying examples](https://github.com/brain-fuel/lawspec/blob/v0.15.0/examples/specs/currying.lawspec) demonstrate a four-argument
417
- function partially applied twice, a formatter with four heterogeneous arguments,
418
- and composition after partial application. Each example states its exact outputs.
419
- Run `node npm/bin/lawspec.mjs examples` after rebuilding to inspect all nine units
420
- in all eight target languages.
421
-
422
- The expanded API's **`assertion` tree is authoritative**: `AssertEqual` contains
423
- two expressions, `AssertImplies` contains a condition and consequence, and
424
- `AssertAll` contains every conjunct. Existing `left`, `right`, and `guards`
425
- fields are compatibility projections of the first conclusion only; consumers
426
- checking compound laws must traverse `assertion`. Source definitions add `And`.
427
- `lawspec explain` prints the full conjunction and its conditional scope.
428
-
429
- ## Predicates and conditional laws (0.5)
430
-
431
- A predicate is a unary function returning `Bool`. Use `true` and `false` in
432
- expressions, example bindings, and expected results. A Boolean expression can
433
- stand alone as a law's definition: it must evaluate to `true`.
434
-
435
- `condition implies consequence` checks the consequence only when the condition
436
- is true. Conditions must have type `Bool`; nested implications short-circuit in
437
- source order. The consequence can be an equality, another implication, a Boolean
438
- predicate, or a reusable law application. Quantify any inputs before using them.
439
-
440
- ```lawspec
441
- unit example.parse_port
442
-
443
- validPort :: Int32 -> Bool
444
- render :: Int32 -> Text
445
- parse :: Text -> Int32
446
-
447
- law `valid ports round trip` is
448
- definition is
449
- `for all` (x :: Int32) .
450
- validPort x implies
451
- parse (render x) = x
452
- end
453
-
454
- example `ordinary port` is
455
- x = 443
456
- expect validPort x = true
457
- expect render x = "443"
458
- expect parse (render x) = 443
459
- end
460
-
461
- example `zero is rejected; the round trip is skipped` is
462
- x = 0
463
- expect validPort x = false
464
- end
465
- end
466
- ```
467
-
468
- The [complete port example](https://github.com/brain-fuel/lawspec/blob/v0.15.0/examples/specs/parse_port.lawspec)
469
- defines valid ports as 1–65535, and covers both endpoints, ordinary ports, zero,
470
- negative values, and 65536. All explicit `expect` assertions run regardless of
471
- the law's condition. A false condition skips only the consequence: invalid ports
472
- never reach `render` or `parse` through the law. Predicate errors still fail the
473
- test; they are not treated as false.
474
-
475
- Implication is logical implication, not generator filtering or an assumption.
476
- Randomized tests still sample the full input domain and count a false condition
477
- as satisfying the law. A narrow predicate may therefore exercise few or no
478
- consequences during a random run. Explicit valid examples ensure the important
479
- cases run, and expectations of both `true` and `false` catch always-false and
480
- always-true predicate implementations.
481
-
482
- The prelude includes `satisfies predicate` (the predicate holds for every input)
483
- and `left inverse when predicate parse render` (the guarded round trip above).
484
- These reusable laws preserve the condition and its lexical bindings when expanded.
485
- `equivalent` can also compare two predicates, since `Bool` supports equality.
486
- The [Boolean flags example](https://github.com/brain-fuel/lawspec/blob/v0.15.0/examples/specs/boolean_flags.lawspec)
487
- checks that flipping twice restores both `false` and `true`; all targets generate
488
- Boolean property inputs and explicit tests for both Boolean boundary values. Java caps Boolean-only JetCheck runs at the number of
489
- possible input combinations (up to 100), avoiding generator exhaustion.
490
-
491
- In 0.5, `implies`, `true`, and `false` become reserved words. Existing 0.4 specs
492
- that use those words as identifiers need renaming. The API adds `BoolLit`,
493
- `Holds`, and `Implies` AST variants, Boolean literal values, and an ordered
494
- `guards` array on expanded laws. `lawspec explain` prints the conditions.
495
-
496
- Kotlin adapters now group functions in an `object` named after the unit (for
497
- example, `object ParsePort` in package `example`). This allows both the port and
498
- alternatives units to define `render(Int)`. When upgrading a Kotlin project,
499
- move existing top-level adapter functions into the indicated object; generation
500
- preserves your adapter and reports the required stub shape. Generated tests call
501
- `ParsePort.validPort(...)`, `ParsePort.render(...)`, and `ParsePort.parse(...)`.
502
-
503
- ## Expected results and migration from 0.3
504
-
505
- Every `example` must bind all quantified inputs and then include one or more
506
- `expect <expression> = <literal>` assertions. The expected literal must have the
507
- contextual scalar type of the expression. Expressions can reference the
508
- example's inputs and the unit's functions, including composed function calls.
509
- Input names shadow function names within expectations, following lexical scope.
510
-
511
- An example passes only when **all its expected results and its enclosing law**
512
- pass. Expected results are authored specifications, never inferred by executing
513
- your adapter. They apply to that example's inputs; randomized and boundary tests
514
- continue to check the general law. Generated assertions show compared values and
515
- identify the example, input bindings and expression. A failing assertion stops
516
- that individual test; other tests remain independent.
517
-
518
- This is an intentional syntax break from 0.3: input-only examples are rejected,
519
- and `expect` is now a reserved keyword. Laws can still omit examples altogether.
520
- For an existing input-only example, retain its bindings and add the intended
521
- result before `end`:
522
-
523
- ```lawspec
524
- example `zero renders as 0 and round-trips unchanged` is
525
- x = 0
526
- expect itoa x = "0"
527
- expect atoi (itoa x) = 0
528
- end
529
- ```
530
-
531
- Update every example before running `check` or `generate`. Use
532
- `npx lawspec explain` to inspect the law expansion, example inputs and expected
533
- results; this command displays the specification without executing adapters.
534
- Existing implementation adapters remain user-owned and are never overwritten.
535
- The historical `scratch.md` is a design draft, not the current syntax reference.
536
-
537
- ## Comparing alternative implementations
538
-
539
- `equivalent` compares two functions with the same input and output types. Its
540
- `Eq b` requirement applies to the **result**, so an `Int32 -> Text` comparison
541
- uses text equality, while `Int32 -> Int32` uses integer equality.
542
-
543
- ```lawspec
544
- unit example.formatting
545
-
546
- render :: Int32 -> Text
547
- referenceRender :: Int32 -> Text
548
-
549
- law `decimal renderers agree` is
550
- definition is
551
- `equivalent` render referenceRender
552
- end
553
- example `both renderers produce a negative decimal string` is
554
- x = -42
555
- expect render x = "-42"
556
- expect referenceRender x = "-42"
557
- end
558
- end
559
- ```
560
-
561
- This expands to `for all (x :: Int32) . render (x) = referenceRender (x)`.
562
- The example inherits the input name `x` from the prelude. Both functions are
563
- user-owned adapter functions; either may delegate to your existing code.
564
-
565
- [The complete example](https://github.com/brain-fuel/lawspec/blob/v0.15.0/examples/specs/equivalent.lawspec) compares decimal
566
- renderers and two implementations that clamp negative integers to zero. For
567
- JavaScript, their adapters can be:
568
-
569
- ```javascript
570
- export const render = x => String(x);
571
- export const referenceRender = x => x.toString(10);
572
- export const clamp = x => Math.max(0, x);
573
- export const referenceClamp = x => x < 0 ? 0 : x;
574
- ```
575
-
576
- The same specification generates native tests for all eight targets. The
577
- integration suite checks both examples with matching implementations, then
578
- breaks each alternative separately to verify detection. The general equivalence law alone does not establish independent correctness;
579
- two implementations can share the same bug. Explicit expectations additionally
580
- check the specified outputs at the supplied example inputs. Quantified inputs can use any supported scalar domain.
581
-
582
- ## Text properties and idempotence
583
-
584
- ```lawspec
585
- unit example.slug
586
-
587
- normalize :: Text -> Text
588
- referenceNormalize :: Text -> Text
589
-
590
- law `normalizers agree` is
591
- definition is
592
- `equivalent` normalize referenceNormalize
593
- end
594
- example `spaces become hyphens; punctuation is preserved` is
595
- x = "Hello, World!"
596
- expect normalize x = "Hello,-World!"
597
- expect referenceNormalize x = "Hello,-World!"
598
- end
599
- end
600
- ```
601
-
602
- The [slug example](https://github.com/brain-fuel/lawspec/blob/v0.15.0/examples/specs/slug.lawspec)
603
- compares two implementations of ASCII-space replacement. It includes empty,
604
- Unicode and escaped text. Each target uses its native string generator:
605
- JetCheck `Generator.stringsOf(Generator.asciiPrintableChars())`, Hypothesis `st.text()`, fast-check `fc.string()`,
606
- Rapid `rapid.String()`, Hedgehog `Gen.text`, or Kotest `Arb.string()`.
607
- Generator distributions differ between libraries; the generated tests also
608
- exercise deterministic empty, whitespace, Unicode, combining-mark and escaped
609
- control-character cases. Hedgehog's generated text length range is 0–100.
610
-
611
- The prelude's `idempotent` law requires `f (f x) = f x`:
612
-
613
- ```lawspec
614
- unit example.canonical_url
615
-
616
- canonicalize :: Text -> Text
617
-
618
- law `canonicalization reaches a fixed point` is
619
- definition is
620
- `idempotent` canonicalize
621
- end
622
- example `all trailing slashes are removed in one pass` is
623
- x = "https://example.com/path///"
624
- expect canonicalize x = "https://example.com/path"
625
- end
626
- end
627
- ```
628
-
629
- The [canonical URL example](https://github.com/brain-fuel/lawspec/blob/v0.15.0/examples/specs/canonical_url.lawspec)
630
- uses removal of **all trailing slashes** as a small fixed-point demonstration,
631
- not a complete URL canonicalization algorithm. For JavaScript:
632
-
633
- ```javascript
634
- export const canonicalize = value => value.replace(/\/+$/, "");
635
- ```
636
-
637
- Removing just one trailing slash fails the supplied repeated-slash example.
638
- The [mixed-input example](https://github.com/brain-fuel/lawspec/blob/v0.15.0/examples/specs/mixed_inputs.lawspec)
639
- shows `Text` and `Int32` in the same quantified property and executable example.
640
- The JavaScript API represents example bindings as typed records whose values use
641
- `DataValue`: lossless tagged scalar payloads or structural constructors. Expected results are
642
- typed expressions inside `Assertion` trees, not untyped JavaScript primitives.
643
- See the [API migration guide](API-MIGRATION.md) for their wire representation.
644
-
645
- ## Generate all example artifacts
646
-
647
- To use native domain bindings, export the runnable payment
648
- example (omit `--target` to export all eight languages):
649
-
650
- ```sh
651
- lawspec examples --example payments --target rust --output native_payments
652
- cd native_payments/rust
653
- # Install the dependencies listed in README.md, then:
654
- lawspec check
655
- lawspec generate
656
- cargo test
657
- ```
658
-
659
- These projects include application-owned types, native generators, binding
660
- configuration, and build files. Re-exporting preserves edits and leaves the
661
- compiler's generation manifest separate from the example export manifest.
662
-
663
- ```sh
664
- npx lawspec examples
665
- # Or select a target and a relative output directory:
666
- npx lawspec examples --target java --output example_artifacts
667
- ```
668
-
669
- This command works without a project configuration or native build tools. It
670
- compiles every bundled example and writes its tests and user-owned stubs to
671
- `example_artifacts/<language>/`, using each target's normal source/test layout.
672
- By default it exports all eight languages; `--json` returns the file inventory.
673
- From a checkout, `make examples` runs the same command.
674
-
675
- These are inspection artifacts, not initialized projects: no build files are
676
- created and dependency compatibility is not checked. To run them, configure the
677
- corresponding native project and implement the stubs. Regeneration preserves
678
- user-owned stubs and refuses to overwrite edited generated tests. Each target
679
- has its own ownership manifest. Output paths must be relative and cannot use
680
- parent traversal or symlinks. The default directory is ignored by Git.
681
-
682
- ## Ownership
683
-
684
- Implementation adapters are created once and belong to you. Implement them or
685
- have them delegate to existing application functions. Regeneration never rewrites
686
- them. If the required adapter contract changes, generation prints the new stub
687
- shape for you to apply manually.
688
-
689
- Generated tests are tracked in `.lawspec/generated.json` with content hashes.
690
- Commit that manifest alongside generated tests. LawSpec refuses to overwrite
691
- unowned files or edited generated files, even if an unowned file has matching
692
- contents. Obsolete tests are deleted only when they still match their recorded
693
- hash. User adapters remain. Output paths cannot traverse outside a target root
694
- or pass through symlinks. Writes use temporary files and atomic replacement;
695
- concurrent edits detected during preflight abort generation.
696
-
697
- ## JavaScript API
698
-
699
- ```javascript
700
- import { createCompiler } from 'lawspec';
701
-
702
- const compiler = await createCompiler();
703
- const result = await compiler.planGeneration({
704
- sources: [{ path: 'codec.lawspec', content: sourceText }],
705
- target: 'python'
706
- });
707
- if (result.diagnostics.length) console.error(result.diagnostics);
708
- else console.log(result.files);
709
- ```
710
-
711
- `check`, `expand`, and `planGeneration` are asynchronous and share structured
712
- source/diagnostic types. `planGeneration` returns proposed paths, contents and
713
- ownership; it does not inspect a host environment or write files. The CLI applies
714
- compatibility and ownership checks. TypeScript declarations ship in the package.
715
- The same compiler instance supports repeated and concurrent requests, serialized
716
- by the JS shim.
717
-
718
- ## Build and verify
719
-
720
- For contributors working from a repository checkout, build a local archive with
721
- `npm pack ./npm` and install it with `npm install --save-dev ./lawspec-0.15.0.tgz`.
722
- The package payload lives in `npm/`.
723
-
724
- ```sh
725
- stack test
726
- # With wasm32-wasi-cabal and wasm32-wasi-ghc installed:
727
- tools/wasm.sh
728
- node --test npm/test/*.test.mjs
729
- node tools/parity.mjs
730
- stack run lawspec-dev -- integrity
731
- node tools/package-smoke.mjs
732
- ```
733
-
734
- Stack is the native development tool. The WASM build uses GHC's wasm32-wasi backend
735
- and Cabal, following Rice's Tax. `tools/wasm.sh` reads `~/.ghc-wasm/env` when present.
736
- The current artifact was built using GHC WASM 9.14.1.20260731; WASM dependencies
737
- are frozen in `wasm/cabal.project.freeze`. Install the cross compiler through
738
- [ghc-wasm-meta](https://gitlab.haskell.org/haskell-wasm/ghc-wasm-meta).
739
-
740
- Haskell's export table generates the JS API and `.d.ts` files. The build records
741
- compiler-source and artifact hashes in `npm/build.json`; `lawspec-dev integrity`
742
- rejects stale WASM or hand-edited generated wrappers. The npm archive is a self-contained consumer
743
- artifact, with no install-time compilation or download hook.
744
-
745
- The complete check runs locally; there is no hosted CI. Install the eight
746
- targets' build tools, then:
747
-
748
- ```sh
749
- stack run lawspec-dev -- ci # everything
750
- stack run lawspec-dev -- ci --target rust --target go
751
- stack run lawspec-dev -- ci --core # compiler, npm and editor only
752
- ```
753
-
754
- It runs the compiler, npm, parity, package and editor checks, then for each
755
- target bootstraps its dependencies, runs every acceptance suite in both machine
756
- profiles, and runs the installed native-binding example. Each step logs to
757
- `.artifacts/ci/`, and the command exits non-zero if any step failed.
758
- `--rust-toolchains 1.85.0,stable` and `--rust-targets i686-unknown-linux-gnu`
759
- add Rust toolchains and architectures. The steps can also be run on their own:
96
+ ## Targets
760
97
 
761
- ```sh
762
- node tools/bootstrap-integration.mjs
763
- stack run lawspec-acceptance -- integration # all eight targets
764
- stack run lawspec-acceptance -- scalar rust # one suite, one target
765
- LAWSPEC_MACHINE_BITS=32 LAWSPEC_MINIFY=1 stack run lawspec-acceptance -- indexed go
766
- stack run lawspec-acceptance -- domain --check # regenerate and compare only
767
- ```
98
+ | Target | Build setup | Test libraries | Test command |
99
+ | --- | --- | --- | --- |
100
+ | `java` | Maven, JDK 25, release 25 | JetCheck 0.3.0, JUnit Jupiter 5.14.x | `mvn test` |
101
+ | `python` | Python 3.13 or 3.14, pyproject | pytest 8.4.x, Hypothesis 6.135.26+ (6.x) | `python -m pytest` |
102
+ | `javascript` | Node 22+, npm, ESM | fast-check 4.x, node:test | `npm test` |
103
+ | `typescript` | Node 22+, npm, TypeScript 5.9.x, ESM | fast-check 4.x, node:test | `npm test` |
104
+ | `go` | Go modules, Go 1.22–1.26 | Rapid 1.2.0, testing | `go test ./...` |
105
+ | `haskell` | Stack, GHC 9.10, LTS 24.58 | Hspec 2.11, Hedgehog 1.5, hspec-hedgehog 0.3 | `stack test` |
106
+ | `kotlin` | JDK/JVM 25, Gradle 9.1–9.3, Kotlin 2.3.21 | Kotest 5.9.1 | `gradle test` |
107
+ | `rust` | Rust 1.85+, edition 2024, Cargo | Proptest 1.11.0 | `cargo test` |
768
108
 
769
- Bootstrap installs the pinned test dependencies into isolated `.integration/`
770
- projects. `lawspec-acceptance` generates each suite's bundled examples in process,
771
- installs the suite's adapters, runs the target's own test command, and requires
772
- every mutant to fail its laws at test time; a mutant that only breaks the build
773
- fails the suite. Suites live in `acceptance/<suite>/`: `suite.json` names the
774
- specifications, `<target>/files/` holds real adapter sources, `<target>/stubs/`
775
- records the stub an adapter was written against, and `<target>/mutants/*.mutant`
776
- holds one search/replace edit per mutant. Suites are `integration`, `algebra`,
777
- `scalar`, `refinement`, `indexed` and `domain`. Gradle 9.3.0 is used from
778
- `.tools/gradle-9.3.0` when present, otherwise from `PATH`; `LAWSPEC_OFFLINE=1`
779
- uses existing dependency caches. `npm/test/build-files.test.mjs` checks that
780
- generation leaves build files unchanged. `LAWSPEC_PYTHON=3.14` selects the
781
- additional Python reference environment. Registry publication is a separate
782
- release action.
109
+ See the [target guides](docs/how-to/targets/index.md).
783
110
 
784
- The native-binding acceptance command uses the installed npm archive, public CLI,
785
- and the selected target's normal test command:
111
+ ## Documentation
786
112
 
787
- ```sh
788
- node tools/native-example-integration.mjs rust
789
- LAWSPEC_MACHINE_BITS=32 LAWSPEC_MINIFY=1 node tools/native-example-integration.mjs rust
790
- ```
113
+ The [documentation](docs/index.md) has tutorials, how-to guides, a reference
114
+ for the language, CLI, configuration and API, and explanations of the design.
115
+ Release history is in the [changelog](CHANGELOG.md). To work on LawSpec itself,
116
+ see [contributing](CONTRIBUTING.md).
791
117
 
792
- Replace `rust` with any supported target. It exports the payment project, verifies
793
- correct behavior, rejects an incorrect fee, and checks regeneration. Per-command
794
- logs live in `.artifacts/native-example-integration/`. See the
795
- [acceptance reference](NATIVE-BINDINGS.md) for dependency overrides and remaining
796
- verification gates.
118
+ Syntax highlighting is available as a [VS Code extension](editors/vscode/README.md).
797
119
 
120
+ ## License
798
121
 
799
- Refinement predicates can depend on earlier inputs. Generated tests backtrack from
800
- impossible prefixes, preserve the domain during shrinking, and validate function
801
- preconditions and postconditions. `Integer` results specify exact values without
802
- choosing a storage width. See the [refinement reference](REFINEMENTS.md) and
803
- [bundled examples](examples/specs/refinements.lawspec).
122
+ MIT. See [LICENSE](LICENSE).