biome-plugin-padding 0.0.0-stage → 0.1.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/README.md +50 -2
- package/README.ru.md +57 -0
- package/package.json +40 -4
- package/src/generate-padding.mjs +183 -0
- package/src/padding.grit.template +335 -0
package/README.md
CHANGED
|
@@ -1,3 +1,51 @@
|
|
|
1
|
-
#
|
|
1
|
+
# biome-plugin-padding
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Русский](README.ru.md) · [GitHub repository](https://github.com/Alexandrsv/biome-plugin-padding)
|
|
4
|
+
|
|
5
|
+
Configure blank lines between adjacent JavaScript and TypeScript statements, for example before a `return` or after a group of imports. The CLI reads rules from `biome.jsonc` and generates a GritQL plugin that Biome uses to report and fix spacing.
|
|
6
|
+
|
|
7
|
+
The generator requires Node.js 20 or later. The plugin has been tested with Biome 2.5.4 and 2.6.9.
|
|
8
|
+
|
|
9
|
+
## Installation and setup
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install --save-dev @biomejs/biome@^2.5.4 biome-plugin-padding
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Add the `biome-padding` comment and plugin path to the `biome.jsonc` at your project root. If you already have a `plugins` array, append the path to it.
|
|
16
|
+
|
|
17
|
+
```jsonc
|
|
18
|
+
{
|
|
19
|
+
/* biome-padding
|
|
20
|
+
[
|
|
21
|
+
{ "blankLine": "always", "prev": "import", "next": "*" },
|
|
22
|
+
{ "blankLine": "any", "prev": "import", "next": "import" },
|
|
23
|
+
{ "blankLine": "always", "prev": "*", "next": "return" },
|
|
24
|
+
{ "blankLine": "never", "prev": ["const", "let"], "next": ["const", "let"] }
|
|
25
|
+
]
|
|
26
|
+
*/
|
|
27
|
+
"plugins": ["./.biome/padding-line-between-statements.grit"]
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
From the directory containing `biome.jsonc`, generate the plugin and apply fixes. Replace `./src` with the path you want to check.
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
npx biome-padding generate
|
|
35
|
+
npx biome check --write ./src
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The example requires a blank line before a `return` that follows another statement, separates the last import from the next statement, and removes blank lines between adjacent `const` or `let` declarations.
|
|
39
|
+
|
|
40
|
+
Commit `.biome/padding-line-between-statements.grit` alongside the config so your IDE and CI can load it. Regenerate it after editing the rules. Use `npx biome check ./src` to check without writing changes, or `npx biome lint --write ./src` to apply lint fixes without running the formatter.
|
|
41
|
+
|
|
42
|
+
## Rule syntax
|
|
43
|
+
|
|
44
|
+
Each rule specifies two adjacent statements in the same scope. The last matching rule wins. In the example, the second rule overrides the first for consecutive imports.
|
|
45
|
+
|
|
46
|
+
- `prev` and `next` accept a category, an array of categories, or `"*"` to match any statement.
|
|
47
|
+
- `blankLine: "always"` requires at least one blank line. `"never"` removes blank lines. `"any"` cancels an earlier requirement for the pair.
|
|
48
|
+
- Categories include `import`, `return`, `const`, `let`, `if`, `function`, `interface`, `type`, `cjs-import`, and `cjs-export`. See the [full selector list](README.ru.md#правила).
|
|
49
|
+
- For supported categories, `singleline-` and `multiline-` narrow the match. For example, `multiline-return` matches only returns that span multiple lines. Format the code first if formatting may change which statements match.
|
|
50
|
+
|
|
51
|
+
The plugin supports JS, JSX, TS, and TSX. It preserves comments and keeps JSDoc with its declaration.
|
package/README.ru.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# biome-plugin-padding
|
|
2
|
+
|
|
3
|
+
[English](README.md) · [Репозиторий на GitHub](https://github.com/Alexandrsv/biome-plugin-padding)
|
|
4
|
+
|
|
5
|
+
Настраиваемые пустые строки между соседними инструкциями JavaScript и TypeScript. Генератор читает правила из `biome.jsonc` и создаёт GritQL-плагин. Biome показывает нарушения и применяет безопасные исправления в `biome check --write` и `biome lint --write`.
|
|
6
|
+
|
|
7
|
+
Для генератора нужен Node.js 20 или новее. Плагин проверен на Biome 2.5.4 и 2.6.9.
|
|
8
|
+
|
|
9
|
+
## Установка
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install --save-dev @biomejs/biome@^2.5.4 biome-plugin-padding
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Добавьте в `biome.jsonc` комментарий `biome-padding` и путь к генерируемому файлу. Если массив `plugins` уже есть, добавьте путь в него.
|
|
16
|
+
|
|
17
|
+
```jsonc
|
|
18
|
+
{
|
|
19
|
+
/* biome-padding
|
|
20
|
+
[
|
|
21
|
+
{ "blankLine": "always", "prev": "import", "next": "*" },
|
|
22
|
+
{ "blankLine": "any", "prev": "import", "next": "import" },
|
|
23
|
+
{ "blankLine": "always", "prev": "*", "next": "return" },
|
|
24
|
+
{ "blankLine": "never", "prev": ["const", "let"], "next": ["const", "let"] }
|
|
25
|
+
]
|
|
26
|
+
*/
|
|
27
|
+
"plugins": ["./.biome/padding-line-between-statements.grit"]
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Запустите из каталога с `biome.jsonc`.
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
npx biome-padding generate
|
|
35
|
+
npx biome check --write ./src
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Добавьте `.biome/padding-line-between-statements.grit` в Git вместе с конфигурацией. После изменения правил снова запустите генератор. Biome может читать готовый файл в IDE и CI.
|
|
39
|
+
|
|
40
|
+
## Правила
|
|
41
|
+
|
|
42
|
+
`prev` и `next` принимают категорию, массив категорий или `"*"`. Для каждой пары действует последнее совпавшее правило. `always` требует одну или больше пустых строк, `never` удаляет пустые строки, а `any` отменяет требования предыдущих правил для этой пары.
|
|
43
|
+
|
|
44
|
+
- Для инструкций доступны `block`, `block-like`, `break`, `case`, `class`, `const`, `continue`, `debugger`, `default`, `directive`, `do`, `empty`, `enum`, `export`, `expression`, `for`, `function`, `function-overload`, `if`, `iife`, `import`, `interface`, `let`, `return`, `switch`, `throw`, `try`, `ts-method`, `type`, `using`, `var`, `while`, `with`.
|
|
45
|
+
- Для CommonJS доступны `cjs-import`, `cjs-export`, `require` и `exports`.
|
|
46
|
+
- Префиксы `singleline-` и `multiline-` доступны для `block-like`, `expression`, `return`, `export`, `var`, `let`, `const`, `using` и `type`.
|
|
47
|
+
|
|
48
|
+
Селекторы работают с соседями в одной области. Поддерживаются файлы JS, JSX, TS и TSX, блоки, списки веток `switch` и их тела, пространства имён TS и сигнатуры методов в типах. Комментарии сохраняются, а JSDoc остаётся рядом со своей декларацией. Селекторы в виде объектов `{ selector, lineMode }` оставлены за рамками этой версии. [Справочник ESLint Stylistic](https://eslint.style/rules/padding-line-between-statements)
|
|
49
|
+
|
|
50
|
+
`biome lint --write` меняет только интервалы, выбранные плагином. Для вставки между инструкциями в одной строке плагин использует первый видимый перенос файла. Если его нет, он использует `formatter.lineEnding` или `javascript.formatter.lineEnding` из `biome.jsonc`, прочитанный при генерации. По умолчанию используется LF.
|
|
51
|
+
|
|
52
|
+
При использовании `singleline-*` и `multiline-*` форматтер может сначала изменить категорию инструкции. Если исходный код ещё не отформатирован, запустите форматирование и затем примените правило.
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
npx biome format --write ./src
|
|
56
|
+
npx biome check --write ./src
|
|
57
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "biome-plugin-padding",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Configurable blank lines between JavaScript and TypeScript statements for Biome",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"test": "node test/padding.test.mjs",
|
|
7
|
+
"release": "npm publish . --access public",
|
|
8
|
+
"prepublishOnly": "npm test"
|
|
9
|
+
},
|
|
10
|
+
"license": "ISC",
|
|
11
|
+
"devDependencies": {
|
|
12
|
+
"@biomejs/biome": "2.6.9"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"jsonc-parser": "3.3.1"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"src/",
|
|
19
|
+
"README.ru.md"
|
|
20
|
+
],
|
|
21
|
+
"bin": {
|
|
22
|
+
"biome-padding": "src/generate-padding.mjs"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@biomejs/biome": "^2.5.4"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"biome",
|
|
32
|
+
"biome-plugin",
|
|
33
|
+
"padding-line-between-statements"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/Alexandrsv/biome-plugin-padding.git"
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { writeSync } from 'node:fs'
|
|
3
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { parse, printParseErrorCode, visit } from 'jsonc-parser'
|
|
5
|
+
|
|
6
|
+
const categoryPatterns = new Map([
|
|
7
|
+
['*', '_'],
|
|
8
|
+
['block', 'JsBlockStatement()'],
|
|
9
|
+
['block-like', 'blockLike()'],
|
|
10
|
+
['break', 'JsBreakStatement()'],
|
|
11
|
+
['case', 'JsCaseClause()'],
|
|
12
|
+
['cjs-export', 'commonJsExport()'],
|
|
13
|
+
['cjs-import', 'commonJsImport()'],
|
|
14
|
+
['class', 'JsClassDeclaration()'],
|
|
15
|
+
['const', 'JsVariableStatement() as $match where { $match <: r"(?s)^const\\b.*" }'],
|
|
16
|
+
['continue', 'JsContinueStatement()'],
|
|
17
|
+
['debugger', 'JsDebuggerStatement()'],
|
|
18
|
+
['default', 'JsDefaultClause()'],
|
|
19
|
+
['directive', 'JsDirective()'],
|
|
20
|
+
['do', 'JsDoWhileStatement()'],
|
|
21
|
+
['empty', 'JsEmptyStatement()'],
|
|
22
|
+
['enum', 'TsEnumDeclaration() as $match where { $match <: r"(?s)^enum\\b.*" }'],
|
|
23
|
+
['export', 'JsExport()'],
|
|
24
|
+
['exports', 'commonJsExportMember()'],
|
|
25
|
+
['expression', 'JsExpressionStatement()'],
|
|
26
|
+
['for', 'or { JsForStatement(), JsForInStatement(), JsForOfStatement() }'],
|
|
27
|
+
['function', 'JsFunctionDeclaration()'],
|
|
28
|
+
['function-overload', 'or { TsDeclareFunctionDeclaration(), TsDeclareStatement(declaration=TsDeclareFunctionDeclaration()) }'],
|
|
29
|
+
['if', 'JsIfStatement()'],
|
|
30
|
+
['iife', 'iifeStatement()'],
|
|
31
|
+
['import', 'JsImport()'],
|
|
32
|
+
['interface', 'TsInterfaceDeclaration()'],
|
|
33
|
+
['let', 'JsVariableStatement() as $match where { $match <: r"(?s)^let\\b.*" }'],
|
|
34
|
+
['require', 'requireDeclaration()'],
|
|
35
|
+
['return', 'JsReturnStatement()'],
|
|
36
|
+
['switch', 'JsSwitchStatement()'],
|
|
37
|
+
['throw', 'JsThrowStatement()'],
|
|
38
|
+
['try', 'or { JsTryStatement(), JsTryFinallyStatement() }'],
|
|
39
|
+
['ts-method', 'TsMethodSignatureTypeMember()'],
|
|
40
|
+
['type', 'TsTypeAliasDeclaration()'],
|
|
41
|
+
['using', 'JsVariableStatement() as $match where { $match <: r"(?s)^(?:await|using)\\b.*" }'],
|
|
42
|
+
['var', 'JsVariableStatement() as $match where { $match <: r"(?s)^var\\b.*" }'],
|
|
43
|
+
['while', 'JsWhileStatement()'],
|
|
44
|
+
['with', 'JsWithStatement()'],
|
|
45
|
+
])
|
|
46
|
+
|
|
47
|
+
const lineModeCategories = ['block-like', 'expression', 'return', 'export', 'var', 'let', 'const', 'using', 'type']
|
|
48
|
+
for (const category of lineModeCategories) {
|
|
49
|
+
const pattern = categoryPatterns.get(category)
|
|
50
|
+
const multiline = 'r"(?s).*[\\r\\n\\x{2028}\\x{2029}].*"'
|
|
51
|
+
categoryPatterns.set(`multiline-${category}`, `and { ${pattern}, $lineMatch where { $lineMatch <: ${multiline} } }`)
|
|
52
|
+
categoryPatterns.set(`singleline-${category}`, `and { ${pattern}, $lineMatch where { $lineMatch <: not ${multiline} } }`)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseJsonc(source, label) {
|
|
56
|
+
const errors = []
|
|
57
|
+
const value = parse(source, errors, { allowTrailingComma: true })
|
|
58
|
+
if (errors.length) {
|
|
59
|
+
throw new Error(`Invalid ${label}: ${printParseErrorCode(errors[0].error)}.`)
|
|
60
|
+
}
|
|
61
|
+
return value
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readRules(source) {
|
|
65
|
+
const marker = /^\/\*\s*biome-padding(?=\s|\[|\*\/)/u
|
|
66
|
+
const blocks = []
|
|
67
|
+
visit(source, {
|
|
68
|
+
onComment(offset, length) {
|
|
69
|
+
const comment = source.slice(offset, offset + length)
|
|
70
|
+
if (marker.test(comment)) blocks.push(comment.replace(marker, '').slice(0, -2))
|
|
71
|
+
},
|
|
72
|
+
})
|
|
73
|
+
if (blocks.length !== 1) {
|
|
74
|
+
throw new Error('Expected exactly one /* biome-padding … */ comment in biome.jsonc.')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const rules = parseJsonc(blocks[0], 'biome-padding JSONC')
|
|
78
|
+
if (!Array.isArray(rules)) throw new Error('The biome-padding comment must contain an array.')
|
|
79
|
+
|
|
80
|
+
return rules.map((rule, index) => {
|
|
81
|
+
const label = `Rule ${index + 1}`
|
|
82
|
+
if (rule === null || typeof rule !== 'object' || Array.isArray(rule)) {
|
|
83
|
+
throw new Error(`${label}: expected an object with blankLine, prev, and next.`)
|
|
84
|
+
}
|
|
85
|
+
const { blankLine, prev, next } = rule
|
|
86
|
+
if (Object.keys(rule).some(key => !['blankLine', 'prev', 'next'].includes(key))) {
|
|
87
|
+
throw new Error(`${label}: expected only blankLine, prev, and next.`)
|
|
88
|
+
}
|
|
89
|
+
if (!['always', 'never', 'any'].includes(blankLine)) {
|
|
90
|
+
throw new Error(`${label}.blankLine: expected "always", "never", or "any".`)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function selectors(value, field) {
|
|
94
|
+
const names = Array.isArray(value) ? value : [value]
|
|
95
|
+
if (!names.length) throw new Error(`${label}.${field}: expected at least one selector.`)
|
|
96
|
+
for (const name of names) {
|
|
97
|
+
if (!categoryPatterns.has(name)) {
|
|
98
|
+
throw new Error(`${label}.${field}: unknown selector ${JSON.stringify(name)}.`)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return names.includes('*') ? ['*'] : [...new Set(names)]
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return { blankLine, prev: selectors(prev, 'prev'), next: selectors(next, 'next') }
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function compileSelector(category, variable) {
|
|
109
|
+
return categoryPatterns.get(category).replaceAll('$match', `$${variable}Match`).replaceAll('$lineMatch', `$${variable}Line`)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function compilePolicy(rules) {
|
|
113
|
+
const branches = rules.toReversed().map(({ blankLine, prev, next }, ruleIndex) => {
|
|
114
|
+
const tests = [[prev, '$previous'], [next, '$current']].flatMap(([names, variable]) => {
|
|
115
|
+
if (names[0] === '*') return []
|
|
116
|
+
return `${variable} <: or { ${names.map((name, index) => compileSelector(name, `${variable.slice(1)}${ruleIndex}_${index}`)).join(', ')} }`
|
|
117
|
+
})
|
|
118
|
+
return `and { ${[...tests, `$policy = "${blankLine}"`].join(', ')} }`
|
|
119
|
+
})
|
|
120
|
+
return `or { ${[...branches, '$policy = "any"'].join(',\n ')} },`
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function compileTemplate(template, rules, lineEnding, maxSize) {
|
|
124
|
+
const candidates = new Set(rules.filter(rule => rule.blankLine !== 'any').flatMap(rule => rule.next))
|
|
125
|
+
const horizontal = String.raw`(?:[^\S\r\n\x{2028}\x{2029}]|\x{feff})`
|
|
126
|
+
const newline = String.raw`(?:\r?\n|\x{2028}|\x{2029})`
|
|
127
|
+
const space = `(?:${horizontal}|${newline})`
|
|
128
|
+
const lineComment = String.raw`//[^\r\n\x{2028}\x{2029}]*`
|
|
129
|
+
const blockEnd = String.raw`(?:[^*]|\*+[^*/])*\*+/`
|
|
130
|
+
const blockComment = String.raw`/\*` + blockEnd
|
|
131
|
+
const ordinaryBlock = String.raw`/\*(?:\*/|[^*]` + blockEnd + ')'
|
|
132
|
+
const comment = `(?:${lineComment}|${blockComment})`
|
|
133
|
+
const trivia = `(?:${space}|${comment})`
|
|
134
|
+
const trailing = `(?:${horizontal}*(?:${lineComment}|${ordinaryBlock}))*`
|
|
135
|
+
const line = `${horizontal}*${newline}`
|
|
136
|
+
const blankTail = `(?:${line})+`
|
|
137
|
+
const replacements = {
|
|
138
|
+
POLICY: compilePolicy(rules),
|
|
139
|
+
ASCII_CHUNKS: 'x'.repeat(Math.ceil(maxSize / 100000)),
|
|
140
|
+
UNICODE_CHUNKS: 'x'.repeat(Math.ceil(maxSize / 4000)),
|
|
141
|
+
CANDIDATE: candidates.has('*') ? '$candidate'
|
|
142
|
+
: `or { ${[...candidates].map((name, index) => compileSelector(name, `candidate${index}`)).join(', ')} }`,
|
|
143
|
+
FALLBACK_NEWLINE: lineEnding === 'crlf' ? '\r\\n' : '\\n',
|
|
144
|
+
TRIVIA: String.raw`(?:${trivia}|\r)`,
|
|
145
|
+
BLOCK_START: String.raw`(?s)^\{${trivia}*(.*)\}$`,
|
|
146
|
+
FILE_START: String.raw`(?s)^\x{feff}?(?:#![^\r\n]*${newline})?${trivia}*(.*)$`,
|
|
147
|
+
LEADING_SEMICOLON: `(?s)^.*?((?:${line})+${horizontal}*);$`,
|
|
148
|
+
BLANK: `^(?:${space}*${comment})*${line}${blankTail}${trivia}*$`,
|
|
149
|
+
TRIVIA_PART: `(?s)^(${space}*)(${comment}|$)(.*)$`,
|
|
150
|
+
COLLAPSE_SPACE: `^(${line})${blankTail}(${horizontal}*)$`,
|
|
151
|
+
AFTER_TRAILING_LINE: `^${trailing}(${horizontal}*(${newline}))${trivia}*$`,
|
|
152
|
+
AFTER_TRAILING_INLINE: `^${trailing}(${horizontal}*)${trivia}*$`,
|
|
153
|
+
}
|
|
154
|
+
return template.replace(/__([A-Z_]+)__/gu, (_, name) => replacements[name])
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function generate() {
|
|
158
|
+
const config = await readFile('biome.jsonc', 'utf8')
|
|
159
|
+
const template = await readFile(new URL('./padding.grit.template', import.meta.url), 'utf8')
|
|
160
|
+
const rules = readRules(config)
|
|
161
|
+
const { javascript, formatter, files } = parseJsonc(config, 'biome.jsonc')
|
|
162
|
+
const maxSize = files?.maxSize ?? 1024 * 1024
|
|
163
|
+
if (!Number.isSafeInteger(maxSize) || maxSize < 1 || maxSize > 0xFFFFFFFF) {
|
|
164
|
+
throw new Error('files.maxSize must be a positive 32-bit integer.')
|
|
165
|
+
}
|
|
166
|
+
const lineEnding = javascript?.formatter?.lineEnding ?? formatter?.lineEnding
|
|
167
|
+
const source = '// Generated by biome-padding. Edit the biome-padding comment in biome.jsonc.\n'
|
|
168
|
+
+ (rules.some(rule => rule.blankLine !== 'any')
|
|
169
|
+
? compileTemplate(template, rules, lineEnding, maxSize)
|
|
170
|
+
: 'file(body=$root) where { false }\n')
|
|
171
|
+
await mkdir('.biome', { recursive: true })
|
|
172
|
+
await writeFile('.biome/padding-line-between-statements.grit', source)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
if (process.argv.length !== 3 || process.argv[2] !== 'generate') {
|
|
177
|
+
throw new Error('Usage: biome-padding generate')
|
|
178
|
+
}
|
|
179
|
+
await generate()
|
|
180
|
+
} catch (error) {
|
|
181
|
+
writeSync(2, `biome-padding: ${error.message}\n`)
|
|
182
|
+
process.exitCode = 1
|
|
183
|
+
}
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
pattern candidate() {
|
|
2
|
+
__CANDIDATE__
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
pattern firstInitializer($value) {
|
|
6
|
+
JsVariableStatement(declaration=JsVariableDeclaration(
|
|
7
|
+
declarators=[JsVariableDeclarator(initializer=JsInitializerClause(expression=$value)), ...]
|
|
8
|
+
))
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
pattern commonJsImport() {
|
|
12
|
+
firstInitializer(value=$value) where { $value <: r"(?s)^require\(.*$" }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
pattern requireCall() {
|
|
16
|
+
or {
|
|
17
|
+
JsCallExpression(callee=JsIdentifierExpression() as $callee) where { $callee <: r"^require$" },
|
|
18
|
+
JsStaticMemberExpression(object=requireCall()),
|
|
19
|
+
JsComputedMemberExpression(object=requireCall()),
|
|
20
|
+
JsParenthesizedExpression(expression=requireCall())
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
pattern requireDeclaration() {
|
|
25
|
+
firstInitializer(value=requireCall())
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
pattern commonJsExport() {
|
|
29
|
+
JsExpressionStatement(expression=JsAssignmentExpression(left=$left)) where {
|
|
30
|
+
$left <: r"(?s)^(?:module\s*\.\s*)?exports(?:\s*(?:\.|\[).*)?$"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
pattern commonJsExportMember() {
|
|
35
|
+
JsExpressionStatement(expression=JsAssignmentExpression(left=$left)) where {
|
|
36
|
+
$left <: r"(?s)^(?:exports\s*(?:\.|\[).*|module\s*\.\s*exports(?:\s*(?:\.|\[).*)?)$"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
pattern iifeCallee() {
|
|
41
|
+
or {
|
|
42
|
+
JsFunctionExpression(),
|
|
43
|
+
JsArrowFunctionExpression(),
|
|
44
|
+
JsParenthesizedExpression(expression=iifeCallee()),
|
|
45
|
+
JsSequenceExpression(right=iifeCallee())
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
pattern iifeCall() {
|
|
50
|
+
or {
|
|
51
|
+
JsCallExpression(callee=iifeCallee()),
|
|
52
|
+
JsParenthesizedExpression(expression=iifeCall())
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
pattern iifeStatement() {
|
|
57
|
+
JsExpressionStatement(expression=or {
|
|
58
|
+
iifeCall(),
|
|
59
|
+
JsUnaryExpression(argument=iifeCall())
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
pattern blockEndingExpression() {
|
|
64
|
+
or {
|
|
65
|
+
JsFunctionExpression(),
|
|
66
|
+
JsArrowFunctionExpression(body=or { JsFunctionBody(), blockEndingExpression() }),
|
|
67
|
+
JsAssignmentExpression(right=blockEndingExpression()),
|
|
68
|
+
JsSequenceExpression(right=blockEndingExpression()),
|
|
69
|
+
JsConditionalExpression(alternate=blockEndingExpression()),
|
|
70
|
+
JsBinaryExpression(right=blockEndingExpression()),
|
|
71
|
+
JsLogicalExpression(right=blockEndingExpression()),
|
|
72
|
+
JsUnaryExpression(argument=blockEndingExpression()),
|
|
73
|
+
JsAwaitExpression(argument=blockEndingExpression()),
|
|
74
|
+
JsYieldExpression(argument=blockEndingExpression())
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
pattern blockEndingDeclaration() {
|
|
79
|
+
JsVariableDeclaration(declarators=[
|
|
80
|
+
..., JsVariableDeclarator(initializer=JsInitializerClause(expression=blockEndingExpression()))
|
|
81
|
+
])
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
pattern blockLike() {
|
|
85
|
+
or {
|
|
86
|
+
JsBlockStatement(),
|
|
87
|
+
JsFunctionDeclaration(),
|
|
88
|
+
JsSwitchStatement(),
|
|
89
|
+
JsTryStatement(),
|
|
90
|
+
JsTryFinallyStatement(),
|
|
91
|
+
JsDoWhileStatement(body=JsBlockStatement()),
|
|
92
|
+
JsIfStatement(else_clause=JsElseClause(alternate=blockLike())),
|
|
93
|
+
JsIfStatement(consequent=blockLike()) as $if where { $if <: not JsIfStatement(else_clause=JsElseClause()) },
|
|
94
|
+
JsForStatement(body=blockLike()),
|
|
95
|
+
JsForInStatement(body=blockLike()),
|
|
96
|
+
JsForOfStatement(body=blockLike()),
|
|
97
|
+
JsWhileStatement(body=blockLike()),
|
|
98
|
+
JsWithStatement(body=blockLike()),
|
|
99
|
+
JsLabeledStatement(body=blockLike()),
|
|
100
|
+
JsVariableStatement(declaration=blockEndingDeclaration()),
|
|
101
|
+
JsExpressionStatement(expression=blockEndingExpression()),
|
|
102
|
+
JsReturnStatement(argument=blockEndingExpression()),
|
|
103
|
+
JsThrowStatement(argument=blockEndingExpression()),
|
|
104
|
+
JsExport(export_clause=or {
|
|
105
|
+
JsFunctionDeclaration(),
|
|
106
|
+
JsVariableDeclarationClause(declaration=blockEndingDeclaration()),
|
|
107
|
+
JsExportDefaultDeclarationClause(declaration=JsFunctionExportDefaultDeclaration()),
|
|
108
|
+
JsExportDefaultExpressionClause(expression=blockEndingExpression())
|
|
109
|
+
}),
|
|
110
|
+
iifeStatement()
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
pattern collapsePart($remainingTrivia, $result) {
|
|
115
|
+
$piece where {
|
|
116
|
+
$remainingTrivia <: r"__TRIVIA_PART__"($spaces, $comment, $tail),
|
|
117
|
+
or {
|
|
118
|
+
and {
|
|
119
|
+
$spaces <: r"__COLLAPSE_SPACE__"($line, $indent),
|
|
120
|
+
$part = `$line$indent`
|
|
121
|
+
},
|
|
122
|
+
$part = $spaces
|
|
123
|
+
},
|
|
124
|
+
$prefix = $result,
|
|
125
|
+
$result = `$prefix$part$comment`,
|
|
126
|
+
$remainingTrivia = $tail
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
predicate collapseGap($gap, $replacement) {
|
|
131
|
+
// A slash per comment is enough iterations, including the final whitespace.
|
|
132
|
+
$parts = split(string=$gap, separator="/"),
|
|
133
|
+
$rest = $gap,
|
|
134
|
+
$result = "",
|
|
135
|
+
$parts <: some collapsePart(remainingTrivia=$rest, result=$result),
|
|
136
|
+
$replacement = $result
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Keep regex repetitions within the engine size limit, even for long literals.
|
|
140
|
+
pattern skipChunk($remaining, $characters, $ascii) {
|
|
141
|
+
$chunk where {
|
|
142
|
+
$count = $characters,
|
|
143
|
+
$countText = text(string=$count),
|
|
144
|
+
$asciiOnly = $ascii,
|
|
145
|
+
or {
|
|
146
|
+
and {
|
|
147
|
+
$asciiOnly == "yes",
|
|
148
|
+
or {
|
|
149
|
+
$countText <: r"^[0-9]{1,5}$",
|
|
150
|
+
and {
|
|
151
|
+
$remaining <: r"(?s)^[\x00-\x7F]{100000}(.*)$"($tail),
|
|
152
|
+
$left = $count - 100000,
|
|
153
|
+
$remaining = $tail,
|
|
154
|
+
$characters = $left
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
and {
|
|
159
|
+
$asciiOnly == "no",
|
|
160
|
+
or {
|
|
161
|
+
$countText <: r"^(?:[0-9]{1,3}|[0-3][0-9]{3})$",
|
|
162
|
+
and {
|
|
163
|
+
$remaining <: r"(?s)^.{4000}(.*)$"($tail),
|
|
164
|
+
$left = $count - 4000,
|
|
165
|
+
$remaining = $tail,
|
|
166
|
+
$characters = $left
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
predicate afterStatement($input, $statement, $remainder) {
|
|
175
|
+
$statementText = text(string=$statement),
|
|
176
|
+
$byteLength = length(target=$statementText),
|
|
177
|
+
$lengthText = text(string=$byteLength),
|
|
178
|
+
$source = $input,
|
|
179
|
+
or {
|
|
180
|
+
and {
|
|
181
|
+
$lengthText <: r"^[0-9]{5,}$",
|
|
182
|
+
$statementText <: r"^[\x00-\x7F]*$",
|
|
183
|
+
$size = $byteLength,
|
|
184
|
+
$chunks = split(string="__ASCII_CHUNKS__", separator="x"),
|
|
185
|
+
$chunks <: some skipChunk(remaining=$source, characters=$size, ascii="yes"),
|
|
186
|
+
$remainingText = text(string=$size),
|
|
187
|
+
$remainingText <: r"^[0-9]{1,5}$",
|
|
188
|
+
$source <: r`(?s)^[\\x00-\\x7F]{$size}(.*)$`($suffix)
|
|
189
|
+
},
|
|
190
|
+
and {
|
|
191
|
+
$chars = split(string=$statementText, separator=""),
|
|
192
|
+
$charCount = length(target=$chars),
|
|
193
|
+
$size = $charCount - 2,
|
|
194
|
+
$sizeText = text(string=$size),
|
|
195
|
+
or {
|
|
196
|
+
$sizeText <: r"^[0-9]{1,4}$",
|
|
197
|
+
and {
|
|
198
|
+
$chunks = split(string="__UNICODE_CHUNKS__", separator="x"),
|
|
199
|
+
$chunks <: some skipChunk(remaining=$source, characters=$size, ascii="no")
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
$remainingText = text(string=$size),
|
|
203
|
+
$remainingText <: r"^[0-9]{1,4}$",
|
|
204
|
+
$source <: r`(?s)^.{$size}(.*)$`($suffix)
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
$remainder = $suffix
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Move the source cursor in AST order. Captures retain the original ranges, so
|
|
211
|
+
// identical statements in the same list still produce distinct edits.
|
|
212
|
+
pattern step($previous, $remaining, $index, $ending) {
|
|
213
|
+
$current where {
|
|
214
|
+
$position = $index,
|
|
215
|
+
$fileNewline = $ending,
|
|
216
|
+
or {
|
|
217
|
+
$position == 0,
|
|
218
|
+
and {
|
|
219
|
+
afterStatement(input=$remaining, statement=$previous, remainder=$afterPrevious),
|
|
220
|
+
$afterPrevious <: r"(?s)^(__TRIVIA__*)(.*)$"($physicalGap, $tail),
|
|
221
|
+
// A semicolon starting the next line may belong to the previous CST node.
|
|
222
|
+
or {
|
|
223
|
+
and {
|
|
224
|
+
$physicalGap <: r"^[^\r\n\x{2028}\x{2029}]*$",
|
|
225
|
+
$previous <: r"__LEADING_SEMICOLON__"($beforeSemicolon),
|
|
226
|
+
$gap = $beforeSemicolon
|
|
227
|
+
},
|
|
228
|
+
$gap = $physicalGap
|
|
229
|
+
},
|
|
230
|
+
__POLICY__
|
|
231
|
+
or {
|
|
232
|
+
and {
|
|
233
|
+
$policy == "always",
|
|
234
|
+
$gap <: not r"__BLANK__",
|
|
235
|
+
or {
|
|
236
|
+
and {
|
|
237
|
+
$gap <: r"__AFTER_TRAILING_LINE__"($insertion, $newline),
|
|
238
|
+
$insertion => `$insertion$newline`
|
|
239
|
+
},
|
|
240
|
+
and {
|
|
241
|
+
$gap <: r"__AFTER_TRAILING_INLINE__"($inline),
|
|
242
|
+
$inline => `$fileNewline$fileNewline$inline`
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
register_diagnostic(span=$current, message="Expected blank line before this statement.", fix_kind="safe")
|
|
246
|
+
},
|
|
247
|
+
and {
|
|
248
|
+
$policy == "never",
|
|
249
|
+
$gap <: r"__BLANK__",
|
|
250
|
+
collapseGap(gap=$gap, replacement=$replacement),
|
|
251
|
+
$gap => $replacement,
|
|
252
|
+
register_diagnostic(span=$current, message="Unexpected blank line before this statement.", fix_kind="safe")
|
|
253
|
+
},
|
|
254
|
+
true
|
|
255
|
+
},
|
|
256
|
+
$remaining = $tail
|
|
257
|
+
}
|
|
258
|
+
},
|
|
259
|
+
$previous = $current,
|
|
260
|
+
$next = $position + 1,
|
|
261
|
+
$index = $next
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
predicate scan($body, $lineEnding) {
|
|
266
|
+
$body <: some candidate(),
|
|
267
|
+
$i = 0,
|
|
268
|
+
$rest = $body,
|
|
269
|
+
$prev = $body,
|
|
270
|
+
$body <: some step(previous=$prev, remaining=$rest, index=$i, ending=$lineEnding)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
predicate scanPrologue($container, $directives, $body, $lineEnding) {
|
|
274
|
+
or {
|
|
275
|
+
and {
|
|
276
|
+
$directives <: [],
|
|
277
|
+
or { scan(body=$body, lineEnding=$lineEnding), true }
|
|
278
|
+
},
|
|
279
|
+
and {
|
|
280
|
+
or { $directives <: some candidate(), $body <: some candidate() },
|
|
281
|
+
$container <: or {
|
|
282
|
+
r"__BLOCK_START__"($start),
|
|
283
|
+
r"__FILE_START__"($start)
|
|
284
|
+
},
|
|
285
|
+
$i = 0,
|
|
286
|
+
$rest = $start,
|
|
287
|
+
$prev = $body,
|
|
288
|
+
$directives <: some step(previous=$prev, remaining=$rest, index=$i, ending=$lineEnding),
|
|
289
|
+
or {
|
|
290
|
+
$body <: some step(previous=$prev, remaining=$rest, index=$i, ending=$lineEnding),
|
|
291
|
+
true
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
pattern nested($eol) {
|
|
298
|
+
or {
|
|
299
|
+
JsFunctionBody(directives=$directives, statements=$body) as $block where {
|
|
300
|
+
scanPrologue(container=$block, directives=$directives, body=$body, lineEnding=$eol)
|
|
301
|
+
},
|
|
302
|
+
or {
|
|
303
|
+
JsBlockStatement(statements=$body),
|
|
304
|
+
JsStaticInitializationBlockClassMember(statements=$body),
|
|
305
|
+
JsCaseClause(consequent=$body),
|
|
306
|
+
JsDefaultClause(consequent=$body),
|
|
307
|
+
JsSwitchStatement(cases=$body),
|
|
308
|
+
TsModuleBlock(items=$body),
|
|
309
|
+
TsInterfaceDeclaration(members=$body),
|
|
310
|
+
TsObjectType(members=$body)
|
|
311
|
+
} where { scan(body=$body, lineEnding=$eol) }
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
file(body=$root) where {
|
|
316
|
+
or {
|
|
317
|
+
and {
|
|
318
|
+
$root <: r"(?s)^.*?(\r?\n|\x{2028}|\x{2029}).*$"($firstNewline),
|
|
319
|
+
$eol = text(string=$firstNewline)
|
|
320
|
+
},
|
|
321
|
+
$eol = `__FALLBACK_NEWLINE__`
|
|
322
|
+
},
|
|
323
|
+
or {
|
|
324
|
+
and {
|
|
325
|
+
$root <: or {
|
|
326
|
+
JsModule(directives=$directives, items=$top),
|
|
327
|
+
JsScript(directives=$directives, statements=$top),
|
|
328
|
+
TsDeclarationModule(directives=$directives, items=$top)
|
|
329
|
+
},
|
|
330
|
+
scanPrologue(container=$root, directives=$directives, body=$top, lineEnding=$eol)
|
|
331
|
+
},
|
|
332
|
+
true
|
|
333
|
+
},
|
|
334
|
+
or { $root <: contains nested(eol=$eol), true }
|
|
335
|
+
}
|