pico_rename

Functions to rename variables in a syntax tree for minification purposes

  1"""Functions to rename variables in a syntax tree for minification purposes"""
  2
  3from utils import *
  4from pico_defs import Language, from_langstr
  5from pico_srcdefs import Focus
  6from pico_tokenize import TokenType, is_identifier, keywords, CommentHint
  7from pico_output import format_string_literal
  8from pico_parse import VarKind, NodeType, VarBase
  9import fnmatch
 10
 11class IncludeExcludeMapping:
 12    """Defines which strings are included or excluded, through dicts & regexes"""
 13
 14    def __init__(m, keys=None):
 15        m.dict = dict.fromkeys(keys, True) if e(keys) else {}
 16        m.default = None
 17        m.regexs = None
 18
 19    def set(m, key, value):
 20        if key == "*":
 21            m.default = value
 22        elif "*" not in key:
 23            m.dict[key] = value
 24        else:
 25            if not m.regexs:
 26                m.regexs = []
 27            m.regexs.append((re.compile(fnmatch.translate(key)), value))
 28            
 29    def __contains__(m, key):
 30        value = m.dict.get(key, m.default)
 31        if value is False:
 32            return False
 33
 34        if m.regexs:
 35            for regex, re_value in m.regexs:
 36                if regex.match(key):
 37                    value = re_value
 38                    if value is False:
 39                        return False
 40        
 41        return bool(value)
 42    
 43class TableMemberPairIncludeExcludeMapping:
 44    """Defines which string-pairs are included or excluded, through dicts & regexes"""
 45
 46    def __init__(m, tables=None, members=None, pairs=None):
 47        m.table_dict = dict.fromkeys(tables, True) if e(tables) else {}
 48        m.member_dict = dict.fromkeys(members, True) if e(members) else {}
 49        m.pair_dict = dict.fromkeys(pairs, True) if e(pairs) else {}
 50        m.default = None
 51        m.regexs = None
 52
 53    def set(m, key, value):
 54        table, member = key
 55        if table == "*" and member == "*":
 56            m.default = value
 57        elif "*" not in table and member == "*":
 58            m.table_dict[table] = value
 59        elif table == "*" and "*" not in member:
 60            m.member_dict[member] = value
 61        elif "*" not in table and "*" not in member:
 62            m.pair_dict[(table, member)] = value
 63        else:
 64            if not m.regexs:
 65                m.regexs = []
 66            m.regexs.append((re.compile(fnmatch.translate(table)),
 67                             re.compile(fnmatch.translate(member)), value))
 68        
 69    def __contains__(m, key):
 70        if isinstance(key, tuple):
 71            table, member = key
 72        else:
 73            table, member = "", key
 74
 75        value = m.pair_dict.get(key, m.table_dict.get(table, m.member_dict.get(member, m.default)))
 76        if value is False:
 77            return False
 78
 79        if m.regexs:
 80            for table_regex, member_regex, re_value in m.regexs:
 81                if table_regex.match(table) and member_regex.match(member):
 82                    value = re_value
 83                    if value is False:
 84                        return False
 85        
 86        return bool(value)
 87
 88def rename_tokens(ctxt, root, rename_opts):
 89    """Rename variables in the given syntax tree in-place"""
 90    
 91    global_strings_cpy = ctxt.builtins | ctxt.builtin_callbacks
 92    preserved_globals = IncludeExcludeMapping(global_strings_cpy)
 93    preserved_members = TableMemberPairIncludeExcludeMapping(members=ctxt.builtin_members)
 94    
 95    # read rename options (e.g. what to preserve)
 96
 97    def add_rule(rule):
 98        value = True
 99        if rule.startswith("!"):
100            value = False
101            rule = rule[1:]
102        
103        if "=" in rule:
104            nonlocal members_as_globals
105            if rule in ("*=*.*", "*.*=*"):
106                members_as_globals = True
107        
108        if "." in rule:
109            preserved_members.set(rule.split(".", 1), value)
110        else:
111            preserved_globals.set(rule, value)
112
113    members_as_globals = False
114    safe_only = rename_opts.get("safe-only", False)
115    focus = Focus(rename_opts.get("focus"))
116    for rule in rename_opts.get("rules", ()):
117        add_rule(rule)
118
119    # collect char histogram
120    # (reusing commonly used chars in our new identifiers lowers compressed size)
121    #
122    # also takes the opportunity to find global preserve hints in code
123
124    char_uses = CounterDictionary()
125    def collect_chars(token):
126        if token.children:
127            for comment in token.children:
128                if comment.hint == CommentHint.preserve:
129                    for value in comment.hintdata:
130                        add_rule(value)
131
132        if token.value is None:
133            return
134
135        if token.type != TokenType.ident: # including preserved idents would help a tiny bit, but isn't a clear win
136                                          # (plus, it's now too early to check for preserved idents here)
137            sublang = getattr(token, "sublang", None)
138            if sublang and sublang.get_unminified_chars:
139                for ch in sublang.get_unminified_chars():
140                    char_uses[ch] += 1
141            else:
142                if token.type == TokenType.string and len(token.value) >= 0x80 and len(set(token.value)) >= 0x80: # ignore compressed strings (heuristic)
143                    return
144
145                for ch in token.value:
146                    char_uses[ch] += 1
147
148    root.traverse_tokens(collect_chars)
149
150    # TODO: something must still be unoptimal with char_uses collection, as hardcoding k_identifier_chars is more helpful than going by uses...
151    if focus.chars:
152        k_identifier_chars = string.ascii_letters + string.digits + "_\x1e\x1f" + "".join(chr(x) for x in range(0x80,0x100))
153    elif focus.compressed:
154        k_identifier_chars = string.ascii_lowercase + string.digits + "_"
155    else:
156        k_identifier_chars = string.ascii_letters + string.digits + "_"
157    
158    ident_chars = []
159    for ch in sorted(char_uses, key=lambda k: char_uses[k], reverse=True):
160        if ch in k_identifier_chars:
161            ident_chars.append(ch)
162    
163    for ch in k_identifier_chars:
164        if ch not in ident_chars:
165            ident_chars.append(ch)
166
167    ident_char_order_map = {ch1: ch2 for ch1, ch2 in zip(ident_chars, ident_chars[1:])}
168
169    # detect which renames are safe to do, if requested
170    # (note - this assumes a "pure" cart with no hints for shrinko8)
171
172    if safe_only:
173        can_access_globals = root.has_env
174
175        if ctxt.lang == Language.picotron and "load" in root.globals:
176            can_access_globals = True
177        # in theory, picotron's 'include' can also do this if used to include a non-code file or a written-at-runtime file
178        # but it seems more useful to assume it won't
179
180        preserved_members.default = True # can't reasonably guarantee safety of this
181        preserved_globals.default = can_access_globals
182
183    # collect uses of identifier
184    # (e.g. to give priority to more frequently used ones)
185
186    global_uses = CounterDictionary()
187    member_uses = CounterDictionary()
188    local_uses = CounterDictionary()
189    label_uses = CounterDictionary()
190    
191    # we avoid renaming into any names used by pico8/lua, as otherwise renamed variables may have a non-nill initial value
192    global_excludes = global_strings_cpy
193    member_excludes = ctxt.builtin_members.copy()
194    local_excludes = defaultdict(set)
195    label_excludes = defaultdict(set)
196
197    globals_after_zero = set()
198    members_after_zero = set()
199    locals_after_zero = set()
200
201    renamed_vars = set()
202
203    def compute_effective_kind(node, kind, explicit):
204        """get the identifier kind (global/member/etc) of a node, taking into account hints in the code"""
205
206        if node.var.rename:
207            node.name = node.var.rename
208            renamed_vars.add(node.var)
209            if kind == VarKind.member:
210                member_excludes.add(node.name)
211            elif kind == VarKind.global_:
212                global_excludes.add(node.name)
213            elif kind == VarKind.local:
214                local_excludes[node.name].add(node.var)
215            elif kind == VarKind.label:
216                label_excludes[node.name].add(node.var)
217            return None
218
219        if kind == VarKind.member:
220            table_name = ""
221            
222            if node.parent.type == NodeType.member and node.parent.key == node and node.parent.child.type == NodeType.var:
223                var_node = node.parent.child
224                table_name = var_node.name
225
226                if not explicit and var_node.var and var_node.var.keys_kind != None:
227                    return compute_effective_kind(node, var_node.var.keys_kind, explicit=True)
228
229            elif node.parent.type == NodeType.table_member and node.parent.key == node:
230                table_node = node.parent.parent
231                if not explicit and table_node.keys_kind != None:
232                    return compute_effective_kind(node, table_node.keys_kind, explicit=True)
233
234                if table_node.parent.type in (NodeType.assign, NodeType.local) and table_node in table_node.parent.sources:
235                    assign_i = table_node.parent.sources.index(table_node)
236                    target_node = list_get(table_node.parent.targets, assign_i)
237                    if target_node and target_node.type == NodeType.var:
238                        table_name = target_node.name
239
240                        if not explicit and target_node.var and target_node.var.keys_kind != None:
241                            return compute_effective_kind(node, target_node.var.keys_kind, explicit=True)
242            
243            if (table_name, node.name) in preserved_members:
244                member_excludes.add(node.name)
245                return None
246            elif table_name == "_ENV" or members_as_globals:
247                return compute_effective_kind(node, VarKind.global_, explicit=True)
248
249        elif kind == VarKind.global_:
250            if not explicit:
251                env_var = node.env_var
252                if env_var and env_var.keys_kind != None:
253                    return compute_effective_kind(node, env_var.keys_kind, explicit=True)
254
255            if node.var.implicit or node.name in preserved_globals:
256                global_excludes.add(node.name)
257                return None
258
259        elif kind == VarKind.local:
260            if node.var.implicit or (node.var.builtin and node.name in preserved_globals):
261                local_excludes[node.name].add(node.var)
262                return None
263            # best to keep this check, e.g. to avoid renaming _ENV locals that are unused unless local builtins are disabled
264            elif node.name == "_ENV":
265                return None
266
267        return kind
268
269    def is_after_zero(node):
270        if not node.is_extra_child():
271            prev = node.prev_token()
272            # TODO: would be good to rename after minify?
273            if prev.type == TokenType.number and prev.value.endswith("0"):
274                return True
275
276    def collect_idents_pre(node):
277        if node.type == NodeType.var:
278            node.effective_kind = compute_effective_kind(node, default(node.var_kind, node.kind), explicit=e(node.var_kind))
279            
280            if node.effective_kind == VarKind.member:
281                member_uses[node.name] += 1
282                if is_after_zero(node):
283                    members_after_zero.add(node.name)
284            
285            elif node.effective_kind == VarKind.global_:
286                global_uses[node.name] += 1
287                if is_after_zero(node):
288                    globals_after_zero.add(node.name)
289            
290            elif node.effective_kind == VarKind.local:
291                local_uses[node.var] += 1
292                if is_after_zero(node):
293                    locals_after_zero.add(node.var)
294            
295            elif node.effective_kind == VarKind.label:
296                label_uses[node.var] += 1
297                    
298            # add to the scope based on real kind, as we need to avoid conflicts with preserved vars too
299            if node.kind == VarKind.global_:
300                for scope in node.scope.chain():
301                    if node.effective_kind == VarKind.member: # rare, e.g. see --[[member-keys]] example
302                        scope.used_members.add(node.name)
303                    else:
304                        scope.used_globals.add(node.name)
305
306            elif node.kind in (VarKind.local, VarKind.label):
307                for scope in node.scope.chain():
308                    scope.used_locals.add(node.var)
309                    if scope == node.var.scope:
310                        if not (node.kind == VarKind.label and ctxt.lang == Language.picotron): # lua 5.4 disallows dup. labels
311                            break
312                        
313        elif node.type == NodeType.sublang:
314            for name, count in node.sublang.get_global_usages().items():
315                if is_identifier(name, ctxt.lang):
316                    if name in preserved_globals:
317                        global_excludes.add(name)
318                    else:
319                        global_uses[name] += count
320
321            for name, count in node.sublang.get_member_usages().items():
322                if is_identifier(name, ctxt.lang):
323                    if name in preserved_members:
324                        member_excludes.add(name)
325                    elif members_as_globals:
326                        global_uses[name] += count
327                    else:
328                        member_uses[name] += count
329
330            for var, count in node.sublang.get_local_usages().items():
331                if not var.implicit:
332                    local_uses[var] += count
333
334    root.traverse_nodes(collect_idents_pre, extra=True)
335
336    # assign new names to identifiers
337
338    def get_next_ident_char(ch, first):
339        nextch = ident_char_order_map.get(ch) if ch else ident_chars[0]
340        while first and nextch and nextch.isdigit():
341            nextch = ident_char_order_map.get(nextch)
342        if nextch:
343            return nextch, True
344        else:
345            return ident_chars[0], False
346
347    def get_idents():
348        """a generator of new identifiers, in the ideal order"""
349        next_ident = ""
350
351        while True:
352            for i in range(len(next_ident)-1, -1, -1):
353                next_ch, found = get_next_ident_char(next_ident[i], i==0)
354                next_ident = str_replace_at(next_ident, i, 1, next_ch)
355                if found:
356                    break
357            else:
358                next_ident = str_insert(next_ident, 0, get_next_ident_char(None, True)[0])
359            if next_ident not in keywords:
360                yield next_ident
361
362    def are_vars_compatible(var1, var2): # it is assumed var1 and var2 have the same name
363        is_global1 = var1.kind in (VarKind.global_, VarKind.member)
364        is_global2 = var2.kind in (VarKind.global_, VarKind.member)
365
366        if is_global1 and is_global2: # both globals/members
367            return var1.kind != var2.kind
368        
369        elif is_global1 or is_global2:
370            gvar, lvar = (var1, var2) if is_global1 else (var2, var1)
371            if lvar.kind == VarKind.label:
372                return True
373            
374            if gvar.kind == VarKind.global_ and lvar.scope.has_used_globals and gvar.name in lvar.scope.used_globals:
375                return False
376            if gvar.kind == VarKind.member and lvar.scope.has_used_members and gvar.name in lvar.scope.used_members:
377                return False
378            return True
379
380        else: # both locals/labels
381            if var1.kind == var2.kind:
382                return var1 not in var2.scope.used_locals and var2 not in var1.scope.used_locals
383            else:
384                return True
385    
386    remaining_locals = list(sorted(local_uses, key=lambda k: local_uses[k], reverse=True))
387    remaining_globals = list(sorted(global_uses, key=lambda k: global_uses[k], reverse=True))
388    remaining_members = list(sorted(member_uses, key=lambda k: member_uses[k], reverse=True))
389    remaining_labels = list(sorted(label_uses, key=lambda k: label_uses[k], reverse=True))
390
391    local_renames, global_renames, member_renames, label_renames = {}, {}, {}, {}
392
393    def try_select_var(sel, excluded, renames, avoids, ident, var_map=None):
394        sel_var = var_map[sel] if e(var_map) else sel
395        
396        if sel in avoids:
397            return False
398
399        for exclude in excluded:
400            if not are_vars_compatible(sel_var, exclude):
401                return False
402
403        excluded.append(sel_var)
404        renames[sel] = ident
405        return True
406
407    def select_var(remaining, excluded, renames, avoids, ident, var_map=None, i=0):
408        while i < len(remaining):
409            if try_select_var(remaining[i], excluded, renames, avoids, ident, var_map):
410                del remaining[i]
411                return i
412            i += 1
413
414    def select_vars(remaining, excluded, renames, avoids, ident):
415        i = 0
416        while i != None:
417            i = select_var(remaining, excluded, renames, avoids, ident, i=i)
418
419    for ident in get_idents():
420        if not remaining_locals and not remaining_globals and not remaining_members and not remaining_labels:
421            break
422
423        avoid_locals = avoid_globals = avoid_members = ()
424        if ctxt.lang == Language.pico8:
425            if ident[0] in "bxBX": # these chars cause extra space if placed after 0
426                avoid_locals, avoid_globals, avoid_members = locals_after_zero, globals_after_zero, members_after_zero
427
428        if ident != "_ENV":
429            excluded = []
430            if ident in global_excludes:
431                excluded.append(root.globals[ident])
432            if ident in member_excludes:
433                excluded.append(root.members[ident])
434            if ident in local_excludes:
435                excluded.extend(local_excludes[ident])
436
437            if not focus.chars: # going over locals first seems to usually increase compression (TODO...)
438                select_vars(remaining_locals, excluded, local_renames, avoid_locals, ident)
439                select_var(remaining_globals, excluded, global_renames, avoid_globals, ident, root.globals)
440                select_var(remaining_members, excluded, member_renames, avoid_members, ident, root.members)
441            else:
442                select_var(remaining_globals, excluded, global_renames, avoid_globals, ident, root.globals)
443                select_var(remaining_members, excluded, member_renames, avoid_members, ident, root.members)
444                select_vars(remaining_locals, excluded, local_renames, avoid_locals, ident)
445
446        if remaining_labels:
447            excluded = list(label_excludes[ident])
448            select_vars(remaining_labels, excluded, label_renames, (), ident)
449
450    if renamed_vars:
451        for var1, var2 in itertools.product(renamed_vars, renamed_vars):
452            if var1 != var2 and var1.rename == var2.rename and not are_vars_compatible(var1, var2):
453                throw(f"rename hint of {var1.name} to {var1.rename} conflicts with that of {var2.name} to {var2.rename}")
454
455    # output the identifier mapping, if needed
456
457    def update_srcmap(mapping, kind=None):
458        for old, new in mapping.items():
459            old_name = old.name if isinstance(old, VarBase) else old
460
461            ctxt.srcmap.append(f"{kind or old.kind} {from_langstr(new, ctxt.lang)} <- {from_langstr(old_name, ctxt.lang)}")
462
463    if e(ctxt.srcmap):
464        update_srcmap(member_renames, VarKind.member)
465        update_srcmap(global_renames, VarKind.global_)
466        update_srcmap(local_renames)
467        update_srcmap(label_renames)
468        update_srcmap({var: var.rename for var in renamed_vars})
469
470    # write the new names into the syntax tree
471
472    def update_idents(node):
473        if node.type == NodeType.var:
474            orig_name = node.name
475
476            if node.effective_kind == VarKind.member:
477                node.name = member_renames[node.name]
478            elif node.effective_kind == VarKind.global_:
479                node.name = global_renames[node.name]
480            elif node.effective_kind == VarKind.local:
481                node.name = local_renames[node.var]
482            elif node.effective_kind == VarKind.label:
483                node.name = label_renames[node.var]
484            elif node.var.rename:
485                orig_name = node.var.name # (node.name already renamed)
486            else:
487                return
488
489            # need to update the tokens as well...
490            if node.parent.type == NodeType.const: # const string interpreted as identifier case
491                assert len(node.parent.children) == 1 and node.parent.extra_names[node.extra_i] == orig_name
492                node.parent.extra_names[node.extra_i] = node.name
493                node.parent.children[0].modify(format_string_literal("".join(node.parent.extra_names)))
494            else:
495                assert len(node.children) >= 1 and node.children[0].value == orig_name
496                node.children[0].modify(node.name)
497                
498        elif node.type == NodeType.sublang:
499            effective_member_renames = global_renames if members_as_globals else member_renames
500            node.sublang.rename(globals=global_renames, members=effective_member_renames, locals=local_renames)
501            
502    root.traverse_nodes(update_idents, extra=True)
503
504    # save for optional later usage
505    ctxt.local_renames, ctxt.global_renames, ctxt.member_renames, ctxt.label_renames = (
506        local_renames, global_renames, member_renames, label_renames)
class IncludeExcludeMapping:
12class IncludeExcludeMapping:
13    """Defines which strings are included or excluded, through dicts & regexes"""
14
15    def __init__(m, keys=None):
16        m.dict = dict.fromkeys(keys, True) if e(keys) else {}
17        m.default = None
18        m.regexs = None
19
20    def set(m, key, value):
21        if key == "*":
22            m.default = value
23        elif "*" not in key:
24            m.dict[key] = value
25        else:
26            if not m.regexs:
27                m.regexs = []
28            m.regexs.append((re.compile(fnmatch.translate(key)), value))
29            
30    def __contains__(m, key):
31        value = m.dict.get(key, m.default)
32        if value is False:
33            return False
34
35        if m.regexs:
36            for regex, re_value in m.regexs:
37                if regex.match(key):
38                    value = re_value
39                    if value is False:
40                        return False
41        
42        return bool(value)

Defines which strings are included or excluded, through dicts & regexes

IncludeExcludeMapping(keys=None)
15    def __init__(m, keys=None):
16        m.dict = dict.fromkeys(keys, True) if e(keys) else {}
17        m.default = None
18        m.regexs = None
def set(m, key, value):
20    def set(m, key, value):
21        if key == "*":
22            m.default = value
23        elif "*" not in key:
24            m.dict[key] = value
25        else:
26            if not m.regexs:
27                m.regexs = []
28            m.regexs.append((re.compile(fnmatch.translate(key)), value))
class TableMemberPairIncludeExcludeMapping:
44class TableMemberPairIncludeExcludeMapping:
45    """Defines which string-pairs are included or excluded, through dicts & regexes"""
46
47    def __init__(m, tables=None, members=None, pairs=None):
48        m.table_dict = dict.fromkeys(tables, True) if e(tables) else {}
49        m.member_dict = dict.fromkeys(members, True) if e(members) else {}
50        m.pair_dict = dict.fromkeys(pairs, True) if e(pairs) else {}
51        m.default = None
52        m.regexs = None
53
54    def set(m, key, value):
55        table, member = key
56        if table == "*" and member == "*":
57            m.default = value
58        elif "*" not in table and member == "*":
59            m.table_dict[table] = value
60        elif table == "*" and "*" not in member:
61            m.member_dict[member] = value
62        elif "*" not in table and "*" not in member:
63            m.pair_dict[(table, member)] = value
64        else:
65            if not m.regexs:
66                m.regexs = []
67            m.regexs.append((re.compile(fnmatch.translate(table)),
68                             re.compile(fnmatch.translate(member)), value))
69        
70    def __contains__(m, key):
71        if isinstance(key, tuple):
72            table, member = key
73        else:
74            table, member = "", key
75
76        value = m.pair_dict.get(key, m.table_dict.get(table, m.member_dict.get(member, m.default)))
77        if value is False:
78            return False
79
80        if m.regexs:
81            for table_regex, member_regex, re_value in m.regexs:
82                if table_regex.match(table) and member_regex.match(member):
83                    value = re_value
84                    if value is False:
85                        return False
86        
87        return bool(value)

Defines which string-pairs are included or excluded, through dicts & regexes

TableMemberPairIncludeExcludeMapping(tables=None, members=None, pairs=None)
47    def __init__(m, tables=None, members=None, pairs=None):
48        m.table_dict = dict.fromkeys(tables, True) if e(tables) else {}
49        m.member_dict = dict.fromkeys(members, True) if e(members) else {}
50        m.pair_dict = dict.fromkeys(pairs, True) if e(pairs) else {}
51        m.default = None
52        m.regexs = None
def set(m, key, value):
54    def set(m, key, value):
55        table, member = key
56        if table == "*" and member == "*":
57            m.default = value
58        elif "*" not in table and member == "*":
59            m.table_dict[table] = value
60        elif table == "*" and "*" not in member:
61            m.member_dict[member] = value
62        elif "*" not in table and "*" not in member:
63            m.pair_dict[(table, member)] = value
64        else:
65            if not m.regexs:
66                m.regexs = []
67            m.regexs.append((re.compile(fnmatch.translate(table)),
68                             re.compile(fnmatch.translate(member)), value))
def rename_tokens(ctxt, root, rename_opts):
 89def rename_tokens(ctxt, root, rename_opts):
 90    """Rename variables in the given syntax tree in-place"""
 91    
 92    global_strings_cpy = ctxt.builtins | ctxt.builtin_callbacks
 93    preserved_globals = IncludeExcludeMapping(global_strings_cpy)
 94    preserved_members = TableMemberPairIncludeExcludeMapping(members=ctxt.builtin_members)
 95    
 96    # read rename options (e.g. what to preserve)
 97
 98    def add_rule(rule):
 99        value = True
100        if rule.startswith("!"):
101            value = False
102            rule = rule[1:]
103        
104        if "=" in rule:
105            nonlocal members_as_globals
106            if rule in ("*=*.*", "*.*=*"):
107                members_as_globals = True
108        
109        if "." in rule:
110            preserved_members.set(rule.split(".", 1), value)
111        else:
112            preserved_globals.set(rule, value)
113
114    members_as_globals = False
115    safe_only = rename_opts.get("safe-only", False)
116    focus = Focus(rename_opts.get("focus"))
117    for rule in rename_opts.get("rules", ()):
118        add_rule(rule)
119
120    # collect char histogram
121    # (reusing commonly used chars in our new identifiers lowers compressed size)
122    #
123    # also takes the opportunity to find global preserve hints in code
124
125    char_uses = CounterDictionary()
126    def collect_chars(token):
127        if token.children:
128            for comment in token.children:
129                if comment.hint == CommentHint.preserve:
130                    for value in comment.hintdata:
131                        add_rule(value)
132
133        if token.value is None:
134            return
135
136        if token.type != TokenType.ident: # including preserved idents would help a tiny bit, but isn't a clear win
137                                          # (plus, it's now too early to check for preserved idents here)
138            sublang = getattr(token, "sublang", None)
139            if sublang and sublang.get_unminified_chars:
140                for ch in sublang.get_unminified_chars():
141                    char_uses[ch] += 1
142            else:
143                if token.type == TokenType.string and len(token.value) >= 0x80 and len(set(token.value)) >= 0x80: # ignore compressed strings (heuristic)
144                    return
145
146                for ch in token.value:
147                    char_uses[ch] += 1
148
149    root.traverse_tokens(collect_chars)
150
151    # TODO: something must still be unoptimal with char_uses collection, as hardcoding k_identifier_chars is more helpful than going by uses...
152    if focus.chars:
153        k_identifier_chars = string.ascii_letters + string.digits + "_\x1e\x1f" + "".join(chr(x) for x in range(0x80,0x100))
154    elif focus.compressed:
155        k_identifier_chars = string.ascii_lowercase + string.digits + "_"
156    else:
157        k_identifier_chars = string.ascii_letters + string.digits + "_"
158    
159    ident_chars = []
160    for ch in sorted(char_uses, key=lambda k: char_uses[k], reverse=True):
161        if ch in k_identifier_chars:
162            ident_chars.append(ch)
163    
164    for ch in k_identifier_chars:
165        if ch not in ident_chars:
166            ident_chars.append(ch)
167
168    ident_char_order_map = {ch1: ch2 for ch1, ch2 in zip(ident_chars, ident_chars[1:])}
169
170    # detect which renames are safe to do, if requested
171    # (note - this assumes a "pure" cart with no hints for shrinko8)
172
173    if safe_only:
174        can_access_globals = root.has_env
175
176        if ctxt.lang == Language.picotron and "load" in root.globals:
177            can_access_globals = True
178        # in theory, picotron's 'include' can also do this if used to include a non-code file or a written-at-runtime file
179        # but it seems more useful to assume it won't
180
181        preserved_members.default = True # can't reasonably guarantee safety of this
182        preserved_globals.default = can_access_globals
183
184    # collect uses of identifier
185    # (e.g. to give priority to more frequently used ones)
186
187    global_uses = CounterDictionary()
188    member_uses = CounterDictionary()
189    local_uses = CounterDictionary()
190    label_uses = CounterDictionary()
191    
192    # we avoid renaming into any names used by pico8/lua, as otherwise renamed variables may have a non-nill initial value
193    global_excludes = global_strings_cpy
194    member_excludes = ctxt.builtin_members.copy()
195    local_excludes = defaultdict(set)
196    label_excludes = defaultdict(set)
197
198    globals_after_zero = set()
199    members_after_zero = set()
200    locals_after_zero = set()
201
202    renamed_vars = set()
203
204    def compute_effective_kind(node, kind, explicit):
205        """get the identifier kind (global/member/etc) of a node, taking into account hints in the code"""
206
207        if node.var.rename:
208            node.name = node.var.rename
209            renamed_vars.add(node.var)
210            if kind == VarKind.member:
211                member_excludes.add(node.name)
212            elif kind == VarKind.global_:
213                global_excludes.add(node.name)
214            elif kind == VarKind.local:
215                local_excludes[node.name].add(node.var)
216            elif kind == VarKind.label:
217                label_excludes[node.name].add(node.var)
218            return None
219
220        if kind == VarKind.member:
221            table_name = ""
222            
223            if node.parent.type == NodeType.member and node.parent.key == node and node.parent.child.type == NodeType.var:
224                var_node = node.parent.child
225                table_name = var_node.name
226
227                if not explicit and var_node.var and var_node.var.keys_kind != None:
228                    return compute_effective_kind(node, var_node.var.keys_kind, explicit=True)
229
230            elif node.parent.type == NodeType.table_member and node.parent.key == node:
231                table_node = node.parent.parent
232                if not explicit and table_node.keys_kind != None:
233                    return compute_effective_kind(node, table_node.keys_kind, explicit=True)
234
235                if table_node.parent.type in (NodeType.assign, NodeType.local) and table_node in table_node.parent.sources:
236                    assign_i = table_node.parent.sources.index(table_node)
237                    target_node = list_get(table_node.parent.targets, assign_i)
238                    if target_node and target_node.type == NodeType.var:
239                        table_name = target_node.name
240
241                        if not explicit and target_node.var and target_node.var.keys_kind != None:
242                            return compute_effective_kind(node, target_node.var.keys_kind, explicit=True)
243            
244            if (table_name, node.name) in preserved_members:
245                member_excludes.add(node.name)
246                return None
247            elif table_name == "_ENV" or members_as_globals:
248                return compute_effective_kind(node, VarKind.global_, explicit=True)
249
250        elif kind == VarKind.global_:
251            if not explicit:
252                env_var = node.env_var
253                if env_var and env_var.keys_kind != None:
254                    return compute_effective_kind(node, env_var.keys_kind, explicit=True)
255
256            if node.var.implicit or node.name in preserved_globals:
257                global_excludes.add(node.name)
258                return None
259
260        elif kind == VarKind.local:
261            if node.var.implicit or (node.var.builtin and node.name in preserved_globals):
262                local_excludes[node.name].add(node.var)
263                return None
264            # best to keep this check, e.g. to avoid renaming _ENV locals that are unused unless local builtins are disabled
265            elif node.name == "_ENV":
266                return None
267
268        return kind
269
270    def is_after_zero(node):
271        if not node.is_extra_child():
272            prev = node.prev_token()
273            # TODO: would be good to rename after minify?
274            if prev.type == TokenType.number and prev.value.endswith("0"):
275                return True
276
277    def collect_idents_pre(node):
278        if node.type == NodeType.var:
279            node.effective_kind = compute_effective_kind(node, default(node.var_kind, node.kind), explicit=e(node.var_kind))
280            
281            if node.effective_kind == VarKind.member:
282                member_uses[node.name] += 1
283                if is_after_zero(node):
284                    members_after_zero.add(node.name)
285            
286            elif node.effective_kind == VarKind.global_:
287                global_uses[node.name] += 1
288                if is_after_zero(node):
289                    globals_after_zero.add(node.name)
290            
291            elif node.effective_kind == VarKind.local:
292                local_uses[node.var] += 1
293                if is_after_zero(node):
294                    locals_after_zero.add(node.var)
295            
296            elif node.effective_kind == VarKind.label:
297                label_uses[node.var] += 1
298                    
299            # add to the scope based on real kind, as we need to avoid conflicts with preserved vars too
300            if node.kind == VarKind.global_:
301                for scope in node.scope.chain():
302                    if node.effective_kind == VarKind.member: # rare, e.g. see --[[member-keys]] example
303                        scope.used_members.add(node.name)
304                    else:
305                        scope.used_globals.add(node.name)
306
307            elif node.kind in (VarKind.local, VarKind.label):
308                for scope in node.scope.chain():
309                    scope.used_locals.add(node.var)
310                    if scope == node.var.scope:
311                        if not (node.kind == VarKind.label and ctxt.lang == Language.picotron): # lua 5.4 disallows dup. labels
312                            break
313                        
314        elif node.type == NodeType.sublang:
315            for name, count in node.sublang.get_global_usages().items():
316                if is_identifier(name, ctxt.lang):
317                    if name in preserved_globals:
318                        global_excludes.add(name)
319                    else:
320                        global_uses[name] += count
321
322            for name, count in node.sublang.get_member_usages().items():
323                if is_identifier(name, ctxt.lang):
324                    if name in preserved_members:
325                        member_excludes.add(name)
326                    elif members_as_globals:
327                        global_uses[name] += count
328                    else:
329                        member_uses[name] += count
330
331            for var, count in node.sublang.get_local_usages().items():
332                if not var.implicit:
333                    local_uses[var] += count
334
335    root.traverse_nodes(collect_idents_pre, extra=True)
336
337    # assign new names to identifiers
338
339    def get_next_ident_char(ch, first):
340        nextch = ident_char_order_map.get(ch) if ch else ident_chars[0]
341        while first and nextch and nextch.isdigit():
342            nextch = ident_char_order_map.get(nextch)
343        if nextch:
344            return nextch, True
345        else:
346            return ident_chars[0], False
347
348    def get_idents():
349        """a generator of new identifiers, in the ideal order"""
350        next_ident = ""
351
352        while True:
353            for i in range(len(next_ident)-1, -1, -1):
354                next_ch, found = get_next_ident_char(next_ident[i], i==0)
355                next_ident = str_replace_at(next_ident, i, 1, next_ch)
356                if found:
357                    break
358            else:
359                next_ident = str_insert(next_ident, 0, get_next_ident_char(None, True)[0])
360            if next_ident not in keywords:
361                yield next_ident
362
363    def are_vars_compatible(var1, var2): # it is assumed var1 and var2 have the same name
364        is_global1 = var1.kind in (VarKind.global_, VarKind.member)
365        is_global2 = var2.kind in (VarKind.global_, VarKind.member)
366
367        if is_global1 and is_global2: # both globals/members
368            return var1.kind != var2.kind
369        
370        elif is_global1 or is_global2:
371            gvar, lvar = (var1, var2) if is_global1 else (var2, var1)
372            if lvar.kind == VarKind.label:
373                return True
374            
375            if gvar.kind == VarKind.global_ and lvar.scope.has_used_globals and gvar.name in lvar.scope.used_globals:
376                return False
377            if gvar.kind == VarKind.member and lvar.scope.has_used_members and gvar.name in lvar.scope.used_members:
378                return False
379            return True
380
381        else: # both locals/labels
382            if var1.kind == var2.kind:
383                return var1 not in var2.scope.used_locals and var2 not in var1.scope.used_locals
384            else:
385                return True
386    
387    remaining_locals = list(sorted(local_uses, key=lambda k: local_uses[k], reverse=True))
388    remaining_globals = list(sorted(global_uses, key=lambda k: global_uses[k], reverse=True))
389    remaining_members = list(sorted(member_uses, key=lambda k: member_uses[k], reverse=True))
390    remaining_labels = list(sorted(label_uses, key=lambda k: label_uses[k], reverse=True))
391
392    local_renames, global_renames, member_renames, label_renames = {}, {}, {}, {}
393
394    def try_select_var(sel, excluded, renames, avoids, ident, var_map=None):
395        sel_var = var_map[sel] if e(var_map) else sel
396        
397        if sel in avoids:
398            return False
399
400        for exclude in excluded:
401            if not are_vars_compatible(sel_var, exclude):
402                return False
403
404        excluded.append(sel_var)
405        renames[sel] = ident
406        return True
407
408    def select_var(remaining, excluded, renames, avoids, ident, var_map=None, i=0):
409        while i < len(remaining):
410            if try_select_var(remaining[i], excluded, renames, avoids, ident, var_map):
411                del remaining[i]
412                return i
413            i += 1
414
415    def select_vars(remaining, excluded, renames, avoids, ident):
416        i = 0
417        while i != None:
418            i = select_var(remaining, excluded, renames, avoids, ident, i=i)
419
420    for ident in get_idents():
421        if not remaining_locals and not remaining_globals and not remaining_members and not remaining_labels:
422            break
423
424        avoid_locals = avoid_globals = avoid_members = ()
425        if ctxt.lang == Language.pico8:
426            if ident[0] in "bxBX": # these chars cause extra space if placed after 0
427                avoid_locals, avoid_globals, avoid_members = locals_after_zero, globals_after_zero, members_after_zero
428
429        if ident != "_ENV":
430            excluded = []
431            if ident in global_excludes:
432                excluded.append(root.globals[ident])
433            if ident in member_excludes:
434                excluded.append(root.members[ident])
435            if ident in local_excludes:
436                excluded.extend(local_excludes[ident])
437
438            if not focus.chars: # going over locals first seems to usually increase compression (TODO...)
439                select_vars(remaining_locals, excluded, local_renames, avoid_locals, ident)
440                select_var(remaining_globals, excluded, global_renames, avoid_globals, ident, root.globals)
441                select_var(remaining_members, excluded, member_renames, avoid_members, ident, root.members)
442            else:
443                select_var(remaining_globals, excluded, global_renames, avoid_globals, ident, root.globals)
444                select_var(remaining_members, excluded, member_renames, avoid_members, ident, root.members)
445                select_vars(remaining_locals, excluded, local_renames, avoid_locals, ident)
446
447        if remaining_labels:
448            excluded = list(label_excludes[ident])
449            select_vars(remaining_labels, excluded, label_renames, (), ident)
450
451    if renamed_vars:
452        for var1, var2 in itertools.product(renamed_vars, renamed_vars):
453            if var1 != var2 and var1.rename == var2.rename and not are_vars_compatible(var1, var2):
454                throw(f"rename hint of {var1.name} to {var1.rename} conflicts with that of {var2.name} to {var2.rename}")
455
456    # output the identifier mapping, if needed
457
458    def update_srcmap(mapping, kind=None):
459        for old, new in mapping.items():
460            old_name = old.name if isinstance(old, VarBase) else old
461
462            ctxt.srcmap.append(f"{kind or old.kind} {from_langstr(new, ctxt.lang)} <- {from_langstr(old_name, ctxt.lang)}")
463
464    if e(ctxt.srcmap):
465        update_srcmap(member_renames, VarKind.member)
466        update_srcmap(global_renames, VarKind.global_)
467        update_srcmap(local_renames)
468        update_srcmap(label_renames)
469        update_srcmap({var: var.rename for var in renamed_vars})
470
471    # write the new names into the syntax tree
472
473    def update_idents(node):
474        if node.type == NodeType.var:
475            orig_name = node.name
476
477            if node.effective_kind == VarKind.member:
478                node.name = member_renames[node.name]
479            elif node.effective_kind == VarKind.global_:
480                node.name = global_renames[node.name]
481            elif node.effective_kind == VarKind.local:
482                node.name = local_renames[node.var]
483            elif node.effective_kind == VarKind.label:
484                node.name = label_renames[node.var]
485            elif node.var.rename:
486                orig_name = node.var.name # (node.name already renamed)
487            else:
488                return
489
490            # need to update the tokens as well...
491            if node.parent.type == NodeType.const: # const string interpreted as identifier case
492                assert len(node.parent.children) == 1 and node.parent.extra_names[node.extra_i] == orig_name
493                node.parent.extra_names[node.extra_i] = node.name
494                node.parent.children[0].modify(format_string_literal("".join(node.parent.extra_names)))
495            else:
496                assert len(node.children) >= 1 and node.children[0].value == orig_name
497                node.children[0].modify(node.name)
498                
499        elif node.type == NodeType.sublang:
500            effective_member_renames = global_renames if members_as_globals else member_renames
501            node.sublang.rename(globals=global_renames, members=effective_member_renames, locals=local_renames)
502            
503    root.traverse_nodes(update_idents, extra=True)
504
505    # save for optional later usage
506    ctxt.local_renames, ctxt.global_renames, ctxt.member_renames, ctxt.label_renames = (
507        local_renames, global_renames, member_renames, label_renames)

Rename variables in the given syntax tree in-place