1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
// MIT License // // Copyright (c) 2018 Guillaume Gomez // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use js::token; /*#[derive(Debug, Clone, PartialEq, Eq)] enum Elem<'a> { Function(Function<'a>), Block(Block<'a>), Variable(Variable<'a>), Condition(token::Condition), Loop(Loop<'a>), Operation(Operation<'a>), } impl<'a> Elem<'a> { fn is_condition(&self) -> bool { match *self { Elem::Condition(_) => true, _ => false, } } } #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum ConditionType { If, ElseIf, Else, Ternary, } #[derive(Clone, PartialEq, Eq, Debug)] struct Block<'a> { elems: Vec<Elem<'a>>, } #[derive(Clone, PartialEq, Eq, Debug)] struct Argument<'a> { name: &'a str, } #[derive(Clone, PartialEq, Eq, Debug)] struct Function<'a> { name: Option<&'a str>, args: Vec<Argument<'a>>, block: Block<'a>, } #[derive(Clone, PartialEq, Eq, Debug)] struct Variable<'a> { name: &'a str, value: Option<&'a str>, } /*struct Condition<'a> { ty_: ConditionType, condition: &'a str, block: Block<'a>, }*/ #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum LoopType { Do, For, While, } #[derive(Clone, PartialEq, Eq, Debug)] struct Loop<'a> { ty_: LoopType, condition: Vec<Elem<'a>>, block: Block<'a>, } #[derive(Clone, PartialEq, Eq, Debug)] struct Operation<'a> { content: &'a str, } fn get_while_condition<'a>(tokens: &[token::Token<'a>], pos: &mut usize) -> Result<Vec<Elem<'a>>, String> { let tmp = *pos; *pos += 1; if let Err(e) = match tokens.get(tmp) { Some(token::Token::Char(token::ReservedChar::OpenParenthese)) => Ok(()), Some(e) => Err(format!("Expected \"(\", found \"{:?}\"", e)), None => Err("Expected \"(\", found nothing...".to_owned()), } { return Err(e); } let mut elems: Vec<Elem<'a>> = Vec::with_capacity(1); while let Some(e) = tokens.get(*pos) { *pos += 1; match e { token::Token::Char(token::ReservedChar::CloseParenthese) => return Ok(elems), token::Token::Condition(e) => { if let Some(cond) = elems.last() { if cond.is_condition() { return Err(format!("\"{:?}\" cannot follow \"{:?}\"", e, cond)); } } } _ => {} } } Err("Expected \")\", found nothing...".to_owned()) } fn get_do<'a>(tokens: &[token::Token<'a>], pos: &mut usize) -> Result<Elem<'a>, String> { let tmp = *pos; *pos += 1; let block = match tokens.get(tmp) { Some(token::Token::Char(token::ReservedChar::OpenCurlyBrace)) => get_block(tokens, pos, true), Some(e) => Err(format!("Expected \"{{\", found \"{:?}\"", e)), None => Err("Expected \"{\", found nothing...".to_owned()), }?; let tmp = *pos; *pos += 1; let condition = match tokens.get(tmp) { Some(token::Token::Keyword(token::Keyword::While)) => get_while_condition(tokens, pos), Some(e) => Err(format!("Expected \"while\", found \"{:?}\"", e)), None => Err("Expected \"while\", found nothing...".to_owned()), }?; let mut loop_ = Loop { ty_: LoopType::Do, condition: condition, block, }; Ok(Elem::Loop(loop_)) } fn get_block<'a>(tokens: &[token::Token<'a>], pos: &mut usize, start_with_paren: bool) -> Result<Block<'a>, String> { let mut block = Block { elems: Vec::with_capacity(2) }; while let Some(e) = tokens.get(*pos) { *pos += 1; block.elems.push(match e { token::Token::Keyword(token::Keyword::Do) => get_do(tokens, pos), token::Token::Char(token::ReservedChar::CloseCurlyBrace) => { if start_with_paren { return Ok(block); } return Err("Unexpected \"}\"".to_owned()); } }?); } if !start_with_paren { Ok(block) } else { Err("Expected \"}\" at the end of the block but didn't find one...".to_owned()) } } fn build_ast<'a>(v: &[token::Token<'a>]) -> Result<Elem<'a>, String> { let mut pos = 0; match get_block(v, &mut pos, false) { Ok(ast) => Ok(Elem::Block(ast)), Err(e) => Err(e), } }*/ /// Minifies a given JS source code. /// /// # Example /// /// ```rust /// extern crate minifier; /// use minifier::js::minify; /// /// fn main() { /// let js = r#" /// function forEach(data, func) { /// for (var i = 0; i < data.length; ++i) { /// func(data[i]); /// } /// }"#.into(); /// let js_minified = minify(js); /// } /// ``` #[inline] pub fn minify(source: &str) -> String { let mut v = token::tokenize(source); token::clean_tokens(&mut v); v.to_string() /*match build_ast(&v) { Ok(x) => {} Err(e) => eprintln!("Failure: {}", e), }*/ } /// Minifies a given JS source code and to replace keywords. /// /// # Example /// /// ```rust /// extern crate minifier; /// use minifier::js::{Keyword, minify_and_replace_keywords}; /// /// fn main() { /// let js = r#" /// function replaceByNull(data, func) { /// for (var i = 0; i < data.length; ++i) { /// if func(data[i]) { /// data[i] = null; /// } /// } /// } /// }"#.into(); /// let js_minified = minify_and_replace_keywords(js, &[(Keyword::Null, "N")]); /// println!("{}", js_minified); /// } /// ``` /// /// The previous code will have all its `null` keywords replaced with `N`. In such cases, /// don't forget to include the definition of `N` in the returned minified javascript: /// /// ```js /// var N = null; /// ``` #[inline] pub fn minify_and_replace_keywords(source: &str, keywords_to_replace: &[(token::Keyword, &str)]) -> String { let mut v = token::tokenize(source); token::clean_tokens(&mut v); for &(keyword, replacement) in keywords_to_replace { for token in v.0.iter_mut() { if match token.get_keyword() { Some(ref k) => *k == keyword, _ => false, } { *token = token::Token::Other(replacement); } } } v.to_string() } #[test] fn simple_quote() { let source = r#"var x = "\\";"#; let expected_result = r#"var x="\\";"#; assert_eq!(minify(source), expected_result); } #[test] fn js_minify_test() { let source = r##" var foo = "something"; var another_var = 2348323; // who doesn't like comments? /* and even longer comments? like on a lot of lines! Fun! */ function far_away(x, y) { var x2 = x + 4; return x * x2 + y; } // this call is useless far_away(another_var, 12); // this call is useless too far_away(another_var, 12); "##; let expected_result = "var foo=\"something\";var another_var=2348323;function far_away(x,y){\ var x2=x+4;return x*x2+y;}far_away(another_var,12);far_away(another_var,\ 12);"; assert_eq!(minify(source), expected_result); } #[test] fn another_js_test() { let source = r#" /*! let's keep this license * * because everyone likes licenses! * * right? */ function forEach(data, func) { for (var i = 0; i < data.length; ++i) { func(data[i]); } } forEach([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], function (x) { console.log(x); }); // I think we're done? console.log('done!'); "#; let expected_result = r#"/*! let's keep this license * * because everyone likes licenses! * * right? */function forEach(data,func){for(var i=0;i<data.length;++i){func(data[i]);}}forEach([0,1,2,3,4,5,6,7,8,9],function(x){console.log(x);});console.log('done!');"#; assert_eq!(minify(source), expected_result); } #[test] fn comment_issue() { let source = r#" search_input.onchange = function(e) { // Do NOT e.preventDefault() here. It will prevent pasting. clearTimeout(searchTimeout); // zero-timeout necessary here because at the time of event handler execution the // pasted content is not in the input field yet. Shouldn’t make any difference for // change, though. setTimeout(search, 0); }; "#; let expected_result = "search_input.onchange=function(e){clearTimeout(searchTimeout);\ setTimeout(search,0);};"; assert_eq!(minify(source), expected_result); } #[test] fn missing_whitespace() { let source = r#" for (var entry in results) { if (results.hasOwnProperty(entry)) { ar.push(results[entry]); } }"#; let expected_result = "for(var entry in results){if(results.hasOwnProperty(entry)){\ ar.push(results[entry]);}}"; assert_eq!(minify(source), expected_result); } #[test] fn weird_regex_issue() { let source = r#" val = val.replace(/\_/g, ""); var valGenerics = extractGenerics(val);"#; let expected_result = "val=val.replace(/\\_/g,\"\");var valGenerics=extractGenerics(val);"; assert_eq!(minify(source), expected_result); } #[test] fn replace_keyword() { let source = r#" var x = ['a', 'b', null, 'd', {'x': null, 'e': null, 'z': 'w'}]; var n = null; "#; let expected_result = "var x=['a','b',N,'d',{'x':N,'e':N,'z':'w'}];var n=N;"; assert_eq!(minify_and_replace_keywords(source, &[(token::Keyword::Null, "N")]), expected_result); } // TODO: requires AST to fix this issue! /*#[test] fn no_semi_colon() { let source = r#" console.log(1) console.log(2) var x = 12; "#; let expected_result = r#"console.log(1);console.log(2);var x=12;"#; assert_eq!(minify(source), expected_result); }*/ // TODO: requires AST to fix this issue! /*#[test] fn correct_replace_for_backline() { let source = r#" function foo() { return 12; } "#; let expected_result = r#"function foo(){return;12;}"#; assert_eq!(minify(source), expected_result); }*/