From 0631852213e69af77e325bc45b01515f8c5f98e9 Mon Sep 17 00:00:00 2001 From: Benjamin Milde Date: Wed, 6 Nov 2024 11:09:28 +0100 Subject: [PATCH] Add atom escaping --- compiler-core/src/codegen.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/compiler-core/src/codegen.rs b/compiler-core/src/codegen.rs index cbef5a7472a..dd9f2710a8e 100644 --- a/compiler-core/src/codegen.rs +++ b/compiler-core/src/codegen.rs @@ -113,6 +113,7 @@ impl<'a> ErlangApp<'a> { .chain(native_modules) .unique() .sorted() + .map(|m| Self::format_atom(&m)) .join(",\n "); // TODO: When precompiling for production (i.e. as a precompiled hex @@ -151,6 +152,27 @@ impl<'a> ErlangApp<'a> { writer.write(&path, &text) } + + fn format_atom(s: &EcoString) -> EcoString { + match s.chars().next() { + Some(first_char) => { + // Check if first character is not lowercase + let needs_quotes = !first_char.is_ascii_lowercase(); + + // Check if string contains any characters other than alphanumeric, underscore, or @ + let contains_special = s + .chars() + .any(|c| !(c.is_alphanumeric() || c == '_' || c == '@')); + + if needs_quotes || contains_special { + EcoString::from(format!("'{}'", s)) + } else { + s.clone() + } + } + None => EcoString::from("''"), + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)]