1 export abstract class _CodeOrName {
2 abstract readonly str: string
3 abstract readonly names: UsedNames
4 abstract toString(): string
5 abstract emptyStr(): boolean
8 export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i
10 export class Name extends _CodeOrName {
12 constructor(s: string) {
14 if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
26 get names(): UsedNames {
27 return {[this.str]: 1}
31 export class _Code extends _CodeOrName {
32 readonly _items: readonly CodeItem[]
34 private _names?: UsedNames
36 constructor(code: string | readonly CodeItem[]) {
38 this._items = typeof code === "string" ? [code] : code
46 if (this._items.length > 1) return false
47 const item = this._items[0]
48 return item === "" || item === '""'
52 return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, ""))
55 get names(): UsedNames {
56 return (this._names ??= this._items.reduce((names: UsedNames, c) => {
57 if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1
63 export type CodeItem = Name | string | number | boolean | null
65 export type UsedNames = Record<string, number | undefined>
67 export type Code = _Code | Name
69 export type SafeExpr = Code | number | boolean | null
71 export const nil = new _Code("")
73 type CodeArg = SafeExpr | string | undefined
75 export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {
76 const code: CodeItem[] = [strs[0]]
78 while (i < args.length) {
79 addCodeArg(code, args[i])
82 return new _Code(code)
85 const plus = new _Code("+")
87 export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {
88 const expr: CodeItem[] = [safeStringify(strs[0])]
90 while (i < args.length) {
92 addCodeArg(expr, args[i])
93 expr.push(plus, safeStringify(strs[++i]))
96 return new _Code(expr)
99 export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {
100 if (arg instanceof _Code) code.push(...arg._items)
101 else if (arg instanceof Name) code.push(arg)
102 else code.push(interpolate(arg))
105 function optimize(expr: CodeItem[]): void {
107 while (i < expr.length - 1) {
108 if (expr[i] === plus) {
109 const res = mergeExprItems(expr[i - 1], expr[i + 1])
110 if (res !== undefined) {
111 expr.splice(i - 1, 3, res)
120 function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {
121 if (b === '""') return a
122 if (a === '""') return b
123 if (typeof a == "string") {
124 if (b instanceof Name || a[a.length - 1] !== '"') return
125 if (typeof b != "string") return `${a.slice(0, -1)}${b}"`
126 if (b[0] === '"') return a.slice(0, -1) + b.slice(1)
129 if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`
133 export function strConcat(c1: Code, c2: Code): Code {
134 return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`
137 // TODO do not allow arrays here
138 function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {
139 return typeof x == "number" || typeof x == "boolean" || x === null
141 : safeStringify(Array.isArray(x) ? x.join(",") : x)
144 export function stringify(x: unknown): Code {
145 return new _Code(safeStringify(x))
148 export function safeStringify(x: unknown): string {
149 return JSON.stringify(x)
150 .replace(/\u2028/g, "\\u2028")
151 .replace(/\u2029/g, "\\u2029")
154 export function getProperty(key: Code | string | number): Code {
155 return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`