@final-hill/decorator-contracts 0.25.3 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +169 -610
- package/dist/AssertionError.d.mts +3 -8
- package/dist/Contracted.d.mts +17 -21
- package/dist/assert.d.mts +19 -7
- package/dist/demands.d.mts +6 -0
- package/dist/ensures.d.mts +6 -0
- package/dist/iff.d.mts +19 -6
- package/dist/implies.d.mts +19 -6
- package/dist/index.d.mts +10 -13
- package/dist/index.mjs +1 -2
- package/dist/index.mjs.map +1 -1
- package/dist/invariant.d.mts +5 -0
- package/dist/rescue.d.mts +6 -0
- package/dist/types.d.mts +7 -0
- package/package.json +18 -15
- package/dist/Contract.d.mts +0 -39
- package/dist/Messages.d.mts +0 -16
- package/dist/index.mjs.LICENSE.txt +0 -6
- package/dist/lib/ClassRegistration.d.mts +0 -23
- package/dist/lib/ClassType.d.mts +0 -10
- package/dist/lib/Feature.d.mts +0 -26
- package/dist/lib/assertDemands.d.mts +0 -9
- package/dist/lib/assertEnsures.d.mts +0 -10
- package/dist/lib/assertInvariants.d.mts +0 -9
- package/dist/lib/classRegistry.d.mts +0 -12
- package/dist/lib/deepFreeze.d.mts +0 -8
- package/dist/lib/index.d.mts +0 -18
- package/dist/lib/takeWhile.d.mts +0 -8
- package/dist/lib/unChecked.d.mts +0 -9
- package/dist/tests/Contract.test.d.mts +0 -7
- package/dist/tests/Stack.test.d.mts +0 -7
- package/dist/tests/assert.test.d.mts +0 -7
- package/dist/tests/deepFreeze.test.d.mts +0 -7
- package/dist/tests/demands.test.d.mts +0 -7
- package/dist/tests/ensures.test.d.mts +0 -7
- package/dist/tests/factoryPattern.test.d.mts +0 -7
- package/dist/tests/iff.test.d.mts +0 -7
- package/dist/tests/implies.test.d.mts +0 -7
- package/dist/tests/invariant.test.d.mts +0 -7
- package/dist/tests/public-properties.test.d.mts +0 -7
- package/dist/tests/rescue.test.d.mts +0 -7
- package/dist/tests/within.test.d.mts +0 -7
package/README.md
CHANGED
|
@@ -17,7 +17,6 @@
|
|
|
17
17
|
- [Invariants](#invariants)
|
|
18
18
|
- [Demands](#demands)
|
|
19
19
|
- [Ensures](#ensures)
|
|
20
|
-
- [Within](#within)
|
|
21
20
|
- [Rescue](#rescue)
|
|
22
21
|
- [The order of assertions](#the-order-of-assertions)
|
|
23
22
|
- [Further Reading](#further-reading)
|
|
@@ -65,181 +64,103 @@ Via [skypack.dev](https://www.skypack.dev/):
|
|
|
65
64
|
|
|
66
65
|
## Usage
|
|
67
66
|
|
|
68
|
-
After installation the
|
|
67
|
+
After installation, use the decorators directly on your class methods and properties. All contracted classes must extend `Contracted` and be instantiated using the static `.new()` method.
|
|
69
68
|
|
|
70
69
|
```typescript
|
|
71
|
-
import {
|
|
72
|
-
|
|
73
|
-
interface StackType<T> {
|
|
74
|
-
readonly limit: number;
|
|
75
|
-
readonly size: number;
|
|
76
|
-
clear(): void;
|
|
77
|
-
isEmpty(): boolean;
|
|
78
|
-
isFull(): boolean;
|
|
79
|
-
pop(): T;
|
|
80
|
-
push(item: T): void;
|
|
81
|
-
top(): T;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const stackContract = new Contract<StackType<any>>({
|
|
85
|
-
[checkedMode]: process.env.NODE_ENV === 'development',
|
|
86
|
-
[invariant](self) {
|
|
87
|
-
return self.isEmpty() == (self.size == 0) &&
|
|
88
|
-
self.isFull() == (self.size == self.limit) &&
|
|
89
|
-
self.size >= 0 && self.size <= self.limit;
|
|
90
|
-
},
|
|
91
|
-
pop: {
|
|
92
|
-
demands(self) { return !self.isEmpty(); },
|
|
93
|
-
ensures(self,old) {
|
|
94
|
-
return !self.isFull() &&
|
|
95
|
-
self.size == old.size - 1;
|
|
96
|
-
}
|
|
97
|
-
},
|
|
98
|
-
push: {
|
|
99
|
-
demands(self){ return !self.isFull(); },
|
|
100
|
-
ensures(self, old, item) {
|
|
101
|
-
return !self.isEmpty() &&
|
|
102
|
-
self.top() === item &&
|
|
103
|
-
self.size === old.size + 1;
|
|
104
|
-
}
|
|
105
|
-
},
|
|
106
|
-
top: {
|
|
107
|
-
demands(self) {
|
|
108
|
-
return !self.isEmpty();
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
});
|
|
70
|
+
import { Contracted, invariant, demands, ensures } from '@final-hill/decorator-contracts';
|
|
112
71
|
|
|
113
|
-
@
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
72
|
+
@invariant((self: Stack<any>) =>
|
|
73
|
+
self.isEmpty() == (self.size == 0) &&
|
|
74
|
+
self.isFull() == (self.size == self.limit) &&
|
|
75
|
+
self.size >= 0 && self.size <= self.limit
|
|
76
|
+
)
|
|
77
|
+
class Stack<T> extends Contracted {
|
|
78
|
+
private _implementation: T[] = [];
|
|
79
|
+
private _size = 0;
|
|
80
|
+
private _limit: number;
|
|
118
81
|
|
|
119
82
|
constructor(limit: number) {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
clear(): void {
|
|
124
|
-
this.#implementation = [];
|
|
125
|
-
this.#size = 0;
|
|
83
|
+
super();
|
|
84
|
+
this._limit = limit;
|
|
126
85
|
}
|
|
127
86
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
}
|
|
87
|
+
get limit() { return this._limit; }
|
|
88
|
+
get size() { return this._size; }
|
|
131
89
|
|
|
132
|
-
|
|
133
|
-
|
|
90
|
+
clear(): void {
|
|
91
|
+
this._implementation = [];
|
|
92
|
+
this._size = 0;
|
|
134
93
|
}
|
|
135
94
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
95
|
+
isEmpty(): boolean { return this._implementation.length == 0; }
|
|
96
|
+
isFull(): boolean { return this._implementation.length == this.limit; }
|
|
139
97
|
|
|
98
|
+
@demands((self: Stack<any>) => !self.isEmpty())
|
|
99
|
+
@ensures((self: Stack<any>, _args, old: Stack<any>) =>
|
|
100
|
+
!self.isFull() && self.size == old.size - 1)
|
|
140
101
|
pop(): T {
|
|
141
|
-
this
|
|
142
|
-
|
|
143
|
-
return this.#implementation.pop()!;
|
|
102
|
+
this._size--;
|
|
103
|
+
return this._implementation.pop()!;
|
|
144
104
|
}
|
|
145
105
|
|
|
106
|
+
@demands((self: Stack<any>) => !self.isFull())
|
|
107
|
+
@ensures((self, [item], old: Stack<any>) =>
|
|
108
|
+
!self.isEmpty() &&
|
|
109
|
+
self.top === item &&
|
|
110
|
+
self.size === old.size + 1
|
|
111
|
+
)
|
|
146
112
|
push(item: T): void {
|
|
147
|
-
this
|
|
148
|
-
this
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
get size(): number {
|
|
152
|
-
return this.#size;
|
|
113
|
+
this._size++;
|
|
114
|
+
this._implementation.push(item);
|
|
153
115
|
}
|
|
154
116
|
|
|
155
|
-
top(): T {
|
|
156
|
-
return this
|
|
117
|
+
get top(): T | undefined {
|
|
118
|
+
return this._implementation.at(-1);
|
|
157
119
|
}
|
|
158
120
|
}
|
|
159
|
-
```
|
|
160
121
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
const fooContract = new Contract<Foo>({
|
|
166
|
-
[checkedMode]: true,
|
|
167
|
-
[invariant](self: Foo) { return self instanceof Foo },
|
|
168
|
-
methodName: {
|
|
169
|
-
demands(self: Foo, arg1, arg2, argN) { return true },
|
|
170
|
-
ensures(self: Foo, old: Foo, arg1, arg2, argN){ return true }
|
|
171
|
-
rescue(self, error, args, retry) {
|
|
172
|
-
console.error(`Error with given arguments ${JSON.stringify(args)}`)
|
|
173
|
-
console.error(error)
|
|
174
|
-
console.log('Attempting to retry')
|
|
175
|
-
self.value = 7
|
|
176
|
-
retry(...args)
|
|
177
|
-
}
|
|
178
|
-
},
|
|
179
|
-
accessorName: {
|
|
180
|
-
...
|
|
181
|
-
}
|
|
182
|
-
})
|
|
183
|
-
|
|
184
|
-
const subContract = new Contract<Sub>({
|
|
185
|
-
[extend]: fooContract,
|
|
186
|
-
methodName: {
|
|
187
|
-
demands(self: Foo){ return true }
|
|
188
|
-
}
|
|
189
|
-
})
|
|
122
|
+
const stack = Stack.new(3);
|
|
123
|
+
stack.push(1);
|
|
124
|
+
stack.push(2);
|
|
125
|
+
stack.pop();
|
|
190
126
|
```
|
|
191
127
|
|
|
192
|
-
##
|
|
128
|
+
## Instantiation: Using the Static `.new(...)` Method
|
|
193
129
|
|
|
194
|
-
|
|
130
|
+
Because this library uses JavaScript `Proxy` to enforce contracts, you **must** instantiate all classes that extend `Contracted` using the static `.new(...)` method (not with `new MyClass(...)`).
|
|
195
131
|
|
|
196
|
-
|
|
197
|
-
const stackContract = new Contract<StackType<any>>({
|
|
198
|
-
[checkedMode]: true,
|
|
199
|
-
...
|
|
200
|
-
})
|
|
201
|
-
```
|
|
132
|
+
This is required so that the instance is wrapped in a Proxy and invariants are asserted immediately after construction. Direct use of the `new` keyword will throw an error.
|
|
202
133
|
|
|
203
|
-
|
|
204
|
-
enable all assertion checks. In production all assertion checks become
|
|
205
|
-
no-ops for run-time efficiency. As the number of contract definitions can
|
|
206
|
-
be numerous, using the appropriate mode becomes increasingly important.
|
|
207
|
-
|
|
208
|
-
You are not prevented from mixing modes in the event you desire to maintain
|
|
209
|
-
a number of checks in a production environment.
|
|
134
|
+
## Checked Mode
|
|
210
135
|
|
|
211
|
-
|
|
136
|
+
Checked Mode controls whether contract checking (invariants, demands, ensures, and rescue) is enabled or disabled at runtime. This feature allows you to turn off contract enforcement in production environments for maximum performance, while keeping it enabled during development and testing to catch bugs and contract violations early.
|
|
212
137
|
|
|
213
|
-
|
|
138
|
+
By default, Checked Mode is enabled. You can control it via the static `[checkedMode]` symbol property of Contracted:
|
|
214
139
|
|
|
215
|
-
```
|
|
216
|
-
|
|
217
|
-
[checkedMode]: !process.env.IS_PRODUCTION,
|
|
218
|
-
...
|
|
219
|
-
})
|
|
140
|
+
```typescript
|
|
141
|
+
Contracted[checkedMode] = false; // Disable Checked Mode
|
|
220
142
|
```
|
|
221
143
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
144
|
+
One approach to managing this is to leverage environment variables. For example, you can interrogate `NODE_ENV` to determine whether to enable or disable Checked Mode:
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
Contracted[checkedMode] = process.env.NODE_ENV === 'development'
|
|
148
|
+
```
|
|
225
149
|
|
|
226
150
|
## Assertions
|
|
227
151
|
|
|
228
|
-
|
|
229
|
-
They are used inline to express a condition that must evaluate to true at a
|
|
230
|
-
particular point of execution.
|
|
152
|
+
Use the `assert` function for inline assertions:
|
|
231
153
|
|
|
232
154
|
```typescript
|
|
233
|
-
import {assert} from '@final-hill/decorator-contracts';
|
|
155
|
+
import { assert } from '@final-hill/decorator-contracts';
|
|
234
156
|
|
|
235
157
|
function avg(xs: number[]): number {
|
|
236
|
-
assert(xs.length > 0, 'The list can not be empty')
|
|
237
|
-
|
|
238
|
-
return xs.reduce((sum, next) => sum + next) / xs.length
|
|
158
|
+
assert(xs.length > 0, 'The list can not be empty');
|
|
159
|
+
return xs.reduce((sum, next) => sum + next) / xs.length;
|
|
239
160
|
}
|
|
240
161
|
```
|
|
241
162
|
|
|
242
|
-
If you are using TypeScript `assert` will also assert the type of the condition:
|
|
163
|
+
If you are using TypeScript, `assert` will also assert the type of the condition:
|
|
243
164
|
|
|
244
165
|
```typescript
|
|
245
166
|
let str: any = 'foo';
|
|
@@ -253,561 +174,206 @@ str.toUpperCase(); // str is now a string
|
|
|
253
174
|
|
|
254
175
|
**`assert` should not be used for validating arguments**
|
|
255
176
|
|
|
256
|
-
Use the
|
|
177
|
+
Use the `@demands` decorator for this purpose.
|
|
257
178
|
|
|
258
179
|
## Implies
|
|
259
180
|
|
|
260
|
-
When defining predicates it is a common use case to encode
|
|
261
|
-
[material implication](https://en.wikipedia.org/wiki/Material_conditional).
|
|
262
|
-
|
|
263
|
-
The truth table is as follows:
|
|
264
|
-
|
|
265
|
-
| *p* | *q* | *p* → *q* |
|
|
266
|
-
|-----|-----|----------------|
|
|
267
|
-
| T | T | T |
|
|
268
|
-
| T | F | F |
|
|
269
|
-
| F | T | T |
|
|
270
|
-
| F | F | T |
|
|
181
|
+
When defining predicates it is a common use case to encode [material implication](https://en.wikipedia.org/wiki/Material_conditional):
|
|
271
182
|
|
|
272
|
-
|
|
183
|
+
```typescript
|
|
184
|
+
import { implies } from '@final-hill/decorator-contracts';
|
|
273
185
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
weather.isSunny,
|
|
277
|
-
person.visitsBeach
|
|
278
|
-
)
|
|
186
|
+
implies(weather.isSunny, person.visitsBeach);
|
|
187
|
+
// Equivalent to: !weather.isSunny || person.visitsBeach
|
|
279
188
|
```
|
|
280
189
|
|
|
281
|
-
This is logically equivalent to: `!p || q`
|
|
282
|
-
|
|
283
190
|
## Iff
|
|
284
191
|
|
|
285
|
-
When defining predicates it is a common use case to encode [if and only if](https://en.wikipedia.org/wiki/Logical_biconditional)
|
|
286
|
-
Also referred to as a biconditional.
|
|
287
|
-
|
|
288
|
-
The truth table is as follows:
|
|
289
|
-
|
|
290
|
-
| *p* | *q* | *p* ↔ *q* |
|
|
291
|
-
|-----|-----|----------------|
|
|
292
|
-
| T | T | T |
|
|
293
|
-
| T | F | F |
|
|
294
|
-
| F | T | F |
|
|
295
|
-
| F | F | T |
|
|
192
|
+
When defining predicates it is a common use case to encode [if and only if](https://en.wikipedia.org/wiki/Logical_biconditional):
|
|
296
193
|
|
|
297
|
-
|
|
194
|
+
```typescript
|
|
195
|
+
import { iff } from '@final-hill/decorator-contracts';
|
|
298
196
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
person.hasTicket,
|
|
302
|
-
person.ridesTrain
|
|
303
|
-
)
|
|
197
|
+
iff(person.hasTicket, person.ridesTrain);
|
|
198
|
+
// Equivalent to: implies(p, q) && implies(q, p)
|
|
304
199
|
```
|
|
305
200
|
|
|
306
|
-
This is logically equivalent to: `implies(p,q) && implies(q,p)`
|
|
307
|
-
|
|
308
201
|
## Encapsulation
|
|
309
202
|
|
|
310
|
-
To guarantee invariants remain valid for classes, public property definitions are forbidden.
|
|
311
|
-
All interactions with a contracted class must be done through a method or accessor.
|
|
312
|
-
This prevents modification of object state outside of the contract system. Private
|
|
313
|
-
properties with accessors should be used instead. Example:
|
|
314
|
-
|
|
315
|
-
```ts
|
|
316
|
-
@Contracted(pointContract)
|
|
317
|
-
class Point2D {
|
|
318
|
-
accessor x: number
|
|
319
|
-
accessor y: number
|
|
320
|
-
|
|
321
|
-
constructor(x: number, y: number) {
|
|
322
|
-
super()
|
|
323
|
-
this.x = x
|
|
324
|
-
this.y = y
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
```
|
|
328
|
-
|
|
329
|
-
## Invariants
|
|
330
|
-
|
|
331
|
-
A class is not just a collection of methods it has semantics that
|
|
332
|
-
bind them together and the `invariant` declaration describes and enforces these relationships.
|
|
333
|
-
This assertion is checked after the associated class is constructed, before and
|
|
334
|
-
after every method execution, and before and after every accessor usage (get/set).
|
|
335
|
-
If this evaluates to false during class usage an `AssertionError` will be thrown in the library code
|
|
336
|
-
as it indicates a bug in the class where it has the [opportunity](#rescue) to handle it.
|
|
337
|
-
True assertions do not throw an error. An example of this is given below using a Stack:
|
|
203
|
+
To guarantee invariants remain valid for classes, public property definitions are forbidden. All interactions with a contracted class must be done through a method or getter/setter. Only properties that start with `_` (conventionally private) can be assigned to after construction.
|
|
338
204
|
|
|
339
205
|
```typescript
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
self.isFull() == (self.size == self.limit) &&
|
|
344
|
-
self.size >= 0 && self.size <= self.limit
|
|
345
|
-
}
|
|
346
|
-
})
|
|
347
|
-
|
|
348
|
-
@Contracted(stackContract)
|
|
349
|
-
class Stack<T> implements StackType<T> {
|
|
350
|
-
...
|
|
206
|
+
class Example extends Contracted {
|
|
207
|
+
_private = 1; // Allowed
|
|
208
|
+
publicProp = 2; // Not allowed
|
|
351
209
|
}
|
|
352
210
|
```
|
|
353
211
|
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
```typescript
|
|
357
|
-
let myStack = new Stack(-1)
|
|
358
|
-
```
|
|
212
|
+
## Note on Private Fields and Accessors
|
|
359
213
|
|
|
360
|
-
|
|
361
|
-
nonsensical according to the invariant therefore the following will
|
|
362
|
-
throw an `AssertionError` after `pop()` is executed due to the size being negative:
|
|
214
|
+
Due to the use of JavaScript `Proxy` in the implementation of this library, native `#private` fields and the `accessor` keyword are **not supported**. Instead, use conventional private fields (e.g., `_private`) and define explicit getter/setter pairs for encapsulation:
|
|
363
215
|
|
|
364
216
|
```typescript
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
```typescript
|
|
372
|
-
const baseContract = new Contract<Base>({
|
|
373
|
-
[invariant](self) { return 0 <= self.value && self.value <= 10 }
|
|
374
|
-
})
|
|
375
|
-
|
|
376
|
-
@Contracted(baseContract)
|
|
377
|
-
class Base { ... }
|
|
378
|
-
|
|
379
|
-
const subContract = new Contract<Sub>({
|
|
380
|
-
[extend]: baseContract,
|
|
381
|
-
[invariant](self){ return 10 <= self.value && self.value <= 20 }
|
|
382
|
-
})
|
|
383
|
-
|
|
384
|
-
@Contracted(subContract)
|
|
385
|
-
class Sub extends Base { ... }
|
|
217
|
+
class Example extends Contracted {
|
|
218
|
+
private _value = 0;
|
|
219
|
+
get value() { return this._value; }
|
|
220
|
+
set value(v: number) { this._value = v; }
|
|
221
|
+
}
|
|
386
222
|
```
|
|
387
223
|
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
`(0 <= self.value && self.value <= 10) && (10 <= self.value && self.value <= 20)`
|
|
224
|
+
Do **not** use:
|
|
391
225
|
|
|
392
|
-
|
|
226
|
+
- `#privateField` syntax
|
|
227
|
+
- `accessor foo` syntax
|
|
393
228
|
|
|
394
|
-
|
|
229
|
+
These will not work correctly with the contract enforcement provided by this library.
|
|
395
230
|
|
|
396
|
-
##
|
|
231
|
+
## Invariants
|
|
397
232
|
|
|
398
|
-
|
|
399
|
-
before its associated feature can execute. In other words before a client
|
|
400
|
-
of your class can execute a method or accessor the defined precondition
|
|
401
|
-
must first be met or an error will be raised [to the caller](#the-order-of-assertions).
|
|
402
|
-
This is because a failure to meet the precondition indicates a bug in the caller's code
|
|
403
|
-
and not yours.
|
|
233
|
+
Use the `@invariant` decorator on your class to enforce relationships between properties and methods. The invariant is checked after construction, before and after every method execution, and before and after every get/set usage.
|
|
404
234
|
|
|
405
235
|
```typescript
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
}
|
|
414
|
-
})
|
|
415
|
-
|
|
416
|
-
@Contracted(stackContract)
|
|
417
|
-
class Stack<T> implements StackType<T> {
|
|
418
|
-
...
|
|
419
|
-
pop(): T {
|
|
420
|
-
return this.#implementation.pop();
|
|
421
|
-
}
|
|
422
|
-
push(item: T): void {
|
|
423
|
-
this.#implementation.push(item);
|
|
424
|
-
}
|
|
236
|
+
@invariant(self => self.value >= 0)
|
|
237
|
+
class Foo extends Contracted {
|
|
238
|
+
protected _value = 0;
|
|
239
|
+
get value() { return this._value; }
|
|
240
|
+
set value(v: number) { this._value = v; }
|
|
241
|
+
|
|
242
|
+
inc(): void { this.value++; }
|
|
243
|
+
dec(): void { this.value--; }
|
|
425
244
|
}
|
|
426
245
|
```
|
|
427
246
|
|
|
428
|
-
|
|
429
|
-
on a stack is that it is not empty. If this assertion fails
|
|
430
|
-
an `AssertionError` is raised.
|
|
431
|
-
|
|
432
|
-
Static features, including the constructor, cannot be assigned a `demands`
|
|
433
|
-
assertion. In the future this may be enabled for non-constructor static methods
|
|
434
|
-
but the implications are not clear at present.
|
|
247
|
+
### Subcontracting and Invariants
|
|
435
248
|
|
|
436
|
-
|
|
249
|
+
When subclassing, if a subclass defines its own `@invariant`, the resulting invariant is **strengthened**: the subclass invariant and the base class invariant are both enforced (they are logically AND-ed together). This means all invariants in the inheritance chain must hold for the object to be valid.
|
|
437
250
|
|
|
438
251
|
```typescript
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
...
|
|
444
|
-
let myStack = new MyStack()
|
|
445
|
-
|
|
446
|
-
myStack.pop() // throws
|
|
447
|
-
```
|
|
448
|
-
|
|
449
|
-
A contract can be extended and that sub contract can declare a `demands` assertion of its own
|
|
450
|
-
for the same feature:
|
|
451
|
-
|
|
452
|
-
```ts
|
|
453
|
-
const baseContract = new Contract<Base>({
|
|
454
|
-
someMethod: {
|
|
455
|
-
demands(){ ... }
|
|
456
|
-
}
|
|
457
|
-
})
|
|
458
|
-
|
|
459
|
-
const subContract = new Contract<Sub>({
|
|
460
|
-
[extend]: baseContract,
|
|
461
|
-
someMethod: {
|
|
462
|
-
demands(){ ... }
|
|
463
|
-
}
|
|
464
|
-
})
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
This subcontracted `demands` declaration can not strengthen the `demands` of the base contract.
|
|
468
|
-
What this means is that the new precondition will be or-ed with its ancestors. If any `demand` is true
|
|
469
|
-
then the obligation is considered fulfilled by the user of the feature.
|
|
470
|
-
|
|
471
|
-
```ts
|
|
472
|
-
const baseContract = new Contract<Base>({
|
|
473
|
-
someMethod: {
|
|
474
|
-
demands(_self, x: number) { return 0 <= x && x <= 10 }
|
|
475
|
-
}
|
|
476
|
-
})
|
|
477
|
-
|
|
478
|
-
@Contracted(baseContract)
|
|
479
|
-
class Base {
|
|
480
|
-
someMethod(x: number) { ... }
|
|
252
|
+
@invariant(self => self.value >= 0)
|
|
253
|
+
class Base extends Contracted {
|
|
254
|
+
// ...
|
|
481
255
|
}
|
|
482
256
|
|
|
483
|
-
|
|
484
|
-
[extend]: baseContract,
|
|
485
|
-
someMethod: {
|
|
486
|
-
demands(_self, x: number){ return -10 <= x && x <= 20 }
|
|
487
|
-
}
|
|
488
|
-
})
|
|
489
|
-
|
|
490
|
-
@Contracted(subContract)
|
|
257
|
+
@invariant(self => self.value <= 10)
|
|
491
258
|
class Sub extends Base {
|
|
492
|
-
|
|
259
|
+
// ...
|
|
493
260
|
}
|
|
261
|
+
// The effective invariant for Sub is: (self.value >= 0) && (self.value <= 10)
|
|
494
262
|
```
|
|
495
263
|
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
`(-10 <= x && x <= 20) || (0 <= x && x <= 10)`
|
|
499
|
-
|
|
500
|
-
## Ensures
|
|
264
|
+
## Demands
|
|
501
265
|
|
|
502
|
-
|
|
503
|
-
caller. The library code then has the [opportunity](#rescue) to capture and fix this error if it's expected.
|
|
266
|
+
Use the `@demands` decorator to specify preconditions for methods or get/set. If the condition fails, an error is thrown before the method executes.
|
|
504
267
|
|
|
505
268
|
```typescript
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
class Stack<T> {
|
|
514
|
-
...
|
|
515
|
-
push(value: T) {
|
|
516
|
-
...
|
|
517
|
-
this.#implementation.push(value);
|
|
518
|
-
}
|
|
269
|
+
class Foo extends Contracted {
|
|
270
|
+
protected _value = 0;
|
|
271
|
+
get value() { return this._value; }
|
|
272
|
+
set value(v: number) { this._value = v; }
|
|
273
|
+
|
|
274
|
+
@demands(self => self.value >= 0)
|
|
275
|
+
dec(): void { this.value--; }
|
|
519
276
|
}
|
|
520
277
|
```
|
|
521
278
|
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
Static features, including the constructor, cannot be assigned an `ensures` declaration. In the future this may be enabled for non-constructor static methods but the implications are not clear at present.
|
|
279
|
+
### Subcontracting and Demands
|
|
525
280
|
|
|
526
|
-
|
|
281
|
+
When subclassing, if a subclass defines its own `@demands` for a method, the resulting precondition is **weakened**: the subclass and base class demands are OR-ed together. The method can be called if **any** of the demands in the inheritance chain are satisfied.
|
|
527
282
|
|
|
528
283
|
```typescript
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
},
|
|
533
|
-
pop: {
|
|
534
|
-
ensures(self, old){ return self.size == old.size - 1 }
|
|
535
|
-
}
|
|
536
|
-
})
|
|
537
|
-
|
|
538
|
-
@Contracted(stackContract)
|
|
539
|
-
class Stack<T> {
|
|
540
|
-
...
|
|
541
|
-
push(value: T) {
|
|
542
|
-
this.#implementation.push(value);
|
|
543
|
-
}
|
|
544
|
-
pop(): T {
|
|
545
|
-
return this.#implementation.pop();
|
|
546
|
-
}
|
|
284
|
+
class Base extends Contracted {
|
|
285
|
+
@demands((_self, x: number) => x >= 0)
|
|
286
|
+
foo(x: number) { /* ... */ }
|
|
547
287
|
}
|
|
548
|
-
```
|
|
549
|
-
|
|
550
|
-
If a class feature is overridden then the `ensures` assertion still applies:
|
|
551
288
|
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
override
|
|
289
|
+
class Sub extends Base {
|
|
290
|
+
@demands((_self, x: number) => x === 42)
|
|
291
|
+
override foo(x: number) { /* ... */ }
|
|
555
292
|
}
|
|
556
|
-
|
|
557
|
-
...
|
|
558
|
-
let myStack = new MyStack()
|
|
559
|
-
|
|
560
|
-
myStack.push()
|
|
561
|
-
myStack.isEmpty() == false;
|
|
293
|
+
// The effective demand for Sub#foo is: (x >= 0) || (x === 42)
|
|
562
294
|
```
|
|
563
295
|
|
|
564
|
-
|
|
296
|
+
## Ensures
|
|
297
|
+
|
|
298
|
+
Use the `@ensures` decorator to specify postconditions for methods or get/set. If the condition fails, an error is thrown after the method executes.
|
|
565
299
|
|
|
566
300
|
```typescript
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
}
|
|
571
|
-
})
|
|
301
|
+
class Foo extends Contracted {
|
|
302
|
+
protected _value = 0;
|
|
303
|
+
get value() { return this._value; }
|
|
304
|
+
set value(v: number) { this._value = v; }
|
|
572
305
|
|
|
573
|
-
@
|
|
574
|
-
|
|
575
|
-
someMethod(x: number) { ... }
|
|
306
|
+
@ensures(self => self.value >= 0)
|
|
307
|
+
dec(): void { this.value--; }
|
|
576
308
|
}
|
|
577
309
|
```
|
|
578
310
|
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
```ts
|
|
582
|
-
const baseContract = new Contract<Base>({
|
|
583
|
-
someMethod: {
|
|
584
|
-
ensures(){ ... }
|
|
585
|
-
}
|
|
586
|
-
})
|
|
311
|
+
### Subcontracting and Ensures
|
|
587
312
|
|
|
588
|
-
|
|
589
|
-
[extend]: baseContract,
|
|
590
|
-
someMethod: {
|
|
591
|
-
ensures(){ ... }
|
|
592
|
-
}
|
|
593
|
-
})
|
|
594
|
-
```
|
|
595
|
-
|
|
596
|
-
This subcontracted `ensures` declaration cannot weaken the `ensures` of the base contract. What this means is that the new post-condition will be and-ed with its ancestors. If all of the `ensures` are true then the obligation is considered fulfilled by the author of the feature otherwise an `AssertionError` is raised.
|
|
313
|
+
When subclassing, if a subclass defines its own `@ensures` for a method, the resulting postcondition is **strengthened**: the subclass and base class ensures are AND-ed together. The method's result must satisfy **all** ensures in the inheritance chain.
|
|
597
314
|
|
|
598
315
|
```typescript
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
}
|
|
603
|
-
})
|
|
604
|
-
|
|
605
|
-
@Contracted(baseContract)
|
|
606
|
-
class Base {
|
|
607
|
-
method(x: number){ ... }
|
|
316
|
+
class Base extends Contracted {
|
|
317
|
+
@ensures((_self, _args, x: number) => x >= 0)
|
|
318
|
+
foo(x: number) { /* ... */ }
|
|
608
319
|
}
|
|
609
320
|
|
|
610
|
-
const subContract = new Contract<Sub>({
|
|
611
|
-
[extend]: baseContract,
|
|
612
|
-
method: {
|
|
613
|
-
ensures(_self, _old, x: number){ return -10 <= x && x <= 20 }
|
|
614
|
-
}
|
|
615
|
-
})
|
|
616
|
-
|
|
617
|
-
@Contracted(subContract)
|
|
618
321
|
class Sub extends Base {
|
|
619
|
-
|
|
322
|
+
@ensures((_self, _args, x: number) => x <= 10)
|
|
323
|
+
override foo(x: number) { /* ... */ }
|
|
620
324
|
}
|
|
325
|
+
// The effective ensures for Sub#foo is: (x >= 0) && (x <= 10)
|
|
621
326
|
```
|
|
622
327
|
|
|
623
|
-
In the above example the post-condition of `Sub.prototype.method` is:
|
|
624
|
-
|
|
625
|
-
`(-10 <= x && x <= 20) && (0 <= x && x <= 10)`
|
|
626
|
-
|
|
627
|
-
Which effectively means that if the method returns `x === 10`
|
|
628
|
-
|
|
629
|
-
## Within
|
|
630
|
-
|
|
631
|
-
The `within` declaration provides a means of requiring the associated feature
|
|
632
|
-
to complete execution within a time constraint.
|
|
633
|
-
|
|
634
|
-
```typescript
|
|
635
|
-
const timingContract = new Contract<Spinner>({
|
|
636
|
-
spinLock: {
|
|
637
|
-
within: 100
|
|
638
|
-
}
|
|
639
|
-
});
|
|
640
|
-
|
|
641
|
-
@Contracted(timingContract)
|
|
642
|
-
class Spinner {
|
|
643
|
-
spinLock(delay: number) {
|
|
644
|
-
const t1 = Date.now();
|
|
645
|
-
while(Date.now() - t1 < delay) {
|
|
646
|
-
continue;
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
return 'Okay';
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
new Ticker().spinLock(50) === 'Okay';
|
|
654
|
-
|
|
655
|
-
new Ticker().spinLock(500) // throws "Timing constraint violated...";
|
|
656
|
-
```
|
|
657
|
-
|
|
658
|
-
Currently `within` only supports synchronous features. async feature support is planned for a future version
|
|
659
|
-
|
|
660
328
|
## Rescue
|
|
661
329
|
|
|
662
|
-
|
|
663
|
-
Robustness is the ability of an implementation to respond to situations
|
|
664
|
-
not specified; in other words the ability to handle exceptions (pun intended).
|
|
665
|
-
This declaration can be associated with class features. The intent of this
|
|
666
|
-
is to restore any invariants of the class and optionally retry execution.
|
|
330
|
+
Use the `@rescue` decorator to handle exceptions thrown by a method, restore invariants, or retry execution:
|
|
667
331
|
|
|
668
332
|
```typescript
|
|
669
|
-
|
|
670
|
-
pop: {
|
|
671
|
-
rescue(_self, error, _args, _retry) {
|
|
672
|
-
console.log(error)
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
})
|
|
333
|
+
import { rescue } from '@final-hill/decorator-contracts';
|
|
676
334
|
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
assert(!this.isEmpty(), 'You can not pop from an empty stack')
|
|
335
|
+
class Example extends Contracted {
|
|
336
|
+
private _value = 3;
|
|
337
|
+
get value() { return this._value; }
|
|
338
|
+
set value(v) { this._value = v; }
|
|
682
339
|
|
|
683
|
-
|
|
684
|
-
}
|
|
685
|
-
...
|
|
340
|
+
@rescue(self => self.value = 5)
|
|
341
|
+
method1(): void { throw new Error('I am error'); }
|
|
686
342
|
}
|
|
687
343
|
```
|
|
688
344
|
|
|
689
|
-
|
|
690
|
-
empty an exception occurs. The `rescue` declaration intercepts this
|
|
691
|
-
exception and handles it by simply logging the error. The exception is
|
|
692
|
-
then raised to the caller.
|
|
693
|
-
|
|
694
|
-
You also have the ability to retry the execution of the decorated
|
|
695
|
-
feature from the beginning by calling the `retry` function. This provides
|
|
696
|
-
a mechanism for [fault tolerance](https://en.wikipedia.org/wiki/Fault_tolerance).
|
|
697
|
-
When `retry` is called the exception will no longer be raised to the caller of the original method.
|
|
698
|
-
`retry` can only be called once per exception rescue in order to prevent unbounded
|
|
699
|
-
recursion. An example of `retry` usage:
|
|
700
|
-
|
|
701
|
-
```ts
|
|
702
|
-
const studentRepositoryContract = new Contract<StudentRepository>({
|
|
703
|
-
getStudent: {
|
|
704
|
-
rescue(_self, error, [id], retry) {
|
|
705
|
-
console.error(error)
|
|
706
|
-
console.log('Retrying with legacy id...')
|
|
707
|
-
retry(`old-${id}`)
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
})
|
|
711
|
-
|
|
712
|
-
@Contracted(studentRepositoryContract)
|
|
713
|
-
class StudentRepository {
|
|
714
|
-
...
|
|
715
|
-
async getStudent(id: string): Student {
|
|
716
|
-
const data = await fetch(`/repos/students/${id}`).then(response => response.json())
|
|
345
|
+
You can also use the `retry` function in your rescue handler to attempt the method again:
|
|
717
346
|
|
|
718
|
-
|
|
347
|
+
```typescript
|
|
348
|
+
class Example extends Contracted {
|
|
349
|
+
@rescue((_self, _error, _args, retry) => retry(3))
|
|
350
|
+
method(value: number): number {
|
|
351
|
+
if (value <= 0)
|
|
352
|
+
throw new Error('value must be greater than 0');
|
|
353
|
+
else
|
|
354
|
+
return value;
|
|
719
355
|
}
|
|
720
356
|
}
|
|
721
357
|
```
|
|
722
358
|
|
|
723
|
-
|
|
724
|
-
is defined on the current class:
|
|
725
|
-
|
|
726
|
-
```ts
|
|
727
|
-
const baseContract = new Contract<Base>({
|
|
728
|
-
myMethod: {
|
|
729
|
-
rescue(self, error, args, retry){ ... }
|
|
730
|
-
}
|
|
731
|
-
})
|
|
732
|
-
|
|
733
|
-
@Contracted(baseContract)
|
|
734
|
-
class Base {
|
|
735
|
-
...
|
|
736
|
-
myMethod(){ ... }
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
class Sub extends Base {
|
|
740
|
-
override myMethod(){ ... throw new Error('BOOM!') ... }
|
|
741
|
-
}
|
|
742
|
-
```
|
|
359
|
+
### Robustness, Organized Panic, and the Benefits of `@rescue`
|
|
743
360
|
|
|
744
|
-
|
|
745
|
-
[N-Version programming](https://en.wikipedia.org/wiki/N-version_programming)
|
|
746
|
-
to enable [Fault-Tolerance](https://en.wikipedia.org/wiki/Fault_tolerance)
|
|
747
|
-
and [Redundancy](https://en.wikipedia.org/wiki/Redundancy_(engineering)).
|
|
748
|
-
|
|
749
|
-
A dated example of this is performing ajax requests in multi-browser environments where `fetch` may not exist:
|
|
750
|
-
|
|
751
|
-
```ts
|
|
752
|
-
const ajaxRequestContract = new Contract<AjaxRequest>({
|
|
753
|
-
get: {
|
|
754
|
-
rescue(self, _error, [url], retry) {
|
|
755
|
-
self.attempts++
|
|
756
|
-
if(self.attempts < 2)
|
|
757
|
-
retry(url)
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
})
|
|
361
|
+
The `@rescue` decorator enables a mechanism for **Robustness** in your code. It allows your implementation to respond to situations not specified, providing the ability to handle exceptions in a structured way. This is sometimes called **Organized Panic**.
|
|
761
362
|
|
|
762
|
-
|
|
763
|
-
class AjaxRequest {
|
|
764
|
-
#attempts = 0
|
|
363
|
+
In addition, `@rescue` provides a foundation for **N-Version programming**, **Fault-Tolerance**, and **Redundancy**. You can implement multiple strategies for handling errors, retrying with alternative logic or data, and ensuring your application can recover from unexpected failures.
|
|
765
364
|
|
|
766
|
-
|
|
767
|
-
set attempts(value: number) { this.#attempts = value }
|
|
365
|
+
Unlike traditional `try/catch`, where exceptions are non-resumable and often handled far from the source (leading to scattered and redundant error handling), `@rescue` allows for **resumable exceptions** and localized, declarative error handling. This means:
|
|
768
366
|
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
return this.getXhr(url)
|
|
774
|
-
}
|
|
367
|
+
- You can lexically determine where exception handling occurs.
|
|
368
|
+
- You can restore invariants or perform corrective actions before retrying or failing.
|
|
369
|
+
- You can optionally call `retry` to attempt the method again with new arguments or after fixing state, providing a form of fault tolerance and robustness.
|
|
370
|
+
- You can implement alternative strategies for error recovery, supporting N-Version programming and redundancy.
|
|
775
371
|
|
|
776
|
-
|
|
777
|
-
return await fetch(url)
|
|
778
|
-
}
|
|
372
|
+
**Inheritance:**
|
|
779
373
|
|
|
780
|
-
|
|
781
|
-
return await new Promise((resolve, reject) => {
|
|
782
|
-
const xhr = new XMLHttpRequest();
|
|
783
|
-
xhr.open('GET', url);
|
|
784
|
-
xhr.onload = function() {
|
|
785
|
-
if (this.status >= 200 && this.status < 300) {
|
|
786
|
-
resolve(xhr.response);
|
|
787
|
-
} else {
|
|
788
|
-
reject({
|
|
789
|
-
status: this.status,
|
|
790
|
-
statusText: xhr.statusText
|
|
791
|
-
});
|
|
792
|
-
}
|
|
793
|
-
};
|
|
794
|
-
xhr.onerror = function() {
|
|
795
|
-
reject({
|
|
796
|
-
status: this.status,
|
|
797
|
-
statusText: xhr.statusText
|
|
798
|
-
});
|
|
799
|
-
};
|
|
800
|
-
xhr.send();
|
|
801
|
-
})
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
```
|
|
374
|
+
If a base class declares a `@rescue` handler for a method, that handler is inherited by subclasses unless the subclass overrides it with its own `@rescue` declaration. This ensures that robust error handling is preserved throughout the inheritance chain, unless explicitly changed.
|
|
805
375
|
|
|
806
|
-
|
|
807
|
-
and indirectly related to the source, and probably redundantly across the callers,
|
|
808
|
-
you can see from the above examples that the `rescue` mechanism enables resumable exceptions and
|
|
809
|
-
"[Organized Panic](https://en.wikipedia.org/wiki/Exception_handling#Exception_handling_based_on_design_by_contract)"
|
|
810
|
-
where you can lexically determine where the handling occurs and optionally perform changes and retry the feature call.
|
|
376
|
+
This approach leads to more maintainable and robust code, as error handling is organized and closely tied to the contract of the class feature, rather than being scattered throughout the call stack.
|
|
811
377
|
|
|
812
378
|
## The order of assertions
|
|
813
379
|
|
|
@@ -815,22 +381,15 @@ When `obj.feature` is called the happy path is:
|
|
|
815
381
|
|
|
816
382
|

|
|
817
383
|
|
|
818
|
-
If an error is thrown and there is no
|
|
819
|
-
is checked before the error is raised to the caller.
|
|
384
|
+
If an error is thrown and there is no `@rescue` defined then the `@invariant` is checked before the error is raised to the caller.
|
|
820
385
|
|
|
821
|
-
If an error is thrown in the
|
|
386
|
+
If an error is thrown in the `@invariant` then it is raised to the caller.
|
|
822
387
|
|
|
823
|
-
If an error is thrown in the
|
|
824
|
-
In this case the `invariant` is not checked because the feature body has not
|
|
825
|
-
been entered and the assertion cannot modify the state of the class without
|
|
826
|
-
calling another method which is governed by its own contracts.
|
|
388
|
+
If an error is thrown in the `@demands` then the error is raised to the caller. In this case the `@invariant` is not checked because the feature body has not been entered and the assertion cannot modify the state of the class without calling another method which is governed by its own contracts.
|
|
827
389
|
|
|
828
|
-
If an error is thrown by the feature body or the
|
|
829
|
-
the `rescue` is executed. If `retry` is called then the process
|
|
830
|
-
starts from the beginning.
|
|
390
|
+
If an error is thrown by the feature body or the `@ensures` then the `@rescue` is executed. If `retry` is called then the process starts from the beginning.
|
|
831
391
|
|
|
832
|
-
If
|
|
833
|
-
`invariant` is checked before the error is raised to the caller.
|
|
392
|
+
If `@rescue` throws an error or does not call `retry` then the `@invariant` is checked before the error is raised to the caller.
|
|
834
393
|
|
|
835
394
|

|
|
836
395
|
|