-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcss-language.js
292 lines (261 loc) · 7.41 KB
/
css-language.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
* @filedescription The CSSLanguage class.
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Imports
//------------------------------------------------------------------------------
import {
parse as originalParse,
lexer as originalLexer,
fork,
tokenTypes,
} from "@eslint/css-tree";
import { CSSSourceCode } from "./css-source-code.js";
import { visitorKeys } from "./css-visitor-keys.js";
import scss from "./scss-syntax.js"
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @typedef {import("@eslint/css-tree").CssNode} CssNode */
/** @typedef {import("@eslint/css-tree").CssNodePlain} CssNodePlain */
/** @typedef {import("@eslint/css-tree").StyleSheet} StyleSheet */
/** @typedef {import("@eslint/css-tree").Comment} Comment */
/** @typedef {import("@eslint/css-tree").Lexer} Lexer */
/** @typedef {import("@eslint/css-tree").SyntaxConfig} SyntaxConfig */
/** @typedef {import("@eslint/core").Language} Language */
/** @typedef {import("@eslint/core").OkParseResult<CssNodePlain> & { comments: Comment[], lexer: Lexer }} OkParseResult */
/** @typedef {import("@eslint/core").ParseResult<CssNodePlain>} ParseResult */
/** @typedef {import("@eslint/core").File} File */
/** @typedef {import("@eslint/core").FileError} FileError */
/**
* @typedef {"css"|"scss"} LanguageMode
*/
/**
* @typedef {Object} CSSLanguageOptions
* @property {boolean} [tolerant] Whether to be tolerant of recoverable parsing errors.
* @property {SyntaxConfig} [customSyntax] Custom syntax to use for parsing.
*/
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
const blockOpenerTokenTypes = new Map([
[tokenTypes.Function, ")"],
[tokenTypes.LeftCurlyBracket, "}"],
[tokenTypes.LeftParenthesis, ")"],
[tokenTypes.LeftSquareBracket, "]"],
]);
const blockCloserTokenTypes = new Map([
[tokenTypes.RightCurlyBracket, "{"],
[tokenTypes.RightParenthesis, "("],
[tokenTypes.RightSquareBracket, "["],
]);
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* CSS Language Object
* @implements {Language}
*/
export class CSSLanguage {
/**
* The type of file to read.
* @type {"text"}
*/
fileType = "text";
/**
* The line number at which the parser starts counting.
* @type {0|1}
*/
lineStart = 1;
/**
* The column number at which the parser starts counting.
* @type {0|1}
*/
columnStart = 1;
/**
* The name of the key that holds the type of the node.
* @type {string}
*/
nodeTypeKey = "type";
/**
* The visitor keys for the CSSTree AST.
* @type {Record<string, string[]>}
*/
visitorKeys = visitorKeys;
/**
* The language mode.
* @type {LanguageMode}
*/
mode;
/**
* The default language options.
* @type {CSSLanguageOptions}
*/
defaultLanguageOptions = {
tolerant: false,
};
/**
* Creates a new instance of the CSSLanguage class.
* @param {Object} options The options for the language.
* @param {LanguageMode} [options.mode] The language mode to use.
*/
constructor({ mode = "css" } = {}) {
this.mode = mode;
}
/**
* Validates the language options.
* @param {CSSLanguageOptions} languageOptions The language options to validate.
* @throws {Error} When the language options are invalid.
*/
validateLanguageOptions(languageOptions) {
if (
"tolerant" in languageOptions &&
typeof languageOptions.tolerant !== "boolean"
) {
throw new TypeError(
"Expected a boolean value for 'tolerant' option.",
);
}
if ("customSyntax" in languageOptions) {
if (
typeof languageOptions.customSyntax !== "object" ||
languageOptions.customSyntax === null
) {
throw new TypeError(
"Expected an object value for 'customSyntax' option.",
);
}
}
}
/**
* Parses the given file into an AST.
* @param {File} file The virtual file to parse.
* @param {Object} [context] The parsing context.
* @param {CSSLanguageOptions} [context.languageOptions] The language options to use for parsing.
* @returns {ParseResult} The result of parsing.
*/
parse(file, { languageOptions = {} } = {}) {
// Note: BOM already removed
const text = /** @type {string} */ (file.body);
/** @type {Comment[]} */
const comments = [];
/** @type {FileError[]} */
const errors = [];
const syntax = this.mode === "scss" ? scss : languageOptions.customSyntax;
const { tolerant } = languageOptions;
const { parse, lexer, toPlainObject } = syntax
? fork(syntax)
: { parse: originalParse, lexer: originalLexer };
/*
* Check for parsing errors first. If there's a parsing error, nothing
* else can happen. However, a parsing error does not throw an error
* from this method - it's just considered a fatal error message, a
* problem that ESLint identified just like any other.
*/
try {
const root = toPlainObject(
parse(text, {
filename: file.path,
positions: true,
onComment(value, loc) {
comments.push({
type: "Comment",
value,
loc,
});
},
onParseError(error) {
if (!tolerant) {
errors.push(error);
}
},
onToken(type, start, end, index) {
if (tolerant) {
return;
}
switch (type) {
// these already generate errors
case tokenTypes.BadString:
case tokenTypes.BadUrl:
break;
default:
/* eslint-disable new-cap -- This is a valid call */
if (this.isBlockOpenerTokenType(type)) {
if (
this.getBlockTokenPairIndex(index) ===
-1
) {
const loc = this.getRangeLocation(
start,
end,
);
errors.push(
parse.SyntaxError(
`Missing closing ${blockOpenerTokenTypes.get(type)}`,
text,
start,
loc.start.line,
loc.start.column,
),
);
}
} else if (this.isBlockCloserTokenType(type)) {
if (
this.getBlockTokenPairIndex(index) ===
-1
) {
const loc = this.getRangeLocation(
start,
end,
);
errors.push(
parse.SyntaxError(
`Missing opening ${blockCloserTokenTypes.get(type)}`,
text,
start,
loc.start.line,
loc.start.column,
),
);
}
}
/* eslint-enable new-cap -- This is a valid call */
}
},
}),
);
if (errors.length) {
return {
ok: false,
errors,
};
}
return {
ok: true,
ast: root,
comments,
lexer,
};
} catch (ex) {
return {
ok: false,
errors: [ex],
};
}
}
/**
* Creates a new `CSSSourceCode` object from the given information.
* @param {File} file The virtual file to create a `CSSSourceCode` object from.
* @param {OkParseResult} parseResult The result returned from `parse()`.
* @returns {CSSSourceCode} The new `CSSSourceCode` object.
*/
createSourceCode(file, parseResult) {
return new CSSSourceCode({
text: /** @type {string} */ (file.body),
ast: parseResult.ast,
comments: parseResult.comments,
lexer: parseResult.lexer,
});
}
}