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/LANGUAGE.md DELETED
@@ -1,692 +0,0 @@
1
- # LawSpec language and compiler boundary (0.15)
2
-
3
- LawSpec describes portable laws, concrete examples, and adapter contracts. The
4
- compiler is written in Haskell. Rust is an output backend alongside Java, Python,
5
- JavaScript, TypeScript, Go, Haskell, and Kotlin.
6
-
7
- ## Lists and algebraic containers
8
-
9
- `List a` is an ordered, finite sequence of values of one type. Lists nest and
10
- retain duplicates. Literals use brackets; their element type comes from the
11
- surrounding signature, quantifier, or annotation. An unconstrained empty list
12
- needs an annotation such as `([] :: List Int8)`.
13
-
14
- ```lawspec
15
- unit guide.lists
16
-
17
- reverse :: List Int32 -> List Int32
18
-
19
- law `reverse preserves length` is
20
- definition is
21
- `for all` (xs :: List Int32) .
22
- prelude.length (reverse xs) = prelude.length xs
23
- end
24
- example `duplicates count separately` is
25
- xs = [3, 1, 3]
26
- expect prelude.length xs = 3
27
- expect reverse xs = [3, 1, 3]
28
- end
29
- end
30
- ```
31
-
32
- `prelude.length` returns an exact integer. List equality compares corresponding
33
- values in order and requires equal lengths. It preserves scalar equality rules:
34
- NaN still differs from itself, signed zeros compare equal, and Symbols compare
35
- by identity. Generic list equality requires `Eq a`.
36
-
37
- `Maybe a` has constructors `Nothing` and `Just value`. `Either a b` has
38
- constructors `Left value` and `Right value`. These are algebraic sums, separate
39
- from the interoperability types `Nullable a` and `Optional a`.
40
-
41
- ```lawspec
42
- unit guide.presence
43
-
44
- echo :: Maybe (Either Int8 Bool) -> Maybe (Either Int8 Bool)
45
-
46
- law `preserve every alternative` is
47
- definition is `for all` (x :: Maybe (Either Int8 Bool)) . echo x = x end
48
- example `absent` is x = Nothing expect echo x = Nothing end
49
- example `left integer` is x = Just (Left 127) expect echo x = Just (Left 127) end
50
- example `right boolean` is x = Just (Right false) expect echo x = Just (Right false) end
51
- end
52
- ```
53
-
54
- For `Maybe (Maybe Bool)`, `Nothing`, `Just Nothing`, and `Just (Just false)`
55
- remain distinct. Nesting a constructor application as an argument generally
56
- requires parentheses, as in `Just (Left 127)`.
57
-
58
- The [collections example](examples/specs/collections.lawspec) combines reverse
59
- involution, sorting idempotence, sortedness, length, and permutation preservation.
60
- `sorted` and `permutation` in that example are adapters supplied by the user;
61
- they are not built-in helpers. Sortedness and length alone cannot establish that
62
- a sorting adapter retained the original elements.
63
-
64
- ## Products, sums, and pattern matching
65
-
66
- A `type` declaration names its constructors and each constructor's fields. One
67
- constructor describes a product; multiple constructors describe a sum. Type
68
- parameters are declared explicitly with `:: Type`.
69
-
70
- ```lawspec
71
- unit guide.trees
72
-
73
- type Pair (a :: Type) (b :: Type) is
74
- Pair
75
- first :: a
76
- second :: b
77
- end
78
-
79
- type Tree (a :: Type) is
80
- Leaf value :: a
81
- Branch children :: List (Tree a)
82
- end
83
-
84
- definition rebuild (tree :: Tree a) :: Tree a is
85
- match tree with
86
- | Leaf value -> Leaf value
87
- | Branch children -> Branch children
88
- end
89
- end
90
-
91
- law `preserve the constructor and its fields` is
92
- definition is `for all` (tree :: Tree Int8) . rebuild tree = tree end
93
- example `nested branches` is
94
- tree = Branch [Leaf 127, Branch [], Leaf -128]
95
- expect rebuild tree = Branch [Leaf 127, Branch [], Leaf -128]
96
- end
97
- end
98
- ```
99
-
100
- Constructors receive fields in declaration order. A match evaluates its
101
- scrutinee once; each branch binds that constructor's fields in the same order.
102
- Bindings are scoped to the branch. Matching must be exhaustive and cannot repeat
103
- a constructor. Lists match with `Nil` and `Cons head tail`; Maybe and Either use
104
- their constructors above. Recursive declarations must be strictly positive.
105
- Constructors may refine natural indices; see [indexed families](#natural-indexed-families).
106
- GADT result signatures that refine type arguments are not supported.
107
-
108
- Equality is structural and type-directed, including named fields and nested
109
- containers. Native public declarations retain their names and type parameters;
110
- schemas and checked codecs support them at runtime. They are not replacements
111
- for the public data types. See the target guides for native representations:
112
- [Java](JAVA.md), [Python](PYTHON.md), [JavaScript/TypeScript](WEB.md),
113
- [Go](GO.md), [Haskell](HASKELL.md), [Kotlin](KOTLIN.md), and [Rust](RUST.md).
114
- In Haskell, `Text` remains `Data.Text.Text`, while `List Char` becomes the linked
115
- list `[Char]`. These are distinct LawSpec types even when they contain the same
116
- characters.
117
-
118
- Generators compose the target framework's generators and shrinkers. Recursive
119
- values have a structural size budget; each constructor reserves enough budget
120
- for its fields before distributing the remainder. Boundaries include empty and
121
- singleton lists and constructor-specific values. Small finite domains are
122
- enumerated. An empty type cannot supply a generated argument, but containers
123
- such as `List Empty` and `Maybe Empty` can still be inhabited. An empty or
124
- unreachable input domain never makes a property pass vacuously.
125
-
126
- Whole-value refinements can inspect products and sums using exhaustive matches.
127
- List element refinements, Maybe/Either payload refinements, and refined arguments
128
- of recursive and nonrecursive named type constructors are supported; see
129
- [refinements](REFINEMENTS.md#named-data-payloads). Direct refinements on named
130
- constructor fields use checked constructor contracts. Recursive payload predicates
131
- follow stored type arguments and preserve outer dependent inputs.
132
-
133
- ## Natural-indexed families
134
-
135
- A data declaration may take `Natural` parameters. Each constructor states how it
136
- determines them with `where <index> = <expression>`:
137
-
138
- ```lawspec
139
- type Vec (n :: Natural) (a :: Type) is
140
- | VNil where n = 0
141
- | VCons head :: a tail :: Vec m a where n = m + 1
142
- end
143
-
144
- type Tree (n :: Natural) (a :: Type) is
145
- | Tip where n = 0
146
- | Bin left :: Tree l a value :: a right :: Tree r a where n = l + r + 1
147
- end
148
-
149
- append :: (xs :: Vec n Int8) -> (ys :: Vec m Int8) -> (r :: Vec (n + m) Int8)
150
- zip :: (xs :: Vec n Int8) -> (ys :: Vec n Bool) -> (r :: Vec n Bool)
151
- ```
152
-
153
- Index expressions are sums of natural literals and index variables. A variable
154
- such as `m` is bound by the field whose type mentions it, and every index needs
155
- exactly one equation in every constructor. `Natural` is also an ordinary value
156
- type: an unbounded integer that is at least zero.
157
-
158
- Indices are evidence, not a second type system. The compiler elaborates a family
159
- before inference into three ordinary declarations:
160
-
161
- - erased data `Vec a` with the same constructors, which is the native
162
- representation on every target;
163
- - a checked structural measure for each index, named `<index>Of<Type>` (here
164
- `nOfVec` and `nOfTree`), recomputed from the constructor equations;
165
- - a refinement, so `Vec e a` in any signature or quantifier means
166
- `(v :: Vec a where nOfVec v == e)`.
167
-
168
- `append` above is therefore an adapter contract: its result must have length
169
- `nOfVec xs + nOfVec ys`, and a native implementation that drops an element
170
- fails with the postcondition. An index variable that is otherwise unbound, like
171
- `n` and `m` in `append`, is implicit. It is determined by the first binder whose
172
- family type mentions it alone, and later occurrences read that binder's measure.
173
- Implicit indices must not first appear inside an expression, and a result cannot
174
- introduce one.
175
-
176
- Generation follows the index. For a free index, as in `append`, values come from
177
- the erased type and the index is their measure. For a fixed index (`Vec 3 Int8`)
178
- or a shared one (`zip`'s `ys`), the target is solved backwards through the
179
- constructor equations: `VCons` for `n = 3` needs a tail with index 2, and `Bin`
180
- splits `n - 1` between its subtrees. Samples are constructed, not filtered, and
181
- shrinking stays within the index on every target. The same planning applies to
182
- any user-written measure over declared data whose branches are a constant plus
183
- the same measure of that branch's fields.
184
-
185
- ### Proved indices and evidence
186
-
187
- Checked definitions may return indexed families. The compiler proves their
188
- result indices statically, so they need no runtime postcondition:
189
-
190
- ```lawspec
191
- definition concatV (xs :: Vec n Int8) (ys :: Vec m Int8) :: Vec (n + m) Int8 is
192
- match xs with
193
- | VNil -> ys
194
- | VCons h t -> VCons h (concatV t ys)
195
- end
196
- end
197
- ```
198
-
199
- The proof uses exact linear arithmetic over the measures. A measure applied to a
200
- known constructor unfolds to that constructor's equation, so `nOfVec (VCons h t)`
201
- is `nOfVec t + 1`. Within a match branch, the scrutinee's constructor is known.
202
- Calls of checked definitions are pure, so equal calls have equal results. A
203
- recursive call contributes its own signature as the induction hypothesis, and
204
- natural measures are non-negative. A definition whose result index does not
205
- follow fails with `definition result refinement could not be proved`.
206
-
207
- Definition postconditions are `proved`, and generated code omits their runtime
208
- checks; see [evidence and discharge](#evidence-and-discharge) for every other
209
- obligation. A proved definition is a natural reference model for a
210
- native adapter, as in `append xs ys = concatV xs ys` in the
211
- [indexed example](examples/specs/indexed_families.lawspec).
212
-
213
- ## Evidence and discharge
214
-
215
- Every obligation of a program reports how it is discharged, strongest first:
216
-
217
- | Status | Obligations | How |
218
- | --- | --- | --- |
219
- | `PROVED` | laws over checked definitions; definition postconditions and indices | statically, by the prover |
220
- | `EXHAUSTIVELY CHECKED` | laws whose inputs form a finite domain | every input, by the compiler or the generated tests |
221
- | `PROPERTY TESTED` | other laws | generated cases, boundary cases and examples |
222
- | `RUNTIME CHECKED` | adapter contracts, definition preconditions, constructor constraints, native type bindings | at every native boundary |
223
- | `ASSUMED / EXTERNAL` | adapters, native functions, custom generators and codec hooks | taken on trust |
224
-
225
- A law that calls only checked definitions is attempted as a proof: its claim
226
- must follow from its input refinements by the same exact linear arithmetic that
227
- proves definition results. Definitions without preconditions are unfolded
228
- into the claim; a definition with preconditions stays a call, and its arguments
229
- must be shown to satisfy them. For example, with
230
- `definition twice (x :: Int32) :: BigInt is x + x end`, the law
231
- `` `for all` (x :: Int32) . twice x = x * 2 `` is proved.
232
-
233
- A law over checked definitions that is not proved but has a finite domain (at
234
- most `exhaustiveLimit` inputs) is evaluated by the compiler for every input. A
235
- counterexample is a compile error with code `refuted`:
236
-
237
- ```text
238
- law always positive is false for x = -128
239
- ```
240
-
241
- A law that calls an adapter is checked by the generated tests: for every input
242
- of a finite domain, or else by property testing, with the adapters it relies on
243
- listed. A law with no inputs has a single case and is exhaustively checked.
244
- Proved and compiler-checked laws are still emitted as tests, which check the
245
- generated native definitions.
246
-
247
- An adapter is native code that LawSpec cannot inspect: its only evidence is the
248
- laws that call it, and one that no law calls is reported as such. Native type
249
- bindings decode values through checked codecs, so they are runtime-checked,
250
- while native functions, custom generators and codec hooks are taken on trust
251
- (their values are still validated).
252
-
253
- `lawspec check` summarizes the evidence by status. `lawspec evidence` lists each
254
- obligation with its claim and reason, grouped by status, and accepts a unit or a
255
- `unit::declaration` filter; with `--json` it prints the API records. The API
256
- reports the obligations in the `evidence` field.
257
-
258
- ## Domain modeling
259
-
260
- ### Wrappers and constrained primitives
261
-
262
- A `wrapper` gives a primitive or container a domain meaning. It declares a
263
- distinct nominal type with one field, `value`, and an optional constraint:
264
-
265
- ```lawspec
266
- wrapper UnitQuantity is Int32 where value >= 1 && value <= 1000 end
267
- wrapper OrderId is Text where prelude.length value > 0 end
268
- wrapper NonEmptyList (a :: Type) is List a where prelude.length value > 0 end
269
- ```
270
-
271
- `UnitQuantity` is not interchangeable with `Int32` or with another wrapper over
272
- `Int32`. Its constructor, `UnitQuantity 5`, checks the constraint, so an invalid
273
- value cannot be constructed in an example, produced by a generator, or decoded
274
- from native code. `valueOfUnitQuantity` unwraps it. A wrapper elaborates to a
275
- single-constructor product with a refined field and a checked definition, and
276
- its native representation is that product on every target. The constraint is
277
- reported as a `construction` obligation in the evidence.
278
-
279
- ### Workflows and state distinctions
280
-
281
- A workflow names a pipeline of adapter steps between distinct state types:
282
-
283
- ```lawspec
284
- type UnvalidatedOrder is UnvalidatedOrder id :: Text quantity :: Int32 end
285
- type ValidatedOrder is ValidatedOrder id :: OrderId quantity :: UnitQuantity end
286
- type PricedOrder is PricedOrder id :: OrderId quantity :: UnitQuantity total :: Int64 end
287
-
288
- workflow placeOrder :: UnvalidatedOrder -> Either OrderError PricedOrder is
289
- validateOrder :: UnvalidatedOrder -> Either OrderError ValidatedOrder
290
- priceOrder :: ValidatedOrder -> Either OrderError PricedOrder
291
- end
292
- ```
293
-
294
- Each step is an ordinary adapter declaration with one input. The compiler checks
295
- that every step accepts the state the previous step produces, that fallible steps
296
- (those returning `Either E T`) share one error type, and that the workflow's
297
- declared result matches: `Either E T` if any step can fail, otherwise `T`. It then
298
- adds the law `placeOrder composes its steps`: the native workflow must equal the
299
- railway composition of the native steps, where the first `Left` is the result. A
300
- step declared again with the same type is shared between workflows.
301
-
302
- Because each state is its own type, a `ValidatedOrder` can only hold checked
303
- values, and a step that needs one cannot be given raw input. See the
304
- [domain modeling example](examples/specs/domain_modeling.lawspec).
305
-
306
- ## Imports and packages
307
-
308
- ### Importing units
309
-
310
- A unit may import other units after its `unit` line:
311
-
312
- ```lawspec
313
- unit shop.orders
314
- import shop.domain as domain (Money, Cents, `commutative`)
315
-
316
- type Currency is | Usd | Gbp end
317
- settlement :: Currency -> domain.Currency
318
-
319
- law `dollars settle in dollars` is
320
- definition is
321
- settlement Usd = domain.Usd
322
- end
323
- end
324
- ```
325
-
326
- `import U` makes every declaration of `U` available qualified by an alias, which
327
- defaults to the unit's last name segment (`import shop.domain` gives `domain`);
328
- `as` names another alias. A parenthesized list also makes the listed names
329
- available unqualified. Listing a data type or wrapper brings its constructors and
330
- its generated functions (`valueOf<Name>`, indexed-family measures) with it; list
331
- a law by its quoted name. Qualified names are written without spaces around the
332
- dot (`domain.Usd`); write `f . g` with spaces to compose a function whose name is
333
- also an alias.
334
-
335
- What can be imported:
336
-
337
- - data types, wrappers and indexed families, with their constructors;
338
- - refinements;
339
- - checked definitions;
340
- - generic laws, that is laws with parameters, which the importer applies to its
341
- own adapters (`` `commutative` total ``).
342
-
343
- Adapter signatures and laws without parameters belong to their unit: they are the
344
- unit's own contract with its native code and are tested there. Referring to
345
- another unit's adapter is an error, as is importing a declaration that uses one.
346
-
347
- Names are scoped to their unit. Two units may both declare `Currency`, `Usd` or a
348
- definition `size`; `domain.Usd` and the local `Usd` are different constructors.
349
- Targets with a single data namespace qualify the colliding native names by unit
350
- (`ShopDomainCurrency`, `ShopOrdersCurrency`). An unqualified name that is both
351
- listed in an import and declared locally is an error, as is one listed from two
352
- units. Imports are not re-exported: a unit uses what it imports itself.
353
-
354
- Imports are resolved before type checking. A data type stays with the unit that
355
- declares it, so values of `domain.Money` are the same values in every importing
356
- unit. Imported refinements, checked definitions and generic laws are copied into
357
- the importing unit, together with everything they use, under names derived from
358
- their unit (`domain.centsOf` is emitted as `shopDomainCentsOf`). Core and all
359
- eight targets therefore need nothing new. Import cycles, unknown units and
360
- missing names are reported at the import.
361
-
362
- ### Packages
363
-
364
- A package is a named, versioned directory of units, described by
365
- `lawspec-package.json`:
366
-
367
- ```json
368
- {
369
- "name": "shop.domain",
370
- "version": "1.2.0",
371
- "sources": ["src"],
372
- "dependencies": {}
373
- }
374
- ```
375
-
376
- Every unit of a package is named after it: `shop.domain` or `shop.domain.<name>`.
377
- A project, or another package, declares the packages it depends on with version
378
- ranges, and lists the package directories to load:
379
-
380
- ```json
381
- {
382
- "version": 1,
383
- "sources": ["orders.lawspec"],
384
- "dependencies": {"shop.domain": "^1.0.0"},
385
- "packages": ["../shop-domain"],
386
- "targets": [{"language": "java", "root": "java"}]
387
- }
388
- ```
389
-
390
- A unit may import the units of its own package (or project) and of the packages
391
- it depends on directly. Versions are `MAJOR.MINOR.PATCH` with an optional
392
- prerelease. Ranges combine `1.2.3` (exactly), `^1.2.3`, `~1.2.3`, `>=`, `>`,
393
- `<=`, `<` and `*`, with npm's meaning. Resolution is exact: one version of each
394
- package is supplied, every range must accept it, a package that nothing requires
395
- is rejected, and package dependency cycles are rejected. Project units may not
396
- use a dependency's namespace.
397
-
398
- A package publishes a behavioral contract. Its types, refinements, definitions
399
- and generic laws are a library, and its adapter signatures and concrete laws are
400
- obligations: a project that depends on the package implements those adapters in
401
- its own native code and is tested against the package's laws, with the same
402
- user-owned adapter files as for its own units. `lawspec package` checks a
403
- package on its own and summarizes its units, laws and data types. A package
404
- directory can be distributed any way that delivers the directory, for example
405
- as an npm package. See the [package example](examples/packages).
406
-
407
- ## Total definitions
408
-
409
- A unit can supply an implementation as a checked total definition:
410
-
411
- ```lawspec
412
- definition increment (x :: Int8) :: BigInt
413
- requires Integer Int8
414
- is
415
- x + 1
416
- end
417
- ```
418
-
419
- Parameters and the result have explicit types. The optional `requires` clause
420
- uses the same `Eq`, `Integer`, `Ordered`, and `Bounded` capabilities as laws.
421
- Requirements are checked even when the definition is unused. Bodies must have
422
- exhaustive matches, proven structural descent for recursive calls, and guards
423
- for operations that could otherwise fail. Calls may use other checked
424
- definitions; external adapters cannot establish a definition's totality.
425
-
426
- For exact arithmetic, the totality checker can combine linear bounds and Boolean
427
- guards. For example, `x >= 0 && 1 / (x + 1) > 0` is safe for integer `x`: the
428
- right side runs only when its denominator is positive. Proof arithmetic uses
429
- arbitrary exact fractions, preserves strict boundaries, and has a bounded work
430
- budget. An unproved obligation is rejected; IEEE expressions never acquire
431
- rational identities such as `x - x = 0` from this checker.
432
-
433
- Primitive integer ranges are available to the checker automatically, including
434
- the selected machine width and BigUInt's nonnegative domain. Integer comparisons
435
- retain integrality: for Int8 `x`, `x < 127 && prelude.Int8 (x + 1) > x` safely
436
- narrows only on the guarded branch. The unguarded conversion is rejected because
437
- `127 + 1` is outside Int8. Range bounds alone do not prove that a Rational or
438
- Decimal input has no fractional part.
439
- Pattern matching retains the primitive ranges of extracted fields within that
440
- branch. For example, an Int8 list head still makes `head + 129` strictly positive;
441
- that fact cannot be reused for an Int64 field in another constructor branch.
442
-
443
- Definitions produce reusable generated source with checked native entry points
444
- on all eight targets. They do not produce user-owned adapter stubs. Integer
445
- arithmetic preserves the mathematical result; the example above returns `128`
446
- for the largest Int8 input. See [the total-function example](examples/specs/total_functions.lawspec)
447
- for recursive list counting, structural equality, and explicit expected values.
448
-
449
- Definitions can quantify type variables implicitly through their signatures:
450
-
451
- ```lawspec
452
- definition same (x :: a) (y :: a) :: Bool requires Eq a is x == y end
453
- definition count (xs :: List a) :: BigInt is
454
- match xs with
455
- | Nil -> 0
456
- | Cons head tail -> 1 + count tail
457
- end
458
- end
459
- ```
460
-
461
- Each template is checked for typing, capabilities, termination, and definedness,
462
- including unused templates. Calls specialize it to concrete argument and result
463
- types before Core elaboration. Different calls can use different types; recursive
464
- self-calls must retain the same types. Ambiguous calls require an annotation,
465
- such as `count ([] :: List Int8)` to specify an empty list's element type.
466
- Unused templates emit no instances.
467
- Checked definitions may also appear in refinement predicates and adapter
468
- preconditions or postconditions. Their closed call graphs contain only other
469
- checked definitions; adapter calls remain forbidden in predicates. The compiler
470
- uses the same concrete Core definitions to check example domains and plan finite
471
- cases and boundaries that generated tests use at runtime.
472
- Definition parameters and results may carry refinements. The compiler proves
473
- body definedness and result claims under ordered input preconditions, checks
474
- callee preconditions, and preserves the contracts through specialization. Native
475
- entry points enforce the same contracts. See [refined definitions](REFINEMENTS.md#refined-definitions).
476
-
477
- ## Source and declarations
478
-
479
- A source has one named `unit`, its imports, function signatures, data
480
- declarations, checked definitions, reusable refinements, and laws. Qualified unit names determine target module/package paths. Function
481
- signatures are curried: `a -> b -> c` takes two inputs and returns `c`. Parentheses
482
- group types and expressions. Comments start with `--` and run to the line end.
483
-
484
- The following grammar summarizes the main forms; the parser and executable
485
- compiler tests specify lexical details:
486
-
487
- ```text
488
- source = "unit" qualified-name import* declaration*
489
- import = "import" qualified-name ["as" name]
490
- ["(" (name | quoted-name) ("," (name | quoted-name))* ")"]
491
- declaration = name "::" type | law | refinement | data-type | function
492
- data-type = "type" name ("(" name "::" "Type" ")")*
493
- "is" constructor* "end"
494
- constructor = name (name "::" type)*
495
- function = "definition" name parameter* "::" type requirements?
496
- "is" expression "end"
497
- type = type-atom ["->" type]
498
- type-atom = primitive | type-variable | "(" type ")"
499
- | ("Nullable" | "Optional" | "List" | "Maybe") type-atom
500
- | "Either" type-atom type-atom
501
- | data-type-name type-atom*
502
- | refinement-name argument*
503
- | "(" name "::" type ["where" expression] ")"
504
- refinement = "refinement" name parameter* requirements?
505
- "is" type "end"
506
- parameter = "(" name "::" type ["where" expression] ")"
507
- requirements = "requires" (capability type)+
508
- capability = "Eq" | "Integer" | "Ordered" | "Bounded"
509
- law = "law" quoted-name parameter* requirements? "is"
510
- "definition" "is" proposition "end"
511
- description? rationale? example* references? "end"
512
- proposition = "`for all`" parameter+ "." proposition
513
- | expression "=" expression
514
- | expression "implies" proposition
515
- | proposition "and" proposition
516
- | quoted-name expression* | expression
517
- expression = ... | "[" [expression ("," expression)*] "]"
518
- | constructor-name expression*
519
- | "match" expression "with"
520
- ("|" constructor-name name* "->" expression)+ "end"
521
- example = "example" quoted-name "is" (name "=" literal)+
522
- ("expect" expression "=" literal)+ "end"
523
- ```
524
-
525
- Law names use backticks. Text/metadata use double quotes with escapes. Named
526
- refinement declarations state their type versus value parameter kinds, including
527
- forward references; the compiler validates their arity and argument kinds.
528
- Lowercase type names represent variables. `a :: Type` is a type parameter, not a
529
- runtime value with a generator.
530
-
531
- A generic law is specialized when invoked with concrete adapters. Its declared
532
- capabilities must justify its operations; specialization resolves those
533
- requirements for the actual types. `Integer` as a capability requires an integer
534
- type. `Integer` in a concrete result signature denotes a representation-independent
535
- mathematical integer. See [refinements and abstract integers](REFINEMENTS.md).
536
-
537
- ## Expressions and arithmetic
538
-
539
- Application binds most tightly. The remaining precedence, highest first, is:
540
- unary `!`/`-`, composition `.`, multiplication/division, addition/subtraction,
541
- comparisons (`==`, `!=`, `<`, `<=`, `>`, `>=`), `&&`, then `||`.
542
- Comparisons do not chain. Arithmetic associates left; composition associates
543
- right. An adjacent numeric sign remains part of an argument: `f -42` applies `f`
544
- to negative 42. Write `x - 42` for subtraction.
545
-
546
- Assertion `=` differs from Boolean `==`. `implies` guards its following
547
- proposition; `and` requires both assertions. Parentheses determine the scope of a
548
- shared guard. Both Boolean operators and implications short-circuit.
549
-
550
- Literals acquire types from declared context. Unconstrained integers have type
551
- `Integer`; decimal tokens have type `Decimal`. An annotation such as
552
- `(127 :: Int8)` specifies context. A declared float context can type a decimal
553
- token directly, but an explicitly constructed exact Decimal is not implicitly
554
- converted into a float.
555
-
556
- Integer `+`, `-`, `*`, and negation produce exact `Integer` results. Decimal
557
- dominates integer/Decimal combinations; Rational dominates exact combinations
558
- involving Rational. Exact `/` returns Rational. `prelude.quot` truncates integer
559
- quotients toward zero; `prelude.rem` is the associated remainder. Division by
560
- zero fails when evaluated. Explicit numeric conversions use `prelude.Type`.
561
- Exact/inexact mixing otherwise fails type checking. IEEE arithmetic widens float
562
- or complex precision as required; equality treats NaN as unequal and signed
563
- zero as equal. Decimal rounding is explicit, with a scale and ties-to-even rule.
564
-
565
- Passing a computed exact result to a bounded adapter argument performs a checked
566
- conversion. It never wraps, truncates a fraction, or silently changes precision.
567
- Adapter results are validated against the declared domain before use. See the
568
- [primitive reference](PRIMITIVES.md) for all domains and helpers.
569
-
570
- ## Refinements and executable contracts
571
-
572
- Refinements are pure Boolean predicates over a value and preceding binders.
573
- They cannot call user adapters. Dependent inputs are generated in order;
574
- shrinking preserves their predicates. Bounds such as `y > Int8.max - x` are
575
- computed with exact arithmetic and can drive a dependent generator. If a chosen
576
- `x` has no possible `y`, generation retries earlier inputs. Search exhaustion
577
- fails explicitly rather than passing a property with no valid cases.
578
-
579
- Contracts check preconditions, evaluate an adapter once, validate the result,
580
- and then check postconditions against that same result. Predicate errors are
581
- contextual failures, not rejected samples. Small finite domains are enumerated;
582
- other domains use target property frameworks. `machineBits: 32 | 64` controls
583
- machine-integer domains independently of the compiler host architecture. Native
584
- machine-sized adapter bindings additionally verify the executing architecture.
585
-
586
- ## Compiler stages and public API
587
-
588
- The parser retains source ranges. Resolution and inference check names, kinds,
589
- capabilities, contextual literals, and generic specializations. Elaboration
590
- produces typed core expressions with resolved declaration/binder IDs, explicit
591
- arithmetic evidence and conversions, plus an authoritative proposition tree.
592
- Refinement declarations become predicates on quantifiers and contracts; targets
593
- do not interpret refinement syntax.
594
-
595
- An independent core validator checks scopes, kinds, operand/result types,
596
- capability evidence, and conversions. A pure core evaluator supports deterministic
597
- domain checks and reference tests. The testing planner computes finite cases,
598
- boundaries, and dependent generator requirements. All eight emitters consume
599
- that plan and the core, without importing source syntax or inference.
600
-
601
- `check`/`expand` report semantic validity. `planGeneration` additionally reports
602
- execution feasibility, including empty finite domains. Source syntax errors,
603
- semantic errors, core invariant failures, and generation errors have distinct
604
- diagnostic codes. Runtime failures identify the law/example or adapter contract.
605
- Parsed expressions retain real source ranges; synthesized expressions identify
606
- the declaration that caused their creation.
607
-
608
- API schema v3 uses separately defined wire views, with lossless tagged scalar
609
- values. It does not serialize internal AST constructors. See the
610
- [API migration guide](API-MIGRATION.md).
611
-
612
- ## Roadmap
613
-
614
- 0.11 elaborates natural-indexed families to erased data, measures and
615
- refinements. The Core type model distinguishes type arguments from index
616
- arguments, but that representation is not a claim that arbitrary dependent
617
- programs are accepted. External type bindings and custom generator bindings
618
- (0.10) configure native representations alongside the typed testing plan and do
619
- not change source-language typing or equality; see
620
- [the binding reference](NATIVE-BINDINGS.md).
621
-
622
- ### 0.12 Proof-producing dependent layer (released)
623
-
624
- - Index equalities in checked definitions are discharged statically. Adapter
625
- results remain runtime-checked.
626
- - Linear `Natural` arithmetic over measures is solved exactly, with unfolding
627
- on known constructors and induction through recursive calls.
628
- - Evidence is recorded for every contract obligation as `proved` or
629
- `runtime-checked`, and reported by `lawspec check` and the API.
630
- - Proved definition postconditions produce no runtime checks.
631
- - Checked definitions may return indexed families. See
632
- [proved indices](#proved-indices-and-evidence).
633
-
634
- Still open, for evaluation in later releases: index equalities between sibling
635
- fields (perfect trees whose subtrees share one index), non-linear indices, and
636
- GADTs that refine type arguments.
637
-
638
- ### 0.13 Wlaschin-style domain modeling primitives (released)
639
-
640
- - Semantic wrappers and constrained primitives: `wrapper` declarations with
641
- checked constructors.
642
- - Illegal states are unrepresentable: wrapper and field constraints are checked
643
- on construction, generation and native decoding, and reported as evidence.
644
- - Explicit domain workflows and state distinctions: `workflow` declarations with
645
- checked step types and a generated railway composition law.
646
- - See [domain modeling](#domain-modeling).
647
-
648
- ### 0.14 Cross-unit imports and packages (released)
649
-
650
- - Reusable law, type and refinement libraries: `import` brings another unit's
651
- types, refinements, checked definitions and generic laws into scope.
652
- - Versioning and namespacing: packages have names, semantic versions and
653
- dependency ranges, units live in their package's namespace, and constructor
654
- names are scoped to their unit.
655
- - Publishable behavioral contracts: a package's adapter signatures and laws are
656
- implemented and tested by every project that depends on it.
657
- - See [imports and packages](#imports-and-packages).
658
-
659
- Still open: re-exports, and several versions of one package in one build.
660
-
661
- ### 0.15 Evidence/discharge model (released)
662
-
663
- Each obligation reports how it was discharged:
664
-
665
- - `PROVED`: discharged statically, by 0.12 evidence or definition proofs.
666
- - `EXHAUSTIVELY CHECKED`: every value of a finite domain was checked.
667
- - `PROPERTY TESTED`: generated cases, examples and boundaries.
668
- - `RUNTIME CHECKED`: adapter contracts and checked codecs at native boundaries.
669
- - `ASSUMED / EXTERNAL`: native adapters and bindings taken on trust.
670
-
671
- Laws over checked definitions are proved or exhaustively evaluated by the
672
- compiler, and false ones on finite domains are rejected. See
673
- [evidence and discharge](#evidence-and-discharge).
674
-
675
- ## Generated project formatting
676
-
677
- `lawspec init --target java` creates a readable Maven scaffold; Kotlin init
678
- likewise expands Gradle blocks with two-space indentation. `--minify` explicitly
679
- selects compact scaffolds and configuration JSON. `generate` and `examples`
680
- accept the same flag for generated source. The mode is per invocation and does
681
- not become a project default. Init preserves existing build files, and generation
682
- preserves user-owned adapters regardless of formatting mode.
683
-
684
- Generated runtime support and checked definitions belong in source directories;
685
- framework-specific property helpers belong in test directories. Both follow
686
- custom layout settings. Python uses PEP 8: four-space indentation, 79-column
687
- code, and 72-column prose. Other targets follow Google language guidance where
688
- applicable, with standard Rust formatting. Formatting is deterministic in the
689
- native and WASM compilers; generation does not download or invoke a formatter.
690
-
691
- See [the release notes](RELEASE-0.10.md) for compatibility and scope, and the target
692
- guides for formatting verification and native representation details.