lawspec 0.14.0 → 0.15.1

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