arktype 2.0.0-dev.0 → 2.0.0-dev.10

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 (219) hide show
  1. package/__tests__/array.test.ts +270 -151
  2. package/__tests__/badDefinitionType.test.ts +10 -3
  3. package/__tests__/basis.test.ts +6 -2
  4. package/__tests__/bounds.test.ts +282 -352
  5. package/__tests__/cast.test.ts +7 -2
  6. package/__tests__/completions.test.ts +8 -3
  7. package/__tests__/config.test.ts +95 -167
  8. package/__tests__/dateLiteral.test.ts +8 -4
  9. package/__tests__/declared.test.ts +7 -6
  10. package/__tests__/discrimination.test.ts +1 -1
  11. package/__tests__/divisor.test.ts +46 -22
  12. package/__tests__/enclosed.test.ts +39 -25
  13. package/__tests__/examples.test.ts +56 -56
  14. package/__tests__/expressions.test.ts +184 -112
  15. package/__tests__/generic.test.ts +307 -288
  16. package/__tests__/group.test.ts +67 -54
  17. package/__tests__/imports.test.ts +62 -49
  18. package/__tests__/instanceof.test.ts +25 -23
  19. package/__tests__/intersection.test.ts +52 -48
  20. package/__tests__/keyTraversal.test.ts +77 -73
  21. package/__tests__/keyof.test.ts +68 -52
  22. package/__tests__/keywords.test.ts +164 -138
  23. package/__tests__/literal.test.ts +60 -21
  24. package/__tests__/match.bench.ts +31 -0
  25. package/__tests__/match.test.ts +222 -22
  26. package/__tests__/narrow.test.ts +52 -54
  27. package/__tests__/objectLiteral.test.ts +347 -205
  28. package/__tests__/operator.bench.ts +4 -4
  29. package/__tests__/pipe.test.ts +501 -0
  30. package/__tests__/realWorld.test.ts +63 -0
  31. package/__tests__/regex.test.ts +17 -7
  32. package/__tests__/scope.bench.ts +1 -1
  33. package/__tests__/scope.test.ts +257 -23
  34. package/__tests__/serialization.test.ts +19 -0
  35. package/__tests__/string.test.ts +11 -7
  36. package/__tests__/submodule.test.ts +26 -39
  37. package/__tests__/this.test.ts +83 -57
  38. package/__tests__/thunk.test.ts +13 -7
  39. package/__tests__/traverse.test.ts +76 -54
  40. package/__tests__/tsGenerics.test.ts +12 -12
  41. package/__tests__/type.test.ts +36 -0
  42. package/__tests__/typeReference.test.ts +7 -7
  43. package/__tests__/unenclosed.test.ts +116 -100
  44. package/__tests__/union.test.ts +171 -104
  45. package/ark.ts +21 -65
  46. package/generic.ts +69 -0
  47. package/main.ts +6 -18
  48. package/match.ts +195 -93
  49. package/module.ts +15 -0
  50. package/out/ark.d.ts +15 -39
  51. package/out/ark.js +9 -18
  52. package/out/ark.js.map +1 -1
  53. package/out/generic.d.ts +21 -0
  54. package/out/generic.js +24 -0
  55. package/out/generic.js.map +1 -0
  56. package/out/main.d.ts +6 -7
  57. package/out/main.js +4 -3
  58. package/out/main.js.map +1 -1
  59. package/out/match.d.ts +57 -34
  60. package/out/match.js +51 -17
  61. package/out/match.js.map +1 -1
  62. package/out/module.d.ts +10 -0
  63. package/out/module.js +3 -0
  64. package/out/module.js.map +1 -0
  65. package/out/parser/definition.d.ts +11 -13
  66. package/out/parser/definition.js +10 -13
  67. package/out/parser/definition.js.map +1 -1
  68. package/out/parser/generic.d.ts +5 -7
  69. package/out/parser/generic.js +7 -11
  70. package/out/parser/generic.js.map +1 -1
  71. package/out/parser/objectLiteral.d.ts +45 -14
  72. package/out/parser/objectLiteral.js +61 -52
  73. package/out/parser/objectLiteral.js.map +1 -1
  74. package/out/parser/semantic/bounds.d.ts +10 -8
  75. package/out/parser/semantic/bounds.js +0 -1
  76. package/out/parser/semantic/bounds.js.map +1 -1
  77. package/out/parser/semantic/divisor.d.ts +5 -7
  78. package/out/parser/semantic/divisor.js +0 -1
  79. package/out/parser/semantic/infer.d.ts +24 -0
  80. package/out/parser/semantic/infer.js +1 -0
  81. package/out/parser/semantic/infer.js.map +1 -0
  82. package/out/parser/semantic/utils.d.ts +3 -7
  83. package/out/parser/semantic/utils.js +0 -1
  84. package/out/parser/semantic/validate.d.ts +15 -14
  85. package/out/parser/semantic/validate.js +1 -1
  86. package/out/parser/semantic/validate.js.map +1 -1
  87. package/out/parser/string/reduce/dynamic.d.ts +13 -13
  88. package/out/parser/string/reduce/dynamic.js +31 -26
  89. package/out/parser/string/reduce/dynamic.js.map +1 -1
  90. package/out/parser/string/reduce/shared.d.ts +6 -20
  91. package/out/parser/string/reduce/shared.js +0 -1
  92. package/out/parser/string/reduce/shared.js.map +1 -1
  93. package/out/parser/string/reduce/static.d.ts +27 -24
  94. package/out/parser/string/reduce/static.js +0 -1
  95. package/out/parser/string/shift/operand/date.d.ts +3 -3
  96. package/out/parser/string/shift/operand/date.js +4 -7
  97. package/out/parser/string/shift/operand/date.js.map +1 -1
  98. package/out/parser/string/shift/operand/enclosed.d.ts +4 -19
  99. package/out/parser/string/shift/operand/enclosed.js +12 -13
  100. package/out/parser/string/shift/operand/enclosed.js.map +1 -1
  101. package/out/parser/string/shift/operand/genericArgs.d.ts +9 -10
  102. package/out/parser/string/shift/operand/genericArgs.js +6 -10
  103. package/out/parser/string/shift/operand/genericArgs.js.map +1 -1
  104. package/out/parser/string/shift/operand/operand.d.ts +3 -4
  105. package/out/parser/string/shift/operand/operand.js +8 -12
  106. package/out/parser/string/shift/operand/operand.js.map +1 -1
  107. package/out/parser/string/shift/operand/unenclosed.d.ts +15 -22
  108. package/out/parser/string/shift/operand/unenclosed.js +24 -36
  109. package/out/parser/string/shift/operand/unenclosed.js.map +1 -1
  110. package/out/parser/string/shift/operator/bounds.d.ts +9 -13
  111. package/out/parser/string/shift/operator/bounds.js +43 -54
  112. package/out/parser/string/shift/operator/bounds.js.map +1 -1
  113. package/out/parser/string/shift/operator/divisor.d.ts +2 -4
  114. package/out/parser/string/shift/operator/divisor.js +1 -3
  115. package/out/parser/string/shift/operator/divisor.js.map +1 -1
  116. package/out/parser/string/shift/operator/operator.d.ts +2 -3
  117. package/out/parser/string/shift/operator/operator.js +12 -19
  118. package/out/parser/string/shift/operator/operator.js.map +1 -1
  119. package/out/parser/string/shift/scanner.d.ts +2 -2
  120. package/out/parser/string/shift/scanner.js +14 -16
  121. package/out/parser/string/shift/scanner.js.map +1 -1
  122. package/out/parser/string/string.d.ts +8 -6
  123. package/out/parser/string/string.js +1 -3
  124. package/out/parser/string/string.js.map +1 -1
  125. package/out/parser/tuple.d.ts +102 -43
  126. package/out/parser/tuple.js +119 -87
  127. package/out/parser/tuple.js.map +1 -1
  128. package/out/scope.d.ts +43 -120
  129. package/out/scope.js +39 -209
  130. package/out/scope.js.map +1 -1
  131. package/out/type.d.ts +43 -64
  132. package/out/type.js +30 -131
  133. package/out/type.js.map +1 -1
  134. package/package.json +7 -3
  135. package/parser/definition.ts +77 -93
  136. package/parser/generic.ts +38 -40
  137. package/parser/objectLiteral.ts +172 -136
  138. package/parser/semantic/bounds.ts +33 -32
  139. package/parser/semantic/divisor.ts +8 -10
  140. package/parser/semantic/infer.ts +141 -0
  141. package/parser/semantic/utils.ts +12 -23
  142. package/parser/semantic/validate.ts +81 -73
  143. package/parser/string/reduce/dynamic.ts +67 -55
  144. package/parser/string/reduce/shared.ts +1 -3
  145. package/parser/string/reduce/static.ts +67 -69
  146. package/parser/string/shift/operand/date.ts +15 -14
  147. package/parser/string/shift/operand/enclosed.ts +30 -25
  148. package/parser/string/shift/operand/genericArgs.ts +46 -45
  149. package/parser/string/shift/operand/operand.ts +32 -38
  150. package/parser/string/shift/operand/unenclosed.ts +107 -158
  151. package/parser/string/shift/operator/bounds.ts +118 -112
  152. package/parser/string/shift/operator/divisor.ts +14 -17
  153. package/parser/string/shift/operator/operator.ts +35 -46
  154. package/parser/string/shift/scanner.ts +51 -50
  155. package/parser/string/string.ts +30 -35
  156. package/parser/tuple.ts +375 -307
  157. package/scope.ts +170 -453
  158. package/type.ts +193 -274
  159. package/__tests__/astUtils.test.ts +0 -17
  160. package/__tests__/cyclic.test.ts +0 -144
  161. package/__tests__/jsdoc.test.ts +0 -64
  162. package/__tests__/morph.test.ts +0 -409
  163. package/__tests__/nodeDefinitions.test.ts +0 -190
  164. package/__tests__/typeMethods.test.ts +0 -69
  165. package/out/ark.d.ts.map +0 -1
  166. package/out/arkConfig.d.ts +0 -2
  167. package/out/arkConfig.d.ts.map +0 -1
  168. package/out/arkConfig.js +0 -10
  169. package/out/arkConfig.js.map +0 -1
  170. package/out/main.d.ts.map +0 -1
  171. package/out/match.d.ts.map +0 -1
  172. package/out/parser/definition.d.ts.map +0 -1
  173. package/out/parser/generic.d.ts.map +0 -1
  174. package/out/parser/objectLiteral.d.ts.map +0 -1
  175. package/out/parser/semantic/bounds.d.ts.map +0 -1
  176. package/out/parser/semantic/divisor.d.ts.map +0 -1
  177. package/out/parser/semantic/intersections.d.ts +0 -14
  178. package/out/parser/semantic/intersections.d.ts.map +0 -1
  179. package/out/parser/semantic/intersections.js +0 -2
  180. package/out/parser/semantic/intersections.js.map +0 -1
  181. package/out/parser/semantic/semantic.d.ts +0 -33
  182. package/out/parser/semantic/semantic.d.ts.map +0 -1
  183. package/out/parser/semantic/semantic.js +0 -2
  184. package/out/parser/semantic/semantic.js.map +0 -1
  185. package/out/parser/semantic/utils.d.ts.map +0 -1
  186. package/out/parser/semantic/validate.d.ts.map +0 -1
  187. package/out/parser/shared.d.ts +0 -54
  188. package/out/parser/shared.d.ts.map +0 -1
  189. package/out/parser/shared.js +0 -47
  190. package/out/parser/shared.js.map +0 -1
  191. package/out/parser/string/reduce/dynamic.d.ts.map +0 -1
  192. package/out/parser/string/reduce/shared.d.ts.map +0 -1
  193. package/out/parser/string/reduce/static.d.ts.map +0 -1
  194. package/out/parser/string/shift/operand/date.d.ts.map +0 -1
  195. package/out/parser/string/shift/operand/enclosed.d.ts.map +0 -1
  196. package/out/parser/string/shift/operand/genericArgs.d.ts.map +0 -1
  197. package/out/parser/string/shift/operand/operand.d.ts.map +0 -1
  198. package/out/parser/string/shift/operand/unenclosed.d.ts.map +0 -1
  199. package/out/parser/string/shift/operator/bounds.d.ts.map +0 -1
  200. package/out/parser/string/shift/operator/divisor.d.ts.map +0 -1
  201. package/out/parser/string/shift/operator/operator.d.ts.map +0 -1
  202. package/out/parser/string/shift/scanner.d.ts.map +0 -1
  203. package/out/parser/string/string.d.ts.map +0 -1
  204. package/out/parser/tuple.d.ts.map +0 -1
  205. package/out/scope.d.ts.map +0 -1
  206. package/out/test.d.ts +0 -2
  207. package/out/test.d.ts.map +0 -1
  208. package/out/test.js +0 -7
  209. package/out/test.js.map +0 -1
  210. package/out/tsconfig.build.tsbuildinfo +0 -1
  211. package/out/type.d.ts.map +0 -1
  212. package/out/util.d.ts +0 -19
  213. package/out/util.d.ts.map +0 -1
  214. package/out/util.js +0 -7
  215. package/out/util.js.map +0 -1
  216. package/parser/semantic/intersections.ts +0 -46
  217. package/parser/semantic/semantic.ts +0 -144
  218. package/parser/shared.ts +0 -152
  219. package/util.ts +0 -36
package/parser/tuple.ts CHANGED
@@ -1,124 +1,176 @@
1
1
  import {
2
- keywords,
3
- schema,
4
2
  type BaseMeta,
5
3
  type Morph,
4
+ type MutableInner,
5
+ type Node,
6
6
  type Out,
7
7
  type Predicate,
8
- type Schema,
9
- type TypeNode,
10
- type ValidatorKind,
11
- type extractIn,
12
- type extractOut,
8
+ type RawSchema,
9
+ type UnionChildKind,
10
+ type UnknownSchema,
11
+ type distillConstrainableIn,
12
+ type distillConstrainableOut,
13
+ type inferIntersection,
13
14
  type inferMorphOut,
14
- type inferNarrow
15
+ type inferNarrow,
16
+ jsObjects,
17
+ makeRootAndArrayPropertiesMutable,
18
+ tsKeywords
15
19
  } from "@arktype/schema"
16
20
  import {
17
- isArray,
18
- objectKindOrDomainOf,
19
- printable,
20
- throwParseError,
21
21
  type BuiltinObjectKind,
22
22
  type Constructor,
23
23
  type Domain,
24
- type List,
24
+ type ErrorMessage,
25
+ append,
26
+ type array,
25
27
  type conform,
26
- type evaluate,
27
- type isAny
28
+ objectKindOrDomainOf,
29
+ type show,
30
+ throwParseError
28
31
  } from "@arktype/util"
29
32
  import type { ParseContext } from "../scope.js"
30
33
  import type { inferDefinition, validateDefinition } from "./definition.js"
31
- import type { inferIntersection } from "./semantic/intersections.js"
32
- import type { InfixOperator, PostfixExpression } from "./semantic/semantic.js"
33
- import { writeUnsatisfiableExpressionError } from "./semantic/validate.js"
34
- import {
35
- parseEntry,
36
- type EntryParseResult,
37
- type validateObjectValue
38
- } from "./shared.js"
34
+ import type { InfixOperator, PostfixExpression } from "./semantic/infer.js"
39
35
  import { writeMissingRightOperandMessage } from "./string/shift/operand/unenclosed.js"
40
36
  import type { BaseCompletions } from "./string/string.js"
41
37
 
42
- export const parseTuple = (def: List, ctx: ParseContext) =>
38
+ export const parseTuple = (def: array, ctx: ParseContext): RawSchema =>
43
39
  maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx)
44
40
 
45
- export const parseTupleLiteral = (def: List, ctx: ParseContext): TypeNode => {
46
- const props: unknown[] = []
47
- let isVariadic = false
48
- for (let i = 0; i < def.length; i++) {
49
- let elementDef = def[i]
50
- ctx.path.push(`${i}`)
51
- if (typeof elementDef === "string" && elementDef.startsWith("...")) {
52
- elementDef = elementDef.slice(3)
53
- isVariadic = true
54
- } else if (
55
- isArray(elementDef) &&
56
- elementDef.length === 2 &&
57
- elementDef[0] === "..."
58
- ) {
59
- elementDef = elementDef[1]
60
- isVariadic = true
41
+ export const parseTupleLiteral = (def: array, ctx: ParseContext): RawSchema => {
42
+ let sequences: MutableInner<"sequence">[] = [{}]
43
+ let i = 0
44
+ while (i < def.length) {
45
+ let spread = false
46
+ let optional = false
47
+ if (def[i] === "..." && i < def.length - 1) {
48
+ spread = true
49
+ i++
61
50
  }
62
- const parsedEntry = parseEntry([`${i}`, elementDef])
63
- const value = ctx.scope.parse(parsedEntry.innerValue, ctx)
64
- if (isVariadic) {
65
- if (!value.extends(keywords.Array)) {
66
- return throwParseError(writeNonArrayRestMessage(elementDef))
67
- }
68
- if (i !== def.length - 1) {
69
- return throwParseError(prematureRestMessage)
70
- }
71
- // TODO: Fix builtins.arrayIndexTypeNode()
72
- const elementType = value.getPath()
73
- // TODO: first variadic i
74
- props.push({ key: keywords.number, value: elementType })
51
+
52
+ const element = ctx.$.parse(def[i], ctx)
53
+
54
+ i++
55
+ if (def[i] === "?") {
56
+ if (spread) return throwParseError(spreadOptionalMessage)
57
+
58
+ optional = true
59
+ i++
60
+ }
61
+ if (spread) {
62
+ if (!element.extends(jsObjects.Array))
63
+ return throwParseError(writeNonArraySpreadMessage(element.expression))
64
+
65
+ // a spread must be distributed over branches e.g.:
66
+ // def: [string, ...(number[] | [true, false])]
67
+ // nodes: [string, ...number[]] | [string, true, false]
68
+ sequences = sequences.flatMap(base =>
69
+ // since appendElement mutates base, we have to shallow-ish clone it for each branch
70
+ element.branches.map(branch =>
71
+ appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)
72
+ )
73
+ )
75
74
  } else {
76
- props.push({
77
- key: {
78
- name: `${i}`,
79
- prerequisite: false,
80
- optional: parsedEntry.kind === "optional"
81
- },
82
- value
83
- })
75
+ sequences = sequences.map(base =>
76
+ appendElement(base, optional ? "optional" : "required", element)
77
+ )
84
78
  }
85
- ctx.path.pop()
86
79
  }
87
- if (!isVariadic) {
88
- props.push({
89
- key: {
90
- name: "length",
91
- prerequisite: true,
92
- optional: false
93
- },
94
- // , ctx
95
- value: schema({ unit: def.length })
96
- })
80
+ return ctx.$.raw.schema(
81
+ sequences.map(
82
+ sequence =>
83
+ ({
84
+ proto: Array,
85
+ sequence
86
+ }) as const
87
+ )
88
+ )
89
+ }
90
+
91
+ type ElementKind = "optional" | "required" | "variadic"
92
+
93
+ const appendElement = (
94
+ base: MutableInner<"sequence">,
95
+ kind: ElementKind,
96
+ element: UnknownSchema
97
+ ): MutableInner<"sequence"> => {
98
+ switch (kind) {
99
+ case "required":
100
+ if (base.optional)
101
+ // e.g. [string?, number]
102
+ return throwParseError(requiredPostOptionalMessage)
103
+ if (base.variadic) {
104
+ // e.g. [...string[], number]
105
+ base.postfix = append(base.postfix, element)
106
+ } else {
107
+ // e.g. [string, number]
108
+ base.prefix = append(base.prefix, element)
109
+ }
110
+ return base
111
+ case "optional":
112
+ if (base.variadic)
113
+ // e.g. [...string[], number?]
114
+ return throwParseError(optionalPostVariadicMessage)
115
+ // e.g. [string, number?]
116
+ base.optional = append(base.optional, element)
117
+ return base
118
+ case "variadic":
119
+ // e.g. [...string[], number, ...string[]]
120
+ if (base.postfix) throwParseError(multipleVariadicMesage)
121
+ if (base.variadic) {
122
+ if (!base.variadic.equals(element)) {
123
+ // e.g. [...string[], ...number[]]
124
+ throwParseError(multipleVariadicMesage)
125
+ }
126
+ // e.g. [...string[], ...string[]]
127
+ // do nothing, second spread doesn't change the type
128
+ } else {
129
+ // e.g. [string, ...number[]]
130
+ base.variadic = element.raw
131
+ }
132
+ return base
133
+ }
134
+ }
135
+
136
+ const appendSpreadBranch = (
137
+ base: MutableInner<"sequence">,
138
+ branch: Node<UnionChildKind>
139
+ ): MutableInner<"sequence"> => {
140
+ const spread = branch.firstReferenceOfKind("sequence")
141
+ if (!spread) {
142
+ // the only array with no sequence reference is unknown[]
143
+ return appendElement(base, "variadic", tsKeywords.unknown)
97
144
  }
98
- // props , ctx
99
- return schema(Array)
145
+ spread.prefix.forEach(node => appendElement(base, "required", node))
146
+ spread.optional.forEach(node => appendElement(base, "optional", node))
147
+ spread.variadic && appendElement(base, "variadic", spread.variadic)
148
+ spread.postfix.forEach(node => appendElement(base, "required", node))
149
+ return base
100
150
  }
101
151
 
102
- export const maybeParseTupleExpression = (
103
- def: List,
152
+ const maybeParseTupleExpression = (
153
+ def: array,
104
154
  ctx: ParseContext
105
- ): TypeNode | undefined => {
106
- const tupleExpressionResult = isIndexOneExpression(def)
107
- ? indexOneParsers[def[1]](def as never, ctx)
108
- : isIndexZeroExpression(def)
109
- ? prefixParsers[def[0]](def as never, ctx)
155
+ ): RawSchema | undefined => {
156
+ const tupleExpressionResult =
157
+ isIndexZeroExpression(def) ? prefixParsers[def[0]](def as never, ctx)
158
+ : isIndexOneExpression(def) ? indexOneParsers[def[1]](def as never, ctx)
110
159
  : undefined
111
- if (tupleExpressionResult) {
112
- return tupleExpressionResult.isNever()
113
- ? throwParseError(
114
- writeUnsatisfiableExpressionError(
115
- def
116
- .map((def) => (typeof def === "string" ? def : printable(def)))
117
- .join(" ")
118
- )
119
- )
120
- : tupleExpressionResult
121
- }
160
+ return tupleExpressionResult
161
+
162
+ // TODO: remove
163
+ // return tupleExpressionResult.isNever()
164
+ // ? throwParseError(
165
+ // writeUnsatisfiableExpressionError(
166
+ // def
167
+ // .map((def) =>
168
+ // typeof def === "string" ? def : printable(def)
169
+ // )
170
+ // .join(" ")
171
+ // )
172
+ // )
173
+ // : tupleExpressionResult
122
174
  }
123
175
 
124
176
  // It is *extremely* important we use readonly any time we check a tuple against
@@ -126,174 +178,197 @@ export const maybeParseTupleExpression = (
126
178
  // def is declared as a const parameter.
127
179
  type InfixExpression = readonly [unknown, InfixOperator, ...unknown[]]
128
180
 
129
- export type validateTuple<
130
- def extends List,
181
+ export type validateTuple<def extends array, $, args> =
182
+ def extends IndexZeroExpression ? validatePrefixExpression<def, $, args>
183
+ : def extends PostfixExpression ? validatePostfixExpression<def, $, args>
184
+ : def extends InfixExpression ? validateInfixExpression<def, $, args>
185
+ : def extends (
186
+ readonly ["", ...unknown[]] | readonly [unknown, "", ...unknown[]]
187
+ ) ?
188
+ readonly [
189
+ def[0] extends "" ? BaseCompletions<$, args, IndexZeroOperator | "...">
190
+ : def[0],
191
+ def[1] extends "" ?
192
+ BaseCompletions<$, args, IndexOneOperator | "..." | "?">
193
+ : def[1]
194
+ ]
195
+ : validateTupleLiteral<def, $, args>
196
+
197
+ export type validateTupleLiteral<def extends array, $, args> = Readonly<
198
+ parseSequence<def, $, args>["validated"]
199
+ >
200
+
201
+ type inferTupleLiteral<def extends array, $, args> = parseSequence<
202
+ def,
131
203
  $,
132
204
  args
133
- > = def extends IndexZeroExpression
134
- ? validatePrefixExpression<def, $, args>
135
- : def extends PostfixExpression
136
- ? validatePostfixExpression<def, $, args>
137
- : def extends InfixExpression
138
- ? validateInfixExpression<def, $, args>
139
- : def extends
140
- | readonly ["", ...unknown[]]
141
- | readonly [unknown, "", ...unknown[]]
142
- ? readonly [
143
- def[0] extends "" ? BaseCompletions<$, args, IndexZeroOperator> : def[0],
144
- def[1] extends "" ? BaseCompletions<$, args, IndexOneOperator> : def[1]
145
- ]
146
- : validateTupleLiteral<def, $, args>
147
-
148
- export type validateTupleLiteral<
149
- def extends List,
150
- $,
151
- args,
152
- result extends unknown[] = []
153
- > = def extends readonly [infer head, ...infer tail]
154
- ? validateTupleLiteral<
155
- tail,
156
- $,
157
- args,
158
- [...result, validateTupleElement<head, tail, $, args>]
159
- >
160
- : result
161
-
162
- type validateTupleElement<head, tail, $, args> =
163
- head extends variadicExpression<infer operand>
164
- ? validateDefinition<operand, $, args> extends infer syntacticResult
165
- ? syntacticResult extends operand
166
- ? semanticallyValidateRestElement<
167
- operand,
168
- $,
169
- args
170
- > extends infer semanticResult
171
- ? semanticResult extends operand
172
- ? tail extends []
173
- ? head
174
- : prematureRestMessage
175
- : semanticResult
176
- : never
177
- : syntacticResult
178
- : never
179
- : validateObjectValue<head, $, args>
180
-
181
- type semanticallyValidateRestElement<operand, $, args> = inferDefinition<
182
- operand,
205
+ >["inferred"]
206
+
207
+ type SequenceParseState = {
208
+ unscanned: array
209
+ inferred: array
210
+ validated: array
211
+ }
212
+
213
+ type parseSequence<def extends array, $, args> = parseNextElement<
214
+ {
215
+ unscanned: def
216
+ inferred: []
217
+ validated: []
218
+ },
183
219
  $,
184
220
  args
185
- > extends infer result
186
- ? result extends never
187
- ? writeNonArrayRestMessage<operand>
188
- : isAny<result> extends true
189
- ? writeNonArrayRestMessage<operand>
190
- : result extends readonly unknown[]
191
- ? operand
192
- : writeNonArrayRestMessage<operand>
193
- : never
221
+ >
194
222
 
195
- export const writeNonArrayRestMessage = <operand>(operand: operand) =>
196
- `Rest element ${
197
- typeof operand === "string" ? `'${operand}'` : ""
198
- } must be an array` as writeNonArrayRestMessage<operand>
223
+ type PreparsedElement = {
224
+ head: unknown
225
+ tail: array
226
+ optional: boolean
227
+ spread: boolean
228
+ }
199
229
 
200
- type writeNonArrayRestMessage<operand> = `Rest element ${operand extends string
201
- ? `'${operand}'`
202
- : ""} must be an array`
230
+ namespace PreparsedElement {
231
+ export type from<result extends PreparsedElement> = result
232
+ }
203
233
 
204
- export const prematureRestMessage = `Rest elements are only allowed at the end of a tuple`
234
+ type preparseNextElement<s extends SequenceParseState> =
235
+ s["unscanned"] extends readonly ["...", infer head, ...infer tail] ?
236
+ tail extends readonly ["?", ...infer postOptionalTail] ?
237
+ PreparsedElement.from<{
238
+ head: head
239
+ tail: postOptionalTail
240
+ // this will be an error we have to handle
241
+ optional: true
242
+ spread: true
243
+ }>
244
+ : PreparsedElement.from<{
245
+ head: head
246
+ tail: tail
247
+ optional: false
248
+ spread: true
249
+ }>
250
+ : s["unscanned"] extends readonly [infer head, "?", ...infer tail] ?
251
+ PreparsedElement.from<{
252
+ head: head
253
+ tail: tail
254
+ optional: true
255
+ spread: false
256
+ }>
257
+ : s["unscanned"] extends readonly [infer head, ...infer tail] ?
258
+ PreparsedElement.from<{
259
+ head: head
260
+ tail: tail
261
+ optional: false
262
+ spread: false
263
+ }>
264
+ : null
265
+
266
+ type parseNextElement<s extends SequenceParseState, $, args> =
267
+ preparseNextElement<s> extends infer next extends PreparsedElement ?
268
+ parseNextElement<
269
+ {
270
+ unscanned: next["tail"]
271
+ inferred: next["spread"] extends true ?
272
+ [
273
+ ...s["inferred"],
274
+ ...conform<inferDefinition<next["head"], $, args>, array>
275
+ ]
276
+ : next["optional"] extends true ?
277
+ [...s["inferred"], inferDefinition<next["head"], $, args>?]
278
+ : [...s["inferred"], inferDefinition<next["head"], $, args>]
279
+ validated: [
280
+ ...s["validated"],
281
+ ...(next["spread"] extends true ?
282
+ [
283
+ inferDefinition<next["head"], $, args> extends (
284
+ infer spreadOperand extends array
285
+ ) ?
286
+ [number, number] extends (
287
+ [s["inferred"]["length"], spreadOperand["length"]]
288
+ ) ?
289
+ ErrorMessage<multipleVariadicMessage>
290
+ : "..."
291
+ : ErrorMessage<writeNonArraySpreadMessage<next["head"]>>
292
+ ]
293
+ : []),
294
+ [next["optional"] | next["spread"], "?"] extends (
295
+ [false, s["validated"][number]]
296
+ ) ?
297
+ ErrorMessage<requiredPostOptionalMessage>
298
+ : validateDefinition<next["head"], $, args>,
299
+ ...(next["optional"] extends true ?
300
+ [
301
+ next["spread"] extends true ? ErrorMessage<spreadOptionalMessage>
302
+ : number extends s["inferred"]["length"] ?
303
+ ErrorMessage<optionalPostVariadicMessage>
304
+ : "?"
305
+ ]
306
+ : [])
307
+ ]
308
+ },
309
+ $,
310
+ args
311
+ >
312
+ : s
205
313
 
206
- type prematureRestMessage = typeof prematureRestMessage
314
+ export const writeNonArraySpreadMessage = <operand extends string>(
315
+ operand: operand
316
+ ): writeNonArraySpreadMessage<operand> =>
317
+ `Spread element must be an array (was ${operand})` as never
207
318
 
208
- type inferTupleLiteral<
209
- def extends List,
210
- $,
211
- args,
212
- result extends unknown[] = []
213
- > = def extends readonly [infer head, ...infer tail]
214
- ? parseEntry<
215
- result["length"],
216
- head extends variadicExpression<infer operand> ? operand : head
217
- > extends infer entryParseResult extends EntryParseResult
218
- ? inferDefinition<
219
- entryParseResult["innerValue"],
220
- $,
221
- args
222
- > extends infer element
223
- ? head extends variadicExpression
224
- ? element extends readonly unknown[]
225
- ? inferTupleLiteral<tail, $, args, [...result, ...element]>
226
- : never
227
- : inferTupleLiteral<
228
- tail,
229
- $,
230
- args,
231
- entryParseResult["kind"] extends "optional"
232
- ? [...result, element?]
233
- : [...result, element]
234
- >
235
- : never
236
- : never
237
- : result
238
-
239
- type variadicExpression<operandDef = unknown> =
240
- | variadicStringExpression<operandDef & string>
241
- | variadicTupleExpression<operandDef>
242
-
243
- type variadicStringExpression<operandDef extends string = string> =
244
- `...${operandDef}`
245
-
246
- type variadicTupleExpression<operandDef = unknown> = readonly [
247
- "...",
248
- operandDef
249
- ]
250
-
251
- export type inferTuple<def extends List, $, args> = def extends TupleExpression
252
- ? inferTupleExpression<def, $, args>
253
- : inferTupleLiteral<def, $, args>
254
-
255
- export type inferTupleExpression<
256
- def extends TupleExpression,
257
- $,
258
- args
259
- > = def[1] extends "[]"
260
- ? inferDefinition<def[0], $, args>[]
261
- : def[1] extends "&"
262
- ? inferIntersection<
319
+ type writeNonArraySpreadMessage<operand> =
320
+ `Spread element must be an array${operand extends string ? `(was ${operand})`
321
+ : ""}`
322
+
323
+ export const multipleVariadicMesage =
324
+ "A tuple may have at most one variadic element"
325
+
326
+ type multipleVariadicMessage = typeof multipleVariadicMesage
327
+
328
+ export const requiredPostOptionalMessage =
329
+ "A required element may not follow an optional element"
330
+
331
+ type requiredPostOptionalMessage = typeof requiredPostOptionalMessage
332
+
333
+ export const optionalPostVariadicMessage =
334
+ "An optional element may not follow a variadic element"
335
+
336
+ type optionalPostVariadicMessage = typeof optionalPostVariadicMessage
337
+
338
+ export const spreadOptionalMessage = "A spread element cannot be optional"
339
+
340
+ type spreadOptionalMessage = typeof optionalPostVariadicMessage
341
+
342
+ export type inferTuple<def extends array, $, args> =
343
+ def extends TupleExpression ? inferTupleExpression<def, $, args>
344
+ : inferTupleLiteral<def, $, args>
345
+
346
+ export type inferTupleExpression<def extends TupleExpression, $, args> =
347
+ def[1] extends "[]" ? inferDefinition<def[0], $, args>[]
348
+ : def[1] extends "&" ?
349
+ inferIntersection<
263
350
  inferDefinition<def[0], $, args>,
264
351
  inferDefinition<def[2], $, args>
265
- >
266
- : def[1] extends "|"
267
- ? inferDefinition<def[0], $, args> | inferDefinition<def[2], $, args>
268
- : def[1] extends ":"
269
- ? inferNarrow<inferDefinition<def[0], $, args>, def[2]>
270
- : def[1] extends "=>"
271
- ? parseMorph<def[0], def[2], $, args>
272
- : def[1] extends "@"
273
- ? inferDefinition<def[0], $, args>
274
- : def extends readonly ["===", ...infer values]
275
- ? values[number]
276
- : def extends readonly [
277
- "instanceof",
278
- ...infer constructors extends Constructor[]
279
- ]
280
- ? InstanceType<constructors[number]>
281
- : def[0] extends "keyof"
282
- ? inferKeyOfExpression<def[1], $, args>
352
+ >
353
+ : def[1] extends "|" ?
354
+ inferDefinition<def[0], $, args> | inferDefinition<def[2], $, args>
355
+ : def[1] extends ":" ? inferNarrow<inferDefinition<def[0], $, args>, def[2]>
356
+ : def[1] extends "=>" ? parseMorph<def[0], def[2], $, args>
357
+ : def[1] extends "@" ? inferDefinition<def[0], $, args>
358
+ : def extends readonly ["===", ...infer values] ? values[number]
359
+ : def extends (
360
+ readonly ["instanceof", ...infer constructors extends Constructor[]]
361
+ ) ?
362
+ InstanceType<constructors[number]>
363
+ : def[0] extends "keyof" ? inferKeyOfExpression<def[1], $, args>
283
364
  : never
284
365
 
285
- export type validatePrefixExpression<
286
- def extends IndexZeroExpression,
287
- $,
288
- args
289
- > = def["length"] extends 1
290
- ? readonly [writeMissingRightOperandMessage<def[0]>]
291
- : def[0] extends "keyof"
292
- ? readonly [def[0], validateDefinition<def[1], $, args>]
293
- : def[0] extends "==="
294
- ? readonly [def[0], ...unknown[]]
295
- : def[0] extends "instanceof"
296
- ? readonly [def[0], ...Constructor[]]
366
+ export type validatePrefixExpression<def extends IndexZeroExpression, $, args> =
367
+ def["length"] extends 1 ? readonly [writeMissingRightOperandMessage<def[0]>]
368
+ : def[0] extends "keyof" ?
369
+ readonly [def[0], validateDefinition<def[1], $, args>]
370
+ : def[0] extends "===" ? readonly [def[0], ...unknown[]]
371
+ : def[0] extends "instanceof" ? readonly [def[0], ...Constructor[]]
297
372
  : never
298
373
 
299
374
  export type validatePostfixExpression<
@@ -304,63 +379,60 @@ export type validatePostfixExpression<
304
379
  // expressions at index 1 after TS 5.1
305
380
  > = conform<def, readonly [validateDefinition<def[0], $, args>, "[]"]>
306
381
 
307
- export type validateInfixExpression<
308
- def extends InfixExpression,
309
- $,
310
- args
311
- > = def["length"] extends 2
312
- ? readonly [def[0], writeMissingRightOperandMessage<def[1]>]
313
- : readonly [
382
+ export type validateInfixExpression<def extends InfixExpression, $, args> =
383
+ def["length"] extends 2 ?
384
+ readonly [def[0], writeMissingRightOperandMessage<def[1]>]
385
+ : readonly [
314
386
  validateDefinition<def[0], $, args>,
315
387
  def[1],
316
- def[1] extends "|"
317
- ? validateDefinition<def[2], $, args>
318
- : def[1] extends "&"
319
- ? validateDefinition<def[2], $, args>
320
- : def[1] extends ":"
321
- ? Predicate<extractIn<inferDefinition<def[0], $, args>>>
322
- : def[1] extends "=>"
323
- ? Morph<extractOut<inferDefinition<def[0], $, args>>, unknown>
324
- : def[1] extends "@"
325
- ? BaseMeta | string
326
- : validateDefinition<def[2], $, args>
327
- ]
388
+ def[1] extends "|" ? validateDefinition<def[2], $, args>
389
+ : def[1] extends "&" ? validateDefinition<def[2], $, args>
390
+ : def[1] extends ":" ?
391
+ Predicate<distillConstrainableIn<inferDefinition<def[0], $, args>>>
392
+ : def[1] extends "=>" ?
393
+ Morph<
394
+ distillConstrainableOut<inferDefinition<def[0], $, args>>,
395
+ unknown
396
+ >
397
+ : def[1] extends "@" ? BaseMeta | string
398
+ : validateDefinition<def[2], $, args>
399
+ ]
328
400
 
329
401
  export type UnparsedTupleExpressionInput = {
330
402
  instanceof: Constructor
331
403
  "===": unknown
332
404
  }
333
405
 
334
- export type UnparsedTupleOperator = evaluate<keyof UnparsedTupleExpressionInput>
406
+ export type UnparsedTupleOperator = show<keyof UnparsedTupleExpressionInput>
335
407
 
336
408
  export const parseKeyOfTuple: PrefixParser<"keyof"> = (def, ctx) =>
337
- ctx.scope.parse(def[1], ctx).keyof()
409
+ ctx.$.parse(def[1], ctx).keyof()
338
410
 
339
- export type inferKeyOfExpression<operandDef, $, args> = evaluate<
411
+ export type inferKeyOfExpression<operandDef, $, args> = show<
340
412
  keyof inferDefinition<operandDef, $, args>
341
413
  >
342
414
 
343
415
  const parseBranchTuple: PostfixParser<"|" | "&"> = (def, ctx) => {
344
- if (def[2] === undefined) {
416
+ if (def[2] === undefined)
345
417
  return throwParseError(writeMissingRightOperandMessage(def[1], ""))
346
- }
347
- const l = ctx.scope.parse(def[0], ctx)
348
- const r = ctx.scope.parse(def[2], ctx)
418
+
419
+ const l = ctx.$.parse(def[0], ctx)
420
+ const r = ctx.$.parse(def[2], ctx)
349
421
  return def[1] === "&" ? l.and(r) : l.or(r)
350
422
  }
351
423
 
352
424
  const parseArrayTuple: PostfixParser<"[]"> = (def, ctx) =>
353
- ctx.scope.parse(def[0], ctx).array()
425
+ ctx.$.parse(def[0], ctx).array()
354
426
 
355
427
  export type PostfixParser<token extends IndexOneOperator> = (
356
428
  def: IndexOneExpression<token>,
357
429
  ctx: ParseContext
358
- ) => TypeNode
430
+ ) => RawSchema
359
431
 
360
432
  export type PrefixParser<token extends IndexZeroOperator> = (
361
433
  def: IndexZeroExpression<token>,
362
434
  ctx: ParseContext
363
- ) => TypeNode
435
+ ) => RawSchema
364
436
 
365
437
  export type TupleExpression = IndexZeroExpression | IndexOneExpression
366
438
 
@@ -376,7 +448,7 @@ export type IndexOneExpression<
376
448
  token extends IndexOneOperator = IndexOneOperator
377
449
  > = readonly [unknown, token, ...unknown[]]
378
450
 
379
- const isIndexOneExpression = (def: List): def is IndexOneExpression =>
451
+ const isIndexOneExpression = (def: array): def is IndexOneExpression =>
380
452
  indexOneParsers[def[1] as IndexOneOperator] !== undefined
381
453
 
382
454
  export const parseMorphTuple: PostfixParser<"=>"> = (def, ctx) => {
@@ -386,25 +458,23 @@ export const parseMorphTuple: PostfixParser<"=>"> = (def, ctx) => {
386
458
  )
387
459
  }
388
460
  // TODO: nested morphs?
389
- return schema({
390
- in: ctx.scope.parse(def[0], ctx) as Schema<ValidatorKind>,
391
- morph: def[2] as Morph
392
- })
461
+ return ctx.$.parse(def[0], ctx).pipe(def[2] as Morph)
393
462
  }
394
463
 
395
464
  export const writeMalformedFunctionalExpressionMessage = (
396
- operator: FunctionalTupleOperator,
465
+ operator: ":" | "=>",
397
466
  value: unknown
398
467
  ) =>
399
468
  `${
400
469
  operator === ":" ? "Narrow" : "Morph"
401
- } expression requires a function following '${operator}' (was ${typeof value})`
470
+ } expression requires a function following '${operator}' (was ${typeof value})` as const
402
471
 
403
- export type parseMorph<inDef, morph, $, args> = morph extends Morph
404
- ? (
405
- In: extractIn<inferDefinition<inDef, $, args>>
406
- ) => Out<inferMorphOut<ReturnType<morph>>>
407
- : never
472
+ export type parseMorph<inDef, morph, $, args> =
473
+ morph extends Morph ?
474
+ (
475
+ In: distillConstrainableIn<inferDefinition<inDef, $, args>>
476
+ ) => Out<inferMorphOut<morph>>
477
+ : never
408
478
 
409
479
  export const parseNarrowTuple: PostfixParser<":"> = (def, ctx) => {
410
480
  if (typeof def[2] !== "function") {
@@ -412,14 +482,11 @@ export const parseNarrowTuple: PostfixParser<":"> = (def, ctx) => {
412
482
  writeMalformedFunctionalExpressionMessage(":", def[2])
413
483
  )
414
484
  }
415
- return ctx.scope
416
- .parse(def[0], ctx)
417
- .constrain("predicate", def[2] as Predicate)
485
+ return ctx.$.parse(def[0], ctx).constrain("predicate", def[2] as Predicate)
418
486
  }
419
487
 
420
- const parseAttributeTuple: PostfixParser<"@"> = (def, ctx) => {
421
- return ctx.scope.parse(def[0], ctx)
422
- }
488
+ const parseAttributeTuple: PostfixParser<"@"> = (def, ctx) =>
489
+ ctx.$.parse(def[0], ctx).configureShallowDescendants(def[2] as never)
423
490
 
424
491
  const indexOneParsers: {
425
492
  [token in IndexOneOperator]: PostfixParser<token>
@@ -432,8 +499,6 @@ const indexOneParsers: {
432
499
  "@": parseAttributeTuple
433
500
  }
434
501
 
435
- export type FunctionalTupleOperator = ":" | "=>"
436
-
437
502
  export type IndexZeroOperator = "keyof" | "instanceof" | "==="
438
503
 
439
504
  export type IndexZeroExpression<
@@ -444,7 +509,7 @@ const prefixParsers: {
444
509
  [token in IndexZeroOperator]: PrefixParser<token>
445
510
  } = {
446
511
  keyof: parseKeyOfTuple,
447
- instanceof: (def) => {
512
+ instanceof: (def, ctx) => {
448
513
  if (typeof def[1] !== "function") {
449
514
  return throwParseError(
450
515
  writeInvalidConstructorMessage(objectKindOrDomainOf(def[1]))
@@ -452,23 +517,26 @@ const prefixParsers: {
452
517
  }
453
518
  const branches = def
454
519
  .slice(1)
455
- .map((ctor) =>
456
- typeof ctor === "function"
457
- ? { proto: ctor as Constructor }
458
- : throwParseError(
459
- writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))
460
- )
520
+ .map(ctor =>
521
+ typeof ctor === "function" ?
522
+ ctx.$.node("proto", { proto: ctor as Constructor })
523
+ : throwParseError(
524
+ writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))
525
+ )
461
526
  )
462
- return schema(...branches)
527
+ return branches.length === 1 ?
528
+ branches[0]
529
+ : ctx.$.node("union", { branches })
463
530
  },
464
- "===": (def) => schema.units(...def.slice(1))
531
+ "===": (def, ctx) => ctx.$.units(def.slice(1))
465
532
  }
466
533
 
467
- const isIndexZeroExpression = (def: List): def is IndexZeroExpression =>
534
+ const isIndexZeroExpression = (def: array): def is IndexZeroExpression =>
468
535
  prefixParsers[def[0] as IndexZeroOperator] !== undefined
469
536
 
470
537
  export const writeInvalidConstructorMessage = <
471
538
  actual extends Domain | BuiltinObjectKind
472
539
  >(
473
540
  actual: actual
474
- ) => `Expected a constructor following 'instanceof' operator (was ${actual})`
541
+ ) =>
542
+ `Expected a constructor following 'instanceof' operator (was ${actual})` as const