Skip to main content

roas_codegen/go/
naming.rs

1//! Go identifiers and literals: exported casing, collision-free
2//! allocation (shared with the Rust backend), and the quoting Go source
3//! and struct tags need.
4
5use crate::rust::naming::words;
6
7/// An exported Go identifier from name parts: ASCII only, so it is a
8/// legal identifier however the description spells it, and upper-case
9/// led, so it is exported. Never empty.
10pub(crate) fn exported(parts: &[String]) -> String {
11    let mut out = String::new();
12    for word in parts.iter().flat_map(|p| words(p)) {
13        let word: String = word.chars().filter(char::is_ascii_alphanumeric).collect();
14        let mut chars = word.chars();
15        if let Some(first) = chars.next() {
16            out.push(first.to_ascii_uppercase());
17            out.extend(chars);
18        }
19    }
20    if out.is_empty() {
21        out = "Unnamed".to_owned();
22    }
23    if out.starts_with(|c: char| c.is_ascii_digit()) {
24        out.insert(0, 'N');
25    }
26    out
27}
28
29/// Go's keywords; an identifier the configuration supplies must not be
30/// one.
31const KEYWORDS: &[&str] = &[
32    "break",
33    "case",
34    "chan",
35    "const",
36    "continue",
37    "default",
38    "defer",
39    "else",
40    "fallthrough",
41    "for",
42    "func",
43    "go",
44    "goto",
45    "if",
46    "import",
47    "interface",
48    "map",
49    "package",
50    "range",
51    "return",
52    "select",
53    "struct",
54    "switch",
55    "type",
56    "var",
57];
58
59pub(crate) fn is_keyword(ident: &str) -> bool {
60    KEYWORDS.contains(&ident)
61}
62
63/// An exported ASCII Go identifier, as a name from the configuration
64/// must be.
65pub(crate) fn is_exported_ident(ident: &str) -> bool {
66    ident.starts_with(|c: char| c.is_ascii_uppercase())
67        && ident
68            .bytes()
69            .all(|b| b.is_ascii_alphanumeric() || b == b'_')
70}
71
72/// A package name: lowercase ASCII, a letter first, not a keyword, and
73/// one another package can import (`main` and `init` cannot be).
74pub(crate) fn is_package_name(name: &str) -> bool {
75    name.starts_with(|c: char| c.is_ascii_lowercase())
76        && name
77            .bytes()
78            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
79        && !is_keyword(name)
80        && name != "main"
81        && name != "init"
82        // `go build` skips a file whose package is `documentation`.
83        && name != "documentation"
84}
85
86/// Operating systems and architectures `go build` knows, from
87/// `internal/syslist`: a file named `x_<os>.go` or `x_<arch>.go` builds
88/// only there.
89const KNOWN_OS: &[&str] = &[
90    "aix",
91    "android",
92    "darwin",
93    "dragonfly",
94    "freebsd",
95    "hurd",
96    "illumos",
97    "ios",
98    "js",
99    "linux",
100    "nacl",
101    "netbsd",
102    "openbsd",
103    "plan9",
104    "solaris",
105    "wasip1",
106    "windows",
107    "zos",
108];
109const KNOWN_ARCH: &[&str] = &[
110    "386",
111    "amd64",
112    "amd64p32",
113    "arm",
114    "armbe",
115    "arm64",
116    "arm64be",
117    "loong64",
118    "mips",
119    "mipsle",
120    "mips64",
121    "mips64le",
122    "mips64p32",
123    "mips64p32le",
124    "ppc",
125    "ppc64",
126    "ppc64le",
127    "riscv",
128    "riscv64",
129    "s390",
130    "s390x",
131    "sparc",
132    "sparc64",
133    "wasm",
134];
135
136/// Whether `go build` would read something into a file named
137/// `<stem>.go` beyond its contents: a `_test` file is built only by
138/// `go test`, and an `_<os>` or `_<arch>` suffix restricts the platforms.
139fn constrained(stem: &str) -> bool {
140    let last = stem.rsplit('_').next().unwrap_or(stem);
141    stem.contains('_') && (last == "test" || KNOWN_OS.contains(&last) || KNOWN_ARCH.contains(&last))
142}
143
144/// A file stem `go build` reads as plain source: lowercase ASCII, a
145/// letter first, no build-constraint suffix, nothing Windows resolves
146/// elsewhere.
147pub(crate) fn is_file_stem(stem: &str) -> bool {
148    stem.starts_with(|c: char| c.is_ascii_lowercase())
149        && stem
150            .bytes()
151            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
152        && !constrained(stem)
153        && crate::write::windows_safe(stem)
154}
155
156/// A file stem derived from free text such as a label: lowercase, other
157/// characters to `_`, never empty, never digit-led, and never one `go
158/// build` would constrain.
159pub fn go_file_name(text: &str) -> String {
160    let mut stem: String = text
161        .chars()
162        .map(|c| {
163            if c.is_ascii_alphanumeric() {
164                c.to_ascii_lowercase()
165            } else {
166                '_'
167            }
168        })
169        .collect();
170    while stem.contains("__") {
171        stem = stem.replace("__", "_");
172    }
173    let stem = stem.trim_matches('_').to_owned();
174    let stem = match stem.chars().next() {
175        None => "api".to_owned(),
176        Some(c) if c.is_ascii_digit() => format!("m_{stem}"),
177        Some(_) => stem,
178    };
179    if is_file_stem(&stem) {
180        stem
181    } else {
182        format!("{stem}_types")
183    }
184}
185
186/// A Go interpreted string literal for `text`, which may hold anything.
187pub(crate) fn quote(text: &str) -> String {
188    let mut out = String::with_capacity(text.len() + 2);
189    out.push('"');
190    for c in text.chars() {
191        match c {
192            '"' => out.push_str("\\\""),
193            '\\' => out.push_str("\\\\"),
194            '\n' => out.push_str("\\n"),
195            '\r' => out.push_str("\\r"),
196            '\t' => out.push_str("\\t"),
197            c if c.is_control() || is_invisible(c) => {
198                if (c as u32) < 0x10000 {
199                    out.push_str(&format!("\\u{:04x}", c as u32));
200                } else {
201                    out.push_str(&format!("\\U{:08x}", c as u32));
202                }
203            }
204            c => out.push(c),
205        }
206    }
207    out.push('"');
208    out
209}
210
211/// Characters that reorder or hide text: escaped in literals and
212/// comments, so the source reads as it compiles.
213pub(crate) fn is_invisible(c: char) -> bool {
214    matches!(
215        c,
216        '\u{061C}'
217            | '\u{200B}'..='\u{200F}'
218            | '\u{2028}'
219            | '\u{2029}'
220            | '\u{202A}'..='\u{202E}'
221            | '\u{2066}'..='\u{2069}'
222            | '\u{FEFF}'
223    )
224}
225
226/// One comment line's text, with anything that would end the line or
227/// hide what it says escaped.
228pub(crate) fn comment_text(text: &str) -> String {
229    // `gofmt` reads a `// +build ...` line anywhere as a build constraint
230    // and moves it to the top, where it can exclude the whole file; the
231    // escaped `+` reads the same and constrains nothing.
232    let trimmed = text.trim_start();
233    let constraint = trimmed
234        .strip_prefix("+build")
235        .is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace));
236    let text = if constraint {
237        format!(
238            "{}\\u{{2b}}{}",
239            &text[..text.len() - trimmed.len()],
240            &trimmed[1..]
241        )
242    } else {
243        text.to_owned()
244    };
245    text.chars()
246        .flat_map(|c| {
247            if (c.is_control() && c != '\t') || is_invisible(c) {
248                c.escape_unicode().collect::<Vec<_>>()
249            } else {
250                vec![c]
251            }
252        })
253        .collect()
254}
255
256/// Whether `encoding/json/v2` can carry `name` in a struct tag: the
257/// stdlib reserves `,`, `\`, `'`, `"` and the backtick in a tag name,
258/// takes an empty name as "use the field name", and `-` alone as "skip
259/// this field" (`-,` names it).
260pub(crate) fn tag_name_ok(name: &str) -> bool {
261    !name.is_empty() && !name.contains([',', '\\', '\'', '"', '`'])
262}
263
264/// A struct-tag key as `reflect.StructTag` parses one: non-empty, no
265/// space, quote, colon or control character.
266pub(crate) fn is_tag_key(key: &str) -> bool {
267    !key.is_empty()
268        && key
269            .chars()
270            .all(|c| c.is_ascii_graphic() && c != '"' && c != ':' && c != '`')
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    fn p(s: &str) -> Vec<String> {
278        vec![s.to_owned()]
279    }
280
281    #[test]
282    fn exported_names() {
283        assert_eq!(exported(&p("pet-status")), "PetStatus");
284        assert_eq!(exported(&p("HTTPServer")), "HttpServer");
285        assert_eq!(exported(&p("123abc")), "N123Abc");
286        assert_eq!(exported(&p("имя")), "Unnamed");
287        assert_eq!(exported(&p("café")), "Caf");
288        assert_eq!(exported(&p("type")), "Type");
289    }
290
291    #[test]
292    fn file_stems_avoid_build_constraints() {
293        assert_eq!(go_file_name("pet-store"), "pet_store");
294        assert_eq!(go_file_name("api_linux"), "api_linux_types");
295        assert_eq!(go_file_name("x-test"), "x_test_types");
296        assert_eq!(go_file_name("386"), "m_386_types");
297        assert_eq!(go_file_name("linux"), "linux");
298        assert_eq!(go_file_name("--"), "api");
299        assert_eq!(go_file_name("con"), "con_types");
300        assert!(!is_file_stem("api_amd64"));
301        assert!(is_file_stem("types"));
302    }
303
304    #[test]
305    fn quoting() {
306        assert_eq!(quote("a\"b\\c\n"), "\"a\\\"b\\\\c\\n\"");
307        assert_eq!(quote("\u{202E}"), "\"\\u202e\"");
308        assert_eq!(quote("\u{1}"), "\"\\u0001\"");
309        assert_eq!(comment_text("a\u{0}b"), "a\\u{0}b");
310        assert_eq!(comment_text("+build ignore"), "\\u{2b}build ignore");
311        assert_eq!(comment_text("  +build"), "  \\u{2b}build");
312        assert_eq!(comment_text("+builder"), "+builder");
313    }
314
315    #[test]
316    fn tag_names() {
317        assert!(tag_name_ok("name"));
318        assert!(tag_name_ok("-"));
319        assert!(tag_name_ok("x y"));
320        assert!(!tag_name_ok(""));
321        assert!(!tag_name_ok("a,b"));
322        assert!(!tag_name_ok("a\"b"));
323        assert!(is_tag_key("db"));
324        assert!(!is_tag_key("a b"));
325        assert!(!is_tag_key("a:b"));
326    }
327}