1 | // eslint-disable-next-line @typescript-eslint/no-extraneous-class
|
---|
2 | export abstract class _CodeOrName {
|
---|
3 | abstract readonly str: string
|
---|
4 | abstract readonly names: UsedNames
|
---|
5 | abstract toString(): string
|
---|
6 | abstract emptyStr(): boolean
|
---|
7 | }
|
---|
8 |
|
---|
9 | export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i
|
---|
10 |
|
---|
11 | export class Name extends _CodeOrName {
|
---|
12 | readonly str: string
|
---|
13 | constructor(s: string) {
|
---|
14 | super()
|
---|
15 | if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
|
---|
16 | this.str = s
|
---|
17 | }
|
---|
18 |
|
---|
19 | toString(): string {
|
---|
20 | return this.str
|
---|
21 | }
|
---|
22 |
|
---|
23 | emptyStr(): boolean {
|
---|
24 | return false
|
---|
25 | }
|
---|
26 |
|
---|
27 | get names(): UsedNames {
|
---|
28 | return {[this.str]: 1}
|
---|
29 | }
|
---|
30 | }
|
---|
31 |
|
---|
32 | export class _Code extends _CodeOrName {
|
---|
33 | readonly _items: readonly CodeItem[]
|
---|
34 | private _str?: string
|
---|
35 | private _names?: UsedNames
|
---|
36 |
|
---|
37 | constructor(code: string | readonly CodeItem[]) {
|
---|
38 | super()
|
---|
39 | this._items = typeof code === "string" ? [code] : code
|
---|
40 | }
|
---|
41 |
|
---|
42 | toString(): string {
|
---|
43 | return this.str
|
---|
44 | }
|
---|
45 |
|
---|
46 | emptyStr(): boolean {
|
---|
47 | if (this._items.length > 1) return false
|
---|
48 | const item = this._items[0]
|
---|
49 | return item === "" || item === '""'
|
---|
50 | }
|
---|
51 |
|
---|
52 | get str(): string {
|
---|
53 | return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, ""))
|
---|
54 | }
|
---|
55 |
|
---|
56 | get names(): UsedNames {
|
---|
57 | return (this._names ??= this._items.reduce((names: UsedNames, c) => {
|
---|
58 | if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1
|
---|
59 | return names
|
---|
60 | }, {}))
|
---|
61 | }
|
---|
62 | }
|
---|
63 |
|
---|
64 | export type CodeItem = Name | string | number | boolean | null
|
---|
65 |
|
---|
66 | export type UsedNames = Record<string, number | undefined>
|
---|
67 |
|
---|
68 | export type Code = _Code | Name
|
---|
69 |
|
---|
70 | export type SafeExpr = Code | number | boolean | null
|
---|
71 |
|
---|
72 | export const nil = new _Code("")
|
---|
73 |
|
---|
74 | type CodeArg = SafeExpr | string | undefined
|
---|
75 |
|
---|
76 | export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {
|
---|
77 | const code: CodeItem[] = [strs[0]]
|
---|
78 | let i = 0
|
---|
79 | while (i < args.length) {
|
---|
80 | addCodeArg(code, args[i])
|
---|
81 | code.push(strs[++i])
|
---|
82 | }
|
---|
83 | return new _Code(code)
|
---|
84 | }
|
---|
85 |
|
---|
86 | const plus = new _Code("+")
|
---|
87 |
|
---|
88 | export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {
|
---|
89 | const expr: CodeItem[] = [safeStringify(strs[0])]
|
---|
90 | let i = 0
|
---|
91 | while (i < args.length) {
|
---|
92 | expr.push(plus)
|
---|
93 | addCodeArg(expr, args[i])
|
---|
94 | expr.push(plus, safeStringify(strs[++i]))
|
---|
95 | }
|
---|
96 | optimize(expr)
|
---|
97 | return new _Code(expr)
|
---|
98 | }
|
---|
99 |
|
---|
100 | export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {
|
---|
101 | if (arg instanceof _Code) code.push(...arg._items)
|
---|
102 | else if (arg instanceof Name) code.push(arg)
|
---|
103 | else code.push(interpolate(arg))
|
---|
104 | }
|
---|
105 |
|
---|
106 | function optimize(expr: CodeItem[]): void {
|
---|
107 | let i = 1
|
---|
108 | while (i < expr.length - 1) {
|
---|
109 | if (expr[i] === plus) {
|
---|
110 | const res = mergeExprItems(expr[i - 1], expr[i + 1])
|
---|
111 | if (res !== undefined) {
|
---|
112 | expr.splice(i - 1, 3, res)
|
---|
113 | continue
|
---|
114 | }
|
---|
115 | expr[i++] = "+"
|
---|
116 | }
|
---|
117 | i++
|
---|
118 | }
|
---|
119 | }
|
---|
120 |
|
---|
121 | function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {
|
---|
122 | if (b === '""') return a
|
---|
123 | if (a === '""') return b
|
---|
124 | if (typeof a == "string") {
|
---|
125 | if (b instanceof Name || a[a.length - 1] !== '"') return
|
---|
126 | if (typeof b != "string") return `${a.slice(0, -1)}${b}"`
|
---|
127 | if (b[0] === '"') return a.slice(0, -1) + b.slice(1)
|
---|
128 | return
|
---|
129 | }
|
---|
130 | if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`
|
---|
131 | return
|
---|
132 | }
|
---|
133 |
|
---|
134 | export function strConcat(c1: Code, c2: Code): Code {
|
---|
135 | return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`
|
---|
136 | }
|
---|
137 |
|
---|
138 | // TODO do not allow arrays here
|
---|
139 | function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {
|
---|
140 | return typeof x == "number" || typeof x == "boolean" || x === null
|
---|
141 | ? x
|
---|
142 | : safeStringify(Array.isArray(x) ? x.join(",") : x)
|
---|
143 | }
|
---|
144 |
|
---|
145 | export function stringify(x: unknown): Code {
|
---|
146 | return new _Code(safeStringify(x))
|
---|
147 | }
|
---|
148 |
|
---|
149 | export function safeStringify(x: unknown): string {
|
---|
150 | return JSON.stringify(x)
|
---|
151 | .replace(/\u2028/g, "\\u2028")
|
---|
152 | .replace(/\u2029/g, "\\u2029")
|
---|
153 | }
|
---|
154 |
|
---|
155 | export function getProperty(key: Code | string | number): Code {
|
---|
156 | return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`
|
---|
157 | }
|
---|
158 |
|
---|
159 | //Does best effort to format the name properly
|
---|
160 | export function getEsmExportName(key: Code | string | number): Code {
|
---|
161 | if (typeof key == "string" && IDENTIFIER.test(key)) {
|
---|
162 | return new _Code(`${key}`)
|
---|
163 | }
|
---|
164 | throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)
|
---|
165 | }
|
---|
166 |
|
---|
167 | export function regexpCode(rx: RegExp): Code {
|
---|
168 | return new _Code(rx.toString())
|
---|
169 | }
|
---|