tree-sitter-aspx 0.0.0-stage → 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 M. Reifschneider
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ tree-sitter-aspx is an original grammar.
2
+
3
+ An existing ASPX grammar was evaluated before this one was written.
4
+ Its rules were not copied. No third-party grammar source is included
5
+ in this repository.
6
+
7
+ See LICENSE for the MIT license text.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # tree-sitter-aspx
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![Verify](https://github.com/alfpricot/tree-sitter-aspx/actions/workflows/verify.yml/badge.svg?branch=dev)](https://github.com/alfpricot/tree-sitter-aspx/actions/workflows/verify.yml)
4
+ [![Crates.io](https://img.shields.io/crates/v/tree-sitter-aspx)](https://crates.io/crates/tree-sitter-aspx)
5
+
6
+ A [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammar for ASP.NET Web Forms markup: `.aspx` pages, `.ascx` user controls, `.master` master pages, and the directive headers of `.asax`, `.asmx`, and `.ashx` files, with Node and Rust bindings. Classic ASP (`.asp` with VBScript) and Razor (`.cshtml`, `.vbhtml`) are different languages and are out of scope, and code-behind files (`.aspx.cs`, `.aspx.vb`) are ordinary C# or VB.NET that this grammar does not parse.
7
+
8
+ ## Installation
9
+
10
+ ```sh
11
+ npm install tree-sitter-aspx # Node
12
+ cargo add tree-sitter-aspx # Rust
13
+ ```
14
+
15
+ ### Requirements
16
+
17
+ - **Node:** the `tree-sitter` package, version `^0.25.0`, is an optional peer dependency. The binding is a Node-API addon with prebuilt copies for Linux and Windows; on any other platform the install compiles it from source and needs a C/C++ toolchain that `node-gyp` can use.
18
+ - **Rust:** 1.85 or newer. The crate depends only on `tree-sitter-language`, so the `tree-sitter` version your own crate uses is the one that parses.
19
+
20
+ ## Usage
21
+
22
+ The grammar parses directives, server comments, HTML comments, code nuggets, `<script>` and `<style>` elements, and tags with attributes. It does not validate HTML. Void tags (`br`, `img`, `meta`, and the other HTML void elements) do not swallow the following markup. End tags that HTML lets a page leave out are implied, as a browser would: an open `li`, `p`, `td`, `tr`, `option`, `dt`, `dd`, or other element with an optional end tag ends at the start tag that closes it (a sibling `li`, a block element after a `p`, and so on), at an ancestor's end tag, or at the end of the file. An end tag that names an element further out closes the elements inside it, and an end tag whose name matches no open element closes nothing and stays in the tree as an `end_tag`, as a browser ignores it. The scanner keeps the names of the innermost 64 open elements; deeper than that, end tags pair with start tags by position. A `<` followed by whitespace starts no tag, so `if a < b` is text, as browsers and ASP.NET read it. `<script>` and `<style>` bodies are raw text, so `<` inside JavaScript or CSS is not a tag, but a nugget or server comment inside a body is still parsed as one. Nuggets and server comments may also stand in for attributes in a tag, as in `<option <%= selected %>>`. `<![CDATA[ ]]>` sections and `<?xml ?>` declarations parse as `cdata_section` and `processing_instruction` nodes whose nuggets are still parsed, and self-closing `<script ... />` and `<style />` tags are `self_closing_element` nodes.
23
+
24
+ The C# and VB.NET inside a page are exposed as `c_sharp_code` and `vb_code` nodes, with injection queries for editors. See [docs/EMBEDDED_CODE.md](docs/EMBEDDED_CODE.md).
25
+
26
+ ### Node
27
+
28
+ The default export exposes `name`, `language`, and `nodeTypeInfo` (the entries from `src/node-types.json`) on every platform, plus the `HIGHLIGHTS_QUERY` and `INJECTIONS_QUERY` strings.
29
+
30
+ ```js
31
+ import Parser from 'tree-sitter';
32
+ import Aspx from 'tree-sitter-aspx';
33
+
34
+ const parser = new Parser();
35
+ parser.setLanguage(Aspx);
36
+ const tree = parser.parse('<%@ Page Language="C#" %>');
37
+ console.log(tree.rootNode.toString());
38
+ ```
39
+
40
+ ### Rust
41
+
42
+ ```rust
43
+ let mut parser = tree_sitter::Parser::new();
44
+ parser
45
+ .set_language(&tree_sitter_aspx::LANGUAGE.into())
46
+ .expect("Error loading ASPX parser");
47
+ ```
48
+
49
+ `LANGUAGE` is a `tree_sitter_language::LanguageFn`. The crate also exports `NODE_TYPES`, `HIGHLIGHTS_QUERY`, and `INJECTIONS_QUERY`.
50
+
51
+ ## How to contribute
52
+
53
+ Branch from `dev` and open pull requests against it. [CONTRIBUTING.md](CONTRIBUTING.md) covers building the parser, running the checks CI runs, and the pull request rules; [ARCHITECTURE.md](ARCHITECTURE.md) explains how the pieces fit together.
54
+
55
+ ## License
56
+
57
+ MIT. See [LICENSE](LICENSE).
package/binding.gyp ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "targets": [
3
+ {
4
+ "target_name": "tree_sitter_aspx_binding",
5
+ "dependencies": [
6
+ "<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
7
+ ],
8
+ "include_dirs": [
9
+ "src",
10
+ ],
11
+ "sources": [
12
+ "bindings/node/binding.cc",
13
+ "src/parser.c",
14
+ "src/scanner.c",
15
+ ],
16
+ "conditions": [
17
+ ["OS!='win'", {
18
+ "cflags_c": [
19
+ "-std=c11",
20
+ ],
21
+ }, {
22
+ "cflags_c": [
23
+ "/std:c11",
24
+ "/utf-8",
25
+ ],
26
+ }],
27
+ ],
28
+ }
29
+ ]
30
+ }
@@ -0,0 +1,20 @@
1
+ #include <napi.h>
2
+
3
+ typedef struct TSLanguage TSLanguage;
4
+
5
+ extern "C" TSLanguage *tree_sitter_aspx();
6
+
7
+ // "tree-sitter", "language" hashed with BLAKE2
8
+ const napi_type_tag LANGUAGE_TYPE_TAG = {
9
+ 0x8AF2E5212AD58ABF, 0xD5006CAD83ABBA16
10
+ };
11
+
12
+ Napi::Object Init(Napi::Env env, Napi::Object exports) {
13
+ exports["name"] = Napi::String::New(env, "aspx");
14
+ auto language = Napi::External<TSLanguage>::New(env, tree_sitter_aspx());
15
+ language.TypeTag(&LANGUAGE_TYPE_TAG);
16
+ exports["language"] = language;
17
+ return exports;
18
+ }
19
+
20
+ NODE_API_MODULE(tree_sitter_aspx_binding, Init)
@@ -0,0 +1,31 @@
1
+ import assert from 'node:assert';
2
+ import { test } from 'node:test';
3
+ import Parser from 'tree-sitter';
4
+
5
+ test('can load grammar', async () => {
6
+ const parser = new Parser();
7
+ await assert.doesNotReject(async () => {
8
+ const { default: language } = await import('./index.js');
9
+ parser.setLanguage(language);
10
+ });
11
+ });
12
+
13
+ test('exports node type metadata', async () => {
14
+ const { default: language } = await import('./index.js');
15
+ assert(Array.isArray(language.nodeTypeInfo));
16
+ assert(language.nodeTypeInfo.some((node) => node.type === 'document'));
17
+ });
18
+
19
+ test('exports the aspx language name', async () => {
20
+ const { default: language } = await import('./index.js');
21
+ assert.equal(language.name, 'aspx');
22
+ });
23
+
24
+ test('parses a page directive without error', async () => {
25
+ const { default: language } = await import('./index.js');
26
+ const parser = new Parser();
27
+ parser.setLanguage(language);
28
+ const tree = parser.parse('<%@ Page Language="C#" Inherits="Example.Page" %>');
29
+ assert.equal(tree.rootNode.hasError, false);
30
+ assert.equal(tree.rootNode.type, 'source_file');
31
+ });
@@ -0,0 +1,57 @@
1
+ type BaseNode = {
2
+ type: string;
3
+ named: boolean;
4
+ };
5
+
6
+ type ChildNode = {
7
+ multiple: boolean;
8
+ required: boolean;
9
+ types: BaseNode[];
10
+ };
11
+
12
+ type NodeInfo =
13
+ | (BaseNode & {
14
+ subtypes: BaseNode[];
15
+ })
16
+ | (BaseNode & {
17
+ fields?: { [name: string]: ChildNode };
18
+ children?: ChildNode;
19
+ });
20
+
21
+ /**
22
+ * The tree-sitter language object for this grammar.
23
+ *
24
+ * @see {@linkcode https://tree-sitter.github.io/node-tree-sitter/interfaces/Parser.Language.html Parser.Language}
25
+ *
26
+ * @example
27
+ * import Parser from "tree-sitter";
28
+ * import Aspx from "tree-sitter-aspx";
29
+ *
30
+ * const parser = new Parser();
31
+ * parser.setLanguage(Aspx);
32
+ */
33
+ declare const binding: {
34
+ /** The language name. */
35
+ name: "aspx";
36
+
37
+ /**
38
+ * The inner language object.
39
+ * @private
40
+ */
41
+ language: unknown;
42
+
43
+ /**
44
+ * The content of the `node-types.json` file for this grammar.
45
+ *
46
+ * @see {@linkplain https://tree-sitter.github.io/tree-sitter/using-parsers/6-static-node-types Static Node Types}
47
+ */
48
+ nodeTypeInfo: NodeInfo[];
49
+
50
+ /** The syntax highlighting query for this grammar. */
51
+ HIGHLIGHTS_QUERY?: string;
52
+
53
+ /** The language injection query for this grammar. */
54
+ INJECTIONS_QUERY?: string;
55
+ };
56
+
57
+ export default binding;
@@ -0,0 +1,41 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const root = fileURLToPath(new URL('../..', import.meta.url));
5
+
6
+ const binding =
7
+ typeof process.versions.bun === 'string'
8
+ ? // Support `bun build --compile` by being statically analyzable enough to find the .node file at build-time
9
+ await import(`${root}/prebuilds/${process.platform}-${process.arch}/tree-sitter-aspx.node`)
10
+ : (await import('node-gyp-build')).default(root);
11
+
12
+ try {
13
+ binding.nodeTypeInfo = JSON.parse(
14
+ readFileSync(new URL('../../src/node-types.json', import.meta.url), 'utf8'),
15
+ );
16
+ } catch {
17
+ // node-types.json is optional metadata; the binding still works without it.
18
+ }
19
+
20
+ const queries = [
21
+ ['HIGHLIGHTS_QUERY', `${root}/queries/highlights.scm`],
22
+ ['INJECTIONS_QUERY', `${root}/queries/injections.scm`],
23
+ ];
24
+
25
+ for (const [prop, path] of queries) {
26
+ Object.defineProperty(binding, prop, {
27
+ configurable: true,
28
+ enumerable: true,
29
+ get() {
30
+ delete binding[prop];
31
+ try {
32
+ binding[prop] = readFileSync(path, 'utf8');
33
+ } catch {
34
+ // A missing query file leaves the property undefined.
35
+ }
36
+ return binding[prop];
37
+ },
38
+ });
39
+ }
40
+
41
+ export default binding;
package/grammar.js ADDED
@@ -0,0 +1,409 @@
1
+ /// <reference types="tree-sitter-cli/dsl" />
2
+ // @ts-check
3
+
4
+ // Lexical precedence above the general tag/attribute names, so `script`,
5
+ // `br`, and `Language` win when they are the same length as the general
6
+ // pattern. Longer names (`scriptmanager`, `break`) still take the general
7
+ // pattern because the lexer prefers the longest match.
8
+ const RESERVED = 1;
9
+
10
+ /**
11
+ * @param {string} word
12
+ */
13
+ function reserved(word) {
14
+ return token(
15
+ prec(
16
+ RESERVED,
17
+ new RegExp(
18
+ word
19
+ .split('')
20
+ .map((ch) => {
21
+ const lower = ch.toLowerCase();
22
+ const upper = ch.toUpperCase();
23
+ return lower === upper
24
+ ? ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
25
+ : `[${upper}${lower}]`;
26
+ })
27
+ .join(''),
28
+ ),
29
+ ),
30
+ );
31
+ }
32
+
33
+ const VOID_TAGS = [
34
+ 'area',
35
+ 'base',
36
+ 'br',
37
+ 'col',
38
+ 'embed',
39
+ 'hr',
40
+ 'img',
41
+ 'input',
42
+ 'link',
43
+ 'meta',
44
+ 'param',
45
+ 'source',
46
+ 'track',
47
+ 'wbr',
48
+ ];
49
+
50
+ export default grammar({
51
+ name: 'aspx',
52
+
53
+ // A UTF-8 BOM is whitespace as far as the page parser is concerned. UTF-16
54
+ // files are decoded to UTF-8 before parsing; see tools/corpus-check.mjs.
55
+ extras: (_) => [/\s/, /\uFEFF/],
56
+
57
+ // Reserved names (`col`, `script`, `Language`, `WebHandler`) must not match
58
+ // a prefix of a longer name (`Columns`, `asp:ScriptManager`). Keywords are
59
+ // recognized only against this word token, which directive names use. Other
60
+ // tag names come from the scanner, which reads the whole name and leaves
61
+ // the reserved ones to the grammar.
62
+ word: ($) => $._name,
63
+
64
+ externals: ($) => [
65
+ $._lang_csharp,
66
+ $._lang_vb,
67
+ $._lang_other,
68
+ $._code_csharp,
69
+ $._code_vb,
70
+ $.server_comment_text,
71
+ $._script_csharp,
72
+ $._script_vb,
73
+ $.style_text,
74
+ $.expression_text,
75
+ $._handler_csharp,
76
+ $._handler_vb,
77
+ $._start_tag_name,
78
+ $._end_tag_name,
79
+ $._implicit_end_tag,
80
+ $._self_closing_delimiter,
81
+ $._stray_end_tag_name,
82
+ $._script_tag_probe,
83
+ ],
84
+
85
+ rules: {
86
+ // WebHandler / WebService files are a directive plus code, not markup.
87
+ // The reserved directive name is what selects that alternative. An empty
88
+ // file is the start rule matching nothing; `document` itself cannot be
89
+ // empty because tree-sitter rejects a non-start rule that matches "".
90
+ source_file: ($) => optional(choice($.handler_file, $.document)),
91
+
92
+ document: ($) => repeat1($._top),
93
+
94
+ handler_file: ($) =>
95
+ seq(
96
+ $.handler_directive,
97
+ repeat(choice($.directive, $.server_comment, $.script_element, $.handler_code)),
98
+ ),
99
+
100
+ // The code of a handler file, labeled with the directive's language like
101
+ // nugget code so consumers count and inject it the same way.
102
+ handler_code: ($) =>
103
+ choice(alias($._handler_csharp, $.c_sharp_code), alias($._handler_vb, $.vb_code)),
104
+
105
+ _top: ($) => choice($._content, $.end_tag),
106
+
107
+ _content: ($) =>
108
+ choice(
109
+ $.directive,
110
+ $.server_comment,
111
+ $.html_comment,
112
+ $._nugget,
113
+ $.script_element,
114
+ $.style_element,
115
+ $.void_element,
116
+ $.self_closing_element,
117
+ $.element,
118
+ $.doctype,
119
+ $.cdata_section,
120
+ $.processing_instruction,
121
+ alias($.stray_end_tag, $.end_tag),
122
+ $.text,
123
+ ),
124
+
125
+ directive: ($) =>
126
+ seq('<%@', field('name', $.directive_name), repeat($._directive_attribute), '%>'),
127
+
128
+ handler_directive: ($) =>
129
+ seq(
130
+ '<%@',
131
+ field('name', alias(choice($.web_handler_name, $.web_service_name), $.directive_name)),
132
+ repeat($._directive_attribute),
133
+ '%>',
134
+ ),
135
+
136
+ _name: (_) => /[A-Za-z_][A-Za-z0-9_.:-]*/,
137
+ directive_name: ($) => $._name,
138
+ web_handler_name: (_) => reserved('WebHandler'),
139
+ web_service_name: (_) => reserved('WebService'),
140
+
141
+ // `Language` is its own attribute so the value is a language_value node
142
+ // and the scanner can record C# vs VB for later code tokens. On an
143
+ // element it is an ordinary attribute; the scanner reads a server
144
+ // script's `language` itself, before the attributes are parsed.
145
+ language_attribute: ($) =>
146
+ seq(
147
+ field('name', alias($.language_name, $.attribute_name)),
148
+ '=',
149
+ choice(
150
+ seq('"', optional(field('value', $._language_value)), '"'),
151
+ seq("'", optional(field('value', $._language_value)), "'"),
152
+ field('value', $._language_value),
153
+ ),
154
+ ),
155
+
156
+ language_name: (_) => reserved('Language'),
157
+
158
+ _language_value: ($) =>
159
+ alias(choice($._lang_csharp, $._lang_vb, $._lang_other), $.language_value),
160
+
161
+ _directive_attribute: ($) => choice($.language_attribute, $.attribute),
162
+
163
+ attribute: ($) =>
164
+ seq(
165
+ field('name', $.attribute_name),
166
+ optional(
167
+ seq(
168
+ '=',
169
+ field(
170
+ 'value',
171
+ choice(
172
+ $.quoted_attribute_value,
173
+ alias($.unquoted_attribute_value, $.attribute_value),
174
+ ),
175
+ ),
176
+ ),
177
+ ),
178
+ ),
179
+
180
+ attribute_name: (_) => /[A-Za-z_:][A-Za-z0-9_.:-]*/,
181
+
182
+ quoted_attribute_value: ($) =>
183
+ choice(
184
+ seq('"', repeat($._double_quoted_chunk), '"'),
185
+ seq("'", repeat($._single_quoted_chunk), "'"),
186
+ ),
187
+
188
+ _double_quoted_chunk: ($) =>
189
+ choice(
190
+ $._nugget,
191
+ $.server_comment,
192
+ alias(/[^"<%]+/, $.attribute_value),
193
+ alias('%', $.attribute_value),
194
+ alias('<', $.attribute_value),
195
+ ),
196
+
197
+ _single_quoted_chunk: ($) =>
198
+ choice(
199
+ $._nugget,
200
+ $.server_comment,
201
+ alias(/[^'<%]+/, $.attribute_value),
202
+ alias('%', $.attribute_value),
203
+ alias('<', $.attribute_value),
204
+ ),
205
+
206
+ unquoted_attribute_value: (_) => /[^"'=<>\s`]+/,
207
+
208
+ // Any run of two or more dashes before `%>` closes the comment, as in
209
+ // `<%-- note ---%>`; the scanner stops the text before that run.
210
+ server_comment: ($) =>
211
+ seq('<%--', optional($.server_comment_text), alias(token(/-*--%>/), '--%>')),
212
+
213
+ // Nuggets inside an HTML comment still execute, so they stay real nodes.
214
+ html_comment: ($) =>
215
+ seq(
216
+ '<!--',
217
+ repeat(
218
+ choice(
219
+ $._nugget,
220
+ $.server_comment,
221
+ $.directive,
222
+ alias(/[^-<>]+/, $.comment_text),
223
+ alias('-', $.comment_text),
224
+ alias('<', $.comment_text),
225
+ alias('>', $.comment_text),
226
+ ),
227
+ ),
228
+ '-->',
229
+ ),
230
+
231
+ _nugget: ($) =>
232
+ choice(
233
+ $.encoded_expression,
234
+ $.output_expression,
235
+ $.binding_expression,
236
+ $.expression_builder,
237
+ $.statement_block,
238
+ ),
239
+
240
+ _embedded_code: ($) =>
241
+ choice(alias($._code_csharp, $.c_sharp_code), alias($._code_vb, $.vb_code)),
242
+
243
+ encoded_expression: ($) => seq('<%:', optional($._embedded_code), '%>'),
244
+ output_expression: ($) => seq('<%=', optional($._embedded_code), '%>'),
245
+ binding_expression: ($) => seq('<%#', optional($._embedded_code), '%>'),
246
+ statement_block: ($) => seq('<%', optional($._embedded_code), '%>'),
247
+
248
+ // Expression builders (`<%$ AppSettings:Key %>`) are not C# or VB.
249
+ expression_builder: ($) =>
250
+ seq('<%$', optional(alias($.expression_text, $.expression_value)), '%>'),
251
+
252
+ // Script and style bodies are raw text up to their end tag, except that
253
+ // nuggets, server comments, and directives inside them are still parsed. A body
254
+ // split by a nugget is several code or style_text chunks; the injection
255
+ // query combines them.
256
+ script_element: ($) =>
257
+ seq(
258
+ alias($.script_start_tag, $.start_tag),
259
+ repeat(
260
+ choice(
261
+ alias($._script_csharp, $.c_sharp_code),
262
+ alias($._script_vb, $.vb_code),
263
+ $._nugget,
264
+ $.server_comment,
265
+ $.directive,
266
+ ),
267
+ ),
268
+ alias($.script_end_tag, $.end_tag),
269
+ ),
270
+
271
+ // The probe is a zero-width scanner token that reads the tag's `runat`
272
+ // and `language` ahead of the grammar, so a server script's body is
273
+ // labeled with its own language.
274
+ script_start_tag: ($) =>
275
+ seq(
276
+ '<',
277
+ field('name', alias($.script_tag_name, $.tag_name)),
278
+ $._script_tag_probe,
279
+ repeat($._tag_item),
280
+ '>',
281
+ ),
282
+
283
+ script_end_tag: ($) => seq('</', field('name', alias($.script_tag_name, $.tag_name)), '>'),
284
+
285
+ script_tag_name: (_) => reserved('script'),
286
+
287
+ style_element: ($) =>
288
+ seq(
289
+ alias($.style_start_tag, $.start_tag),
290
+ repeat(choice($.style_text, $._nugget, $.server_comment, $.directive)),
291
+ alias($.style_end_tag, $.end_tag),
292
+ ),
293
+
294
+ style_start_tag: ($) =>
295
+ seq('<', field('name', alias($.style_tag_name, $.tag_name)), repeat($._tag_item), '>'),
296
+
297
+ style_end_tag: ($) => seq('</', field('name', alias($.style_tag_name, $.tag_name)), '>'),
298
+
299
+ style_tag_name: (_) => reserved('style'),
300
+
301
+ void_element: ($) =>
302
+ seq(
303
+ '<',
304
+ field('name', alias($.void_tag_name, $.tag_name)),
305
+ repeat($._tag_item),
306
+ choice('/>', '>'),
307
+ ),
308
+
309
+ void_tag_name: (_) => choice(...VOID_TAGS.map((name) => reserved(name))),
310
+
311
+ // `<script src="..." />` and `<style />` close themselves in XHTML-era
312
+ // pages instead of opening a raw-text body. Other names go through the
313
+ // scanner's open-element stack, so their `/>` is the scanner's token.
314
+ self_closing_element: ($) =>
315
+ choice(
316
+ seq(
317
+ '<',
318
+ field('name', $._tag_name),
319
+ repeat($._tag_item),
320
+ alias($._self_closing_delimiter, '/>'),
321
+ ),
322
+ seq(
323
+ '<',
324
+ field('name', alias($.script_tag_name, $.tag_name)),
325
+ $._script_tag_probe,
326
+ repeat($._tag_item),
327
+ '/>',
328
+ ),
329
+ seq('<', field('name', alias($.style_tag_name, $.tag_name)), repeat($._tag_item), '/>'),
330
+ ),
331
+
332
+ // An element ends at its end tag or, for HTML's optional end tags (`li`,
333
+ // `p`, `td`, `option`, and the rest), where the scanner finds it implied:
334
+ // at a sibling or other start tag that closes it, at an ancestor's end
335
+ // tag, or at the end of the file.
336
+ element: ($) => seq($.start_tag, repeat($._content), choice($.end_tag, $._implicit_end_tag)),
337
+
338
+ start_tag: ($) => seq('<', field('name', $._tag_name), repeat($._tag_item), '>'),
339
+
340
+ // A nugget or server comment can stand in for an attribute, as in
341
+ // `<option value="1" <%= selected ? "selected" : "" %>>`.
342
+ _tag_item: ($) => choice($.attribute, $._nugget, $.server_comment),
343
+
344
+ // Start and end tag names come from the scanner, which keeps the stack of
345
+ // open elements that implied end tags are decided from.
346
+ _tag_name: ($) => alias($._start_tag_name, $.tag_name),
347
+
348
+ end_tag: ($) =>
349
+ seq(
350
+ '</',
351
+ field(
352
+ 'name',
353
+ choice(
354
+ alias($.script_tag_name, $.tag_name),
355
+ alias($.style_tag_name, $.tag_name),
356
+ alias($.void_tag_name, $.tag_name),
357
+ alias($._end_tag_name, $.tag_name),
358
+ ),
359
+ ),
360
+ '>',
361
+ ),
362
+
363
+ // An end tag that names no open element closes nothing, as a browser
364
+ // treats it, so `<p><table></table></p>` keeps its parent open.
365
+ stray_end_tag: ($) => seq('</', field('name', alias($._stray_end_tag_name, $.tag_name)), '>'),
366
+
367
+ doctype: ($) => seq($.doctype_token, optional(alias(/[^>]+/, $.doctype_declaration)), '>'),
368
+
369
+ doctype_token: (_) => token(prec(RESERVED, /<![Dd][Oo][Cc][Tt][Yy][Pp][Ee]/)),
370
+
371
+ // `<![CDATA[ ... ]]>` and `<?xml ... ?>` appear in XHTML-era pages and
372
+ // .asmx files. ASP.NET still runs nuggets inside them, as in an RSS feed's
373
+ // `<![CDATA[<%# Eval("Body") %>]]>`, so nuggets stay real nodes and the
374
+ // rest is text.
375
+ cdata_section: ($) =>
376
+ seq(
377
+ '<![CDATA[',
378
+ repeat(
379
+ choice(
380
+ $._nugget,
381
+ $.server_comment,
382
+ alias(/[^\]<]+/, $.text),
383
+ alias(']', $.text),
384
+ alias('<', $.text),
385
+ ),
386
+ ),
387
+ ']]>',
388
+ ),
389
+
390
+ processing_instruction: ($) =>
391
+ seq(
392
+ '<?',
393
+ repeat(
394
+ choice(
395
+ $._nugget,
396
+ $.server_comment,
397
+ alias(/[^?<]+/, $.text),
398
+ alias('?', $.text),
399
+ alias('<', $.text),
400
+ ),
401
+ ),
402
+ '?>',
403
+ ),
404
+
405
+ // A `<` followed by whitespace starts no tag, as browsers and ASP.NET's
406
+ // own tag pattern read it, so `a < b` is text rather than an element.
407
+ text: (_) => token(choice(/[^<\s][^<]*/, /<\s[^<]*/)),
408
+ },
409
+ });