1//! Small cross-cutting helpers used by multiple macro modules.
23/// Extract `#[cfg(...)]` attributes from a list of attributes.
4///
5/// These should be propagated to generated items so they are conditionally
6/// compiled along with the original function.
7pub(crate) fn extract_cfg_attrs(attrs: &[syn::Attribute]) -> Vec<syn::Attribute> {
8attrs9 .iter()
10 .filter(|attr| attr.path().is_ident("cfg"))
11 .cloned()
12 .collect()
13}
1415/// Rewrites a leading `Self` in `path` to `type_ident`: a path an attribute
16/// names (`#[r_data(get = "Self::f")]`, `fallback = "Self::f"`) is called
17/// from a free function the macro emits outside any impl, where `Self` means
18/// nothing.
19pub(crate) fn resolve_self(path: &mut syn::Path, type_ident: &syn::Ident) {
20if let Some(first) = path.segments.first_mut()
21 && first.ident == "Self"
22{
23first.ident = syn::Ident::new(&type_ident.to_string(), first.ident.span());
24 }
25}
2627/// Format a human-readable source location note from a syntax span.
28///
29/// Column is reported as 1-based for consistency with editor displays.
30pub(crate) fn source_location_doc(span: proc_macro2::Span) -> String {
31let start = span.start();
32::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Generated from source location line {0}, column {1}.",
start.line, start.column + 1))
})format!(
33"Generated from source location line {}, column {}.",
34 start.line,
35 start.column + 1
36)37}
3839/// The `(file:line:col)` a wrapper comment gives for a syntax span, e.g.
40/// `(lib.rs:114:12)`.
41///
42/// The file is the one `file!()` names, as in the `# Generated from Rust …`
43/// headers, and the column is 1-based. The wrapper writer compares wrappers
44/// with every `(<file>.rs:LINE:COL)` position normalized, so a comment in this
45/// form doesn't rewrite the wrappers file when only lines above it moved.
46pub(crate) fn source_position(span: proc_macro2::Span) -> String {
47let start = span.start();
48::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}:{1}:{2})", span.file(),
start.line, start.column + 1))
})format!("({}:{}:{})", span.file(), start.line, start.column + 1)49}
5051/// Build a `TokenStream` containing a raw string literal from an R wrapper string.
52///
53/// Every generated wrapper is finalized here, so this is also where calls a
54/// formal would shadow are qualified: `formals` holds every R formal of the
55/// wrappers in `s`, and each call to a base function that shares a name with
56/// one of them is written `base::name(...)`
57/// ([`qualify_shadowed_calls`](crate::r_shadowing::qualify_shadowed_calls)).
58///
59/// The delimiter has one more `#` than the longest run of `#` after a `"` in
60/// the wrapper, so a doc comment quoting `"# a footer"` or a default of `"#"`
61/// can't end the literal early (#2111).
62pub(crate) fn r_wrapper_raw_literal(
63 s: &str,
64 formals: &std::collections::BTreeSet<String>,
65) -> proc_macro2::TokenStream {
66use std::str::FromStr;
67let s = crate::r_shadowing::qualify_shadowed_calls(s, formals);
68let hashes = "#".repeat(raw_string_hashes(&s));
69let raw = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("r{0}\"\n{1}\n\"{0}", hashes, s))
})format!("r{hashes}\"\n{s}\n\"{hashes}");
70 proc_macro2::TokenStream::from_str(&raw).expect("valid raw string literal")
71}
7273/// How many `#` a raw string literal holding `s` needs: one more than the
74/// longest run of `#` that follows a `"` in `s`.
75fn raw_string_hashes(s: &str) -> usize {
76let longest = s77 .match_indices('"')
78 .map(|(i, _)| s[i + 1..].bytes().take_while(|&b| b == b'#').count())
79 .max()
80 .unwrap_or(0);
81longest + 1
82}
8384#[cfg(test)]
85mod tests;