arity 0.5.0

An LSP, formatter, and linter for R
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
//! Symbol providers backed by the harvested index.
//!
//! - [`IndexedProvider`] resolves names against the *attached* packages it has
//!   indexed, and exposes the rich per-symbol data ([`lookup`](IndexedProvider::lookup))
//!   for future LSP features. It deliberately knows nothing about base R.
//! - [`CompositeProvider`] layers [`IndexedProvider`] over
//!   [`StaticBaseR`](crate::semantic::symbols::StaticBaseR) and implements the
//!   thin [`SymbolProvider`] trait with R's search-path masking semantics:
//!   default packages attach first, then `library()`-loaded packages in source
//!   order, and the last attacher masks.

use std::collections::{HashMap, HashSet};
use std::sync::LazyLock;

use smol_str::SmolStr;

use crate::rindex::cache::Cache;
use crate::rindex::remote::RemoteExports;
use crate::rindex::schema::{PackageIndex, SymbolEntry};
use crate::semantic::symbols::{
    BundledPackages, LoadedPackage, PackageOrigin, StaticBaseR, SymbolProvider,
};

/// R's default-package export lists. A compile-time constant (baked-in symbol
/// lists), shared process-wide so it is parsed once rather than per provider.
static BASE_R: LazyLock<StaticBaseR> = LazyLock::new(StaticBaseR::new);

/// The bundled top-N CRAN export lists. Also a compile-time constant, shared.
static BUNDLED: LazyLock<BundledPackages> = LazyLock::new(BundledPackages::new);

/// Resolve a bare `name` against R's default packages, the harvested `indexed`
/// layer, the network `remote` sidecar, and the bundled CRAN lists, honoring
/// search-path masking: default packages attach first, then `loaded` packages in
/// source order, and the last attacher masks. Per package the precedence is
/// version-exact installed index → remote sidecar (names-only, all CRAN) →
/// bundled list (names-only, baked-in top-N).
///
/// This is the single masking implementation; both [`CompositeProvider`] and the
/// salsa `external_resolution` query call it. The static layers are read from
/// the shared [`BASE_R`]/[`BUNDLED`] singletons; `indexed` and `remote` vary at
/// runtime.
pub fn resolve_origin(
    indexed: &IndexedProvider,
    remote: &RemoteExports,
    name: &str,
    loaded: &[LoadedPackage],
) -> PackageOrigin {
    // Default packages attach first.
    let mut candidates: Vec<SmolStr> = match BASE_R.origin(name, &[]) {
        PackageOrigin::Resolved(p) => vec![p],
        PackageOrigin::Ambiguous(v) => v,
        PackageOrigin::Unknown => Vec::new(),
    };
    // Then `library()`-attached packages in source order; the last attacher
    // masks. Prefer the version-exact installed index, then the remote sidecar,
    // and finally the baked-in bundled CRAN export list.
    for pkg in loaded {
        let exports_it = if indexed.has_package(&pkg.name) {
            indexed.exports(&pkg.name, name)
        } else if remote.has_package(&pkg.name) {
            remote.exports(&pkg.name, name)
        } else {
            BUNDLED.exports(&pkg.name, name)
        };
        if exports_it && !candidates.contains(&pkg.name) {
            candidates.push(pkg.name.clone());
        }
    }
    match candidates.len() {
        0 => PackageOrigin::Unknown,
        1 => PackageOrigin::Resolved(candidates.into_iter().next().unwrap()),
        _ => PackageOrigin::Ambiguous(candidates),
    }
}

/// True if `pkg`'s exports are fully known — a default package, a harvested
/// package, a remote-sidecar package, or a bundled CRAN package — so an
/// unresolved name attributed to it is genuinely undefined rather than merely
/// un-indexed.
pub fn package_indexed(indexed: &IndexedProvider, remote: &RemoteExports, pkg: &str) -> bool {
    BASE_R.package_indexed(pkg)
        || indexed.has_package(pkg)
        || remote.has_package(pkg)
        || BUNDLED.has_package(pkg)
}

/// True if `name` is exported by one of R's default packages.
pub fn is_base(name: &str) -> bool {
    BASE_R.is_base(name)
}

/// Iterate every base/default-package export name, for completion candidates.
pub fn base_names() -> impl Iterator<Item = &'static SmolStr> {
    let base: &'static StaticBaseR = &BASE_R;
    base.base_names()
}

/// The default package that exports a base `name`, if any (for `resolve` to
/// attach docs to a bare base-R completion once `base` is harvested).
pub fn base_package_of(name: &str) -> Option<&'static SmolStr> {
    let base: &'static StaticBaseR = &BASE_R;
    base.package_of(name)
}

/// Iterate a bundled CRAN package's export names, if bundled — completion's
/// member fallback when the package isn't locally harvested.
pub fn bundled_exports(package: &str) -> Option<impl Iterator<Item = &'static SmolStr>> {
    let bundled: &'static BundledPackages = &BUNDLED;
    bundled.package_exports(package)
}

/// Resolves names against indexed, attached packages and holds the rich data.
#[derive(Debug, Default)]
pub struct IndexedProvider {
    /// package → set of exported names (for `origin` membership tests).
    pkg_exports: HashMap<SmolStr, HashSet<SmolStr>>,
    /// package → full harvested index (for `lookup`).
    indices: HashMap<SmolStr, PackageIndex>,
}

impl IndexedProvider {
    pub fn empty() -> Self {
        Self::default()
    }

    /// Build from a set of harvested package indices.
    pub fn from_indices(indices: impl IntoIterator<Item = PackageIndex>) -> Self {
        let mut pkg_exports: HashMap<SmolStr, HashSet<SmolStr>> = HashMap::new();
        let mut map: HashMap<SmolStr, PackageIndex> = HashMap::new();
        for idx in indices {
            let names: HashSet<SmolStr> = idx
                .symbols
                .iter()
                .filter(|s| s.exported)
                .map(|s| s.name.clone())
                .collect();
            pkg_exports.insert(idx.package.clone(), names);
            map.insert(idx.package.clone(), idx);
        }
        IndexedProvider {
            pkg_exports,
            indices: map,
        }
    }

    /// Load every package index currently named by the cache's `meta.json`.
    pub fn from_cache(cache: &Cache) -> Self {
        Self::from_indices(cache.load_all())
    }

    /// True if this provider has an index for `package`.
    pub fn has_package(&self, package: &str) -> bool {
        self.pkg_exports.contains_key(package)
    }

    /// The rich entry for `pkg::name`, if indexed.
    pub fn lookup(&self, package: &str, name: &str) -> Option<&SymbolEntry> {
        self.indices
            .get(package)?
            .symbols
            .iter()
            .find(|s| s.name == name)
    }

    /// The full harvested index for a package, if present.
    pub fn package(&self, package: &str) -> Option<&PackageIndex> {
        self.indices.get(package)
    }

    fn exports(&self, package: &str, name: &str) -> bool {
        self.pkg_exports
            .get(package)
            .is_some_and(|set| set.contains(name))
    }
}

/// The default-package + bundled-CRAN + harvested-index resolver, honoring
/// search-path masking. Precedence per package: locally harvested index
/// (version-exact) → base defaults → bundled CRAN (approximate latest).
///
/// Holds only the harvested [`IndexedProvider`]; the static default-package and
/// bundled-CRAN layers live in the shared [`BASE_R`]/[`BUNDLED`] singletons, and
/// all three are combined by the free [`resolve_origin`]/[`package_indexed`]
/// functions — the same ones the salsa `external_resolution` query uses.
#[derive(Debug)]
pub struct CompositeProvider {
    indexed: IndexedProvider,
    remote: RemoteExports,
}

impl CompositeProvider {
    /// No local index — base defaults plus the bundled CRAN export lists.
    pub fn base_only() -> Self {
        CompositeProvider {
            indexed: IndexedProvider::empty(),
            remote: RemoteExports::new(),
        }
    }

    pub fn with_index(indexed: IndexedProvider) -> Self {
        CompositeProvider {
            indexed,
            remote: RemoteExports::new(),
        }
    }

    /// Attach a remote-sidecar tier (builder style).
    pub fn with_remote(mut self, remote: RemoteExports) -> Self {
        self.remote = remote;
        self
    }

    /// The indexed layer, for callers that need the rich data (e.g. the LSP).
    pub fn indexed(&self) -> &IndexedProvider {
        &self.indexed
    }
}

impl SymbolProvider for CompositeProvider {
    fn origin(&self, name: &str, loaded: &[LoadedPackage]) -> PackageOrigin {
        resolve_origin(&self.indexed, &self.remote, name, loaded)
    }

    fn is_base(&self, name: &str) -> bool {
        is_base(name)
    }

    fn package_indexed(&self, pkg: &str) -> bool {
        package_indexed(&self.indexed, &self.remote, pkg)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rindex::schema::{SCHEMA_VERSION, SymbolKind};
    use rowan::{TextRange, TextSize};

    fn pkg(name: &str, exports: &[&str]) -> PackageIndex {
        PackageIndex {
            schema_version: SCHEMA_VERSION,
            package: SmolStr::new(name),
            version: SmolStr::new("1.0"),
            lib_path: "/lib".into(),
            r_version: None,
            harvested_at: 0,
            symbols: exports
                .iter()
                .map(|n| SymbolEntry {
                    name: SmolStr::new(*n),
                    kind: SymbolKind::Function,
                    exported: true,
                    formals: None,
                    help: None,
                })
                .collect(),
        }
    }

    fn loaded(name: &str) -> LoadedPackage {
        LoadedPackage {
            name: SmolStr::new(name),
            range: TextRange::new(TextSize::new(0), TextSize::new(0)),
        }
    }

    #[test]
    fn is_base_delegates_to_base_only() {
        let p = CompositeProvider::with_index(IndexedProvider::from_indices([pkg(
            "dplyr",
            &["across"],
        )]));
        assert!(p.is_base("c"));
        // An indexed-only package export is not "base".
        assert!(!p.is_base("across"));
    }

    #[test]
    fn loaded_package_masks_base_name() {
        // `filter` exists in stats (base set) and dplyr; with dplyr attached it
        // should be Ambiguous with dplyr masking (last).
        let p = CompositeProvider::with_index(IndexedProvider::from_indices([pkg(
            "dplyr",
            &["filter"],
        )]));
        match p.origin("filter", &[loaded("dplyr")]) {
            PackageOrigin::Ambiguous(v) => {
                assert_eq!(v.last().map(|s| s.as_str()), Some("dplyr"));
                assert!(v.iter().any(|s| s == "stats"));
            }
            other => panic!("expected Ambiguous, got {other:?}"),
        }
    }

    #[test]
    fn resolves_indexed_only_name() {
        let p = CompositeProvider::with_index(IndexedProvider::from_indices([pkg(
            "dplyr",
            &["across"],
        )]));
        // `across` is not a base name; attaching dplyr resolves it.
        assert_eq!(
            p.origin("across", &[loaded("dplyr")]),
            PackageOrigin::Resolved(SmolStr::new("dplyr"))
        );
    }

    #[test]
    fn unindexed_unbundled_loaded_package_leaves_name_unknown() {
        let p = CompositeProvider::base_only();
        // A package that is neither indexed nor bundled: a name only it would
        // export stays Unknown (conservative whole-file suppression still
        // applies via `package_indexed`).
        assert!(!p.package_indexed("not_a_real_package_xyz"));
        assert_eq!(
            p.origin("some_export_xyz", &[loaded("not_a_real_package_xyz")]),
            PackageOrigin::Unknown
        );
    }

    #[test]
    fn bundled_package_is_indexed_and_resolves() {
        // No local index: the bundled CRAN list backs resolution.
        let p = CompositeProvider::base_only();
        assert!(p.package_indexed("data.table"));
        assert_eq!(
            p.origin("fread", &[loaded("data.table")]),
            PackageOrigin::Resolved(SmolStr::new("data.table"))
        );
        // An unknown name with a bundled package attached stays Unknown, so
        // `undefined-symbol` can fire on it.
        assert_eq!(
            p.origin("not_a_real_export_xyz", &[loaded("data.table")]),
            PackageOrigin::Unknown
        );
    }

    #[test]
    fn installed_index_wins_over_bundled() {
        // An installed index for a bundled package is version-exact and takes
        // precedence: its export resolves, and a name only the (stale) bundled
        // list has does not.
        let p = CompositeProvider::with_index(IndexedProvider::from_indices([pkg(
            "data.table",
            &["custom_installed_sym"],
        )]));
        assert_eq!(
            p.origin("custom_installed_sym", &[loaded("data.table")]),
            PackageOrigin::Resolved(SmolStr::new("data.table"))
        );
        assert_eq!(
            p.origin("fread", &[loaded("data.table")]),
            PackageOrigin::Unknown
        );
    }

    fn remote(pkgs: &[(&str, &[&str])]) -> RemoteExports {
        let mut r = RemoteExports::new();
        for (pkg, names) in pkgs {
            r.insert_package(*pkg, names.iter().map(|n| SmolStr::new(*n)));
        }
        r
    }

    #[test]
    fn remote_resolves_uninstalled_unbundled_package() {
        // `tinytable` is neither installed nor in the bundled top-N; the remote
        // sidecar supplies its names so a real export resolves and `package_indexed`
        // is true (so `undefined-symbol` fires on a genuine non-export).
        let p = CompositeProvider::base_only().with_remote(remote(&[("tinytable", &["tt"])]));
        assert!(p.package_indexed("tinytable"));
        assert_eq!(
            p.origin("tt", &[loaded("tinytable")]),
            PackageOrigin::Resolved(SmolStr::new("tinytable"))
        );
        assert_eq!(
            p.origin("not_a_real_export", &[loaded("tinytable")]),
            PackageOrigin::Unknown
        );
    }

    #[test]
    fn installed_index_wins_over_remote() {
        // A version-exact local index masks the names-only remote tier for the
        // same package: the installed export resolves, a remote-only name does not.
        let p = CompositeProvider::with_index(IndexedProvider::from_indices([pkg(
            "tinytable",
            &["installed_sym"],
        )]))
        .with_remote(remote(&[("tinytable", &["remote_only_sym"])]));
        assert_eq!(
            p.origin("installed_sym", &[loaded("tinytable")]),
            PackageOrigin::Resolved(SmolStr::new("tinytable"))
        );
        assert_eq!(
            p.origin("remote_only_sym", &[loaded("tinytable")]),
            PackageOrigin::Unknown
        );
    }

    #[test]
    fn remote_wins_over_bundled() {
        // The remote tier sits above the baked-in bundled list: for a bundled
        // package, the remote names take precedence (fresher, version-aware).
        // `fread` is a real bundled `data.table` export; the remote omits it.
        let p = CompositeProvider::base_only().with_remote(remote(&[("data.table", &["new_sym"])]));
        assert_eq!(
            p.origin("new_sym", &[loaded("data.table")]),
            PackageOrigin::Resolved(SmolStr::new("data.table"))
        );
        assert_eq!(
            p.origin("fread", &[loaded("data.table")]),
            PackageOrigin::Unknown
        );
    }

    #[test]
    fn lookup_exposes_rich_data() {
        let provider = IndexedProvider::from_indices([pkg("dplyr", &["filter"])]);
        assert!(provider.lookup("dplyr", "filter").is_some());
        assert!(provider.lookup("dplyr", "nope").is_none());
        assert!(provider.has_package("dplyr"));
    }
}