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//! ```
5960use std::collections::HashSet;
6162/// 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];
9899/// 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];
111112/// 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"];
117118/// 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}
127128/// 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"
131let tag_name = tag132 .strip_prefix('@')
133 .and_then(|rest| rest.split_whitespace().next())
134 .unwrap_or("");
135MULTILINE_TAGS.contains(&tag_name)
136}
137138/// Check if a tag's continuation lines are joined with a space (see [`JOINED_TAGS`]).
139fn is_joined_tag(tag: &str) -> bool {
140let tag_name = tag141 .strip_prefix('@')
142 .and_then(|rest| rest.split_whitespace().next())
143 .unwrap_or("");
144JOINED_TAGS.contains(&tag_name)
145}
146147// region: doc lines
148149/// 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.
153attr: usize,
154/// The line with its rustdoc lead removed (see [`doc_lines`]); empty for
155 /// a blank line.
156text: String,
157}
158159/// 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> {
172let mut out = Vec::new();
173for (attr, a) in attrs.iter().enumerate() {
174if !a.path().is_ident("doc") {
175continue;
176 }
177let syn::Meta::NameValue(nv) = &a.meta else {
178continue;
179 };
180let syn::Expr::Lit(expr_lit) = &nv.value else {
181continue;
182 };
183let syn::Lit::Str(lit) = &expr_lit.lit else {
184continue;
185 };
186let value = lit.value();
187// `"".lines()` yields nothing, but an empty `///` is one blank line.
188let 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 };
193let lead = if value.contains('\n') {
194 common_indent(&lines)
195 } else {
196" "
197};
198for line in lines {
199let 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 }
210out211}
212213/// The leading whitespace every non-blank line of `lines` starts with.
214fn common_indent<'a>(lines: &[&'a str]) -> &'a str {
215lines216 .iter()
217 .filter(|line| !line.trim().is_empty())
218 .map(|line| &line[..line.len() - line.trim_start().len()])
219 .reduce(|common, lead| {
220let shared = common221 .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}
230231/// 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).
236Prose,
237/// A line starting with `@` (after leading whitespace): a new tag.
238TagStart,
239/// Part of the open tag's text, or a blank line that ends a tag (trailing,
240 /// or before the next tag).
241TagBody,
242/// After a single-line tag: rustdoc only, never R. A blank line is
243 /// rustdoc when a rustdoc-only line follows it.
244Rustdoc,
245}
246247/// 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.
251Multi,
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`.
255Joined { bare_topic: bool },
256/// Any other tag: its own line only.
257Single,
258}
259260impl OpenTag {
261fn of(tag_line: &str) -> Self {
262if is_multiline_tag(tag_line) {
263Self::Multi264 } else if is_joined_tag(tag_line) {
265Self::Joined { bare_topic: false }
266 } else if is_bare_topic_tag(tag_line) {
267Self::Joined { bare_topic: true }
268 } else {
269Self::Single270 }
271 }
272}
273274/// 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> {
277let mut roles = Vec::with_capacity(lines.len());
278let mut open: Option<OpenTag> = None;
279for line in lines {
280let text = line.text.trim_start();
281let role = if text.starts_with('@') {
282 open = Some(OpenTag::of(text));
283 LineRole::TagStart
284 } else {
285match open {
286None => LineRole::Prose,
287Some(OpenTag::Multi | OpenTag::Joined { bare_topic: false }) => LineRole::TagBody,
288Some(OpenTag::Joined { bare_topic: true }) => {
289if !text.is_empty() {
290 open = Some(OpenTag::Single);
291 }
292 LineRole::TagBody
293 }
294Some(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.
301let mut next_is_rustdoc = false;
302for (line, role) in lines.iter().zip(roles.iter_mut()).rev() {
303if !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 }
309roles310}
311312// endregion
313314/// 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.
325Rendered,
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`]).
329Suppressed,
330}
331332impl RdPage {
333/// [`RdPage::Suppressed`] when `no_page`, else [`RdPage::Rendered`].
334pub(crate) fn suppressed_if(no_page: bool) -> Self {
335if no_page {
336Self::Suppressed337 } else {
338Self::Rendered339 }
340 }
341}
342343/// 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> {
353roxygen_tags_from_attrs_impl(attrs, page)
354}
355356/// 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> {
367roxygen_tags_with(attrs, ProseLinks::Strip, RdPage::Suppressed)
368}
369370/// 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> {
379roxygen_tags_from_attrs_impl(attrs, page)
380}
381382/// 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 {
386has_roxygen_tag(&explicit_roxygen_tags_from_attrs(attrs), tag)
387}
388389/// 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> {
404roxygen_tags_with(attrs, crate::crate_config::roxygen_prose_links(), page)
405}
406407/// [`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> {
415let explicit = explicit_roxygen_tags_from_attrs(attrs);
416let no_page = page == RdPage::Suppressed || has_roxygen_tag(&explicit, "noRd");
417let (links, tag_links) = if no_page {
418 (ProseLinks::Strip, Neutralize::AllLinks)
419 } else {
420 (links, Neutralize::RustdocOnly)
421 };
422let mut tags: Vec<String> = explicit423 .into_iter()
424 .map(|tag| neutralize_tag_links(tag, tag_links))
425 .collect();
426427// Check which tags are present
428let tag_names_set = tag_names(&tags);
429let has_description = tag_names_set.contains("description");
430431// 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.
445if !has_description && let Some(desc) = leading_prose_from_attrs(attrs, links) {
446tags.insert(0, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("@description {0}", desc))
})format!("@description {}", desc));
447 }
448449tags450}
451452/// 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> {
466let lines = doc_lines(attrs);
467let roles = classify(&lines);
468let 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.
471let mut pending_blanks = 0;
472473for (line, role) in lines.iter().zip(roles) {
474match role {
475 LineRole::TagStart => {
476 pending_blanks = 0;
477 tags.push(line.text.trim_start().to_string());
478 }
479 LineRole::TagBody => {
480let Some(last) = tags.last_mut() else {
481continue;
482 };
483if is_multiline_tag(last) {
484if line.text.is_empty() {
485 pending_blanks += 1;
486 } else {
487for _ 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.
495last.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.
502LineRole::Prose | LineRole::Rustdoc => {}
503 }
504 }
505506tags507}
508509/// 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 {
514if 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}
520521/// 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 {
526let mut out = String::new();
527for line in tags.iter().flat_map(|tag| tag.lines()) {
528 out.push_str(&roxygen_line(line));
529 out.push('\n');
530 }
531out532}
533534/// 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]) {
539lines.extend(tags.iter().flat_map(|tag| tag.lines()).map(roxygen_line));
540}
541542/// Like [`push_roxygen_tags`] but takes `&[&str]` for filtered tag slices.
543pub(crate) fn push_roxygen_tags_str(lines: &mut Vec<String>, tags: &[&str]) {
544lines.extend(tags.iter().flat_map(|tag| tag.lines()).map(roxygen_line));
545}
546547/// 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 {
554if tag.contains(' ') {
555// Multi-word tag: match the full content after @
556tags.iter().any(|t| {
557t.trim_start()
558 .strip_prefix('@')
559 .is_some_and(|rest| rest.trim() == tag)
560 })
561 } else {
562tag_names(tags).contains(tag)
563 }
564}
565566/// 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 {
572let names = tag_names(tags);
573names.contains("export") || names.contains("exportS3Method")
574}
575576/// 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> {
583tags.iter().find_map(|t| {
584let rest = t.trim_start().strip_prefix("@rdname")?;
585let value = rest.trim();
586 (rest.starts_with(char::is_whitespace) && !value.is_empty()).then_some(value)
587 })
588}
589590/// 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) {
594let topic = method_page(tags, default);
595lines.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#\' @rdname {0}", topic))
})format!("#' @rdname {topic}"));
596}
597598/// 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> {
606source_tag_with(crate::crate_config::source_tags_enabled(), text.as_ref())
607}
608609/// [`source_tag`] with the crate setting passed in (testable without a manifest).
610pub(crate) fn source_tag_with(enabled: bool, text: &str) -> Option<String> {
611enabled.then(|| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#\' @source {0}", text))
})format!("#' @source {text}"))
612}
613614/// 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> {
620source_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}
625626/// 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> {
629source_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}
634635/// 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> {
640let mut names = HashSet::new();
641for tag in tags {
642let trimmed = tag.trim_start();
643let name = trimmed
644 .strip_prefix('@')
645 .and_then(|rest| rest.split_whitespace().next());
646if let Some(name) = name {
647 names.insert(name);
648 }
649 }
650names651}
652653/// 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> {
658for tag in tags {
659let trimmed = tag.trim_start();
660if let Some(rest) = trimmed.strip_prefix('@') {
661let mut parts = rest.splitn(2, |c: char| c.is_whitespace());
662if let Some(name) = parts.next()
663 && name == tag_name
664 {
665// Get the value (everything after the tag name)
666return parts.next().map(|s| s.trim());
667 }
668 }
669 }
670None671}
672673/// 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 {
680let lower = s.to_lowercase();
681let mut result = String::new();
682for word in lower.split_whitespace() {
683if !result.is_empty() {
684 result.push(' ');
685 }
686 result.push_str(word);
687 }
688result.truncate(
689result690 .trim_end_matches(|c: char| c.is_ascii_punctuation())
691 .len(),
692 );
693result694}
695696/// 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> {
701let mut lines = Vec::new();
702703for attr in attrs {
704if !attr.path().is_ident("doc") {
705continue;
706 }
707let syn::Meta::NameValue(nv) = &attr.meta else {
708continue;
709 };
710let syn::Expr::Lit(expr_lit) = &nv.value else {
711continue;
712 };
713let syn::Lit::Str(lit) = &expr_lit.lit else {
714continue;
715 };
716717let content = lit.value();
718let trimmed = content.trim();
719720// If we hit a @tag before any content, there's no implicit title
721if trimmed.starts_with('@') {
722if lines.is_empty() {
723return None;
724 }
725break;
726 }
727728// Empty line ends first sentence for title extraction
729if trimmed.is_empty() {
730break;
731 }
732733// Check if this line contains a sentence-ending period
734if let Some(pos) = trimmed.find(". ") {
735 lines.push(trimmed[..pos].to_string());
736break;
737 } else if trimmed.ends_with('.') {
738 lines.push(trimmed.trim_end_matches('.').to_string());
739break;
740 } else {
741 lines.push(trimmed.to_string());
742 }
743 }
744745if lines.is_empty() {
746None747 } else {
748Some(lines.join(" "))
749 }
750}
751752/// 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> {
762let mut lines = Vec::new();
763let mut found_first_paragraph = false;
764let mut in_gap = false;
765766for attr in attrs {
767if !attr.path().is_ident("doc") {
768continue;
769 }
770let syn::Meta::NameValue(nv) = &attr.meta else {
771continue;
772 };
773let syn::Expr::Lit(expr_lit) = &nv.value else {
774continue;
775 };
776let syn::Lit::Str(lit) = &expr_lit.lit else {
777continue;
778 };
779780let content = lit.value();
781let trimmed = content.trim();
782783// If we hit a @tag, stop
784if trimmed.starts_with('@') {
785break;
786 }
787788if !found_first_paragraph {
789// Still in the first paragraph (title)
790if trimmed.is_empty() {
791// Blank line — first paragraph ended, now in the gap
792found_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
798if !trimmed.is_empty() {
799// Start of second paragraph
800in_gap = false;
801 lines.push(trimmed.to_string());
802 }
803 } else {
804// In second paragraph
805if trimmed.is_empty() {
806// End of second paragraph
807break;
808 }
809 lines.push(trimmed.to_string());
810 }
811 }
812813if lines.is_empty() {
814None815 } else {
816Some(lines.join(" "))
817 }
818}
819820/// 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]
836Strip,
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`]).
841Keep,
842}
843844impl ProseLinks {
845/// Parse the manifest spelling (`"strip"` / `"keep"`).
846pub(crate) fn parse_name(name: &str) -> Option<Self> {
847match name {
848"strip" => Some(Self::Strip),
849"keep" => Some(Self::Keep),
850_ => None,
851 }
852 }
853}
854855/// 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> {
871let lines = doc_lines(attrs);
872let prose: Vec<&str> = lines873 .iter()
874 .zip(classify(&lines))
875 .take_while(|(_, role)| *role == LineRole::Prose)
876 .map(|(line, _)| line.text.as_str())
877 .collect();
878let first = prose.iter().position(|line| !line.is_empty())?;
879let last = prose.iter().rposition(|line| !line.is_empty())?;
880let prose = &prose[first..=last];
881Some(match links {
882 ProseLinks::Strip => sanitize_prose_links(prose, Neutralize::AllLinks),
883 ProseLinks::Keep => sanitize_prose_links(prose, Neutralize::RustdocOnly),
884 })
885}
886887/// 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 {
892if roxygen_tag_name(&tag).is_some_and(|name| CODE_TAGS.contains(&name)) {
893return tag;
894 }
895sanitize_prose_links(&tag.lines().collect::<Vec<_>>(), links)
896}
897898/// 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`]).
903AllLinks,
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.
908RustdocOnly,
909}
910911/// [`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 {
920fn flush(paragraph: &mut Vec<&str>, out: &mut Vec<String>, links: Neutralize) {
921if !paragraph.is_empty() {
922out.push(sanitize_roxygen_links(¶graph.join("\n"), links));
923paragraph.clear();
924 }
925 }
926927let mut out: Vec<String> = Vec::new();
928let mut paragraph: Vec<&str> = Vec::new();
929let mut open_fence: Option<&str> = None;
930for &line in lines {
931if let Some(open) = open_fence {
932if 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 }
947flush(&mut paragraph, &mut out, links);
948out.join("\n")
949}
950951/// 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> {
954let body = line.trim_start_matches(' ');
955if line.len() - body.len() > 3 {
956return None;
957 }
958let fence_char = body.chars().next().filter(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
'`' | '~' => true,
_ => false,
}matches!(c, '`' | '~'))?;
959let run = body.len() - body.trim_start_matches(fence_char).len();
960 (run >= 3).then(|| &body[..run])
961}
962963/// 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 {
966close.starts_with(&open[..1])
967 && close.len() >= open.len()
968 && line.trim_start_matches(' ')[close.len()..]
969 .trim()
970 .is_empty()
971}
972973/// 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 {
991let bytes = s.as_bytes();
992let mut out = String::with_capacity(s.len());
993let mut i = 0;
994let mut in_code = false;
995while i < s.len() {
996if 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]`.
1000in_code = !in_code;
1001 out.push('`');
1002 i += 1;
1003continue;
1004 }
1005if !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.
1009if i > 0 && bytes[i - 1] == b'\\' {
1010 out.push('[');
1011 i += 1;
1012continue;
1013 }
1014// `[` is ASCII, so `i + 1` is a char boundary.
1015if let Some(close_rel) = s[i + 1..].find(']') {
1016let close = i + 1 + close_rel;
1017let 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.
1023if bytes.get(close + 1) == Some(&b'(') {
1024if 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 }
1033continue;
1034 }
1035// `[text][target]` — reference link; `[text]` — shortcut link,
1036 // its own target.
1037let (target, end) = match bytes.get(close + 1) {
1038Some(b'[') => match s[close + 2..].find(']') {
1039Some(t_rel) => (&s[close + 2..close + 2 + t_rel], close + 2 + t_rel + 1),
1040None => (inner, close + 1),
1041 },
1042_ => (inner, close + 1),
1043 };
1044// Keep `text`, drop the brackets and any `[target]`.
1045if 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;
1051continue;
1052 }
1053 }
1054let ch = s[i..].chars().next().unwrap();
1055 out.push(ch);
1056 i += ch.len_utf8();
1057 }
1058out1059}
10601061/// 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.
1077let mut depth = 1usize;
1078let close = start1079 + s[start..].find(|c: char| {
1080match c {
1081'(' => depth += 1,
1082')' => depth -= 1,
1083_ => {}
1084 }
1085 depth == 0 || c.is_whitespace()
1086 })?;
1087if s.as_bytes()[close] != b')' {
1088return None;
1089 }
1090let dest = &s[start..close];
1091let path = strip_rustdoc_disambiguator(dest);
1092 (is_rust_path(path) && path.contains("::")).then_some(close + 1)
1093}
10941095/// `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 {
1099const 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 ];
1125match dest.split_once('@') {
1126Some((kind, rest)) if KINDS.contains(&kind) => rest,
1127_ => dest,
1128 }
1129}
11301131/// 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 {
1137let path = dest1138 .strip_suffix("()")
1139 .or_else(|| dest.strip_suffix('!'))
1140 .unwrap_or(dest);
1141path.split("::").all(|segment| {
1142let mut chars = segment.chars();
1143chars1144 .next()
1145 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
1146 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1147 })
1148}
11491150/// 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 {
1163let target = target.trim();
1164let target = target1165 .strip_prefix('`')
1166 .and_then(|t| t.strip_suffix('`'))
1167 .unwrap_or(target);
1168let Some((pkg, _)) = target.rsplit_once("::") else {
1169return 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}
11731174/// 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 {
1186use quote::quote;
11871188// 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).
1191let tags = explicit_roxygen_tags_from_attrs(attrs);
1192let mut warnings = proc_macro2::TokenStream::new();
11931194// Check @title conflict
1195if 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 {
1199let 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 );
1205warnings.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! {
1206const _: () = {
1207#[deprecated(note = #msg)]
1208 #[doc(hidden)]
1209 #[allow(dead_code)]
1210const MINIEXTENDR_DOC_LINT_TITLE: () = ();
1211let _ = MINIEXTENDR_DOC_LINT_TITLE;
1212 };
1213 });
1214 }
12151216// Check @description conflict
1217if 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 {
1221let 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 );
1227warnings.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! {
1228const _: () = {
1229#[deprecated(note = #msg)]
1230 #[doc(hidden)]
1231 #[allow(dead_code)]
1232const MINIEXTENDR_DOC_LINT_DESC: () = ();
1233let _ = MINIEXTENDR_DOC_LINT_DESC;
1234 };
1235 });
1236 }
12371238warnings1239}
12401241/// 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}
12491250/// 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"];
12611262/// 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"];
12691270/// 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> {
1274let rest = tag.trim_start().strip_prefix('@')?;
1275let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
1276Some(&rest[..end])
1277}
12781279/// 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}
12911292/// 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) {
1317strip_tags_in(tags, type_name, span, METHOD_ONLY_TAGS)
1318}
13191320/// 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) {
1329use quote::quote_spanned;
13301331let mut filtered = Vec::new();
1332let mut warnings = proc_macro2::TokenStream::new();
13331334for tag in tags {
1335let Some(name) = roxygen_tag_name(tag) else {
1336 filtered.push(tag.clone());
1337continue;
1338 };
1339if !method_only.contains(&name) {
1340// Keeps unrecognised tags (and, for R6, @param) without warning.
1341filtered.push(tag.clone());
1342continue;
1343 }
1344let 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 =>
1351const _: () = {
1352#[deprecated(note = #msg)]
1353 #[doc(hidden)]
1354 #[allow(dead_code)]
1355const _MINIEXTENDR_IMPL_METHOD_TAG_WARN: () = ();
1356#[doc(hidden)]
1357 #[allow(dead_code)]
1358const _MINIEXTENDR_IMPL_METHOD_TAG_USE: () = _MINIEXTENDR_IMPL_METHOD_TAG_WARN;
1359 };
1360 });
1361 }
13621363 (filtered, warnings)
1364}
13651366/// 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> {
1379let mut names = HashSet::new();
1380for tag in tags {
1381let Some(names_token) = param_names_token(tag) else {
1382continue;
1383 };
1384for name in names_token.split(',') {
1385let name = name.trim();
1386if !name.is_empty() {
1387 names.insert(name.to_string());
1388 }
1389 }
1390 }
1391names1392}
13931394/// 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 {
1408tags.iter().any(|tag| tag_documents_param(tag, name))
1409}
14101411/// 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> {
1415tags.iter().find(|tag| tag_documents_param(tag, name))
1416}
14171418/// Shared predicate: does this single `@param` tag document `name`?
1419fn tag_documents_param(tag: &str, name: &str) -> bool {
1420let Some(names_token) = param_names_token(tag) else {
1421return false;
1422 };
1423names_token.split(',').any(|n| n.trim() == name)
1424}
14251426/// 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> {
1437let mut renamed = Vec::new();
1438for tag in tags.iter_mut() {
1439// The name token's place in the tag, as `param_names_token` finds it.
1440let lead = tag.len() - tag.trim_start().len();
1441let Some(rest) = tag[lead..].strip_prefix("@param ") else {
1442continue;
1443 };
1444let start = tag.len() - rest.trim_start().len();
1445let end = tag[start..]
1446 .find(char::is_whitespace)
1447 .map_or(tag.len(), |n| start + n);
1448let mut changed = false;
1449let names: Vec<String> = tag[start..end]
1450 .split(',')
1451 .map(|name| match rename(name) {
1452Some(new) => {
1453 changed = true;
1454 renamed.push((name.to_string(), new.clone()));
1455 new
1456 }
1457None => name.to_string(),
1458 })
1459 .collect();
1460if changed {
1461 tag.replace_range(start..end, &names.join(","));
1462 }
1463 }
1464for (old, new) in renamed {
1465let 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();
1471if documented > 1 {
1472return 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 }
1478Ok(())
1479}
14801481/// 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> {
1484let trimmed = tag.trim_start();
1485let rest = trimmed.strip_prefix("@param ")?;
1486rest.split_whitespace().next()
1487}
14881489// region: shared pages (#1590)
14901491/// 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> {
1494tags.iter().find_map(|t| {
1495let rest = t.trim_start().strip_prefix("@describeIn")?;
1496if rest.starts_with(char::is_whitespace) {
1497rest.split_whitespace().next()
1498 } else {
1499None1500 }
1501 })
1502}
15031504/// 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 {
1517describe_in_topic(tags).is_some()
1518 || rdname_value(tags).is_some_and(|topic| Some(topic) != default_page)
1519}
15201521/// 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 {
1527describe_in_topic(tags)
1528 .or_else(|| rdname_value(tags))
1529 .unwrap_or(default_page)
1530}
15311532/// 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 {
1538tags.iter().any(|tag| match roxygen_tag_name(tag) {
1539Some("inheritParams") => true,
1540Some("inherit") => {
1541let mut fields = tag.split_whitespace().skip(2).peekable(); // `@inherit`, source
1542fields.peek().is_none() || fields.any(|field| field == "params")
1543 }
1544_ => false,
1545 })
1546}
15471548/// 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 {
1564joins_author_topic(tags, default_page) || inherits_params(tags)
1565}
15661567/// 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";
15831584/// 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 {
1589joins_author_topic(tags, Some(default_page))
1590 && !has_roxygen_tag(tags, "order")
1591 && !has_roxygen_tag(tags, "noRd")
1592}
15931594/// 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) {
1601if orders_after_topic_blocks(tags, default_page) {
1602lines.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#\' {0}",
ORDER_AFTER_TOPIC_BLOCKS))
})format!("#' {ORDER_AFTER_TOPIC_BLOCKS}"));
1603 }
1604}
16051606/// 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__ ";
16181619/// 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)> {
1657let mut match_arg_doc_placeholders = Vec::new();
1658let missing_default_docs = parsed.missing_default_param_docs();
1659let call_line = call_param_doc1660 .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}"));
1662if describe_in_topic(tags).is_some() || inherits_params(tags) {
1663tags.extend(call_line);
1664return match_arg_doc_placeholders;
1665 }
1666let formals = parsed.formals();
1667for arg in inputs {
1668let syn::FnArg::Typed(pt) = arg else {
1669continue;
1670 };
1671let syn::Pat::Ident(pat_ident) = pt.pat.as_ref() else {
1672continue;
1673 };
1674// `NArgs` is no R formal (#1860), so it gets no `@param`.
1675if parsed.is_dots_param(&pat_ident.ident) || crate::type_inspect::is_nargs_marker(&pt.ty) {
1676continue;
1677 }
1678let 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`.
1681let r_name = formals.of(&rust_name);
1682if param_documented(tags, &r_name) {
1683continue;
1684 }
16851686if 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) {
1692let 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 }
1708tags.extend(call_line);
1709match_arg_doc_placeholders1710}
17111712// endregion
17131714/// 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> {
1723let bytes = formals.as_bytes();
1724let mut out = Vec::new();
1725let mut depth: i32 = 0;
1726let mut quote: Option<u8> = None;
1727let mut start = 0usize;
1728let mut i = 0usize;
1729while i < bytes.len() {
1730let b = bytes[i];
1731match quote {
1732Some(q) => {
1733if b == b'\\' {
1734 i += 1; // skip the escaped char
1735} else if b == q {
1736 quote = None;
1737 }
1738 }
1739None => match b {
1740b'"' | b'\'' => quote = Some(b),
1741b'(' | b'[' | b'{' => depth += 1,
1742b')' | b']' | b'}' => depth -= 1,
1743b',' if depth == 0 => {
1744 out.push(formals[start..i].trim());
1745 start = i + 1;
1746 }
1747_ => {}
1748 },
1749 }
1750 i += 1;
1751 }
1752out.push(formals[start..].trim());
1753out.into_iter().filter(|s| !s.is_empty()).collect()
1754}
17551756/// 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 {
1759formal.split('=').next().unwrap_or(formal).trim()
1760}
17611762/// 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) {
1779strip_tags_in(tags, type_name, span, METHOD_ONLY_TAGS_R6)
1780}
17811782/// 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> {
1804let lines = doc_lines(attrs);
1805let roles = classify(&lines);
18061807// Each attribute's lines are contiguous; its first non-blank line decides
1808 // (its first line when all are blank).
1809let mut roxygen_attrs = HashSet::new();
1810let mut offset = 0;
1811for group in lines.chunk_by(|a, b| a.attr == b.attr) {
1812let deciding = group.iter().position(|l| !l.text.is_empty()).unwrap_or(0);
1813if #[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 }
18211822attrs1823 .iter()
1824 .enumerate()
1825 .filter(|(i, _)| !roxygen_attrs.contains(i))
1826 .map(|(_, attr)| attr.clone())
1827 .collect()
1828}
18291830#[cfg(test)]
1831mod tests;