blob: 1577ba4476d026c23de2071dbbaafca265de2e1f [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Build-compiled C/C++ assertion header emitter (`--emit-c-asserts`).
//!
//! Emits a deterministic header intended to be included from a hand-written
//! C/C++ FFI header and compiled under the real target build flags (with
//! `-Werror=strict-prototypes -Werror=incompatible-function-pointer-types` on
//! Clang, or `-Werror=strict-prototypes -Werror=incompatible-pointer-types` on
//! GCC, for C translation units). Contains:
//! - target-policy `_Static_assert` checks (`CHAR_BIT`, pointer width,
//! `CHAR_MIN` signedness, and `sizeof(long) * CHAR_BIT`),
//! - `sizeof`, `_Alignof`, and per-field `offsetof` assertions for every
//! verified record,
//! - `sizeof` assertions for every verified enum (catching `-fshort-enums`
//! drift), and
//! - a strict-prototype function-pointer witness
//! `static R (*const anneal_proto_<sym>)(P...) = &<sym>;` for every verified
//! `direction == export` function.
use std::{collections::BTreeSet, fmt::Write as _};
use crate::{
check::{CheckOutcome, CppTagMeta, MatchedEnum, MatchedExport, MatchedRecord},
cpp_bundle::CppType,
report::ParseError,
rust_desc::RustType,
};
/// Emits a C11/C++17 assertion header for a passing [`CheckOutcome`].
///
/// Fails closed if `outcome.report.ok` is false or if any C/C++ identifier,
/// record name, enum name, or export type cannot be rendered safely without
/// syntactic ambiguity or injection.
pub fn emit_c_asserts(outcome: &CheckOutcome) -> Result<String, ParseError> {
if !outcome.report.ok {
return Err(ParseError::Schema(
"refusing to emit C assertion header for a failing FFI check".to_owned(),
));
}
let policy = &outcome.target_policy;
validate_c_comment_text(&policy.target_triple, "target_triple")?;
let mut body = String::new();
let _ = writeln!(body, "#include <limits.h>");
let _ = writeln!(body, "#include <stdbool.h>");
let _ = writeln!(body, "#include <stddef.h>");
let _ = writeln!(body, "#include <stdint.h>");
let _ = writeln!(body);
let _ = writeln!(body, "#ifdef __cplusplus");
let _ = writeln!(body, "#define ANNEAL_STATIC_ASSERT(cond, msg) static_assert((cond), msg)");
let _ = writeln!(body, "#define ANNEAL_ALIGNOF(T) alignof(T)");
let _ = writeln!(body, "#if defined(__GNUC__) || defined(__clang__)");
let _ = writeln!(body, "#define ANNEAL_RESTRICT __restrict__");
let _ = writeln!(body, "#else");
let _ = writeln!(body, "#define ANNEAL_RESTRICT");
let _ = writeln!(body, "#endif");
let _ = writeln!(body, "#else");
let _ = writeln!(body, "#define ANNEAL_STATIC_ASSERT(cond, msg) _Static_assert((cond), msg)");
let _ = writeln!(body, "#define ANNEAL_ALIGNOF(T) _Alignof(T)");
let _ = writeln!(body, "#define ANNEAL_RESTRICT restrict");
let _ = writeln!(body, "#endif");
let _ = writeln!(body, "#if defined(__GNUC__) || defined(__clang__)");
let _ = writeln!(body, "#define ANNEAL_MAYBE_UNUSED __attribute__((unused))");
let _ = writeln!(body, "#else");
let _ = writeln!(body, "#define ANNEAL_MAYBE_UNUSED");
let _ = writeln!(body, "#endif");
let _ = writeln!(body);
// 1. Target policy assertions.
let _ = writeln!(body, "/* Target policy assertions */");
let _ = writeln!(body, "ANNEAL_STATIC_ASSERT(CHAR_BIT == 8, \"anneal: expected 8-bit char\");");
let _ = writeln!(
body,
"ANNEAL_STATIC_ASSERT(sizeof(void *) * CHAR_BIT == {}, \
\"anneal: pointer_width_bits mismatch\");",
policy.pointer_width_bits
);
if policy.char_is_signed {
let _ = writeln!(
body,
"ANNEAL_STATIC_ASSERT(CHAR_MIN < 0, \"anneal: expected signed char (CHAR_MIN < 0)\");"
);
} else {
let _ = writeln!(
body,
"ANNEAL_STATIC_ASSERT(CHAR_MIN == 0, \
\"anneal: expected unsigned char (CHAR_MIN == 0)\");"
);
}
if let Some(c_long_bits) = policy.c_long_bits {
let _ = writeln!(
body,
"ANNEAL_STATIC_ASSERT(sizeof(long) * CHAR_BIT == {c_long_bits}, \
\"anneal: c_long_bits mismatch\");"
);
}
// 2. Record layout assertions (`sizeof`, `_Alignof`, `offsetof`).
if !outcome.matched_records.is_empty() {
let _ = writeln!(body);
let _ = writeln!(body, "/* Record layout assertions */");
for pair in &outcome.matched_records {
emit_record_asserts(&mut body, pair, policy.is_cplusplus)?;
}
}
// 3. Enum width assertions (`sizeof`).
if !outcome.matched_enums.is_empty() {
let _ = writeln!(body);
let _ = writeln!(body, "/* Enum size assertions */");
for en in &outcome.matched_enums {
emit_enum_asserts(&mut body, en, policy.is_cplusplus)?;
}
}
// 4. Export prototype witnesses.
if !outcome.matched_exports.is_empty() {
let _ = writeln!(body);
let _ = writeln!(body, "/* Export prototype witnesses */");
let mut used_witnesses = BTreeSet::new();
for exp in &outcome.matched_exports {
emit_export_witness(&mut body, exp, outcome, &mut used_witnesses)?;
}
}
let _ = writeln!(body);
let _ = writeln!(body, "#undef ANNEAL_MAYBE_UNUSED");
let _ = writeln!(body, "#undef ANNEAL_ALIGNOF");
let _ = writeln!(body, "#undef ANNEAL_STATIC_ASSERT");
let guard = format!("ANNEAL_FFI_ASSERTS_{:016X}_H", fnv1a_64(body.as_bytes()));
let mut out = String::new();
let _ =
writeln!(out, "/* Generated by anneal-ffi-check for target `{}`. */", policy.target_triple);
let _ = writeln!(
out,
"/* Compile C targets with: -Werror=strict-prototypes \
-Werror=incompatible-function-pointer-types (Clang) or \
-Werror=strict-prototypes -Werror=incompatible-pointer-types (GCC) */"
);
let _ = writeln!(out, "#ifndef {guard}");
let _ = writeln!(out, "#define {guard}");
let _ = writeln!(out);
out.push_str(&body);
let _ = writeln!(out, "#endif /* {guard} */");
Ok(out)
}
fn fnv1a_64(bytes: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for &b in bytes {
hash ^= u64::from(b);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
hash
}
fn emit_record_asserts(
out: &mut String,
pair: &MatchedRecord,
is_cplusplus: bool,
) -> Result<(), ParseError> {
let tag_name = effective_cpp_tag_name(
&pair.cpp.name,
pair.cpp.qualified_name.as_deref(),
Some(&pair.cpp.id),
is_cplusplus,
);
let c_ty = format_record_type_name(
tag_name,
pair.cpp.is_union,
pair.cpp.is_anonymous_typedef,
is_cplusplus,
)?;
let label = escape_c_string(&pair.cpp.id)?;
let _ = writeln!(
out,
"ANNEAL_STATIC_ASSERT(sizeof({c_ty}) == {}, \"anneal: sizeof({label}) mismatch\");",
pair.cpp.size_bytes
);
let _ = writeln!(
out,
"ANNEAL_STATIC_ASSERT(ANNEAL_ALIGNOF({c_ty}) == {}, \
\"anneal: alignof({label}) mismatch\");",
pair.cpp.align_bytes
);
for cf in &pair.cpp.fields {
if cf.name.is_empty() {
return Err(ParseError::Schema(format!(
"cannot emit offsetof assertion for unnamed field in `{}`",
pair.cpp.id
)));
}
if !cf.offset_bits.is_multiple_of(8) {
return Err(ParseError::Schema(format!(
"cannot emit offsetof assertion for non-byte-aligned field `{}.{}`",
pair.cpp.id, cf.name
)));
}
validate_c_ident(&cf.name, false, "record field name")?;
let flabel = escape_c_string(&cf.name)?;
let _ = writeln!(
out,
"ANNEAL_STATIC_ASSERT(offsetof({c_ty}, {}) == {}, \
\"anneal: offsetof({label}, {flabel}) mismatch\");",
cf.name,
cf.offset_bits / 8
);
}
Ok(())
}
fn emit_enum_asserts(
out: &mut String,
en: &MatchedEnum,
is_cplusplus: bool,
) -> Result<(), ParseError> {
if !en.cpp.bits.is_multiple_of(8) || en.cpp.bits == 0 {
return Err(ParseError::Schema(format!(
"cannot emit sizeof assertion for enum `{}` with width {} bits",
en.cpp.name, en.cpp.bits
)));
}
let tag_name = effective_cpp_tag_name(
&en.cpp.name,
en.cpp.qualified_name.as_deref(),
en.cpp.id.as_deref(),
is_cplusplus,
);
let c_ty = format_enum_type_name(
tag_name,
en.cpp.is_anonymous_typedef,
en.cpp.is_scoped.unwrap_or(false),
is_cplusplus,
)?;
let label = escape_c_string(&en.cpp.name)?;
let _ = writeln!(
out,
"ANNEAL_STATIC_ASSERT(sizeof({c_ty}) == {}, \"anneal: sizeof({label}) mismatch\");",
en.cpp.bits / 8
);
Ok(())
}
fn emit_export_witness(
out: &mut String,
exp: &MatchedExport,
outcome: &CheckOutcome,
used_witnesses: &mut BTreeSet<String>,
) -> Result<(), ParseError> {
let is_cxx = outcome.target_policy.is_cplusplus;
let fn_expr_name = if is_cxx {
exp.cpp.qualified_name.as_deref().unwrap_or(&exp.cpp.unmangled_name)
} else {
exp.cpp.unmangled_name.as_str()
};
validate_c_ident(fn_expr_name, is_cxx, "export function name")?;
let witness_ident = unique_c_ident(&exp.cpp.symbol, used_witnesses);
let params_str = if exp.rust.params.is_empty() {
"void".to_owned()
} else {
let mut parts = Vec::with_capacity(exp.rust.params.len());
for (rp, cp) in exp.rust.params.iter().zip(exp.cpp.params.iter()) {
parts.push(format_c_declarator(&rp.ty, &cp.ty, "", false, outcome)?);
}
parts.join(", ")
};
let fn_ptr_inner =
format!("(*const ANNEAL_MAYBE_UNUSED anneal_proto_{witness_ident})({params_str})");
let full_decl = format_c_declarator(
&exp.rust.return_ty,
&exp.cpp.return_ty,
&fn_ptr_inner,
false,
outcome,
)?;
if !is_cxx {
// In C mode, emit the pragma-guarded function-pointer witness BEFORE
// the exact prototype redeclaration so that omitting, deleting, or
// renaming an exported function in the included C header fails
// immediately with an undeclared-identifier error (rather than being
// silently synthesized by the redeclaration). The diagnostic-error
// pragmas enforce hard errors on GCC < 14 and Clang < 16 without
// requiring extra `-Werror` flags, and the trailing redeclaration
// enforces ISO C hard conflicting-types errors on other compilers.
let _ = writeln!(out, "#if !defined(__cplusplus)");
let _ = writeln!(out, "#if defined(__clang__)");
let _ = writeln!(out, "#pragma clang diagnostic push");
let _ = writeln!(out, "#pragma clang diagnostic ignored \"-Wunknown-warning-option\"");
let _ = writeln!(
out,
"#pragma clang diagnostic error \"-Wincompatible-function-pointer-types\""
);
let _ = writeln!(out, "#pragma clang diagnostic error \"-Wincompatible-pointer-types\"");
let _ = writeln!(out, "#elif defined(__GNUC__)");
let _ = writeln!(out, "#pragma GCC diagnostic push");
let _ = writeln!(out, "#pragma GCC diagnostic error \"-Wincompatible-pointer-types\"");
let _ = writeln!(out, "#endif");
let _ = writeln!(out, "#endif");
}
let _ = writeln!(out, "static {full_decl} = &{fn_expr_name};");
if !is_cxx {
let redecl_inner = format!("{fn_expr_name}({params_str})");
let redecl = format_c_declarator(
&exp.rust.return_ty,
&exp.cpp.return_ty,
&redecl_inner,
false,
outcome,
)?;
let _ = writeln!(out, "#if !defined(__cplusplus)");
let _ = writeln!(out, "#if defined(__clang__)");
let _ = writeln!(out, "#pragma clang diagnostic pop");
let _ = writeln!(out, "#pragma clang diagnostic push");
let _ = writeln!(out, "#pragma clang diagnostic ignored \"-Wredundant-decls\"");
let _ = writeln!(out, "#elif defined(__GNUC__)");
let _ = writeln!(out, "#pragma GCC diagnostic pop");
let _ = writeln!(out, "#pragma GCC diagnostic push");
let _ = writeln!(out, "#pragma GCC diagnostic ignored \"-Wredundant-decls\"");
let _ = writeln!(out, "#endif");
let _ = writeln!(out, "{redecl};");
let _ = writeln!(out, "#if defined(__clang__)");
let _ = writeln!(out, "#pragma clang diagnostic pop");
let _ = writeln!(out, "#elif defined(__GNUC__)");
let _ = writeln!(out, "#pragma GCC diagnostic pop");
let _ = writeln!(out, "#endif");
let _ = writeln!(out, "#endif");
}
Ok(())
}
/// Formats a C/C++ type declarator using inside-out C declarator rules so
/// pointers-to-pointers, pointers-to-arrays, and function-pointer witnesses
/// returning pointers stay syntactically valid in both C11 and C++17.
fn format_c_declarator(
rty: &RustType,
cty: &CppType,
inner: &str,
qual_const: bool,
outcome: &CheckOutcome,
) -> Result<String, ParseError> {
let is_cxx = outcome.target_policy.is_cplusplus;
match (rty, cty) {
(
RustType::Ptr { pointee: rp, is_const: rc, .. },
CppType::Ptr { pointee: cp, is_restrict, .. },
) => {
let mut ptr_prefix = String::from("*");
if qual_const {
ptr_prefix.push_str("const");
}
if *is_restrict {
if qual_const {
ptr_prefix.push(' ');
}
ptr_prefix.push_str("ANNEAL_RESTRICT");
}
if !inner.is_empty() {
if qual_const || *is_restrict {
ptr_prefix.push(' ');
}
ptr_prefix.push_str(inner);
}
format_c_declarator(rp, cp, &ptr_prefix, *rc, outcome)
}
(
RustType::Ptr { pointee: rp, is_const: rc, .. },
CppType::Ref { pointee: cp, is_rvalue, .. },
) => {
let sigil = if *is_rvalue { "&&" } else { "&" };
let ref_inner =
if inner.is_empty() { sigil.to_owned() } else { format!("{sigil}{inner}") };
format_c_declarator(rp, cp, &ref_inner, *rc, outcome)
}
(RustType::Array { elem: re, len }, CppType::Array { elem: ce, .. }) => {
let wrapped = if inner.starts_with('*') || inner.starts_with('&') {
format!("({inner})[{len}]")
} else {
format!("{inner}[{len}]")
};
format_c_declarator(re, ce, &wrapped, qual_const, outcome)
}
_ => {
let base = format_c_base_type(rty, cty, is_cxx, outcome)?;
let qualified = if qual_const { format!("const {base}") } else { base };
if inner.is_empty() {
Ok(qualified)
} else {
Ok(format!("{qualified} {inner}"))
}
}
}
}
fn format_c_base_type(
rty: &RustType,
cty: &CppType,
is_cxx: bool,
outcome: &CheckOutcome,
) -> Result<String, ParseError> {
match (rty, cty) {
(RustType::Void, CppType::Void) => Ok("void".to_owned()),
(RustType::Bool, CppType::Bool) => Ok("bool".to_owned()),
(RustType::CChar, CppType::Int { c_spelling, .. }) => match c_spelling.as_deref() {
Some(sp) => Ok(validated_c_int_spelling(sp)?.to_owned()),
None => Ok("char".to_owned()),
},
(RustType::CLong, CppType::Int { c_spelling, .. }) => match c_spelling.as_deref() {
Some(sp) => Ok(validated_c_int_spelling(sp)?.to_owned()),
None => Ok("long".to_owned()),
},
(RustType::CULong, CppType::Int { c_spelling, .. }) => match c_spelling.as_deref() {
Some(sp) => Ok(validated_c_int_spelling(sp)?.to_owned()),
None => Ok("unsigned long".to_owned()),
},
(RustType::Int { bits, signed }, CppType::Int { c_spelling, .. }) => {
if let Some(sp) = c_spelling.as_deref() {
return Ok(validated_c_int_spelling(sp)?.to_owned());
}
let ty = match (bits, signed) {
(8, true) => "int8_t",
(8, false) => "uint8_t",
(16, true) => "int16_t",
(16, false) => "uint16_t",
(32, true) => "int32_t",
(32, false) => "uint32_t",
(64, true) => "int64_t",
(64, false) => "uint64_t",
(128, true) => "__int128",
(128, false) => "unsigned __int128",
_ => {
return Err(ParseError::Schema(format!(
"cannot emit C integer type for {bits}-bit signed={signed}"
)));
}
};
Ok(ty.to_owned())
}
(
RustType::Enum { .. } | RustType::CEnum { .. },
CppType::Int { enum_id, enum_name, .. },
) => {
let key = enum_id.as_deref().or(enum_name.as_deref()).ok_or_else(|| {
ParseError::Schema(
"cannot emit C enum prototype witness without C enum identity".to_owned(),
)
})?;
let meta = outcome.enum_tags.get(key).ok_or_else(|| {
ParseError::Schema(format!(
"cannot emit C enum prototype witness: enum `{key}` not found in bundle"
))
})?;
let tag_name = effective_cpp_tag_name(
&meta.name,
meta.qualified_name.as_deref(),
Some(key),
is_cxx,
);
format_enum_type_name(tag_name, meta.is_anonymous_typedef, meta.is_scoped, is_cxx)
}
(RustType::Record { .. }, CppType::Record { id }) => {
let meta = outcome.record_tags.get(id).ok_or_else(|| {
ParseError::Schema(format!(
"cannot emit C record type: record `{id}` not found in bundle"
))
})?;
let tag_name = effective_cpp_tag_name(
&meta.name,
meta.qualified_name.as_deref(),
Some(id),
is_cxx,
);
format_record_type_name(tag_name, meta.is_union, meta.is_anonymous_typedef, is_cxx)
}
(RustType::Opaque { .. }, CppType::Void) => Ok("void".to_owned()),
(RustType::Opaque { .. }, CppType::Record { id }) => {
let meta: &CppTagMeta = outcome.record_tags.get(id).ok_or_else(|| {
ParseError::Schema(format!(
"cannot emit C opaque pointee type: record `{id}` not found in bundle"
))
})?;
let tag_name = effective_cpp_tag_name(
&meta.name,
meta.qualified_name.as_deref(),
Some(id),
is_cxx,
);
format_record_type_name(tag_name, meta.is_union, meta.is_anonymous_typedef, is_cxx)
}
_ => Err(ParseError::Schema(format!(
"cannot emit C assertion type for Rust `{rty:?}` / C `{cty:?}`"
))),
}
}
fn effective_cpp_tag_name<'a>(
name: &'a str,
qualified_name: Option<&'a str>,
id: Option<&'a str>,
is_cplusplus: bool,
) -> &'a str {
if is_cplusplus {
if let Some(qn) = qualified_name {
return qn;
}
if let Some(raw_id) = id {
let stripped = raw_id
.strip_prefix("struct.")
.or_else(|| raw_id.strip_prefix("union."))
.or_else(|| raw_id.strip_prefix("enum."))
.unwrap_or(raw_id);
if stripped.contains("::") {
return stripped;
}
}
}
name
}
fn validated_c_int_spelling(s: &str) -> Result<&str, ParseError> {
match s {
"char"
| "signed char"
| "unsigned char"
| "short"
| "short int"
| "signed short"
| "signed short int"
| "unsigned short"
| "unsigned short int"
| "int"
| "signed"
| "signed int"
| "unsigned"
| "unsigned int"
| "long"
| "long int"
| "signed long"
| "signed long int"
| "unsigned long"
| "unsigned long int"
| "long long"
| "long long int"
| "signed long long"
| "signed long long int"
| "unsigned long long"
| "unsigned long long int"
| "__int128"
| "unsigned __int128" => Ok(s),
other => Err(ParseError::Schema(format!(
"unsupported canonical C integer spelling `{other}` in RawCppBundle"
))),
}
}
fn format_record_type_name(
name: &str,
is_union: bool,
is_anonymous_typedef: bool,
is_cplusplus: bool,
) -> Result<String, ParseError> {
if name.is_empty() {
return Err(ParseError::Schema(
"cannot emit C assertion for unnamed anonymous struct/union".to_owned(),
));
}
validate_c_ident(name, is_cplusplus, "record name")?;
if is_anonymous_typedef || is_cplusplus {
Ok(name.to_owned())
} else if is_union {
Ok(format!("union {name}"))
} else {
Ok(format!("struct {name}"))
}
}
fn format_enum_type_name(
name: &str,
is_anonymous_typedef: bool,
is_scoped: bool,
is_cplusplus: bool,
) -> Result<String, ParseError> {
if name.is_empty() {
return Err(ParseError::Schema(
"cannot emit C assertion for unnamed anonymous enum".to_owned(),
));
}
validate_c_ident(name, is_cplusplus, "enum name")?;
if is_anonymous_typedef || is_scoped || is_cplusplus {
Ok(name.to_owned())
} else {
Ok(format!("enum {name}"))
}
}
fn validate_c_ident(name: &str, allow_cxx_qual: bool, ctx: &str) -> Result<(), ParseError> {
if name.is_empty() {
return Err(ParseError::Schema(format!("{ctx} cannot be empty")));
}
let segments: Vec<&str> = if allow_cxx_qual { name.split("::").collect() } else { vec![name] };
for seg in segments {
let mut cs = seg.chars();
let valid = matches!(cs.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
&& cs.all(|c| c.is_ascii_alphanumeric() || c == '_');
if !valid {
return Err(ParseError::Schema(format!(
"{ctx} `{name}` is not a valid C/C++ identifier"
)));
}
}
Ok(())
}
fn validate_c_comment_text(s: &str, ctx: &str) -> Result<(), ParseError> {
if s.contains("*/") || s.contains("/*") || s.contains("??") {
return Err(ParseError::Schema(format!(
"{ctx} contains disallowed C comment delimiter or trigraph sequence"
)));
}
for ch in s.chars() {
if ch == '\0' || ch.is_control() || is_bidi_or_invisible(ch) {
return Err(ParseError::Schema(format!(
"{ctx} contains disallowed control or bidi character U+{:04X}",
ch as u32
)));
}
}
Ok(())
}
fn escape_c_string(s: &str) -> Result<String, ParseError> {
for ch in s.chars() {
if ch == '\0' || ch.is_control() || is_bidi_or_invisible(ch) {
return Err(ParseError::Schema(format!(
"C string literal contains disallowed control or bidi character U+{:04X}",
ch as u32
)));
}
}
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
// Escape `?` to block C11 trigraph sequences such as `??/` from
// turning into backslashes inside string literals.
'?' => out.push_str("\\?"),
c => out.push(c),
}
}
Ok(out)
}
fn is_bidi_or_invisible(ch: char) -> bool {
matches!(
ch as u32,
0x061C
| 0x200B..=0x200F
| 0x202A..=0x202E
| 0x2060..=0x206F
| 0xFEFF
)
}
fn unique_c_ident(raw: &str, used: &mut BTreeSet<String>) -> String {
let mut base = String::new();
for ch in raw.chars() {
if ch.is_ascii_alphanumeric() || ch == '_' {
base.push(ch);
} else {
base.push('_');
}
}
if base.is_empty() || !base.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
{
base.insert_str(0, "fn_");
}
if used.insert(base.clone()) {
return base;
}
let mut suffix = 2usize;
loop {
let cand = format!("{base}_{suffix}");
if used.insert(cand.clone()) {
return cand;
}
suffix += 1;
}
}