arity 0.17.0

A language server, 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
//! Static discovery of roxygen2's package-wide options from `DESCRIPTION`.
//!
//! roxygen2 (7.3.3, `R/options.R`) resolves its options by evaluating the
//! `Roxygen` field of `DESCRIPTION` as an R expression (conventionally
//! `list(markdown = TRUE)`), overlaying the value of `man/roxygen/meta.R`
//! (sourced; its last expression's value) via `modifyList(desc, meta)`, and
//! falling back to defaults — `markdown = FALSE`.
//!
//! Arity's semantics stay **static** (no R evaluation), so this module
//! approximates that resolution by parsing the same texts with arity's own
//! parser and reading the `markdown` argument only when it is a literal
//! `TRUE`/`FALSE` in a plain `list(...)` call. Anything dynamic (a variable, a
//! computed list, an unparseable field) resolves to "unknown", which falls
//! through to the next layer exactly like an absent key would: an unknown
//! `meta.R` defers to the `DESCRIPTION` field, and an unknown field defers to
//! roxygen2's off default. The approximation therefore only misses packages
//! that compute their markdown flag at roxygenize time — it never *invents* a
//! markdown default.

use std::path::Path;

use crate::ast::{Arg, AstNode, CallExpr, HasArgList};
use crate::config::CompatVersion;
use crate::parser::parse;
use crate::project::scope::package_root;
use crate::rindex::harvest::parse_dcf;
use crate::syntax::SyntaxKind;

/// The package-wide roxygen markdown default for the package at `root`
/// (a directory holding `DESCRIPTION`): `man/roxygen/meta.R` when statically
/// resolvable, else the `Roxygen` field of `DESCRIPTION`, else `false`
/// (roxygen2's default). Touches disk.
pub fn roxygen_markdown_default(root: &Path) -> bool {
    let desc = std::fs::read_to_string(root.join("DESCRIPTION"))
        .ok()
        .and_then(|text| roxygen_field(&text))
        .and_then(|expr| markdown_from_r_text(&expr));
    let meta = std::fs::read_to_string(root.join("man/roxygen/meta.R"))
        .ok()
        .and_then(|text| markdown_from_r_text(&text));
    meta.or(desc).unwrap_or(false)
}

/// [`roxygen_markdown_default`] resolved for a single file: walk up to the
/// enclosing package root (`DESCRIPTION` + `R/`). A loose file outside any
/// package keeps roxygen2's off default. Touches disk.
pub fn roxygen_markdown_default_for_file(path: &Path) -> bool {
    package_root(path).is_some_and(|root| roxygen_markdown_default(&root))
}

/// [`roxygen_markdown_default_for_file`] anchored at a directory instead of a
/// file — for stdin input, where the only location is the working directory.
/// The walk starts at `dir` itself (a `package_root` walk starts at the
/// argument's parent). Touches disk.
pub fn roxygen_markdown_default_for_dir(dir: &Path) -> bool {
    roxygen_markdown_default_for_file(&dir.join("_stdin_.R"))
}

/// A per-directory-memoized [`roxygen_markdown_default_for_file`], for batch
/// walks (format/lint over a package) where every file in `R/` would otherwise
/// re-walk to the root and re-read `DESCRIPTION`. Two files sharing a parent
/// directory always share a package root, so the memo key is the parent.
#[derive(Debug, Default)]
pub struct MarkdownDefaultResolver {
    by_dir: std::collections::HashMap<std::path::PathBuf, bool>,
}

impl MarkdownDefaultResolver {
    pub fn new() -> Self {
        Self::default()
    }

    /// The markdown default for `file`, resolved once per parent directory.
    pub fn resolve(&mut self, file: &Path) -> bool {
        match file.parent() {
            Some(dir) => *self
                .by_dir
                .entry(dir.to_path_buf())
                .or_insert_with(|| roxygen_markdown_default_for_file(file)),
            None => false,
        }
    }
}

/// The name declared by the `Package` field of the DESCRIPTION at `root`
/// (a directory holding one). `None` when there is no readable DESCRIPTION or
/// it declares no `Package`. Touches disk.
pub fn package_name(root: &Path) -> Option<String> {
    let text = std::fs::read_to_string(root.join("DESCRIPTION")).ok()?;
    parse_dcf(&text)
        .into_iter()
        .find(|(key, _)| key == "Package")
        .map(|(_, value)| value)
        .filter(|name| !name.is_empty())
}

/// [`package_name`] resolved for a single file: walk up to the enclosing
/// package root (`DESCRIPTION` + `R/`) and read its `Package` field. `None` for
/// a loose file outside any package. Touches disk.
///
/// Note the walk anchors on [`package_root`], which requires an `R/` directory,
/// so a file under `tests/testthat/` of a package resolves to that package —
/// which is exactly the case that matters for `internal-function`.
pub fn package_name_for_file(path: &Path) -> Option<String> {
    package_root(path).and_then(|root| package_name(&root))
}

/// The `Roxygen` field's value from DESCRIPTION text (continuation lines
/// joined), if present.
fn roxygen_field(description: &str) -> Option<String> {
    parse_dcf(description)
        .into_iter()
        .find(|(key, _)| key == "Roxygen")
        .map(|(_, value)| value)
}

/// The tool-version facts a package's `DESCRIPTION` declares, for the
/// version-aware lint rules' compat floors (see `config::CompatConfig`, whose
/// explicit keys override these).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DescriptionCompat {
    /// The R floor from `Depends: R (>= x.y)` (a `>` constraint counts too —
    /// close enough for a floor).
    pub r: Option<CompatVersion>,
    /// The roxygen2 version the package documents with:
    /// `Config/roxygen2/version` (written by roxygen2 >= 8.0.0), then the
    /// legacy `RoxygenNote`.
    pub roxygen2: Option<CompatVersion>,
}

/// Read the [`DescriptionCompat`] facts of the package at `root` (a directory
/// holding `DESCRIPTION`). One disk read for both fields; all-`None` when
/// there is no readable `DESCRIPTION`. Touches disk.
pub fn description_compat(root: &Path) -> DescriptionCompat {
    let Ok(text) = std::fs::read_to_string(root.join("DESCRIPTION")) else {
        return DescriptionCompat::default();
    };
    let fields = parse_dcf(&text);
    let get = |name: &str| {
        fields
            .iter()
            .find(|(key, _)| key == name)
            .map(|(_, value)| value.as_str())
    };
    DescriptionCompat {
        r: get("Depends").and_then(r_depends_floor),
        roxygen2: get("Config/roxygen2/version")
            .or_else(|| get("RoxygenNote"))
            .and_then(|v| CompatVersion::parse(v.trim())),
    }
}

/// [`description_compat`] resolved for a single file: walk up to the enclosing
/// package root (`DESCRIPTION` + `R/`). All-`None` for a loose file outside
/// any package — the version-aware rules then stay silent unless the user
/// configures a floor. Touches disk.
pub fn description_compat_for_file(path: &Path) -> DescriptionCompat {
    package_root(path)
        .map(|root| description_compat(&root))
        .unwrap_or_default()
}

/// The R version floor a `Depends` field declares: the comma-separated entry
/// naming exactly `R`, with a parenthesized `>=`/`>` constraint (any other
/// operator states no floor). `Depends: R (>= 4.1.0), stats` → `4.1.0`.
fn r_depends_floor(depends: &str) -> Option<CompatVersion> {
    for entry in depends.split(',') {
        let entry = entry.trim();
        let (name, constraint) = match entry.find('(') {
            Some(open) => (
                entry[..open].trim(),
                entry[open + 1..].trim_end().strip_suffix(')'),
            ),
            None => (entry, None),
        };
        if name != "R" {
            continue;
        }
        let constraint = constraint?.trim();
        let version = constraint
            .strip_prefix(">=")
            .or_else(|| constraint.strip_prefix('>'))?;
        return CompatVersion::parse(version.trim());
    }
    None
}

/// Statically resolve the `markdown` element of the R text's value: the text's
/// **last** top-level expression (both `eval(parse(text = field))` and
/// `source(meta.R)$value` yield the last expression's value) must be a plain
/// `list(...)` call carrying a literal `markdown = TRUE`/`FALSE`. `None` when
/// the value is absent or not statically resolvable.
fn markdown_from_r_text(text: &str) -> Option<bool> {
    let output = parse(text);
    if !output.diagnostics.is_empty() {
        return None;
    }
    // The last top-level expression must itself be the `list(...)` call. Walk
    // elements, not nodes: an atom statement (`x` after the list) is a bare
    // token in this CST and a node-level `last_child` would skip right past it.
    let last = output
        .cst
        .children_with_tokens()
        .filter(|el| {
            !matches!(
                el.kind(),
                SyntaxKind::WHITESPACE
                    | SyntaxKind::NEWLINE
                    | SyntaxKind::COMMENT
                    | SyntaxKind::SEMICOLON
            )
        })
        .last()?;
    let last = CallExpr::cast(last.into_node()?)?;
    if last.callee_name().as_deref() != Some("list") {
        return None;
    }
    last.args()
        .filter(|arg| arg.name().as_deref() == Some("markdown"))
        .last()
        .and_then(|arg| literal_logical(&arg))
}

/// The literal logical value of a named argument, when its value is exactly
/// the `TRUE` or `FALSE` constant (an identifier token — R's special constants
/// are bare tokens in the CST). `None` for anything else, including `T`/`F`
/// (reassignable in R) and computed values.
fn literal_logical(arg: &Arg) -> Option<bool> {
    let value = arg.value()?;
    let token = value.into_token()?;
    match token.text() {
        "TRUE" => Some(true),
        "FALSE" => Some(false),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn package(description: &str) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir(dir.path().join("R")).expect("R/");
        std::fs::write(dir.path().join("R/a.R"), "NULL\n").expect("a.R");
        std::fs::write(dir.path().join("DESCRIPTION"), description).expect("DESCRIPTION");
        dir
    }

    fn write_meta(dir: &tempfile::TempDir, source: &str) {
        let meta_dir = dir.path().join("man/roxygen");
        std::fs::create_dir_all(&meta_dir).expect("man/roxygen/");
        std::fs::write(meta_dir.join("meta.R"), source).expect("meta.R");
    }

    #[test]
    fn description_compat_reads_r_floor_and_roxygen2_version() {
        let dir = package(
            "Package: mypkg\n\
             Depends: methods, R (>= 4.1.0), stats\n\
             RoxygenNote: 7.3.2\n",
        );
        let compat = description_compat(dir.path());
        assert_eq!(compat.r, CompatVersion::parse("4.1.0"));
        assert_eq!(compat.roxygen2, CompatVersion::parse("7.3.2"));
        // Per-file resolution walks to the package root.
        assert_eq!(
            description_compat_for_file(&dir.path().join("R/a.R")),
            compat
        );
        // A loose file outside any package resolves to no floors.
        let loose = tempfile::tempdir().expect("tempdir");
        assert_eq!(
            description_compat_for_file(&loose.path().join("script.R")),
            DescriptionCompat::default()
        );
    }

    #[test]
    fn description_compat_prefers_the_modern_roxygen2_field() {
        // roxygen2 8.0.0 records its version in `Config/roxygen2/version`;
        // the legacy `RoxygenNote` remains as the fallback.
        let dir = package(
            "Package: mypkg\n\
             Config/roxygen2/version: 8.0.0\n\
             RoxygenNote: 7.3.2\n",
        );
        assert_eq!(
            description_compat(dir.path()).roxygen2,
            CompatVersion::parse("8.0.0")
        );
    }

    #[test]
    fn r_depends_floor_parses_constraint_shapes() {
        let floor = |s: &str| r_depends_floor(s);
        assert_eq!(floor("R (>= 4.1)"), CompatVersion::parse("4.1"));
        assert_eq!(floor("R (> 4.0.5)"), CompatVersion::parse("4.0.5"));
        assert_eq!(
            floor("stats, R(>=3.5.0), utils"),
            CompatVersion::parse("3.5.0")
        );
        // No constraint, a non-floor operator, or no R entry: no floor.
        assert_eq!(floor("R"), None);
        assert_eq!(floor("R (== 4.1)"), None);
        assert_eq!(floor("Rcpp (>= 1.0)"), None);
        assert_eq!(floor(""), None);
    }

    #[test]
    fn package_name_from_description() {
        let dir = package("Package: mypkg\nVersion: 1.0\n");
        assert_eq!(package_name(dir.path()).as_deref(), Some("mypkg"));
        // Walks up from a file, including one nested well below the root.
        assert_eq!(
            package_name_for_file(&dir.path().join("R/a.R")).as_deref(),
            Some("mypkg")
        );
        assert_eq!(
            package_name_for_file(&dir.path().join("tests/testthat/test-a.R")).as_deref(),
            Some("mypkg")
        );
    }

    #[test]
    fn package_name_is_none_without_a_package() {
        // No DESCRIPTION at all.
        let loose = tempfile::tempdir().expect("tempdir");
        assert_eq!(package_name(loose.path()), None);
        assert_eq!(package_name_for_file(&loose.path().join("a.R")), None);
        // A DESCRIPTION that declares no `Package`.
        let dir = package("Version: 1.0\n");
        assert_eq!(package_name(dir.path()), None);
    }

    #[test]
    fn markdown_true_from_roxygen_field() {
        let dir = package("Package: p\nRoxygen: list(markdown = TRUE)\n");
        assert!(roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn markdown_defaults_off_without_field() {
        let dir = package("Package: p\n");
        assert!(!roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn markdown_false_is_explicit_off() {
        let dir = package("Package: p\nRoxygen: list(markdown = FALSE)\n");
        assert!(!roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn field_with_more_options_and_continuation() {
        let dir = package(
            "Package: p\nRoxygen: list(load = \"installed\",\n    markdown = TRUE)\nDepends: R\n",
        );
        assert!(roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn non_literal_markdown_value_is_unknown() {
        let dir = package("Package: p\nRoxygen: list(markdown = flag)\n");
        assert!(!roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn non_list_field_is_unknown() {
        let dir = package("Package: p\nRoxygen: make_options()\n");
        assert!(!roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn meta_overrides_description_on() {
        let dir = package("Package: p\nRoxygen: list(markdown = FALSE)\n");
        write_meta(&dir, "list(markdown = TRUE)\n");
        assert!(roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn meta_overrides_description_off() {
        let dir = package("Package: p\nRoxygen: list(markdown = TRUE)\n");
        write_meta(&dir, "list(markdown = FALSE)\n");
        assert!(!roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn meta_last_expression_wins_after_other_statements() {
        let dir = package("Package: p\n");
        write_meta(&dir, "x <- 1\nlist(markdown = TRUE)\n");
        assert!(roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn meta_trailing_atom_is_not_the_list() {
        // `source()`'s value is `x`, not the list — statically unknown, so the
        // DESCRIPTION field wins.
        let dir = package("Package: p\nRoxygen: list(markdown = FALSE)\n");
        write_meta(&dir, "list(markdown = TRUE)\nx\n");
        assert!(!roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn unresolvable_meta_defers_to_description() {
        let dir = package("Package: p\nRoxygen: list(markdown = TRUE)\n");
        write_meta(&dir, "build_meta()\n");
        assert!(roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn meta_list_without_markdown_defers_to_description() {
        let dir = package("Package: p\nRoxygen: list(markdown = TRUE)\n");
        write_meta(&dir, "list(knitr_chunk_options = NULL)\n");
        assert!(roxygen_markdown_default(dir.path()));
    }

    #[test]
    fn for_file_resolves_via_package_root() {
        let dir = package("Package: p\nRoxygen: list(markdown = TRUE)\n");
        assert!(roxygen_markdown_default_for_file(&dir.path().join("R/a.R")));
    }

    #[test]
    fn for_file_outside_a_package_is_off() {
        let dir = tempfile::tempdir().expect("tempdir");
        let loose = dir.path().join("loose.R");
        std::fs::write(&loose, "NULL\n").expect("loose.R");
        assert!(!roxygen_markdown_default_for_file(&loose));
    }
}