1use heck::ToLowerCamelCase;
2use std::collections::hash_map::RandomState;
3use std::collections::{HashMap, HashSet};
4use std::hash::{BuildHasher, Hash};
5
6#[derive(Default)]
7pub struct LocalNames {
8 local_name_ids: HashMap<u64, String>,
10 local_names: HashSet<String>,
11 random_state: RandomState,
12}
13
14impl<'a> LocalNames {
15 pub fn exclude_globals(&mut self, globals: &[&str]) {
17 for name in globals {
18 self.local_names.insert(name.to_string());
19 }
20 }
21
22 pub fn create_once(&'a mut self, goal_name: &str) -> &'a str {
24 let goal_name = if let Some(last_char) = goal_name.rfind('/') {
25 &goal_name[last_char + 1..]
26 } else {
27 goal_name
28 };
29 let mut goal = to_js_identifier(goal_name);
30 if self.local_names.contains(&goal) {
31 let mut idx = 1;
32 loop {
33 let valid_name_suffixed = format!("{goal}${idx}");
34 if !self.local_names.contains(&valid_name_suffixed) {
35 goal = valid_name_suffixed;
36 break;
37 }
38 idx += 1;
39 }
40 }
41 self.local_names.insert(goal.to_string());
42 self.local_names.get(&goal).unwrap()
43 }
44
45 pub fn get<H: Hash>(&'a self, unique_id: H) -> &'a str {
46 let hash = self.random_state.hash_one(&unique_id);
47 if !self.local_name_ids.contains_key(&hash) {
48 panic!("Internal error, no name defined in local names map");
49 }
50 &self.local_name_ids[&hash]
51 }
52
53 pub fn try_get<H: Hash>(&'a self, unique_id: H) -> Option<&'a str> {
54 let hash = self.random_state.hash_one(&unique_id);
55 if !self.local_name_ids.contains_key(&hash) {
56 return None;
57 }
58 Some(&self.local_name_ids[&hash])
59 }
60
61 pub fn get_or_create<H: Hash>(&'a mut self, unique_id: H, goal_name: &str) -> (&'a str, bool) {
66 let hash = self.random_state.hash_one(&unique_id);
67 let mut seen = true;
68 #[allow(clippy::map_entry)]
69 if !self.local_name_ids.contains_key(&hash) {
70 let goal = self.create_once(goal_name).to_string();
71 self.local_name_ids.insert(hash, goal);
72 seen = false;
73 }
74 (self.local_name_ids.get(&hash).unwrap(), seen)
75 }
76}
77
78pub fn to_js_identifier(goal_name: &str) -> String {
80 if is_valid_js_identifier(goal_name) {
81 goal_name.to_string()
82 } else {
83 let goal = goal_name.to_lower_camel_case();
84 let mut identifier = String::new();
85 for char in goal.chars() {
86 let valid_char = if identifier.is_empty() {
87 is_valid_js_identifier_start(char)
88 } else {
89 is_valid_js_identifier_char(char)
90 };
91 if valid_char {
92 identifier.push(char);
93 } else {
94 identifier.push(match char {
95 '.' => '_',
96 _ => '$',
97 });
98 }
99 }
100 if !is_valid_js_identifier(&identifier) {
101 identifier = format!("_{identifier}");
102 if !is_valid_js_identifier(&identifier) {
103 panic!("Unable to generate valid identifier {identifier} for '{goal_name}'");
104 }
105 }
106 identifier
107 }
108}
109
110pub fn static_member_name(item_name: &str) -> String {
116 let name = item_name.to_lower_camel_case();
117 if name == "prototype" {
118 "prototype_".to_string()
119 } else {
120 name
121 }
122}
123
124pub fn function_expression_name(name: &str) -> String {
129 if is_js_reserved_word(name) || matches!(name, "arguments" | "eval") {
130 format!("${name}")
131 } else {
132 name.to_string()
133 }
134}
135
136pub fn is_readonly_class_static(name: &str) -> bool {
142 matches!(name, "name" | "length" | "caller" | "arguments")
143}
144
145pub fn is_valid_js_identifier(s: &str) -> bool {
146 let mut chars = s.chars();
147 if let Some(char) = chars.next() {
148 if !is_valid_js_identifier_start(char) {
149 return false;
150 }
151 } else {
152 return false;
153 }
154 for char in chars {
155 if !is_valid_js_identifier_char(char) {
156 return false;
157 }
158 }
159 !is_js_reserved_word(s)
160}
161
162pub fn is_js_reserved_word(s: &str) -> bool {
163 RESERVED_KEYWORDS.binary_search(&s).is_ok()
164}
165
166fn is_valid_js_identifier_start(code: char) -> bool {
169 match code {
170 'A'..='Z' | 'a'..='z' | '$' | '_' => true,
171 _ => false,
173 }
174}
175
176fn is_valid_js_identifier_char(code: char) -> bool {
179 match code {
180 '0'..='9' | 'A'..='Z' | 'a'..='z' | '$' | '_' => true,
181 _ => false,
183 }
184}
185
186pub fn maybe_quote_id(name: &str) -> String {
192 if is_valid_js_identifier(name) {
193 name.to_string()
194 } else {
195 js_string_literal(name)
196 }
197}
198
199pub fn maybe_quote_member(name: &str) -> String {
202 if name == "*" {
203 "".to_string()
204 } else if is_valid_js_identifier(name) {
205 format!(".{name}")
206 } else {
207 format!("[{}]", js_string_literal(name))
208 }
209}
210
211pub fn js_string_literal(value: &str) -> String {
213 let mut literal = String::with_capacity(value.len() + 2);
214 literal.push('"');
215 for ch in value.chars() {
216 match ch {
217 '"' => literal.push_str("\\\""),
218 '\\' => literal.push_str("\\\\"),
219 '\n' => literal.push_str("\\n"),
220 '\r' => literal.push_str("\\r"),
221 '\t' => literal.push_str("\\t"),
222 '\u{08}' => literal.push_str("\\b"),
223 '\u{0c}' => literal.push_str("\\f"),
224 '\u{2028}' => literal.push_str("\\u2028"),
225 '\u{2029}' => literal.push_str("\\u2029"),
226 ch if ch.is_control() => {
227 use std::fmt::Write as _;
228 write!(literal, "\\u{:04x}", ch as u32).unwrap();
229 }
230 ch => literal.push(ch),
231 }
232 }
233 literal.push('"');
234 literal
235}
236
237pub(crate) const RESERVED_KEYWORDS: &[&str] = &[
238 "await",
239 "break",
240 "case",
241 "catch",
242 "class",
243 "const",
244 "continue",
245 "debugger",
246 "default",
247 "delete",
248 "do",
249 "else",
250 "enum",
251 "eval",
252 "export",
253 "extends",
254 "false",
255 "finally",
256 "for",
257 "function",
258 "if",
259 "implements",
260 "import",
261 "in",
262 "instanceof",
263 "interface",
264 "let",
265 "new",
266 "null",
267 "package",
268 "private",
269 "protected",
270 "public",
271 "return",
272 "static",
273 "super",
274 "switch",
275 "this",
276 "throw",
277 "true",
278 "try",
279 "typeof",
280 "var",
281 "void",
282 "while",
283 "with",
284 "yield",
285];
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290
291 #[test]
295 fn reserved_keywords_are_sorted_and_searchable() {
296 assert!(
297 RESERVED_KEYWORDS.windows(2).all(|w| w[0] < w[1]),
298 "RESERVED_KEYWORDS must be sorted for binary_search"
299 );
300 for keyword in RESERVED_KEYWORDS {
301 assert!(
302 is_js_reserved_word(keyword),
303 "binary_search must find reserved keyword: {keyword}"
304 );
305 assert!(
306 !is_valid_js_identifier(keyword),
307 "reserved keyword must not be a valid JS identifier: {keyword}"
308 );
309 }
310 }
311
312 #[test]
315 fn eval_is_sanitized() {
316 assert!(!is_valid_js_identifier("eval"));
317 assert_ne!(to_js_identifier("eval"), "eval");
318 assert!(is_valid_js_identifier(&to_js_identifier("eval")));
319 }
320
321 #[test]
322 fn quotes_javascript_string_literals() {
323 assert_eq!(
324 js_string_literal("pkg/\"quoted\"\\path\u{2028}"),
325 "\"pkg/\\\"quoted\\\"\\\\path\\u2028\""
326 );
327 }
328}