pub fn cfg_gated_free_functions(lib_rs_source: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = lib_rs_source.lines().collect();
let mut result = Vec::new();
let mut i = 0;
while i < lines.len() {
let line = lines[i];
if line.starts_with("#[cfg(")
&& let Some(end) = find_attribute_end(&lines, i)
{
if let Some(name) = lines.get(end + 1).and_then(|l| free_pub_fn_name(l)) {
result.push((name, lines[i..=end].join("\n")));
}
i = end + 1;
continue;
}
i += 1;
}
result
}
fn find_attribute_end(lines: &[&str], start: usize) -> Option<usize> {
let mut depth = paren_delta(lines[start]);
let mut end = start;
while depth > 0 {
end += 1;
let line = *lines.get(end)?;
depth += paren_delta(line);
}
(depth == 0 && lines[end].trim_end().ends_with(")]")).then_some(end)
}
fn paren_delta(line: &str) -> i32 {
line.matches('(').count() as i32 - line.matches(')').count() as i32
}
fn free_pub_fn_name(line: &str) -> Option<String> {
let rest = line
.strip_prefix("pub async fn ")
.or_else(|| line.strip_prefix("pub fn "))?;
let name_end = rest.find('(')?;
Some(rest[..name_end].to_string())
}
pub fn inject_frb_cfg_gates(frb_generated_source: &str, cfg_gated_fns: &[(String, String)]) -> String {
if cfg_gated_fns.is_empty() {
return frb_generated_source.to_string();
}
let lines: Vec<&str> = frb_generated_source.lines().collect();
let mut result = String::with_capacity(frb_generated_source.len());
for (idx, line) in lines.iter().enumerate() {
if let Some(gate) = gate_for_wire_line(line, cfg_gated_fns)
&& !already_gated(&lines, idx, gate)
{
let indent = leading_whitespace(line);
for gate_line in gate.lines() {
result.push_str(&indent);
result.push_str(gate_line);
result.push('\n');
}
}
result.push_str(line);
result.push('\n');
}
if !frb_generated_source.ends_with('\n') && result.ends_with('\n') {
result.pop();
}
result
}
pub fn carry_lib_rs_cfg_gates_into_frb_generated(lib_rs_source: &str, frb_generated_source: &str) -> String {
let gated = cfg_gated_free_functions(lib_rs_source);
inject_frb_cfg_gates(frb_generated_source, &gated)
}
fn leading_whitespace(line: &str) -> String {
line.chars().take_while(|c| c.is_whitespace()).collect()
}
fn gate_for_wire_line<'a>(line: &str, cfg_gated_fns: &'a [(String, String)]) -> Option<&'a str> {
let trimmed = line.trim_start();
cfg_gated_fns.iter().find_map(|(name, gate)| {
let def = format!("fn wire__crate__{name}_impl(");
let arm = format!("=> wire__crate__{name}_impl(");
(trimmed.starts_with(&def) || trimmed.contains(&arm)).then_some(gate.as_str())
})
}
fn already_gated(lines: &[&str], idx: usize, gate: &str) -> bool {
let gate_last_line = gate.lines().last().unwrap_or(gate).trim();
idx > 0 && lines[idx - 1].trim() == gate_last_line
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cfg_gated_free_functions_finds_single_line_gate() {
let lib_rs =
"#[cfg(feature = \"transcription\")]\npub fn build_decoder_prompt_tokens(x: i64) -> i64 {\n x\n}\n";
let found = cfg_gated_free_functions(lib_rs);
assert_eq!(
found,
vec![(
"build_decoder_prompt_tokens".to_string(),
"#[cfg(feature = \"transcription\")]".to_string()
)]
);
}
#[test]
fn cfg_gated_free_functions_finds_async_fn() {
let lib_rs = "#[cfg(feature = \"url-ingestion\")]\npub async fn map_url(uri: String) -> String {\n uri\n}\n";
let found = cfg_gated_free_functions(lib_rs);
assert_eq!(
found,
vec![("map_url".to_string(), "#[cfg(feature = \"url-ingestion\")]".to_string())]
);
}
#[test]
fn cfg_gated_free_functions_preserves_multiline_predicate() {
let lib_rs = concat!(
"#[cfg(any(\n",
" any(feature = \"late-interaction-presets\", feature = \"late-interaction\"),\n",
" feature = \"late-interaction-presets\"\n",
"))]\n",
"pub fn max_sim_score(a: i64, b: i64) -> f64 {\n",
" 0.0\n",
"}\n",
);
let found = cfg_gated_free_functions(lib_rs);
assert_eq!(found.len(), 1);
assert_eq!(found[0].0, "max_sim_score");
assert!(found[0].1.starts_with("#[cfg(any(\n"));
assert!(found[0].1.ends_with("))]"));
}
#[test]
fn cfg_gated_free_functions_ignores_indented_gates() {
let lib_rs = concat!(
"#[cfg(feature = \"presets\")]\n",
"impl MetaSchema {\n",
" #[cfg(feature = \"presets\")]\n",
" pub fn compile(json: String) -> MetaSchema {\n",
" todo!()\n",
" }\n",
"}\n",
);
assert!(cfg_gated_free_functions(lib_rs).is_empty());
}
#[test]
fn cfg_gated_free_functions_ignores_ungated_functions() {
let lib_rs = "pub fn always_present() -> i32 {\n 1\n}\n";
assert!(cfg_gated_free_functions(lib_rs).is_empty());
}
#[test]
fn inject_frb_cfg_gates_gates_definition_and_dispatch_arm() {
let frb_generated = concat!(
"fn wire__crate__build_decoder_prompt_tokens_impl(\n",
" port_: i32,\n",
") {\n",
"}\n",
"fn dispatch(func_id: i32) {\n",
" match func_id {\n",
" 28 => wire__crate__build_decoder_prompt_tokens_impl(port, ptr, rust_vec_len, data_len),\n",
" 29 => wire__crate__classify_chunks_impl(port, ptr, rust_vec_len, data_len),\n",
" }\n",
"}\n",
);
let gated = vec![(
"build_decoder_prompt_tokens".to_string(),
"#[cfg(feature = \"transcription\")]".to_string(),
)];
let result = inject_frb_cfg_gates(frb_generated, &gated);
assert!(
result.contains("#[cfg(feature = \"transcription\")]\nfn wire__crate__build_decoder_prompt_tokens_impl("),
"missing gate above the wire wrapper definition: {result}"
);
let expected_arm_gate = " #[cfg(feature = \"transcription\")]\n \
28 => wire__crate__build_decoder_prompt_tokens_impl(";
assert!(
result.contains(expected_arm_gate),
"missing gate above the dispatch arm, or wrong indentation: {result}"
);
assert!(
!result.contains("#[cfg(feature = \"transcription\")]\n 29 =>"),
"unrelated dispatch arm must not be gated: {result}"
);
}
#[test]
fn inject_frb_cfg_gates_is_idempotent() {
let frb_generated = concat!(
"fn wire__crate__timestamp_token_to_ms_impl(\n",
" port_: i32,\n",
") {\n",
"}\n",
);
let gated = vec![(
"timestamp_token_to_ms".to_string(),
"#[cfg(feature = \"transcription\")]".to_string(),
)];
let once = inject_frb_cfg_gates(frb_generated, &gated);
let twice = inject_frb_cfg_gates(&once, &gated);
assert_eq!(once, twice);
assert_eq!(once.matches("#[cfg(feature = \"transcription\")]").count(), 1);
}
#[test]
fn inject_frb_cfg_gates_noop_when_no_gated_functions() {
let frb_generated = "fn wire__crate__always_present_impl() {}\n";
assert_eq!(inject_frb_cfg_gates(frb_generated, &[]), frb_generated);
}
#[test]
fn carry_lib_rs_cfg_gates_into_frb_generated_end_to_end() {
let lib_rs = "#[cfg(feature = \"transcription\")]\npub fn timestamp_token_to_ms(id: i64) -> i64 {\n id\n}\n";
let frb_generated = concat!(
"fn wire__crate__timestamp_token_to_ms_impl(port_: i32) {}\n",
"fn dispatch(func_id: i32) {\n",
" match func_id {\n",
" 287 => wire__crate__timestamp_token_to_ms_impl(port, ptr, rust_vec_len, data_len),\n",
" }\n",
"}\n",
);
let result = carry_lib_rs_cfg_gates_into_frb_generated(lib_rs, frb_generated);
assert!(result.contains("#[cfg(feature = \"transcription\")]\nfn wire__crate__timestamp_token_to_ms_impl("));
assert!(result.contains(" #[cfg(feature = \"transcription\")]\n 287 =>"));
}
}