-
Notifications
You must be signed in to change notification settings - Fork 0
/
code-contract.ts
102 lines (93 loc) · 2.16 KB
/
code-contract.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* @file Code contract utility
*/
//
// Types
//
// deno-lint-ignore no-explicit-any
type FunctionType<T> = ((...args: any[]) => T) & { name: string };
type ContractType<TResult> = {
// deno-lint-ignore no-explicit-any
pre?: (...args: any[]) => boolean;
post?: (result: TResult) => boolean;
invariant?: () => boolean;
};
//
// Variables
//
let checkContract = true;
//
// Functions
//
/**
* Bind function with code contract
* @param fn Function to bind
* @param contract Code contract
* @returns Bound function
*/
export function codeContract<
T extends FunctionType<ReturnType<T>>,
>(
fn: T,
contract: ContractType<ReturnType<T>> = {},
): T {
if (checkContract === false) {
return fn;
}
return ((...args) => {
const check = requireContractCheck();
if (
check !== false && contract.pre !== undefined &&
contract.pre(...args) === false
) {
const msg = [
"Code Contract: Failed to assert the pre condition.",
`\tfunction: ${fn.name}`,
`\targs: ${JSON.stringify(args)}`,
];
throw new Error(msg.join("\n"));
}
const result = fn(...args);
if (
check !== false && contract.post !== undefined &&
contract.post(result) === false
) {
const msg = [
"Code Contract: Failed to assert the post condition.",
`\tfunction: ${fn.name}`,
`\tresult: ${JSON.stringify(args)}`,
];
throw new Error(msg.join("\n"));
}
if (
check !== false && contract.invariant !== undefined &&
contract.invariant() === false
) {
const msg = [
"Code Contract: Failed to assert the invariant.",
`\tfunction: ${fn.name}`,
];
throw new Error(msg.join("\n"));
}
return result;
}) as T;
}
/**
* Enable contract
*/
export function enableContract() {
checkContract = true;
}
/**
* Disable contract check
*/
export function disableContract() {
checkContract = false;
}
/**
* Require contract check
* @returns Require contract check flag
*/
function requireContractCheck() {
return checkContract;
}