| 93 | * allow undefined, as an optional key's value does |
| 94 | */ |
| 95 | const normalizedSequence = ( |
| 96 | raw: Sequence.Inner, |
| 97 | loose$?: BaseScope |
| 98 | ): Sequence.Inner | undefined => { |
| 99 | let widened = false |
| 100 | const widen = (node: BaseRoot): BaseRoot => { |
| 101 | const result = withUndefined(node) |
| 102 | if (result === node) return node |
| 103 | widened = true |
| 104 | return deferAliases(result, loose$!) as BaseRoot |
| 105 | } |
| 106 | let minVariadicLength = raw.minVariadicLength ?? 0 |
| 107 | const prefix = raw.prefix?.slice() ?? [] |
| 108 | const defaultables = |
| 109 | (loose$ ? |
| 110 | raw.defaultables?.map( |
| 111 | ([node, value]): Sequence.DefaultableElement => [widen(node), value] |
| 112 | ) |
| 113 | : raw.defaultables?.slice()) ?? [] |
| 114 | const optionals = |
| 115 | (loose$ ? raw.optionals?.map(widen) : raw.optionals?.slice()) ?? [] |
| 116 | const postfix = raw.postfix?.slice() ?? [] |
| 117 | if (raw.variadic) { |
| 118 | // optional elements equivalent to the variadic parameter are redundant |
| 119 | while (optionals[optionals.length - 1]?.equals(raw.variadic)) |
| 120 | optionals.pop() |
| 121 | |
| 122 | if (optionals.length === 0 && defaultables.length === 0) { |
| 123 | // If there are no optional, normalize prefix |
| 124 | // elements adjacent and equivalent to variadic: |
| 125 | // { variadic: number, prefix: [string, number] } |
| 126 | // reduces to: |
| 127 | // { variadic: number, prefix: [string], minVariadicLength: 1 } |
| 128 | while (prefix[prefix.length - 1]?.equals(raw.variadic)) { |
| 129 | prefix.pop() |
| 130 | minVariadicLength++ |
| 131 | } |
| 132 | } |
| 133 | // Normalize postfix elements adjacent and equivalent to variadic: |
| 134 | // { variadic: number, postfix: [number, number, 5] } |
| 135 | // reduces to: |
| 136 | // { variadic: number, postfix: [5], minVariadicLength: 2 } |
| 137 | while (postfix[0]?.equals(raw.variadic)) { |
| 138 | postfix.shift() |
| 139 | minVariadicLength++ |
| 140 | } |
| 141 | } else if (optionals.length === 0 && defaultables.length === 0) { |
| 142 | // if there's no variadic, optional or defaultable elements, |
| 143 | // postfix can just be appended to prefix |
| 144 | prefix.push(...postfix.splice(0)) |
| 145 | } |
| 146 | if ( |
| 147 | widened || |
| 148 | // if any variadic adjacent elements were moved to minVariadicLength |
| 149 | minVariadicLength !== (raw.minVariadicLength ?? 0) || |
| 150 | // or any postfix elements were moved to prefix |
| 151 | (raw.prefix && raw.prefix.length !== prefix.length) |
| 152 | ) { |