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 is_valid_js_identifier(s: &str) -> bool {
111 let mut chars = s.chars();
112 if let Some(char) = chars.next() {
113 if !is_valid_js_identifier_start(char) {
114 return false;
115 }
116 } else {
117 return false;
118 }
119 for char in chars {
120 if !is_valid_js_identifier_char(char) {
121 return false;
122 }
123 }
124 !is_js_reserved_word(s)
125}
126
127pub fn is_js_reserved_word(s: &str) -> bool {
128 RESERVED_KEYWORDS.binary_search(&s).is_ok()
129}
130
131fn is_valid_js_identifier_start(code: char) -> bool {
134 match code {
135 'A'..='Z' | 'a'..='z' | '$' | '_' => true,
136 _ => false,
138 }
139}
140
141fn is_valid_js_identifier_char(code: char) -> bool {
144 match code {
145 '0'..='9' | 'A'..='Z' | 'a'..='z' | '$' | '_' => true,
146 _ => false,
148 }
149}
150
151pub fn maybe_quote_id(name: &str) -> String {
157 if is_valid_js_identifier(name) {
158 name.to_string()
159 } else {
160 js_string_literal(name)
161 }
162}
163
164pub fn maybe_quote_member(name: &str) -> String {
167 if name == "*" {
168 "".to_string()
169 } else if is_valid_js_identifier(name) {
170 format!(".{name}")
171 } else {
172 format!("[{}]", js_string_literal(name))
173 }
174}
175
176pub fn js_string_literal(value: &str) -> String {
178 let mut literal = String::with_capacity(value.len() + 2);
179 literal.push('"');
180 for ch in value.chars() {
181 match ch {
182 '"' => literal.push_str("\\\""),
183 '\\' => literal.push_str("\\\\"),
184 '\n' => literal.push_str("\\n"),
185 '\r' => literal.push_str("\\r"),
186 '\t' => literal.push_str("\\t"),
187 '\u{08}' => literal.push_str("\\b"),
188 '\u{0c}' => literal.push_str("\\f"),
189 '\u{2028}' => literal.push_str("\\u2028"),
190 '\u{2029}' => literal.push_str("\\u2029"),
191 ch if ch.is_control() => {
192 use std::fmt::Write as _;
193 write!(literal, "\\u{:04x}", ch as u32).unwrap();
194 }
195 ch => literal.push(ch),
196 }
197 }
198 literal.push('"');
199 literal
200}
201
202pub(crate) const RESERVED_KEYWORDS: &[&str] = &[
203 "await",
204 "break",
205 "case",
206 "catch",
207 "class",
208 "const",
209 "continue",
210 "debugger",
211 "default",
212 "delete",
213 "do",
214 "else",
215 "enum",
216 "eval",
217 "export",
218 "extends",
219 "false",
220 "finally",
221 "for",
222 "function",
223 "if",
224 "implements",
225 "import",
226 "in",
227 "instanceof",
228 "interface",
229 "let",
230 "new",
231 "null",
232 "package",
233 "private",
234 "protected",
235 "public",
236 "return",
237 "static",
238 "super",
239 "switch",
240 "this",
241 "throw",
242 "true",
243 "try",
244 "typeof",
245 "var",
246 "void",
247 "while",
248 "with",
249 "yield",
250];
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[test]
260 fn reserved_keywords_are_sorted_and_searchable() {
261 assert!(
262 RESERVED_KEYWORDS.windows(2).all(|w| w[0] < w[1]),
263 "RESERVED_KEYWORDS must be sorted for binary_search"
264 );
265 for keyword in RESERVED_KEYWORDS {
266 assert!(
267 is_js_reserved_word(keyword),
268 "binary_search must find reserved keyword: {keyword}"
269 );
270 assert!(
271 !is_valid_js_identifier(keyword),
272 "reserved keyword must not be a valid JS identifier: {keyword}"
273 );
274 }
275 }
276
277 #[test]
280 fn eval_is_sanitized() {
281 assert!(!is_valid_js_identifier("eval"));
282 assert_ne!(to_js_identifier("eval"), "eval");
283 assert!(is_valid_js_identifier(&to_js_identifier("eval")));
284 }
285
286 #[test]
287 fn quotes_javascript_string_literals() {
288 assert_eq!(
289 js_string_literal("pkg/\"quoted\"\\path\u{2028}"),
290 "\"pkg/\\\"quoted\\\"\\\\path\\u2028\""
291 );
292 }
293}