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
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Code completion: scope-aware bare names (locals + attached-package exports +
//! base R) and `pkg::`/`pkg:::` member completion, backed by the harvested
//! index. Items carry only a label + identity; docs/signature are attached
//! lazily on `completionItem/resolve`.
//!
//! Mirrors the hover read path: [`completion_via_db`] resolves off the snapshot's
//! cached parse when the tracked buffer matches, else re-parses; [`compute_completions`]
//! is the pure, parse-from-text wrapper used by tests. Completion stays strictly
//! read-only — an unharvested package degrades to the bundled names-only list,
//! and the normal lint cycle harvests `referenced_packages` so a later request
//! sees rich data.

use super::*;

/// Identity carried on a completion item (serialized into `CompletionItem.data`)
/// so `completionItem/resolve` can attach docs without the original document.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "t")]
enum CompletionData {
    /// A namespaced or attached-package symbol; resolve via `indexed.lookup`.
    Member { package: SmolStr, name: SmolStr },
    /// A bare base-R name; resolve via the base name→package map then lookup.
    Bare { name: SmolStr },
    /// A scope local; nothing to attach.
    Local,
}

/// What the cursor is positioned to complete.
enum CompletionContext {
    /// After `pkg::` / `pkg:::`, optionally with a partial member name.
    Member {
        package: SmolStr,
        internal: bool,
        prefix: String,
    },
    /// A bare identifier with a (possibly empty) typed prefix.
    Bare { prefix: String, offset: TextSize },
    /// Inside a string/comment, or nothing to complete.
    None,
}

/// A gathered candidate before it becomes a `CompletionItem`. `sort_group`
/// orders the buckets (0 locals, 1 attached lib, 2 base, 3 member).
struct Candidate {
    label: String,
    kind: CompletionItemKind,
    sort_group: u8,
    data: CompletionData,
}

/// Resolve completion off the snapshot's cached parse when the db's tracked
/// buffer for `path` still matches `text`; otherwise re-parse. Falls back on
/// cancellation. The harvested index comes from the same snapshot.
pub(crate) fn completion_via_db(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    position: Position,
) -> Option<CompletionResponse> {
    let line_index = LineIndex::new(text);
    let offset = TextSize::new(line_index.position_to_byte(position).min(text.len()) as u32);
    let index = snapshot.library_data().unwrap_or_default();
    let remote = snapshot.remote_exports().unwrap_or_default();
    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        let file = snapshot.lookup_file(path)?;
        if snapshot.file_text(file) != text {
            return None;
        }
        let root = snapshot.parsed_tree(file);
        Some(completions_from_node(&root, offset, &index, &remote))
    }));
    match cached {
        Ok(Some(resp)) => resp,
        Ok(None) | Err(_) => {
            let root = parse(text).cst;
            completions_from_node(&root, offset, &index, &remote)
        }
    }
}

/// Build completions at byte `offset`. Pure (parses `text` itself) so it is
/// unit-testable; the LSP read path uses [`completion_via_db`].
pub fn compute_completions(
    text: &str,
    offset: usize,
    indexed: &IndexedProvider,
) -> Option<CompletionResponse> {
    let root = parse(text).cst;
    let offset = TextSize::new(offset.min(text.len()) as u32);
    completions_from_node(&root, offset, indexed, &RemoteExports::new())
}

/// Attach documentation + signature to a resolved completion item, using the
/// identity stashed in its `data`. Returns the item unchanged when there is
/// nothing to attach (a local, an unindexed symbol, or malformed `data`).
pub fn resolve_completion(mut item: CompletionItem, indexed: &IndexedProvider) -> CompletionItem {
    let Some(data) = item
        .data
        .clone()
        .and_then(|v| serde_json::from_value::<CompletionData>(v).ok())
    else {
        return item;
    };
    let resolved = match &data {
        CompletionData::Member { package, name } => indexed
            .lookup(package, name)
            .map(|entry| (package.clone(), entry)),
        CompletionData::Bare { name } => base_package_of(name)
            .and_then(|pkg| indexed.lookup(pkg, name).map(|entry| (pkg.clone(), entry))),
        CompletionData::Local => None,
    };
    if let Some((package, entry)) = resolved {
        item.documentation = Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: render_hover_markdown(&package, entry),
        }));
        item.detail = signature_of(entry);
    }
    item
}

/// Build completions off an already-parsed CST.
pub(crate) fn completions_from_node(
    root: &SyntaxNode,
    offset: TextSize,
    indexed: &IndexedProvider,
    remote: &RemoteExports,
) -> Option<CompletionResponse> {
    match classify_context(root, offset) {
        CompletionContext::None => None,
        CompletionContext::Member {
            package,
            internal,
            prefix,
        } => Some(build_response(
            member_candidates(indexed, remote, &package, internal),
            &prefix,
            true,
        )),
        CompletionContext::Bare { prefix, offset } => Some(build_response(
            bare_candidates(root, offset, indexed, remote),
            &prefix,
            false,
        )),
    }
}

/// Classify what the cursor at `offset` is positioned to complete.
fn classify_context(root: &SyntaxNode, offset: TextSize) -> CompletionContext {
    if in_string_or_comment(root, offset) {
        return CompletionContext::None;
    }
    if let Some((package, internal, prefix)) = member_context(root, offset) {
        return CompletionContext::Member {
            package,
            internal,
            prefix,
        };
    }
    bare_context(root, offset)
}

/// True when the cursor sits inside a string or comment (no completion there).
fn in_string_or_comment(root: &SyntaxNode, offset: TextSize) -> bool {
    let bad = |k: SyntaxKind| matches!(k, SyntaxKind::STRING | SyntaxKind::COMMENT);
    match root.token_at_offset(offset) {
        TokenAtOffset::None => false,
        TokenAtOffset::Single(t) => bad(t.kind()),
        // A boundary: the cursor is typing into the left token. Only comments
        // (which run to end of line) keep us "inside" at their trailing edge.
        TokenAtOffset::Between(left, _) => left.kind() == SyntaxKind::COMMENT,
    }
}

/// Detect a `pkg::`/`pkg:::` member-completion context: either a partial RHS
/// name, or a just-typed operator with nothing after it.
fn member_context(root: &SyntaxNode, offset: TextSize) -> Option<(SmolStr, bool, String)> {
    // Partial name: the cursor is on the RHS name of a `pkg::name` access.
    if let Some(token) = pick_name_token(root, offset) {
        for ancestor in token.parent_ancestors() {
            if ancestor.kind() == SyntaxKind::BINARY_EXPR
                && let Some(access) = BinaryExpr::cast(ancestor).and_then(|b| b.namespace_access())
                && access.name_token == token
            {
                return Some((
                    access.package,
                    access.internal,
                    prefix_in_token(&token, offset),
                ));
            }
        }
    }
    // Just-typed `pkg::` with no RHS yet: recover via a token-level left-scan.
    recover_namespace_at(root, offset).map(|(pkg, internal)| (pkg, internal, String::new()))
}

/// Recover the package + operator kind when the cursor follows a `::`/`:::`
/// that has no right-hand side yet (so no clean `BINARY_EXPR` formed).
fn recover_namespace_at(root: &SyntaxNode, offset: TextSize) -> Option<(SmolStr, bool)> {
    let left = match root.token_at_offset(offset) {
        TokenAtOffset::Single(t) => Some(t),
        TokenAtOffset::Between(l, _) => Some(l),
        TokenAtOffset::None => None,
    }?;
    let op = skip_trivia_left(left)?;
    let internal = match op.kind() {
        SyntaxKind::COLON2 => false,
        SyntaxKind::COLON3 => true,
        _ => return None,
    };
    let pkg = prev_non_trivia(&op)?;
    if !matches!(pkg.kind(), SyntaxKind::IDENT | SyntaxKind::STRING) {
        return None;
    }
    Some((token_text_unquoted(&pkg), internal))
}

/// Bare-name context, unless the cursor is on the package operand of a
/// `pkg::name` access (we never complete package names).
fn bare_context(root: &SyntaxNode, offset: TextSize) -> CompletionContext {
    if let Some(token) = pick_name_token(root, offset) {
        for ancestor in token.parent_ancestors() {
            if ancestor.kind() == SyntaxKind::BINARY_EXPR
                && let Some(access) = BinaryExpr::cast(ancestor).and_then(|b| b.namespace_access())
                && access.package_token == token
            {
                return CompletionContext::None;
            }
        }
        return CompletionContext::Bare {
            prefix: prefix_in_token(&token, offset),
            offset,
        };
    }
    // No name under the cursor (blank space, after an operator): allow an
    // explicit, empty-prefix invocation.
    CompletionContext::Bare {
        prefix: String::new(),
        offset,
    }
}

/// Exported (or, for `:::`, all) symbols of `package`. Falls back through the
/// names-only tiers when the package isn't locally harvested: the remote sidecar
/// first, then the baked-in bundled list. The names-only tiers carry only
/// exports, so `:::` cannot surface internals there.
fn member_candidates(
    indexed: &IndexedProvider,
    remote: &RemoteExports,
    package: &str,
    internal: bool,
) -> Vec<Candidate> {
    if let Some(pkg) = indexed.package(package) {
        return pkg
            .symbols
            .iter()
            .filter(|s| internal || s.exported)
            .map(|s| Candidate {
                label: s.name.to_string(),
                kind: kind_of(s.kind),
                sort_group: 3,
                data: CompletionData::Member {
                    package: SmolStr::new(package),
                    name: s.name.clone(),
                },
            })
            .collect();
    }
    let names = remote
        .package_exports(package)
        .map(|it| it.collect::<Vec<_>>())
        .or_else(|| bundled_exports(package).map(|it| it.collect::<Vec<_>>()));
    match names {
        Some(names) => names
            .into_iter()
            .map(|n| Candidate {
                label: n.to_string(),
                kind: CompletionItemKind::FUNCTION,
                sort_group: 3,
                data: CompletionData::Member {
                    package: SmolStr::new(package),
                    name: n.clone(),
                },
            })
            .collect(),
        None => Vec::new(),
    }
}

/// Bare-name candidates: scope-visible locals, attached-package exports, and
/// base-R default-package names.
fn bare_candidates(
    root: &SyntaxNode,
    offset: TextSize,
    indexed: &IndexedProvider,
    remote: &RemoteExports,
) -> Vec<Candidate> {
    let model = SemanticModel::build(root);
    let mut out: Vec<Candidate> = Vec::new();

    // 1. Scope-visible locals.
    for (name, _kind) in model.names_in_scope_at(offset) {
        out.push(Candidate {
            label: name.to_string(),
            kind: CompletionItemKind::VARIABLE,
            sort_group: 0,
            data: CompletionData::Local,
        });
    }

    // 2. Exports of `library()`-attached packages.
    for pkg in model.loaded_packages() {
        if let Some(idx) = indexed.package(&pkg.name) {
            out.extend(
                idx.symbols
                    .iter()
                    .filter(|s| s.exported)
                    .map(|s| Candidate {
                        label: s.name.to_string(),
                        kind: kind_of(s.kind),
                        sort_group: 1,
                        data: CompletionData::Member {
                            package: pkg.name.clone(),
                            name: s.name.clone(),
                        },
                    }),
            );
        } else if let Some(names) = remote
            .package_exports(&pkg.name)
            .map(|it| it.collect::<Vec<_>>())
            .or_else(|| bundled_exports(&pkg.name).map(|it| it.collect::<Vec<_>>()))
        {
            out.extend(names.into_iter().map(|n| Candidate {
                label: n.to_string(),
                kind: CompletionItemKind::FUNCTION,
                sort_group: 1,
                data: CompletionData::Member {
                    package: pkg.name.clone(),
                    name: n.clone(),
                },
            }));
        }
    }

    // 3. Base-R default-package names.
    out.extend(base_names().map(|name| Candidate {
        label: name.to_string(),
        kind: CompletionItemKind::FUNCTION,
        sort_group: 2,
        data: CompletionData::Bare { name: name.clone() },
    }));

    out
}

/// Prefix-filter, dedup (lowest `sort_group` wins per label), and assemble the
/// response. Bare lists are marked incomplete (filtered from a large universe)
/// so the client re-queries as typing continues.
fn build_response(mut cands: Vec<Candidate>, prefix: &str, member: bool) -> CompletionResponse {
    if !prefix.is_empty() {
        cands.retain(|c| c.label.starts_with(prefix));
    }
    // Sort by label then group so the first of each label run is the lowest
    // group; dedup keeps that one (e.g. a local masks the base name once).
    cands.sort_by(|a, b| a.label.cmp(&b.label).then(a.sort_group.cmp(&b.sort_group)));
    cands.dedup_by(|a, b| a.label == b.label);
    let items = cands
        .into_iter()
        .map(|c| CompletionItem {
            sort_text: Some(format!("{}{}", c.sort_group, c.label)),
            filter_text: Some(c.label.clone()),
            kind: Some(c.kind),
            data: serde_json::to_value(c.data).ok(),
            label: c.label,
            ..Default::default()
        })
        .collect();
    CompletionResponse::List(CompletionList {
        is_incomplete: !member,
        items,
    })
}

fn kind_of(kind: SymbolKind) -> CompletionItemKind {
    match kind {
        SymbolKind::Function => CompletionItemKind::FUNCTION,
        SymbolKind::Data => CompletionItemKind::VALUE,
        SymbolKind::Other => CompletionItemKind::FIELD,
    }
}

/// The token text up to `offset` — the prefix the user has typed so far.
fn prefix_in_token(token: &SyntaxToken<RLanguage>, offset: TextSize) -> String {
    let start = token.text_range().start();
    let rel = offset.checked_sub(start).map_or(0, u32::from) as usize;
    let text = token.text();
    text.get(..rel.min(text.len())).unwrap_or(text).to_string()
}

/// The unquoted name a token denotes (raw `IDENT`, or quoted `STRING` contents).
fn token_text_unquoted(token: &SyntaxToken<RLanguage>) -> SmolStr {
    if token.kind() == SyntaxKind::STRING {
        let text = token.text();
        if text.len() >= 2 {
            return SmolStr::new(&text[1..text.len() - 1]);
        }
    }
    SmolStr::new(token.text())
}

fn is_trivia_kind(kind: SyntaxKind) -> bool {
    matches!(
        kind,
        SyntaxKind::WHITESPACE | SyntaxKind::NEWLINE | SyntaxKind::COMMENT
    )
}

/// `token`, or the nearest preceding non-trivia token in document order.
fn skip_trivia_left(token: SyntaxToken<RLanguage>) -> Option<SyntaxToken<RLanguage>> {
    let mut cur = Some(token);
    while let Some(t) = cur {
        if !is_trivia_kind(t.kind()) {
            return Some(t);
        }
        cur = t.prev_token();
    }
    None
}

/// The nearest non-trivia token strictly before `token` in document order.
fn prev_non_trivia(token: &SyntaxToken<RLanguage>) -> Option<SyntaxToken<RLanguage>> {
    let mut cur = token.prev_token();
    while let Some(t) = cur {
        if !is_trivia_kind(t.kind()) {
            return Some(t);
        }
        cur = t.prev_token();
    }
    None
}

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

    fn items(resp: CompletionResponse) -> Vec<CompletionItem> {
        match resp {
            CompletionResponse::Array(v) => v,
            CompletionResponse::List(l) => l.items,
        }
    }

    fn labels(resp: CompletionResponse) -> Vec<String> {
        items(resp).into_iter().map(|i| i.label).collect()
    }

    fn at_end(src: &str, needle: &str) -> usize {
        src.find(needle).expect("needle present") + needle.len()
    }

    fn provider_with_unexported() -> IndexedProvider {
        let idx = PackageIndex {
            schema_version: SCHEMA_VERSION,
            package: "pkg".into(),
            version: "1.0".into(),
            lib_path: "/lib".into(),
            r_version: None,
            harvested_at: 0,
            symbols: vec![
                SymbolEntry {
                    name: "pub_fn".into(),
                    kind: SymbolKind::Function,
                    exported: true,
                    formals: None,
                    help: None,
                },
                SymbolEntry {
                    name: "priv_fn".into(),
                    kind: SymbolKind::Function,
                    exported: false,
                    formals: None,
                    help: None,
                },
            ],
        };
        IndexedProvider::from_indices([idx])
    }

    #[test]
    fn member_completion_after_pkg_colons() {
        // `dplyr::` with nothing after: the parse-recovery left-scan finds the
        // package and lists its exports.
        let src = "dplyr::\n";
        let got = labels(compute_completions(src, at_end(src, "::"), &indexed_dplyr()).unwrap());
        assert!(got.contains(&"across".to_string()), "{got:?}");
    }

    #[test]
    fn member_completion_with_partial_prefix() {
        let p = indexed_dplyr();
        let hit = "dplyr::acr\n";
        assert!(
            labels(compute_completions(hit, at_end(hit, "acr"), &p).unwrap())
                .contains(&"across".to_string())
        );
        let miss = "dplyr::zzz\n";
        assert!(labels(compute_completions(miss, at_end(miss, "zzz"), &p).unwrap()).is_empty());
    }

    #[test]
    fn member_internal_includes_unexported() {
        let p = provider_with_unexported();
        let public = labels(compute_completions("pkg::\n", at_end("pkg::\n", "::"), &p).unwrap());
        assert!(public.contains(&"pub_fn".to_string()));
        assert!(!public.contains(&"priv_fn".to_string()), "{public:?}");
        let internal =
            labels(compute_completions("pkg:::\n", at_end("pkg:::\n", ":::"), &p).unwrap());
        assert!(internal.contains(&"pub_fn".to_string()));
        assert!(internal.contains(&"priv_fn".to_string()), "{internal:?}");
    }

    #[test]
    fn member_falls_back_to_bundled() {
        // data.table isn't harvested into `indexed`, so the bundled names-only
        // list backs member completion.
        let src = "data.table::\n";
        let got =
            labels(compute_completions(src, at_end(src, "::"), &IndexedProvider::empty()).unwrap());
        assert!(got.contains(&"fread".to_string()), "{got:?}");
    }

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

    fn labels_with_remote(src: &str, needle: &str, remote: &RemoteExports) -> Vec<String> {
        let root = parse(src).cst;
        let offset = TextSize::new(at_end(src, needle) as u32);
        labels(completions_from_node(&root, offset, &IndexedProvider::empty(), remote).unwrap())
    }

    #[test]
    fn member_uses_remote_for_uninstalled_unbundled_package() {
        // `tinytable` is neither harvested nor bundled; the remote sidecar backs
        // `pkg::` member completion.
        let got = labels_with_remote(
            "tinytable::\n",
            "::",
            &remote("tinytable", &["tt", "theme_tt"]),
        );
        assert!(got.contains(&"tt".to_string()), "{got:?}");
        assert!(got.contains(&"theme_tt".to_string()), "{got:?}");
    }

    #[test]
    fn bare_uses_remote_for_attached_uninstalled_package() {
        let got = labels_with_remote(
            "library(tinytable)\ntt\n",
            "\ntt",
            &remote("tinytable", &["tt"]),
        );
        assert!(got.contains(&"tt".to_string()), "{got:?}");
    }

    #[test]
    fn bare_prefix_includes_local_and_base() {
        // `v` matches the local `value` (group 0) and base names like `vector`
        // (group 2); the local sorts ahead of base.
        let src = "value <- 1\nv\n";
        let off = src.rfind('v').unwrap() + 1;
        let its = items(compute_completions(src, off, &IndexedProvider::empty()).unwrap());
        let value = its
            .iter()
            .find(|i| i.label == "value")
            .expect("local value");
        assert_eq!(value.kind, Some(CompletionItemKind::VARIABLE));
        assert!(value.sort_text.as_deref().unwrap().starts_with('0'));
        assert!(its.iter().any(|i| i.label == "vector"), "a base name");
    }

    #[test]
    fn bare_local_masks_base_duplicate() {
        // A local named `mean` appears once, attributed to the local (group 0),
        // not the base function.
        let src = "mean <- 1\nmea\n";
        let off = at_end(src, "mea");
        let its = items(compute_completions(src, off, &IndexedProvider::empty()).unwrap());
        let means: Vec<_> = its.iter().filter(|i| i.label == "mean").collect();
        assert_eq!(means.len(), 1, "one `mean`: {its:?}");
        assert!(means[0].sort_text.as_deref().unwrap().starts_with('0'));
    }

    #[test]
    fn bare_includes_attached_export() {
        let src = "library(dplyr)\nacr\n";
        let got = labels(compute_completions(src, at_end(src, "acr"), &indexed_dplyr()).unwrap());
        assert!(got.contains(&"across".to_string()), "{got:?}");
    }

    #[test]
    fn locals_respect_scope() {
        // `a` (param of f) completes inside f but not g; `b` only inside g.
        let src = "f <- function(a) {\n  \n}\ng <- function(b) {\n  b\n}\n";
        let off_f = src.find("  \n").unwrap() + 2;
        let in_f = labels(compute_completions(src, off_f, &IndexedProvider::empty()).unwrap());
        assert!(in_f.contains(&"a".to_string()), "f sees a: {in_f:?}");
        assert!(!in_f.contains(&"b".to_string()), "f hides b: {in_f:?}");
    }

    #[test]
    fn no_completion_in_string() {
        let src = "x <- \"dpl\"\n";
        let off = src.find("dpl").unwrap() + 1;
        assert!(compute_completions(src, off, &documented_dplyr()).is_none());
    }

    #[test]
    fn no_completion_in_comment() {
        let src = "# dplyr::acr\n";
        assert!(compute_completions(src, at_end(src, "acr"), &indexed_dplyr()).is_none());
    }

    #[test]
    fn resolve_attaches_docs() {
        let item = CompletionItem {
            label: "across".into(),
            data: serde_json::to_value(CompletionData::Member {
                package: "dplyr".into(),
                name: "across".into(),
            })
            .ok(),
            ..Default::default()
        };
        let resolved = resolve_completion(item, &documented_dplyr());
        let doc = match resolved.documentation {
            Some(Documentation::MarkupContent(m)) => m.value,
            other => panic!("expected markdown, got {other:?}"),
        };
        assert!(doc.contains("dplyr::across"), "{doc}");
        assert_eq!(resolved.detail.as_deref(), Some("across(.cols, .fns)"));
    }

    #[test]
    fn resolve_local_unchanged() {
        let item = CompletionItem {
            label: "x".into(),
            data: serde_json::to_value(CompletionData::Local).ok(),
            ..Default::default()
        };
        let resolved = resolve_completion(item, &documented_dplyr());
        assert!(resolved.documentation.is_none());
        assert!(resolved.detail.is_none());
    }
}