pico_minify
Functions to minify a cart - that is specifically removing or replacing tokens (doesn't include renaming / etc)
1"""Functions to minify a cart - that is specifically removing or replacing tokens (doesn't include renaming / etc)""" 2 3from utils import * 4from pico_defs import fixnum_is_negative, float_is_negative, Language 5from pico_srcdefs import Focus 6from pico_tokenize import Token, TokenType, StopTraverse, k_skip_children 7from pico_parse import Node, NodeType, VarKind 8from pico_parse import k_unary_ops_prec, get_precedence, is_right_assoc, can_replace_with_unary 9from pico_parse import is_vararg_expr, is_short_block_stmt, is_root_global_or_builtin_local 10from pico_output import format_luanum, format_fixnum, format_string_literal 11 12def minify_string_literal(ctxt, token, focus, value=None): 13 if value is None: 14 value = token.parsed_value 15 16 if focus.chars: 17 return format_string_literal(value, use_complex_long=ctxt.version >= 40) 18 else: 19 # haven't found a good balanced heuristic for 'long' yet 20 return format_string_literal(value, long=token.value.startswith('[')) 21 22def get_node_bodies(node): 23 if node.type in (NodeType.if_, NodeType.elseif): 24 yield node.then 25 if node.else_: 26 yield from get_node_bodies(node.else_) 27 else: 28 yield node.body 29 30def analyze_code_for_minify(root, focus, ctxt, safe_builtins): 31 shorthands_can_nest = ctxt.version >= 42 32 shorts = CounterDictionary() 33 longs = CounterDictionary() 34 allowed_shorts = set() 35 36 def allow_shorthand_nesting(parent, body, child): 37 # at this point, both parent and child are either shorthands or may become shorthands 38 if shorthands_can_nest: 39 # the then of a short if-else cannot contain anything except nested if-elses 40 if ((parent.type == NodeType.if_ and parent.else_ and body is parent.then) and 41 not (child.type == NodeType.if_ and child.else_)): 42 return False 43 44 # note - pico8 now supports shorthands terminated by 'end', but we don't generate those yet 45 if body.next_token() is not child.next_token(): 46 return False 47 48 return True 49 else: 50 # in theory, could've supported nesting print even here, but never did 51 return False 52 53 def allow_parent_shorthands(node): 54 allowed = True 55 prev_parent = node 56 def check_parent_shorthand(parent): 57 nonlocal prev_parent, allowed 58 if (parent.short or parent in allowed_shorts) and not allow_shorthand_nesting(parent, prev_parent, node): 59 allowed = False 60 prev_parent = parent 61 62 node.traverse_parents(check_parent_shorthand) 63 return allowed 64 65 def allow_child_shorthands(node, body): 66 allowed = True 67 def check_child_shorthand(child): 68 nonlocal allowed 69 if (child.short or child in allowed_shorts) and not allow_shorthand_nesting(node, body, child): 70 allowed = False 71 72 body.traverse_nodes(post=check_child_shorthand) 73 return allowed 74 75 def analyze_node_post(node): 76 if node.type in (NodeType.if_, NodeType.while_): 77 to_short = node.short 78 79 weight = 1 80 if node.type == NodeType.if_: 81 else_ = node.else_ 82 while else_ and else_.type == NodeType.elseif: 83 weight += 1 84 else_ = else_.else_ 85 has_elseif = weight > 1 86 87 # can the node be converted to shorthand? 88 if not to_short and not has_elseif: 89 has_empties, starts_with_do = False, False 90 allow_shorthand = allow_parent_shorthands(node) 91 92 # now check the children 93 if not allow_child_shorthands(node, node.cond): 94 allow_shorthand = False 95 96 for i, body in enumerate(get_node_bodies(node)): 97 if not allow_child_shorthands(node, body): 98 allow_shorthand = False 99 100 if not body.children: 101 has_empties = True 102 103 if i == 0: 104 # a shorthand cannot begin with a do block. (would be a longhand) 105 starts_with_do = body.first_token().value == "do" 106 107 # empty bodies require extra ';'s to shorten, which worsens compression 108 to_short = allow_shorthand and not (has_empties and not focus.chars) and not starts_with_do 109 if to_short: 110 allowed_shorts.add(node) 111 112 if to_short: 113 shorts[node.type] += weight 114 else: 115 longs[node.type] += weight 116 117 # print shorthands save tokens, so we don't currently undo them 118 # note: could support calls to something other than the print builtin, but not sure it's safe... 119 elif (node.type == NodeType.call and node.func.type == NodeType.var and is_root_global_or_builtin_local(node.func) and 120 node.func.name == "print" and node.func.var.name == "print" and # both before and after any rename 121 not node.func.var.reassigned and (not root.has_env or not safe_builtins)): 122 123 # note: could support expressions, but only in non-vararg contexts, which mostly defeats the purpose 124 if not node.short and node.parent.type == NodeType.block and allow_parent_shorthands(node) and allow_child_shorthands(node, node): 125 allowed_shorts.add(node) 126 127 root.traverse_nodes(post=analyze_node_post) 128 129 new_shorts = {} 130 for type in (NodeType.if_, NodeType.while_): 131 # if everything can be made short, that's always best. 132 # else, consistency is better for compression while more shorts are better for chars 133 if focus.chars or not longs[type] or (not focus.compressed and longs[type] * 1.4 <= shorts[type]): 134 new_shorts[type] = True 135 elif focus.compressed: 136 new_shorts[type] = False 137 else: 138 new_shorts[type] = None # leave alone 139 140 if focus.compressed and not (new_shorts[NodeType.if_] and new_shorts[NodeType.while_]): 141 new_shorts[NodeType.call] = None 142 else: 143 new_shorts[NodeType.call] = True 144 145 return Dynamic(new_shorts=new_shorts, allowed_shorts=allowed_shorts) 146 147def on_enable_shorthand(node): 148 # remove line breaks originally in the source 149 vline = node.first_token().vline 150 def fix_vlines(token): 151 token.vline = vline 152 for comment in token.children: 153 comment.vline = vline 154 node.traverse_tokens(fix_vlines) 155 156def minify_change_block_shorthand(node, new_short): 157 if new_short: 158 node.short = True 159 node.remove_token(2, ("then", "do")) 160 if node.type == NodeType.if_ and node.else_: 161 node.else_.short = True 162 node.else_.remove_token(-1, "end") 163 else: 164 node.remove_token(-1, "end") 165 166 # we can assume node.cond is not wrapped in parens, since we're in a post-visit 167 # wrap it in parens ourselves (TODO: eww...) 168 node.cond.replace_with(Node(NodeType.group, [], child=node.cond.move())) 169 node.cond.children.append(node.cond.child) 170 node.cond.insert_token(0, TokenType.punct, "(", near_next=True) 171 node.cond.append_token(TokenType.punct, ")") 172 173 # fixup empty bodies 174 for body in get_node_bodies(node): 175 if not body.children: 176 body.append_token(TokenType.punct, ";") 177 178 on_enable_shorthand(node) 179 180 else: 181 node.short = False 182 node.insert_token(2, TokenType.keyword, "then" if node.type == NodeType.if_ else "do") 183 if node.type == NodeType.if_ and node.else_: 184 node.else_.short = False 185 node.else_.append_token(TokenType.keyword, "end", near_next=True) 186 else: 187 node.append_token(TokenType.keyword, "end", near_next=True) 188 189def minify_change_print_shorthand(node, new_short): 190 assert new_short 191 node.short = True 192 node.func.var.implicit = True 193 node.add_extra_child(node.func) 194 195 end_paren = node.children[-1] 196 if end_paren.is_token and end_paren.value == ")": # else, this is a paren-less call 197 node.remove_token(1, "(") 198 node.remove_token(-1, ")") 199 200 node.insert_token(1, TokenType.punct, "?", near_next=True) 201 node.remove_child(0) 202 node.func = node.children[0] 203 204 on_enable_shorthand(node) 205 206def node_contains_vars(root, vars): 207 def visitor(node): 208 if node.type == NodeType.var and node.var in vars: 209 raise StopTraverse() 210 211 try: 212 root.traverse_nodes(visitor, extra=True) 213 return False 214 except StopTraverse: 215 return True 216 217def expr_is_trivial(root, ctxt, safe_only, allow_member=True, allow_index=True, allow_call=True, has_env=True): 218 def visitor(expr): 219 # nodes that cannot call user-defined code in any case 220 if expr.type in (NodeType.const, NodeType.varargs, NodeType.group, 221 NodeType.table, NodeType.table_member, NodeType.table_index): # (since new tables have no metatable) 222 pass 223 elif expr.type == NodeType.var and (expr.kind != VarKind.global_ or not has_env): 224 pass 225 elif expr.type == NodeType.unary_op and expr.op == "not": 226 pass 227 elif expr.type == NodeType.binary_op and expr.op in ("and", "or"): 228 pass 229 elif expr.type == NodeType.function: 230 assert not expr.target # we only traverse expressions! 231 return k_skip_children 232 # nodes that may call user-defined code 233 elif expr.type == NodeType.call: 234 func = expr.func 235 if (safe_only or not allow_call or 236 not (func.type == NodeType.var and is_root_global_or_builtin_local(func) and not func.var.reassigned and func.name not in ctxt.builtins_with_callbacks)): 237 raise StopTraverse() 238 elif expr.type == NodeType.member and not allow_member: 239 raise StopTraverse() 240 elif expr.type == NodeType.index and not allow_index: 241 raise StopTraverse() 242 # nodes that may call user-defined code via metatables (E.g. member access, operators) 243 elif safe_only: 244 raise StopTraverse() 245 246 try: 247 root.traverse_nodes(visitor) 248 return True 249 except StopTraverse: 250 return False 251 252def minify_merge_assignments(prev, next, ctxt, safe_only, has_env): 253 if len(prev.targets) < len(prev.sources): 254 return 255 256 if (len(prev.targets) > len(prev.sources) and 257 ((prev.sources and is_vararg_expr(prev.sources[-1])) or (next.sources and is_vararg_expr(next.sources[-1])) or len(next.targets) < len(next.sources))): 258 return 259 260 merge_prev = getattr(next.first_token(), "merge_prev", None) 261 if merge_prev is False: 262 return 263 264 # check if prev's targets are used in next's sources or targets 265 266 require_trivial = False # True when prev.targets may be accessed indirectly from functions that may be called by next.soources 267 allow_index = allow_member = True 268 target_vars = [] 269 for target in prev.targets: 270 if target.type == NodeType.var: 271 target_vars.append(target.var) 272 # is it possible for 'next' to access 'target' without refering to it directly? (via function call) 273 if target.kind == VarKind.global_ or (prev.type == NodeType.assign and target.var.captured): 274 require_trivial = True 275 elif target.type == NodeType.member: 276 target_vars.append(target.key.var) 277 require_trivial = True 278 allow_index = False # TODO: could rely on rename's preserve logic 279 elif target.type == NodeType.index: 280 require_trivial = True 281 allow_member = False # TODO: could rely on rename's preserve logic 282 allow_index = False 283 else: # just in case... 284 return 285 286 for node in next.sources: 287 if target_vars and node_contains_vars(node, target_vars): 288 return 289 if require_trivial and not expr_is_trivial(node, ctxt, safe_only, allow_member, allow_index, has_env=has_env): 290 return 291 292 for node in next.targets: 293 if target_vars and node_contains_vars(node, target_vars): 294 return 295 if require_trivial and not expr_is_trivial(node, ctxt, safe_only, allow_member, allow_index, allow_call=False, has_env=has_env): 296 return 297 298 # when reordering local declarations, ensure we don't change which local wins out among identically-named locals 299 # (this relies on rename being done already!) 300 301 if len(prev.targets) > len(prev.sources) and prev.type == NodeType.local: 302 for target in prev.targets[len(prev.sources):]: 303 for next_target in next.targets: 304 if target.name == next_target.name: 305 return 306 307 # do the merge: (TODO: eww...) 308 309 def insert_array_items(dst_node, dst_arr, dst_arr_i, src_arr, src_arr_i, count): 310 count = default(count, len(src_arr) - src_arr_i) 311 if not count: 312 return 313 314 need_end_comma = False 315 if dst_arr_i < len(dst_arr): 316 dst_i = dst_node.children.index(dst_arr[dst_arr_i]) 317 need_end_comma = True 318 elif len(dst_arr): 319 dst_i = dst_node.children.index(dst_arr[dst_arr_i - 1]) + 1 320 dst_node.insert_token(dst_i, TokenType.punct, ",") 321 dst_i += 1 322 else: 323 assert dst_arr is dst_node.sources 324 dst_node.append_token(TokenType.punct, "=") 325 dst_i = len(dst_node.children) 326 327 for i in range(count): 328 src_elem = src_arr[src_arr_i + i] 329 dst_arr.insert(dst_arr_i + i, src_elem) 330 331 dst_node.insert_existing(dst_i, src_elem) 332 dst_i += 1 333 334 if i < count - 1 or need_end_comma: 335 dst_node.insert_token(dst_i, TokenType.punct, ",") 336 dst_i += 1 337 338 insert_array_items(prev, prev.targets, len(prev.sources), next.targets, 0, None) 339 insert_array_items(prev, prev.sources, len(prev.sources), next.sources, 0, None) 340 341 next.erase() 342 343def value_is_negative(ctxt, value): 344 if ctxt.lang == Language.pico8: 345 return fixnum_is_negative(value) 346 elif isinstance(value, int): 347 return value < 0 348 else: 349 return float_is_negative(value) 350 351def minify_code(ctxt, root, minify_opts): 352 """minify `root` in-place (replacing/removing/rearranging tokens - doesn't include renaming/etc)""" 353 354 safe_reorder = minify_opts.get("safe-reorder", False) 355 safe_builtins = minify_opts.get("safe-builtins", False) 356 minify_tokens = minify_opts.get("tokens", True) 357 minify_reorder = minify_opts.get("reorder", True) 358 focus = Focus(minify_opts.get("focus")) 359 360 if not focus.tokens: 361 safe_reorder = True # nothing gained with False here, so set it to True just in case. 362 363 analysis = analyze_code_for_minify(root, focus, ctxt, safe_builtins) 364 365 def fixup_nodes_pre(node): 366 if minify_tokens: 367 # remove shorthands 368 369 if node.type in (NodeType.if_, NodeType.while_) and node.short and (analysis.new_shorts[node.type] == False): 370 minify_change_block_shorthand(node, False) 371 372 # remove unneeded groups 373 374 while node.type == NodeType.group: 375 inner, outer = node.child, node.parent 376 inner_prec, outer_prec = get_precedence(inner), get_precedence(outer) 377 remove = False 378 379 if e(outer_prec): 380 if e(inner_prec): 381 remove = inner_prec > outer_prec or (inner_prec == outer_prec and 382 (outer_prec == k_unary_ops_prec or is_right_assoc(outer) == (outer.right == node))) 383 elif inner.type in (NodeType.group, NodeType.var, NodeType.index, NodeType.member, NodeType.call, NodeType.varargs): 384 remove = True 385 elif inner.type == NodeType.const: 386 remove = (focus.tokens or can_replace_with_unary(node) or 387 not (inner.token.type == TokenType.number and value_is_negative(ctxt, inner.token.parsed_value))) 388 389 elif ((outer.type in (NodeType.index, NodeType.member) and node == outer.child) or 390 (outer.type == NodeType.call and node == outer.func)): 391 remove = inner.type in (NodeType.group, NodeType.var, NodeType.index, NodeType.member, NodeType.call) 392 393 elif outer.type in (NodeType.group, NodeType.table_member, NodeType.table_index, NodeType.op_assign): 394 remove = True 395 elif outer.type == NodeType.index: 396 remove = node == outer.key 397 elif outer.type == NodeType.call: 398 remove = node in outer.args[:-1] or (outer.args and node == outer.args[-1] and not is_vararg_expr(inner)) 399 elif outer.type in (NodeType.assign, NodeType.local, NodeType.for_in): 400 remove = (node in outer.sources[:-1] or (outer.sources and node == outer.sources[-1] and 401 (not is_vararg_expr(inner) or (3 if outer.type == NodeType.for_in else len(outer.targets)) <= len(outer.sources)))) 402 elif outer.type in (NodeType.return_, NodeType.table): 403 remove = (node in outer.items[:-1] or (outer.items and node == outer.items[-1] and not is_vararg_expr(inner))) 404 elif outer.type in (NodeType.if_, NodeType.elseif, NodeType.while_, NodeType.until, NodeType.for_) and not outer.short: 405 remove = True 406 407 if remove: 408 node.replace_with(node.child.move()) 409 # node may now be another group, so loop 410 else: 411 break 412 413 def fixup_nodes_post(node): 414 if minify_tokens: 415 # create shorthands 416 417 if (node.type in (NodeType.if_, NodeType.while_) and not node.short and 418 analysis.new_shorts[node.type] and node in analysis.allowed_shorts): 419 minify_change_block_shorthand(node, True) 420 421 if (node.type == NodeType.call and not node.short and 422 analysis.new_shorts[node.type] and node in analysis.allowed_shorts): 423 minify_change_print_shorthand(node, True) 424 425 if minify_reorder: 426 # merge assignments 427 428 if node.type == NodeType.local or (focus.tokens and node.type == NodeType.assign): 429 prev = node.prev_sibling() 430 while prev and prev.type == None: # skip erased 431 prev = prev.prev_sibling() 432 if prev and prev.type == node.type: 433 minify_merge_assignments(prev, node, ctxt, safe_reorder, root.has_env) 434 435 def fixup_tokens(token): 436 437 # minify sublangs 438 439 sublang = getattr(token, "sublang", None) 440 if sublang and sublang.minify: 441 token.modify(minify_string_literal(ctxt, token, focus, value=sublang.minify())) 442 443 if minify_tokens: 444 445 # remove unneeded tokens 446 447 if token.value == ";" and token.parent.type == NodeType.block and token.next_token().value != "(": 448 gparent = token.parent.parent 449 if not (gparent and is_short_block_stmt(gparent) and not token.parent.stmts): 450 token.erase() 451 return 452 453 if token.value in (",", ";") and token.parent.type == NodeType.table and token.next_sibling().value == "}": 454 token.erase() 455 return 456 457 if token.value == "(" and token.parent.type == NodeType.call and len(token.parent.args) == 1: 458 arg = token.parent.args[0] 459 if arg.type == NodeType.table or (arg.type == NodeType.const and arg.token.type == TokenType.string): 460 token.erase("(") 461 token.parent.erase_token(-1, ")") 462 return 463 464 # replace tokens for higher consistency 465 466 if token.value == ";" and token.parent.type == NodeType.table: 467 token.modify(",") 468 469 if token.value == "!=": 470 token.modify("~=") 471 472 if token.value == "^^" and ctxt.version >= 37: 473 token.modify("~") 474 475 if token.value == "then" and ctxt.lang == Language.pico8 and ctxt.version >= 42: 476 token.modify("do") # I HATE THIS :( 477 478 if token.value == "//" and ctxt.lang == Language.picotron: 479 token.modify("\\") 480 481 if token.value == "//=" and ctxt.lang == Language.picotron: 482 token.modify("\\=") 483 484 if token.type == TokenType.string: 485 token.modify(minify_string_literal(ctxt, token, focus)) 486 487 if token.type == TokenType.number: 488 allow_unary = can_replace_with_unary(token.parent) 489 format_num = format_luanum if ctxt.lang == Language.picotron else format_fixnum 490 token.modify(format_num(token.parsed_value, sign=None if allow_unary else '')) 491 492 if token.type == TokenType.number: 493 if token.value.startswith("-") or token.value.startswith("~"): # either due to format_fixnum above, or due to ConstToken.value 494 # insert synthetic unary token, so that output_tokens's tokenize and root.get_tokens() won't get confused 495 token.parent.insert_token(0, TokenType.punct, token.value[0], near_next=True) 496 token.modify(token.value[1:]) 497 elif token.value.startswith("("): # special case where a unary was forced on us 498 # insert synthetic unary tokens, as needed 499 token.parent.insert_token(0, TokenType.punct, token.value[0], near_next=True) 500 token.parent.insert_token(1, TokenType.punct, token.value[1], near_next=True) 501 token.parent.append_token(TokenType.punct, token.value[-1]) 502 token.modify(token.value[2:-1]) 503 504 root.traverse_nodes(fixup_nodes_pre, fixup_nodes_post, tokens=fixup_tokens)
def
minify_string_literal(ctxt, token, focus, value=None):
13def minify_string_literal(ctxt, token, focus, value=None): 14 if value is None: 15 value = token.parsed_value 16 17 if focus.chars: 18 return format_string_literal(value, use_complex_long=ctxt.version >= 40) 19 else: 20 # haven't found a good balanced heuristic for 'long' yet 21 return format_string_literal(value, long=token.value.startswith('['))
def
get_node_bodies(node):
def
analyze_code_for_minify(root, focus, ctxt, safe_builtins):
31def analyze_code_for_minify(root, focus, ctxt, safe_builtins): 32 shorthands_can_nest = ctxt.version >= 42 33 shorts = CounterDictionary() 34 longs = CounterDictionary() 35 allowed_shorts = set() 36 37 def allow_shorthand_nesting(parent, body, child): 38 # at this point, both parent and child are either shorthands or may become shorthands 39 if shorthands_can_nest: 40 # the then of a short if-else cannot contain anything except nested if-elses 41 if ((parent.type == NodeType.if_ and parent.else_ and body is parent.then) and 42 not (child.type == NodeType.if_ and child.else_)): 43 return False 44 45 # note - pico8 now supports shorthands terminated by 'end', but we don't generate those yet 46 if body.next_token() is not child.next_token(): 47 return False 48 49 return True 50 else: 51 # in theory, could've supported nesting print even here, but never did 52 return False 53 54 def allow_parent_shorthands(node): 55 allowed = True 56 prev_parent = node 57 def check_parent_shorthand(parent): 58 nonlocal prev_parent, allowed 59 if (parent.short or parent in allowed_shorts) and not allow_shorthand_nesting(parent, prev_parent, node): 60 allowed = False 61 prev_parent = parent 62 63 node.traverse_parents(check_parent_shorthand) 64 return allowed 65 66 def allow_child_shorthands(node, body): 67 allowed = True 68 def check_child_shorthand(child): 69 nonlocal allowed 70 if (child.short or child in allowed_shorts) and not allow_shorthand_nesting(node, body, child): 71 allowed = False 72 73 body.traverse_nodes(post=check_child_shorthand) 74 return allowed 75 76 def analyze_node_post(node): 77 if node.type in (NodeType.if_, NodeType.while_): 78 to_short = node.short 79 80 weight = 1 81 if node.type == NodeType.if_: 82 else_ = node.else_ 83 while else_ and else_.type == NodeType.elseif: 84 weight += 1 85 else_ = else_.else_ 86 has_elseif = weight > 1 87 88 # can the node be converted to shorthand? 89 if not to_short and not has_elseif: 90 has_empties, starts_with_do = False, False 91 allow_shorthand = allow_parent_shorthands(node) 92 93 # now check the children 94 if not allow_child_shorthands(node, node.cond): 95 allow_shorthand = False 96 97 for i, body in enumerate(get_node_bodies(node)): 98 if not allow_child_shorthands(node, body): 99 allow_shorthand = False 100 101 if not body.children: 102 has_empties = True 103 104 if i == 0: 105 # a shorthand cannot begin with a do block. (would be a longhand) 106 starts_with_do = body.first_token().value == "do" 107 108 # empty bodies require extra ';'s to shorten, which worsens compression 109 to_short = allow_shorthand and not (has_empties and not focus.chars) and not starts_with_do 110 if to_short: 111 allowed_shorts.add(node) 112 113 if to_short: 114 shorts[node.type] += weight 115 else: 116 longs[node.type] += weight 117 118 # print shorthands save tokens, so we don't currently undo them 119 # note: could support calls to something other than the print builtin, but not sure it's safe... 120 elif (node.type == NodeType.call and node.func.type == NodeType.var and is_root_global_or_builtin_local(node.func) and 121 node.func.name == "print" and node.func.var.name == "print" and # both before and after any rename 122 not node.func.var.reassigned and (not root.has_env or not safe_builtins)): 123 124 # note: could support expressions, but only in non-vararg contexts, which mostly defeats the purpose 125 if not node.short and node.parent.type == NodeType.block and allow_parent_shorthands(node) and allow_child_shorthands(node, node): 126 allowed_shorts.add(node) 127 128 root.traverse_nodes(post=analyze_node_post) 129 130 new_shorts = {} 131 for type in (NodeType.if_, NodeType.while_): 132 # if everything can be made short, that's always best. 133 # else, consistency is better for compression while more shorts are better for chars 134 if focus.chars or not longs[type] or (not focus.compressed and longs[type] * 1.4 <= shorts[type]): 135 new_shorts[type] = True 136 elif focus.compressed: 137 new_shorts[type] = False 138 else: 139 new_shorts[type] = None # leave alone 140 141 if focus.compressed and not (new_shorts[NodeType.if_] and new_shorts[NodeType.while_]): 142 new_shorts[NodeType.call] = None 143 else: 144 new_shorts[NodeType.call] = True 145 146 return Dynamic(new_shorts=new_shorts, allowed_shorts=allowed_shorts)
def
on_enable_shorthand(node):
def
minify_change_block_shorthand(node, new_short):
157def minify_change_block_shorthand(node, new_short): 158 if new_short: 159 node.short = True 160 node.remove_token(2, ("then", "do")) 161 if node.type == NodeType.if_ and node.else_: 162 node.else_.short = True 163 node.else_.remove_token(-1, "end") 164 else: 165 node.remove_token(-1, "end") 166 167 # we can assume node.cond is not wrapped in parens, since we're in a post-visit 168 # wrap it in parens ourselves (TODO: eww...) 169 node.cond.replace_with(Node(NodeType.group, [], child=node.cond.move())) 170 node.cond.children.append(node.cond.child) 171 node.cond.insert_token(0, TokenType.punct, "(", near_next=True) 172 node.cond.append_token(TokenType.punct, ")") 173 174 # fixup empty bodies 175 for body in get_node_bodies(node): 176 if not body.children: 177 body.append_token(TokenType.punct, ";") 178 179 on_enable_shorthand(node) 180 181 else: 182 node.short = False 183 node.insert_token(2, TokenType.keyword, "then" if node.type == NodeType.if_ else "do") 184 if node.type == NodeType.if_ and node.else_: 185 node.else_.short = False 186 node.else_.append_token(TokenType.keyword, "end", near_next=True) 187 else: 188 node.append_token(TokenType.keyword, "end", near_next=True)
def
minify_change_print_shorthand(node, new_short):
190def minify_change_print_shorthand(node, new_short): 191 assert new_short 192 node.short = True 193 node.func.var.implicit = True 194 node.add_extra_child(node.func) 195 196 end_paren = node.children[-1] 197 if end_paren.is_token and end_paren.value == ")": # else, this is a paren-less call 198 node.remove_token(1, "(") 199 node.remove_token(-1, ")") 200 201 node.insert_token(1, TokenType.punct, "?", near_next=True) 202 node.remove_child(0) 203 node.func = node.children[0] 204 205 on_enable_shorthand(node)
def
node_contains_vars(root, vars):
def
expr_is_trivial( root, ctxt, safe_only, allow_member=True, allow_index=True, allow_call=True, has_env=True):
218def expr_is_trivial(root, ctxt, safe_only, allow_member=True, allow_index=True, allow_call=True, has_env=True): 219 def visitor(expr): 220 # nodes that cannot call user-defined code in any case 221 if expr.type in (NodeType.const, NodeType.varargs, NodeType.group, 222 NodeType.table, NodeType.table_member, NodeType.table_index): # (since new tables have no metatable) 223 pass 224 elif expr.type == NodeType.var and (expr.kind != VarKind.global_ or not has_env): 225 pass 226 elif expr.type == NodeType.unary_op and expr.op == "not": 227 pass 228 elif expr.type == NodeType.binary_op and expr.op in ("and", "or"): 229 pass 230 elif expr.type == NodeType.function: 231 assert not expr.target # we only traverse expressions! 232 return k_skip_children 233 # nodes that may call user-defined code 234 elif expr.type == NodeType.call: 235 func = expr.func 236 if (safe_only or not allow_call or 237 not (func.type == NodeType.var and is_root_global_or_builtin_local(func) and not func.var.reassigned and func.name not in ctxt.builtins_with_callbacks)): 238 raise StopTraverse() 239 elif expr.type == NodeType.member and not allow_member: 240 raise StopTraverse() 241 elif expr.type == NodeType.index and not allow_index: 242 raise StopTraverse() 243 # nodes that may call user-defined code via metatables (E.g. member access, operators) 244 elif safe_only: 245 raise StopTraverse() 246 247 try: 248 root.traverse_nodes(visitor) 249 return True 250 except StopTraverse: 251 return False
def
minify_merge_assignments(prev, next, ctxt, safe_only, has_env):
253def minify_merge_assignments(prev, next, ctxt, safe_only, has_env): 254 if len(prev.targets) < len(prev.sources): 255 return 256 257 if (len(prev.targets) > len(prev.sources) and 258 ((prev.sources and is_vararg_expr(prev.sources[-1])) or (next.sources and is_vararg_expr(next.sources[-1])) or len(next.targets) < len(next.sources))): 259 return 260 261 merge_prev = getattr(next.first_token(), "merge_prev", None) 262 if merge_prev is False: 263 return 264 265 # check if prev's targets are used in next's sources or targets 266 267 require_trivial = False # True when prev.targets may be accessed indirectly from functions that may be called by next.soources 268 allow_index = allow_member = True 269 target_vars = [] 270 for target in prev.targets: 271 if target.type == NodeType.var: 272 target_vars.append(target.var) 273 # is it possible for 'next' to access 'target' without refering to it directly? (via function call) 274 if target.kind == VarKind.global_ or (prev.type == NodeType.assign and target.var.captured): 275 require_trivial = True 276 elif target.type == NodeType.member: 277 target_vars.append(target.key.var) 278 require_trivial = True 279 allow_index = False # TODO: could rely on rename's preserve logic 280 elif target.type == NodeType.index: 281 require_trivial = True 282 allow_member = False # TODO: could rely on rename's preserve logic 283 allow_index = False 284 else: # just in case... 285 return 286 287 for node in next.sources: 288 if target_vars and node_contains_vars(node, target_vars): 289 return 290 if require_trivial and not expr_is_trivial(node, ctxt, safe_only, allow_member, allow_index, has_env=has_env): 291 return 292 293 for node in next.targets: 294 if target_vars and node_contains_vars(node, target_vars): 295 return 296 if require_trivial and not expr_is_trivial(node, ctxt, safe_only, allow_member, allow_index, allow_call=False, has_env=has_env): 297 return 298 299 # when reordering local declarations, ensure we don't change which local wins out among identically-named locals 300 # (this relies on rename being done already!) 301 302 if len(prev.targets) > len(prev.sources) and prev.type == NodeType.local: 303 for target in prev.targets[len(prev.sources):]: 304 for next_target in next.targets: 305 if target.name == next_target.name: 306 return 307 308 # do the merge: (TODO: eww...) 309 310 def insert_array_items(dst_node, dst_arr, dst_arr_i, src_arr, src_arr_i, count): 311 count = default(count, len(src_arr) - src_arr_i) 312 if not count: 313 return 314 315 need_end_comma = False 316 if dst_arr_i < len(dst_arr): 317 dst_i = dst_node.children.index(dst_arr[dst_arr_i]) 318 need_end_comma = True 319 elif len(dst_arr): 320 dst_i = dst_node.children.index(dst_arr[dst_arr_i - 1]) + 1 321 dst_node.insert_token(dst_i, TokenType.punct, ",") 322 dst_i += 1 323 else: 324 assert dst_arr is dst_node.sources 325 dst_node.append_token(TokenType.punct, "=") 326 dst_i = len(dst_node.children) 327 328 for i in range(count): 329 src_elem = src_arr[src_arr_i + i] 330 dst_arr.insert(dst_arr_i + i, src_elem) 331 332 dst_node.insert_existing(dst_i, src_elem) 333 dst_i += 1 334 335 if i < count - 1 or need_end_comma: 336 dst_node.insert_token(dst_i, TokenType.punct, ",") 337 dst_i += 1 338 339 insert_array_items(prev, prev.targets, len(prev.sources), next.targets, 0, None) 340 insert_array_items(prev, prev.sources, len(prev.sources), next.sources, 0, None) 341 342 next.erase()
def
value_is_negative(ctxt, value):
def
minify_code(ctxt, root, minify_opts):
352def minify_code(ctxt, root, minify_opts): 353 """minify `root` in-place (replacing/removing/rearranging tokens - doesn't include renaming/etc)""" 354 355 safe_reorder = minify_opts.get("safe-reorder", False) 356 safe_builtins = minify_opts.get("safe-builtins", False) 357 minify_tokens = minify_opts.get("tokens", True) 358 minify_reorder = minify_opts.get("reorder", True) 359 focus = Focus(minify_opts.get("focus")) 360 361 if not focus.tokens: 362 safe_reorder = True # nothing gained with False here, so set it to True just in case. 363 364 analysis = analyze_code_for_minify(root, focus, ctxt, safe_builtins) 365 366 def fixup_nodes_pre(node): 367 if minify_tokens: 368 # remove shorthands 369 370 if node.type in (NodeType.if_, NodeType.while_) and node.short and (analysis.new_shorts[node.type] == False): 371 minify_change_block_shorthand(node, False) 372 373 # remove unneeded groups 374 375 while node.type == NodeType.group: 376 inner, outer = node.child, node.parent 377 inner_prec, outer_prec = get_precedence(inner), get_precedence(outer) 378 remove = False 379 380 if e(outer_prec): 381 if e(inner_prec): 382 remove = inner_prec > outer_prec or (inner_prec == outer_prec and 383 (outer_prec == k_unary_ops_prec or is_right_assoc(outer) == (outer.right == node))) 384 elif inner.type in (NodeType.group, NodeType.var, NodeType.index, NodeType.member, NodeType.call, NodeType.varargs): 385 remove = True 386 elif inner.type == NodeType.const: 387 remove = (focus.tokens or can_replace_with_unary(node) or 388 not (inner.token.type == TokenType.number and value_is_negative(ctxt, inner.token.parsed_value))) 389 390 elif ((outer.type in (NodeType.index, NodeType.member) and node == outer.child) or 391 (outer.type == NodeType.call and node == outer.func)): 392 remove = inner.type in (NodeType.group, NodeType.var, NodeType.index, NodeType.member, NodeType.call) 393 394 elif outer.type in (NodeType.group, NodeType.table_member, NodeType.table_index, NodeType.op_assign): 395 remove = True 396 elif outer.type == NodeType.index: 397 remove = node == outer.key 398 elif outer.type == NodeType.call: 399 remove = node in outer.args[:-1] or (outer.args and node == outer.args[-1] and not is_vararg_expr(inner)) 400 elif outer.type in (NodeType.assign, NodeType.local, NodeType.for_in): 401 remove = (node in outer.sources[:-1] or (outer.sources and node == outer.sources[-1] and 402 (not is_vararg_expr(inner) or (3 if outer.type == NodeType.for_in else len(outer.targets)) <= len(outer.sources)))) 403 elif outer.type in (NodeType.return_, NodeType.table): 404 remove = (node in outer.items[:-1] or (outer.items and node == outer.items[-1] and not is_vararg_expr(inner))) 405 elif outer.type in (NodeType.if_, NodeType.elseif, NodeType.while_, NodeType.until, NodeType.for_) and not outer.short: 406 remove = True 407 408 if remove: 409 node.replace_with(node.child.move()) 410 # node may now be another group, so loop 411 else: 412 break 413 414 def fixup_nodes_post(node): 415 if minify_tokens: 416 # create shorthands 417 418 if (node.type in (NodeType.if_, NodeType.while_) and not node.short and 419 analysis.new_shorts[node.type] and node in analysis.allowed_shorts): 420 minify_change_block_shorthand(node, True) 421 422 if (node.type == NodeType.call and not node.short and 423 analysis.new_shorts[node.type] and node in analysis.allowed_shorts): 424 minify_change_print_shorthand(node, True) 425 426 if minify_reorder: 427 # merge assignments 428 429 if node.type == NodeType.local or (focus.tokens and node.type == NodeType.assign): 430 prev = node.prev_sibling() 431 while prev and prev.type == None: # skip erased 432 prev = prev.prev_sibling() 433 if prev and prev.type == node.type: 434 minify_merge_assignments(prev, node, ctxt, safe_reorder, root.has_env) 435 436 def fixup_tokens(token): 437 438 # minify sublangs 439 440 sublang = getattr(token, "sublang", None) 441 if sublang and sublang.minify: 442 token.modify(minify_string_literal(ctxt, token, focus, value=sublang.minify())) 443 444 if minify_tokens: 445 446 # remove unneeded tokens 447 448 if token.value == ";" and token.parent.type == NodeType.block and token.next_token().value != "(": 449 gparent = token.parent.parent 450 if not (gparent and is_short_block_stmt(gparent) and not token.parent.stmts): 451 token.erase() 452 return 453 454 if token.value in (",", ";") and token.parent.type == NodeType.table and token.next_sibling().value == "}": 455 token.erase() 456 return 457 458 if token.value == "(" and token.parent.type == NodeType.call and len(token.parent.args) == 1: 459 arg = token.parent.args[0] 460 if arg.type == NodeType.table or (arg.type == NodeType.const and arg.token.type == TokenType.string): 461 token.erase("(") 462 token.parent.erase_token(-1, ")") 463 return 464 465 # replace tokens for higher consistency 466 467 if token.value == ";" and token.parent.type == NodeType.table: 468 token.modify(",") 469 470 if token.value == "!=": 471 token.modify("~=") 472 473 if token.value == "^^" and ctxt.version >= 37: 474 token.modify("~") 475 476 if token.value == "then" and ctxt.lang == Language.pico8 and ctxt.version >= 42: 477 token.modify("do") # I HATE THIS :( 478 479 if token.value == "//" and ctxt.lang == Language.picotron: 480 token.modify("\\") 481 482 if token.value == "//=" and ctxt.lang == Language.picotron: 483 token.modify("\\=") 484 485 if token.type == TokenType.string: 486 token.modify(minify_string_literal(ctxt, token, focus)) 487 488 if token.type == TokenType.number: 489 allow_unary = can_replace_with_unary(token.parent) 490 format_num = format_luanum if ctxt.lang == Language.picotron else format_fixnum 491 token.modify(format_num(token.parsed_value, sign=None if allow_unary else '')) 492 493 if token.type == TokenType.number: 494 if token.value.startswith("-") or token.value.startswith("~"): # either due to format_fixnum above, or due to ConstToken.value 495 # insert synthetic unary token, so that output_tokens's tokenize and root.get_tokens() won't get confused 496 token.parent.insert_token(0, TokenType.punct, token.value[0], near_next=True) 497 token.modify(token.value[1:]) 498 elif token.value.startswith("("): # special case where a unary was forced on us 499 # insert synthetic unary tokens, as needed 500 token.parent.insert_token(0, TokenType.punct, token.value[0], near_next=True) 501 token.parent.insert_token(1, TokenType.punct, token.value[1], near_next=True) 502 token.parent.append_token(TokenType.punct, token.value[-1]) 503 token.modify(token.value[2:-1]) 504 505 root.traverse_nodes(fixup_nodes_pre, fixup_nodes_post, tokens=fixup_tokens)
minify root in-place (replacing/removing/rearranging tokens - doesn't include renaming/etc)