pub const C_KEYWORDS: &[&str] = &[
"auto",
"break",
"case",
"char",
"const",
"continue",
"default",
"do",
"double",
"else",
"enum",
"extern",
"float",
"for",
"goto",
"if",
"inline",
"int",
"long",
"register",
"restrict",
"return",
"short",
"signed",
"sizeof",
"static",
"struct",
"switch",
"typedef",
"union",
"unsigned",
"void",
"volatile",
"while",
"_Alignas",
"_Alignof",
"_Atomic",
"_Bool",
"_Complex",
"_Generic",
"_Imaginary",
"_Noreturn",
"_Static_assert",
"_Thread_local",
"alignas",
"alignof",
"bool",
"constexpr",
"false",
"nullptr",
"static_assert",
"thread_local",
"true",
"typeof",
"typeof_unqual",
"_BitInt",
"_Decimal128",
"_Decimal32",
"_Decimal64",
];
pub fn is_c_keyword(s: &str) -> bool {
C_KEYWORDS.contains(&s)
}
pub fn sanitize_ident(name: &str) -> String {
let mut out = String::with_capacity(name.len());
for ch in name.chars() {
if ch.is_ascii_alphanumeric() || ch == '_' {
out.push(ch);
} else {
out.push('_');
}
}
if out.is_empty() {
out.push('_');
} else if out.starts_with(|c: char| c.is_ascii_digit()) {
out.insert(0, '_');
}
if is_c_keyword(&out) {
out.push('_');
}
out
}
pub fn sanitize_ident_strict(name: &str) -> String {
let base = sanitize_ident(name);
let trimmed = base.trim_start_matches('_');
let mut out = if trimmed.is_empty() || trimmed.starts_with(|c: char| c.is_ascii_digit()) {
format!("z{trimmed}")
} else {
trimmed.to_string()
};
if is_c_keyword(&out) {
out.push('_');
}
out
}
#[derive(Debug, Clone)]
pub struct Gensym {
prefix: String,
counter: u64,
}
impl Gensym {
pub fn new() -> Self {
Self::with_prefix("__tmp")
}
pub fn with_prefix(prefix: &str) -> Self {
Self {
prefix: prefix.to_string(),
counter: 0,
}
}
pub fn fresh(&mut self) -> String {
let name = format!("{}{}", self.prefix, self.counter);
self.counter += 1;
name
}
pub fn fresh_named(&mut self, base: &str) -> String {
let name = format!("{}_{}_{}", self.prefix, sanitize_ident(base), self.counter);
self.counter += 1;
name
}
pub fn reset(&mut self) {
self.counter = 0;
}
}
impl Default for Gensym {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanitizes_invalid_characters() {
assert_eq!(sanitize_ident("hello world"), "hello_world");
assert_eq!(sanitize_ident("my-var!"), "my_var_");
assert_eq!(sanitize_ident("a.b.c"), "a_b_c");
assert_eq!(sanitize_ident("ns::name"), "ns__name");
}
#[test]
fn sanitizes_leading_digit_and_empty() {
assert_eq!(sanitize_ident("123abc"), "_123abc");
assert_eq!(sanitize_ident("0"), "_0");
assert_eq!(sanitize_ident(""), "_");
}
#[test]
fn sanitizes_keywords() {
assert_eq!(sanitize_ident("int"), "int_");
assert_eq!(sanitize_ident("struct"), "struct_");
assert_eq!(sanitize_ident("_Bool"), "_Bool_");
assert_eq!(sanitize_ident("count"), "count");
}
#[test]
fn strict_avoids_reserved_identifiers() {
assert_eq!(sanitize_ident_strict("_Foo"), "Foo");
assert_eq!(sanitize_ident_strict("__bar"), "bar");
assert_eq!(sanitize_ident_strict("_lower"), "lower");
assert_eq!(sanitize_ident_strict("123"), "z123");
assert_eq!(sanitize_ident_strict("_"), "z");
assert_eq!(sanitize_ident_strict(""), "z");
assert_eq!(sanitize_ident_strict("normal"), "normal");
assert_eq!(sanitize_ident_strict("_int"), "int_");
for input in ["_Foo", "__x", "_", "___", "123", ""] {
assert!(!sanitize_ident_strict(input).starts_with('_'));
}
}
#[test]
fn keyword_lookup() {
assert!(is_c_keyword("return"));
assert!(is_c_keyword("bool"));
assert!(is_c_keyword("_Atomic"));
assert!(!is_c_keyword("Return"));
assert!(!is_c_keyword("counter"));
}
#[test]
fn gensym_is_unique_and_prefixed() {
let mut g = Gensym::new();
assert_eq!(g.fresh(), "__tmp0");
assert_eq!(g.fresh(), "__tmp1");
assert_eq!(g.fresh_named("index"), "__tmp_index_2");
g.reset();
assert_eq!(g.fresh(), "__tmp0");
let mut labels = Gensym::with_prefix("L");
assert_eq!(labels.fresh(), "L0");
assert_eq!(labels.fresh(), "L1");
}
}