@willbooster/tree-sitter-markdown 0.0.0-placeholder.0 → 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) 2021 Matthias Deiml
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/README.md CHANGED
@@ -1,3 +1,196 @@
1
1
  # @willbooster/tree-sitter-markdown
2
2
 
3
- This version is a placeholder that reserves the package name so that releases can be published from GitHub Actions with trusted publishing. Use 1.0.0 or later.
3
+ [![npm version](https://img.shields.io/npm/v/@willbooster/tree-sitter-markdown.svg)](https://www.npmjs.com/package/@willbooster/tree-sitter-markdown)
4
+ [![license](https://img.shields.io/npm/l/@willbooster/tree-sitter-markdown.svg)](https://www.npmjs.com/package/@willbooster/tree-sitter-markdown)
5
+ [![Test](https://github.com/WillBooster/tree-sitter-markdown/actions/workflows/test.yml/badge.svg)](https://github.com/WillBooster/tree-sitter-markdown/actions/workflows/test.yml)
6
+ [![Test rust](https://github.com/WillBooster/tree-sitter-markdown/actions/workflows/test-rust.yml/badge.svg)](https://github.com/WillBooster/tree-sitter-markdown/actions/workflows/test-rust.yml)
7
+ [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
8
+ [![wbfy](https://img.shields.io/badge/wbfy-20.41.9-1e90ff.svg)](https://github.com/WillBooster/shared/tree/main/packages/wbfy)
9
+ [![crates.io](https://img.shields.io/crates/v/willbooster-tree-sitter-md.svg)](https://crates.io/crates/willbooster-tree-sitter-md)
10
+
11
+ Markdown grammars for [tree-sitter](https://github.com/tree-sitter/tree-sitter), forked from
12
+ [tree-sitter-grammars/tree-sitter-markdown](https://github.com/tree-sitter-grammars/tree-sitter-markdown). We are
13
+ grateful to its authors and contributors. This is not an official release of that project.
14
+
15
+ This fork builds on the grammars, external scanners, and queries of upstream's version 0.5.3 and generates the parsers
16
+ with the [WillBooster/tree-sitter](https://github.com/WillBooster/tree-sitter) generator. The block scanner compares the
17
+ digits of an ordered list marker with `'0'` and `'9'` instead of calling `isdigit`, which the C headers for
18
+ `wasm32-unknown-unknown` do not declare; both accept the ASCII digits only. The parsers carry that fork's
19
+ own ABI number (`0x57420001`) and load only with that fork's runtime, version 2.0.0 or later: upstream's tree-sitter
20
+ runtime rejects them. They parse as the parsers in upstream's 0.5.3 packages do, with these exceptions:
21
+
22
+ - A NUL character is part of the text around it, in both grammars, where upstream's lexers report it as an unexpected
23
+ character in an `ERROR` node.
24
+ - A block that starts with bracketed text holding a backslash escape or a character reference, such as
25
+ `[\<g> element](/a)` or `[&lt;a&gt;] b`, has an error in both parsers. Upstream's parser reads an `ERROR` that holds the
26
+ `link_label`, followed by a paragraph. When the rest of the line reads as a single link destination, as in both
27
+ examples, this parser reads a `link_reference_definition` whose `:` is `MISSING` instead.
28
+
29
+ It holds two grammars, as upstream does: `markdown` (in `tree-sitter-markdown/`) parses the block structure of a
30
+ document, and `markdown_inline` (in `tree-sitter-markdown-inline/`) parses the inline content that the block grammar
31
+ leaves in `inline` and `pipe_table_cell` nodes. Both parsers include the extensions that upstream enables by default:
32
+ GitHub Flavored Markdown (task lists, strikethrough, and pipe tables), YAML and TOML metadata blocks, and LaTeX spans.
33
+ Tags and wiki links, which upstream adds only when its parsers are generated with environment variables set, are not
34
+ included, as they are not in upstream's packages.
35
+
36
+ ## Usage
37
+
38
+ The npm package ships `tree-sitter-markdown.wasm` and `tree-sitter-markdown_inline.wasm` for
39
+ [@willbooster/web-tree-sitter](https://www.npmjs.com/package/@willbooster/web-tree-sitter) version 2.0.0 or later, which
40
+ runs in Node.js, Bun, browsers, and Cloudflare Workers. Parse a document with the block grammar, then parse the inline
41
+ content of each `inline` or `pipe_table_cell` node with the inline grammar, limited to the node's range without its
42
+ named children (block continuations such as the `>` of a block quote). In Node.js and Bun, load the grammars from their
43
+ paths:
44
+
45
+ ```js
46
+ import { fileURLToPath } from 'node:url';
47
+ import { Language, Parser } from '@willbooster/web-tree-sitter';
48
+
49
+ await Parser.init();
50
+ const load = (name) =>
51
+ Language.load(fileURLToPath(import.meta.resolve(`@willbooster/tree-sitter-markdown/${name}.wasm`)));
52
+ const blockParser = new Parser();
53
+ blockParser.setLanguage(await load('tree-sitter-markdown'));
54
+ const inlineParser = new Parser();
55
+ inlineParser.setLanguage(await load('tree-sitter-markdown_inline'));
56
+
57
+ const source = '# Title\n\n> Some *emphasized*\n> text.\n';
58
+ const tree = blockParser.parse(source);
59
+ for (const node of tree.rootNode.descendantsOfType(['inline', 'pipe_table_cell'])) {
60
+ const includedRanges = [];
61
+ let start = { index: node.startIndex, position: node.startPosition };
62
+ for (const child of node.namedChildren) {
63
+ includedRanges.push({
64
+ startIndex: start.index,
65
+ startPosition: start.position,
66
+ endIndex: child.startIndex,
67
+ endPosition: child.startPosition,
68
+ });
69
+ start = { index: child.endIndex, position: child.endPosition };
70
+ }
71
+ includedRanges.push({
72
+ startIndex: start.index,
73
+ startPosition: start.position,
74
+ endIndex: node.endIndex,
75
+ endPosition: node.endPosition,
76
+ });
77
+ const inlineTree = inlineParser.parse(source, null, { includedRanges });
78
+ }
79
+ ```
80
+
81
+ In browsers, serve the `.wasm` files and load them by URL (the example uses Vite's `?url` imports):
82
+
83
+ ```js
84
+ import { Language, Parser } from '@willbooster/web-tree-sitter';
85
+ import runtimeUrl from '@willbooster/web-tree-sitter/web-tree-sitter.wasm?url';
86
+ import markdownUrl from '@willbooster/tree-sitter-markdown/tree-sitter-markdown.wasm?url';
87
+ import markdownInlineUrl from '@willbooster/tree-sitter-markdown/tree-sitter-markdown_inline.wasm?url';
88
+
89
+ await Parser.init({ locateFile: () => runtimeUrl });
90
+ const blockParser = new Parser();
91
+ blockParser.setLanguage(await Language.load(markdownUrl));
92
+ const inlineParser = new Parser();
93
+ inlineParser.setLanguage(await Language.load(markdownInlineUrl));
94
+ ```
95
+
96
+ Cloudflare Workers do not allow compiling Wasm at run time, so import the `.wasm` files as modules, with or without
97
+ Node.js compatibility:
98
+
99
+ ```js
100
+ import { Language, Parser } from '@willbooster/web-tree-sitter';
101
+ import runtime from '@willbooster/web-tree-sitter/web-tree-sitter.wasm';
102
+ import markdown from '@willbooster/tree-sitter-markdown/tree-sitter-markdown.wasm';
103
+ import markdownInline from '@willbooster/tree-sitter-markdown/tree-sitter-markdown_inline.wasm';
104
+
105
+ await Parser.init({ wasmModule: runtime });
106
+ const blockParser = new Parser();
107
+ blockParser.setLanguage(await Language.load(markdown));
108
+ const inlineParser = new Parser();
109
+ inlineParser.setLanguage(await Language.load(markdownInline));
110
+ ```
111
+
112
+ The package also ships the grammar definitions (`common/common.js`, `common/html_entities.json`,
113
+ `tree-sitter-markdown/grammar.js`, and `tree-sitter-markdown-inline/grammar.js`), the queries in
114
+ `tree-sitter-markdown/queries/` and `tree-sitter-markdown-inline/queries/`, and the node types in
115
+ `tree-sitter-markdown/src/node-types.json` and `tree-sitter-markdown-inline/src/node-types.json`.
116
+
117
+ In Rust, depend on the [crate](https://crates.io/crates/willbooster-tree-sitter-md) and on
118
+ [willbooster-tree-sitter](https://crates.io/crates/willbooster-tree-sitter), the runtime this package is tested and
119
+ fuzzed with:
120
+
121
+ ```toml
122
+ [dependencies]
123
+ tree-sitter = { package = "willbooster-tree-sitter", version = "2" }
124
+ tree-sitter-md = { package = "willbooster-tree-sitter-md", version = "1" }
125
+ ```
126
+
127
+ ```rust
128
+ let mut parser = tree_sitter::Parser::new();
129
+ parser.set_language(&tree_sitter_md::LANGUAGE.into())?;
130
+ ```
131
+
132
+ The crate keeps the API of upstream's `tree-sitter-md` crate: `tree_sitter_md::INLINE_LANGUAGE` is the inline grammar,
133
+ and the `parser` feature adds `MarkdownParser`, which parses a document with both grammars into a `MarkdownTree`.
134
+ `MarkdownCursor::field_name` returns a name that borrows from the tree (`Option<&'tree str>`), since the
135
+ willbooster-tree-sitter runtime returns field names with that lifetime, where upstream's returns `Option<&'static str>`.
136
+
137
+ ## Development
138
+
139
+ ```sh
140
+ mise install
141
+ bun install --frozen-lockfile
142
+ bun run test/ci-setup # installs Chromium for the browser test
143
+ bun run build/ci
144
+ bun run test
145
+ script/parse-examples
146
+ cargo test --all-features
147
+ ```
148
+
149
+ The scripts and tests generate, build, test, and parse with `script/tree-sitter`, the tree-sitter CLI of the
150
+ WillBooster/tree-sitter runtime version locked in `Cargo.lock`, since the generator and the runtime of upstream's CLI are
151
+ not the ones this package ships with. Its first run downloads that CLI from the runtime's GitHub Release, or builds it
152
+ with `cargo` (whose build runs the CMake that `mise.toml` pins) when the download fails or the release has no binary
153
+ that runs here. Run other CLI commands through it as well (e.g. `script/tree-sitter parse --grammar-path
154
+ tree-sitter-markdown file.md`).
155
+
156
+ `bun run generate` records a fresh generation profile for each grammar from the cases in its `test/corpus` (and, for the
157
+ block grammar, from Git-tracked files in `examples/`, of which there are none), then generates compact parser tables.
158
+ It generates the parsers with upstream's default extensions whatever extension variables (e.g. `ALL_EXTENSIONS`) the
159
+ environment holds. The parsers also embed metadata from `tree-sitter.json`. After changing a grammar, `common/`,
160
+ `tree-sitter.json`, or a corpus case, regenerate and commit `tree-sitter-markdown/src/` and
161
+ `tree-sitter-markdown-inline/src/`. Profiles in `.tmp/generation-profiles/` are temporary and must not be committed.
162
+ `bun run build-wasm`, `bun run build/ci`, and the release build regenerate the parsers before compiling them.
163
+
164
+ `bun run test` runs:
165
+
166
+ - the corpus of each grammar (`script/test-corpus`), with the native build and with the Wasm build (the first run
167
+ downloads the WASI SDK). The corpora are upstream's, which expect every extension: `script/corpus-exclusions` lists
168
+ the cases of the tags and wiki-link extensions, which these parsers leave out;
169
+ - an incremental-parsing check (`test/unit/incremental.test.ts`): `script/fuzz-corpus` runs `tree-sitter fuzz` for a
170
+ grammar, which edits each of its corpus cases at random, reparses it, undoes the edits, and reparses again.
171
+ `TREE_SITTER_SEED`, `TREE_SITTER_ITERATIONS`, and `TREE_SITTER_EDITS` run other or more edits. It skips the cases that
172
+ `script/fuzz-corpus` excludes, which upstream's parser fails as well;
173
+ - a check that the real-world Markdown files in `examples/` fail to parse with the block grammar exactly as listed in
174
+ `script/known-failures.txt`. The first run clones the repositories. The example repositories are pinned to commits in
175
+ `script/parse-examples`. After a grammar change or a moved pin alters that list, `script/parse-examples` rewrites it;
176
+ review its diff before committing;
177
+ - a performance check (`test/unit/performance.test.ts`) that input leaving constructs open on each line parses in
178
+ linear time with both grammars, since consumers parse files while they are being edited. It loads the Wasm builds
179
+ through @willbooster/web-tree-sitter, which `bun run build/ci` rebuilds after regenerating the parsers;
180
+ - a check (`test/unit/runtimeVersion.test.ts`) that `@willbooster/web-tree-sitter` in `package.json` and
181
+ `willbooster-tree-sitter` in `Cargo.lock` are the same version, since the Wasm tests run on the former and the Rust
182
+ tests, the fuzzer, and the CLI on the latter;
183
+ - tests that load the Wasm builds with @willbooster/web-tree-sitter in Chromium (`test/e2e/browser.test.ts`) and in
184
+ Cloudflare Workers with and without Node.js compatibility (`test/e2e/workers.test.ts`).
185
+
186
+ The tests compile the parsers into `.tmp/tree-sitter-lib` rather than the CLI's cache shared by every checkout;
187
+ `script/fuzz-corpus` and `script/parse-examples` build a parser of their own in `.tmp/` for each run and delete it
188
+ afterwards.
189
+
190
+ CI also runs these tests on Linux arm64 and macOS, where the CLI compiles the parsers and the scanners natively, and
191
+ fuzzes both parsers with libFuzzer and sanitizers (`.github/workflows/robustness.yml`).
192
+
193
+ ### References
194
+
195
+ - [CommonMark Spec](https://spec.commonmark.org/)
196
+ - [GitHub Flavored Markdown Spec](https://github.github.com/gfm/)
@@ -0,0 +1,132 @@
1
+ /// <reference types="tree-sitter-cli/dsl" />
2
+
3
+ module.exports.EXTENSION_DEFAULT = !process.env.NO_DEFAULT_EXTENSIONS;
4
+ module.exports.EXTENSION_GFM = process.env.EXTENSION_GFM || module.exports.EXTENSION_DEFAULT || process.env.ALL_EXTENSIONS;
5
+ module.exports.EXTENSION_TASK_LIST = process.env.EXTENSION_TASK_LIST || module.exports.EXTENSION_GFM || process.env.ALL_EXTENSIONS;
6
+ module.exports.EXTENSION_STRIKETHROUGH = process.env.EXTENSION_STRIKETHROUGH || module.exports.EXTENSION_GFM || process.env.ALL_EXTENSIONS;
7
+ module.exports.EXTENSION_PIPE_TABLE = process.env.EXTENSION_PIPE_TABLE || module.exports.EXTENSION_GFM || process.env.ALL_EXTENSIONS;
8
+ module.exports.EXTENSION_MINUS_METADATA = process.env.EXTENSION_MINUS_METADATA || module.exports.EXTENSION_DEFAULT || process.env.ALL_EXTENSIONS;
9
+ module.exports.EXTENSION_PLUS_METADATA = process.env.EXTENSION_PLUS_METADATA || module.exports.EXTENSION_DEFAULT || process.env.ALL_EXTENSIONS;
10
+ module.exports.EXTENSION_TAGS = process.env.EXTENSION_TAGS || process.env.ALL_EXTENSIONS;
11
+ module.exports.EXTENSION_LATEX = process.env.EXTENSION_LATEX || module.exports.EXTENSION_DEFAULT || process.env.ALL_EXTENSIONS;
12
+ module.exports.EXTENSION_WIKI_LINK = process.env.EXTENSION_WIKI_LINK || process.env.ALL_EXTENSIONS;
13
+
14
+ const PUNCTUATION_CHARACTERS_REGEX = '!-/:-@\\[-`\\{-~';
15
+ const PUNCTUATION_CHARACTERS_ARRAY = [
16
+ '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<',
17
+ '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'
18
+ ];
19
+
20
+ const PRECEDENCE_LEVEL_LINK = 10;
21
+
22
+ module.exports.PRECEDENCE_LEVEL_LINK = PRECEDENCE_LEVEL_LINK;
23
+
24
+ module.exports.PUNCTUATION_CHARACTERS_REGEX = PUNCTUATION_CHARACTERS_REGEX;
25
+
26
+ /** @type {Record<string, ($: GrammarSymbols<any>) => RuleOrLiteral>} */
27
+ module.exports.rules = {
28
+
29
+ // A backslash escape. This can often be part of different nodes like link labels
30
+ //
31
+ // https://github.github.com/gfm/#backslash-escapes
32
+ backslash_escape: $ => $._backslash_escape,
33
+ _backslash_escape: $ => new RegExp('\\\\[' + PUNCTUATION_CHARACTERS_REGEX + ']'),
34
+
35
+ // HTML entity and numeric character references.
36
+ //
37
+ // The regex for entity references are build from the html_entities.json file.
38
+ //
39
+ // https://github.github.com/gfm/#entity-and-numeric-character-references
40
+ entity_reference: $ => html_entity_regex(),
41
+ numeric_character_reference: $ => /&#([0-9]{1,7}|[xX][0-9a-fA-F]{1,6});/,
42
+
43
+ link_label: $ => seq('[', repeat1(choice(
44
+ $._text_inline_no_link,
45
+ $.backslash_escape,
46
+ $.entity_reference,
47
+ $.numeric_character_reference,
48
+ $._soft_line_break
49
+ )), ']'),
50
+
51
+ link_destination: $ => prec.dynamic(PRECEDENCE_LEVEL_LINK, choice(
52
+ seq('<', repeat(choice($._text_no_angle, $.backslash_escape, $.entity_reference, $.numeric_character_reference)), '>'),
53
+ seq(
54
+ choice( // first character is not a '<'
55
+ $._word,
56
+ punctuation_without($, ['<', '(', ')']),
57
+ $.backslash_escape,
58
+ $.entity_reference,
59
+ $.numeric_character_reference,
60
+ $._link_destination_parenthesis
61
+ ),
62
+ repeat(choice(
63
+ $._word,
64
+ punctuation_without($, ['(', ')']),
65
+ $.backslash_escape,
66
+ $.entity_reference,
67
+ $.numeric_character_reference,
68
+ $._link_destination_parenthesis
69
+ )),
70
+ )
71
+ )),
72
+ _link_destination_parenthesis: $ => seq('(', repeat(choice(
73
+ $._word,
74
+ punctuation_without($, ['(', ')']),
75
+ $.backslash_escape,
76
+ $.entity_reference,
77
+ $.numeric_character_reference,
78
+ $._link_destination_parenthesis
79
+ )), ')'),
80
+ _text_no_angle: $ => choice($._word, punctuation_without($, ['<', '>']), $._whitespace),
81
+ link_title: $ => choice(
82
+ seq('"', repeat(choice(
83
+ $._word,
84
+ punctuation_without($, ['"']),
85
+ $._whitespace,
86
+ $.backslash_escape,
87
+ $.entity_reference,
88
+ $.numeric_character_reference,
89
+ seq($._soft_line_break, optional(seq($._soft_line_break, $._trigger_error)))
90
+ )), '"'),
91
+ seq("'", repeat(choice(
92
+ $._word,
93
+ punctuation_without($, ["'"]),
94
+ $._whitespace,
95
+ $.backslash_escape,
96
+ $.entity_reference,
97
+ $.numeric_character_reference,
98
+ seq($._soft_line_break, optional(seq($._soft_line_break, $._trigger_error)))
99
+ )), "'"),
100
+ seq('(', repeat(choice(
101
+ $._word,
102
+ punctuation_without($, ['(', ')']),
103
+ $._whitespace,
104
+ $.backslash_escape,
105
+ $.entity_reference,
106
+ $.numeric_character_reference,
107
+ seq($._soft_line_break, optional(seq($._soft_line_break, $._trigger_error)))
108
+ )), ')'),
109
+ ),
110
+
111
+ _newline_token: $ => /\n|\r\n?/,
112
+ };
113
+
114
+ // Returns a rule that matches all characters that count as punctuation inside markdown, besides
115
+ // a list of excluded punctuation characters. Calling this function with a empty list as the second
116
+ // argument returns a rule that matches all punctuation.
117
+ function punctuation_without($, chars) {
118
+ return seq(choice(...PUNCTUATION_CHARACTERS_ARRAY.filter(c => !chars.includes(c))), optional($._last_token_punctuation));
119
+ }
120
+
121
+ module.exports.punctuation_without = punctuation_without;
122
+
123
+ // Constructs a regex that matches all html entity references.
124
+ function html_entity_regex() {
125
+ // A file with all html entities, should be kept up to date with
126
+ // https://html.spec.whatwg.org/multipage/entities.json
127
+ let html_entities = require("./html_entities.json");
128
+ let s = '&(';
129
+ s += Object.keys(html_entities).map(name => name.substring(1, name.length - 1)).join('|');
130
+ s += ');';
131
+ return new RegExp(s);
132
+ }