cairo-language-server 2.20.0

The Cairo Language Server
Documentation
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
use std::ops::Not;

use cairo_lang_defs::db::DefsGroup;
use cairo_lang_defs::ids::FreeFunctionLongId;
use cairo_lang_defs::ids::ModuleId;
use cairo_lang_defs::ids::ModuleItemId;
use cairo_lang_defs::ids::SubmoduleLongId;
use cairo_lang_defs::ids::TopLevelLanguageElementId;
use cairo_lang_defs::plugin::MacroPlugin;
use cairo_lang_filesystem::db::FilesGroup;
use cairo_lang_filesystem::db::get_originating_location;
use cairo_lang_filesystem::ids::CrateId;
use cairo_lang_filesystem::ids::SmolStrId;
use cairo_lang_filesystem::ids::SpanInFile;
use cairo_lang_filesystem::span::TextPositionSpan;
use cairo_lang_semantic::lsp_helpers::LspHelpers;
use cairo_lang_syntax::node::helpers::QueryAttrs;
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_syntax::node::{TypedStablePtr, TypedSyntaxNode, ast::Attribute, ast::ModuleItem};
use cairo_lang_test_plugin::TestPlugin;
use cairo_lang_utils::Intern;
use cairo_language_common::CommonGroup;
use lsp_types::{CodeLens, Command, Range, Url};

use super::{
    AnnotatedNode, CodeLensInterface, CodeLensInternal, LSCodeLens, collect_functions_with_attrs,
    make_lens_args, send_execute_in_terminal,
};
use crate::config::{Config, TestRunner};
use crate::lang::db::AnalysisDatabase;
use crate::lang::db::LsSyntaxGroup;
use crate::lang::lsp::ToLsp;
use crate::lang::lsp::{LsProtoGroup, ToCairo};
use crate::server::client::Notifier;
use crate::state::State;

const TEST_EXECUTABLES: [&str; 2] = ["test", "snforge_internal_test_executable"];
const FUZZER_ATTR: &str = "fuzzer";
const TEST_CASE_ATTR: &str = "test_case";

#[derive(PartialEq, Clone, Debug)]
pub struct TestCodeLens {
    lens: CodeLens,
    full_path: String,
}

impl CodeLensInterface for TestCodeLens {
    fn execute(&self, file_url: Url, state: &State, notifier: &Notifier) -> Option<()> {
        let (full_qualified_path, module_id) =
            get_full_path_and_module_id(&file_url, state, &self.lens, &self.full_path)?;

        let db = &state.db;
        let command = state.config.test_runner.command(
            full_qualified_path,
            AvailableTestRunners::new(db, module_id.owning_crate(db))?,
            &state.config.run_test_command,
        )?;

        let file_path = file_url.to_file_path().ok()?;
        let cwd = state.project_controller.configs_registry().manifest_dir_for_file(&file_path)?;
        send_execute_in_terminal(state, notifier, command, cwd);
        Some(())
    }

    fn lens(&self) -> CodeLens {
        self.lens.clone()
    }
}

pub fn get_full_path_and_module_id<'db>(
    file_url: &Url,
    state: &'db State,
    lens: &CodeLens,
    full_path: &str,
) -> Option<(TestFullQualifiedPath, ModuleId<'db>)> {
    let db = &state.db;

    let file = db.file_for_url(file_url)?;
    let span = TextPositionSpan::offset_in_file(lens.range.to_cairo(), db, file)?;
    // When creating range we have to use [`SyntaxNode::span_without_trivia`] to place lens next to attribute
    let node = db.widest_node_within_span_without_trivia(file, span)?;

    let (full_qualified_path, module_id) =
        db.get_node_resultants(node).as_ref()?.iter().find_map(|resultant| {
            let module_item =
                resultant.ancestors_with_self(db).find_map(|node| ModuleItem::cast(db, node))?;
            let module_id = db.find_module_containing_node(module_item.as_syntax_node())?;
            let path = TestFullQualifiedPath::new(db, module_item, module_id)?;

            // Find resultant that produced this codelens earlier by comparing full paths
            (sanitize_test_case_name(path.as_ref()) == full_path).then_some((path, module_id))
        })?;

    Some((full_qualified_path, module_id))
}

pub struct TestCodeLensInternal {
    pub full_path: String,
    pub is_on_mod: bool,
    pub is_fuzzer: bool,
    pub range: Range,
    pub file_url: Url,
}

impl TestCodeLensInternal {
    fn new(
        range: Range,
        full_path: String,
        file_url: Url,
        is_on_mod: bool,
        is_fuzzer: bool,
    ) -> Self {
        Self {
            full_path: sanitize_test_case_name(&full_path),
            is_on_mod,
            is_fuzzer,
            file_url,
            range,
        }
    }
}

impl CodeLensInternal for TestCodeLensInternal {
    fn into_ls_lens(self, index: usize) -> LSCodeLens {
        let mut title = "â–¶ Run test".to_string();

        if self.is_on_mod {
            title.push('s');
        }

        let command = Command {
            title,
            command: "cairo.executeCodeLens".to_string(),
            arguments: Some(make_lens_args(self.file_url.clone(), index)),
        };

        LSCodeLens::Test(TestCodeLens {
            lens: CodeLens { range: self.range, command: Some(command), data: None },
            full_path: self.full_path,
        })
    }
}

pub fn get_test_code_lenses(
    db: &AnalysisDatabase,
    url: Url,
    config: &Config,
) -> Option<Vec<TestCodeLensInternal>> {
    let mut file_code_lens = vec![];
    let file = db.file_for_url(&url)?;

    let main_module = *db.file_modules(file).ok()?.first()?;

    let is_runner_available = config
        .test_runner
        .command(
            TestFullQualifiedPath::Function(String::new()), // We can substitute with anything here.
            AvailableTestRunners::new(db, main_module.owning_crate(db))?,
            &config.run_test_command,
        )
        .is_some();

    if is_runner_available {
        collect_test_lenses(&mut file_code_lens, db, main_module, url);
    }

    Some(file_code_lens)
}

pub enum TestFullQualifiedPath {
    Function(String),
    Module(String),
}

impl TestFullQualifiedPath {
    fn cairo_test_command(&self) -> String {
        format!("scarb cairo-test --filter {}", self.as_ref())
    }

    fn snforge_command(&self) -> String {
        match self {
            TestFullQualifiedPath::Function(path) => {
                format!("snforge test {path} --exact", path = sanitize_test_case_name(path))
            }
            TestFullQualifiedPath::Module(path) => {
                format!("snforge test {path}", path = sanitize_test_case_name(path))
            }
        }
    }
}

impl AsRef<str> for TestFullQualifiedPath {
    fn as_ref(&self) -> &str {
        match self {
            TestFullQualifiedPath::Function(path) | TestFullQualifiedPath::Module(path) => path,
        }
    }
}

impl TestFullQualifiedPath {
    pub fn new(
        db: &AnalysisDatabase,
        module_item: ModuleItem,
        module_id: ModuleId,
    ) -> Option<Self> {
        match module_item {
            ModuleItem::FreeFunction(function_with_body) => {
                let path = ModuleItemId::FreeFunction(
                    FreeFunctionLongId(module_id, function_with_body.stable_ptr(db)).intern(db),
                )
                .full_path(db);

                Some(TestFullQualifiedPath::Function(path))
            }
            ModuleItem::Module(item_module) => {
                let path = ModuleItemId::Submodule(
                    SubmoduleLongId(module_id, item_module.stable_ptr(db)).intern(db),
                )
                .full_path(db);

                Some(TestFullQualifiedPath::Module(path))
            }
            _ => None,
        }
    }
}

struct AvailableTestRunners {
    cairo_test: bool,
    snforge: bool,
}

impl AvailableTestRunners {
    fn new<'db>(db: &'db AnalysisDatabase, crate_id: CrateId<'db>) -> Option<Self> {
        let cairo_test = db.crate_macro_plugins(crate_id).iter().any(|plugin_id| {
            plugin_id.long(db).plugin_type_id() == TestPlugin::default().plugin_type_id()
        });

        // TODO(software-mansion/scarb#2347): This will not work with crate renames in `Scarb.toml`, but there is no better way to do this now.
        let snforge = db.crate_config(crate_id)?.settings.dependencies.contains_key("snforge_std");

        Some(Self { cairo_test, snforge })
    }
}

impl TestRunner {
    fn command(
        &self,
        test_path: TestFullQualifiedPath,
        available_runners: AvailableTestRunners,
        custom_command: &str,
    ) -> Option<String> {
        match self {
            Self::Auto => match (available_runners.cairo_test, available_runners.snforge) {
                (true, false) => Some(test_path.cairo_test_command()),
                (false, true) => Some(test_path.snforge_command()),
                _ => None,
            },
            Self::CairoTest if available_runners.cairo_test => Some(test_path.cairo_test_command()),
            Self::Snforge if available_runners.snforge => Some(test_path.snforge_command()),
            Self::Custom => Some(custom_command.replace("{{TEST_PATH}}", test_path.as_ref())),
            _ => None,
        }
    }
}

fn collect_test_functions<'db>(
    db: &'db AnalysisDatabase,
    module: ModuleId<'db>,
) -> Vec<AnnotatedNode<'db>> {
    collect_functions_with_attrs(db, module, &TEST_EXECUTABLES)
}

fn collect_test_lenses<'db>(
    file_code_lens: &mut Vec<TestCodeLensInternal>,
    db: &'db AnalysisDatabase,
    module: ModuleId<'db>,
    file_url: Url,
) {
    for node in collect_test_functions(db, module) {
        let attribute_ptr = node.attribute_ptr;
        maybe_push_code_lens(
            db,
            file_code_lens,
            |range, full_path| {
                TestCodeLensInternal::new(
                    range,
                    full_path,
                    file_url.clone(),
                    false,
                    is_fuzzer_test(db, attribute_ptr),
                )
            },
            node,
        );
    }

    let Ok(modules) = db.module_submodules_ids(module) else { return };

    for submodule in modules.iter().copied() {
        let is_inline = db.is_submodule_inline(submodule);

        let has_tests = if is_inline {
            let tests_count = file_code_lens.len();

            collect_test_lenses(
                file_code_lens,
                db,
                ModuleId::Submodule(submodule),
                file_url.clone(),
            );

            // Append mod only if it contains tests.
            tests_count != file_code_lens.len()
        } else {
            has_any_test(db, ModuleId::Submodule(submodule))
        };

        if has_tests {
            let ptr = submodule.stable_ptr(db).lookup(db).module_kw(db).stable_ptr(db).untyped();

            let full_path = submodule.full_path(db);
            let module_node = AnnotatedNode { full_path: full_path.clone(), attribute_ptr: ptr };
            maybe_push_code_lens(
                db,
                file_code_lens,
                |range, full_path| {
                    TestCodeLensInternal::new(range, full_path, file_url.clone(), true, false)
                },
                module_node,
            );
        }
    }
}

fn has_any_test<'db>(db: &'db AnalysisDatabase, module: ModuleId<'db>) -> bool {
    if collect_test_functions(db, module).is_empty().not() {
        return true;
    }

    let Ok(modules) = db.module_submodules_ids(module) else { return false };

    modules.iter().copied().map(ModuleId::Submodule).any(|submodule| {
        collect_test_functions(db, submodule).is_empty().not() || has_any_test(db, submodule)
    })
}

fn get_test_lens_range<'db>(
    db: &'db AnalysisDatabase,
    ptr: SyntaxStablePtrId<'db>,
) -> Option<Range> {
    // Use [`SyntaxNode::span_without_trivia`] to place lens next to attribute
    let SpanInFile { file_id, span } = get_originating_location(
        db,
        SpanInFile { file_id: ptr.file_id(db), span: ptr.lookup(db).span_without_trivia(db) },
        None,
    );

    span.position_in_file(db, file_id).map(|position| position.to_lsp())
}

fn maybe_push_code_lens(
    db: &AnalysisDatabase,
    file_state: &mut Vec<TestCodeLensInternal>,
    make_code_lens: impl FnOnce(Range, String) -> TestCodeLensInternal,
    annotated_function: AnnotatedNode,
) {
    let AnnotatedNode { attribute_ptr, full_path } = annotated_function;
    if let Some(range) = get_test_lens_range(db, attribute_ptr) {
        let lens_builder = make_code_lens(range, full_path);

        file_state.push(lens_builder)
    }
}

fn is_fuzzer_test(db: &AnalysisDatabase, ptr: SyntaxStablePtrId) -> bool {
    let SpanInFile { file_id, span } = get_originating_location(
        db,
        SpanInFile { file_id: ptr.file_id(db), span: ptr.lookup(db).span_without_trivia(db) },
        None,
    );

    let Some(original_node) = db.find_syntax_node_at_offset(file_id, span.start) else {
        return false;
    };

    // We do not want to skip test cases.
    // `#[test_case]` generates a new test with `#[snforge_internal_test_executable]`
    // directly so it is okay to test for it as an ancestor.
    if original_node
        .ancestor_of_type::<Attribute>(db)
        .map(|attr| {
            attr.attr(db).as_syntax_node().get_text_without_trivia(db)
                == SmolStrId::from(db, TEST_CASE_ATTR)
        })
        .unwrap_or(false)
    {
        return false;
    }

    original_node
        .ancestors_with_self(db)
        .find_map(|n| ModuleItem::cast(db, n))
        .map(|module_item| module_item.find_attr(db, FUZZER_ATTR).is_some())
        .unwrap_or(false)
}

// Copied from starknet-foundry
pub fn sanitize_test_case_name(name: &str) -> String {
    // Test names generated by `#[test]` and `#[fuzzer]` macros contain internal suffixes
    name.replace("__test_generated", "")
        .replace("__fuzzer_generated", "")
        .replace("__snforge_internal_test_generated", "")
        .replace("__snforge_internal_fuzzer_generated", "")
}