-
-
Notifications
You must be signed in to change notification settings - Fork 442
/
css.rs
680 lines (607 loc) · 23.4 KB
/
css.rs
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
use super::{
is_diagnostic_error, CodeActionsParams, ExtensionHandler, FixAllParams, LintParams,
LintResults, ParseResult,
};
use crate::configuration::to_analyzer_rules;
use crate::file_handlers::DebugCapabilities;
use crate::file_handlers::{
AnalyzerCapabilities, Capabilities, FormatterCapabilities, ParserCapabilities,
};
use crate::settings::{
FormatSettings, LanguageListSettings, LanguageSettings, LinterSettings, OverrideSettings,
ServiceLanguage, Settings, WorkspaceSettingsHandle,
};
use crate::workspace::{
CodeAction, DocumentFileSource, FixAction, FixFileMode, FixFileResult, GetSyntaxTreeResult,
OrganizeImportsResult, PullActionsResult,
};
use crate::WorkspaceError;
use biome_analyze::options::PreferredQuote;
use biome_analyze::{
AnalysisFilter, AnalyzerConfiguration, AnalyzerOptions, ControlFlow, Never,
RuleCategoriesBuilder, RuleCategory,
};
use biome_css_analyze::analyze;
use biome_css_formatter::context::CssFormatOptions;
use biome_css_formatter::format_node;
use biome_css_parser::CssParserOptions;
use biome_css_syntax::{CssLanguage, CssRoot, CssSyntaxNode};
use biome_diagnostics::{category, Applicability, Diagnostic, DiagnosticExt, Severity};
use biome_formatter::{
FormatError, IndentStyle, IndentWidth, LineEnding, LineWidth, Printed, QuoteStyle,
};
use biome_fs::BiomePath;
use biome_js_analyze::RuleError;
use biome_js_syntax::AnyJsRoot;
use biome_parser::AnyParse;
use biome_rowan::{AstNode, NodeCache};
use biome_rowan::{TextRange, TextSize, TokenAtOffset};
use std::borrow::Cow;
use tracing::{debug_span, error, info, trace, trace_span};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CssFormatterSettings {
pub line_ending: Option<LineEnding>,
pub line_width: Option<LineWidth>,
pub indent_width: Option<IndentWidth>,
pub indent_style: Option<IndentStyle>,
pub quote_style: Option<QuoteStyle>,
pub enabled: Option<bool>,
}
impl Default for CssFormatterSettings {
fn default() -> Self {
Self {
enabled: Some(false),
indent_style: Default::default(),
indent_width: Default::default(),
line_ending: Default::default(),
line_width: Default::default(),
quote_style: Default::default(),
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CssLinterSettings {
pub enabled: Option<bool>,
}
// NOTE: we want to make the linter opt-in for now
impl Default for CssLinterSettings {
fn default() -> Self {
Self {
enabled: Some(false),
}
}
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CssParserSettings {
pub allow_wrong_line_comments: bool,
pub css_modules: bool,
}
impl ServiceLanguage for CssLanguage {
type FormatterSettings = CssFormatterSettings;
type LinterSettings = CssLinterSettings;
type OrganizeImportsSettings = ();
type FormatOptions = CssFormatOptions;
type ParserSettings = CssParserSettings;
type EnvironmentSettings = ();
fn lookup_settings(language: &LanguageListSettings) -> &LanguageSettings<Self> {
&language.css
}
fn resolve_format_options(
global: Option<&FormatSettings>,
overrides: Option<&OverrideSettings>,
language: Option<&Self::FormatterSettings>,
path: &BiomePath,
document_file_source: &DocumentFileSource,
) -> Self::FormatOptions {
let indent_style = language
.and_then(|l| l.indent_style)
.or(global.and_then(|g| g.indent_style))
.unwrap_or_default();
let line_width = language
.and_then(|l| l.line_width)
.or(global.and_then(|g| g.line_width))
.unwrap_or_default();
let indent_width = language
.and_then(|l| l.indent_width)
.or(global.and_then(|g| g.indent_width))
.unwrap_or_default();
let line_ending = language
.and_then(|l| l.line_ending)
.or(global.and_then(|g| g.line_ending))
.unwrap_or_default();
let options = CssFormatOptions::new(
document_file_source
.to_css_file_source()
.unwrap_or_default(),
)
.with_indent_style(indent_style)
.with_indent_width(indent_width)
.with_line_width(line_width)
.with_line_ending(line_ending)
.with_quote_style(language.and_then(|l| l.quote_style).unwrap_or_default());
if let Some(overrides) = overrides {
overrides.to_override_css_format_options(path, options)
} else {
options
}
}
fn resolve_analyzer_options(
global: Option<&Settings>,
_linter: Option<&LinterSettings>,
_overrides: Option<&OverrideSettings>,
_language: Option<&Self::LinterSettings>,
file_path: &BiomePath,
_file_source: &DocumentFileSource,
) -> AnalyzerOptions {
let preferred_quote = global
.and_then(|global| {
global
.languages
.css
.formatter
.quote_style
.map(|quote_style: QuoteStyle| {
if quote_style == QuoteStyle::Single {
PreferredQuote::Single
} else {
PreferredQuote::Double
}
})
})
.unwrap_or_default();
let configuration = AnalyzerConfiguration {
rules: global
.map(|g| to_analyzer_rules(g, file_path.as_path()))
.unwrap_or_default(),
globals: vec![],
preferred_quote,
jsx_runtime: None,
};
AnalyzerOptions {
configuration,
file_path: file_path.to_path_buf(),
}
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct CssFileHandler;
impl ExtensionHandler for CssFileHandler {
fn capabilities(&self) -> Capabilities {
Capabilities {
parser: ParserCapabilities { parse: Some(parse) },
debug: DebugCapabilities {
debug_syntax_tree: Some(debug_syntax_tree),
debug_control_flow: None,
debug_formatter_ir: Some(debug_formatter_ir),
},
analyzer: AnalyzerCapabilities {
lint: Some(lint),
code_actions: Some(code_actions),
rename: None,
fix_all: Some(fix_all),
organize_imports: Some(organize_imports),
},
formatter: FormatterCapabilities {
format: Some(format),
format_range: Some(format_range),
format_on_type: Some(format_on_type),
},
}
}
}
fn parse(
biome_path: &BiomePath,
_file_source: DocumentFileSource,
text: &str,
settings: Option<&Settings>,
cache: &mut NodeCache,
) -> ParseResult {
let mut options = CssParserOptions {
allow_wrong_line_comments: settings
.map(|s| s.languages.css.parser.allow_wrong_line_comments)
.unwrap_or_default(),
css_modules: settings
.map(|s| s.languages.css.parser.css_modules)
.unwrap_or_default(),
};
if let Some(settings) = settings {
options = settings
.override_settings
.to_override_css_parser_options(biome_path, options);
}
let parse = biome_css_parser::parse_css_with_cache(text, cache, options);
let root = parse.syntax();
let diagnostics = parse.into_diagnostics();
ParseResult {
any_parse: AnyParse::new(
// SAFETY: the parser should always return a root node
root.as_send().unwrap(),
diagnostics,
),
language: None,
}
}
fn debug_syntax_tree(_rome_path: &BiomePath, parse: AnyParse) -> GetSyntaxTreeResult {
let syntax: CssSyntaxNode = parse.syntax();
let tree: CssRoot = parse.tree();
GetSyntaxTreeResult {
cst: format!("{syntax:#?}"),
ast: format!("{tree:#?}"),
}
}
fn debug_formatter_ir(
biome_path: &BiomePath,
document_file_source: &DocumentFileSource,
parse: AnyParse,
settings: WorkspaceSettingsHandle,
) -> Result<String, WorkspaceError> {
let options = settings.format_options::<CssLanguage>(biome_path, document_file_source);
let tree = parse.syntax();
let formatted = format_node(options, &tree)?;
let root_element = formatted.into_document();
Ok(root_element.to_string())
}
#[tracing::instrument(level = "debug", skip(parse))]
fn format(
biome_path: &BiomePath,
document_file_source: &DocumentFileSource,
parse: AnyParse,
settings: WorkspaceSettingsHandle,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<CssLanguage>(biome_path, document_file_source);
tracing::debug!("Format with the following options: \n{}", options);
let tree = parse.syntax();
let formatted = format_node(options, &tree)?;
match formatted.print() {
Ok(printed) => Ok(printed),
Err(error) => Err(WorkspaceError::FormatError(error.into())),
}
}
fn format_range(
biome_path: &BiomePath,
document_file_source: &DocumentFileSource,
parse: AnyParse,
settings: WorkspaceSettingsHandle,
range: TextRange,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<CssLanguage>(biome_path, document_file_source);
let tree = parse.syntax();
let printed = biome_css_formatter::format_range(options, &tree, range)?;
Ok(printed)
}
fn format_on_type(
biome_path: &BiomePath,
document_file_source: &DocumentFileSource,
parse: AnyParse,
settings: WorkspaceSettingsHandle,
offset: TextSize,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<CssLanguage>(biome_path, document_file_source);
let tree = parse.syntax();
let range = tree.text_range();
if offset < range.start() || offset > range.end() {
return Err(WorkspaceError::FormatError(FormatError::RangeError {
input: TextRange::at(offset, TextSize::from(0)),
tree: range,
}));
}
let token = match tree.token_at_offset(offset) {
// File is empty, do nothing
TokenAtOffset::None => panic!("empty file"),
TokenAtOffset::Single(token) => token,
// The cursor should be right after the closing character that was just typed,
// select the previous token as the correct one
TokenAtOffset::Between(token, _) => token,
};
let root_node = match token.parent() {
Some(node) => node,
None => panic!("found a token with no parent"),
};
let printed = biome_css_formatter::format_sub_tree(options, &root_node)?;
Ok(printed)
}
fn lint(params: LintParams) -> LintResults {
debug_span!("Linting CSS file", path =? params.path, language =? params.language).in_scope(
move || {
let workspace_settings = ¶ms.workspace;
let analyzer_options =
workspace_settings.analyzer_options::<CssLanguage>(params.path, ¶ms.language);
let tree = params.parse.tree();
let mut diagnostics = params.parse.into_diagnostics();
let has_only_filter = !params.only.is_empty();
let mut rules = None;
let enabled_rules = if let Some(settings) = params.workspace.settings() {
// Compute final rules (taking `overrides` into account)
rules = settings.as_rules(params.path.as_path());
if has_only_filter {
params
.only
.into_iter()
.map(|selector| selector.into())
.collect::<Vec<_>>()
} else {
rules
.as_ref()
.map(|rules| rules.as_enabled_rules())
.unwrap_or_default()
.into_iter()
.collect::<Vec<_>>()
}
} else {
vec![]
};
let disabled_rules = params
.skip
.into_iter()
.map(|selector| selector.into())
.collect::<Vec<_>>();
let filter = AnalysisFilter {
categories: params.categories,
enabled_rules: Some(enabled_rules.as_slice()),
disabled_rules: &disabled_rules,
range: None,
};
// Do not report unused suppression comment diagnostics if:
// - it is a syntax-only analyzer pass, or
// - if a single rule is run.
let ignores_suppression_comment =
!filter.categories.contains(RuleCategory::Lint) || has_only_filter;
let mut diagnostic_count = diagnostics.len() as u32;
let mut errors = diagnostics
.iter()
.filter(|diag| diag.severity() <= Severity::Error)
.count();
info!("Analyze file {}", params.path.display());
let (_, analyze_diagnostics) = analyze(&tree, filter, &analyzer_options, |signal| {
if let Some(mut diagnostic) = signal.diagnostic() {
// Do not report unused suppression comment diagnostics if this is a syntax-only analyzer pass
if ignores_suppression_comment
&& diagnostic.category() == Some(category!("suppressions/unused"))
{
return ControlFlow::<Never>::Continue(());
}
diagnostic_count += 1;
// We do now check if the severity of the diagnostics should be changed.
// The configuration allows to change the severity of the diagnostics emitted by rules.
let severity = diagnostic
.category()
.filter(|category| category.name().starts_with("lint/"))
.map_or_else(
|| diagnostic.severity(),
|category| {
rules
.as_ref()
.and_then(|rules| rules.get_severity_from_code(category))
.unwrap_or(Severity::Warning)
},
);
if severity >= Severity::Error {
errors += 1;
}
if diagnostic_count <= params.max_diagnostics {
for action in signal.actions() {
if !action.is_suppression() {
diagnostic = diagnostic.add_code_suggestion(action.into());
}
}
let error = diagnostic.with_severity(severity);
diagnostics.push(biome_diagnostics::serde::Diagnostic::new(error));
}
}
ControlFlow::<Never>::Continue(())
});
diagnostics.extend(
analyze_diagnostics
.into_iter()
.map(biome_diagnostics::serde::Diagnostic::new)
.collect::<Vec<_>>(),
);
let skipped_diagnostics = diagnostic_count.saturating_sub(diagnostics.len() as u32);
LintResults {
diagnostics,
errors,
skipped_diagnostics,
}
},
)
}
fn organize_imports(parse: AnyParse) -> Result<OrganizeImportsResult, WorkspaceError> {
Ok(OrganizeImportsResult {
code: parse.syntax::<CssLanguage>().to_string(),
})
}
#[tracing::instrument(level = "debug", skip(params))]
pub(crate) fn code_actions(params: CodeActionsParams) -> PullActionsResult {
let CodeActionsParams {
parse,
range,
workspace,
path,
manifest: _,
language,
settings,
} = params;
debug_span!("Code actions JavaScript", range =? range, path =? path).in_scope(move || {
let tree = parse.tree();
trace_span!("Parsed file", tree =? tree).in_scope(move || {
let rules = settings.as_rules(params.path.as_path());
let filter = rules
.as_ref()
.map(|rules| rules.as_enabled_rules())
.unwrap_or_default()
.into_iter()
.collect::<Vec<_>>();
let mut filter = AnalysisFilter::from_enabled_rules(filter.as_slice());
let mut categories = RuleCategoriesBuilder::default().with_syntax().with_lint();
if settings.organize_imports.enabled {
categories = categories.with_action();
}
filter.categories = categories.build();
filter.range = Some(range);
let analyzer_options = workspace.analyzer_options::<CssLanguage>(path, &language);
let Some(_) = language.to_css_file_source() else {
error!("Could not determine the file source of the file");
return PullActionsResult { actions: vec![] };
};
trace!("CSS runs the analyzer");
let mut actions = Vec::new();
analyze(&tree, filter, &analyzer_options, |signal| {
actions.extend(signal.actions().into_code_action_iter().map(|item| {
CodeAction {
category: item.category.clone(),
rule_name: item
.rule_name
.map(|(group, name)| (Cow::Borrowed(group), Cow::Borrowed(name))),
suggestion: item.suggestion,
}
}));
ControlFlow::<Never>::Continue(())
});
PullActionsResult { actions }
})
})
}
/// If applies all the safe fixes to the given syntax tree.
pub(crate) fn fix_all(params: FixAllParams) -> Result<FixFileResult, WorkspaceError> {
let FixAllParams {
parse,
fix_file_mode,
workspace,
should_format,
biome_path,
manifest: _,
document_file_source,
} = params;
let settings = workspace.settings();
let Some(settings) = settings else {
let tree: AnyJsRoot = parse.tree();
return Ok(FixFileResult {
actions: vec![],
errors: 0,
skipped_suggested_fixes: 0,
code: tree.syntax().to_string(),
});
};
let mut tree: CssRoot = parse.tree();
let mut actions = Vec::new();
// Compute final rules (taking `overrides` into account)
let rules = settings.as_rules(params.biome_path.as_path());
let rule_filter_list = rules
.as_ref()
.map(|rules| rules.as_enabled_rules())
.unwrap_or_default()
.into_iter()
.collect::<Vec<_>>();
let filter = AnalysisFilter::from_enabled_rules(rule_filter_list.as_slice());
let mut skipped_suggested_fixes = 0;
let mut errors: u16 = 0;
let analyzer_options =
workspace.analyzer_options::<CssLanguage>(biome_path, &document_file_source);
loop {
let (action, _) = analyze(&tree, filter, &analyzer_options, |signal| {
let current_diagnostic = signal.diagnostic();
if let Some(diagnostic) = current_diagnostic.as_ref() {
if is_diagnostic_error(diagnostic, rules.as_deref()) {
errors += 1;
}
}
for action in signal.actions() {
// suppression actions should not be part of the fixes (safe or suggested)
if action.is_suppression() {
continue;
}
match fix_file_mode {
FixFileMode::SafeFixes => {
if action.applicability == Applicability::MaybeIncorrect {
skipped_suggested_fixes += 1;
}
if action.applicability == Applicability::Always {
errors = errors.saturating_sub(1);
return ControlFlow::Break(action);
}
}
FixFileMode::SafeAndUnsafeFixes => {
if matches!(
action.applicability,
Applicability::Always | Applicability::MaybeIncorrect
) {
errors = errors.saturating_sub(1);
return ControlFlow::Break(action);
}
}
}
}
ControlFlow::Continue(())
});
match action {
Some(action) => {
if let (root, Some((range, _))) =
action.mutation.commit_with_text_range_and_edit(true)
{
tree = match CssRoot::cast(root) {
Some(tree) => tree,
None => {
return Err(WorkspaceError::RuleError(
RuleError::ReplacedRootWithNonRootError {
rule_name: action.rule_name.map(|(group, rule)| {
(Cow::Borrowed(group), Cow::Borrowed(rule))
}),
},
));
}
};
actions.push(FixAction {
rule_name: action
.rule_name
.map(|(group, rule)| (Cow::Borrowed(group), Cow::Borrowed(rule))),
range,
});
}
}
None => {
let code = if should_format {
format_node(
workspace.format_options::<CssLanguage>(biome_path, &document_file_source),
tree.syntax(),
)?
.print()?
.into_code()
} else {
tree.syntax().to_string()
};
return Ok(FixFileResult {
code,
skipped_suggested_fixes,
actions,
errors: errors.into(),
});
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use biome_css_syntax::CssFileSource;
#[test]
fn inherit_global_format_settings() {
let format_options = CssLanguage::resolve_format_options(
Some(&FormatSettings::default()),
None,
None,
&BiomePath::new(""),
&DocumentFileSource::Css(CssFileSource::css()),
);
assert_eq!(
format_options,
CssFormatOptions::default()
.with_indent_style(IndentStyle::default())
.with_indent_width(IndentWidth::default())
.with_line_ending(LineEnding::default())
.with_line_width(LineWidth::default())
);
}
}