MCPcopy Create free account
hub / github.com/arktypeio/arktype / parseTupleLiteral

Function parseTupleLiteral

ark/type/parser/tupleLiteral.ts:30–103  ·  view source on GitHub ↗
(
	def: array,
	ctx: BaseParseContext
)

Source from the content-addressed store, hash-verified

28} from "./property.ts"
29
30export const parseTupleLiteral = (
31 def: array,
32 ctx: BaseParseContext
33): BaseRoot => {
34 let sequences: mutableInnerOfKind<"sequence">[] = [{}]
35 let i = 0
36 while (i < def.length) {
37 let spread = false
38 if (def[i] === "..." && i < def.length - 1) {
39 spread = true
40 i++
41 }
42
43 const parsedProperty = parseProperty(def[i], ctx)
44
45 const [valueNode, operator, possibleDefaultValue] =
46 !isArray(parsedProperty) ? [parsedProperty] : parsedProperty
47
48 // what's spread is its elements, which an optional or a default can't be
49 if (spread && operator) {
50 return throwParseError(
51 operator === "?" ? spreadOptionalMessage : spreadDefaultableMessage
52 )
53 }
54
55 // string defaults run no user code
56 if (
57 typeof def[i] === "string" &&
58 typeof possibleDefaultValue === "function"
59 )
60 checkDefault(valueNode, possibleDefaultValue(), null)
61
62 i++
63 if (spread) {
64 if (!valueNode.extends($ark.kw.Array))
65 return throwParseError(writeNonArraySpreadMessage(valueNode.expression))
66
67 // a spread must be distributed over branches e.g.:
68 // def: [string, ...(number[] | [true, false])]
69 // nodes: [string, ...number[]] | [string, true, false]
70 sequences = sequences.flatMap(base =>
71 // since appendElement mutates base, we have to shallow-ish clone it for each branch
72 valueNode.distribute(branch =>
73 appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)
74 )
75 )
76 } else {
77 sequences = sequences.map(base => {
78 if (operator === "?") return appendOptionalElement(base, valueNode)
79
80 if (operator === "=")
81 return appendDefaultableElement(base, valueNode, possibleDefaultValue)
82
83 return appendRequiredElement(base, valueNode)
84 })
85 }
86 }
87

Callers 1

parseTupleFunction · 0.90

Calls 14

parsePropertyFunction · 0.90
throwParseErrorFunction · 0.90
checkDefaultFunction · 0.90
isEmptyObjectFunction · 0.90
appendSpreadBranchFunction · 0.85
appendOptionalElementFunction · 0.85
appendDefaultableElementFunction · 0.85
appendRequiredElementFunction · 0.85
extendsMethod · 0.80
distributeMethod · 0.80

Tested by

no test coverage detected