squawk_wasm/
lib.rs

1use line_index::LineIndex;
2use log::info;
3use serde::Serialize;
4use wasm_bindgen::prelude::*;
5use web_sys::js_sys::Error;
6
7#[wasm_bindgen(start)]
8pub fn run() {
9    use log::Level;
10
11    // When the `console_error_panic_hook` feature is enabled, we can call the
12    // `set_panic_hook` function at least once during initialization, and then
13    // we will get better error messages if our code ever panics.
14    //
15    // For more details see
16    // https://github.com/rustwasm/console_error_panic_hook#readme
17    #[cfg(feature = "console_error_panic_hook")]
18    console_error_panic_hook::set_once();
19    console_log::init_with_level(Level::Debug).expect("Initializing logger went wrong.");
20    info!("init!");
21}
22
23#[wasm_bindgen]
24pub fn dump_cst(text: String) -> String {
25    let parse = squawk_syntax::SourceFile::parse(&text);
26    format!("{:#?}", parse.syntax_node())
27}
28
29#[wasm_bindgen]
30pub fn dump_tokens(text: String) -> String {
31    let tokens = squawk_lexer::tokenize(&text);
32    let mut start = 0;
33    let mut out = String::new();
34    for token in tokens {
35        let end = start + token.len;
36        let content = &text[start as usize..(end) as usize];
37        out += &format!("{:?}@{start}..{end} {:?}\n", token.kind, content);
38        start += token.len;
39    }
40    out
41}
42
43#[expect(unused)]
44#[derive(Serialize)]
45enum Severity {
46    Hint,
47    Info,
48    Warning,
49    Error,
50}
51
52#[derive(Serialize)]
53struct LintError {
54    severity: Severity,
55    code: String,
56    message: String,
57    start_line_number: u32,
58    start_column: u32,
59    end_line_number: u32,
60    end_column: u32,
61    // used for the linter tab
62    range_start: usize,
63    // used for the linter tab
64    range_end: usize,
65    // used for the linter tab
66    messages: Vec<String>,
67    fix: Option<Fix>,
68}
69
70#[derive(Serialize)]
71struct Fix {
72    title: String,
73    edits: Vec<TextEdit>,
74}
75
76#[derive(Serialize)]
77struct TextEdit {
78    start_line_number: u32,
79    start_column: u32,
80    end_line_number: u32,
81    end_column: u32,
82    text: String,
83}
84
85#[wasm_bindgen]
86pub fn lint(text: String) -> Result<JsValue, Error> {
87    let mut linter = squawk_linter::Linter::with_all_rules();
88    let parse = squawk_syntax::SourceFile::parse(&text);
89    let parse_errors = parse.errors();
90
91    let line_index = LineIndex::new(&text);
92
93    // TODO: chain these with other stuff
94    let parse_errors = parse_errors.iter().map(|x| {
95        let range_start = x.range().start();
96        let range_end = x.range().end();
97        let start = line_index.line_col(range_start);
98        let end = line_index.line_col(range_end);
99        let start = line_index
100            .to_wide(line_index::WideEncoding::Utf16, start)
101            .unwrap();
102        let end = line_index
103            .to_wide(line_index::WideEncoding::Utf16, end)
104            .unwrap();
105        LintError {
106            severity: Severity::Error,
107            code: "syntax-error".to_string(),
108            message: x.message().to_string(),
109            start_line_number: start.line,
110            start_column: start.col,
111            end_line_number: end.line,
112            end_column: end.col,
113            range_start: range_start.into(),
114            range_end: range_end.into(),
115            messages: vec![],
116            fix: None,
117        }
118    });
119
120    let lint_errors = linter.lint(&parse, &text);
121    let errors = lint_errors.into_iter().map(|x| {
122        let start = line_index.line_col(x.text_range.start());
123        let end = line_index.line_col(x.text_range.end());
124        let start = line_index
125            .to_wide(line_index::WideEncoding::Utf16, start)
126            .unwrap();
127        let end = line_index
128            .to_wide(line_index::WideEncoding::Utf16, end)
129            .unwrap();
130
131        let messages = x.help.into_iter().collect();
132
133        let fix = x.fix.map(|fix| {
134            let edits = fix
135                .edits
136                .into_iter()
137                .map(|edit| {
138                    let start_pos = line_index.line_col(edit.text_range.start());
139                    let end_pos = line_index.line_col(edit.text_range.end());
140                    let start_wide = line_index
141                        .to_wide(line_index::WideEncoding::Utf16, start_pos)
142                        .unwrap();
143                    let end_wide = line_index
144                        .to_wide(line_index::WideEncoding::Utf16, end_pos)
145                        .unwrap();
146
147                    TextEdit {
148                        start_line_number: start_wide.line,
149                        start_column: start_wide.col,
150                        end_line_number: end_wide.line,
151                        end_column: end_wide.col,
152                        text: edit.text.unwrap_or_default(),
153                    }
154                })
155                .collect();
156
157            Fix {
158                title: fix.title,
159                edits,
160            }
161        });
162
163        LintError {
164            code: x.code.to_string(),
165            range_start: x.text_range.start().into(),
166            range_end: x.text_range.end().into(),
167            message: x.message.clone(),
168            messages,
169            // parser errors should be error
170            severity: Severity::Warning,
171            start_line_number: start.line,
172            start_column: start.col,
173            end_line_number: end.line,
174            end_column: end.col,
175            fix,
176        }
177    });
178
179    let mut errors_to_dump = errors.chain(parse_errors).collect::<Vec<_>>();
180    errors_to_dump.sort_by_key(|k| (k.start_line_number, k.start_column));
181
182    serde_wasm_bindgen::to_value(&errors_to_dump).map_err(into_error)
183}
184
185fn into_error<E: std::fmt::Display>(err: E) -> Error {
186    Error::new(&err.to_string())
187}
188
189#[wasm_bindgen]
190pub fn goto_definition(content: String, line: u32, col: u32) -> Result<JsValue, Error> {
191    let parse = squawk_syntax::SourceFile::parse(&content);
192    let line_index = LineIndex::new(&content);
193    let offset = position_to_offset(&line_index, line, col)?;
194    let result = squawk_ide::goto_definition::goto_definition(parse.tree(), offset);
195
196    let response = result.map(|range| {
197        let start = line_index.line_col(range.start());
198        let end = line_index.line_col(range.end());
199        let start_wide = line_index
200            .to_wide(line_index::WideEncoding::Utf16, start)
201            .unwrap();
202        let end_wide = line_index
203            .to_wide(line_index::WideEncoding::Utf16, end)
204            .unwrap();
205
206        LocationRange {
207            start_line: start_wide.line,
208            start_column: start_wide.col,
209            end_line: end_wide.line,
210            end_column: end_wide.col,
211        }
212    });
213
214    serde_wasm_bindgen::to_value(&response).map_err(into_error)
215}
216
217#[wasm_bindgen]
218pub fn hover(content: String, line: u32, col: u32) -> Result<JsValue, Error> {
219    let parse = squawk_syntax::SourceFile::parse(&content);
220    let line_index = LineIndex::new(&content);
221    let offset = position_to_offset(&line_index, line, col)?;
222    let result = squawk_ide::hover::hover(&parse.tree(), offset);
223
224    serde_wasm_bindgen::to_value(&result).map_err(into_error)
225}
226
227#[wasm_bindgen]
228pub fn find_references(content: String, line: u32, col: u32) -> Result<JsValue, Error> {
229    let parse = squawk_syntax::SourceFile::parse(&content);
230    let line_index = LineIndex::new(&content);
231    let offset = position_to_offset(&line_index, line, col)?;
232    let references = squawk_ide::find_references::find_references(&parse.tree(), offset);
233
234    let locations: Vec<LocationRange> = references
235        .iter()
236        .map(|range| {
237            let start = line_index.line_col(range.start());
238            let end = line_index.line_col(range.end());
239            let start_wide = line_index
240                .to_wide(line_index::WideEncoding::Utf16, start)
241                .unwrap();
242            let end_wide = line_index
243                .to_wide(line_index::WideEncoding::Utf16, end)
244                .unwrap();
245
246            LocationRange {
247                start_line: start_wide.line,
248                start_column: start_wide.col,
249                end_line: end_wide.line,
250                end_column: end_wide.col,
251            }
252        })
253        .collect();
254
255    serde_wasm_bindgen::to_value(&locations).map_err(into_error)
256}
257
258#[wasm_bindgen]
259pub fn document_symbols(content: String) -> Result<JsValue, Error> {
260    let parse = squawk_syntax::SourceFile::parse(&content);
261    let line_index = LineIndex::new(&content);
262    let symbols = squawk_ide::document_symbols::document_symbols(&parse.tree());
263
264    let converted: Vec<WasmDocumentSymbol> = symbols
265        .into_iter()
266        .map(|s| convert_document_symbol(&line_index, s))
267        .collect();
268
269    serde_wasm_bindgen::to_value(&converted).map_err(into_error)
270}
271
272#[wasm_bindgen]
273pub fn code_actions(content: String, line: u32, col: u32) -> Result<JsValue, Error> {
274    let parse = squawk_syntax::SourceFile::parse(&content);
275    let line_index = LineIndex::new(&content);
276    let offset = position_to_offset(&line_index, line, col)?;
277    let actions = squawk_ide::code_actions::code_actions(parse.tree(), offset);
278
279    let converted = actions.map(|actions| {
280        actions
281            .into_iter()
282            .map(|action| {
283                let edits = action
284                    .edits
285                    .into_iter()
286                    .map(|edit| {
287                        let start_pos = line_index.line_col(edit.text_range.start());
288                        let end_pos = line_index.line_col(edit.text_range.end());
289                        let start_wide = line_index
290                            .to_wide(line_index::WideEncoding::Utf16, start_pos)
291                            .unwrap();
292                        let end_wide = line_index
293                            .to_wide(line_index::WideEncoding::Utf16, end_pos)
294                            .unwrap();
295
296                        TextEdit {
297                            start_line_number: start_wide.line,
298                            start_column: start_wide.col,
299                            end_line_number: end_wide.line,
300                            end_column: end_wide.col,
301                            text: edit.text.unwrap_or_default(),
302                        }
303                    })
304                    .collect();
305
306                WasmCodeAction {
307                    title: action.title,
308                    edits,
309                    kind: match action.kind {
310                        squawk_ide::code_actions::ActionKind::QuickFix => "quickfix",
311                        squawk_ide::code_actions::ActionKind::RefactorRewrite => "refactor.rewrite",
312                    }
313                    .to_string(),
314                }
315            })
316            .collect::<Vec<_>>()
317    });
318
319    serde_wasm_bindgen::to_value(&converted).map_err(into_error)
320}
321
322fn position_to_offset(
323    line_index: &LineIndex,
324    line: u32,
325    col: u32,
326) -> Result<rowan::TextSize, Error> {
327    let wide_pos = line_index::WideLineCol { line, col };
328
329    let pos = line_index
330        .to_utf8(line_index::WideEncoding::Utf16, wide_pos)
331        .ok_or_else(|| Error::new("Invalid position"))?;
332
333    line_index
334        .offset(pos)
335        .ok_or_else(|| Error::new("Invalid position offset"))
336}
337
338#[derive(Serialize)]
339struct LocationRange {
340    start_line: u32,
341    start_column: u32,
342    end_line: u32,
343    end_column: u32,
344}
345
346#[derive(Serialize)]
347struct WasmCodeAction {
348    title: String,
349    edits: Vec<TextEdit>,
350    kind: String,
351}
352
353#[derive(Serialize)]
354struct WasmDocumentSymbol {
355    name: String,
356    detail: Option<String>,
357    kind: String,
358    start_line: u32,
359    start_column: u32,
360    end_line: u32,
361    end_column: u32,
362    selection_start_line: u32,
363    selection_start_column: u32,
364    selection_end_line: u32,
365    selection_end_column: u32,
366    children: Vec<WasmDocumentSymbol>,
367}
368
369fn convert_document_symbol(
370    line_index: &LineIndex,
371    symbol: squawk_ide::document_symbols::DocumentSymbol,
372) -> WasmDocumentSymbol {
373    let full_start = line_index.line_col(symbol.full_range.start());
374    let full_end = line_index.line_col(symbol.full_range.end());
375    let full_start_wide = line_index
376        .to_wide(line_index::WideEncoding::Utf16, full_start)
377        .unwrap();
378    let full_end_wide = line_index
379        .to_wide(line_index::WideEncoding::Utf16, full_end)
380        .unwrap();
381
382    let focus_start = line_index.line_col(symbol.focus_range.start());
383    let focus_end = line_index.line_col(symbol.focus_range.end());
384    let focus_start_wide = line_index
385        .to_wide(line_index::WideEncoding::Utf16, focus_start)
386        .unwrap();
387    let focus_end_wide = line_index
388        .to_wide(line_index::WideEncoding::Utf16, focus_end)
389        .unwrap();
390
391    WasmDocumentSymbol {
392        name: symbol.name,
393        detail: symbol.detail,
394        kind: match symbol.kind {
395            squawk_ide::document_symbols::DocumentSymbolKind::Table => "table",
396            squawk_ide::document_symbols::DocumentSymbolKind::Function => "function",
397            squawk_ide::document_symbols::DocumentSymbolKind::Type => "type",
398            squawk_ide::document_symbols::DocumentSymbolKind::Column => "column",
399            squawk_ide::document_symbols::DocumentSymbolKind::Variant => "variant",
400        }
401        .to_string(),
402        start_line: full_start_wide.line,
403        start_column: full_start_wide.col,
404        end_line: full_end_wide.line,
405        end_column: full_end_wide.col,
406        selection_start_line: focus_start_wide.line,
407        selection_start_column: focus_start_wide.col,
408        selection_end_line: focus_end_wide.line,
409        selection_end_column: focus_end_wide.col,
410        children: symbol
411            .children
412            .into_iter()
413            .map(|child| convert_document_symbol(line_index, child))
414            .collect(),
415    }
416}
417
418#[wasm_bindgen]
419pub fn inlay_hints(content: String) -> Result<JsValue, Error> {
420    let parse = squawk_syntax::SourceFile::parse(&content);
421    let line_index = LineIndex::new(&content);
422    let hints = squawk_ide::inlay_hints::inlay_hints(&parse.tree());
423
424    let converted: Vec<WasmInlayHint> = hints
425        .into_iter()
426        .map(|hint| {
427            let position = line_index.line_col(hint.position);
428            let position_wide = line_index
429                .to_wide(line_index::WideEncoding::Utf16, position)
430                .unwrap();
431
432            WasmInlayHint {
433                line: position_wide.line,
434                column: position_wide.col,
435                label: hint.label,
436                kind: match hint.kind {
437                    squawk_ide::inlay_hints::InlayHintKind::Type => "type",
438                    squawk_ide::inlay_hints::InlayHintKind::Parameter => "parameter",
439                }
440                .to_string(),
441            }
442        })
443        .collect();
444
445    serde_wasm_bindgen::to_value(&converted).map_err(into_error)
446}
447
448#[derive(Serialize)]
449struct WasmInlayHint {
450    line: u32,
451    column: u32,
452    label: String,
453    kind: String,
454}