@openrewrite/rewrite 8.100.0 → 8.100.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/java/rpc.d.ts.map +1 -1
  2. package/dist/java/rpc.js +6 -1
  3. package/dist/java/rpc.js.map +1 -1
  4. package/dist/javascript/add-import.d.ts.map +1 -1
  5. package/dist/javascript/add-import.js +3 -0
  6. package/dist/javascript/add-import.js.map +1 -1
  7. package/dist/javascript/binding.d.ts.map +1 -1
  8. package/dist/javascript/binding.js +8 -1
  9. package/dist/javascript/binding.js.map +1 -1
  10. package/dist/javascript/comparator.js +2 -1
  11. package/dist/javascript/comparator.js.map +1 -1
  12. package/dist/javascript/format/format.d.ts.map +1 -1
  13. package/dist/javascript/format/format.js +3 -2
  14. package/dist/javascript/format/format.js.map +1 -1
  15. package/dist/javascript/format/minimum-viable-spacing-visitor.js +3 -3
  16. package/dist/javascript/format/minimum-viable-spacing-visitor.js.map +1 -1
  17. package/dist/javascript/parser.d.ts.map +1 -1
  18. package/dist/javascript/parser.js +11 -17
  19. package/dist/javascript/parser.js.map +1 -1
  20. package/dist/javascript/print.d.ts +4 -0
  21. package/dist/javascript/print.d.ts.map +1 -1
  22. package/dist/javascript/print.js +82 -20
  23. package/dist/javascript/print.js.map +1 -1
  24. package/dist/javascript/rpc.js +2 -0
  25. package/dist/javascript/rpc.js.map +1 -1
  26. package/dist/javascript/scope.d.ts.map +1 -1
  27. package/dist/javascript/scope.js +4 -1
  28. package/dist/javascript/scope.js.map +1 -1
  29. package/dist/javascript/templating/comparator.d.ts +9 -0
  30. package/dist/javascript/templating/comparator.d.ts.map +1 -1
  31. package/dist/javascript/templating/comparator.js +21 -0
  32. package/dist/javascript/templating/comparator.js.map +1 -1
  33. package/dist/javascript/templating/debug.d.ts.map +1 -1
  34. package/dist/javascript/templating/debug.js +2 -0
  35. package/dist/javascript/templating/debug.js.map +1 -1
  36. package/dist/javascript/templating/precedence.d.ts.map +1 -1
  37. package/dist/javascript/templating/precedence.js +36 -39
  38. package/dist/javascript/templating/precedence.js.map +1 -1
  39. package/dist/javascript/templating/types.d.ts +4 -4
  40. package/dist/javascript/tree-debug.d.ts.map +1 -1
  41. package/dist/javascript/tree-debug.js +6 -3
  42. package/dist/javascript/tree-debug.js.map +1 -1
  43. package/dist/javascript/tree.d.ts +4 -1
  44. package/dist/javascript/tree.d.ts.map +1 -1
  45. package/dist/javascript/tree.js +2 -0
  46. package/dist/javascript/tree.js.map +1 -1
  47. package/dist/javascript/type-mapping.d.ts +1 -0
  48. package/dist/javascript/type-mapping.d.ts.map +1 -1
  49. package/dist/javascript/type-mapping.js +12 -1
  50. package/dist/javascript/type-mapping.js.map +1 -1
  51. package/dist/json/edit.d.ts +150 -0
  52. package/dist/json/edit.d.ts.map +1 -0
  53. package/dist/json/edit.js +667 -0
  54. package/dist/json/edit.js.map +1 -0
  55. package/dist/json/index.d.ts +1 -0
  56. package/dist/json/index.d.ts.map +1 -1
  57. package/dist/json/index.js +1 -0
  58. package/dist/json/index.js.map +1 -1
  59. package/dist/parser.d.ts +1 -1
  60. package/dist/parser.d.ts.map +1 -1
  61. package/dist/print.d.ts +16 -0
  62. package/dist/print.d.ts.map +1 -1
  63. package/dist/print.js +33 -0
  64. package/dist/print.js.map +1 -1
  65. package/dist/rewrite-javascript-version.txt +1 -1
  66. package/dist/rpc/request/get-languages.d.ts.map +1 -1
  67. package/dist/rpc/request/get-languages.js +1 -0
  68. package/dist/rpc/request/get-languages.js.map +1 -1
  69. package/dist/rpc/request/parse.d.ts.map +1 -1
  70. package/dist/rpc/request/parse.js +4 -0
  71. package/dist/rpc/request/parse.js.map +1 -1
  72. package/dist/rpc/server.d.ts +1 -0
  73. package/dist/rpc/server.d.ts.map +1 -1
  74. package/dist/rpc/server.js +1 -0
  75. package/dist/rpc/server.js.map +1 -1
  76. package/dist/xml/assertions.d.ts +4 -0
  77. package/dist/xml/assertions.d.ts.map +1 -0
  78. package/dist/xml/assertions.js +31 -0
  79. package/dist/xml/assertions.js.map +1 -0
  80. package/dist/xml/index.d.ts +8 -0
  81. package/dist/xml/index.d.ts.map +1 -0
  82. package/dist/xml/index.js +39 -0
  83. package/dist/xml/index.js.map +1 -0
  84. package/dist/xml/namespaces.d.ts +36 -0
  85. package/dist/xml/namespaces.d.ts.map +1 -0
  86. package/dist/xml/namespaces.js +98 -0
  87. package/dist/xml/namespaces.js.map +1 -0
  88. package/dist/xml/parser.d.ts +15 -0
  89. package/dist/xml/parser.d.ts.map +1 -0
  90. package/dist/xml/parser.js +677 -0
  91. package/dist/xml/parser.js.map +1 -0
  92. package/dist/xml/print.d.ts +2 -0
  93. package/dist/xml/print.d.ts.map +1 -0
  94. package/dist/xml/print.js +209 -0
  95. package/dist/xml/print.js.map +1 -0
  96. package/dist/xml/rpc.d.ts +2 -0
  97. package/dist/xml/rpc.d.ts.map +1 -0
  98. package/dist/xml/rpc.js +313 -0
  99. package/dist/xml/rpc.js.map +1 -0
  100. package/dist/xml/tree.d.ts +244 -0
  101. package/dist/xml/tree.d.ts.map +1 -0
  102. package/dist/xml/tree.js +265 -0
  103. package/dist/xml/tree.js.map +1 -0
  104. package/dist/xml/visitor.d.ts +35 -0
  105. package/dist/xml/visitor.d.ts.map +1 -0
  106. package/dist/xml/visitor.js +203 -0
  107. package/dist/xml/visitor.js.map +1 -0
  108. package/package.json +5 -1
  109. package/src/java/rpc.ts +6 -1
  110. package/src/javascript/add-import.ts +3 -0
  111. package/src/javascript/binding.ts +10 -1
  112. package/src/javascript/comparator.ts +2 -1
  113. package/src/javascript/format/format.ts +3 -2
  114. package/src/javascript/format/minimum-viable-spacing-visitor.ts +3 -3
  115. package/src/javascript/parser.ts +12 -17
  116. package/src/javascript/print.ts +85 -23
  117. package/src/javascript/rpc.ts +2 -0
  118. package/src/javascript/scope.ts +4 -1
  119. package/src/javascript/templating/comparator.ts +23 -0
  120. package/src/javascript/templating/debug.ts +1 -0
  121. package/src/javascript/templating/precedence.ts +17 -20
  122. package/src/javascript/templating/types.ts +4 -4
  123. package/src/javascript/tree-debug.ts +7 -3
  124. package/src/javascript/tree.ts +4 -1
  125. package/src/javascript/type-mapping.ts +15 -1
  126. package/src/json/edit.ts +750 -0
  127. package/src/json/index.ts +1 -0
  128. package/src/parser.ts +1 -1
  129. package/src/print.ts +42 -0
  130. package/src/rpc/request/get-languages.ts +1 -0
  131. package/src/rpc/request/parse.ts +3 -0
  132. package/src/rpc/server.ts +1 -0
  133. package/src/xml/assertions.ts +28 -0
  134. package/src/xml/index.ts +23 -0
  135. package/src/xml/namespaces.ts +109 -0
  136. package/src/xml/parser.ts +692 -0
  137. package/src/xml/print.ts +225 -0
  138. package/src/xml/rpc.ts +370 -0
  139. package/src/xml/tree.ts +455 -0
  140. package/src/xml/visitor.ts +227 -0
@@ -0,0 +1,692 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ * <p>
4
+ * Licensed under the Moderne Source Available License (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ * <p>
8
+ * https://docs.moderne.io/licensing/moderne-source-available-license
9
+ * <p>
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import {emptyMarkers, markers, Markers} from "../markers";
17
+ import {Parser, ParserInput, parserInputRead, Parsers} from "../parser";
18
+ import {SourceFile} from "../tree";
19
+ import {randomId} from "../uuid";
20
+ import {Xml} from "./tree";
21
+
22
+ const ACCEPTED_FILE_EXTENSIONS = new Set([
23
+ "xml", "wsdl", "xhtml", "xsd", "xsl", "xslt", "xmi", "tld", "jxb", "xjb", "jsp", "jspx", "tagx",
24
+ "mapxmi", "tblxmi", "dbxmi", "schxmi",
25
+ "det", "pjb", "qjb", "sjb", "prt", "srt", "psc", "ssc", "tbd", "tfm", "dqs", "stp", "dcn", "pst",
26
+ "csproj", "vbproj", "fsproj", "props", "targets", "slnx",
27
+ "projitems", "shproj", "vcxproj", "sqlproj", "njsproj", "pyproj", "wapproj", "ruleset", "dotsettings",
28
+ "jrxml"
29
+ ]);
30
+
31
+ const HTML_VOID_ELEMENTS = new Set([
32
+ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"
33
+ ]);
34
+
35
+ /**
36
+ * Parses XML into an {@link Xml.Document} that prints back byte for byte. The tree has the shape
37
+ * `org.openrewrite.xml.XmlParser` gives the same source, down to which element each run of whitespace
38
+ * is the prefix of, so that a recipe sees the same tree whichever side parsed the file.
39
+ */
40
+ export class XmlParser extends Parser {
41
+
42
+ /**
43
+ * Whether `org.openrewrite.xml.XmlParser` takes the file at this path.
44
+ */
45
+ static accept(sourcePath: string): boolean {
46
+ const fileName = sourcePath.substring(Math.max(sourcePath.lastIndexOf("/"), sourcePath.lastIndexOf("\\")) + 1);
47
+ const dot = fileName.lastIndexOf(".");
48
+ if (0 < dot && dot < fileName.length - 1 &&
49
+ ACCEPTED_FILE_EXTENSIONS.has(fileName.substring(dot + 1).toLowerCase())) {
50
+ return true;
51
+ }
52
+ const lower = fileName.toLowerCase();
53
+ return lower === "nuget.config" || lower === "packages.config" ||
54
+ ((lower.startsWith("app.") || lower.startsWith("web.")) && lower.endsWith(".config"));
55
+ }
56
+
57
+ async *parse(...sourcePaths: ParserInput[]): AsyncGenerator<SourceFile> {
58
+ for (const input of sourcePaths) {
59
+ const sourcePath = this.relativePath(input);
60
+ try {
61
+ const text = parserInputRead(input);
62
+ const bom = text.startsWith("\uFEFF");
63
+ const document: Xml.Document = {
64
+ ...new XmlParserReader(bom ? text.substring(1) : text, isHtmlLike(sourcePath)).parse(),
65
+ sourcePath,
66
+ charsetName: "UTF-8",
67
+ charsetBomMarked: bom
68
+ };
69
+ yield await this.requirePrintEqualsInput(document, input, text);
70
+ } catch (e: any) {
71
+ yield this.error(input, e instanceof Error ? e : new Error(String(e)));
72
+ }
73
+ }
74
+ }
75
+ }
76
+
77
+ function isHtmlLike(sourcePath: string): boolean {
78
+ const p = sourcePath.toLowerCase();
79
+ return p.endsWith(".jsp") || p.endsWith(".html") || p.endsWith(".htm");
80
+ }
81
+
82
+ const NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF" +
83
+ "\\u200C-\\u200D\\u2070-\\u218F\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}";
84
+ const NAME_CHAR = NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
85
+ const NAME = `[${NAME_START_CHAR}][${NAME_CHAR}]*`;
86
+
87
+ /**
88
+ * The whitespace the lexer skips between the parts of a tag, `S` in the grammar.
89
+ */
90
+ const TAG_WHITESPACE = /[ \t\r\n]*/y;
91
+ /**
92
+ * The whitespace the lexer skips between markup, `WS` in the grammar.
93
+ */
94
+ const MARKUP_WHITESPACE = /^[ \t\n\r\f]+$/;
95
+ const NAME_PATTERN = new RegExp(NAME, "uy");
96
+ const NAME_START_PATTERN = new RegExp(`[${NAME_START_CHAR}]`, "uy");
97
+ const NAME_CHAR_PATTERN = new RegExp(`[${NAME_CHAR}]`, "uy");
98
+ const REFERENCE_PATTERN = new RegExp(`&(?:#[0-9]+|#x[0-9a-fA-F]+|${NAME});`, "uy");
99
+ const PARAMETER_ENTITY_REFERENCE_PATTERN = new RegExp(`%${NAME};`, "uy");
100
+ const TEXT_END = /[<&]/g;
101
+
102
+ /**
103
+ * `java.lang.Character.isWhitespace(char)`, by which the Java parser splits the whitespace off character data.
104
+ */
105
+ function isJavaWhitespace(c: number): boolean {
106
+ return (c >= 0x09 && c <= 0x0D) || (c >= 0x1C && c <= 0x20) || c === 0x1680 ||
107
+ (c >= 0x2000 && c <= 0x2006) || (c >= 0x2008 && c <= 0x200A) ||
108
+ c === 0x2028 || c === 0x2029 || c === 0x205F || c === 0x3000;
109
+ }
110
+
111
+ class XmlParserReader {
112
+ private cursor = 0;
113
+
114
+ constructor(private readonly source: string, private readonly htmlMode: boolean) {
115
+ }
116
+
117
+ parse(): Omit<Xml.Document, "sourcePath"> {
118
+ const prefix = this.markupWhitespace();
119
+ const prolog = this.parseProlog();
120
+ const beforeRoot = this.cursor;
121
+ const rootPrefix = this.markupWhitespace();
122
+ let root: Xml.Tag | undefined;
123
+ if (this.startsWithTag()) {
124
+ root = this.parseTag(rootPrefix);
125
+ } else if (this.cursor === this.source.length) {
126
+ this.cursor = beforeRoot;
127
+ } else {
128
+ throw this.error("Expected the root element");
129
+ }
130
+ return {
131
+ kind: Xml.Kind.Document,
132
+ id: randomId(),
133
+ prefix,
134
+ markers: emptyMarkers,
135
+ prolog,
136
+ root,
137
+ eof: this.source.substring(this.cursor)
138
+ };
139
+ }
140
+
141
+ private parseProlog(): Xml.Prolog {
142
+ const xmlDecl = this.startsWithXmlDecl() ? this.parseXmlDecl() : undefined;
143
+
144
+ const misc: Xml.Misc[] = [];
145
+ while (true) {
146
+ const start = this.cursor;
147
+ const prefix = this.markupWhitespace();
148
+ if (this.startsWith("<!--")) {
149
+ misc.push(this.parseComment(prefix));
150
+ } else if (this.startsWithDocTypeDecl()) {
151
+ misc.push(this.parseDocTypeDecl(prefix));
152
+ } else if (this.startsWith("<?") && !this.startsWithXmlDecl()) {
153
+ misc.push(this.parseProcessingInstruction(prefix));
154
+ } else if (this.startsWith("<%--")) {
155
+ misc.push(this.parseJspComment(prefix));
156
+ } else if (this.startsWith("<%!")) {
157
+ misc.push(this.parseDelimited(prefix, Xml.Kind.JspDeclaration, "<%!", "%>"));
158
+ } else {
159
+ this.cursor = start;
160
+ break;
161
+ }
162
+ }
163
+
164
+ const jspDirectives: Xml.JspDirective[] = [];
165
+ while (true) {
166
+ const start = this.cursor;
167
+ const prefix = this.markupWhitespace();
168
+ if (this.startsWith("<%@")) {
169
+ jspDirectives.push(this.parseJspDirective(prefix));
170
+ } else {
171
+ this.cursor = start;
172
+ break;
173
+ }
174
+ }
175
+
176
+ return {
177
+ kind: Xml.Kind.Prolog,
178
+ id: randomId(),
179
+ prefix: "",
180
+ markers: emptyMarkers,
181
+ xmlDecl,
182
+ misc,
183
+ jspDirectives
184
+ };
185
+ }
186
+
187
+ private parseXmlDecl(): Xml.XmlDecl {
188
+ this.cursor += "<?".length;
189
+ const name = this.name();
190
+ const {attributes, before} = this.parseAttributes();
191
+ this.expect("?>");
192
+ return {
193
+ kind: Xml.Kind.XmlDecl,
194
+ id: randomId(),
195
+ prefix: "",
196
+ markers: emptyMarkers,
197
+ name,
198
+ attributes,
199
+ beforeTagDelimiterPrefix: before
200
+ };
201
+ }
202
+
203
+ private parseProcessingInstruction(prefix: string): Xml.ProcessingInstruction {
204
+ this.cursor += "<?".length;
205
+ const name = this.name();
206
+ const end = this.indexOf("?>", this.cursor, "<?" + name);
207
+ const data = this.source.substring(this.cursor, end);
208
+ this.cursor = end + "?>".length;
209
+ // As the lexer has it, a lone whitespace character is skipped, while any longer run is data.
210
+ const isData = data.length > 1 || (data.length === 1 && !/[ \t\r\n]/.test(data));
211
+ return {
212
+ kind: Xml.Kind.ProcessingInstruction,
213
+ id: randomId(),
214
+ prefix,
215
+ markers: emptyMarkers,
216
+ name,
217
+ processingInstructions: isData ? this.charData(data, "") : undefined,
218
+ beforeTagDelimiterPrefix: isData ? "" : data
219
+ };
220
+ }
221
+
222
+ private parseTag(prefix: string): Xml.Tag {
223
+ const start = this.cursor;
224
+ this.cursor += "<".length;
225
+ const name = this.name();
226
+ const {attributes, before} = this.parseAttributes();
227
+
228
+ if (this.startsWith("/>")) {
229
+ this.cursor += "/>".length;
230
+ return this.tag(prefix, emptyMarkers, name, attributes, undefined, undefined, before);
231
+ }
232
+ this.expect(">");
233
+ if (this.htmlMode && HTML_VOID_ELEMENTS.has(name.toLowerCase())) {
234
+ return this.tag(prefix, markers({kind: Xml.MarkersKind.HtmlVoidElement, id: randomId()}),
235
+ name, attributes, undefined, undefined, before);
236
+ }
237
+
238
+ const content: Xml.Content[] = [];
239
+ while (true) {
240
+ const textStart = this.cursor;
241
+ TEXT_END.lastIndex = textStart;
242
+ const textEnd = TEXT_END.exec(this.source)?.index ?? this.source.length;
243
+ this.cursor = textEnd;
244
+ let itemPrefix = "";
245
+ if (textEnd > textStart) {
246
+ const text = this.source.substring(textStart, textEnd);
247
+ if (MARKUP_WHITESPACE.test(text)) {
248
+ itemPrefix = text;
249
+ } else {
250
+ content.push(this.charData(text, ""));
251
+ }
252
+ }
253
+ if (this.cursor >= this.source.length) {
254
+ throw this.error(`Unclosed element <${name}>`, start);
255
+ }
256
+ if (this.startsWith("</")) {
257
+ const closing = this.parseClosing(itemPrefix, name);
258
+ return this.tag(prefix, emptyMarkers, name, attributes, content, closing, before);
259
+ }
260
+ content.push(this.parseContent(itemPrefix));
261
+ }
262
+ }
263
+
264
+ private parseClosing(prefix: string, openName: string): Xml.TagClosing {
265
+ const start = this.cursor;
266
+ this.cursor += "</".length;
267
+ const name = this.name();
268
+ const before = this.tagWhitespace();
269
+ this.expect(">");
270
+ if (!this.htmlMode && name !== openName) {
271
+ throw this.error(`Mismatched closing tag </${name}> for <${openName}>`, start);
272
+ }
273
+ return {
274
+ kind: Xml.Kind.TagClosing,
275
+ id: randomId(),
276
+ prefix,
277
+ markers: emptyMarkers,
278
+ name,
279
+ beforeTagDelimiterPrefix: before
280
+ };
281
+ }
282
+
283
+ private tag(prefix: string, tagMarkers: Markers, name: string, attributes: Xml.Attribute[],
284
+ content: Xml.Content[] | undefined, closing: Xml.TagClosing | undefined, before: string): Xml.Tag {
285
+ return {
286
+ kind: Xml.Kind.Tag,
287
+ id: randomId(),
288
+ prefix,
289
+ markers: tagMarkers,
290
+ name,
291
+ attributes,
292
+ content,
293
+ closing,
294
+ beforeTagDelimiterPrefix: before
295
+ };
296
+ }
297
+
298
+ private parseContent(prefix: string): Xml.Content {
299
+ if (this.startsWith("<!--")) {
300
+ return this.parseComment(prefix);
301
+ } else if (this.startsWith("<![CDATA[")) {
302
+ const end = this.indexOf("]]>", this.cursor + "<![CDATA[".length, "<![CDATA[");
303
+ const text = this.source.substring(this.cursor + "<![CDATA[".length, end);
304
+ this.cursor = end + "]]>".length;
305
+ return {
306
+ kind: Xml.Kind.CharData,
307
+ id: randomId(),
308
+ prefix,
309
+ markers: emptyMarkers,
310
+ cdata: true,
311
+ text,
312
+ afterText: ""
313
+ };
314
+ } else if (this.startsWith("<%--")) {
315
+ return this.parseJspComment(prefix);
316
+ } else if (this.startsWith("<%!")) {
317
+ return this.parseDelimited(prefix, Xml.Kind.JspDeclaration, "<%!", "%>");
318
+ } else if (this.startsWith("<%=")) {
319
+ return this.parseDelimited(prefix, Xml.Kind.JspExpression, "<%=", "%>");
320
+ } else if (this.startsWith("<%") && this.cursor + 2 < this.source.length && !"@-".includes(this.source[this.cursor + 2])) {
321
+ return this.parseDelimited(prefix, Xml.Kind.JspScriptlet, "<%", "%>");
322
+ } else if (this.startsWith("<?") && !this.startsWithXmlDecl()) {
323
+ return this.parseProcessingInstruction(prefix);
324
+ } else if (this.startsWithTag()) {
325
+ return this.parseTag(prefix);
326
+ } else if (this.startsWith("&")) {
327
+ REFERENCE_PATTERN.lastIndex = this.cursor;
328
+ const reference = REFERENCE_PATTERN.exec(this.source);
329
+ if (!reference) {
330
+ throw this.error("Expected an entity or character reference");
331
+ }
332
+ this.cursor += reference[0].length;
333
+ return {
334
+ kind: Xml.Kind.CharData,
335
+ id: randomId(),
336
+ prefix,
337
+ markers: emptyMarkers,
338
+ cdata: false,
339
+ text: reference[0],
340
+ afterText: ""
341
+ };
342
+ }
343
+ throw this.error("Unexpected markup");
344
+ }
345
+
346
+ private parseComment(prefix: string): Xml.Comment {
347
+ const end = this.indexOf("-->", this.cursor + "<!--".length, "<!--");
348
+ const text = this.source.substring(this.cursor + "<!--".length, end);
349
+ this.cursor = end + "-->".length;
350
+ return {
351
+ kind: Xml.Kind.Comment,
352
+ id: randomId(),
353
+ prefix,
354
+ markers: emptyMarkers,
355
+ text
356
+ };
357
+ }
358
+
359
+ private parseJspComment(prefix: string): Xml.JspComment {
360
+ return this.parseDelimited(prefix, Xml.Kind.JspComment, "<%--", "--%>");
361
+ }
362
+
363
+ private parseDelimited<K extends typeof Xml.Kind.JspComment | typeof Xml.Kind.JspDeclaration |
364
+ typeof Xml.Kind.JspExpression | typeof Xml.Kind.JspScriptlet>(prefix: string, kind: K, open: string, close: string):
365
+ { kind: K, id: string, prefix: string, markers: Markers, content: string } {
366
+ // The lexer's non-greedy match needs at least one character between a scriptlet's `<%` and `%>`.
367
+ const contentStart = this.cursor + open.length;
368
+ const end = this.indexOf(close, kind === Xml.Kind.JspScriptlet ? contentStart + 1 : contentStart, open);
369
+ const content = this.source.substring(contentStart, end);
370
+ this.cursor = end + close.length;
371
+ return {
372
+ kind,
373
+ id: randomId(),
374
+ prefix,
375
+ markers: emptyMarkers,
376
+ content
377
+ };
378
+ }
379
+
380
+ private parseJspDirective(prefix: string): Xml.JspDirective {
381
+ this.cursor += "<%@".length;
382
+ const beforeTypePrefix = this.tagWhitespace();
383
+ const type = this.name();
384
+ const {attributes, before} = this.parseAttributes();
385
+ this.expect("%>");
386
+ return {
387
+ kind: Xml.Kind.JspDirective,
388
+ id: randomId(),
389
+ prefix,
390
+ markers: emptyMarkers,
391
+ beforeTypePrefix,
392
+ type,
393
+ attributes,
394
+ beforeDirectiveEndPrefix: before
395
+ };
396
+ }
397
+
398
+ private parseAttributes(): { attributes: Xml.Attribute[], before: string } {
399
+ const attributes: Xml.Attribute[] = [];
400
+ while (true) {
401
+ const prefix = this.tagWhitespace();
402
+ if (!this.startsWithName()) {
403
+ return {attributes, before: prefix};
404
+ }
405
+ attributes.push(this.parseAttribute(prefix));
406
+ }
407
+ }
408
+
409
+ private parseAttribute(prefix: string): Xml.Attribute {
410
+ const key: Xml.Ident = {
411
+ kind: Xml.Kind.Ident,
412
+ id: randomId(),
413
+ prefix: "",
414
+ markers: emptyMarkers,
415
+ name: this.name()
416
+ };
417
+ const beforeEquals = this.tagWhitespace();
418
+ this.expect("=");
419
+ const valuePrefix = this.tagWhitespace();
420
+ const valueStart = this.cursor;
421
+ const quote = this.source[this.cursor];
422
+ if (quote !== '"' && quote !== "'") {
423
+ throw this.error(`Expected a quoted value for attribute ${key.name}`);
424
+ }
425
+ const end = this.source.indexOf(quote, this.cursor + 1);
426
+ const value = end < 0 ? "" : this.source.substring(this.cursor + 1, end);
427
+ if (end < 0 || value.includes("<")) {
428
+ throw this.error(`Malformed value of attribute ${key.name}`, valueStart);
429
+ }
430
+ this.cursor = end + 1;
431
+ return {
432
+ kind: Xml.Kind.Attribute,
433
+ id: randomId(),
434
+ prefix,
435
+ markers: emptyMarkers,
436
+ key,
437
+ beforeEquals,
438
+ value: {
439
+ kind: Xml.Kind.AttributeValue,
440
+ id: randomId(),
441
+ prefix: valuePrefix,
442
+ markers: emptyMarkers,
443
+ quote: quote === '"' ? "Double" : "Single",
444
+ value
445
+ }
446
+ };
447
+ }
448
+
449
+ private parseDocTypeDecl(prefix: string): Xml.DocTypeDecl {
450
+ this.cursor += "<!".length;
451
+ const documentDeclaration = this.source.substring(this.cursor, this.cursor + "DOCTYPE".length);
452
+ this.cursor += documentDeclaration.length;
453
+
454
+ const namePrefix = this.tagWhitespace();
455
+ const name = this.ident(namePrefix, this.name());
456
+
457
+ let externalId: Xml.Ident | undefined;
458
+ let start = this.cursor;
459
+ const externalIdPrefix = this.tagWhitespace();
460
+ if (this.startsWithName()) {
461
+ externalId = this.ident(externalIdPrefix, this.name());
462
+ } else {
463
+ this.cursor = start;
464
+ }
465
+
466
+ const internalSubset: Xml.Ident[] = [];
467
+ while (true) {
468
+ start = this.cursor;
469
+ const stringPrefix = this.tagWhitespace();
470
+ const quote = this.source[this.cursor];
471
+ if (quote !== '"' && quote !== "'") {
472
+ this.cursor = start;
473
+ break;
474
+ }
475
+ const end = this.source.indexOf(quote, this.cursor + 1);
476
+ if (end < 0 || this.source.substring(this.cursor, end).includes("<")) {
477
+ throw this.error("Malformed string in the document type declaration");
478
+ }
479
+ internalSubset.push(this.ident(stringPrefix, this.source.substring(this.cursor, end + 1)));
480
+ this.cursor = end + 1;
481
+ }
482
+
483
+ let externalSubsets: Xml.DocTypeDeclExternalSubsets | undefined;
484
+ start = this.cursor;
485
+ const subsetPrefix = this.tagWhitespace();
486
+ if (this.startsWith("[")) {
487
+ externalSubsets = this.parseExternalSubsets(subsetPrefix);
488
+ } else {
489
+ this.cursor = start;
490
+ }
491
+
492
+ const before = this.tagWhitespace();
493
+ this.expect(">");
494
+ return {
495
+ kind: Xml.Kind.DocTypeDecl,
496
+ id: randomId(),
497
+ prefix,
498
+ markers: emptyMarkers,
499
+ name,
500
+ documentDeclaration,
501
+ externalId,
502
+ internalSubset,
503
+ externalSubsets,
504
+ beforeTagDelimiterPrefix: before
505
+ };
506
+ }
507
+
508
+ private parseExternalSubsets(prefix: string): Xml.DocTypeDeclExternalSubsets {
509
+ this.cursor += "[".length;
510
+ const elements: Xml.Element[] = [];
511
+ while (true) {
512
+ const elementPrefix = this.tagWhitespace();
513
+ if (this.startsWith("]")) {
514
+ if (elements.length > 0) {
515
+ elements[elements.length - 1] = {
516
+ ...elements[elements.length - 1],
517
+ beforeTagDelimiterPrefix: elementPrefix
518
+ };
519
+ } else if (elementPrefix !== "") {
520
+ throw this.error("An empty internal subset has no element to hold its whitespace");
521
+ }
522
+ this.cursor += "]".length;
523
+ break;
524
+ }
525
+ const start = this.cursor;
526
+ this.skipMarkupDecl();
527
+ elements.push({
528
+ kind: Xml.Kind.Element,
529
+ id: randomId(),
530
+ prefix: "",
531
+ markers: emptyMarkers,
532
+ subset: [this.ident(elementPrefix, this.source.substring(start, this.cursor))],
533
+ beforeTagDelimiterPrefix: ""
534
+ });
535
+ }
536
+ return {
537
+ kind: Xml.Kind.DocTypeDeclExternalSubsets,
538
+ id: randomId(),
539
+ prefix,
540
+ markers: emptyMarkers,
541
+ elements
542
+ };
543
+ }
544
+
545
+ /**
546
+ * Moves past a markup declaration, comment, processing instruction or parameter entity reference
547
+ * of a document type declaration's internal subset, which the tree keeps as text.
548
+ */
549
+ private skipMarkupDecl(): void {
550
+ if (this.startsWith("<!--")) {
551
+ this.cursor = this.indexOf("-->", this.cursor + "<!--".length, "<!--") + "-->".length;
552
+ } else if (this.startsWith("<?")) {
553
+ this.cursor = this.indexOf("?>", this.cursor + "<?".length, "<?") + "?>".length;
554
+ } else if (this.startsWith("<!")) {
555
+ const start = this.cursor;
556
+ this.cursor += "<!".length;
557
+ while (true) {
558
+ const c = this.source[this.cursor];
559
+ if (c === undefined) {
560
+ throw this.error("Unterminated markup declaration", start);
561
+ } else if (c === ">") {
562
+ this.cursor++;
563
+ return;
564
+ } else if (c === '"' || c === "'" || c === "[") {
565
+ const end = this.source.indexOf(c === "[" ? "]" : c, this.cursor + 1);
566
+ if (end < 0) {
567
+ throw this.error("Unterminated markup declaration", start);
568
+ }
569
+ this.cursor = end + 1;
570
+ } else {
571
+ this.cursor++;
572
+ }
573
+ }
574
+ } else {
575
+ PARAMETER_ENTITY_REFERENCE_PATTERN.lastIndex = this.cursor;
576
+ const reference = PARAMETER_ENTITY_REFERENCE_PATTERN.exec(this.source);
577
+ if (!reference) {
578
+ throw this.error("Expected a markup declaration in the internal subset");
579
+ }
580
+ this.cursor += reference[0].length;
581
+ }
582
+ }
583
+
584
+ private charData(text: string, prefix: string): Xml.CharData {
585
+ let start = 0;
586
+ while (start < text.length && isJavaWhitespace(text.charCodeAt(start))) {
587
+ start++;
588
+ }
589
+ let end = text.length;
590
+ while (end > start && isJavaWhitespace(text.charCodeAt(end - 1))) {
591
+ end--;
592
+ }
593
+ return {
594
+ kind: Xml.Kind.CharData,
595
+ id: randomId(),
596
+ prefix: prefix + text.substring(0, start),
597
+ markers: emptyMarkers,
598
+ cdata: false,
599
+ text: text.substring(start, end),
600
+ afterText: text.substring(end)
601
+ };
602
+ }
603
+
604
+ private ident(prefix: string, name: string): Xml.Ident {
605
+ return {
606
+ kind: Xml.Kind.Ident,
607
+ id: randomId(),
608
+ prefix,
609
+ markers: emptyMarkers,
610
+ name
611
+ };
612
+ }
613
+
614
+ private name(): string {
615
+ NAME_PATTERN.lastIndex = this.cursor;
616
+ const match = NAME_PATTERN.exec(this.source);
617
+ if (!match) {
618
+ throw this.error("Expected a name");
619
+ }
620
+ this.cursor += match[0].length;
621
+ return match[0];
622
+ }
623
+
624
+ private startsWithName(): boolean {
625
+ NAME_START_PATTERN.lastIndex = this.cursor;
626
+ return NAME_START_PATTERN.test(this.source);
627
+ }
628
+
629
+ private startsWithTag(): boolean {
630
+ if (this.source[this.cursor] !== "<") {
631
+ return false;
632
+ }
633
+ NAME_START_PATTERN.lastIndex = this.cursor + 1;
634
+ return NAME_START_PATTERN.test(this.source);
635
+ }
636
+
637
+ private startsWithXmlDecl(): boolean {
638
+ if (!this.startsWith("<?xml")) {
639
+ return false;
640
+ }
641
+ NAME_CHAR_PATTERN.lastIndex = this.cursor + "<?xml".length;
642
+ return !NAME_CHAR_PATTERN.test(this.source);
643
+ }
644
+
645
+ private startsWithDocTypeDecl(): boolean {
646
+ return this.startsWith("<!") &&
647
+ this.source.substring(this.cursor + 2, this.cursor + 2 + "DOCTYPE".length).toUpperCase() === "DOCTYPE";
648
+ }
649
+
650
+ private tagWhitespace(): string {
651
+ TAG_WHITESPACE.lastIndex = this.cursor;
652
+ const whitespace = TAG_WHITESPACE.exec(this.source)![0];
653
+ this.cursor += whitespace.length;
654
+ return whitespace;
655
+ }
656
+
657
+ private markupWhitespace(): string {
658
+ const start = this.cursor;
659
+ while (this.cursor < this.source.length && " \t\n\r\f".includes(this.source[this.cursor])) {
660
+ this.cursor++;
661
+ }
662
+ return this.source.substring(start, this.cursor);
663
+ }
664
+
665
+ private startsWith(s: string): boolean {
666
+ return this.source.startsWith(s, this.cursor);
667
+ }
668
+
669
+ private expect(s: string): void {
670
+ if (!this.startsWith(s)) {
671
+ throw this.error(`Expected '${s}'`);
672
+ }
673
+ this.cursor += s.length;
674
+ }
675
+
676
+ private indexOf(s: string, from: number, opened: string): number {
677
+ const index = this.source.indexOf(s, from);
678
+ if (index < 0) {
679
+ throw this.error(`Expected '${s}' to close '${opened}'`);
680
+ }
681
+ return index;
682
+ }
683
+
684
+ private error(message: string, at: number = this.cursor): Error {
685
+ const before = this.source.substring(0, at);
686
+ const line = before.split("\n").length;
687
+ const column = at - before.lastIndexOf("\n");
688
+ return new Error(`${message} at line ${line}, column ${column}`);
689
+ }
690
+ }
691
+
692
+ Parsers.registerParser("xml", XmlParser);