aboutsummaryrefslogtreecommitdiff
path: root/src/js/_codegen/builtin-parser.ts
blob: ffd5671c104d70b8fc42640bca84b42fc964748e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import { applyReplacements } from "./replacements";

/**
 * Slices a string until it hits a }, but keeping in mind JS comments,
 * regex, template literals, comments, and matching {
 *
 * Used to extract function bodies without parsing the code.
 *
 * If you pass replace=true, it will run replacements on the code
 */
export function sliceSourceCode(
  contents: string,
  replace: boolean,
  replaceRequire?: (specifier: string) => string,
  endOnComma = false,
): { result: string; rest: string } {
  let bracketCount = 0;
  let i = 0;
  let result = "";
  while (contents.length) {
    const match = contents.match(
      endOnComma && bracketCount <= 1
        ? /((?:[(,=;:{]|return|\=\>)\s*)\/[^\/\*]|\/\*|\/\/|['"}`\),]|(?<!\$)\brequire\(|(\$assert\(|\$debug\()/
        : /((?:[(,=;:{]|return|\=\>)\s*)\/[^\/\*]|\/\*|\/\/|['"}`\)]|(?<!\$)\brequire\(|(\$assert\(|\$debug\()/,
    );
    i = match?.index ?? contents.length;
    if (match?.[2]) {
      i += match[2].length - 1;
    }
    bracketCount += [...contents.slice(0, i).matchAll(/[({]/g)].length;
    const chunk = replace ? applyReplacements(contents, i) : [contents.slice(0, i), contents.slice(i)];
    result += chunk[0];
    contents = chunk[1] as string;
    if (chunk[2]) {
      continue;
    }
    if (match?.[1]) {
      if (match[1].startsWith("(") || match[1].startsWith(",")) {
        bracketCount++;
      }
      const { result: result2, rest } = sliceRegularExpressionSourceCode(
        contents.slice(match?.[1].length + 1),
        replace,
      );
      result += contents.slice(0, match?.[1].length + 1) + result2;
      contents = rest;
      continue;
    }
    if (!contents.length) break;
    if (contents.startsWith("/*")) {
      i = contents.slice(2).indexOf("*/") + 2;
    } else if (contents.startsWith("//")) {
      i = contents.slice(2).indexOf("\n") + 2;
    } else if (contents.startsWith("'")) {
      i = getEndOfBasicString(contents.slice(1), "'") + 2;
    } else if (contents.startsWith('"')) {
      i = getEndOfBasicString(contents.slice(1), '"') + 2;
    } else if (contents.startsWith("`")) {
      const { result: result2, rest } = sliceTemplateLiteralSourceCode(contents.slice(1), replace);
      result += "`" + result2;
      contents = rest;
      i = 0;
      continue;
    } else if (contents.startsWith("}")) {
      bracketCount--;
      if (bracketCount <= 0) {
        result += "}";
        contents = contents.slice(1);
        break;
      }
      i = 1;
    } else if (contents.startsWith(")")) {
      bracketCount--;
      if (bracketCount <= 0) {
        result += ")";
        contents = contents.slice(1);
        break;
      }
      i = 1;
    } else if (endOnComma && contents.startsWith(",")) {
      if (bracketCount <= 1) {
        result += ",";
        contents = contents.slice(1);
        // if the next non-whitespace character is ), also consume
        let match = contents.match(/^\s*\)/);
        if (match) {
          contents = contents.slice(match[0].length);
        }
        break;
      }
      i = 1;
    } else if (contents.startsWith("require(")) {
      if (replaceRequire) {
        const staticSpecifier = contents.match(/\brequire\(["']([^"']+)["']\)/);
        if (staticSpecifier) {
          const specifier = staticSpecifier[1];
          result += replaceRequire(specifier);
          contents = contents.slice(staticSpecifier[0].length);
          continue;
        } else {
          throw new Error("Require with dynamic specifier not supported here.");
        }
      } else {
        throw new Error("Require is not supported here.");
      }
    } else {
      console.error(contents.slice(0, 100));
      throw new Error("TODO");
    }
    result += contents.slice(0, i);
    contents = contents.slice(i);
  }

  return { result, rest: contents };
}

function sliceTemplateLiteralSourceCode(contents: string, replace: boolean) {
  let i = 0;
  let result = "";
  while (contents.length) {
    i = contents.match(/`|\${/)!.index!;
    result += contents.slice(0, i);
    contents = contents.slice(i);
    if (!contents.length) break;
    if (contents.startsWith("`")) {
      result += "`";
      contents = contents.slice(1);
      break;
    } else if (contents.startsWith("$")) {
      const { result: result2, rest } = sliceSourceCode(contents.slice(1), replace);
      result += "$" + result2;
      contents = rest;
      continue;
    } else {
      throw new Error("TODO");
    }
  }

  return { result, rest: contents };
}

function sliceRegularExpressionSourceCode(contents: string, replace: boolean) {
  let i = 0;
  let result = "";
  while (contents.length) {
    i = contents.match(/\/(?!\/|\*)|\\|\[/)!.index!;
    result += contents.slice(0, i);
    contents = contents.slice(i);
    if (!contents.length) break;
    if (contents.startsWith("/")) {
      result += "/";
      contents = contents.slice(1);
      break;
    } else if (contents.startsWith("\\")) {
      result += "\\";
      contents = contents.slice(1);
      if (!contents.length) break;
      result += contents[0];
      contents = contents.slice(1);
      continue;
    } else if (contents.startsWith("[")) {
      let end = contents.match(/(?<!\\)]/)!.index!;
      result += contents.slice(0, end + 1);
      contents = contents.slice(end + 1);
      continue;
    } else {
      throw new Error("TODO");
    }
  }

  return { result, rest: contents };
}

function getEndOfBasicString(str: string, quote: "'" | '"') {
  let i = 0;
  while (i < str.length) {
    if (str[i] === "\\") {
      i++;
    } else if (str[i] === quote) {
      return i;
    }
    i++;
  }
  throw new Error("String did not end");
}