Skip to main content

miniextendr_macros/
crate_config.rs

1//! Crate-level `#[miniextendr]` defaults read from the user crate's manifest.
2//!
3//! Proc-macro invocations share no state, so a default meant for every
4//! `#[miniextendr]` item in a crate cannot be declared on one macro call:
5//! `miniextendr_init!` expands with no knowledge of the functions and vice
6//! versa. The one place every expansion can see is the manifest. Cargo sets
7//! `CARGO_MANIFEST_DIR` for the crate being compiled and the proc macro runs
8//! inside that `rustc` process, so it can read `Cargo.toml` at expansion time.
9//! Cargo refingerprints a package when its manifest changes, so an edit takes
10//! effect on the next build with no stale expansions.
11//!
12//! Supported spelling (the table header; dotted keys under `[package]` or
13//! `[package.metadata]` are accepted too, inline tables are rejected):
14//!
15//! ```toml
16//! [package.metadata.miniextendr]
17//! noexport_postfix = "_impl"
18//! source_tags = true
19//! call_attribution = "caller"
20//! conversion_error_class = ["pkg_error_argument", "pkg_error"]
21//! preconditions = false
22//! roxygen_prose_links = "keep"
23//! ```
24//!
25//! The reader is a deliberately small line-based scanner rather than a TOML
26//! dependency: the macro crate ships in every downstream build, and the only
27//! values it needs are strings, booleans and a single-line string array
28//! under one well-known table.
29
30use std::cell::RefCell;
31use std::collections::HashMap;
32use std::path::{Path, PathBuf};
33
34use crate::r_wrapper_builder::CallAttribution;
35use crate::roxygen::ProseLinks;
36
37/// Dotted path of the `noexport_postfix` key.
38const NOEXPORT_POSTFIX_KEY: &str = "package.metadata.miniextendr.noexport_postfix";
39/// Dotted path of the `source_tags` key.
40const SOURCE_TAGS_KEY: &str = "package.metadata.miniextendr.source_tags";
41/// Dotted path of the `call_attribution` key.
42const CALL_ATTRIBUTION_KEY: &str = "package.metadata.miniextendr.call_attribution";
43/// Dotted path of the `conversion_error_class` key.
44const CONVERSION_ERROR_CLASS_KEY: &str = "package.metadata.miniextendr.conversion_error_class";
45/// Dotted path of the `preconditions` key.
46const PRECONDITIONS_KEY: &str = "package.metadata.miniextendr.preconditions";
47/// Dotted path of the `roxygen_prose_links` key.
48const ROXYGEN_PROSE_LINKS_KEY: &str = "package.metadata.miniextendr.roxygen_prose_links";
49/// The classes the R raise helper appends to every Rust error. A crate-level
50/// class naming one of them would duplicate a layer of the vector.
51const FRAMEWORK_ERROR_CLASSES: [&str; 4] = ["rust_error", "simpleError", "error", "condition"];
52/// Dotted path of the table itself, used to reject the inline-table spelling.
53const TABLE_KEY: &str = "package.metadata.miniextendr";
54
55/// Crate-wide defaults declared under `[package.metadata.miniextendr]`.
56#[derive(#[automatically_derived]impl ::core::fmt::Debug for CrateConfig {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            "CrateConfig noexport_postfix source_tags call_attribution conversion_error_class preconditions roxygen_prose_links";
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.noexport_postfix, &self.source_tags,
                        &self.call_attribution, &self.conversion_error_class,
                        &self.preconditions, &&self.roxygen_prose_links];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for CrateConfig {
    #[inline]
    fn clone(&self) -> Self {
        CrateConfig {
            noexport_postfix: ::core::clone::Clone::clone(&self.noexport_postfix),
            source_tags: ::core::clone::Clone::clone(&self.source_tags),
            call_attribution: ::core::clone::Clone::clone(&self.call_attribution),
            conversion_error_class: ::core::clone::Clone::clone(&self.conversion_error_class),
            preconditions: ::core::clone::Clone::clone(&self.preconditions),
            roxygen_prose_links: ::core::clone::Clone::clone(&self.roxygen_prose_links),
        }
    }
}Clone, #[automatically_derived]impl ::core::default::Default for CrateConfig {
    #[inline]
    fn default() -> Self {
        CrateConfig {
            noexport_postfix: ::core::default::Default::default(),
            source_tags: ::core::default::Default::default(),
            call_attribution: ::core::default::Default::default(),
            conversion_error_class: ::core::default::Default::default(),
            preconditions: ::core::default::Default::default(),
            roxygen_prose_links: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    CrateConfig {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CrateConfig {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.source_tags == other.source_tags &&
                            self.noexport_postfix == other.noexport_postfix &&
                        self.call_attribution == other.call_attribution &&
                    self.conversion_error_class == other.conversion_error_class
                && self.preconditions == other.preconditions &&
            self.roxygen_prose_links == other.roxygen_prose_links
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for CrateConfig {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<String>>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<Option<CallAttribution>>;
        let _: ::core::cmp::AssertParamIsEq<Vec<String>>;
        let _: ::core::cmp::AssertParamIsEq<Option<bool>>;
        let _: ::core::cmp::AssertParamIsEq<Option<ProseLinks>>;
    }
}Eq)]
57pub(crate) struct CrateConfig {
58    /// `noexport_postfix = "..."`: appended to the Rust name of every
59    /// `noexport` / `internal` free function that sets neither `r_name` nor
60    /// its own `postfix`. Exported functions keep their Rust names.
61    pub(crate) noexport_postfix: Option<String>,
62    /// `source_tags = true`: every generated roxygen block carries a
63    /// `@source Generated by miniextendr from …` provenance tag. Off by
64    /// default (#1552): the tag collects one paragraph per function on a
65    /// shared Rd page, and the `# Generated from Rust fn … (file:line:col)`
66    /// comment above each wrapper remains the navigation pointer.
67    pub(crate) source_tags: bool,
68    /// `call_attribution = "wrapper" | "caller" | "none"`: the condition-call
69    /// attribution of every free function that neither takes a `Call` /
70    /// `CallerCall` parameter nor sets `call = ...` (#1566). `caller` applies
71    /// to `noexport` / `internal` functions; exported ones keep `wrapper`.
72    /// `none` (#1851) applies to every free function: its conditions carry
73    /// no call. Unset means the framework default, `wrapper`.
74    pub(crate) call_attribution: Option<CallAttribution>,
75    /// `conversion_error_class = "..." | ["...", ...]`: classes added to every
76    /// argument-conversion condition of the crate, after the error type's own
77    /// `RConditionData` classes (duplicates skipped) and before the
78    /// `rust_error` layering. Empty when unset.
79    pub(crate) conversion_error_class: Vec<String>,
80    /// `preconditions = true | false`: whether the generated R wrappers of
81    /// the crate keep their type-derived argument checks (#1566). Below every
82    /// item-level and per-parameter spelling, above the
83    /// `no-preconditions-default` feature (see
84    /// `crate::r_preconditions::resolve_type_checks`). Unset means the feature
85    /// decides, and without it the checks are kept.
86    pub(crate) preconditions: Option<bool>,
87    /// `roxygen_prose_links = "strip" | "keep"`: whether the leading prose of
88    /// a doc comment keeps its `[...]` links on its way to `@description`
89    /// (see [`ProseLinks`]). Unset means the framework default, `strip`.
90    pub(crate) roxygen_prose_links: Option<ProseLinks>,
91}
92
93/// A malformed `[package.metadata.miniextendr]` entry, reported as a compile
94/// error on the `#[miniextendr]` item that tried to use it.
95#[derive(#[automatically_derived]impl ::core::fmt::Debug for CrateConfigError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "CrateConfigError manifest message", &self.manifest,
            &&self.message)
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for CrateConfigError {
    #[inline]
    fn clone(&self) -> Self {
        CrateConfigError {
            manifest: ::core::clone::Clone::clone(&self.manifest),
            message: ::core::clone::Clone::clone(&self.message),
        }
    }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    CrateConfigError {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CrateConfigError {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.manifest == other.manifest && self.message == other.message
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for CrateConfigError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<PathBuf>;
        let _: ::core::cmp::AssertParamIsEq<String>;
    }
}Eq)]
96pub(crate) struct CrateConfigError {
97    manifest: PathBuf,
98    message: String,
99}
100
101impl std::fmt::Display for CrateConfigError {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.write_fmt(format_args!("{0}: [package.metadata.miniextendr] {1}",
        self.manifest.display(), self.message))write!(
104            f,
105            "{}: [package.metadata.miniextendr] {}",
106            self.manifest.display(),
107            self.message
108        )
109    }
110}
111
112/// The crate config for the crate currently being compiled.
113///
114/// Returns the defaults when `CARGO_MANIFEST_DIR` is unset or its `Cargo.toml`
115/// cannot be read; only a present-but-malformed entry is an error. Results are
116/// cached per thread and manifest directory, so a single proc-macro server
117/// process serving several crates (rust-analyzer) never leaks one crate's
118/// default into another.
119pub(crate) fn crate_config() -> Result<CrateConfig, CrateConfigError> {
120    let Some(dir) = std::env::var_os("CARGO_MANIFEST_DIR") else {
121        return Ok(CrateConfig::default());
122    };
123    crate_config_for_dir(Path::new(&dir))
124}
125
126/// Whether generated roxygen blocks carry `@source` provenance tags.
127///
128/// Read by the impl-block and derive generators, which have no single item to
129/// hang a manifest error on; a malformed table reads as the default here and
130/// is reported as a compile error by the first `#[miniextendr]` function,
131/// which goes through [`crate_config`].
132pub(crate) fn source_tags_enabled() -> bool {
133    crate_config().map(|c| c.source_tags).unwrap_or(false)
134}
135
136/// The crate-level classes of argument-conversion conditions
137/// (`conversion_error_class`), empty when unset.
138///
139/// Read by the argument-conversion codegen, which runs for free functions,
140/// impl methods, trait methods and sidecar setters alike; a malformed table
141/// reads as the default here and is reported as a compile error by the first
142/// `#[miniextendr]` function, which goes through [`crate_config`].
143pub(crate) fn conversion_error_class() -> Vec<String> {
144    crate_config()
145        .map(|c| c.conversion_error_class)
146        .unwrap_or_default()
147}
148
149/// The crate default of the type-derived R-side checks (`preconditions`),
150/// `None` when unset.
151///
152/// Read by the impl-block and trait-impl generators, which have no single
153/// item to hang a manifest error on; a malformed table reads as unset here and
154/// is reported as a compile error by the first `#[miniextendr]` function,
155/// which goes through [`crate_config`].
156pub(crate) fn preconditions_default() -> Option<bool> {
157    crate_config().ok().and_then(|c| c.preconditions)
158}
159
160/// What leading doc-comment prose does with its `[...]` links
161/// (`roxygen_prose_links`), [`ProseLinks::Strip`] when unset.
162///
163/// Read by the roxygen extraction every generator shares, which has no single
164/// item to hang a manifest error on; a malformed table reads as the default
165/// here and is reported as a compile error by the first `#[miniextendr]`
166/// function, which goes through [`crate_config`].
167pub(crate) fn roxygen_prose_links() -> ProseLinks {
168    crate_config()
169        .ok()
170        .and_then(|c| c.roxygen_prose_links)
171        .unwrap_or_default()
172}
173
174/// [`crate_config`] for an explicit manifest directory (the cached entry point).
175pub(crate) fn crate_config_for_dir(dir: &Path) -> Result<CrateConfig, CrateConfigError> {
176    const CACHE:
    ::std::thread::LocalKey<RefCell<HashMap<PathBuf,
    Result<CrateConfig, CrateConfigError>>>> =
    {
        #[allow(mismatched_lifetime_syntaxes)]
        #[inline]
        fn __rust_std_internal_init_fn(_lifetime_elision:
                ::std::marker::PhantomData<&'static ()>)
            ->
                RefCell<HashMap<PathBuf,
                Result<CrateConfig, CrateConfigError>>> {
            RefCell::new(HashMap::new())
        }
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<RefCell<HashMap<PathBuf,
                                    Result<CrateConfig, CrateConfigError>>>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<HashMap<PathBuf,
                                        Result<CrateConfig, CrateConfigError>>>, ()> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        || __rust_std_internal_init_fn(::std::marker::PhantomData))
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<HashMap<PathBuf,
                                        Result<CrateConfig, CrateConfigError>>>, !> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        || __rust_std_internal_init_fn(::std::marker::PhantomData))
                                }
                        }
                    })
        }
    };thread_local! {
177        static CACHE: RefCell<HashMap<PathBuf, Result<CrateConfig, CrateConfigError>>> =
178            RefCell::new(HashMap::new());
179    }
180    CACHE.with_borrow_mut(|cache| {
181        cache
182            .entry(dir.to_path_buf())
183            .or_insert_with(|| read_crate_config(&dir.join("Cargo.toml")))
184            .clone()
185    })
186}
187
188/// Read and parse one manifest. Missing or unreadable files yield the defaults.
189fn read_crate_config(manifest: &Path) -> Result<CrateConfig, CrateConfigError> {
190    match std::fs::read_to_string(manifest) {
191        Ok(text) => parse_crate_config(&text).map_err(|message| CrateConfigError {
192            manifest: manifest.to_path_buf(),
193            message,
194        }),
195        Err(_) => Ok(CrateConfig::default()),
196    }
197}
198
199/// Parse the `[package.metadata.miniextendr]` table out of manifest text.
200///
201/// Tracks the current table header and resolves every `key = value` line to a
202/// dotted path, so the header form, `miniextendr.noexport_postfix = "..."`
203/// under `[package.metadata]`, and `metadata.miniextendr.noexport_postfix`
204/// under `[package]` all resolve to the same key. Everything else in the
205/// manifest is skipped without interpretation.
206pub(crate) fn parse_crate_config(text: &str) -> Result<CrateConfig, String> {
207    let mut config = CrateConfig::default();
208    let mut source_tags_seen = false;
209    let mut conversion_error_class_seen = false;
210    let mut table = String::new();
211
212    for raw_line in text.lines() {
213        let line = raw_line.trim();
214        if line.is_empty() || line.starts_with('#') {
215            continue;
216        }
217        if let Some(header) = line.strip_prefix('[') {
218            // `[[array.of.tables]]` and `[table]`: keys below belong to it.
219            let header = header.strip_prefix('[').unwrap_or(header);
220            let end = header
221                .find(']')
222                .ok_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unterminated table header `{0}`",
                line))
    })format!("unterminated table header `{line}`"))?;
223            table = normalize_key(&header[..end]);
224            continue;
225        }
226        let Some((key, value)) = line.split_once('=') else {
227            continue;
228        };
229        let key = normalize_key(key);
230        let full = if table.is_empty() {
231            key
232        } else {
233            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}", table, key))
    })format!("{table}.{key}")
234        };
235        if full == TABLE_KEY && value.trim_start().starts_with('{') {
236            return Err(
237                "inline tables are not supported here; write a `[package.metadata.miniextendr]` \
238                 table with each key on its own line"
239                    .to_string(),
240            );
241        }
242        if full == CALL_ATTRIBUTION_KEY {
243            if config.call_attribution.is_some() {
244                return Err("`call_attribution` is set more than once".to_string());
245            }
246            let value = value.trim();
247            let attribution = parse_string_value(value)
248                .as_deref()
249                .and_then(CallAttribution::parse_name)
250                .ok_or_else(|| {
251                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`call_attribution` must be one of \"wrapper\", \"caller\", \"none\", found `{0}`",
                value))
    })format!(
252                        "`call_attribution` must be one of \"wrapper\", \"caller\", \"none\", found \
253                         `{value}`"
254                    )
255                })?;
256            config.call_attribution = Some(attribution);
257            continue;
258        }
259        if full == CONVERSION_ERROR_CLASS_KEY {
260            if conversion_error_class_seen {
261                return Err("`conversion_error_class` is set more than once".to_string());
262            }
263            let value = value.trim();
264            let classes = parse_string_value(value)
265                .map(|class| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [class]))vec![class])
266                .or_else(|| parse_string_array_value(value))
267                .ok_or_else(|| {
268                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`conversion_error_class` must be a string or a single-line array of strings, found `{0}`",
                value))
    })format!(
269                        "`conversion_error_class` must be a string or a single-line array of \
270                         strings, found `{value}`"
271                    )
272                })?;
273            validate_conversion_error_class(&classes)?;
274            config.conversion_error_class = classes;
275            conversion_error_class_seen = true;
276            continue;
277        }
278        if full == ROXYGEN_PROSE_LINKS_KEY {
279            if config.roxygen_prose_links.is_some() {
280                return Err("`roxygen_prose_links` is set more than once".to_string());
281            }
282            let value = value.trim();
283            let links = parse_string_value(value)
284                .as_deref()
285                .and_then(ProseLinks::parse_name)
286                .ok_or_else(|| {
287                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`roxygen_prose_links` must be one of \"strip\", \"keep\", found `{0}`",
                value))
    })format!(
288                        "`roxygen_prose_links` must be one of \"strip\", \"keep\", found \
289                         `{value}`"
290                    )
291                })?;
292            config.roxygen_prose_links = Some(links);
293            continue;
294        }
295        if full == PRECONDITIONS_KEY {
296            if config.preconditions.is_some() {
297                return Err("`preconditions` is set more than once".to_string());
298            }
299            config.preconditions = Some(parse_bool_value(value.trim()).ok_or_else(|| {
300                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`preconditions` must be `true` or `false`, found `{0}`",
                value.trim()))
    })format!(
301                    "`preconditions` must be `true` or `false`, found `{}`",
302                    value.trim()
303                )
304            })?);
305            continue;
306        }
307        if full == SOURCE_TAGS_KEY {
308            if source_tags_seen {
309                return Err("`source_tags` is set more than once".to_string());
310            }
311            config.source_tags = parse_bool_value(value.trim()).ok_or_else(|| {
312                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`source_tags` must be `true` or `false`, found `{0}`",
                value.trim()))
    })format!(
313                    "`source_tags` must be `true` or `false`, found `{}`",
314                    value.trim()
315                )
316            })?;
317            source_tags_seen = true;
318            continue;
319        }
320        if full != NOEXPORT_POSTFIX_KEY {
321            continue;
322        }
323        if config.noexport_postfix.is_some() {
324            return Err("`noexport_postfix` is set more than once".to_string());
325        }
326        let value = parse_string_value(value.trim()).ok_or_else(|| {
327            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`noexport_postfix` must be a string, found `{0}`",
                value.trim()))
    })format!(
328                "`noexport_postfix` must be a string, found `{}`",
329                value.trim()
330            )
331        })?;
332        validate_noexport_postfix(&value)?;
333        config.noexport_postfix = Some(value);
334    }
335
336    Ok(config)
337}
338
339/// Collapse a dotted key or table header to `a.b.c`: trims each segment and
340/// strips one layer of quotes so `[ "package" . metadata ]` compares equal to
341/// `[package.metadata]`.
342fn normalize_key(key: &str) -> String {
343    key.split('.')
344        .map(|segment| {
345            let segment = segment.trim();
346            segment
347                .strip_prefix('"')
348                .and_then(|s| s.strip_suffix('"'))
349                .or_else(|| {
350                    segment
351                        .strip_prefix('\'')
352                        .and_then(|s| s.strip_suffix('\''))
353                })
354                .unwrap_or(segment)
355        })
356        .collect::<Vec<_>>()
357        .join(".")
358}
359
360/// Parse a single-line TOML basic (`"..."`) or literal (`'...'`) string.
361///
362/// Escape sequences are not accepted: the value must be an R identifier
363/// fragment, which never needs one. Multi-line strings and non-string values
364/// return `None`.
365fn parse_string_value(value: &str) -> Option<String> {
366    let (quote, rest) = match value.chars().next()? {
367        c @ ('"' | '\'') => (c, &value[1..]),
368        _ => return None,
369    };
370    if rest.starts_with(quote) && rest[1..].starts_with(quote) {
371        // `"""` / `'''`: multi-line strings are not supported.
372        return None;
373    }
374    let end = rest.find(quote)?;
375    let body = &rest[..end];
376    if body.contains('\\') {
377        return None;
378    }
379    let trailing = rest[end + 1..].trim_start();
380    if !(trailing.is_empty() || trailing.starts_with('#')) {
381        return None;
382    }
383    Some(body.to_string())
384}
385
386/// Parse a single-line TOML array of strings (`["a", 'b']`, a trailing comma
387/// and a trailing `# comment` allowed), each element under the
388/// [`parse_string_value`] rules. Multi-line arrays and non-string elements
389/// return `None`.
390fn parse_string_array_value(value: &str) -> Option<Vec<String>> {
391    let mut rest = value.strip_prefix('[')?.trim_start();
392    let mut items = Vec::new();
393    loop {
394        if let Some(after) = rest.strip_prefix(']') {
395            let trailing = after.trim_start();
396            return (trailing.is_empty() || trailing.starts_with('#')).then_some(items);
397        }
398        let quote = rest.chars().next().filter(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
    '"' | '\'' => true,
    _ => false,
}matches!(c, '"' | '\''))?;
399        let body_and_rest = &rest[1..];
400        let end = body_and_rest.find(quote)?;
401        let body = &body_and_rest[..end];
402        if body.contains('\\') {
403            return None;
404        }
405        items.push(body.to_string());
406        rest = body_and_rest[end + 1..].trim_start();
407        if let Some(after) = rest.strip_prefix(',') {
408            rest = after.trim_start();
409        } else if !rest.starts_with(']') {
410            return None;
411        }
412    }
413}
414
415/// Parse a TOML boolean, allowing a trailing `# comment`.
416fn parse_bool_value(value: &str) -> Option<bool> {
417    let (literal, rest) = match value.split_once(char::is_whitespace) {
418        Some((literal, rest)) => (literal, rest.trim_start()),
419        None => (value, ""),
420    };
421    if !(rest.is_empty() || rest.starts_with('#')) {
422        return None;
423    }
424    match literal {
425        "true" => Some(true),
426        "false" => Some(false),
427        _ => None,
428    }
429}
430
431/// `conversion_error_class` must name at least one class, each non-empty,
432/// distinct, and not one of the framework's own layers (`rust_error`,
433/// `simpleError`, `error`, `condition`), which are always appended.
434fn validate_conversion_error_class(classes: &[String]) -> Result<(), String> {
435    if classes.is_empty() {
436        return Err("`conversion_error_class` must name at least one class".to_string());
437    }
438    for (i, class) in classes.iter().enumerate() {
439        if class.trim().is_empty() {
440            return Err("`conversion_error_class` entries must not be empty".to_string());
441        }
442        if FRAMEWORK_ERROR_CLASSES.contains(&class.as_str()) {
443            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`conversion_error_class` must not name `{0}`: every conversion error already carries `rust_error`, `simpleError`, `error` and `condition`",
                class))
    })format!(
444                "`conversion_error_class` must not name `{class}`: every conversion error already \
445                 carries `rust_error`, `simpleError`, `error` and `condition`"
446            ));
447        }
448        if classes[..i].contains(class) {
449            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`conversion_error_class` names `{0}` more than once",
                class))
    })format!(
450                "`conversion_error_class` names `{class}` more than once"
451            ));
452        }
453    }
454    Ok(())
455}
456
457/// Mirror of `miniextendr_fn::validate_postfix` for the manifest value.
458fn validate_noexport_postfix(value: &str) -> Result<(), String> {
459    if value.is_empty() {
460        return Err("`noexport_postfix` must not be empty".to_string());
461    }
462    if !value
463        .chars()
464        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
465    {
466        return Err(
467            "`noexport_postfix` must be a valid R identifier fragment (letters, digits, `_`, `.`)"
468                .to_string(),
469        );
470    }
471    Ok(())
472}
473
474#[cfg(test)]
475mod tests;