summaryrefslogtreecommitdiff
path: root/src/parser.ts
blob: d972e72cef018075c5e5ff2521fc6e2faf05d5cd (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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
const [CHARS, TAG_START, TAG_END, END_TAG_START, EQ, EOF, UNKNOWN] = Array.from(new Array(20), (x, i) => i + 1);

const voidTags = new Set(['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']);

type Visitor = (tag: Tag) => Tag;

interface State {
  code: string;
  index: number;
  visitor: Visitor;
  tagName?: string;
}

interface Attribute {
  name: string;
  value?: string;
  boolean: boolean;
  start: number;
  end: number;
}

interface Text {
  type: 0;
  data: string;
  start: number;
  end: number;
}

export interface Tag {
  type: 1;
  tagName: string;
  attributes: Array<Attribute>;
  children: Array<Tag | Text>;
  void: boolean;
  start: number;
  end: number;
}

interface Document {
  children: Array<Tag | Text>;
}

function stateChar(state: State) {
  return state.code[state.index];
}

function stateNext(state: State) {
  state.index++;
  return stateChar(state);
}

function stateRewind(state: State) {
  state.index--;
  return stateChar(state);
}

function stateInBounds(state: State) {
  return state.index < state.code.length;
}

function createState(code: string, visitor: Visitor): State {
  return {
    code,
    index: 0,
    visitor,
  };
}

function* _stringify(tag: Tag): Generator<string, void, unknown> {
  yield '<';
  yield tag.tagName;
  for (let attr of tag.attributes) {
    yield ' ';
    yield `"${attr.name}"`;
    if (!attr.boolean) {
      yield '=';
      yield `"${attr.value}"`;
    }
  }
  if (!tag.void) {
    for (let child of tag.children) {
      if (child.type === 0) {
        yield child.data;
      } else {
        yield* _stringify(child);
      }
    }
  }
}

function stringify(tag: Tag) {
  let out = '';
  for (let chunk of _stringify(tag)) {
    out += chunk;
  }
  return out;
}

function spliceSlice(str: string, index: number, count: number, add: string) {
  // We cannot pass negative indexes directly to the 2nd slicing operation.
  if (index < 0) {
    index = str.length + index;
    if (index < 0) {
      index = 0;
    }
  }

  return str.slice(0, index) + (add || '') + str.slice(index + count);
}

function replaceTag(state: State, tag: Tag) {
  const origLen = tag.end - tag.start;
  const html = stringify(tag);
  const newLen = html.length;
  const newCurIndex = tag.start + newLen;

  state.code = spliceSlice(state.code, tag.start, origLen, html);
  state.index = newCurIndex;
}

function consumeToken(state: State) {
  do {
    const c = stateNext(state);

    if (/\s/.test(c)) {
      continue;
    }

    if (c === '<') {
      return TAG_START;
    }

    if (c === '>') {
      return TAG_END;
    }

    if (c === '/') {
      return END_TAG_START;
    }

    if (/[a-zA-Z]/.test(c)) {
      return CHARS;
    }

    return UNKNOWN;
  } while (stateInBounds(state));

  return EOF;
}

function consumeText(state: State): Text {
  let start = state.index;
  let data = '';
  let c = stateNext(state);
  while (stateInBounds(state) && c !== '<') {
    data += c;
    c = stateNext(state);
  }

  return {
    type: 0,
    data,
    start,
    end: state.index - 1,
  };
}

function consumeTagName(state: State): string {
  let name = '';
  let token = consumeToken(state);
  while (token === CHARS) {
    name += stateChar(state);
    token = consumeToken(state);
  }
  return name.toLowerCase();
}

function consumeAttribute(state: State): Attribute {
  let start = state.index;
  let name = '',
    token;
  do {
    name += stateChar(state).toLowerCase();
    token = consumeToken(state);
  } while (token === CHARS);

  if (token !== EQ) {
    stateRewind(state);
    return {
      name,
      boolean: true,
      start,
      end: state.index - 1,
    };
  }

  let value = '';
  do {
    value += stateChar(state).toLowerCase();
    token = consumeToken(state);
  } while (token === CHARS);

  return {
    name,
    value,
    boolean: false,
    start,
    end: state.index - 1,
  };
}

function consumeChildren(state: State): Array<Tag | Text> {
  const children: Array<Tag | Text> = [];

  childLoop: while (stateInBounds(state)) {
    const token = consumeToken(state);
    switch (token) {
      case TAG_START: {
        const next = consumeToken(state);
        if (next === END_TAG_START) {
          consumeTagName(state);
          consumeToken(state); // >
          break childLoop;
        } else {
          stateRewind(state);
          consumeTag(state);
        }
        break;
      }
      case CHARS: {
        children.push(consumeText(state));
        break;
      }
      default: {
        break;
      }
    }
  }

  return children;
}

function consumeTag(state: State): Tag {
  const start = state.index - 1;
  const tagName = consumeTagName(state);
  const attributes: Array<Attribute> = [];

  let token = consumeToken(state);

  // Collect attributes
  attrLoop: while (token !== TAG_END) {
    switch (token) {
      case CHARS: {
        attributes.push(consumeAttribute(state));
        break;
      }
      default: {
        break attrLoop;
      }
    }

    token = consumeToken(state);
  }

  const children: Array<Tag | Text> = consumeChildren(state);

  const node: Tag = {
    type: 1,
    tagName,
    attributes,
    children,
    void: voidTags.has(tagName),
    start,
    end: state.index - 1,
  };

  const replacement = state.visitor(node);
  if (replacement !== node) {
    replaceTag(state, node);
  }

  return node;
}

function consumeDocument(state: State): Document {
  const children: Array<Tag | Text> = consumeChildren(state);

  return {
    children,
  };
}

export function preparse(code: string, visitor: Visitor) {
  const state = createState(code, visitor);
  consumeDocument(state);
}