1use crate::rust::naming::words;
6
7pub(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
29const 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
63pub(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
72pub(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 && name != "documentation"
84}
85
86const 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
136fn 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
144pub(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
156pub 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
186pub(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
211pub(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
226pub(crate) fn comment_text(text: &str) -> String {
229 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
256pub(crate) fn tag_name_ok(name: &str) -> bool {
261 !name.is_empty() && !name.contains([',', '\\', '\'', '"', '`'])
262}
263
264pub(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}