prettier-plugin-julia 0.0.0-stage → 0.2.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,59 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.2.1] - 2026-11-16
10
+
11
+ First release on npm: `npm install --save-dev prettier prettier-plugin-julia`. No
12
+ changes to formatting.
13
+
14
+ ## [0.2.0] - 2026-11-10
15
+
16
+ ### Changed
17
+
18
+ - `wasm/parser.wasm` rebuilt on [WasmCodegen.jl](https://github.com/gbaraldi/WasmCodegen.jl)
19
+ main `98cad1f` (v0.1.0: `316bbaf`), with WasmBuilder.jl 0.1.1 and `wasm-opt -O3`
20
+ (Binaryen 130). JuliaSyntax is unchanged: the one shipped in Julia 1.13.2 (also the one in
21
+ 1.13.3). The parser output is identical to v0.1.0's on 25,174 real-world Julia files, and
22
+ parsing speed is the same within noise (0.156 → 0.159 s/MB). The module is 739,251 bytes
23
+ (was 735,576). `wasm/manifest.json` also records the WasmBuilder and Binaryen versions.
24
+ It is the same file as in eslint-plugin-julia v0.2.0. The build was first checked on
25
+ WasmCodegen main in #2; this release ships it.
26
+
27
+ ### Fixed
28
+
29
+ - The source links in `wasm/manifest.json` point at topiary-julia's `jlparse` branch, where
30
+ the parser sources are (the links to `main` were broken).
31
+
32
+ ## [0.1.0] - 2026-11-08
33
+
34
+ First release, distributed as a GitHub release tarball (not on npm yet).
35
+
36
+ ### Added
37
+
38
+ - Prettier 3 plugin for Julia (`.jl`): language registration, the `julia` parser, and a
39
+ printer built on JuliaSyntax (from Julia 1.13.2) compiled to WebAssembly. No Julia
40
+ installation needed.
41
+ - Style close to Runic and JuliaFormatter: 4-space indent, 92 columns, spaces around binary
42
+ operators except `:` and `^`, `f(x; k=1)` keyword arguments, one element per line with a
43
+ trailing comma when a list doesn't fit, unindented `module` bodies, `for i in`.
44
+ - Safety check: every output is parsed again and compared with the input in a strict
45
+ normal form; code whose meaning would change is kept as written and reported. Options
46
+ `juliaVerify` and `juliaReport`.
47
+ - `# prettier-ignore` and `#! format: off` / `#! format: on`.
48
+ - ` ```julia ` / ` ```jl ` blocks in Markdown, formatted with 4-space indent
49
+ and 92 columns.
50
+ - Usage guide for the CLI, GitHub Actions, lint-staged, pre-commit and VS Code
51
+ ([docs/usage.md](docs/usage.md)).
52
+
53
+ Tested on 25,174 real-world Julia files: all valid files formatted and verified, no region
54
+ kept as written, formatting is idempotent.
55
+
56
+ [Unreleased]: https://github.com/pankgeorg/prettier-plugin-julia/compare/v0.2.1...HEAD
57
+ [0.2.1]: https://github.com/pankgeorg/prettier-plugin-julia/compare/v0.2.0...v0.2.1
58
+ [0.2.0]: https://github.com/pankgeorg/prettier-plugin-julia/compare/v0.1.0...v0.2.0
59
+ [0.1.0]: https://github.com/pankgeorg/prettier-plugin-julia/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Panagiotis Georgakopoulos
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,188 @@
1
- # Temporary Holding Version
1
+ # prettier-plugin-julia
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
+ [![CI](https://github.com/pankgeorg/prettier-plugin-julia/actions/workflows/ci.yml/badge.svg)](https://github.com/pankgeorg/prettier-plugin-julia/actions/workflows/ci.yml)
4
+ [![Release](https://img.shields.io/github/v/release/pankgeorg/prettier-plugin-julia)](https://github.com/pankgeorg/prettier-plugin-julia/releases)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ A [Prettier](https://prettier.io) 3 plugin that formats Julia code. It parses with Julia's
8
+ own parser, [JuliaSyntax](https://github.com/JuliaLang/JuliaSyntax.jl) as shipped with Julia
9
+ 1.13, compiled to WebAssembly: no Julia installation needed, and the plugin reads code
10
+ exactly as Julia does.
11
+
12
+ **Every format is checked.** The output is parsed again and compared with the input. Code
13
+ whose formatting would change what the program means is kept exactly as written, and
14
+ reported. The plugin never writes a program that parses differently from yours.
15
+
16
+ <!-- prettier-ignore -->
17
+ ```julia
18
+ # before
19
+ function f(x::Int,y=2;k=3) where T
20
+ z = x+y # trailing
21
+ if z>3 return z end
22
+ [i^2 for i = 1:n if isodd(i)]
23
+ end
24
+
25
+ # after
26
+ function f(x::Int, y=2; k=3) where T
27
+ z = x + y # trailing
28
+ if z > 3
29
+ return z
30
+ end
31
+ [i^2 for i in 1:n if isodd(i)]
32
+ end
33
+ ```
34
+
35
+ ## Install
36
+
37
+ Node `^22.23.3` or `^24.22.1`, and Prettier 3.
38
+
39
+ ```sh
40
+ npm install --save-dev prettier prettier-plugin-julia
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ `.prettierrc`:
46
+
47
+ ```json
48
+ { "plugins": ["prettier-plugin-julia"] }
49
+ ```
50
+
51
+ ```sh
52
+ npx prettier --write "**/*.jl" # format
53
+ npx prettier --check "**/*.jl" # exit code 1 if a file would change (for CI)
54
+ ```
55
+
56
+ Markdown files get their ` ```julia ` blocks formatted too (`npx prettier --write "**/*.md"`).
57
+
58
+ [docs/usage.md](docs/usage.md) has the rest:
59
+
60
+ - a Julia project without Node (a three-file setup);
61
+ - a copy-paste GitHub Actions workflow that fails with a diff;
62
+ - lint-staged, pre-commit and VS Code settings;
63
+ - the Prettier API.
64
+
65
+ ## Style
66
+
67
+ 4-space indent, 92 columns, close to Runic and JuliaFormatter:
68
+
69
+ - spaces around binary operators except `:`, `^` and `::`;
70
+ - `f(x; k=1)`: keyword arguments and defaults without spaces;
71
+ - a list that doesn't fit goes one element per line, with a trailing comma;
72
+ - `module` bodies are not indented;
73
+ - at most one blank line in a row;
74
+ - `for i = …` is written `for i in …`.
75
+
76
+ Strings, string macros, comments and multi-line matrices are kept as written. Details:
77
+ [docs/style.md](docs/style.md).
78
+
79
+ | Option | Default | Meaning |
80
+ | ------------- | ------- | -------------------------------------------------------------------------- |
81
+ | `printWidth` | `92` | Line width. |
82
+ | `tabWidth` | `4` | Spaces per indentation level (`useTabs` for tabs). |
83
+ | `juliaVerify` | `true` | Check every format and keep code as written where it would change meaning. |
84
+ | `juliaReport` | `true` | Warn on stderr for each region kept as written. |
85
+
86
+ To leave code alone: `# prettier-ignore` before a statement, `#! format: off` …
87
+ `#! format: on` around a region, or `.prettierignore` for whole files.
88
+
89
+ ## Safety
90
+
91
+ After printing, the plugin parses the output with JuliaSyntax and compares both trees in a
92
+ strict normal form:
93
+
94
+ - whitespace and comments are ignored; leaf text must match exactly;
95
+ - node kinds and flags must match: infix vs prefix call, `@m(x)` vs `@m x`, `mutable`,
96
+ triple-quoted strings;
97
+ - comments must all survive, in order.
98
+
99
+ The only freedoms are layout ones: `a; b` on one line vs two, a trailing comma in a
100
+ multi-line list (not in a one-element tuple, where it changes the meaning).
101
+
102
+ If the trees differ, the smallest differing node is printed exactly as written and the file
103
+ is printed again (up to 30 rounds; after that, the whole file is left as it is). Each such
104
+ region is reported:
105
+
106
+ ```
107
+ [prettier-plugin-julia] warn: src/a.jl:12:5: kept `[x -y]` as written (formatting would change its meaning: …)
108
+ ```
109
+
110
+ Input that JuliaSyntax rejects is reported as a syntax error, with its position, and left
111
+ alone. A printer crash also leaves the file as it is.
112
+
113
+ What "same meaning" does not cover, as for any formatter that moves code between lines:
114
+
115
+ - source locations: `@__LINE__`, stack traces, and macros that read `__source__` see new
116
+ line numbers;
117
+ - statement grouping by `;` at top level: `a; b` on one line is a single `toplevel`
118
+ expression, two lines are two. Only code that loads files with
119
+ `include(mapexpr, …)`/`include_string(mapexpr, …)` can tell the difference.
120
+
121
+ The printer is written so that the check rarely fires:
122
+
123
+ - it only breaks lines where Julia reads a line break as whitespace or continuation, never
124
+ inside a matrix row or between macro arguments;
125
+ - it keeps `- 2`, `[x -y]`, `"""doc""" f` and the like as written;
126
+ - it prints anything it has no rule for token by token.
127
+
128
+ On the corpus below no region needed protecting; the tests inject printer bugs to show that
129
+ they are caught.
130
+
131
+ ## Results and comparison
132
+
133
+ Corpus: 25,174 unique Julia files (229 MB) from Julia 1.11/1.13 base, stdlib and tests, and
134
+ the packages of several Julia depots, deduplicated by content. Arm64 Linux, Node 22.
135
+
136
+ | | |
137
+ | ---------------------------------------------------- | -------------------------------- |
138
+ | Formatted and verified | 25,163 (3,267 already formatted) |
139
+ | Rejected by JuliaSyntax (not valid Julia 1.13) | 11 |
140
+ | Regions kept as written / whole files kept / crashes | 0 / 0 / 0 |
141
+ | Not idempotent (formatting twice ≠ once) | 0 |
142
+
143
+ The same 300-file sample through [Runic](https://github.com/fredrikekre/Runic.jl) 1.13 and
144
+ [JuliaFormatter](https://github.com/domluna/JuliaFormatter.jl) 2.14 (default settings),
145
+ checked with the same JuliaSyntax normal form:
146
+
147
+ | | this plugin | Runic | JuliaFormatter |
148
+ | ------------------------------- | ----------- | ------ | -------------- |
149
+ | Files left unchanged | 31 | 88 | 38 |
150
+ | Output parses to the same tree | 300 | 146 | 233 |
151
+ | Time, 4.4 MB, warm, one process | 5.7 s | 3.9 s | 1.6 s |
152
+ | Time per MB | 1.3 s | 0.88 s | 0.35 s |
153
+ | Start-up + a tiny file | 0.22 s | 0.27 s | 0.52 s |
154
+
155
+ Runic and JuliaFormatter change trees on purpose: Runic adds explicit `return`s, braces in
156
+ `where {T}`, parentheses around range operands, and normalizes float literals;
157
+ JuliaFormatter adds `where` braces, parentheses and `::Any`. These rewrites are meant to be
158
+ equivalent. This plugin only changes layout, so its output can be checked mechanically.
159
+
160
+ **Speed, honestly:** once warm, the plugin is about 1.5× slower than Runic and 3.7× slower
161
+ than JuliaFormatter. With `juliaVerify: false` it matches Runic (0.9 s/MB) and is 2.5×
162
+ slower than JuliaFormatter. Start-up is shorter than both, so on a few small files it is
163
+ as quick as either. Where the time goes (`node scripts/bench.mjs`, s/MB):
164
+
165
+ | Stage | s/MB | % |
166
+ | -------------------------------------------- | -------: | --: |
167
+ | JuliaSyntax parse (Wasm) | 0.15 | 11 |
168
+ | Copying source in and the tree out of Wasm | 0.09 | 7 |
169
+ | Tree building | 0.14 | 10 |
170
+ | Doc building (this printer) | 0.24 | 18 |
171
+ | Line fitting (Prettier's `printDocToString`) | 0.27 | 21 |
172
+ | Verification: parsing the output | 0.24 | 19 |
173
+ | Verification: tree building and comparison | 0.17 | 13 |
174
+ | **Total** | **1.31** | |
175
+
176
+ The parser itself is under a fifth of the time. v0.2.0's parser, rebuilt on WasmCodegen main
177
+ `98cad1f`, parses at the same speed and gives identical trees.
178
+
179
+ ## Development
180
+
181
+ See [CONTRIBUTING.md](CONTRIBUTING.md): `npm test`, `npm run lint`, `npm run format:check`,
182
+ the corpus scripts, and where `wasm/parser.wasm` comes from.
183
+
184
+ ## License
185
+
186
+ MIT. `wasm/parser.wasm` contains code from Julia and JuliaSyntax (MIT) and WasmCodegen.jl
187
+ (MIT); see `wasm/LICENSES/`. The parser layer is shared with
188
+ [eslint-plugin-julia](https://github.com/pankgeorg/eslint-plugin-julia).
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "prettier-plugin-julia",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Prettier plugin for Julia, using Julia's own parser (JuliaSyntax) compiled to WebAssembly; every format is checked to keep the program's meaning",
5
+ "keywords": [
6
+ "prettier",
7
+ "prettier-plugin",
8
+ "julia",
9
+ "julialang",
10
+ "formatter",
11
+ "code-formatter",
12
+ "juliasyntax",
13
+ "webassembly"
14
+ ],
15
+ "homepage": "https://github.com/pankgeorg/prettier-plugin-julia#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/pankgeorg/prettier-plugin-julia/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/pankgeorg/prettier-plugin-julia.git"
22
+ },
23
+ "license": "MIT",
24
+ "author": "Panagiotis Georgakopoulos",
25
+ "type": "module",
26
+ "engines": {
27
+ "node": "^22.23.3 || ^24.22.1"
28
+ },
29
+ "main": "./src/index.js",
30
+ "exports": {
31
+ ".": "./src/index.js",
32
+ "./package.json": "./package.json"
33
+ },
34
+ "files": [
35
+ "src/",
36
+ "wasm/",
37
+ "README.md",
38
+ "LICENSE",
39
+ "CHANGELOG.md"
40
+ ],
41
+ "scripts": {
42
+ "test": "node scripts/check-artifact.mjs && node --test tests/*.test.js",
43
+ "lint": "eslint .",
44
+ "format": "prettier --write .",
45
+ "format:check": "prettier --check .",
46
+ "format:julia": "prettier --ignore-path .gitignore --check \"tests/format/*.out.jl\"",
47
+ "smoke": "node scripts/smoke.mjs",
48
+ "corpus": "node scripts/corpus.mjs",
49
+ "corpus:summary": "node scripts/corpus-summary.mjs"
50
+ },
51
+ "peerDependencies": {
52
+ "prettier": "^3.0.0"
53
+ },
54
+ "devDependencies": {
55
+ "@eslint/js": "^10.0.1",
56
+ "eslint": "^10.14.0",
57
+ "eslint-plugin-n": "^18.5.0",
58
+ "globals": "^17.14.0",
59
+ "prettier": "3.9.10"
60
+ }
61
+ }
package/src/format.js ADDED
@@ -0,0 +1,82 @@
1
+ // Format with verification: print, parse the output, compare; protect the differing node
2
+ // (print it verbatim) and try again; after MAX_ROUNDS, keep the whole file as written.
3
+ import { printer as docPrinter } from 'prettier/doc';
4
+ import { parseTree, hasErrors, isErrorDiagnostic } from './tree.js';
5
+ import { normalizeTree, parentsOf, printJulia } from './printer.js';
6
+ import { verify } from './verify.js';
7
+
8
+ const MAX_ROUNDS = 30;
9
+ const STATEMENT_LISTS = new Set(['block', 'toplevel', 'toplevel-file']);
10
+
11
+ export class JuliaSyntaxError extends SyntaxError {
12
+ constructor(d) {
13
+ super(d.message);
14
+ this.loc = { start: { line: d.loc.line, column: d.loc.column + 1 } };
15
+ }
16
+ }
17
+
18
+ /** Parse for formatting: throws JuliaSyntaxError on a syntax error. */
19
+ export function parseForFormat(text) {
20
+ const tree = parseTree(text);
21
+ if (hasErrors(tree)) throw new JuliaSyntaxError(tree.diagnostics.find(isErrorDiagnostic));
22
+ normalizeTree(tree.root);
23
+ return { tree, text };
24
+ }
25
+
26
+ export function render(doc, options) {
27
+ return docPrinter.printDocToString(doc, {
28
+ printWidth: options.printWidth ?? 92,
29
+ tabWidth: options.tabWidth ?? 4,
30
+ useTabs: options.useTabs ?? false,
31
+ endOfLine: 'lf',
32
+ }).formatted;
33
+ }
34
+
35
+ /**
36
+ * @returns {{ output: string, regions: Array<{line, column, excerpt, reason}>, whole: string|null, rounds: number }}
37
+ * `whole` is the reason when the whole file was kept as written.
38
+ */
39
+ export function formatParsed(parsed, options = {}, hooks = {}) {
40
+ const { tree, text } = parsed;
41
+ let parentMap = null;
42
+ const parents = { get: (n) => (parentMap ??= parentsOf(tree.root)).get(n) };
43
+ const protect = new Set();
44
+ const reasons = new Map();
45
+ const doVerify = options.juliaVerify !== false;
46
+ for (let round = 1; round <= MAX_ROUNDS; round++) {
47
+ let output;
48
+ try {
49
+ output = render(printJulia(tree, text, protect, hooks.mutate ?? null), options);
50
+ } catch (e) {
51
+ // A printer bug must not lose the file: keep it as written and say why.
52
+ return { output: text, regions: [], whole: `printer error: ${e?.message ?? e}`, rounds: round, error: e };
53
+ }
54
+ if (!doVerify) return { output, regions: [], whole: null, rounds: round };
55
+ const d = verify(tree, output);
56
+ if (!d) return { output, regions: regionsOf(protect, reasons, tree), whole: null, rounds: round };
57
+ let target = d.node;
58
+ if (target && target.text !== undefined) target = parents.get(target) ?? null;
59
+ while (target && (protect.has(target) || STATEMENT_LISTS.has(target.kind))) target = parents.get(target) ?? null;
60
+ if (!target || target === tree.root) return { output: text, regions: [], whole: d.message, rounds: round };
61
+ protect.add(target);
62
+ reasons.set(target, d.message);
63
+ }
64
+ return { output: text, regions: [], whole: `no verified formatting after ${MAX_ROUNDS} rounds`, rounds: MAX_ROUNDS };
65
+ }
66
+
67
+ function regionsOf(protect, reasons, tree) {
68
+ // Report only outermost protected nodes.
69
+ const all = [...protect];
70
+ const inside = (a, b) => a !== b && b.start <= a.start && a.end <= b.end;
71
+ return all
72
+ .filter((n) => !all.some((m) => inside(n, m)))
73
+ .map((n) => {
74
+ const { line, column } = tree.loc(n.start);
75
+ return { line, column: column + 1, start: n.start, end: n.end, reason: reasons.get(n) };
76
+ })
77
+ .sort((a, b) => a.start - b.start);
78
+ }
79
+
80
+ export function formatJulia(text, options = {}, hooks = {}) {
81
+ return formatParsed(parseForFormat(text), options, hooks);
82
+ }
package/src/index.js ADDED
@@ -0,0 +1,87 @@
1
+ // prettier-plugin-julia: Prettier 3 plugin entry point.
2
+ import { parseForFormat, formatParsed } from './format.js';
3
+ import { manifest } from './parser/wasm-host.js';
4
+
5
+ export const languages = [
6
+ {
7
+ name: 'Julia',
8
+ parsers: ['julia'],
9
+ extensions: ['.jl'],
10
+ aliases: ['julia', 'jl'],
11
+ linguistLanguageId: 184,
12
+ tmScope: 'source.julia',
13
+ aceMode: 'julia',
14
+ vscodeLanguageIds: ['julia'],
15
+ },
16
+ ];
17
+
18
+ export const parsers = {
19
+ julia: {
20
+ astFormat: 'julia-ast',
21
+ parse(text) {
22
+ const parsed = parseForFormat(text);
23
+ return { type: 'JuliaFile', parsed, start: 0, end: text.length };
24
+ },
25
+ locStart: (node) => node.start ?? 0,
26
+ locEnd: (node) => node.end ?? 0,
27
+ },
28
+ };
29
+
30
+ const prefix = '[prettier-plugin-julia]';
31
+
32
+ function report(filepath, result, text) {
33
+ const name = filepath ?? '<input>';
34
+ if (result.whole) {
35
+ console.warn(
36
+ `${prefix} warn: ${name}: kept the whole file as written (formatting would change its meaning: ${result.whole})`,
37
+ );
38
+ }
39
+ for (const r of result.regions) {
40
+ const first = text.slice(r.start, r.end).split('\n')[0];
41
+ const excerpt = first.length > 40 ? first.slice(0, 40) + '…' : first;
42
+ console.warn(
43
+ `${prefix} warn: ${name}:${r.line}:${r.column}: kept \`${excerpt}\` as written (formatting would change its meaning: ${r.reason})`,
44
+ );
45
+ }
46
+ }
47
+
48
+ export const printers = {
49
+ 'julia-ast': {
50
+ print(path, options) {
51
+ const node = path.node;
52
+ if (node.type !== 'JuliaFile') return '';
53
+ // In a Markdown ```julia block, tabWidth/printWidth are the Markdown file's (Prettier's
54
+ // defaults, 2 and 80, unless set): use Julia's 4 and 92 there.
55
+ const opts = options.parentParser ? { ...options, ...defaultOptions } : options;
56
+ const result = formatParsed(node.parsed, opts);
57
+ if (options.juliaReport !== false) report(options.filepath, result, node.parsed.text);
58
+ return result.output;
59
+ },
60
+ getVisitorKeys: () => [],
61
+ },
62
+ };
63
+
64
+ export const options = {
65
+ juliaVerify: {
66
+ category: 'Julia',
67
+ type: 'boolean',
68
+ default: true,
69
+ description:
70
+ 'Check every format with JuliaSyntax and keep code whose meaning would change as written (disable only to debug the printer).',
71
+ },
72
+ juliaReport: {
73
+ category: 'Julia',
74
+ type: 'boolean',
75
+ default: true,
76
+ description: 'Print a warning for each region kept as written by the safety check.',
77
+ },
78
+ };
79
+
80
+ export const defaultOptions = {
81
+ tabWidth: 4,
82
+ printWidth: 92,
83
+ };
84
+
85
+ export const juliaSyntax = { julia: manifest.versions.julia, sha256: manifest.sha256 };
86
+
87
+ export default { languages, parsers, printers, options, defaultOptions };
@@ -0,0 +1,21 @@
1
+ # Vendored parser layer
2
+
3
+ `wasm-host.js`, `green-tree.js`, `positions.js` and `flags.js` here, and `../../wasm/`
4
+ (`parser.wasm`, `manifest.json`, `LICENSES/`), plus `../../scripts/parser/` (the artifact's
5
+ build inputs), are copied unmodified from
6
+ [eslint-plugin-julia](https://github.com/pankgeorg/eslint-plugin-julia) at commit `7c11a07`.
7
+ For v0.2.0, `../../wasm/` and `../../scripts/parser/` were refreshed with the parser rebuilt on
8
+ WasmCodegen main `98cad1f`: the same bytes as eslint-plugin-julia v0.2.0. The four JavaScript
9
+ files are unchanged; eslint-plugin-julia has since reformatted its copies with Prettier, so
10
+ `check-vendored.mjs` reports them as differing in formatting only.
11
+
12
+ Vendored rather than depended on: that package doesn't export its parser layer, has
13
+ `eslint` as a peer dependency, and a git dependency would fetch the whole ESLint plugin on
14
+ every install. `node scripts/check-vendored.mjs PATH/TO/eslint-plugin-julia` reports any drift.
15
+
16
+ `../tree.js` (ours) builds the full tree, trivia included, from the same `readWasm` +
17
+ `placeGreen` + `positions`.
18
+
19
+ For speed, `../tree.js` maps byte offsets to UTF-16 itself (an identity map for ASCII files,
20
+ one `charCodeAt` pass otherwise) instead of calling the vendored `positions`; the result is
21
+ the same table (checked byte for byte on 173 non-ASCII corpus files).
@@ -0,0 +1,19 @@
1
+ // These meanings are pinned to the manifest's JuliaSyntax grammar. Never interpret
2
+ // overloaded bits 8/9 without checking the kind.
3
+ export const isInfixCall = n => ['call', 'dotcall'].includes(n.kind) && n.interior && (n.flags & 24) === 8;
4
+ export const isPrefixCall = n => n.kind === 'call' && n.interior && (n.flags & 24) === 0;
5
+ export const isPrefixOperatorCall = n => n.kind === 'call' && n.interior && (n.flags & 24) === 16;
6
+ export const isMutableStruct = n => n.kind === 'struct' && n.interior && Boolean(n.flags & 256);
7
+ export const isTripleString = n => ['string', 'cmdstring'].includes(n.kind) && n.interior && Boolean(n.flags & 256);
8
+ export const isShortFunction = n => n.kind === 'function' && n.interior && Boolean(n.flags & 256);
9
+ export const hasTrailingComma = n => ['tuple', 'call', 'dotcall', 'curly', 'ref', 'vect', 'braces', 'parameters'].includes(n.kind) && n.interior && Boolean(n.flags & 512);
10
+ export const semanticChildren = n => n.children;
11
+ export const getOperatorToken = n => isInfixCall(n) ? n.children[1] : isPrefixOperatorCall(n) ? n.children[0] : undefined;
12
+ export function isInsideMacro(n, source) {
13
+ for (let p = n; p; p = source.getParent(p)) if (p.kind === 'macrocall') return true;
14
+ return false;
15
+ }
16
+ export function isQuoted(n, source) {
17
+ for (let p = n; p; p = source.getParent(p)) if (['quote', 'inert'].includes(p.kind)) return true;
18
+ return false;
19
+ }
@@ -0,0 +1,31 @@
1
+ // Postorder placement ported from proto/parser.mjs and topiary-julia/src/jlparse.rs.
2
+ // Place ALL leaves, including nonzero TOMBSTONEs, before removing any trivia.
3
+ export function placeGreen(raw, byteLength) {
4
+ const nodes = [], stack = [];
5
+ let cursor = 0;
6
+ for (let i = 0; i < raw.length; i++) {
7
+ const o = raw[i], interior = Boolean(o.class & 1), children = [];
8
+ if (!Number.isInteger(o.span) || o.span < 0 || !Number.isInteger(o.nodespan) || o.nodespan < 0) {
9
+ throw new Error(`Invalid green node dimensions at ${i}`);
10
+ }
11
+ let start = cursor;
12
+ if (interior) {
13
+ const first = i - o.nodespan;
14
+ if (first < 0) throw new Error(`Invalid green subtree at ${i}`);
15
+ while (stack.length && stack.at(-1) >= first) children.push(stack.pop());
16
+ children.reverse();
17
+ if (children.length) {
18
+ const firstChild = nodes[children[0]];
19
+ const subtreeStart = children[0] - (firstChild.interior ? firstChild.nodespan : 0);
20
+ if (subtreeStart !== first) throw new Error(`Misaligned green subtree at ${i}`);
21
+ start = firstChild.start;
22
+ } else cursor += o.span;
23
+ } else cursor += o.span;
24
+ if (cursor > byteLength || cursor - start !== o.span) throw new Error(`Invalid green span at ${i}`);
25
+ nodes.push({ ...o, interior, start, end: cursor, children });
26
+ stack.push(i);
27
+ }
28
+ if (cursor !== byteLength) throw new Error(`Tree covers ${cursor} bytes; input has ${byteLength}`);
29
+ const roots = stack.filter(i => nodes[i].interior || nodes[i].start !== nodes[i].end);
30
+ return { nodes, roots };
31
+ }
@@ -0,0 +1,27 @@
1
+ // Ported from the investigation prototype. All public offsets use UTF-16.
2
+ const encoder = new TextEncoder();
3
+ export function positions(text, byteLength = encoder.encode(text).length) {
4
+ const byteToIndex = new Uint32Array(byteLength + 1);
5
+ let byte = 0, index = 0;
6
+ for (const char of text) {
7
+ const cp = char.codePointAt(0);
8
+ const width = cp <= 0x7f ? 1 : cp <= 0x7ff ? 2 : cp <= 0xffff ? 3 : 4;
9
+ byteToIndex.fill(index, byte, byte + width);
10
+ byte += width;
11
+ index += char.length;
12
+ byteToIndex[byte] = index;
13
+ }
14
+ const starts = [0];
15
+ for (const match of text.matchAll(/\r\n|[\r\n]/gu)) starts.push(match.index + match[0].length);
16
+ function loc(index) {
17
+ let lo = 0, hi = starts.length;
18
+ while (lo + 1 < hi) {
19
+ const mid = (lo + hi) >>> 1;
20
+ if (starts[mid] <= index) lo = mid; else hi = mid;
21
+ }
22
+ return { line: lo + 1, column: index - starts[lo] };
23
+ }
24
+ const at = b => byteToIndex[Math.max(0, Math.min(byteLength, b))];
25
+ return { byteToIndex, at, loc };
26
+ }
27
+
@@ -0,0 +1,60 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+
4
+ export const manifest = JSON.parse(readFileSync(new URL('../../wasm/manifest.json', import.meta.url), 'utf8'));
5
+ const bytes = readFileSync(new URL('../../wasm/parser.wasm', import.meta.url));
6
+ if (createHash('sha256').update(bytes).digest('hex') !== manifest.sha256) {
7
+ throw new Error('Julia parser artifact hash differs from wasm/manifest.json');
8
+ }
9
+ const module = new WebAssembly.Module(bytes);
10
+ const encoder = new TextEncoder(), decoder = new TextDecoder();
11
+
12
+ export class ParserTrapError extends Error {
13
+ constructor(cause) {
14
+ super(`JuliaSyntax Wasm trap (Julia ${manifest.versions.julia}, sha256 ${manifest.sha256}): ${cause.message}`, { cause });
15
+ this.name = 'ParserTrapError';
16
+ }
17
+ }
18
+
19
+ // One synchronous instance per isolate. The factory is injectable for trap tests.
20
+ export function createWasmHost(instantiate = () => new WebAssembly.Instance(module, {})) {
21
+ let instance, busy = false;
22
+ const names = new Map();
23
+ return function readWasm(text) {
24
+ if (busy) throw new Error('Julia parser adapter is not reentrant');
25
+ busy = true;
26
+ try {
27
+ instance ??= instantiate();
28
+ const e = instance.exports;
29
+ const string = (len, byte) => decoder.decode(Uint8Array.from({ length: len }, (_, i) => byte(i + 1)));
30
+ const name = kind => {
31
+ if (!names.has(kind)) names.set(kind, string(e.kind_name_len(kind), j => e.kind_name_byte(kind, j)));
32
+ return names.get(kind);
33
+ };
34
+ const source = encoder.encode(text);
35
+ e.src_resize(source.length);
36
+ for (let i = 0; i < source.length; i += 4) {
37
+ e.src_set4(i + 1, source[i] | (source[i + 1] << 8) | (source[i + 2] << 16) | (source[i + 3] << 24));
38
+ }
39
+ const count = e.parse_src(1);
40
+ if (!Number.isInteger(count) || count < 0) throw new Error('Invalid Julia parser output count');
41
+ // Copy every result and diagnostic before another file can reuse the instance.
42
+ const raw = Array.from({ length: count }, (_, i) => {
43
+ const k = i + 1, kindId = e.out_kind(k), nodespan = e.out_nodespan(k), cls = e.out_class(k);
44
+ return { kindId, kind: name(kindId), span: e.out_span(k), nodespan,
45
+ class: cls, flags: e.out_flags(k), ...(!(cls & 1) && { originalKind: name(nodespan) }) };
46
+ });
47
+ const diagnostics = Array.from({ length: e.ndiag() }, (_, i) => {
48
+ const k = i + 1;
49
+ return { first: e.diag_first(k), last: e.diag_last(k), level: e.diag_level(k),
50
+ message: string(e.diag_msg_len(k), j => e.diag_msg_byte(k, j)) };
51
+ });
52
+ return { raw, diagnostics, bytes: source.length };
53
+ } catch (error) {
54
+ if (!(error instanceof WebAssembly.RuntimeError)) throw error;
55
+ instance = undefined; // A trapped instance's mutable stream is never reused.
56
+ throw new ParserTrapError(error);
57
+ } finally { busy = false; }
58
+ };
59
+ }
60
+ export const readWasm = createWasmHost();