Skip to main content

miniextendr_macros/
roxygen.rs

1//! Roxygen tag extraction and processing for R wrapper generation.
2//!
3//! This module extracts roxygen2-style tags (e.g., `@param`, `@examples`) from Rust
4//! doc comments and propagates them to generated R wrapper code.
5//!
6//! # Usage
7//!
8//! In Rust doc comments, use roxygen2 tags:
9//!
10//! ```rust,ignore
11//! /// @param x A numeric input.
12//! /// @return The squared value.
13//! /// @examples
14//! /// square(4)
15//! #[miniextendr]
16//! pub fn square(x: f64) -> f64 { x * x }
17//! ```
18//!
19//! # How doc lines carry over
20//!
21//! Every reader here ([`explicit_roxygen_tags_from_attrs`],
22//! [`leading_prose_from_attrs`], [`strip_roxygen_from_attrs`]) walks the same
23//! lines ([`doc_lines`]) with the same roles ([`classify`]):
24//!
25//! - Text before the first `@tag` line is leading prose. It becomes
26//!   `@description` (when the block has none) with its lines, blank lines and
27//!   indentation kept, and it stays in rustdoc. Its `[...]` links lose their
28//!   brackets unless the crate sets `roxygen_prose_links = "keep"`
29//!   ([`ProseLinks`]). Under `"keep"`, and in the text of every explicit tag
30//!   but the code ones ([`CODE_TAGS`]), only a link roxygen2 can never
31//!   resolve loses them ([`is_rustdoc_only_target`]). An inline link whose
32//!   destination is such a Rust path (`[text](crate::x)`) keeps only its text
33//!   under either setting ([`inline_rustdoc_destination`]); other
34//!   `[text](url)` links stay. A block that renders no help page (its own
35//!   `@noRd`, or a caller's [`RdPage::Suppressed`]: `noexport`, a class
36//!   without a page) loses every link in its prose and its non-code tag
37//!   text, whatever the setting.
38//! - A tag runs from its `@tag` line to the next one. A multi-line tag
39//!   (`@description`, `@return`, `@examples`, ...) keeps its blank lines (a
40//!   roxygen2 paragraph break; a blank line in an example) and the indentation
41//!   of its continuation lines, less the one space rustdoc's `/// ` puts there.
42//!   Trailing blank lines are dropped. roxygen2 markdown reads a continuation
43//!   indented 4 or more spaces after a blank line as a code block, as rustdoc
44//!   does.
45//! - A joined tag (`@title`, `@keywords`, `@concept`, `@aliases`) folds its
46//!   wrapped lines onto one line.
47//! - A single-line tag (`@export`, `@noRd`, `@rdname topic`, ...) ends at its
48//!   line. Lines after it, up to the next tag, are rustdoc only.
49//! - Rustdoc keeps the leading prose and the rustdoc-only lines, and drops
50//!   every tag with its text.
51//!
52//! # R Package Configuration
53//!
54//! For roxygen2 to process multiline tags correctly, add this to your `DESCRIPTION` file:
55//!
56//! ```text
57//! Roxygen: list(markdown = TRUE)
58//! ```
59
60use std::collections::HashSet;
61
62/// Tags that allow multi-line content (continuation lines appended).
63/// All other tags are treated as single-line.
64const MULTILINE_TAGS: &[&str] = &[
65    "examples",
66    "description",
67    "details",
68    "return",
69    "returns",
70    "param",
71    "note",
72    "seealso",
73    "section",
74    "format",
75    "references",
76    "slot",
77    "field",
78    "value", // synonym for return
79    "prop",  // S7 property documentation (roxygen2 8.0.0+)
80    // Tags whose *name* is a single word but whose text may wrap onto the
81    // next `///` line. Dropping the wrapped part silently truncated them (#1476).
82    "describeIn",
83    "family",
84    "inherit",
85    "inheritParams",
86    "inheritSection",
87    // roxygen2's other tags whose text runs over several lines (code, raw Rd,
88    // NAMESPACE directives, free text).
89    "examplesIf",
90    "usage",
91    "rawRd",
92    "rawNamespace",
93    "evalRd",
94    "evalNamespace",
95    "source",
96    "author",
97];
98
99/// Tags whose text is R code or raw Rd, not markdown: their `[...]` is never
100/// a link, so [`neutralize_tag_links`] leaves them as written.
101const CODE_TAGS: &[&str] = &[
102    "examples",
103    "examplesIf",
104    "usage",
105    "eval",
106    "evalRd",
107    "evalNamespace",
108    "rawRd",
109    "rawNamespace",
110];
111
112/// Tags whose wrapped continuation lines are joined back onto one line with a
113/// space instead of a newline: roxygen2 wants these on a single line (or reads
114/// them as one whitespace-separated list), but a long title, keyword list,
115/// concept, or alias list in a Rust doc comment can be wrapped by the author.
116const JOINED_TAGS: &[&str] = &["title", "keywords", "concept", "aliases"];
117
118/// A bare `@name` / `@rdname` (topic written on the next `///` line, which
119/// roxygen2 accepts) takes exactly one continuation line as its topic. Once
120/// the tag has a topic it is single-line again, so following prose is not
121/// absorbed (see `test_rdname_stays_single_line`). The wrapper registry
122/// decides page routing from the single `#' @name <topic>` line, so a dropped
123/// topic would silently change which page a function lands on.
124fn is_bare_topic_tag(tag: &str) -> bool {
125    #[allow(non_exhaustive_omitted_patterns)] match tag {
    "@name" | "@rdname" => true,
    _ => false,
}matches!(tag, "@name" | "@rdname")
126}
127
128/// Check if a tag name supports multi-line content.
129fn is_multiline_tag(tag: &str) -> bool {
130    // Extract the tag name from "@tagname ..." or "@tagname"
131    let tag_name = tag
132        .strip_prefix('@')
133        .and_then(|rest| rest.split_whitespace().next())
134        .unwrap_or("");
135    MULTILINE_TAGS.contains(&tag_name)
136}
137
138/// Check if a tag's continuation lines are joined with a space (see [`JOINED_TAGS`]).
139fn is_joined_tag(tag: &str) -> bool {
140    let tag_name = tag
141        .strip_prefix('@')
142        .and_then(|rest| rest.split_whitespace().next())
143        .unwrap_or("");
144    JOINED_TAGS.contains(&tag_name)
145}
146
147// region: doc lines
148
149/// One line of a string-literal doc attribute.
150#[derive(#[automatically_derived]impl ::core::fmt::Debug for DocLine {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DocLine attr text", &self.attr, &&self.text)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for DocLine {
}
#[automatically_derived]impl ::core::cmp::PartialEq for DocLine {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.attr == other.attr && self.text == other.text
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for DocLine {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<usize>;
        let _: ::core::cmp::AssertParamIsEq<String>;
    }
}Eq)]
151struct DocLine {
152    /// Index of the doc attribute in the attribute slice it was read from.
153    attr: usize,
154    /// The line with its rustdoc lead removed (see [`doc_lines`]); empty for
155    /// a blank line.
156    text: String,
157}
158
159/// The lines of every string-literal doc attribute in `attrs`, in order.
160///
161/// Non-doc attributes are skipped, so an interleaved `#[cfg(...)]` never
162/// interrupts a tag (#613). A `#[doc = include_str!(..)]` is not a literal and
163/// stays unread. Per attribute:
164///
165/// - a single-line literal (each `///` line, a `#[doc = "..."]` from
166///   `macro_rules!`) loses at most the one leading space rustdoc's `/// `
167///   puts there;
168/// - a multi-line literal (`/** ... */`, `#[doc = "a\nb"]`) loses the common
169///   leading whitespace of its non-blank lines, so a relative indent survives;
170/// - a whitespace-only line becomes an empty one.
171fn doc_lines(attrs: &[syn::Attribute]) -> Vec<DocLine> {
172    let mut out = Vec::new();
173    for (attr, a) in attrs.iter().enumerate() {
174        if !a.path().is_ident("doc") {
175            continue;
176        }
177        let syn::Meta::NameValue(nv) = &a.meta else {
178            continue;
179        };
180        let syn::Expr::Lit(expr_lit) = &nv.value else {
181            continue;
182        };
183        let syn::Lit::Str(lit) = &expr_lit.lit else {
184            continue;
185        };
186        let value = lit.value();
187        // `"".lines()` yields nothing, but an empty `///` is one blank line.
188        let lines: Vec<&str> = if value.is_empty() {
189            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [""]))vec![""]
190        } else {
191            value.lines().collect()
192        };
193        let lead = if value.contains('\n') {
194            common_indent(&lines)
195        } else {
196            " "
197        };
198        for line in lines {
199            let text = if line.trim().is_empty() {
200                ""
201            } else {
202                line.strip_prefix(lead).unwrap_or(line)
203            };
204            out.push(DocLine {
205                attr,
206                text: text.to_string(),
207            });
208        }
209    }
210    out
211}
212
213/// The leading whitespace every non-blank line of `lines` starts with.
214fn common_indent<'a>(lines: &[&'a str]) -> &'a str {
215    lines
216        .iter()
217        .filter(|line| !line.trim().is_empty())
218        .map(|line| &line[..line.len() - line.trim_start().len()])
219        .reduce(|common, lead| {
220            let shared = common
221                .char_indices()
222                .zip(lead.chars())
223                .take_while(|((_, a), b)| a == b)
224                .last()
225                .map_or(0, |((i, c), _)| i + c.len_utf8());
226            &common[..shared]
227        })
228        .unwrap_or("")
229}
230
231/// What a doc line is to roxygen extraction and rustdoc stripping.
232#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for LineRole {
}
#[automatically_derived]impl ::core::clone::Clone for LineRole {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for LineRole { }Copy, #[automatically_derived]impl ::core::fmt::Debug for LineRole {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                LineRole::Prose => "Prose",
                LineRole::TagStart => "TagStart",
                LineRole::TagBody => "TagBody",
                LineRole::Rustdoc => "Rustdoc",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for LineRole
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for LineRole {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for LineRole { }Eq)]
233enum LineRole {
234    /// Before the first tag: leading prose (promoted to `@description`, kept
235    /// in rustdoc).
236    Prose,
237    /// A line starting with `@` (after leading whitespace): a new tag.
238    TagStart,
239    /// Part of the open tag's text, or a blank line that ends a tag (trailing,
240    /// or before the next tag).
241    TagBody,
242    /// After a single-line tag: rustdoc only, never R. A blank line is
243    /// rustdoc when a rustdoc-only line follows it.
244    Rustdoc,
245}
246
247/// How the tag that is open takes the lines that follow it.
248#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for OpenTag {
}
#[automatically_derived]impl ::core::clone::Clone for OpenTag {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for OpenTag { }Copy)]
249enum OpenTag {
250    /// [`MULTILINE_TAGS`]: every line up to the next tag, blank lines included.
251    Multi,
252    /// [`JOINED_TAGS`], or a bare `@name` / `@rdname` still waiting for its
253    /// topic ([`is_bare_topic_tag`]): the non-blank lines, folded onto one
254    /// line. A bare topic tag takes one line, then it is `Single`.
255    Joined { bare_topic: bool },
256    /// Any other tag: its own line only.
257    Single,
258}
259
260impl OpenTag {
261    fn of(tag_line: &str) -> Self {
262        if is_multiline_tag(tag_line) {
263            Self::Multi
264        } else if is_joined_tag(tag_line) {
265            Self::Joined { bare_topic: false }
266        } else if is_bare_topic_tag(tag_line) {
267            Self::Joined { bare_topic: true }
268        } else {
269            Self::Single
270        }
271    }
272}
273
274/// The role of each of `lines` ([`doc_lines`]): the one rule the tag
275/// extractor, the leading-prose reader and the rustdoc strip share.
276fn classify(lines: &[DocLine]) -> Vec<LineRole> {
277    let mut roles = Vec::with_capacity(lines.len());
278    let mut open: Option<OpenTag> = None;
279    for line in lines {
280        let text = line.text.trim_start();
281        let role = if text.starts_with('@') {
282            open = Some(OpenTag::of(text));
283            LineRole::TagStart
284        } else {
285            match open {
286                None => LineRole::Prose,
287                Some(OpenTag::Multi | OpenTag::Joined { bare_topic: false }) => LineRole::TagBody,
288                Some(OpenTag::Joined { bare_topic: true }) => {
289                    if !text.is_empty() {
290                        open = Some(OpenTag::Single);
291                    }
292                    LineRole::TagBody
293                }
294                Some(OpenTag::Single) => LineRole::Rustdoc,
295            }
296        };
297        roles.push(role);
298    }
299    // A blank line after a single-line tag goes with the paragraph after it:
300    // rustdoc before a rustdoc-only line, the tag's end otherwise.
301    let mut next_is_rustdoc = false;
302    for (line, role) in lines.iter().zip(roles.iter_mut()).rev() {
303        if !line.text.is_empty() {
304            next_is_rustdoc = *role == LineRole::Rustdoc;
305        } else if *role == LineRole::Rustdoc && !next_is_rustdoc {
306            *role = LineRole::TagBody;
307        }
308    }
309    roles
310}
311
312// endregion
313
314/// Whether a doc block's roxygen text can reach a rendered help page, as far
315/// as the caller knows, which decides what happens to its `[...]` links.
316///
317/// A block that renders no page sends roxygen2 no link: none of them could
318/// render, and roxygen2 still resolves (and warns on) every one it is handed
319/// (#1818). The reader sees an explicit `@noRd` in the block itself; the
320/// caller says when its attributes take the page away.
321#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RdPage {
}
#[automatically_derived]impl ::core::clone::Clone for RdPage {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for RdPage { }Copy, #[automatically_derived]impl ::core::fmt::Debug for RdPage {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RdPage::Rendered => "Rendered",
                RdPage::Suppressed => "Suppressed",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for RdPage {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RdPage {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for RdPage { }Eq)]
322pub(crate) enum RdPage {
323    /// The block renders a page unless its own tags say `@noRd`: its links
324    /// follow the crate's [`ProseLinks`] setting.
325    Rendered,
326    /// The block renders no page whatever its tags: a `noexport` entry point,
327    /// a class without a page, or a method of one. Every link loses its
328    /// brackets ([`Neutralize::AllLinks`]).
329    Suppressed,
330}
331
332impl RdPage {
333    /// [`RdPage::Suppressed`] when `no_page`, else [`RdPage::Rendered`].
334    pub(crate) fn suppressed_if(no_page: bool) -> Self {
335        if no_page {
336            Self::Suppressed
337        } else {
338            Self::Rendered
339        }
340    }
341}
342
343/// Extract roxygen tag lines (starting with '@') from Rust doc attributes.
344///
345/// Most tags capture only a single line. Multi-line tags like `@examples`,
346/// `@description`, `@param`, and `@return` append their continuation lines,
347/// blank lines and indentation included (see the module docs).
348///
349/// Leading prose (the paragraphs before the first tag) is promoted to
350/// `@description` when the block has none. `page` says whether the block can
351/// render a help page ([`RdPage`]).
352pub(crate) fn roxygen_tags_from_attrs(attrs: &[syn::Attribute], page: RdPage) -> Vec<String> {
353    roxygen_tags_from_attrs_impl(attrs, page)
354}
355
356/// Roxygen tags from a trait declaration's docs, for the wrappers of an
357/// implementation whose method has none of its own (an inherited default, a
358/// method an empty impl registers, a written method without a doc comment).
359///
360/// The docs are the trait's rustdoc, written where the trait is declared,
361/// often in another crate, so every `[...]` loses its brackets whatever the
362/// implementing crate's [`ProseLinks`] setting, as in a block with no page
363/// ([`RdPage::Suppressed`]): in rustdoc a bracket names a Rust item or is
364/// plain text (`slot [4]`), not an R topic the implementing package can
365/// resolve.
366pub(crate) fn declaration_roxygen_tags(attrs: &[syn::Attribute]) -> Vec<String> {
367    roxygen_tags_with(attrs, ProseLinks::Strip, RdPage::Suppressed)
368}
369
370/// Extract roxygen tags for an impl-block method.
371///
372/// Identical to [`roxygen_tags_from_attrs`] — leading prose is promoted to
373/// `@description` in every context. Kept as a named alias so the class-system
374/// generators read clearly at the call site.
375pub(crate) fn roxygen_tags_from_attrs_for_r6_method(
376    attrs: &[syn::Attribute],
377    page: RdPage,
378) -> Vec<String> {
379    roxygen_tags_from_attrs_impl(attrs, page)
380}
381
382/// Whether the doc comment in `attrs` has the roxygen tag `tag` (matched as
383/// [`has_roxygen_tag`] does), for a caller deciding a block's [`RdPage`]
384/// before it reads the block's tags.
385pub(crate) fn attrs_have_roxygen_tag(attrs: &[syn::Attribute], tag: &str) -> bool {
386    has_roxygen_tag(&explicit_roxygen_tags_from_attrs(attrs), tag)
387}
388
389/// Core implementation of roxygen tag extraction from `#[doc = "..."]` attributes.
390///
391/// Walks the doc lines ([`doc_lines`]) with their roles ([`classify`]). Lines
392/// starting with `@` begin a new tag; continuation lines are appended only if
393/// the current tag is multiline-capable (or joined, see [`JOINED_TAGS`]).
394///
395/// Only doc attributes are read, in order, so interleaved `#[cfg(...)]` or
396/// other non-doc attributes never break multiline-tag continuation (#613).
397/// This is a pure parse-side transform: the emitted `TokenStream` is
398/// unaffected.
399///
400/// Leading prose (paragraphs before the first `@tag`) is promoted to a
401/// `@description` tag — never `@title`. The `@title` is left to the caller
402/// (structural name); see [`leading_prose_from_attrs`] for why.
403fn roxygen_tags_from_attrs_impl(attrs: &[syn::Attribute], page: RdPage) -> Vec<String> {
404    roxygen_tags_with(attrs, crate::crate_config::roxygen_prose_links(), page)
405}
406
407/// [`roxygen_tags_from_attrs_impl`] with the crate's [`ProseLinks`] setting
408/// passed in (testable without a manifest).
409///
410/// Every explicit tag loses its rustdoc-only links ([`neutralize_tag_links`])
411/// whatever the setting, which governs the leading prose only. A block that
412/// renders no page ([`RdPage::Suppressed`], or its own `@noRd`) loses every
413/// link, in the prose and in each non-code tag (#1818).
414fn roxygen_tags_with(attrs: &[syn::Attribute], links: ProseLinks, page: RdPage) -> Vec<String> {
415    let explicit = explicit_roxygen_tags_from_attrs(attrs);
416    let no_page = page == RdPage::Suppressed || has_roxygen_tag(&explicit, "noRd");
417    let (links, tag_links) = if no_page {
418        (ProseLinks::Strip, Neutralize::AllLinks)
419    } else {
420        (links, Neutralize::RustdocOnly)
421    };
422    let mut tags: Vec<String> = explicit
423        .into_iter()
424        .map(|tag| neutralize_tag_links(tag, tag_links))
425        .collect();
426
427    // Check which tags are present
428    let tag_names_set = tag_names(&tags);
429    let has_description = tag_names_set.contains("description");
430
431    // Promote leading prose doc comments to `@description` (all paragraphs before
432    // the first `@tag`), unless the author already wrote an explicit `@description`.
433    //
434    // The page `@title` is NOT synthesized from prose. Rustdoc summaries are markdown
435    // written for `cargo doc` — intra-doc links (`[`Foo`]`, `[x][crate::y]`) and code
436    // spans — which roxygen2's markdown parser tries to resolve as R `\link{}` topics
437    // and fails ("could not resolve link to topic" / "refers to un-installed package").
438    // Titles come from the structural name instead: the wrapper name for standalone
439    // functions (see `lib.rs`) and `@title {Name} Class` for class blocks (see
440    // `ClassDocBuilder`). Demoting prose to `@description` keeps it visible while the
441    // title stays link-free.
442    //
443    // `leading_prose_from_attrs` returns `None` for tag-led blocks (no leading prose),
444    // so `@inherit`/`@rdname`-only docs never gain a spurious description.
445    if !has_description && let Some(desc) = leading_prose_from_attrs(attrs, links) {
446        tags.insert(0, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@description {0}", desc))
    })format!("@description {}", desc));
447    }
448
449    tags
450}
451
452/// Parse only the author-written `@tag` lines from doc attributes — no
453/// leading-prose promotion.
454///
455/// A tag line is left-trimmed, so `///   @param` still starts a tag. A
456/// multi-line tag keeps its continuation lines as written (less the rustdoc
457/// lead, [`doc_lines`]) and its interior blank lines, and drops its trailing
458/// ones; a joined or bare-topic tag folds its lines onto one with a space.
459///
460/// [`roxygen_tags_from_attrs_impl`] layers the leading-prose → `@description`
461/// promotion on top of this. [`doc_conflict_warnings`] must use this raw parse
462/// instead: comparing the *synthesized* description (all leading prose) against
463/// the implicit one (second paragraph) warned on every multi-paragraph doc
464/// comment that had no explicit `@description` at all (#1172).
465fn explicit_roxygen_tags_from_attrs(attrs: &[syn::Attribute]) -> Vec<String> {
466    let lines = doc_lines(attrs);
467    let roles = classify(&lines);
468    let mut tags: Vec<String> = Vec::new();
469    // Blank lines seen inside a multi-line tag, written out only when more of
470    // its text follows: a tag's trailing blank lines are dropped.
471    let mut pending_blanks = 0;
472
473    for (line, role) in lines.iter().zip(roles) {
474        match role {
475            LineRole::TagStart => {
476                pending_blanks = 0;
477                tags.push(line.text.trim_start().to_string());
478            }
479            LineRole::TagBody => {
480                let Some(last) = tags.last_mut() else {
481                    continue;
482                };
483                if is_multiline_tag(last) {
484                    if line.text.is_empty() {
485                        pending_blanks += 1;
486                    } else {
487                        for _ in 0..std::mem::take(&mut pending_blanks) {
488                            last.push('\n');
489                        }
490                        last.push('\n');
491                        last.push_str(&line.text);
492                    }
493                } else if !line.text.is_empty() {
494                    // Wrapped joined tag or bare topic: fold onto one line.
495                    last.push(' ');
496                    last.push_str(line.text.trim());
497                }
498            }
499            // Leading prose is read by `leading_prose_from_attrs` and promoted
500            // to @description in `roxygen_tags_from_attrs_impl`; rustdoc-only
501            // lines never reach R.
502            LineRole::Prose | LineRole::Rustdoc => {}
503        }
504    }
505
506    tags
507}
508
509/// One roxygen comment line: `#' text`, or a bare `#'` for a blank `text`
510/// (no trailing whitespace in the generated R). Render author tag text
511/// through this (or the `push_roxygen_tags*` helpers), never
512/// `format!("#' {}", ..)`.
513pub(crate) fn roxygen_line(text: &str) -> String {
514    if text.trim().is_empty() {
515        "#'".to_string()
516    } else {
517        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}", text))
    })format!("#' {text}")
518    }
519}
520
521/// Render roxygen tag lines as "#' ..." comment lines.
522///
523/// Multiline tags (containing '\n') are split into separate `#'` lines
524/// ([`roxygen_line`]).
525pub(crate) fn format_roxygen_tags(tags: &[String]) -> String {
526    let mut out = String::new();
527    for line in tags.iter().flat_map(|tag| tag.lines()) {
528        out.push_str(&roxygen_line(line));
529        out.push('\n');
530    }
531    out
532}
533
534/// Push roxygen tag lines into a vector of R wrapper lines.
535///
536/// Multiline tags (containing '\n') are split into separate `#'` lines
537/// ([`roxygen_line`]).
538pub(crate) fn push_roxygen_tags(lines: &mut Vec<String>, tags: &[String]) {
539    lines.extend(tags.iter().flat_map(|tag| tag.lines()).map(roxygen_line));
540}
541
542/// Like [`push_roxygen_tags`] but takes `&[&str]` for filtered tag slices.
543pub(crate) fn push_roxygen_tags_str(lines: &mut Vec<String>, tags: &[&str]) {
544    lines.extend(tags.iter().flat_map(|tag| tag.lines()).map(roxygen_line));
545}
546
547/// Return true if the tag list contains a specific roxygen tag.
548///
549/// Supports both single-word tags (e.g., `"export"`, `"noRd"`) and
550/// multi-word tags (e.g., `"keywords internal"`). For single-word tags,
551/// matches the first word after `@`. For multi-word tags, matches the
552/// full content after `@` (trimmed).
553pub(crate) fn has_roxygen_tag(tags: &[String], tag: &str) -> bool {
554    if tag.contains(' ') {
555        // Multi-word tag: match the full content after @
556        tags.iter().any(|t| {
557            t.trim_start()
558                .strip_prefix('@')
559                .is_some_and(|rest| rest.trim() == tag)
560        })
561    } else {
562        tag_names(tags).contains(tag)
563    }
564}
565
566/// Whether the author registers the function themselves, with `@export` or
567/// `@exportS3Method` (bare or `pkg::generic`), so a public standalone fn gets
568/// no automatic `@export`. Next to a delayed `@exportS3Method pkg::generic`
569/// a bare `@export` makes roxygen2 write an eager registration as well, and
570/// the package fails to load when `pkg` is only in Suggests (#1944).
571pub(crate) fn has_export_tag(tags: &[String]) -> bool {
572    let names = tag_names(tags);
573    names.contains("export") || names.contains("exportS3Method")
574}
575
576/// The topic named by the tag list's own `@rdname` tag, if it has one.
577///
578/// Class generators default every method onto the class page (`@rdname
579/// <Class>`); a method-level `/// @rdname other` splits it onto its own page.
580/// Every emission path that injects the class default must consult this first
581/// so a user-supplied topic is honoured once, not duplicated by the default.
582pub(crate) fn rdname_value(tags: &[String]) -> Option<&str> {
583    tags.iter().find_map(|t| {
584        let rest = t.trim_start().strip_prefix("@rdname")?;
585        let value = rest.trim();
586        (rest.starts_with(char::is_whitespace) && !value.is_empty()).then_some(value)
587    })
588}
589
590/// Push `#' @rdname <topic>` for a scaffolding block that follows its method:
591/// the method's page ([`method_page`]: its `@describeIn` destination or own
592/// `@rdname`), else `default` (the class page).
593pub(crate) fn push_rdname_or_default(lines: &mut Vec<String>, tags: &[String], default: &str) {
594    let topic = method_page(tags, default);
595    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", topic))
    })format!("#' @rdname {topic}"));
596}
597
598/// The `@source` provenance line for a generated documentation block, or
599/// `None` unless the crate opted in with `[package.metadata.miniextendr]
600/// source_tags = true` (#1552). On a shared Rd page the tag collects one
601/// paragraph per function, so it is off by default; the `# Generated from
602/// Rust fn … (file:line:col)` comment above each wrapper stays as the
603/// navigation pointer. Every emitter goes through here (or the two
604/// specialisations below), so the knob has one implementation.
605pub(crate) fn source_tag(text: impl AsRef<str>) -> Option<String> {
606    source_tag_with(crate::crate_config::source_tags_enabled(), text.as_ref())
607}
608
609/// [`source_tag`] with the crate setting passed in (testable without a manifest).
610pub(crate) fn source_tag_with(enabled: bool, text: &str) -> Option<String> {
611    enabled.then(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @source {0}", text))
    })format!("#' @source {text}"))
612}
613
614/// The `@source` line for a class method: ``Generated by miniextendr from
615/// `Type::method` ``, subject to [`source_tag`]'s opt-in.
616pub(crate) fn method_source_tag(
617    type_ident: &syn::Ident,
618    method_ident: &syn::Ident,
619) -> Option<String> {
620    source_tag(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from `{0}::{1}`",
                type_ident, method_ident))
    })format!(
621        "Generated by miniextendr from `{}::{}`",
622        type_ident, method_ident
623    ))
624}
625
626/// The `@source` line for a class definition: ``Generated by miniextendr from
627/// Rust type `Type` ``, subject to [`source_tag`]'s opt-in.
628pub(crate) fn class_source_tag(type_ident: &syn::Ident) -> Option<String> {
629    source_tag(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from Rust type `{0}`",
                type_ident))
    })format!(
630        "Generated by miniextendr from Rust type `{}`",
631        type_ident
632    ))
633}
634
635/// Extract the set of tag names from a list of roxygen tag strings.
636///
637/// Each tag string is expected to start with `@tagname`. Returns a set of
638/// the tag names (without the `@` prefix).
639fn tag_names(tags: &[String]) -> HashSet<&str> {
640    let mut names = HashSet::new();
641    for tag in tags {
642        let trimmed = tag.trim_start();
643        let name = trimmed
644            .strip_prefix('@')
645            .and_then(|rest| rest.split_whitespace().next());
646        if let Some(name) = name {
647            names.insert(name);
648        }
649    }
650    names
651}
652
653/// Find the value of a specific roxygen tag (e.g., "title" for `@title ...`).
654///
655/// Returns `None` if the tag is not present or has no value.
656#[cfg_attr(not(feature = "doc-lint"), allow(dead_code))]
657pub(crate) fn find_tag_value<'a>(tags: &'a [String], tag_name: &str) -> Option<&'a str> {
658    for tag in tags {
659        let trimmed = tag.trim_start();
660        if let Some(rest) = trimmed.strip_prefix('@') {
661            let mut parts = rest.splitn(2, |c: char| c.is_whitespace());
662            if let Some(name) = parts.next()
663                && name == tag_name
664            {
665                // Get the value (everything after the tag name)
666                return parts.next().map(|s| s.trim());
667            }
668        }
669    }
670    None
671}
672
673/// Normalize text for comparison: lowercase, collapse whitespace, strip trailing punctuation.
674///
675/// Used by `doc_conflict_warnings` to compare explicit `@title`/`@description` values
676/// with implicit values derived from the doc comment structure. Normalization ensures
677/// minor formatting differences (extra spaces, trailing periods) don't trigger false warnings.
678#[cfg_attr(not(feature = "doc-lint"), allow(dead_code))]
679fn normalize_for_comparison(s: &str) -> String {
680    let lower = s.to_lowercase();
681    let mut result = String::new();
682    for word in lower.split_whitespace() {
683        if !result.is_empty() {
684            result.push(' ');
685        }
686        result.push_str(word);
687    }
688    result.truncate(
689        result
690            .trim_end_matches(|c: char| c.is_ascii_punctuation())
691            .len(),
692    );
693    result
694}
695
696/// Extract the implicit title from doc attributes (first sentence, up to first `.` or newline).
697///
698/// Returns `None` if there are no doc comments or if docs start with a `@tag`.
699#[cfg_attr(not(feature = "doc-lint"), allow(dead_code))]
700pub(crate) fn implicit_title_from_attrs(attrs: &[syn::Attribute]) -> Option<String> {
701    let mut lines = Vec::new();
702
703    for attr in attrs {
704        if !attr.path().is_ident("doc") {
705            continue;
706        }
707        let syn::Meta::NameValue(nv) = &attr.meta else {
708            continue;
709        };
710        let syn::Expr::Lit(expr_lit) = &nv.value else {
711            continue;
712        };
713        let syn::Lit::Str(lit) = &expr_lit.lit else {
714            continue;
715        };
716
717        let content = lit.value();
718        let trimmed = content.trim();
719
720        // If we hit a @tag before any content, there's no implicit title
721        if trimmed.starts_with('@') {
722            if lines.is_empty() {
723                return None;
724            }
725            break;
726        }
727
728        // Empty line ends first sentence for title extraction
729        if trimmed.is_empty() {
730            break;
731        }
732
733        // Check if this line contains a sentence-ending period
734        if let Some(pos) = trimmed.find(". ") {
735            lines.push(trimmed[..pos].to_string());
736            break;
737        } else if trimmed.ends_with('.') {
738            lines.push(trimmed.trim_end_matches('.').to_string());
739            break;
740        } else {
741            lines.push(trimmed.to_string());
742        }
743    }
744
745    if lines.is_empty() {
746        None
747    } else {
748        Some(lines.join(" "))
749    }
750}
751
752/// Extract the implicit description from doc attributes (second paragraph).
753///
754/// In roxygen2, the first paragraph is the title and the second paragraph is the
755/// description. This function skips the first paragraph (up to the first blank line)
756/// and returns the second paragraph.
757///
758/// Returns `None` if there is no second paragraph, no doc comments, or if docs
759/// start with a `@tag`.
760#[cfg_attr(not(feature = "doc-lint"), allow(dead_code))]
761pub(crate) fn implicit_description_from_attrs(attrs: &[syn::Attribute]) -> Option<String> {
762    let mut lines = Vec::new();
763    let mut found_first_paragraph = false;
764    let mut in_gap = false;
765
766    for attr in attrs {
767        if !attr.path().is_ident("doc") {
768            continue;
769        }
770        let syn::Meta::NameValue(nv) = &attr.meta else {
771            continue;
772        };
773        let syn::Expr::Lit(expr_lit) = &nv.value else {
774            continue;
775        };
776        let syn::Lit::Str(lit) = &expr_lit.lit else {
777            continue;
778        };
779
780        let content = lit.value();
781        let trimmed = content.trim();
782
783        // If we hit a @tag, stop
784        if trimmed.starts_with('@') {
785            break;
786        }
787
788        if !found_first_paragraph {
789            // Still in the first paragraph (title)
790            if trimmed.is_empty() {
791                // Blank line — first paragraph ended, now in the gap
792                found_first_paragraph = true;
793                in_gap = true;
794            }
795            // Non-empty lines before first blank are title — skip
796        } else if in_gap {
797            // Between paragraphs — skip blank lines
798            if !trimmed.is_empty() {
799                // Start of second paragraph
800                in_gap = false;
801                lines.push(trimmed.to_string());
802            }
803        } else {
804            // In second paragraph
805            if trimmed.is_empty() {
806                // End of second paragraph
807                break;
808            }
809            lines.push(trimmed.to_string());
810        }
811    }
812
813    if lines.is_empty() {
814        None
815    } else {
816        Some(lines.join(" "))
817    }
818}
819
820/// What leading prose does with `[...]` link syntax on its way to
821/// `@description`: the crate's `roxygen_prose_links` setting in
822/// `[package.metadata.miniextendr]`.
823///
824/// rustdoc and roxygen2 read the same `[name()]` / `[pkg::name()]` / `[Topic]`
825/// / `` [`Topic`] `` syntax as a link to a Rust item and to an R help topic
826/// respectively, so the two cannot be told apart from the text: rustdoc
827/// resolves `[name()]` to an in-scope Rust fn and warns
828/// `broken_intra_doc_links` on any it cannot find. The crate says which reader
829/// its doc comments are written for.
830#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ProseLinks {
}
#[automatically_derived]impl ::core::clone::Clone for ProseLinks {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ProseLinks { }Copy, #[automatically_derived]impl ::core::fmt::Debug for ProseLinks {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ProseLinks::Strip => "Strip",
                ProseLinks::Keep => "Keep",
            })
    }
}Debug, #[automatically_derived]impl ::core::default::Default for ProseLinks {
    #[inline]
    fn default() -> Self { Self::Strip }
}Default, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ProseLinks {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ProseLinks {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ProseLinks { }Eq)]
831pub(crate) enum ProseLinks {
832    /// `"strip"`, the default: doc comments are written for rustdoc, so a link
833    /// loses its brackets ([`Neutralize::AllLinks`]) and roxygen2 never tries
834    /// to resolve a Rust item as an R topic.
835    #[default]
836    Strip,
837    /// `"keep"`: doc comments are written for roxygen2, so leading prose keeps
838    /// its links, as the text of an explicit tag does. Only the links roxygen2
839    /// can never resolve lose their brackets ([`Neutralize::RustdocOnly`]).
840    /// A block that renders no page is read as under `Strip` ([`RdPage`]).
841    Keep,
842}
843
844impl ProseLinks {
845    /// Parse the manifest spelling (`"strip"` / `"keep"`).
846    pub(crate) fn parse_name(name: &str) -> Option<Self> {
847        match name {
848            "strip" => Some(Self::Strip),
849            "keep" => Some(Self::Keep),
850            _ => None,
851        }
852    }
853}
854
855/// Collect the leading prose of a doc comment (the lines before the first
856/// `@tag`, [`LineRole::Prose`]) as roxygen `@description` text, its links
857/// treated per the crate's [`ProseLinks`] setting (passed in, so the unit tests
858/// need no manifest; [`roxygen_tags_with`] passes `Strip` for a block that
859/// renders no page).
860///
861/// The lines ([`doc_lines`]) keep their line breaks, blank lines (roxygen2
862/// paragraph breaks, rendered as bare `#'` lines by `push_roxygen_tags`) and
863/// indentation, so a markdown list, a nested item or a fenced block reaches
864/// roxygen2 as written. Leading and trailing blank lines are dropped. With
865/// [`ProseLinks::Strip`] every link is neutralized; with [`ProseLinks::Keep`]
866/// only the rustdoc-only ones are ([`sanitize_prose_links`]).
867///
868/// Returns `None` when the block has no leading prose (empty, or starts with a `@tag`),
869/// so tag-led blocks never gain a spurious `@description`.
870fn leading_prose_from_attrs(attrs: &[syn::Attribute], links: ProseLinks) -> Option<String> {
871    let lines = doc_lines(attrs);
872    let prose: Vec<&str> = lines
873        .iter()
874        .zip(classify(&lines))
875        .take_while(|(_, role)| *role == LineRole::Prose)
876        .map(|(line, _)| line.text.as_str())
877        .collect();
878    let first = prose.iter().position(|line| !line.is_empty())?;
879    let last = prose.iter().rposition(|line| !line.is_empty())?;
880    let prose = &prose[first..=last];
881    Some(match links {
882        ProseLinks::Strip => sanitize_prose_links(prose, Neutralize::AllLinks),
883        ProseLinks::Keep => sanitize_prose_links(prose, Neutralize::RustdocOnly),
884    })
885}
886
887/// An explicit tag with the `links` of its text neutralized: the rustdoc-only
888/// ones ([`Neutralize::RustdocOnly`]), or all of them in a block that renders
889/// no page ([`Neutralize::AllLinks`]). A code tag ([`CODE_TAGS`]) stays as
890/// written.
891fn neutralize_tag_links(tag: String, links: Neutralize) -> String {
892    if roxygen_tag_name(&tag).is_some_and(|name| CODE_TAGS.contains(&name)) {
893        return tag;
894    }
895    sanitize_prose_links(&tag.lines().collect::<Vec<_>>(), links)
896}
897
898/// Which `[...]` links [`sanitize_roxygen_links`] reduces to their text.
899#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Neutralize {
}
#[automatically_derived]impl ::core::clone::Clone for Neutralize {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Neutralize { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    Neutralize {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Neutralize {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Neutralize { }Eq)]
900enum Neutralize {
901    /// Every link: leading prose under [`ProseLinks::Strip`], and the prose
902    /// and tag text of a block that renders no page ([`RdPage`]).
903    AllLinks,
904    /// Only a link whose target roxygen2 can never resolve
905    /// ([`is_rustdoc_only_target`]): leading prose under [`ProseLinks::Keep`],
906    /// and explicit tag text ([`neutralize_tag_links`]), in a block that
907    /// renders a page.
908    RustdocOnly,
909}
910
911/// [`sanitize_roxygen_links`] over prose lines, one paragraph (the lines
912/// between blank lines) at a time, joined back with their line breaks.
913///
914/// A link whose text and target sit on two lines of one paragraph is still
915/// found. CommonMark code spans do not cross a blank line, so an unbalanced
916/// backtick cannot switch neutralizing off beyond its paragraph. A fenced
917/// block (```` ``` ```` or `~~~`, blank lines included) is code and passes
918/// through untouched, so `x[i]` there is never rewritten.
919fn sanitize_prose_links(lines: &[&str], links: Neutralize) -> String {
920    fn flush(paragraph: &mut Vec<&str>, out: &mut Vec<String>, links: Neutralize) {
921        if !paragraph.is_empty() {
922            out.push(sanitize_roxygen_links(&paragraph.join("\n"), links));
923            paragraph.clear();
924        }
925    }
926
927    let mut out: Vec<String> = Vec::new();
928    let mut paragraph: Vec<&str> = Vec::new();
929    let mut open_fence: Option<&str> = None;
930    for &line in lines {
931        if let Some(open) = open_fence {
932            if fence_marker(line).is_some_and(|close| closes_fence(line, close, open)) {
933                open_fence = None;
934            }
935            out.push(line.to_string());
936        } else if let Some(open) = fence_marker(line) {
937            flush(&mut paragraph, &mut out, links);
938            open_fence = Some(open);
939            out.push(line.to_string());
940        } else if line.is_empty() {
941            flush(&mut paragraph, &mut out, links);
942            out.push(String::new());
943        } else {
944            paragraph.push(line);
945        }
946    }
947    flush(&mut paragraph, &mut out, links);
948    out.join("\n")
949}
950
951/// The fence run (3 or more `` ` `` or `~`) a CommonMark code-fence line
952/// starts with, after at most 3 spaces of indent.
953fn fence_marker(line: &str) -> Option<&str> {
954    let body = line.trim_start_matches(' ');
955    if line.len() - body.len() > 3 {
956        return None;
957    }
958    let fence_char = body.chars().next().filter(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '`' | '~' => true,
    _ => false,
}matches!(c, '`' | '~'))?;
959    let run = body.len() - body.trim_start_matches(fence_char).len();
960    (run >= 3).then(|| &body[..run])
961}
962
963/// Whether `line`, whose fence run is `close`, ends the block `open` began: the
964/// same character, at least as long, and nothing after it.
965fn closes_fence(line: &str, close: &str, open: &str) -> bool {
966    close.starts_with(&open[..1])
967        && close.len() >= open.len()
968        && line.trim_start_matches(' ')[close.len()..]
969            .trim()
970            .is_empty()
971}
972
973/// Neutralize rustdoc intra-doc link syntax so prose is valid roxygen2 markdown.
974///
975/// rustdoc `[`Foo`]` / `[Foo]` / `[text][target]` are intra-doc links resolved
976/// against *Rust* items by `cargo doc`. roxygen2 (markdown on) reads the same
977/// `[...]` as an R `\link{}` to a *help topic*, which can't resolve. We strip the
978/// link brackets down to the visible text (keeping any `` `code` `` span), while
979/// leaving genuine markdown links `[text](url)` — recognized by the `]( ` that
980/// follows — untouched. With [`Neutralize::AllLinks`] a roxygen2 link
981/// (`[other_fn()]`) is stripped too: the syntax is rustdoc's as well, so a
982/// crate writing for roxygen2 opts out with [`ProseLinks::Keep`]. With
983/// [`Neutralize::RustdocOnly`] only a link whose target roxygen2 can never
984/// resolve is stripped ([`is_rustdoc_only_target`]); the rest stay as written.
985///
986/// rustdoc's inline form `[text](crate::x)` is the one `[text](...)` that loses
987/// its link, under either scope: its destination is a rustdoc-only Rust path
988/// ([`inline_rustdoc_destination`]), which roxygen2 would render as a dead
989/// `\href{}`.
990fn sanitize_roxygen_links(s: &str, links: Neutralize) -> String {
991    let bytes = s.as_bytes();
992    let mut out = String::with_capacity(s.len());
993    let mut i = 0;
994    let mut in_code = false;
995    while i < s.len() {
996        if bytes[i] == b'`' {
997            // Inline code span: markdown (and roxygen2) never parse `[...]`
998            // inside backticks as a link, so neither do we — stripping there
999            // would corrupt code like `x[i]`.
1000            in_code = !in_code;
1001            out.push('`');
1002            i += 1;
1003            continue;
1004        }
1005        if !in_code && bytes[i] == b'[' {
1006            // `\[` is a backslash-escaped literal bracket (idiomatic rustdoc
1007            // for suppressing intra-doc links, e.g. `Box<\[u8\]>`). Not a link
1008            // opener — pass it through; roxygen2's markdown unescapes it.
1009            if i > 0 && bytes[i - 1] == b'\\' {
1010                out.push('[');
1011                i += 1;
1012                continue;
1013            }
1014            // `[` is ASCII, so `i + 1` is a char boundary.
1015            if let Some(close_rel) = s[i + 1..].find(']') {
1016                let close = i + 1 + close_rel;
1017                let inner = &s[i + 1..close];
1018                // `[text](dest)` — an inline link. A rustdoc-only Rust path
1019                // (`[text](crate::x)`, [`inline_rustdoc_destination`]) keeps
1020                // its text alone under every scope. Anything else is a real
1021                // markdown link: emit `[` literally and let the inner text +
1022                // `](url)` flow through unchanged.
1023                if bytes.get(close + 1) == Some(&b'(') {
1024                    if let Some(end) = inline_rustdoc_destination(s, close + 2)
1025                        && !inner.contains('[')
1026                    {
1027                        out.push_str(inner);
1028                        i = end;
1029                    } else {
1030                        out.push('[');
1031                        i += 1;
1032                    }
1033                    continue;
1034                }
1035                // `[text][target]` — reference link; `[text]` — shortcut link,
1036                // its own target.
1037                let (target, end) = match bytes.get(close + 1) {
1038                    Some(b'[') => match s[close + 2..].find(']') {
1039                        Some(t_rel) => (&s[close + 2..close + 2 + t_rel], close + 2 + t_rel + 1),
1040                        None => (inner, close + 1),
1041                    },
1042                    _ => (inner, close + 1),
1043                };
1044                // Keep `text`, drop the brackets and any `[target]`.
1045                if links == Neutralize::AllLinks || is_rustdoc_only_target(target) {
1046                    out.push_str(inner);
1047                } else {
1048                    out.push_str(&s[i..end]);
1049                }
1050                i = end;
1051                continue;
1052            }
1053        }
1054        let ch = s[i..].chars().next().unwrap();
1055        out.push(ch);
1056        i += ch.len_utf8();
1057    }
1058    out
1059}
1060
1061/// The end (past its `)`) of the destination of an inline link `[text](dest)`
1062/// starting at byte `start` (just past the `(`), when that destination was
1063/// written for rustdoc: a Rust path ([`is_rust_path`]) containing `::`, with
1064/// an optional disambiguator prefix ([`strip_rustdoc_disambiguator`]), such as
1065/// `crate::x`, `serde::Serialize` or `fn@Self::new`.
1066///
1067/// rustdoc reads `[text](crate::x)` as an intra-doc link; roxygen2 reads it as
1068/// a web link and renders `\href{crate::x}{text}`, a dead link, without a
1069/// warning (#1744). roxygen2 never reads the inline form as an R link, so the
1070/// root of the path does not matter (`dplyr::bind_rows` is as dead as
1071/// `crate::x`, #1756). `None` for an unclosed destination, one that spans
1072/// whitespace, any URL (`https://a.b/c::d`, `./x.html`), and a path without
1073/// `::`: `Foo`, which a relative URL may spell.
1074fn inline_rustdoc_destination(s: &str, start: usize) -> Option<usize> {
1075    // The matching `)`: a destination may hold balanced parentheses, as the
1076    // `()` of `crate::f()` does.
1077    let mut depth = 1usize;
1078    let close = start
1079        + s[start..].find(|c: char| {
1080            match c {
1081                '(' => depth += 1,
1082                ')' => depth -= 1,
1083                _ => {}
1084            }
1085            depth == 0 || c.is_whitespace()
1086        })?;
1087    if s.as_bytes()[close] != b')' {
1088        return None;
1089    }
1090    let dest = &s[start..close];
1091    let path = strip_rustdoc_disambiguator(dest);
1092    (is_rust_path(path) && path.contains("::")).then_some(close + 1)
1093}
1094
1095/// `dest` without a rustdoc disambiguator prefix (`fn@crate::x` -> `crate::x`).
1096/// rustdoc's prefixes are the item kinds below; any other `word@rest` is left
1097/// whole and so fails [`is_rust_path`].
1098fn strip_rustdoc_disambiguator(dest: &str) -> &str {
1099    const KINDS: &[&str] = &[
1100        "struct",
1101        "enum",
1102        "trait",
1103        "union",
1104        "mod",
1105        "module",
1106        "const",
1107        "constant",
1108        "static",
1109        "function",
1110        "fn",
1111        "method",
1112        "derive",
1113        "type",
1114        "tyalias",
1115        "typealias",
1116        "macro",
1117        "prim",
1118        "primitive",
1119        "field",
1120        "variant",
1121        "value",
1122        "namespace",
1123        "attr",
1124    ];
1125    match dest.split_once('@') {
1126        Some((kind, rest)) if KINDS.contains(&kind) => rest,
1127        _ => dest,
1128    }
1129}
1130
1131/// Whether `dest` is a Rust path as an inline link destination writes it:
1132/// identifiers joined by `::`, with an optional `()` or `!` suffix. A URL with
1133/// a `/`, `.`, `#`, `?` or lone `:` never is one, even with a `::` in it
1134/// (`https://a.b/c::d`). A bare `Foo` can be either, so the caller also asks
1135/// for a `::`.
1136fn is_rust_path(dest: &str) -> bool {
1137    let path = dest
1138        .strip_suffix("()")
1139        .or_else(|| dest.strip_suffix('!'))
1140        .unwrap_or(dest);
1141    path.split("::").all(|segment| {
1142        let mut chars = segment.chars();
1143        chars
1144            .next()
1145            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
1146            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1147    })
1148}
1149
1150/// Whether roxygen2 can never resolve the link target `target`, so the link
1151/// was written for rustdoc.
1152///
1153/// roxygen2 reads `pkg::topic` as a link into the R package `pkg`, everything
1154/// before the last `::`, and warns "refers to un-installed package" when no
1155/// such package is installed. A target is rustdoc-only when that `pkg` is a
1156/// Rust path root (`crate`, `self`, `Self`) or cannot be an R package name
1157/// (`a::b`, `my_mod`; see [`crate::naming::is_r_package_name`]). Backticks around the target
1158/// are ignored, as both readers do. Anything else may be an R link, so it is
1159/// left alone: `[topic]`, `` [`topic`] ``, `[fn()]` and `[pkg::topic]`, which
1160/// roxygen2 documents, and so `` [`Type::method`] `` (`Type` can be a package:
1161/// `R6`, `S7`, `Matrix`) and `[super::x]` (`super` is on CRAN).
1162fn is_rustdoc_only_target(target: &str) -> bool {
1163    let target = target.trim();
1164    let target = target
1165        .strip_prefix('`')
1166        .and_then(|t| t.strip_suffix('`'))
1167        .unwrap_or(target);
1168    let Some((pkg, _)) = target.rsplit_once("::") else {
1169        return false;
1170    };
1171    #[allow(non_exhaustive_omitted_patterns)] match pkg {
    "crate" | "self" | "Self" => true,
    _ => false,
}matches!(pkg, "crate" | "self" | "Self") || !crate::naming::is_r_package_name(pkg)
1172}
1173
1174/// Check for conflicts between explicit `@title`/`@description` tags and implicit values.
1175///
1176/// When the `doc-lint` feature is enabled, returns tokens that generate compile-time
1177/// deprecation warnings if explicit roxygen tags differ from the implicit values
1178/// derived from the doc comment structure.
1179///
1180/// The returned tokens should be appended to the macro expansion output.
1181#[cfg(feature = "doc-lint")]
1182pub(crate) fn doc_conflict_warnings(
1183    attrs: &[syn::Attribute],
1184    _span: proc_macro2::Span,
1185) -> proc_macro2::TokenStream {
1186    use quote::quote;
1187
1188    // Raw parse only: `roxygen_tags_from_attrs` synthesizes a `@description`
1189    // from leading prose, which this lint must not mistake for an
1190    // author-written tag (#1172).
1191    let tags = explicit_roxygen_tags_from_attrs(attrs);
1192    let mut warnings = proc_macro2::TokenStream::new();
1193
1194    // Check @title conflict
1195    if let Some(explicit) = find_tag_value(&tags, "title")
1196        && let Some(implicit) = implicit_title_from_attrs(attrs)
1197        && normalize_for_comparison(explicit) != normalize_for_comparison(&implicit)
1198    {
1199        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr doc-lint: explicit @title differs from first doc line. R\'s roxygen2 uses the first line as the title. implicit: \"{0}\", explicit @title: \"{1}\"",
                implicit, explicit))
    })format!(
1200            "miniextendr doc-lint: explicit @title differs from first doc line. \
1201             R's roxygen2 uses the first line as the title. \
1202             implicit: \"{}\", explicit @title: \"{}\"",
1203            implicit, explicit
1204        );
1205        warnings.extend({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_underscore(&mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "deprecated");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "note");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::ToTokens::to_tokens(&msg, &mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "doc");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "hidden");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "allow");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "dead_code");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "const");
            ::quote::__private::push_ident(&mut _s,
                "MINIEXTENDR_DOC_LINT_TITLE");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_underscore(&mut _s);
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s,
                "MINIEXTENDR_DOC_LINT_TITLE");
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
1206            const _: () = {
1207                #[deprecated(note = #msg)]
1208                #[doc(hidden)]
1209                #[allow(dead_code)]
1210                const MINIEXTENDR_DOC_LINT_TITLE: () = ();
1211                let _ = MINIEXTENDR_DOC_LINT_TITLE;
1212            };
1213        });
1214    }
1215
1216    // Check @description conflict
1217    if let Some(explicit) = find_tag_value(&tags, "description")
1218        && let Some(implicit) = implicit_description_from_attrs(attrs)
1219        && normalize_for_comparison(explicit) != normalize_for_comparison(&implicit)
1220    {
1221        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr doc-lint: explicit @description differs from first paragraph. R\'s roxygen2 uses the first paragraph as the description. implicit: \"{0}\", explicit @description: \"{1}\"",
                implicit, explicit))
    })format!(
1222            "miniextendr doc-lint: explicit @description differs from first paragraph. \
1223             R's roxygen2 uses the first paragraph as the description. \
1224             implicit: \"{}\", explicit @description: \"{}\"",
1225            implicit, explicit
1226        );
1227        warnings.extend({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_underscore(&mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "deprecated");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "note");
                            ::quote::__private::push_eq(&mut _s);
                            ::quote::ToTokens::to_tokens(&msg, &mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "doc");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "hidden");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "allow");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "dead_code");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "const");
            ::quote::__private::push_ident(&mut _s,
                "MINIEXTENDR_DOC_LINT_DESC");
            ::quote::__private::push_colon(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_ident(&mut _s, "let");
            ::quote::__private::push_underscore(&mut _s);
            ::quote::__private::push_eq(&mut _s);
            ::quote::__private::push_ident(&mut _s,
                "MINIEXTENDR_DOC_LINT_DESC");
            ::quote::__private::push_semi(&mut _s);
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
1228            const _: () = {
1229                #[deprecated(note = #msg)]
1230                #[doc(hidden)]
1231                #[allow(dead_code)]
1232                const MINIEXTENDR_DOC_LINT_DESC: () = ();
1233                let _ = MINIEXTENDR_DOC_LINT_DESC;
1234            };
1235        });
1236    }
1237
1238    warnings
1239}
1240
1241/// No-op when doc-lint feature is disabled.
1242#[cfg(not(feature = "doc-lint"))]
1243pub(crate) fn doc_conflict_warnings(
1244    _attrs: &[syn::Attribute],
1245    _span: proc_macro2::Span,
1246) -> proc_macro2::TokenStream {
1247    proc_macro2::TokenStream::new()
1248}
1249
1250/// Roxygen tags that only make sense on individual methods, not on impl blocks.
1251///
1252/// - `@param` — impl blocks have no parameters (except for R6 class-level param docs,
1253///   which roxygen2 8.0.0 inherits into all methods; those are exempted by
1254///   [`strip_method_tags_r6`]).
1255/// - `@return` / `@returns` — impl blocks have no return value.
1256/// - `@examples` — examples belong on the method that is being demonstrated.
1257/// - `@export` — redundant: export for class-level docs is handled by
1258///   `ClassDocBuilder`, which emits `@export` based on the impl block's
1259///   `internal` / `noexport` attrs, not on user-supplied roxygen.
1260const METHOD_ONLY_TAGS: &[&str] = &["param", "return", "returns", "examples", "export"];
1261
1262/// Tags stripped from impl-block docs for R6 classes — same as `METHOD_ONLY_TAGS`
1263/// minus `"param"`, since roxygen2 8.0.0 inherits class-level `@param` tags into
1264/// all R6 methods and strips them from the rendered method entries automatically.
1265/// This means `/// @param breed …` on an R6 impl block is valid and intentional,
1266/// not a misplaced method-only tag. Keeping them avoids both the compile warning
1267/// and the resulting `(no documentation available)` placeholder on subclass ctors.
1268const METHOD_ONLY_TAGS_R6: &[&str] = &["return", "returns", "examples", "export"];
1269
1270/// Extract the tag name from a roxygen line (everything between `@` and the
1271/// first whitespace character). Returns `None` for lines that don't start with
1272/// a tag.
1273pub(crate) fn roxygen_tag_name(tag: &str) -> Option<&str> {
1274    let rest = tag.trim_start().strip_prefix('@')?;
1275    let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
1276    Some(&rest[..end])
1277}
1278
1279/// Whether a method block without `\usage` (an env method `Type$method`, a
1280/// trait method `Type$Trait$method`) forwards the author tag `tag`: every tag
1281/// but a bare `@export`. On such a block roxygen2's namespace roclet turns a
1282/// bare `@export` into `export("Type$method")`, and R refuses to load the
1283/// namespace ("undefined exports"). The member is reachable through its
1284/// exported class, so exporting it is never valid. An `@export <symbol>`
1285/// names its own target and is forwarded.
1286pub(crate) fn forwarded_member_tag(tag: &str) -> bool {
1287    !tag.trim_start()
1288        .strip_prefix("@export")
1289        .is_some_and(|rest| rest.trim().is_empty())
1290}
1291
1292/// Filter out method-specific roxygen tags from impl-block-level docs and emit
1293/// compile warnings for each stripped tag.
1294///
1295/// Method-specific tags (`@param`, `@return`, `@returns`, `@examples`,
1296/// `@export`) on an impl block are meaningless — they belong on individual
1297/// methods, or (for `@export`) are emitted by `ClassDocBuilder`. When users
1298/// put them on impl blocks, the tags leak into the class-level Rd file where
1299/// R CMD check warns about "documented arguments not in \\usage" and similar.
1300///
1301/// Each stripped tag's warning is wrapped in its own anonymous
1302/// `const _: () = { ... };` block (same pattern as [`doc_conflict_warnings`]),
1303/// so the inner const names can stay fixed — an anonymous const block is a
1304/// fresh item scope every expansion, so two `#[miniextendr] impl Foo` blocks
1305/// on the *same* type (e.g. an inherent impl plus a trait impl) never collide
1306/// with `error[E0428]: the name ... is defined multiple times`, without any
1307/// per-block disambiguator (#1118).
1308///
1309/// Returns the filtered tags and a TokenStream of deprecation warnings for
1310/// each stripped tag. The caller should append the warnings to its output so
1311/// the user sees them at compile time.
1312pub(crate) fn strip_method_tags(
1313    tags: &[String],
1314    type_name: &str,
1315    span: proc_macro2::Span,
1316) -> (Vec<String>, proc_macro2::TokenStream) {
1317    strip_tags_in(tags, type_name, span, METHOD_ONLY_TAGS)
1318}
1319
1320/// Shared body of [`strip_method_tags`] and [`strip_method_tags_r6`]: drop
1321/// every tag whose name is in `method_only` and emit one warning const scope
1322/// per dropped tag. The two public entry points differ only in the tag table.
1323fn strip_tags_in(
1324    tags: &[String],
1325    type_name: &str,
1326    span: proc_macro2::Span,
1327    method_only: &[&str],
1328) -> (Vec<String>, proc_macro2::TokenStream) {
1329    use quote::quote_spanned;
1330
1331    let mut filtered = Vec::new();
1332    let mut warnings = proc_macro2::TokenStream::new();
1333
1334    for tag in tags {
1335        let Some(name) = roxygen_tag_name(tag) else {
1336            filtered.push(tag.clone());
1337            continue;
1338        };
1339        if !method_only.contains(&name) {
1340            // Keeps unrecognised tags (and, for R6, @param) without warning.
1341            filtered.push(tag.clone());
1342            continue;
1343        }
1344        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: @{0} on impl block `{1}` has no effect — move it to the method. Tag: {2}",
                name, type_name, tag.trim()))
    })format!(
1345            "miniextendr: @{} on impl block `{}` has no effect — move it to the method. Tag: {}",
1346            name,
1347            type_name,
1348            tag.trim()
1349        );
1350        warnings.extend({
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(span).__into_span();
    ::quote::__private::push_ident_spanned(&mut _s, _span, "const");
    ::quote::__private::push_underscore_spanned(&mut _s, _span);
    ::quote::__private::push_colon_spanned(&mut _s, _span);
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let _: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::__private::TokenStream::new()
        });
    ::quote::__private::push_eq_spanned(&mut _s, _span);
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            let _span: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::__private::push_pound_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "deprecated");
                    ::quote::__private::push_group_spanned(&mut _s, _span,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            let _span: ::quote::__private::Span =
                                ::quote::__private::get_span(_span).__into_span();
                            ::quote::__private::push_ident_spanned(&mut _s, _span,
                                "note");
                            ::quote::__private::push_eq_spanned(&mut _s, _span);
                            ::quote::ToTokens::to_tokens(&msg, &mut _s);
                            _s
                        });
                    _s
                });
            ::quote::__private::push_pound_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "doc");
                    ::quote::__private::push_group_spanned(&mut _s, _span,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            let _span: ::quote::__private::Span =
                                ::quote::__private::get_span(_span).__into_span();
                            ::quote::__private::push_ident_spanned(&mut _s, _span,
                                "hidden");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_pound_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "allow");
                    ::quote::__private::push_group_spanned(&mut _s, _span,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            let _span: ::quote::__private::Span =
                                ::quote::__private::get_span(_span).__into_span();
                            ::quote::__private::push_ident_spanned(&mut _s, _span,
                                "dead_code");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_ident_spanned(&mut _s, _span, "const");
            ::quote::__private::push_ident_spanned(&mut _s, _span,
                "_MINIEXTENDR_IMPL_METHOD_TAG_WARN");
            ::quote::__private::push_colon_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let _: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::TokenStream::new()
                });
            ::quote::__private::push_eq_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let _: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::TokenStream::new()
                });
            ::quote::__private::push_semi_spanned(&mut _s, _span);
            ::quote::__private::push_pound_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "doc");
                    ::quote::__private::push_group_spanned(&mut _s, _span,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            let _span: ::quote::__private::Span =
                                ::quote::__private::get_span(_span).__into_span();
                            ::quote::__private::push_ident_spanned(&mut _s, _span,
                                "hidden");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_pound_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "allow");
                    ::quote::__private::push_group_spanned(&mut _s, _span,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            let _span: ::quote::__private::Span =
                                ::quote::__private::get_span(_span).__into_span();
                            ::quote::__private::push_ident_spanned(&mut _s, _span,
                                "dead_code");
                            _s
                        });
                    _s
                });
            ::quote::__private::push_ident_spanned(&mut _s, _span, "const");
            ::quote::__private::push_ident_spanned(&mut _s, _span,
                "_MINIEXTENDR_IMPL_METHOD_TAG_USE");
            ::quote::__private::push_colon_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let _: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::TokenStream::new()
                });
            ::quote::__private::push_eq_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span,
                "_MINIEXTENDR_IMPL_METHOD_TAG_WARN");
            ::quote::__private::push_semi_spanned(&mut _s, _span);
            _s
        });
    ::quote::__private::push_semi_spanned(&mut _s, _span);
    _s
}quote_spanned! { span =>
1351            const _: () = {
1352                #[deprecated(note = #msg)]
1353                #[doc(hidden)]
1354                #[allow(dead_code)]
1355                const _MINIEXTENDR_IMPL_METHOD_TAG_WARN: () = ();
1356                #[doc(hidden)]
1357                #[allow(dead_code)]
1358                const _MINIEXTENDR_IMPL_METHOD_TAG_USE: () = _MINIEXTENDR_IMPL_METHOD_TAG_WARN;
1359            };
1360        });
1361    }
1362
1363    (filtered, warnings)
1364}
1365
1366/// Extract the set of parameter names declared via `@param` in a list of roxygen tags.
1367///
1368/// For each `@param <names> <desc>` tag in `tags`, extracts `<names>` and inserts
1369/// each comma-separated name into the returned `HashSet`. roxygen2 supports
1370/// documenting several params in one tag (`@param a,b,c desc` documents `a`,
1371/// `b`, and `c`) — the name token is split on `,` (and each piece trimmed
1372/// defensively, though roxygen2's own syntax has no spaces around the commas)
1373/// so multi-name tags don't collapse to a single name. Used by R6 class
1374/// generators to build the set of class-level params so method param loops
1375/// can suppress `(no documentation available)` for names already covered at
1376/// class level (roxygen2 8.0.0 inherits class-level `@param` tags into all
1377/// methods automatically).
1378pub(crate) fn extract_param_names(tags: &[String]) -> HashSet<String> {
1379    let mut names = HashSet::new();
1380    for tag in tags {
1381        let Some(names_token) = param_names_token(tag) else {
1382            continue;
1383        };
1384        for name in names_token.split(',') {
1385            let name = name.trim();
1386            if !name.is_empty() {
1387                names.insert(name.to_string());
1388            }
1389        }
1390    }
1391    names
1392}
1393
1394/// Returns `true` if `name` is documented by any `@param` tag in `tags`.
1395///
1396/// A tag documents `name` if `name` is exactly one of the comma-separated
1397/// names in its `@param <names> <desc>` name token (see
1398/// [`extract_param_names`]). This is an **exact-membership** check, not a
1399/// prefix match — `starts_with(&format!("@param {name}"))` was the previous
1400/// (buggy) approach: it misses every name after the first in a comma-list
1401/// tag (`@param a,b,c desc` "documents" only `a`, so `b`/`c` get a spurious
1402/// `(no documentation available)` filler that roxygen2 then merges into a
1403/// duplicate `\item{b}` and `\item{c}` in the rendered Rd — an
1404/// `R CMD check` `checking Rd \usage sections` WARNING), and it also
1405/// false-positives on names that are prefixes of other names (`@param x2
1406/// desc` looks like it documents `x` too).
1407pub(crate) fn param_documented(tags: &[String], name: &str) -> bool {
1408    tags.iter().any(|tag| tag_documents_param(tag, name))
1409}
1410
1411/// Like [`param_documented`] but returns the matching tag itself rather than
1412/// a bool, for callers that reuse the tag's rendered text verbatim (S7
1413/// constructor param doc forwarding pushes the found tag as-is).
1414pub(crate) fn find_param_tag<'a>(tags: &'a [String], name: &str) -> Option<&'a String> {
1415    tags.iter().find(|tag| tag_documents_param(tag, name))
1416}
1417
1418/// Shared predicate: does this single `@param` tag document `name`?
1419fn tag_documents_param(tag: &str, name: &str) -> bool {
1420    let Some(names_token) = param_names_token(tag) else {
1421        return false;
1422    };
1423    names_token.split(',').any(|n| n.trim() == name)
1424}
1425
1426/// Rename what the `@param` tags in `tags` document: each name in a tag's
1427/// name token (`a,b` in `@param a,b desc`) that `rename` maps is replaced,
1428/// and the rest of the tag is kept as written. The names map at once, so two
1429/// parameters can swap names.
1430///
1431/// A name a rename produces must then be documented once: `Err` names the
1432/// tag that was renamed onto a name another tag already documents.
1433pub(crate) fn rename_param_tags(
1434    tags: &mut [String],
1435    rename: impl Fn(&str) -> Option<String>,
1436) -> Result<(), String> {
1437    let mut renamed = Vec::new();
1438    for tag in tags.iter_mut() {
1439        // The name token's place in the tag, as `param_names_token` finds it.
1440        let lead = tag.len() - tag.trim_start().len();
1441        let Some(rest) = tag[lead..].strip_prefix("@param ") else {
1442            continue;
1443        };
1444        let start = tag.len() - rest.trim_start().len();
1445        let end = tag[start..]
1446            .find(char::is_whitespace)
1447            .map_or(tag.len(), |n| start + n);
1448        let mut changed = false;
1449        let names: Vec<String> = tag[start..end]
1450            .split(',')
1451            .map(|name| match rename(name) {
1452                Some(new) => {
1453                    changed = true;
1454                    renamed.push((name.to_string(), new.clone()));
1455                    new
1456                }
1457                None => name.to_string(),
1458            })
1459            .collect();
1460        if changed {
1461            tag.replace_range(start..end, &names.join(","));
1462        }
1463    }
1464    for (old, new) in renamed {
1465        let documented = tags
1466            .iter()
1467            .filter_map(|tag| param_names_token(tag))
1468            .flat_map(|token| token.split(','))
1469            .filter(|name| *name == new)
1470            .count();
1471        if documented > 1 {
1472            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`@param {0}` documents the trait\'s parameter `{1}`, which another `@param` documents too; keep one of them",
                old, new))
    })format!(
1473                "`@param {old}` documents the trait's parameter `{new}`, which another \
1474                 `@param` documents too; keep one of them"
1475            ));
1476        }
1477    }
1478    Ok(())
1479}
1480
1481/// Returns the `@param` name token (e.g. `a,b,c` in `@param a,b,c desc`) of a
1482/// single tag, or `None` if `tag` isn't an `@param` tag.
1483fn param_names_token(tag: &str) -> Option<&str> {
1484    let trimmed = tag.trim_start();
1485    let rest = trimmed.strip_prefix("@param ")?;
1486    rest.split_whitespace().next()
1487}
1488
1489// region: shared pages (#1590)
1490
1491/// The topic named by the tag list's own `@describeIn <topic> <description>`
1492/// tag, if it has one.
1493pub(crate) fn describe_in_topic(tags: &[String]) -> Option<&str> {
1494    tags.iter().find_map(|t| {
1495        let rest = t.trim_start().strip_prefix("@describeIn")?;
1496        if rest.starts_with(char::is_whitespace) {
1497            rest.split_whitespace().next()
1498        } else {
1499            None
1500        }
1501    })
1502}
1503
1504/// Whether the author's tags put the block on a topic other than
1505/// `default_page`: `@describeIn topic ...`, or an `@rdname topic` that names
1506/// another page. The block then joins a topic whose own block (usually the
1507/// author's, often in R) documents the page, so generated lines that claim the
1508/// page (a structural `@param`, the page `\name` and title) must give way to it.
1509///
1510/// `tags` must be the author's own tags (doc comment or `doc = "..."`), and
1511/// `default_page` the page the framework puts the block on anyway: a class
1512/// generator passes the class name, so a redundant author `@rdname <Class>`
1513/// counts as no page tag. A standalone function passes `None` (whether an
1514/// `@rdname` names its own page or its file's stem page is only known when
1515/// the wrapper registry writes the file), so any `@rdname` counts there.
1516pub(crate) fn joins_author_topic(tags: &[String], default_page: Option<&str>) -> bool {
1517    describe_in_topic(tags).is_some()
1518        || rdname_value(tags).is_some_and(|topic| Some(topic) != default_page)
1519}
1520
1521/// The page a method's block lands on: its `@describeIn` destination (roxygen2
1522/// files a `@describeIn` block under the destination's topic), its own
1523/// `@rdname`, else `default_page` (the class page). A companion block that
1524/// must share the method's page (the S3 generic block, whose class-qualified
1525/// `@name` is also the method's alias) gets `@rdname` this.
1526pub(crate) fn method_page<'a>(tags: &'a [String], default_page: &'a str) -> &'a str {
1527    describe_in_topic(tags)
1528        .or_else(|| rdname_value(tags))
1529        .unwrap_or(default_page)
1530}
1531
1532/// Whether the author's tags inherit the parameter docs from another topic:
1533/// `@inheritParams source`, or `@inherit source` whose field list includes
1534/// params (roxygen2 inherits every field when none is listed). roxygen2 fills
1535/// only the arguments the merged topic leaves undocumented, so a generated
1536/// line would block the inheritance.
1537fn inherits_params(tags: &[String]) -> bool {
1538    tags.iter().any(|tag| match roxygen_tag_name(tag) {
1539        Some("inheritParams") => true,
1540        Some("inherit") => {
1541            let mut fields = tag.split_whitespace().skip(2).peekable(); // `@inherit`, source
1542            fields.peek().is_none() || fields.any(|field| field == "params")
1543        }
1544        _ => false,
1545    })
1546}
1547
1548/// Returns `true` when the author's roxygen block takes its argument
1549/// documentation from another block, so the generators must not add `@param`
1550/// lines for the arguments it leaves undocumented (#1590):
1551///
1552/// - the block joins another topic ([`joins_author_topic`]: `@rdname topic`,
1553///   `@describeIn topic ...`), whose own block documents the arguments.
1554///   roxygen2 keeps one entry per argument name on a merged page, and a
1555///   generated line such as `(no documentation available)` is the entry that
1556///   survives, so it would replace the topic's description (and add a second
1557///   entry beside a grouped `@param a,b`);
1558/// - the block inherits them ([`inherits_params`]).
1559///
1560/// An argument that no block documents is still reported by `R CMD check`
1561/// ("Undocumented arguments in Rd file"), so nothing goes missing silently.
1562/// See [`joins_author_topic`] for `tags` and `default_page`.
1563pub(crate) fn params_documented_elsewhere(tags: &[String], default_page: Option<&str>) -> bool {
1564    joins_author_topic(tags, default_page) || inherits_params(tags)
1565}
1566
1567/// The `@order` tag that sorts a generated block after every block without
1568/// one, so the topic's own block claims a merged page regardless of R file
1569/// order (#1590).
1570///
1571/// roxygen2 gives a merged page the `\name` and `\title` of the first block
1572/// it reads, and every block contributes a `\name` (a `@describeIn` block
1573/// too, from its object), so dropping generated titles cannot fix the page
1574/// name. Blocks are read in `order_blocks()` order: every block of the
1575/// package sorted with `order(as.double(<@order>))`, `Inf` for a block
1576/// without `@order`, which is stable and puts `NaN` last. A generated block
1577/// that joins an author topic therefore sorts after the author's block
1578/// wherever the R files sit, and the generated blocks of one topic keep their
1579/// source order among themselves (a topic made only of generated blocks
1580/// renders as before). On a merged page a later block's `@param` wins, which
1581/// is why joining blocks also drop their generated `@param` lines.
1582pub(crate) const ORDER_AFTER_TOPIC_BLOCKS: &str = "@order NaN";
1583
1584/// Whether a block with the author's `tags` gets `@order NaN`
1585/// ([`ORDER_AFTER_TOPIC_BLOCKS`]): it joins an author topic
1586/// ([`joins_author_topic`] against `default_page`), the author did not order
1587/// it with their own `@order`, and it renders a page (no `@noRd`).
1588pub(crate) fn orders_after_topic_blocks(tags: &[String], default_page: &str) -> bool {
1589    joins_author_topic(tags, Some(default_page))
1590        && !has_roxygen_tag(tags, "order")
1591        && !has_roxygen_tag(tags, "noRd")
1592}
1593
1594/// Push `#' @order NaN` ([`ORDER_AFTER_TOPIC_BLOCKS`]) when
1595/// [`orders_after_topic_blocks`] holds.
1596pub(crate) fn push_order_after_topic_blocks(
1597    lines: &mut Vec<String>,
1598    tags: &[String],
1599    default_page: &str,
1600) {
1601    if orders_after_topic_blocks(tags, default_page) {
1602        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}",
                ORDER_AFTER_TOPIC_BLOCKS))
    })format!("#' {ORDER_AFTER_TOPIC_BLOCKS}"));
1603    }
1604}
1605
1606/// Prefix of a generated `@param` line in a standalone function's wrapper
1607/// (`#' .__MX_PARAM_FILLER__ @param x (no documentation available)`), for the
1608/// wrapper registry to resolve when it writes the file
1609/// (`resolve_standalone_pages` in `miniextendr-api/src/registry.rs`, which
1610/// spells the same prefix). Whether an author `@rdname topic` names the
1611/// function's own page or its file's stem page (the opt-in group page,
1612/// #1289), and whether another function on the page documents the argument,
1613/// is only known then. The registry keeps the line (without the prefix) when
1614/// the function stays on its own or file-stem page and no other function
1615/// there documents the argument, and drops it otherwise. roxygen2 keeps the later of two `@param` lines for one name, so
1616/// a filler written after the real description would replace it.
1617pub(crate) const PARAM_FILLER_MARKER: &str = ".__MX_PARAM_FILLER__ ";
1618
1619/// Append the generated `@param` tags for a standalone function's R
1620/// parameters to the author's `tags`, and return the `(doc_placeholder,
1621/// rust_param)` pair of every match_arg parameter that received the
1622/// write-time placeholder (the resolver registry needs one
1623/// `MX_MATCH_ARG_PARAM_DOCS` entry each).
1624///
1625/// Every non-dots parameter the author left undocumented gets, in order of
1626/// preference:
1627///
1628/// 1. `choices(...)`: the quoted list, "One of ..." / "One or more of ...";
1629/// 2. `match_arg`: a placeholder the wrapper writer resolves (#210);
1630/// 3. a `Missing<..>` parameter with a default:
1631///    [`MISSING_DEFAULT_PARAM_DOC`](crate::miniextendr_fn::MISSING_DEFAULT_PARAM_DOC)
1632///    (#2161);
1633/// 4. anything else: `(no documentation available)`.
1634///
1635/// Each line carries [`PARAM_FILLER_MARKER`], so the wrapper registry decides
1636/// whether it is written. Nothing is generated when the block takes its
1637/// arguments from elsewhere whatever page it sits on: `@describeIn` (the
1638/// destination documents them) or inherited params ([`inherits_params`]).
1639///
1640/// `call_param_doc` is the text for the trailing `.call` formal of a
1641/// `call = caller` or `call_arg` wrapper ([`CallAttribution::param_doc`],
1642/// #1613, #1834), appended after the parameters' lines unless the author
1643/// documented `.call`. It is no filler: the line is written as the author's
1644/// would be, under `@describeIn` and inherited params too. The formal is
1645/// generated, so the topic a block joins, or the topic it inherits from, has
1646/// it documented only when another generated block on that page does, and
1647/// roxygen2 merges equal `@param .call` lines of one page into one entry.
1648///
1649/// [`CallAttribution::param_doc`]: crate::r_wrapper_builder::CallAttribution::param_doc
1650pub(crate) fn push_fn_param_tags(
1651    tags: &mut Vec<String>,
1652    inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
1653    parsed: &crate::miniextendr_fn::MiniextendrFunctionParsed,
1654    c_ident: &str,
1655    call_param_doc: Option<&str>,
1656) -> Vec<(String, String)> {
1657    let mut match_arg_doc_placeholders = Vec::new();
1658    let missing_default_docs = parsed.missing_default_param_docs();
1659    let call_line = call_param_doc
1660        .filter(|_| !param_documented(tags, ".call"))
1661        .map(|doc| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@param .call {0}", doc))
    })format!("@param .call {doc}"));
1662    if describe_in_topic(tags).is_some() || inherits_params(tags) {
1663        tags.extend(call_line);
1664        return match_arg_doc_placeholders;
1665    }
1666    let formals = parsed.formals();
1667    for arg in inputs {
1668        let syn::FnArg::Typed(pt) = arg else {
1669            continue;
1670        };
1671        let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1672            continue;
1673        };
1674        // `NArgs` is no R formal (#1860), so it gets no `@param`.
1675        if parsed.is_dots_param(&pat_ident.ident) || crate::type_inspect::is_nargs_marker(&pt.ty) {
1676            continue;
1677        }
1678        let rust_name = crate::naming::ident_name(&pat_ident.ident);
1679        // The R formal, a declared `formal` included (#1842): the author's own
1680        // `@param conf.int` documents `conf_int: f64` declared as `conf.int`.
1681        let r_name = formals.of(&rust_name);
1682        if param_documented(tags, &r_name) {
1683            continue;
1684        }
1685
1686        if let Some(doc) = parsed
1687            .param_attrs(&rust_name)
1688            .and_then(crate::miniextendr_fn::ParamAttrs::literal_choices_doc)
1689        {
1690            tags.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}@param {1} {2}",
                PARAM_FILLER_MARKER, r_name, doc))
    })format!("{PARAM_FILLER_MARKER}@param {r_name} {doc}"));
1691        } else if parsed.has_match_arg_attr(&rust_name) {
1692            let doc_placeholder = crate::match_arg_keys::param_doc_placeholder(
1693                c_ident,
1694                &crate::match_arg_keys::param_key(&rust_name),
1695            );
1696            tags.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}@param {1} {2}",
                PARAM_FILLER_MARKER, r_name, doc_placeholder))
    })format!(
1697                "{PARAM_FILLER_MARKER}@param {r_name} {doc_placeholder}"
1698            ));
1699            match_arg_doc_placeholders.push((doc_placeholder, rust_name));
1700        } else if let Some(doc) = missing_default_docs.get(&r_name) {
1701            tags.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}@param {1} {2}",
                PARAM_FILLER_MARKER, r_name, doc))
    })format!("{PARAM_FILLER_MARKER}@param {r_name} {doc}"));
1702        } else {
1703            tags.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}@param {1} (no documentation available)",
                PARAM_FILLER_MARKER, r_name))
    })format!(
1704                "{PARAM_FILLER_MARKER}@param {r_name} (no documentation available)"
1705            ));
1706        }
1707    }
1708    tags.extend(call_line);
1709    match_arg_doc_placeholders
1710}
1711
1712// endregion
1713
1714/// Split an R formals/argument string on **top-level** commas only.
1715///
1716/// Commas nested inside parentheses, brackets, or braces — or inside a single-
1717/// or double-quoted string literal — are ignored. So `x, mode = c("a", "b"), ...`
1718/// yields `["x", "mode = c(\"a\", \"b\")", "..."]`, whereas a naive
1719/// `split(", ")` wrongly breaks the `c("a", "b")` default into two bogus
1720/// formals (`mode = c("a"` and `"b")`) — the source of spurious `@param "b")`
1721/// roxygen entries on match_arg'd trait-method shortcuts (ScalerS7 / ScalerR6).
1722pub(crate) fn split_r_formals(formals: &str) -> Vec<&str> {
1723    let bytes = formals.as_bytes();
1724    let mut out = Vec::new();
1725    let mut depth: i32 = 0;
1726    let mut quote: Option<u8> = None;
1727    let mut start = 0usize;
1728    let mut i = 0usize;
1729    while i < bytes.len() {
1730        let b = bytes[i];
1731        match quote {
1732            Some(q) => {
1733                if b == b'\\' {
1734                    i += 1; // skip the escaped char
1735                } else if b == q {
1736                    quote = None;
1737                }
1738            }
1739            None => match b {
1740                b'"' | b'\'' => quote = Some(b),
1741                b'(' | b'[' | b'{' => depth += 1,
1742                b')' | b']' | b'}' => depth -= 1,
1743                b',' if depth == 0 => {
1744                    out.push(formals[start..i].trim());
1745                    start = i + 1;
1746                }
1747                _ => {}
1748            },
1749        }
1750        i += 1;
1751    }
1752    out.push(formals[start..].trim());
1753    out.into_iter().filter(|s| !s.is_empty()).collect()
1754}
1755
1756/// Extract the R parameter name from a single formal (e.g. `mode = c("a","b")`
1757/// → `mode`). Pair with [`split_r_formals`], never a raw `split(',')`.
1758pub(crate) fn formal_name(formal: &str) -> &str {
1759    formal.split('=').next().unwrap_or(formal).trim()
1760}
1761
1762/// Like [`strip_method_tags`] but for R6 impl blocks.
1763///
1764/// R6 class-level `@param` tags are **kept** (roxygen2 8.0.0 inherits them into
1765/// all methods automatically — rd-R6.Rmd §"Class-level docs"). All other
1766/// method-only tags (`@return`, `@returns`, `@examples`, `@export`) are still
1767/// stripped with a compile-time warning. No warning is generated for `@param`.
1768///
1769/// Returns `(filtered_tags, warnings)` — same shape as [`strip_method_tags`].
1770/// Each stripped tag's warning is wrapped in its own anonymous
1771/// `const _: () = { ... };` block, so no per-impl-block disambiguator is
1772/// needed to keep warning-const names unique (#1118) — see
1773/// [`strip_method_tags`] for the full rationale.
1774pub(crate) fn strip_method_tags_r6(
1775    tags: &[String],
1776    type_name: &str,
1777    span: proc_macro2::Span,
1778) -> (Vec<String>, proc_macro2::TokenStream) {
1779    strip_tags_in(tags, type_name, span, METHOD_ONLY_TAGS_R6)
1780}
1781
1782/// Strip roxygen tag lines from doc attributes, keeping only regular documentation.
1783///
1784/// Returns a new vector of attributes with roxygen lines removed from doc comments.
1785/// Non-doc attributes, and doc attributes that are not string literals
1786/// (`#[doc = include_str!(..)]`), are passed through unchanged.
1787///
1788/// # Algorithm
1789///
1790/// The lines are classified by the same rule the tag extractor reads
1791/// ([`classify`]), so text that reaches R help leaves rustdoc and text that
1792/// does not stays:
1793///
1794/// - leading prose (before the first `@tag`) is kept;
1795/// - a tag and every line it takes are dropped: the paragraphs of a
1796///   multi-line tag (`@return X` / blank / more text), the wrapped lines of a
1797///   joined tag (`@title`), a bare `@rdname`'s topic line;
1798/// - a line after a single-line tag (`@export`, `@noRd`, `@rdname topic`) is
1799///   rustdoc only and kept, with the blank line before it.
1800///
1801/// A doc attribute is dropped when its first non-blank line is a tag or tag
1802/// text, or when it is blank and inside or at the end of a tag.
1803pub(crate) fn strip_roxygen_from_attrs(attrs: &[syn::Attribute]) -> Vec<syn::Attribute> {
1804    let lines = doc_lines(attrs);
1805    let roles = classify(&lines);
1806
1807    // Each attribute's lines are contiguous; its first non-blank line decides
1808    // (its first line when all are blank).
1809    let mut roxygen_attrs = HashSet::new();
1810    let mut offset = 0;
1811    for group in lines.chunk_by(|a, b| a.attr == b.attr) {
1812        let deciding = group.iter().position(|l| !l.text.is_empty()).unwrap_or(0);
1813        if #[allow(non_exhaustive_omitted_patterns)] match roles[offset + deciding] {
    LineRole::TagStart | LineRole::TagBody => true,
    _ => false,
}matches!(
1814            roles[offset + deciding],
1815            LineRole::TagStart | LineRole::TagBody
1816        ) {
1817            roxygen_attrs.insert(group[0].attr);
1818        }
1819        offset += group.len();
1820    }
1821
1822    attrs
1823        .iter()
1824        .enumerate()
1825        .filter(|(i, _)| !roxygen_attrs.contains(i))
1826        .map(|(_, attr)| attr.clone())
1827        .collect()
1828}
1829
1830#[cfg(test)]
1831mod tests;