-
-
Notifications
You must be signed in to change notification settings - Fork 541
/
Copy pathsvelte.rs
196 lines (176 loc) · 6.15 KB
/
svelte.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
use crate::file_handlers::{
javascript, AnalyzerCapabilities, Capabilities, CodeActionsParams, DebugCapabilities,
ExtensionHandler, FixAllParams, FormatterCapabilities, LintParams, LintResults, Mime,
ParseResult, ParserCapabilities,
};
use crate::settings::SettingsHandle;
use crate::workspace::{
DocumentFileSource, FixFileResult, OrganizeImportsResult, PullActionsResult,
};
use crate::WorkspaceError;
use biome_formatter::Printed;
use biome_fs::BiomePath;
use biome_js_parser::{parse_js_with_cache, JsParserOptions};
use biome_js_syntax::{EmbeddingKind, JsFileSource, TextRange, TextSize};
use biome_parser::AnyParse;
use biome_rowan::NodeCache;
use lazy_static::lazy_static;
use regex::{Match, Regex};
use tracing::debug;
#[derive(Debug, Default, PartialEq, Eq)]
pub struct SvelteFileHandler;
lazy_static! {
// https://regex101.com/r/E4n4hh/3
pub static ref SVELTE_FENCE: Regex = Regex::new(
r#"(?ixms)(?:<script[^>]?)
(?:
(?:(lang)\s*=\s*['"](?P<lang>[^'"]*)['"])
|
(?:(\w+)\s*(?:=\s*['"]([^'"]*)['"])?)
)*
[^>]*>\n(?P<script>(?U:.*))</script>"#
)
.unwrap();
}
impl SvelteFileHandler {
/// It extracts the JavaScript/TypeScript code contained in the script block of a Svelte file
///
/// If there's no script block, an empty string is returned.
pub fn input(text: &str) -> &str {
match Self::matches_script(text) {
Some(script) => &text[script.start()..script.end()],
_ => "",
}
}
/// It takes the original content of a Svelte file, and new output of an Svelte file. The output is only the content contained inside the
/// Svelte `<script>` tag. The function replaces `output` inside that `<script>`.
pub fn output(input: &str, output: &str) -> String {
if let Some(script) = Self::matches_script(input) {
format!(
"{}{}{}",
&input[..script.start()],
output,
&input[script.end()..]
)
} else {
input.to_string()
}
}
/// Returns the start byte offset of the Svelte `<script>` tag
pub fn start(input: &str) -> Option<u32> {
Self::matches_script(input).map(|m| m.start() as u32)
}
fn matches_script(input: &str) -> Option<Match> {
SVELTE_FENCE
.captures(input)
.and_then(|captures| captures.name("script"))
}
pub fn file_source(text: &str) -> JsFileSource {
let matches = SVELTE_FENCE.captures(text);
matches
.and_then(|captures| captures.name("lang"))
.filter(|lang| lang.as_str() == "ts")
.map_or(JsFileSource::js_module(), |_| {
JsFileSource::ts().with_embedding_kind(EmbeddingKind::Svelte)
})
}
}
impl ExtensionHandler for SvelteFileHandler {
fn mime(&self) -> Mime {
Mime::Javascript
}
fn capabilities(&self) -> Capabilities {
Capabilities {
parser: ParserCapabilities { parse: Some(parse) },
debug: DebugCapabilities {
debug_syntax_tree: None,
debug_control_flow: None,
debug_formatter_ir: None,
},
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(
_rome_path: &BiomePath,
_file_source: DocumentFileSource,
text: &str,
_settings: SettingsHandle,
cache: &mut NodeCache,
) -> ParseResult {
let matches = SVELTE_FENCE.captures(text);
let script = match matches {
Some(ref captures) => &text[captures.name("script").unwrap().range()],
_ => "",
};
let language = matches
.and_then(|captures| captures.name("lang"))
.filter(|lang| lang.as_str() == "ts")
.map_or(JsFileSource::js_module(), |_| JsFileSource::ts());
debug!("Parsing file with language {:?}", language);
let parse = parse_js_with_cache(script, language, JsParserOptions::default(), cache);
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: Some(if language.is_typescript() {
JsFileSource::ts().into()
} else {
JsFileSource::js_module().into()
}),
}
}
#[tracing::instrument(level = "trace", skip(parse, settings))]
fn format(
biome_path: &BiomePath,
document_file_source: &DocumentFileSource,
parse: AnyParse,
settings: SettingsHandle,
) -> Result<Printed, WorkspaceError> {
javascript::format(biome_path, document_file_source, parse, settings)
}
pub(crate) fn format_range(
biome_path: &BiomePath,
document_file_source: &DocumentFileSource,
parse: AnyParse,
settings: SettingsHandle,
range: TextRange,
) -> Result<Printed, WorkspaceError> {
javascript::format_range(biome_path, document_file_source, parse, settings, range)
}
pub(crate) fn format_on_type(
biome_path: &BiomePath,
document_file_source: &DocumentFileSource,
parse: AnyParse,
settings: SettingsHandle,
offset: TextSize,
) -> Result<Printed, WorkspaceError> {
javascript::format_on_type(biome_path, document_file_source, parse, settings, offset)
}
pub(crate) fn lint(params: LintParams) -> LintResults {
javascript::lint(params)
}
pub(crate) fn code_actions(params: CodeActionsParams) -> PullActionsResult {
javascript::code_actions(params)
}
fn fix_all(params: FixAllParams) -> Result<FixFileResult, WorkspaceError> {
javascript::fix_all(params)
}
fn organize_imports(parse: AnyParse) -> Result<OrganizeImportsResult, WorkspaceError> {
javascript::organize_imports(parse)
}