arktype 0.0.1 → 0.1.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.
Files changed (147) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +101 -0
  3. package/dist/api.cjs +15 -0
  4. package/dist/api.d.ts +2 -0
  5. package/dist/api.mjs +1 -0
  6. package/dist/cjs/main.js +462 -0
  7. package/dist/cjs/nodes/branches.js +85 -0
  8. package/dist/cjs/nodes/compose.js +140 -0
  9. package/dist/cjs/nodes/discriminate.js +199 -0
  10. package/dist/cjs/nodes/functors.js +35 -0
  11. package/dist/cjs/nodes/infer.js +4 -0
  12. package/dist/cjs/nodes/node.js +108 -0
  13. package/dist/cjs/nodes/predicate.js +87 -0
  14. package/dist/cjs/nodes/rules/class.js +21 -0
  15. package/dist/cjs/nodes/rules/collapsibleSet.js +49 -0
  16. package/dist/cjs/nodes/rules/divisor.js +33 -0
  17. package/dist/cjs/nodes/rules/props.js +72 -0
  18. package/dist/cjs/nodes/rules/range.js +109 -0
  19. package/dist/cjs/nodes/rules/regex.js +68 -0
  20. package/dist/cjs/nodes/rules/rules.js +156 -0
  21. package/dist/cjs/nodes/rules/subdomain.js +78 -0
  22. package/dist/cjs/package.json +3 -0
  23. package/dist/cjs/parse/definition.js +33 -0
  24. package/dist/cjs/parse/record.js +37 -0
  25. package/dist/cjs/parse/string/ast.js +36 -0
  26. package/dist/cjs/parse/string/reduce/dynamic.js +150 -0
  27. package/dist/cjs/parse/string/reduce/shared.js +23 -0
  28. package/dist/cjs/parse/string/reduce/static.js +4 -0
  29. package/dist/cjs/parse/string/shift/operand/enclosed.js +54 -0
  30. package/dist/cjs/parse/string/shift/operand/operand.js +11 -0
  31. package/dist/cjs/parse/string/shift/operand/unenclosed.js +53 -0
  32. package/dist/cjs/parse/string/shift/operator/bounds.js +87 -0
  33. package/dist/cjs/parse/string/shift/operator/divisor.js +35 -0
  34. package/dist/cjs/parse/string/shift/operator/operator.js +26 -0
  35. package/dist/cjs/parse/string/shift/scanner.js +99 -0
  36. package/dist/cjs/parse/string/string.js +43 -0
  37. package/dist/cjs/parse/tuple/keyof.js +46 -0
  38. package/dist/cjs/parse/tuple/morph.js +56 -0
  39. package/dist/cjs/parse/tuple/narrow.js +15 -0
  40. package/dist/cjs/parse/tuple/tuple.js +85 -0
  41. package/dist/cjs/parse/tuple/utils.js +48 -0
  42. package/dist/cjs/traverse/problems.js +249 -0
  43. package/dist/cjs/traverse/traverse.js +268 -0
  44. package/dist/cjs/utils/chainableNoOpProxy.js +23 -0
  45. package/dist/cjs/utils/domains.js +67 -0
  46. package/dist/cjs/utils/errors.js +26 -0
  47. package/dist/cjs/utils/freeze.js +16 -0
  48. package/dist/cjs/utils/generics.js +36 -0
  49. package/dist/cjs/utils/numericLiterals.js +84 -0
  50. package/dist/cjs/utils/paths.js +32 -0
  51. package/dist/cjs/utils/serialize.js +98 -0
  52. package/dist/cjs/utils/unionToTuple.js +4 -0
  53. package/dist/mjs/main.js +442 -0
  54. package/dist/mjs/nodes/branches.js +71 -0
  55. package/dist/mjs/nodes/compose.js +118 -0
  56. package/dist/mjs/nodes/discriminate.js +184 -0
  57. package/dist/mjs/nodes/functors.js +27 -0
  58. package/dist/mjs/nodes/infer.js +1 -0
  59. package/dist/mjs/nodes/node.js +90 -0
  60. package/dist/mjs/nodes/predicate.js +69 -0
  61. package/dist/mjs/nodes/rules/class.js +7 -0
  62. package/dist/mjs/nodes/rules/collapsibleSet.js +35 -0
  63. package/dist/mjs/nodes/rules/divisor.js +19 -0
  64. package/dist/mjs/nodes/rules/props.js +57 -0
  65. package/dist/mjs/nodes/rules/range.js +90 -0
  66. package/dist/mjs/nodes/rules/regex.js +53 -0
  67. package/dist/mjs/nodes/rules/rules.js +138 -0
  68. package/dist/mjs/nodes/rules/subdomain.js +63 -0
  69. package/dist/mjs/package.json +3 -0
  70. package/dist/mjs/parse/definition.js +17 -0
  71. package/dist/mjs/parse/record.js +29 -0
  72. package/dist/mjs/parse/string/ast.js +19 -0
  73. package/dist/mjs/parse/string/reduce/dynamic.js +142 -0
  74. package/dist/mjs/parse/string/reduce/shared.js +6 -0
  75. package/dist/mjs/parse/string/reduce/static.js +1 -0
  76. package/dist/mjs/parse/string/shift/operand/enclosed.js +39 -0
  77. package/dist/mjs/parse/string/shift/operand/operand.js +3 -0
  78. package/dist/mjs/parse/string/shift/operand/unenclosed.js +36 -0
  79. package/dist/mjs/parse/string/shift/operator/bounds.js +70 -0
  80. package/dist/mjs/parse/string/shift/operator/divisor.js +21 -0
  81. package/dist/mjs/parse/string/shift/operator/operator.js +11 -0
  82. package/dist/mjs/parse/string/shift/scanner.js +91 -0
  83. package/dist/mjs/parse/string/string.js +28 -0
  84. package/dist/mjs/parse/tuple/keyof.js +38 -0
  85. package/dist/mjs/parse/tuple/morph.js +42 -0
  86. package/dist/mjs/parse/tuple/narrow.js +7 -0
  87. package/dist/mjs/parse/tuple/tuple.js +71 -0
  88. package/dist/mjs/parse/tuple/utils.js +34 -0
  89. package/dist/mjs/traverse/problems.js +229 -0
  90. package/dist/mjs/traverse/traverse.js +252 -0
  91. package/dist/mjs/utils/chainableNoOpProxy.js +15 -0
  92. package/dist/mjs/utils/domains.js +48 -0
  93. package/dist/mjs/utils/errors.js +10 -0
  94. package/dist/mjs/utils/freeze.js +8 -0
  95. package/dist/mjs/utils/generics.js +15 -0
  96. package/dist/mjs/utils/numericLiterals.js +71 -0
  97. package/dist/mjs/utils/paths.js +18 -0
  98. package/dist/mjs/utils/serialize.js +81 -0
  99. package/dist/mjs/utils/unionToTuple.js +1 -0
  100. package/dist/tsconfig.temp.tsbuildinfo +1 -0
  101. package/dist/types/main.d.ts +257 -0
  102. package/dist/types/nodes/branches.d.ts +14 -0
  103. package/dist/types/nodes/compose.d.ts +92 -0
  104. package/dist/types/nodes/discriminate.d.ts +27 -0
  105. package/dist/types/nodes/functors.d.ts +6 -0
  106. package/dist/types/nodes/infer.d.ts +35 -0
  107. package/dist/types/nodes/node.d.ts +51 -0
  108. package/dist/types/nodes/predicate.d.ts +88 -0
  109. package/dist/types/nodes/rules/class.d.ts +3 -0
  110. package/dist/types/nodes/rules/collapsibleSet.d.ts +4 -0
  111. package/dist/types/nodes/rules/divisor.d.ts +2 -0
  112. package/dist/types/nodes/rules/props.d.ts +20 -0
  113. package/dist/types/nodes/rules/range.d.ts +33 -0
  114. package/dist/types/nodes/rules/regex.d.ts +14 -0
  115. package/dist/types/nodes/rules/rules.d.ts +44 -0
  116. package/dist/types/nodes/rules/subdomain.d.ts +15 -0
  117. package/dist/types/parse/definition.d.ts +29 -0
  118. package/dist/types/parse/record.d.ts +24 -0
  119. package/dist/types/parse/string/ast.d.ts +42 -0
  120. package/dist/types/parse/string/reduce/dynamic.d.ts +34 -0
  121. package/dist/types/parse/string/reduce/shared.d.ts +24 -0
  122. package/dist/types/parse/string/reduce/static.d.ts +115 -0
  123. package/dist/types/parse/string/shift/operand/enclosed.d.ts +28 -0
  124. package/dist/types/parse/string/shift/operand/operand.d.ts +9 -0
  125. package/dist/types/parse/string/shift/operand/unenclosed.d.ts +18 -0
  126. package/dist/types/parse/string/shift/operator/bounds.d.ts +20 -0
  127. package/dist/types/parse/string/shift/operator/divisor.d.ts +9 -0
  128. package/dist/types/parse/string/shift/operator/operator.d.ts +13 -0
  129. package/dist/types/parse/string/shift/scanner.d.ts +89 -0
  130. package/dist/types/parse/string/string.d.ts +27 -0
  131. package/dist/types/parse/tuple/keyof.d.ts +2 -0
  132. package/dist/types/parse/tuple/morph.d.ts +15 -0
  133. package/dist/types/parse/tuple/narrow.d.ts +13 -0
  134. package/dist/types/parse/tuple/tuple.d.ts +37 -0
  135. package/dist/types/parse/tuple/utils.d.ts +19 -0
  136. package/dist/types/traverse/problems.d.ts +123 -0
  137. package/dist/types/traverse/traverse.d.ts +48 -0
  138. package/dist/types/utils/chainableNoOpProxy.d.ts +14 -0
  139. package/dist/types/utils/domains.d.ts +58 -0
  140. package/dist/types/utils/errors.d.ts +6 -0
  141. package/dist/types/utils/freeze.d.ts +2 -0
  142. package/dist/types/utils/generics.d.ts +118 -0
  143. package/dist/types/utils/numericLiterals.d.ts +28 -0
  144. package/dist/types/utils/paths.d.ts +7 -0
  145. package/dist/types/utils/serialize.d.ts +38 -0
  146. package/dist/types/utils/unionToTuple.d.ts +11 -0
  147. package/package.json +102 -2
@@ -0,0 +1,138 @@
1
+ import { writeImplicitNeverMessage } from "../../parse/string/ast.js";
2
+ import { throwParseError } from "../../utils/errors.js";
3
+ import { listFrom } from "../../utils/generics.js";
4
+ import { composeIntersection, composeKeyedIntersection, equality, isDisjoint, isEquality } from "../compose.js";
5
+ import { classIntersection } from "./class.js";
6
+ import { collapsibleListUnion } from "./collapsibleSet.js";
7
+ import { divisorIntersection } from "./divisor.js";
8
+ import { flattenProps, propsIntersection } from "./props.js";
9
+ import { flattenRange, rangeIntersection } from "./range.js";
10
+ import { getRegex, regexIntersection } from "./regex.js";
11
+ import { flattenSubdomain, subdomainIntersection } from "./subdomain.js";
12
+ const rulesOf = (branch)=>branch.input ?? branch;
13
+ export const branchIntersection = (l, r, state)=>{
14
+ const lRules = rulesOf(l);
15
+ const rRules = rulesOf(r);
16
+ const rulesResult = rulesIntersection(lRules, rRules, state);
17
+ if ("morph" in l) {
18
+ if ("morph" in r) {
19
+ if (l.morph === r.morph) {
20
+ return isEquality(rulesResult) || isDisjoint(rulesResult) ? rulesResult : {
21
+ input: rulesResult,
22
+ morph: l.morph
23
+ };
24
+ }
25
+ return state.lastOperator === "&" ? throwParseError(writeImplicitNeverMessage(state.path, "of morphs")) : {};
26
+ }
27
+ return isDisjoint(rulesResult) ? rulesResult : {
28
+ input: isEquality(rulesResult) ? l.input : rulesResult,
29
+ morph: l.morph
30
+ };
31
+ }
32
+ if ("morph" in r) {
33
+ return isDisjoint(rulesResult) ? rulesResult : {
34
+ input: isEquality(rulesResult) ? r.input : rulesResult,
35
+ morph: r.morph
36
+ };
37
+ }
38
+ return rulesResult;
39
+ };
40
+ export const rulesIntersection = (l, r, state)=>"value" in l ? "value" in r ? l.value === r.value ? equality() : state.addDisjoint("value", l.value, r.value) : literalSatisfiesRules(l.value, r, state) ? l : state.addDisjoint("leftAssignability", l, r) : "value" in r ? literalSatisfiesRules(r.value, l, state) ? r : state.addDisjoint("rightAssignability", l, r) : narrowableRulesIntersection(l, r, state);
41
+ const narrowIntersection = composeIntersection(collapsibleListUnion);
42
+ export const narrowableRulesIntersection = composeKeyedIntersection({
43
+ subdomain: subdomainIntersection,
44
+ divisor: divisorIntersection,
45
+ regex: regexIntersection,
46
+ props: propsIntersection,
47
+ class: classIntersection,
48
+ range: rangeIntersection,
49
+ narrow: narrowIntersection
50
+ }, {
51
+ onEmpty: "bubble"
52
+ });
53
+ const ruleFlatteners = {
54
+ subdomain: flattenSubdomain,
55
+ regex: (entries, rule)=>{
56
+ for (const source of listFrom(rule)){
57
+ entries.push([
58
+ "regex",
59
+ getRegex(source)
60
+ ]);
61
+ }
62
+ },
63
+ divisor: (entries, rule)=>{
64
+ entries.push([
65
+ "divisor",
66
+ rule
67
+ ]);
68
+ },
69
+ range: flattenRange,
70
+ class: (entries, rule)=>{
71
+ entries.push([
72
+ "class",
73
+ rule
74
+ ]);
75
+ },
76
+ props: flattenProps,
77
+ narrow: (entries, rule)=>{
78
+ for (const narrow of listFrom(rule)){
79
+ entries.push([
80
+ "narrow",
81
+ narrow
82
+ ]);
83
+ }
84
+ },
85
+ value: (entries, rule)=>{
86
+ entries.push([
87
+ "value",
88
+ rule
89
+ ]);
90
+ }
91
+ };
92
+ export const precedenceMap = {
93
+ // Critical: No other checks are performed if these fail
94
+ domain: 0,
95
+ value: 0,
96
+ domains: 0,
97
+ branches: 0,
98
+ subdomain: 0,
99
+ switch: 0,
100
+ alias: 0,
101
+ // Shallow: All shallow checks will be performed even if one or more fail
102
+ class: 1,
103
+ regex: 1,
104
+ divisor: 1,
105
+ bound: 1,
106
+ // Deep: Performed if all shallow checks pass, even if one or more deep checks fail
107
+ requiredProps: 2,
108
+ optionalProps: 2,
109
+ // Narrow: Only performed if all shallow and deep checks pass
110
+ narrow: 3,
111
+ // Morph: Only performed if all validation passes
112
+ morph: 4
113
+ };
114
+ export const flattenBranch = (branch, ctx)=>{
115
+ if ("morph" in branch) {
116
+ const result = flattenRules(branch.input, ctx);
117
+ result.push([
118
+ "morph",
119
+ branch.morph
120
+ ]);
121
+ return result;
122
+ }
123
+ return flattenRules(branch, ctx);
124
+ };
125
+ const flattenRules = (rules, ctx)=>{
126
+ const entries = [];
127
+ let k;
128
+ for(k in rules){
129
+ ruleFlatteners[k](entries, rules[k], ctx);
130
+ }
131
+ return entries.sort((l, r)=>precedenceMap[l[0]] - precedenceMap[r[0]]);
132
+ };
133
+ export const literalSatisfiesRules = (data, rules, state)=>!state.type.meta.scope.type([
134
+ "node",
135
+ {
136
+ [state.domain]: rules
137
+ }
138
+ ])(data).problems;
@@ -0,0 +1,63 @@
1
+ import { throwInternalError } from "../../utils/errors.js";
2
+ import { composeIntersection, equality, isDisjoint, isEquality } from "../compose.js";
3
+ import { flattenNode, nodeIntersection } from "../node.js";
4
+ export const subdomainIntersection = composeIntersection((l, r, state)=>{
5
+ if (typeof l === "string") {
6
+ if (typeof r === "string") {
7
+ return l === r ? equality() : state.addDisjoint("subdomain", l, r);
8
+ }
9
+ return l === r[0] ? r : state.addDisjoint("subdomain", l, r[0]);
10
+ }
11
+ if (typeof r === "string") {
12
+ return l[0] === r ? l : state.addDisjoint("subdomain", l[0], r);
13
+ }
14
+ if (l[0] !== r[0]) {
15
+ return state.addDisjoint("subdomain", l[0], r[0]);
16
+ }
17
+ const result = [
18
+ l[0]
19
+ ];
20
+ let lImpliesR = true;
21
+ let rImpliesL = true;
22
+ for(let i = 1; i < l.length; i++){
23
+ const lNode = l[i];
24
+ const rNode = r[i];
25
+ state.path.push(subdomainParameterToPathSegment(l[0], i));
26
+ const parameterResult = nodeIntersection(lNode, rNode, state);
27
+ state.path.pop();
28
+ if (isEquality(parameterResult)) {
29
+ result[i] = lNode;
30
+ } else if (parameterResult === l) {
31
+ result[i] = lNode;
32
+ rImpliesL = false;
33
+ } else if (parameterResult === r) {
34
+ result[i] = rNode;
35
+ lImpliesR = false;
36
+ } else if (isDisjoint(parameterResult)) {
37
+ return parameterResult;
38
+ } else {
39
+ result[i] = parameterResult;
40
+ lImpliesR = false;
41
+ rImpliesL = false;
42
+ }
43
+ }
44
+ return lImpliesR ? rImpliesL ? equality() : l : rImpliesL ? r : result;
45
+ });
46
+ const subdomainParameterToPathSegment = (subdomain, i)=>subdomain === "Array" ? "${number}" : subdomain === "Set" ? "${item}" : subdomain === "Map" ? i === 1 ? "${key}" : "${value}" : throwInternalError(`Unexpected parameterized subdomain '${subdomain}'`);
47
+ export const subdomainPathSegments = {
48
+ "${number}": true,
49
+ "${item}": true,
50
+ "${key}": true,
51
+ "${value}": true
52
+ };
53
+ export const flattenSubdomain = (entries, rule, ctx)=>entries.push([
54
+ "subdomain",
55
+ typeof rule === "string" ? rule : rule[0] === "Map" ? [
56
+ rule[0],
57
+ flattenNode(rule[1], ctx),
58
+ flattenNode(rule[2], ctx)
59
+ ] : [
60
+ rule[0],
61
+ flattenNode(rule[1], ctx)
62
+ ]
63
+ ]);
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,17 @@
1
+ import { isType } from "../main.js";
2
+ import { subdomainOf } from "../utils/domains.js";
3
+ import { throwParseError } from "../utils/errors.js";
4
+ import { parseRecord } from "./record.js";
5
+ import { parseString } from "./string/string.js";
6
+ import { parseTuple } from "./tuple/tuple.js";
7
+ export const parseDefinition = (def, ctx)=>{
8
+ const subdomain = subdomainOf(def);
9
+ return subdomain === "string" ? parseString(def, ctx) : subdomain === "object" ? parseRecord(def, ctx) : subdomain === "Array" ? parseTuple(def, ctx) : subdomain === "RegExp" ? {
10
+ string: {
11
+ regex: def.source
12
+ }
13
+ } : isType(def) ? def.node : throwParseError(writeBadDefinitionTypeMessage(subdomain));
14
+ };
15
+ export const as = Symbol("as");
16
+ export const unknownDefinitionMessage = "Cannot statically parse a definition inferred as unknown. Consider using 'as inferred<...>' to cast it.";
17
+ export const writeBadDefinitionTypeMessage = (actual)=>`Type definitions must be strings or objects (was ${actual})`;
@@ -0,0 +1,29 @@
1
+ import { parseDefinition } from "./definition.js";
2
+ import { Scanner } from "./string/shift/scanner.js";
3
+ export const parseRecord = (def, ctx)=>{
4
+ const props = {};
5
+ for(const definitionKey in def){
6
+ let keyName = definitionKey;
7
+ let isOptional = false;
8
+ if (definitionKey[definitionKey.length - 1] === "?") {
9
+ if (definitionKey[definitionKey.length - 2] === Scanner.escapeToken) {
10
+ keyName = `${definitionKey.slice(0, -2)}?`;
11
+ } else {
12
+ keyName = definitionKey.slice(0, -1);
13
+ isOptional = true;
14
+ }
15
+ }
16
+ ctx.path.push(keyName);
17
+ const propNode = parseDefinition(def[definitionKey], ctx);
18
+ ctx.path.pop();
19
+ props[keyName] = isOptional ? [
20
+ "?",
21
+ propNode
22
+ ] : propNode;
23
+ }
24
+ return {
25
+ object: {
26
+ props
27
+ }
28
+ };
29
+ };
@@ -0,0 +1,19 @@
1
+ import { disjointDescriptionWriters } from "../../nodes/compose.js";
2
+ import { keysOf } from "../../utils/generics.js";
3
+ export const compileDisjointReasonsMessage = (disjoints)=>{
4
+ const paths = keysOf(disjoints);
5
+ if (paths.length === 1) {
6
+ const path = paths[0];
7
+ return `${path === "/" ? "" : `At ${path}: `}Intersection of ${disjointDescriptionWriters[disjoints[path].kind](disjoints[path])} results in an unsatisfiable type`;
8
+ }
9
+ let message = `
10
+ "Intersection results in unsatisfiable types at the following paths:\n`;
11
+ for(const path1 in disjoints){
12
+ message += ` ${path1}: ${disjointDescriptionWriters[disjoints[path1].kind](disjoints[path1])}\n`;
13
+ }
14
+ return message;
15
+ };
16
+ export const writeImplicitNeverMessage = (path, description)=>`${path.length ? `At ${path}: ` : ""}Intersection ${description ? `${description} ` : ""}results in an unsatisfiable type`;
17
+ export const writeUndiscriminatableMorphUnionMessage = (path)=>`${path === "/" ? "A" : `At ${path}, a`} union including one or more morphs must be discriminatable`;
18
+ export const writeIndivisibleMessage = (root)=>`Divisibility operand ${root} must be a number`;
19
+ export const writeUnboundableMessage = (root)=>`Bounded expression ${root} must be a number, string or array`;
@@ -0,0 +1,142 @@
1
+ import { functors } from "../../../nodes/functors.js";
2
+ import { intersection, isLiteralNode, union } from "../../../nodes/node.js";
3
+ import { minComparators } from "../../../nodes/rules/range.js";
4
+ import { throwInternalError, throwParseError } from "../../../utils/errors.js";
5
+ import { isKeyOf } from "../../../utils/generics.js";
6
+ import { stringify } from "../../../utils/serialize.js";
7
+ import { Scanner } from "../shift/scanner.js";
8
+ import { unclosedGroupMessage, writeMultipleLeftBoundsMessage, writeOpenRangeMessage, writeUnmatchedGroupCloseMessage, writeUnpairableComparatorMessage } from "./shared.js";
9
+ export class DynamicState {
10
+ error(message) {
11
+ return throwParseError(message);
12
+ }
13
+ hasRoot() {
14
+ return this.root !== undefined;
15
+ }
16
+ resolveRoot() {
17
+ this.assertHasRoot();
18
+ return this.ctx.type.meta.scope.resolveNode(this.root);
19
+ }
20
+ rootToString() {
21
+ this.assertHasRoot();
22
+ return stringify(this.root);
23
+ }
24
+ ejectRootIfLimit() {
25
+ this.assertHasRoot();
26
+ const resolution = typeof this.root === "string" ? this.ctx.type.meta.scope.resolveNode(this.root) : this.root;
27
+ if (isLiteralNode(resolution, "number")) {
28
+ const limit = resolution.number.value;
29
+ this.root = undefined;
30
+ return limit;
31
+ }
32
+ }
33
+ ejectRangeIfOpen() {
34
+ if (this.branches.range) {
35
+ const range = this.branches.range;
36
+ delete this.branches.range;
37
+ return range;
38
+ }
39
+ }
40
+ assertHasRoot() {
41
+ if (this.root === undefined) {
42
+ return throwInternalError("Unexpected interaction with unset root");
43
+ }
44
+ }
45
+ assertUnsetRoot() {
46
+ if (this.root !== undefined) {
47
+ return throwInternalError("Unexpected attempt to overwrite root");
48
+ }
49
+ }
50
+ setRoot(node) {
51
+ this.assertUnsetRoot();
52
+ this.root = node;
53
+ }
54
+ rootToArray() {
55
+ this.root = functors.Array(this.ejectRoot());
56
+ }
57
+ intersect(node) {
58
+ this.root = intersection(this.ejectRoot(), node, this.ctx.type);
59
+ }
60
+ ejectRoot() {
61
+ this.assertHasRoot();
62
+ const root = this.root;
63
+ this.root = undefined;
64
+ return root;
65
+ }
66
+ ejectFinalizedRoot() {
67
+ this.assertHasRoot();
68
+ const root = this.root;
69
+ this.root = ejectedProxy;
70
+ return root;
71
+ }
72
+ finalize() {
73
+ if (this.groups.length) {
74
+ return this.error(unclosedGroupMessage);
75
+ }
76
+ this.finalizeBranches();
77
+ this.scanner.finalized = true;
78
+ }
79
+ reduceLeftBound(limit, comparator) {
80
+ const invertedComparator = Scanner.invertedComparators[comparator];
81
+ if (!isKeyOf(invertedComparator, minComparators)) {
82
+ return this.error(writeUnpairableComparatorMessage(comparator));
83
+ }
84
+ if (this.branches.range) {
85
+ return this.error(writeMultipleLeftBoundsMessage(this.branches.range.limit, this.branches.range.comparator, limit, invertedComparator));
86
+ }
87
+ this.branches.range = {
88
+ limit,
89
+ comparator: invertedComparator
90
+ };
91
+ }
92
+ finalizeBranches() {
93
+ this.assertRangeUnset();
94
+ if (this.branches.union) {
95
+ this.pushRootToBranch("|");
96
+ this.setRoot(this.branches.union);
97
+ } else if (this.branches.intersection) {
98
+ this.setRoot(intersection(this.branches.intersection, this.ejectRoot(), this.ctx.type));
99
+ }
100
+ }
101
+ finalizeGroup() {
102
+ this.finalizeBranches();
103
+ const topBranchState = this.groups.pop();
104
+ if (!topBranchState) {
105
+ return this.error(writeUnmatchedGroupCloseMessage(this.scanner.unscanned));
106
+ }
107
+ this.branches = topBranchState;
108
+ }
109
+ pushRootToBranch(token) {
110
+ this.assertRangeUnset();
111
+ this.branches.intersection = this.branches.intersection ? intersection(this.branches.intersection, this.ejectRoot(), this.ctx.type) : this.ejectRoot();
112
+ if (token === "|") {
113
+ this.branches.union = this.branches.union ? union(this.branches.union, this.branches.intersection, this.ctx.type) : this.branches.intersection;
114
+ delete this.branches.intersection;
115
+ }
116
+ }
117
+ assertRangeUnset() {
118
+ if (this.branches.range) {
119
+ return this.error(writeOpenRangeMessage(this.branches.range.limit, this.branches.range.comparator));
120
+ }
121
+ }
122
+ reduceGroupOpen() {
123
+ this.groups.push(this.branches);
124
+ this.branches = {};
125
+ }
126
+ previousOperator() {
127
+ return this.branches.range?.comparator ?? this.branches.intersection ? "&" : this.branches.union ? "|" : undefined;
128
+ }
129
+ shiftedByOne() {
130
+ this.scanner.shift();
131
+ return this;
132
+ }
133
+ constructor(def, ctx){
134
+ this.ctx = ctx;
135
+ this.branches = {};
136
+ this.groups = [];
137
+ this.scanner = new Scanner(def);
138
+ }
139
+ }
140
+ const ejectedProxy = new Proxy({}, {
141
+ get: ()=>throwInternalError(`Unexpected attempt to access ejected attributes`)
142
+ });
@@ -0,0 +1,6 @@
1
+ import { Scanner } from "../shift/scanner.js";
2
+ export const writeUnmatchedGroupCloseMessage = (unscanned)=>`Unmatched )${unscanned === "" ? "" : ` before ${unscanned}`}`;
3
+ export const unclosedGroupMessage = "Missing )";
4
+ export const writeOpenRangeMessage = (min, comparator)=>`Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`;
5
+ export const writeUnpairableComparatorMessage = (comparator)=>`Left-bounded expressions must specify their limits using < or <= (was ${comparator})`;
6
+ export const writeMultipleLeftBoundsMessage = (openLimit, openComparator, limit, comparator)=>`An expression may have at most one left bound (parsed ${openLimit}${Scanner.invertedComparators[openComparator]}, ${limit}${Scanner.invertedComparators[comparator]})`;
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,39 @@
1
+ import { getRegex } from "../../../../nodes/rules/regex.js";
2
+ export const parseEnclosed = (s, enclosing)=>{
3
+ const token = s.scanner.shiftUntil(untilLookaheadIsClosing[enclosing]);
4
+ if (s.scanner.lookahead === "") {
5
+ return s.error(writeUnterminatedEnclosedMessage(token, enclosing));
6
+ }
7
+ // Shift the scanner one additional time for the second enclosing token
8
+ if (s.scanner.shift() === "/") {
9
+ // Cache the regex instance to throw right way if its invalid
10
+ getRegex(token);
11
+ s.setRoot({
12
+ string: {
13
+ regex: token
14
+ }
15
+ });
16
+ } else {
17
+ s.setRoot({
18
+ string: {
19
+ value: token
20
+ }
21
+ });
22
+ }
23
+ };
24
+ export const enclosingChar = {
25
+ "'": 1,
26
+ '"': 1,
27
+ "/": 1
28
+ };
29
+ const untilLookaheadIsClosing = {
30
+ "'": (scanner)=>scanner.lookahead === `'`,
31
+ '"': (scanner)=>scanner.lookahead === `"`,
32
+ "/": (scanner)=>scanner.lookahead === `/`
33
+ };
34
+ const enclosingCharDescriptions = {
35
+ '"': "double-quote",
36
+ "'": "single-quote",
37
+ "/": "forward slash"
38
+ };
39
+ export const writeUnterminatedEnclosedMessage = (fragment, enclosing)=>`${enclosing}${fragment} requires a closing ${enclosingCharDescriptions[enclosing]}`;
@@ -0,0 +1,3 @@
1
+ import { enclosingChar, parseEnclosed } from "./enclosed.js";
2
+ import { parseUnenclosed, writeMissingOperandMessage } from "./unenclosed.js";
3
+ export const parseOperand = (s)=>s.scanner.lookahead === "" ? s.error(writeMissingOperandMessage(s)) : s.scanner.lookahead === "(" ? s.shiftedByOne().reduceGroupOpen() : s.scanner.lookaheadIsIn(enclosingChar) ? parseEnclosed(s, s.scanner.shift()) : parseUnenclosed(s);
@@ -0,0 +1,36 @@
1
+ import { tryParseWellFormedBigint, tryParseWellFormedNumber } from "../../../../utils/numericLiterals.js";
2
+ export const parseUnenclosed = (s)=>{
3
+ const token = s.scanner.shiftUntilNextTerminator();
4
+ s.setRoot(unenclosedToNode(s, token));
5
+ };
6
+ const unenclosedToNode = (s, token)=>{
7
+ if (s.ctx.type.meta.scope.addReferenceIfResolvable(token, s.ctx)) {
8
+ return token;
9
+ }
10
+ return maybeParseUnenclosedLiteral(token) ?? s.error(token === "" ? writeMissingOperandMessage(s) : writeUnresolvableMessage(token));
11
+ };
12
+ const maybeParseUnenclosedLiteral = (token)=>{
13
+ const maybeNumber = tryParseWellFormedNumber(token);
14
+ if (maybeNumber !== undefined) {
15
+ return {
16
+ number: {
17
+ value: maybeNumber
18
+ }
19
+ };
20
+ }
21
+ const maybeBigint = tryParseWellFormedBigint(token);
22
+ if (maybeBigint !== undefined) {
23
+ return {
24
+ bigint: {
25
+ value: maybeBigint
26
+ }
27
+ };
28
+ }
29
+ };
30
+ export const writeUnresolvableMessage = (token)=>`'${token}' is unresolvable`;
31
+ export const writeMissingOperandMessage = (s)=>{
32
+ const operator = s.previousOperator();
33
+ return operator ? writeMissingRightOperandMessage(operator, s.scanner.unscanned) : writeExpressionExpectedMessage(s.scanner.unscanned);
34
+ };
35
+ export const writeMissingRightOperandMessage = (token, unscanned)=>`Token '${token}' requires a right operand${unscanned ? ` before '${unscanned}'` : ""}`;
36
+ export const writeExpressionExpectedMessage = (unscanned)=>`Expected an expression${unscanned ? ` before '${unscanned}'` : ""}`;
@@ -0,0 +1,70 @@
1
+ import { stringifyRange } from "../../../../nodes/compose.js";
2
+ import { compareStrictness, maxComparators, minComparators } from "../../../../nodes/rules/range.js";
3
+ import { throwInternalError } from "../../../../utils/errors.js";
4
+ import { hasKey, isKeyOf, keysOf, listFrom } from "../../../../utils/generics.js";
5
+ import { tryParseWellFormedNumber } from "../../../../utils/numericLiterals.js";
6
+ import { writeUnboundableMessage } from "../../ast.js";
7
+ import { writeUnpairableComparatorMessage } from "../../reduce/shared.js";
8
+ import { Scanner } from "../scanner.js";
9
+ export const parseBound = (s, start)=>{
10
+ const comparator = shiftComparator(s, start);
11
+ const maybeMin = s.ejectRootIfLimit();
12
+ return maybeMin === undefined ? parseRightBound(s, comparator) : s.reduceLeftBound(maybeMin, comparator);
13
+ };
14
+ const shiftComparator = (s, start)=>s.scanner.lookaheadIs("=") ? `${start}${s.scanner.shift()}` : isKeyOf(start, Scanner.oneCharComparators) ? start : s.error(singleEqualsMessage);
15
+ export const singleEqualsMessage = `= is not a valid comparator. Use == to check for equality`;
16
+ export const parseRightBound = (s, comparator)=>{
17
+ const limitToken = s.scanner.shiftUntilNextTerminator();
18
+ const limit = tryParseWellFormedNumber(limitToken, writeInvalidLimitMessage(comparator, limitToken + s.scanner.unscanned));
19
+ const openRange = s.ejectRangeIfOpen();
20
+ const rightBound = {
21
+ comparator,
22
+ limit
23
+ };
24
+ const range = openRange ? !hasComparatorIn(rightBound, maxComparators) ? s.error(writeUnpairableComparatorMessage(comparator)) : compareStrictness("min", openRange, rightBound) === "l" ? s.error(writeEmptyRangeMessage({
25
+ min: openRange,
26
+ max: rightBound
27
+ })) : {
28
+ min: openRange,
29
+ max: rightBound
30
+ } : hasComparator(rightBound, "==") ? rightBound : hasComparatorIn(rightBound, minComparators) ? {
31
+ min: rightBound
32
+ } : hasComparatorIn(rightBound, maxComparators) ? {
33
+ max: rightBound
34
+ } : throwInternalError(`Unexpected comparator '${rightBound.comparator}'`);
35
+ s.intersect(distributeRange(range, s));
36
+ };
37
+ const distributeRange = (range, s)=>{
38
+ const resolution = s.resolveRoot();
39
+ const domains = keysOf(resolution);
40
+ const distributedRange = {};
41
+ const rangePredicate = {
42
+ range
43
+ };
44
+ const isBoundable = domains.every((domain)=>{
45
+ switch(domain){
46
+ case "string":
47
+ distributedRange.string = rangePredicate;
48
+ return true;
49
+ case "number":
50
+ distributedRange.number = rangePredicate;
51
+ return true;
52
+ case "object":
53
+ distributedRange.object = rangePredicate;
54
+ if (resolution.object === true) {
55
+ return false;
56
+ }
57
+ return listFrom(resolution.object).every((branch)=>hasKey(branch, "subdomain") && (branch.subdomain === "Array" || branch.subdomain[0] === "Array"));
58
+ default:
59
+ return false;
60
+ }
61
+ });
62
+ if (!isBoundable) {
63
+ s.error(writeUnboundableMessage(s.rootToString()));
64
+ }
65
+ return distributedRange;
66
+ };
67
+ const hasComparator = (bound, comparator)=>bound.comparator === comparator;
68
+ const hasComparatorIn = (bound, comparators)=>bound.comparator in comparators;
69
+ export const writeInvalidLimitMessage = (comparator, limit)=>`Comparator ${comparator} must be followed by a number literal (was '${limit}')`;
70
+ export const writeEmptyRangeMessage = (range)=>`${stringifyRange(range)} is empty`;
@@ -0,0 +1,21 @@
1
+ import { keysOf } from "../../../../utils/generics.js";
2
+ import { tryParseWellFormedInteger } from "../../../../utils/numericLiterals.js";
3
+ import { writeIndivisibleMessage } from "../../ast.js";
4
+ export const parseDivisor = (s)=>{
5
+ const divisorToken = s.scanner.shiftUntilNextTerminator();
6
+ const divisor = tryParseWellFormedInteger(divisorToken, writeInvalidDivisorMessage(divisorToken));
7
+ if (divisor === 0) {
8
+ s.error(writeInvalidDivisorMessage(0));
9
+ }
10
+ const rootDomains = keysOf(s.resolveRoot());
11
+ if (rootDomains.length === 1 && rootDomains[0] === "number") {
12
+ s.intersect({
13
+ number: {
14
+ divisor
15
+ }
16
+ });
17
+ } else {
18
+ s.error(writeIndivisibleMessage(s.rootToString()));
19
+ }
20
+ };
21
+ export const writeInvalidDivisorMessage = (divisor)=>`% operator must be followed by a non-zero integer literal (was ${divisor})`;
@@ -0,0 +1,11 @@
1
+ import { throwInternalError } from "../../../../utils/errors.js";
2
+ import { isKeyOf } from "../../../../utils/generics.js";
3
+ import { Scanner } from "../scanner.js";
4
+ import { parseBound } from "./bounds.js";
5
+ import { parseDivisor } from "./divisor.js";
6
+ export const parseOperator = (s)=>{
7
+ const lookahead = s.scanner.shift();
8
+ return lookahead === "" ? s.finalize() : lookahead === "[" ? s.scanner.shift() === "]" ? s.rootToArray() : s.error(incompleteArrayTokenMessage) : isKeyOf(lookahead, Scanner.branchTokens) ? s.pushRootToBranch(lookahead) : lookahead === ")" ? s.finalizeGroup() : isKeyOf(lookahead, Scanner.comparatorStartChars) ? parseBound(s, lookahead) : lookahead === "%" ? parseDivisor(s) : lookahead === " " ? parseOperator(s) : /* c8 ignore next */ throwInternalError(writeUnexpectedCharacterMessage(lookahead));
9
+ };
10
+ export const writeUnexpectedCharacterMessage = (char)=>`Unexpected character '${char}'`;
11
+ export const incompleteArrayTokenMessage = `Missing expected ']'`;