code.ts 4.4 KB

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