code.ts 4.3 KB

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