fatou 0.10.0

A language server, formatter, and linter for Julia
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
//! `undefined-name`: a free identifier that no resolution tier provides.
//!
//! A read that binds nowhere — not up the scope chain, not an explicit
//! import, not a workspace sibling, not a whole-module `using`'s export, not
//! Base/Core — raises `UndefVarError` the moment it runs. Resolution follows
//! the shared masking order in [`crate::resolve::Resolver`], so this rule
//! agrees with completion, hover, and go-to-definition about what a name
//! means.
//!
//! Julia's `include`-splicing and metaprogramming make "is this defined?"
//! undecidable for a file in isolation, so the rule buys soundness with
//! deliberate bail-outs, skipping the whole file when:
//!
//! - the caller provides no [`ResolutionContext`] (nothing to resolve
//!   against);
//! - a whole-module `using` does not resolve against the provided library
//!   (an unharvested package, or a relative `using .M`) — it may export
//!   anything;
//! - the file calls `eval`/`@eval` (definitions invisible to the model);
//! - the file `include`s anything while no workspace context is known, or
//!   `include`s a non-literal path even with one (the harvest cannot follow
//!   it).
//!
//! Within a checkable file, value reads inside macro calls are exempt (a
//! macro receives unevaluated expressions and may bind names itself), quoted
//! code (`:(…)`, `quote … end`) is exempt entirely, and the module-implicit
//! names `eval`, `include`, `new`, and `ccall` always resolve.
//!
//! Off by default: without project context a bare file may be an `include`d
//! fragment reading its host's globals. The language server enables the rule
//! for workspace member files, where the include graph pins the file's host
//! module and the harvested library answers the remaining tiers; on the CLI
//! (which resolves against the built-in Base/Core snapshot only) it is
//! opt-in via `--select`, sound for self-contained scripts.

use rowan::TextRange;

use crate::ast::{AstNode, AstToken, CallExpr, Expr, MacroCall};
use crate::linter::diagnostic::Diagnostic;
use crate::linter::rules::{Example, Rule, RuleContext};
use crate::project::include_target;
use crate::resolve::{Namespace, Resolution, Resolver, has_unresolvable_using};
use crate::syntax::{SyntaxKind, SyntaxNode};

pub struct UndefinedName;

/// Names every module defines implicitly (`eval`, `include`) or that are
/// magic in their position (`new` in inner constructors, `ccall`'s builtin).
/// None appear in export lists, so resolution alone would flag them.
const MODULE_IMPLICIT: &[&str] = &["eval", "include", "new", "ccall"];

impl Rule for UndefinedName {
    fn id(&self) -> &'static str {
        "undefined-name"
    }

    fn default_enabled(&self) -> bool {
        // Sound only with project context: a bare file may be an `include`d
        // fragment reading its host's globals. The language server turns the
        // rule on for workspace member files; CLI users opt in for
        // self-contained scripts.
        false
    }

    fn description(&self) -> &'static str {
        "Flag an identifier that no resolution tier provides: not a local or \
         a file binding, not a workspace sibling, not a whole-module \
         `using`'s export, and not a Base/Core name. Such a read raises \
         `UndefVarError` at runtime. The whole file is skipped when it \
         `eval`s, `include`s outside a known workspace, or `using`s a module \
         the library cannot resolve — in those cases any name may exist; \
         value reads inside macro calls and quoted code are likewise exempt. \
         Off by default: the rule needs project context to be sound, so the \
         language server enables it for workspace member files, while the CLI \
         (resolving against a built-in Base/Core snapshot) leaves it opt-in \
         for self-contained scripts."
    }

    fn examples(&self) -> &'static [Example] {
        &[Example {
            caption: "`raduis` is a typo; no tier resolves it:",
            source: "function area(radius)\n    return pi * raduis^2\nend\n",
        }]
    }

    fn check_file(&self, ctx: &RuleContext<'_>, sink: &mut Vec<Diagnostic>) {
        let Some(resolution) = &ctx.resolution else {
            return;
        };
        if has_unresolvable_using(
            ctx.model,
            resolution.packages,
            resolution.workspace.as_ref(),
        ) {
            return;
        }
        let scan = FileScan::collect(ctx.root);
        if scan.calls_eval {
            return;
        }
        // With a workspace, literal includes are followed by the harvest, so
        // their definitions resolve via the workspace tier; a dynamic path
        // (or any include without a workspace) brings in unknowable names.
        if scan.dynamic_include || (resolution.workspace.is_none() && scan.literal_include) {
            return;
        }

        let resolver = Resolver::new(ctx.model, resolution.packages)
            .with_workspace(resolution.workspace.clone());
        for ident in ctx.model.idents() {
            if ident.binding.is_some() {
                continue;
            }
            if scan.in_skipped(ident.range, ident.is_macro) {
                continue;
            }
            let namespace = if ident.is_macro {
                Namespace::Macro
            } else {
                Namespace::Value
            };
            if !ident.is_macro
                && (MODULE_IMPLICIT.contains(&ident.name.as_str()) || ident.name == "_")
            {
                continue;
            }
            if resolver.resolve(&ident.name, ident.range.start(), namespace)
                == Resolution::Unresolved
            {
                let display = if ident.is_macro {
                    format!("@{}", ident.name)
                } else {
                    ident.name.to_string()
                };
                sink.push(Diagnostic::new(
                    self.id(),
                    ident.range,
                    format!("`{display}` is not defined"),
                ));
            }
        }
    }
}

/// One pass over the CST collecting everything the rule skips or bails on:
/// macro-call and quote extents, and the `eval`/`include` call shapes.
struct FileScan {
    /// `MACRO_CALL` extents. Value reads inside are exempt (the macro may
    /// bind them); the macro's own name is still checked.
    macro_calls: Vec<TextRange>,
    /// `QUOTE_EXPR` extents: quoted code is data, not reads.
    quotes: Vec<TextRange>,
    calls_eval: bool,
    literal_include: bool,
    dynamic_include: bool,
}

impl FileScan {
    fn collect(root: &SyntaxNode) -> Self {
        let mut scan = FileScan {
            macro_calls: Vec::new(),
            quotes: Vec::new(),
            calls_eval: false,
            literal_include: false,
            dynamic_include: false,
        };
        for node in root.descendants() {
            match node.kind() {
                SyntaxKind::MACRO_CALL => {
                    scan.macro_calls.push(node.text_range());
                    let name = MacroCall::cast(node)
                        .and_then(|call| call.name())
                        .and_then(|name| name.macro_token());
                    if name.is_some_and(|token| token.text() == "eval") {
                        scan.calls_eval = true;
                    }
                }
                SyntaxKind::QUOTE_EXPR => scan.quotes.push(node.text_range()),
                SyntaxKind::CALL_EXPR => {
                    let Some(call) = CallExpr::cast(node) else {
                        continue;
                    };
                    let Some(Expr::Name(callee)) = call.callee() else {
                        continue;
                    };
                    match callee.ident().map(|ident| ident.text().to_string()) {
                        Some(name) if name == "eval" => scan.calls_eval = true,
                        Some(name) if name == "include" => {
                            if include_target(&call).is_some() {
                                scan.literal_include = true;
                            } else {
                                scan.dynamic_include = true;
                            }
                        }
                        _ => {}
                    }
                }
                _ => {}
            }
        }
        scan
    }

    /// Whether the read at `range` is exempt: inside quoted code, or a value
    /// read inside a macro call (the macro name itself stays checked).
    fn in_skipped(&self, range: TextRange, is_macro: bool) -> bool {
        let within = |extents: &[TextRange]| extents.iter().any(|e| e.contains_range(range));
        within(&self.quotes) || (!is_macro && within(&self.macro_calls))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::index::model::{
        DefLocation, ExportedName, FunctionGroup, ModuleIndex, ModuleUsing, PackageIndex, Span,
        Visibility,
    };
    use crate::linter::rules::ResolutionContext;
    use crate::semantic::SemanticModel;
    use std::collections::BTreeMap;
    use std::sync::Arc;

    fn loc() -> DefLocation {
        DefLocation {
            file: "src/x.jl".into(),
            range: Span { start: 0, end: 0 },
        }
    }

    /// A library with a Base exporting `exports`, plus a workspace package
    /// `MyPkg` defining top-level functions `siblings` (unexported — the shape
    /// of a package's own globals).
    fn base(exports: &[&str]) -> BTreeMap<String, Arc<PackageIndex>> {
        let pkg = PackageIndex {
            name: "Base".to_string(),
            root: ModuleIndex {
                name: "Base".to_string(),
                bare: false,
                loc: loc(),
                exports: exports
                    .iter()
                    .map(|n| ExportedName {
                        name: n.to_string(),
                        visibility: Visibility::Exported,
                        loc: loc(),
                    })
                    .collect(),
                functions: Vec::new(),
                types: Vec::new(),
                consts: Vec::new(),
                macros: Vec::new(),
                submodules: Vec::new(),
                usings: Vec::new(),
                imported_names: Vec::new(),
            },
            members: Vec::new(),
            member_modules: Default::default(),
            diagnostics: Vec::new(),
        };
        BTreeMap::from([("Base".to_string(), Arc::new(pkg))])
    }

    fn workspace(siblings: &[&str]) -> Arc<PackageIndex> {
        Arc::new(PackageIndex {
            name: "MyPkg".to_string(),
            root: ModuleIndex {
                name: "MyPkg".to_string(),
                bare: false,
                loc: loc(),
                exports: Vec::new(),
                functions: siblings
                    .iter()
                    .map(|f| FunctionGroup {
                        name: f.to_string(),
                        owner: None,
                        methods: Vec::new(),
                        doc: None,
                    })
                    .collect(),
                types: Vec::new(),
                consts: Vec::new(),
                macros: Vec::new(),
                submodules: Vec::new(),
                usings: Vec::new(),
                imported_names: Vec::new(),
            },
            members: Vec::new(),
            member_modules: Default::default(),
            diagnostics: Vec::new(),
        })
    }

    /// A workspace package whose root module records whole-module `using` paths
    /// `usings` and module-level bound names `imported` — a sibling file's load
    /// surface, spliced into the module by `include`.
    fn workspace_with_loads(usings: &[&[&str]], imported: &[&str]) -> Arc<PackageIndex> {
        let mut pkg = (*workspace(&[])).clone();
        pkg.root.usings = usings
            .iter()
            .map(|components| ModuleUsing {
                leading_dots: 0,
                components: components.iter().map(|c| c.to_string()).collect(),
            })
            .collect();
        pkg.root.imported_names = imported.iter().map(|n| n.to_string()).collect();
        Arc::new(pkg)
    }

    /// `base` plus an extra package `name` exporting `exports`.
    fn base_plus(name: &str, exports: &[&str]) -> BTreeMap<String, Arc<PackageIndex>> {
        let mut lib = base(&[]);
        let extra = base(exports);
        let mut pkg = (*extra.get("Base").unwrap().clone()).clone();
        pkg.name = name.to_string();
        pkg.root.name = name.to_string();
        lib.insert(name.to_string(), Arc::new(pkg));
        lib
    }

    /// Lint `src` with the rule alone, against `packages` and an optional
    /// workspace package (host module = the package root).
    fn messages(
        src: &str,
        packages: &BTreeMap<String, Arc<PackageIndex>>,
        ws: Option<Arc<PackageIndex>>,
    ) -> Vec<String> {
        let parsed = crate::parser::parse(src);
        assert!(parsed.diagnostics.is_empty(), "fixture must parse clean");
        let model = SemanticModel::build(&parsed.cst);
        let ctx = RuleContext {
            path: None,
            root: &parsed.cst,
            model: &model,
            resolution: Some(ResolutionContext {
                packages,
                workspace: ws.map(|pkg| (pkg, Vec::new())),
            }),
            includes: &[],
            julia_target: None,
        };
        let mut sink = Vec::new();
        UndefinedName.check_file(&ctx, &mut sink);
        sink.into_iter().map(|d| d.message.body).collect()
    }

    #[test]
    fn qualified_base_extension_resolves_via_self_export() {
        // `function Base.show(...)` reads `Base` as a module qualifier. The
        // harvest synthesizes Base's own name into its exports (Julia never
        // `export`s it), so the read resolves — a real-world `Base.show`
        // extension must not raise `undefined-name`.
        let lib = base(&["Base", "IO", "print", "show"]);
        let src = "function Base.show(io::IO, x)\n    print(io, x)\nend\n";
        assert_eq!(
            messages(src, &lib, Some(workspace(&[]))),
            Vec::<String>::new()
        );
    }

    #[test]
    fn qualified_base_extension_flags_without_self_export() {
        // Guard on the fix: strip Base's self-name and the same qualifier read
        // is unresolved — exactly the false positive the harvest self-export
        // removes.
        let lib = base(&["IO", "print", "show"]);
        let src = "function Base.show(io::IO, x)\n    print(io, x)\nend\n";
        let msgs = messages(src, &lib, Some(workspace(&[])));
        assert_eq!(msgs, vec!["`Base` is not defined".to_string()], "{msgs:?}");
    }

    #[test]
    fn workspace_package_self_name_resolves() {
        // A file spliced into the package's root module may qualify a call with
        // the package's own name (`MyPkg.helper()`); Julia binds a module's own
        // name inside it, so the qualifier must not raise `undefined-name`.
        // Regression: SLOPE.jl's `SLOPE.fit_slope_dense(...)` inside module SLOPE.
        let lib = base(&[]);
        let msgs = messages("f() = MyPkg.helper()\n", &lib, Some(workspace(&["helper"])));
        assert_eq!(msgs, Vec::<String>::new(), "{msgs:?}");
    }

    #[test]
    fn workspace_sibling_resolves() {
        // `helper` is defined in a sibling file of the package; with the
        // workspace tier it resolves, while `helprr` stays undefined.
        let lib = base(&[]);
        let msgs = messages(
            "f() = helper() + helprr()\n",
            &lib,
            Some(workspace(&["helper"])),
        );
        assert_eq!(msgs.len(), 1, "{msgs:?}");
        assert!(msgs[0].contains("helprr"));
    }

    #[test]
    fn sibling_using_export_resolves() {
        // SLOPE.jl regression: `cv.jl` reads `SparseMatrixCSC`, which a sibling
        // `models.jl` brings in with `using SparseArrays`. The module-wide
        // `using` resolves the read, so no false `undefined-name`.
        let lib = base_plus("SparseArrays", &["SparseMatrixCSC"]);
        let ws = workspace_with_loads(&[&["SparseArrays"]], &[]);
        assert_eq!(
            messages("f(::SparseMatrixCSC) = 1\n", &lib, Some(ws)),
            Vec::<String>::new(),
        );
    }

    #[test]
    fn sibling_imported_name_resolves() {
        // A name a sibling file's `import Foo` binds is a module global here.
        let lib = base(&[]);
        let ws = workspace_with_loads(&[], &["Foo"]);
        assert_eq!(
            messages("g() = Foo.helper()\n", &lib, Some(ws)),
            Vec::<String>::new(),
        );
    }

    #[test]
    fn unresolvable_sibling_using_bails_the_file() {
        // A sibling's `using` of an unharvested package could export anything,
        // so the whole file is skipped — even a genuine typo goes unreported.
        let lib = base(&[]);
        let ws = workspace_with_loads(&[&["Unharvested"]], &[]);
        assert_eq!(
            messages("f() = mystery()\n", &lib, Some(ws)),
            Vec::<String>::new(),
        );
    }

    #[test]
    fn without_workspace_a_sibling_read_would_flag() {
        // The same source with no workspace context flags both — which is
        // exactly why the rule is gated to member files by the server and
        // opt-in on the CLI.
        let lib = base(&[]);
        let msgs = messages("f() = helper() + helprr()\n", &lib, None);
        assert_eq!(msgs.len(), 2, "{msgs:?}");
    }

    #[test]
    fn literal_include_bails_only_without_a_workspace() {
        let lib = base(&[]);
        let src = "include(\"other.jl\")\nf() = mystery()\n";
        // No workspace: the include splices unknowable names — bail.
        assert_eq!(messages(src, &lib, None), Vec::<String>::new());
        // With a workspace, the harvest followed the include; `mystery` not
        // being in the package index is a real finding.
        let msgs = messages(src, &lib, Some(workspace(&["helper"])));
        assert_eq!(msgs.len(), 1, "{msgs:?}");
        assert!(msgs[0].contains("mystery"));
    }

    #[test]
    fn dynamic_include_bails_even_with_a_workspace() {
        let lib = base(&[]);
        let src = "include(joinpath(root, \"gen.jl\"))\nf() = mystery()\n";
        assert_eq!(
            messages(src, &lib, Some(workspace(&[]))),
            Vec::<String>::new()
        );
    }

    #[test]
    fn quoted_code_is_not_read() {
        let lib = base(&[]);
        let msgs = messages(
            "ex = :(alpha + beta)\nblock = quote\n    gamma(delta)\nend\n",
            &lib,
            Some(workspace(&[])),
        );
        assert_eq!(msgs, Vec::<String>::new());
    }

    #[test]
    fn no_resolution_context_is_silent() {
        let parsed = crate::parser::parse("f() = mystery()\n");
        let model = SemanticModel::build(&parsed.cst);
        let ctx = RuleContext {
            path: None,
            root: &parsed.cst,
            model: &model,
            resolution: None,
            includes: &[],
            julia_target: None,
        };
        let mut sink = Vec::new();
        UndefinedName.check_file(&ctx, &mut sink);
        assert!(sink.is_empty());
    }
}