-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathseparate-choices.ts
58 lines (53 loc) · 1.79 KB
/
separate-choices.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { makeListener, n } from "../utils";
import type { Rule } from "eslint";
import { Settings } from "../settings";
import type { visitor } from "@peggyjs/eslint-parser";
const rule: Rule.RuleModule = {
meta: {
type: "layout",
docs: {
description: "require each top-level choice in a rule to be on a new line",
recommended: true,
url: "https://github.com/peggyjs/peggyjs-eslint-plugin/blob/main/docs/rules/separate-choices.md",
},
messages: {
next: "Each top-level choice in a rule must be on a new line.",
},
fixable: "whitespace",
schema: [],
},
create(context: Rule.RuleContext): Rule.RuleListener {
const settings = new Settings(context.settings);
const indent = settings.indent;
const newline = settings.newline;
return makeListener({
rule(node: visitor.AST.Rule): void {
const expr: visitor.AST.Expression = (node.expression.type === "named")
? node.expression.expression
: node.expression;
if (expr.type === "choice") {
let prevLine = node.equals.loc.start.line - 1;
let prevEnd = node.equals.range[1];
for (const choice of expr.alternatives) {
if (choice.loc.start.line === prevLine) {
const start = prevEnd; // Capture in case multiple
context.report({
node: n(choice),
messageId: "next",
fix(fixer: Rule.RuleFixer): Rule.Fix {
return fixer.replaceTextRange(
[start, choice.range[0]],
`${newline}${indent}/ `
);
},
});
}
prevLine = choice.loc.end.line;
prevEnd = choice.range[1];
}
}
},
});
},
};
export = rule;