pico_constfold

Evaluation of constant pico expressions to produce a constant (note that we play it safe and don't support potentially unstable operations)

  1"""Evaluation of constant pico expressions to produce a constant (note that we play it safe and don't support potentially unstable operations)"""
  2
  3from utils import *
  4from pico_defs import *
  5from pico_srcdefs import Error, Source, Focus
  6from pico_tokenize import Token, TokenType, k_skip_children, tokenize, KeepCommentFlags
  7from pico_parse import Node, NodeType, VarKind, is_root_global_or_builtin_local, is_vararg_expr, can_replace_with_unary
  8from pico_output import output_node, format_fixnum, format_luanum, format_string_literal
  9
 10class ConstToken(Token):
 11    """A token that's created from a value, instead of from a string"""
 12
 13    def __init__(m, type, parsed_value, other):
 14        super().__init__(type, None, other.source, other.idx, other.endidx, other.vline, other.lang, modified=True)
 15        m.parsed_value = parsed_value
 16        lazy_property.clear(m, "value")
 17
 18    @lazy_property
 19    def value(m): # used during going over chars for rename (tsk...) and for output when not minify-tokens
 20                  # (but not used for output under minify-tokens)
 21        if isinstance(m.parsed_value, (int, float)):
 22            allow_unary = can_replace_with_unary(m.parent) if m.parent else True
 23            format_num = format_fixnum if m.lang == Language.pico8 else format_luanum
 24            return format_num(m.parsed_value, sign=None if allow_unary else "")
 25        else:
 26            return format_string_literal(m.parsed_value, long=False)
 27
 28    @post_property_change
 29    def parent(m, old, new):
 30        lazy_property.clear(m, "value")
 31
 32class LuaType(Enum):
 33    """A lua (or pico8) type for the purpose of constant folding"""
 34    nil = boolean = fixnum = integer = float = string = ...
 35
 36class LuaValue:
 37    """A lua (or pico8) value for the purpose of constant folding"""
 38
 39    def __init__(m, type, value):
 40        m.type, m.value = type, value
 41
 42    @property
 43    def is_fixnum(m):
 44        return m.type == LuaType.fixnum
 45    @property
 46    def is_integer(m):
 47        return m.type == LuaType.integer
 48    @property
 49    def is_float(m):
 50        return m.type == LuaType.float
 51    @property
 52    def is_float_cvt(m):
 53        return m.type in (LuaType.integer, LuaType.float)
 54    @property
 55    def is_integer_cvt(m):
 56        return (m.type == LuaType.integer or
 57                (m.type == LuaType.float and m.value.is_integer() and is_luaint_in_range(m.value)))
 58    @property
 59    def is_number(m):
 60        return m.type in (LuaType.fixnum, LuaType.integer, LuaType.float)
 61    @property
 62    def is_string(m):
 63        return m.type == LuaType.string
 64    
 65    @property
 66    def is_truthy(m):
 67        return not (m.type == LuaType.nil or (m.type == LuaType.boolean and not m.value))
 68    @property
 69    def float_value(m):
 70        return float(m.value)
 71    @property
 72    def uint_value(m):
 73        return int(m.value) & k_luaint_mask # assumes is_integer_cvt, so can't overflow
 74    @property
 75    def signed_value(m):
 76        if m.is_fixnum:
 77            return fixnum_to_signed(m.value)
 78        else:
 79            return m.value
 80
 81class LuaNil(LuaValue):
 82    def __init__(m):
 83        super().__init__(LuaType.nil, None)
 84
 85class LuaBoolean(LuaValue):
 86    def __init__(m, value):
 87        super().__init__(LuaType.boolean, bool(value))
 88
 89class LuaFixnum(LuaValue):
 90    # (value must be a fixnum)
 91    def __init__(m, value):
 92        super().__init__(LuaType.fixnum, value & k_fixnum_mask)
 93        
 94class LuaInteger(LuaValue):
 95    # (value must be an int)
 96    def __init__(m, value):
 97        super().__init__(LuaType.integer, num_to_luaint(value))
 98        
 99class LuaFloat(LuaValue):
100    # (value must be a float)
101    def __init__(m, value):
102        super().__init__(LuaType.float, float(value))
103        
104class LuaString(LuaValue):
105    # (value must be a string)
106    def __init__(m, value):
107        super().__init__(LuaType.string, value)
108
109k_lua_nil = LuaNil()
110k_lua_true = LuaBoolean(True)
111k_lua_false = LuaBoolean(False)
112k_lua_maxint = 0x7fff
113
114# lua ops - given the language and the parameters, return the result,
115#   or None if unable or unwilling to do the computation
116
117def lua_neg(lang, a):
118    if a.is_fixnum:
119        return LuaFixnum(-a.value)
120    elif a.is_integer:
121        return LuaInteger(-a.value)
122    elif a.is_float:
123        return LuaFloat(-a.value)
124
125def lua_abs(lang, a):
126    if a.is_fixnum and a.value != 0x80000000: # avoid relying on clamping overflow behavior
127        return LuaFixnum(abs(a.signed_value))
128    elif a.is_integer and a.value != -0x8000000000000000: # avoid relying on wrapping overflow behavior
129        return LuaInteger(abs(a.value))
130    elif a.is_float and not float_is_negzero(a.value): # avoid relying on wrong neg-0 behaviour
131        return LuaFloat(abs(a.value))
132
133def lua_floor(lang, a):
134    if a.is_fixnum:
135        return LuaFixnum(a.value & 0xffff0000)
136    elif a.is_integer:
137        return a
138    elif a.is_float:
139        try:
140            result = math.floor(a.value)
141            if is_luaint_in_range(result): # avoid relying on wrapping overflow behavior
142                return LuaInteger(result)
143        except (OverflowError, ValueError):
144            pass
145
146def lua_ceil(lang, a):
147    if a.is_fixnum:
148        result = a.value
149        if result & 0xffff:
150            result = (result & 0xffff0000) + 0x10000
151            if result == 0x80000000: # avoid relying on wrapping overflow behavior
152                return
153        return LuaFixnum(result)
154    elif a.is_integer:
155        return a
156    elif a.is_float:
157        try:
158            result = math.ceil(a.value)
159            if is_luaint_in_range(result): # avoid relying on wrapping overflow behavior
160                return LuaInteger(result)
161        except (OverflowError, ValueError):
162            pass
163
164def lua_add(lang, a, b):
165    if a.is_fixnum and b.is_fixnum:
166        return LuaFixnum(a.value + b.value)
167    elif a.is_integer and b.is_integer:
168        return LuaInteger(a.value + b.value)
169    elif a.is_float_cvt and b.is_float_cvt:
170        result = a.float_value + b.float_value
171        if not math.isnan(result):
172            return LuaFloat(result)
173
174def lua_sub(lang, a, b):
175    if a.is_fixnum and b.is_fixnum:
176        return LuaFixnum(a.value - b.value)
177    elif a.is_integer and b.is_integer:
178        return LuaInteger(a.value - b.value)
179    elif a.is_float_cvt and b.is_float_cvt:
180        result = a.float_value - b.float_value
181        if not math.isnan(result):
182            return LuaFloat(result)
183
184def lua_mul(lang, a, b):
185    if a.is_fixnum and b.is_fixnum:
186        result = (a.signed_value * b.signed_value) >> 16
187        if is_signed_fixnum_in_range(result): # avoid relying on wrapping overflow behavior (or should we?)
188            return LuaFixnum(result)
189    
190    elif a.is_integer and b.is_integer:
191        return LuaInteger(a.value * b.value)
192    elif a.is_float_cvt and b.is_float_cvt:
193        result = a.float_value * b.float_value
194        if not math.isnan(result):
195            return LuaFloat(result)
196
197def _div_trunc(a, b):
198    if (a < 0) != (b < 0):
199        return -(a // -b)
200    else:
201        return a // b
202
203def lua_div(lang, a, b):
204    if a.is_fixnum and b.is_fixnum and b.value != 0: # avoid relying on div-by-0 behavior
205        result = _div_trunc(a.signed_value << 16, b.signed_value)
206        if is_signed_fixnum_in_range(result): # avoid relying on clamping overflow behavior
207            return LuaFixnum(result)
208    
209    elif a.is_float_cvt and b.is_float_cvt and b.value != 0: # avoid relying on non-standard div-by-0 behaviour
210        result = a.float_value / b.float_value
211        if not math.isnan(result):
212            return LuaFloat(result)
213
214def lua_idiv(lang, a, b):
215    if a.is_fixnum and b.is_fixnum:
216        c = lua_div(lang, a, b)
217        if c:
218            return lua_floor(lang, c)
219
220    elif a.is_integer and b.is_integer and b.value != 0: # avoid relying on non-standard div-by-0 behaviour
221        return LuaInteger(a.value // b.value)
222    elif a.is_float_cvt and b.is_float_cvt and b.value != 0: # avoid relying on non-standard div-by-0 behaviour
223        result = a.float_value // b.float_value
224        if not math.isnan(result):
225            return LuaFloat(result)
226
227def lua_mod(lang, a, b):
228    if a.is_fixnum and b.is_fixnum and b.value != 0 and not fixnum_is_negative(b.value): # avoid relying on mod-by-0 behavior, or on non-standard mod-by-neg behavior
229        result = a.signed_value % b.signed_value
230        if is_signed_fixnum_in_range(result): # probably always true, but just in case
231            return LuaFixnum(result)
232    
233    elif a.is_integer and b.is_integer and b.value != 0: # avoid relying on non-standard mod-by-0 behavior
234        return LuaInteger(a.value % b.value)
235    elif a.is_float_cvt and b.is_float_cvt and b.value != 0: # avoid relying on non-standard mod-by-0 behavior
236        result = a.float_value % b.float_value
237        if not math.isnan(result):
238            return LuaFloat(result)
239
240def lua_eq(lang, a, b):
241    if a.is_number and b.is_number:
242        return LuaBoolean(a.value == b.value)
243    else:
244        return LuaBoolean(a.type == b.type and a.value == b.value)
245    
246def lua_not_eq(lang, a, b):
247    if a.is_number and b.is_number:
248        return LuaBoolean(a.value != b.value)
249    else:
250        return LuaBoolean(a.type != b.type or a.value != b.value)
251
252def lua_less(lang, a, b):
253    if a.is_number and b.is_number:
254        return LuaBoolean(a.signed_value < b.signed_value)
255    elif a.is_string and b.is_string:
256        return LuaBoolean(a.value < b.value)
257
258def lua_less_eq(lang, a, b):
259    if a.is_number and b.is_number:
260        return LuaBoolean(a.signed_value <= b.signed_value)
261    elif a.is_string and b.is_string:
262        return LuaBoolean(a.value <= b.value)
263
264def lua_greater(lang, a, b):
265    if a.is_number and b.is_number:
266        return LuaBoolean(a.signed_value > b.signed_value)
267    elif a.is_string and b.is_string:
268        return LuaBoolean(a.value > b.value)
269
270def lua_greater_eq(lang, a, b):
271    if a.is_number and b.is_number:
272        return LuaBoolean(a.signed_value >= b.signed_value)
273    elif a.is_string and b.is_string:
274        return LuaBoolean(a.value >= b.value)
275
276def lua_max(lang, a, b):
277    if a.is_number and b.is_number:
278        return a if a.signed_value > b.signed_value else b
279
280def lua_min(lang, a, b):
281    if a.is_number and b.is_number:
282        return a if a.signed_value < b.signed_value else b
283
284def lua_mid(lang, a, b, c):
285    if a.is_number and b.is_number and c.is_number:
286        av, bv, cv = a.signed_value, b.signed_value, c.signed_value
287        condab, condbc, condac = av < bv, bv < cv, av < cv
288        return b if condab == condbc else a if condab != condac else c
289
290def lua_bin_not(lang, a):
291    if a.is_fixnum:
292        return LuaFixnum(~a.value)
293    elif a.is_integer_cvt:
294        return LuaInteger(~a.uint_value)
295
296def lua_bin_and(lang, a, b):
297    if a.is_fixnum and b.is_fixnum:
298        return LuaFixnum(a.value & b.value)
299    elif a.is_integer_cvt and b.is_integer_cvt:
300        return LuaInteger(a.uint_value & b.uint_value)
301
302def lua_bin_or(lang, a, b):
303    if a.is_fixnum and b.is_fixnum:
304        return LuaFixnum(a.value | b.value)
305    elif a.is_integer_cvt and b.is_integer_cvt:
306        return LuaInteger(a.uint_value | b.uint_value)
307
308def lua_bin_xor(lang, a, b):
309    if a.is_fixnum and b.is_fixnum:
310        return LuaFixnum(a.value ^ b.value)
311    elif a.is_integer_cvt and b.is_integer_cvt:
312        return LuaInteger(a.uint_value ^ b.uint_value)
313
314def lua_shl(lang, a, b):
315    if a.is_fixnum and b.is_fixnum:
316        if fixnum_is_negative(b.value):
317            if not fixnum_is_negative(a.value): # avoid relying on questionable shift-left-neg-by-neg behaviour
318                return lua_lshr(lang, a, lua_neg(lang, b))
319        elif fixnum_is_whole(b.value): # avoid relying on shift-by-fract behaviour
320            return LuaFixnum(a.value << min(fixnum_to_whole(b.value), 32))
321    
322    elif a.is_integer_cvt and b.is_integer_cvt:
323        if b.value < 0:
324            return lua_shr(lang, a, lua_neg(lang, b))
325        else:
326            return LuaInteger(a.uint_value << min(b.uint_value, 64))
327
328def lua_shr(lang, a, b):
329    if a.is_fixnum and b.is_fixnum:
330        if fixnum_is_negative(b.value):
331            return lua_shl(lang, a, lua_neg(lang, b))
332        elif fixnum_is_whole(b.value):
333            return LuaFixnum(fixnum_to_signed(a.value) >> min(fixnum_to_whole(b.value), 32))
334    
335    elif a.is_integer_cvt and b.is_integer_cvt:
336        if b.value < 0:
337            return lua_shl(lang, a, lua_neg(lang, b))
338        elif a.value >= 0: # avoid relying on inconsistent shift-right-neg behaviour (for now?)
339            return LuaInteger(a.uint_value >> min(b.uint_value, 64))
340
341def lua_lshr(lang, a, b):
342    if a.is_fixnum and b.is_fixnum:
343        if fixnum_is_negative(b.value):
344            return lua_shl(lang, a, lua_neg(lang, b))
345        elif fixnum_is_whole(b.value):
346            return LuaFixnum(a.value >> min(fixnum_to_whole(b.value), 32))
347    # not yet(?) impl. for picotron?
348
349def lua_rotl(lang, a, b):
350    if a.is_fixnum and b.is_fixnum:
351        if fixnum_is_negative(b.value):
352            return lua_rotr(lang, a, lua_neg(lang, b))
353        elif fixnum_is_whole(b.value):
354            return LuaFixnum(rotate_left(a.value, fixnum_to_whole(b.value), 32))
355    # not yet(?) impl. for picotron?
356
357def lua_rotr(lang, a, b):
358    if a.is_fixnum and b.is_fixnum:
359        if fixnum_is_negative(b.value):
360            return lua_rotl(lang, a, lua_neg(lang, b))
361        elif fixnum_is_whole(b.value):
362            return LuaFixnum(rotate_right(a.value, fixnum_to_whole(b.value), 32))
363    # not yet(?) impl. for picotron?
364
365def lua_not(lang, a):
366    return LuaBoolean(not a.is_truthy)
367
368def lua_and(lang, a, b):
369    return b if a.is_truthy else a
370    
371def lua_or(lang, a, b):
372    return a if a.is_truthy else b
373
374def lua_len(lang, a):
375    if a.is_string:
376        if lang == Language.pico8 and len(a.value) <= k_lua_maxint: # avoid relying on long string behavior
377            return LuaFixnum(len(a.value) << 16)
378        elif lang == Language.picotron:
379            return LuaInteger(len(encode_luastr(a.value)))
380
381def _lua_tostr(a):
382    if a.is_string:
383        return a
384    elif a.is_fixnum and fixnum_is_whole(a.value): # avoid relying on fract. tostr
385        return LuaString(format_fixnum(a.value, base=10, sign='-' if fixnum_is_negative(a.value) else ''))
386    elif a.is_integer:
387        return LuaString(format_luanum(a.value, base=10, sign='-' if a.value < 0 else ''))
388    # avoid relying on float tostr
389
390def lua_cat(lang, a, b):
391    a, b = _lua_tostr(a), _lua_tostr(b)
392    if a and b:
393        return LuaString(a.value + b.value)
394
395k_const_unary_ops = {
396    "-": lua_neg,
397    "~": lua_bin_not,
398    "not": lua_not,
399    "#": lua_len,
400}
401
402k_const_binary_ops = {
403    "or": lua_or,
404    "and": lua_and,
405    "!=": lua_not_eq,
406    "~=": lua_not_eq,
407    "==": lua_eq,
408    "<": lua_less,
409    "<=": lua_less_eq,
410    ">": lua_greater,
411    ">=": lua_greater_eq,
412    "|": lua_bin_or,
413    "^^": lua_bin_xor,
414    "~": lua_bin_xor,
415    "&": lua_bin_and,
416    "<<": lua_shl,
417    ">>": lua_shr,
418    ">>>": lua_lshr,
419    "<<>": lua_rotl,
420    ">><": lua_rotr,
421    "..": lua_cat,
422    "+": lua_add,
423    "-": lua_sub,
424    "*": lua_mul,
425    "/": lua_div,
426    "\\": lua_idiv,
427    "%": lua_mod,
428}
429
430k_const_globals = {
431    "abs": (lua_abs, 1, None),
432    "band": (lua_bin_and, 2, Language.pico8),
433    "bnot": (lua_bin_not, 1, Language.pico8),
434    "bor": (lua_bin_or, 2, Language.pico8),
435    "bxor": (lua_bin_xor, 2, Language.pico8),
436    "ceil": (lua_ceil, 1, None),
437    "flr": (lua_floor, 1, None),
438    "lshr": (lua_lshr, 2, Language.pico8),
439    "max": (lua_max, 2, None),
440    "mid": (lua_mid, 3, None),
441    "min": (lua_min, 2, None),
442    "rotl": (lua_rotl, 2, Language.pico8),
443    "rotr": (lua_rotr, 2, Language.pico8),
444    "shl": (lua_shl, 2, Language.pico8),
445    "shr": (lua_shr, 2, Language.pico8),
446}
447
448def const_from_token(token):
449    if token.type == TokenType.number:
450        if token.lang == Language.picotron:
451            if isinstance(token.parsed_value, int):
452                return LuaInteger(token.parsed_value)
453            else:
454                return LuaFloat(token.parsed_value)
455        else:
456            return LuaFixnum(token.parsed_value)
457    elif token.type == TokenType.string:
458        return LuaString(token.parsed_value)
459    elif token.value == "nil":
460        return k_lua_nil
461    elif token.value == "true":
462        return k_lua_true
463    elif token.value == "false":
464        return k_lua_false
465    else:
466        return None
467
468def get_const(node):
469    if node.type == NodeType.const:
470        token = node.token
471        constval = const_from_token(token)
472        assert constval, "unexpected const token: %s" % token
473        return constval
474    elif node.type == NodeType.group:
475        return get_const(node.child)
476    else:
477        return getattr(node, "worse_const", None)
478
479def set_const(node, value, ctxt, focus, force):
480    if value.is_number:
481        token = ConstToken(TokenType.number, value.value, node)
482    elif value.type == LuaType.string:
483        token = ConstToken(TokenType.string, value.value, node)
484    elif value.type == LuaType.boolean:
485        token = Token.synthetic(TokenType.keyword, "true" if value.value else "false", node)
486    elif value.type == LuaType.nil:
487        token = Token.synthetic(TokenType.keyword, "nil", node)
488    else:
489        assert False, "unexpected const value: %s" % value
490    
491    if focus == Focus.chars and not force:
492        # the new token may take more chars than before
493        # though it may still be useful when further folded
494        if len(token.value) > len(output_node(node, ctxt)):
495            node.worse_const = value
496            return
497
498    node.replace_with(create_const_node(token))
499
500def fixup_syntax_between(parent, prev, next):
501    nextt = next.first_token()
502    if nextt and nextt.value == "(":
503        prevt = prev.last_token()
504        if prevt.value in (")", "]") or prevt.type == TokenType.ident:
505            i = parent.children.index(prev)
506            parent.insert_token(i+1, TokenType.punct, ";", near_next=True)
507
508def fixup_syntax_after_remove(stmt):
509    # after removing stmt (or even just part of stmt), extra semicolons may need to be inserted
510    parent = stmt.parent
511    if parent.type == NodeType.block:
512        stmt_n = len(parent.stmts)
513        stmt_i = parent.stmts.index(stmt)
514        if stmt.type is None:
515            if 0 < stmt_i < stmt_n - 1:
516                fixup_syntax_between(parent, parent.stmts[stmt_i-1], parent.stmts[stmt_i+1])
517        else:
518            if stmt_i > 0:
519                fixup_syntax_between(parent, parent.stmts[stmt_i-1], stmt)
520            if stmt_i < stmt_n - 1:
521                fixup_syntax_between(parent, stmt, parent.stmts[stmt_i+1])
522
523def erase_assign_targets(node, indices):
524    if len(node.targets) < len(node.sources) and len(indices) == len(node.targets):
525        indices.pop() # can't deal with this easily otherwise
526
527    def delete_array_item(node, array, i):
528        child_i = node.children.index(array[i])
529        node.remove_child(child_i)
530        
531        # need to delete comma too
532        if i > 0:
533            node.remove_token(child_i - 1, ",")
534        elif len(array) > 1:
535            node.remove_token(child_i, ",")
536        elif node.type == NodeType.local and array is node.sources:
537            node.remove_token(child_i - 1, "=")
538        
539        del array[i]
540
541    for i in reversed(indices):
542        delete_array_item(node, node.targets, i)
543        if i < len(node.sources):
544            delete_array_item(node, node.sources, i)
545    
546    if not node.targets and not node.sources:
547        node.erase()
548    elif not node.sources and node.type != NodeType.local:
549        nil_token = Token.synthetic(TokenType.keyword, "nil", node, append=True)
550        node.sources.append(create_const_node(nil_token))
551        node.append_existing(node.sources[-1])
552    else:
553        assert node.targets # due to the pop above
554    
555    fixup_syntax_after_remove(node)
556
557def create_const_node(token):
558    return Node(NodeType.const, [token], token=token)
559
560def create_do_node_if_needed(node):
561    needed = False
562
563    def check_do_needed(node):
564        nonlocal needed
565        if node.type == NodeType.var and node.new:
566            needed = True
567        elif node.type in (NodeType.return_, NodeType.break_, NodeType.goto):
568            needed = True
569        elif node.type in (NodeType.if_, NodeType.elseif, NodeType.while_, NodeType.repeat, NodeType.for_, NodeType.for_in, NodeType.do):
570            return k_skip_children
571        elif node.type == NodeType.function:
572            if node.target:
573                node.target.traverse_nodes(pre=check_do_needed)
574            return k_skip_children
575
576    node.traverse_nodes(pre=check_do_needed)
577    if needed:
578        do_token = Token.synthetic(TokenType.keyword, "do", node, prepend=True)
579        end_token = Token.synthetic(TokenType.keyword, "end", node, append=True)
580        node = Node(NodeType.do, [do_token, node, end_token], body=node)
581    return node
582
583def create_else_node(node, short=False):
584    else_token = Token.synthetic(TokenType.keyword, "else", node, prepend=True)
585    end_token = Token.synthetic(TokenType.keyword, "end", node, append=True)
586    return Node(NodeType.else_, [else_token, node, end_token], body=node, short=short)
587
588def remove_else_node(node):
589    assert node.children[-1] is node.else_
590    node.remove_child(-1)
591    node.else_ = None
592    end_token = Token.synthetic(TokenType.keyword, "end", node, append=True)
593    node.append_existing(end_token)
594
595def fold_consts(ctxt, minify_opts, root, errors):
596    lang = ctxt.lang
597    
598    focus = Focus(minify_opts.get("focus"))
599    safe_builtins = minify_opts.get("safe-builtins", False)
600
601    def add_error(msg, node):
602        errors.append(Error(msg, node))
603
604    in_const_ctxt = 0
605    const_ctxt_fail = None
606
607    def skip_special(node):
608        if node.type in (NodeType.local, NodeType.assign):
609            # we traverse these specially in update_node_constval
610            return k_skip_children
611
612    def update_node_constval(node):
613        nonlocal in_const_ctxt, const_ctxt_fail
614        # we don't check NodeType.const/group until needed (in get_const)
615
616        if node.type == NodeType.unary_op:
617            func = k_const_unary_ops.get(node.op, None)
618            if func:
619                child_const = get_const(node.child)
620                if child_const:
621                    constval = func(lang, child_const)
622                    if constval:
623                        set_const(node, constval, ctxt, focus, in_const_ctxt)
624
625        elif node.type == NodeType.binary_op:
626            func = k_const_binary_ops.get(node.op, None)
627            if func:
628                left_const = get_const(node.left)
629                if left_const: # (optimization)
630                    right_const = get_const(node.right)
631                    if right_const:
632                        constval = func(lang, left_const, right_const)
633                    elif func in (lua_and, lua_or): # short-circuit
634                        constval = func(lang, left_const, node.right)
635                    else:
636                        constval = None
637                    
638                    if constval:
639                        if constval is node.right:
640                            node.replace_with(node.right)
641                        else:
642                            set_const(node, constval, ctxt, focus, in_const_ctxt)
643
644        elif node.type == NodeType.var and node.var and not node.new and not node.assignment:
645            if node.var.constval:
646                set_const(node, node.var.constval, ctxt, focus, in_const_ctxt or node.var.is_const)
647            elif node.var.is_const:
648                add_error(f"'{node.name}' is marked as constant but is used above where it is assigned to", node)
649                node.var.is_const = False
650
651        elif node.type in (NodeType.local, NodeType.assign):
652            visit_assign(node)
653        
654        # we assume that in a const context, calls are always to builtins
655        elif (node.type == NodeType.call and node.func.type == NodeType.var and is_root_global_or_builtin_local(node.func) and
656                not node.func.var.reassigned and (not root.has_env or not safe_builtins or in_const_ctxt)):
657            func, num_args, func_lang = k_const_globals.get(node.func.name, (None, None, None))
658            if func and (num_args is None or num_args == len(node.args)) and (func_lang is None or func_lang == lang):
659                arg_consts = []
660                for arg in node.args:
661                    arg_const = get_const(arg)
662                    if arg_const:
663                        arg_consts.append(arg_const)
664                    else:
665                        break # (optimization)
666                else:
667                    constval = func(lang, *arg_consts)
668                    if constval:
669                        set_const(node, constval, ctxt, focus, in_const_ctxt)
670        
671        elif node.type in (NodeType.if_, NodeType.elseif):
672            constval = get_const(node.cond)
673            if constval:
674                if constval.is_truthy:
675                    if node.else_:
676                        node.else_.erase(KeepCommentFlags.first)
677                    
678                    if node.type == NodeType.if_:
679                        node.replace_with(create_do_node_if_needed(node.then))
680                    else:
681                        node.replace_with(create_else_node(node.then, node.short))
682                else:
683                    node.then.erase(keep_comments=False)
684                    if node.else_:
685                        node.else_.first_token().remove_comments()
686
687                    if node.type == NodeType.if_:
688                        if not node.else_:
689                            node.erase(KeepCommentFlags.first)
690                        elif node.else_.type == NodeType.else_:
691                            node.replace_with(create_do_node_if_needed(node.else_.body))
692                        else: # elseif
693                            node.replace_with(node.else_)
694                            node.modify_token(0, "if", expected="elseif")
695                            node.type = NodeType.if_
696                    else:
697                        if not node.else_:
698                            remove_else_node(node.parent)
699                        else:
700                            node.replace_with(node.else_)
701    
702        # store which node was expected to be const but isn't
703        if in_const_ctxt and node.type != NodeType.const and const_ctxt_fail is None:
704            if node.parent.type == NodeType.call and node == node.parent.func:
705                pass
706            else:
707                const_ctxt_fail = node
708
709    def visit_assign(node):
710        nonlocal in_const_ctxt, const_ctxt_fail
711        erasable = []
712
713        for i, target in enumerate(node.targets):
714            target.traverse_nodes(pre=skip_special, post=update_node_constval)
715
716            if target.type == NodeType.var:
717                is_const_ctxt = target.var.is_const
718                # (even if a global is assigned once, it's hard to tell if all its uses are after the assignment, so we close globals under --[[const]])
719                is_const = ((target.kind == VarKind.local and not target.var.reassigned) or
720                            (is_const_ctxt and target.kind == VarKind.global_ and target.var.reassigned <= 1 and target.name not in ctxt.builtins))
721            else:
722                is_const = is_const_ctxt = False
723
724            if is_const_ctxt:
725                in_const_ctxt += 1
726                const_ctxt_fail = None
727                
728            constval = None
729            if is_const and is_const_ctxt != False:
730                if i < len(node.sources):
731                    source = node.sources[i]
732                    source.traverse_nodes(pre=skip_special, post=update_node_constval)
733                    constval = get_const(source)
734                elif not (node.sources and is_vararg_expr(node.sources[-1])):
735                    constval = k_lua_nil
736            else:
737                if i < len(node.sources):
738                    node.sources[i].traverse_nodes(pre=skip_special, post=update_node_constval)
739            
740            if constval:
741                const_unwanted = isinstance(constval, LuaString) or focus == Focus.chars # cases likely to make char count increase too much
742                if is_const_ctxt or not const_unwanted:
743                    erasable.append(i)
744                    if not target.var.constval: # may've been set to something else through ctxt.consts
745                        target.var.constval = constval
746            else:
747                if is_const_ctxt:
748                    reason = ""
749                    if const_ctxt_fail:
750                        reason = f" due to '{const_ctxt_fail.source_text}'"
751                    elif not is_const:
752                        reason = f" due to being reassigned"
753                    add_error(f"Local '{target.name}' is marked as const but its value cannot be determined" + reason, target)
754                    target.var.is_const = False
755                    
756            if is_const_ctxt:
757                in_const_ctxt -= 1
758                const_ctxt_fail = None
759        
760        for i, source in enumerate(node.sources):
761            if i >= len(node.targets): # else, traversed above
762                source.traverse_nodes(pre=skip_special, post=update_node_constval)
763        
764        if erasable:
765            erase_assign_targets(node, erasable)
766
767    root.traverse_nodes(pre=skip_special, post=update_node_constval)
768
769def parse_constant(value, lang, as_str=False):
770    if as_str:
771        return LuaString(to_langstr(value, lang))
772
773    tokens, errors = tokenize(Source("<const>", to_langstr(value, lang)), lang=lang)
774    if not errors:
775        token = None
776        if len(tokens) == 1:
777            token = tokens[0]
778        elif len(tokens) == 2 and tokens[0].value in ("-", "~") and tokens[1].type == TokenType.number:
779            token = tokens[1]
780            token.value = tokens[0].value + token.value
781                    
782        if token:
783            constval = const_from_token(token)
784            if constval:
785                return constval
class ConstToken(pico_tokenize.Token):
11class ConstToken(Token):
12    """A token that's created from a value, instead of from a string"""
13
14    def __init__(m, type, parsed_value, other):
15        super().__init__(type, None, other.source, other.idx, other.endidx, other.vline, other.lang, modified=True)
16        m.parsed_value = parsed_value
17        lazy_property.clear(m, "value")
18
19    @lazy_property
20    def value(m): # used during going over chars for rename (tsk...) and for output when not minify-tokens
21                  # (but not used for output under minify-tokens)
22        if isinstance(m.parsed_value, (int, float)):
23            allow_unary = can_replace_with_unary(m.parent) if m.parent else True
24            format_num = format_fixnum if m.lang == Language.pico8 else format_luanum
25            return format_num(m.parsed_value, sign=None if allow_unary else "")
26        else:
27            return format_string_literal(m.parsed_value, long=False)
28
29    @post_property_change
30    def parent(m, old, new):
31        lazy_property.clear(m, "value")

A token that's created from a value, instead of from a string

ConstToken(type, parsed_value, other)
14    def __init__(m, type, parsed_value, other):
15        super().__init__(type, None, other.source, other.idx, other.endidx, other.vline, other.lang, modified=True)
16        m.parsed_value = parsed_value
17        lazy_property.clear(m, "value")
def value(unknown):

Method decorator that turns it into a lazily-evaluated property

parent

Method decorator that creates a field-backed read-write property that calls the decorated method when changed (going by == equality), with the old and new values

class LuaType(utils.Enum):
33class LuaType(Enum):
34    """A lua (or pico8) type for the purpose of constant folding"""
35    nil = boolean = fixnum = integer = float = string = ...

A lua (or pico8) type for the purpose of constant folding

LuaType(value)
172        def __init__(m, value):
173            if value in full_value_name_map:
174                m.value = value
175            elif value in full_name_value_map:
176                m.value = full_name_value_map[value]
177            else:
178                raise ValueError(f"{value} not value of {cls_name}")
value
nil = LuaType.nil
boolean = LuaType.boolean
fixnum = LuaType.fixnum
integer = LuaType.integer
float = LuaType.float
string = LuaType.string
class LuaValue:
37class LuaValue:
38    """A lua (or pico8) value for the purpose of constant folding"""
39
40    def __init__(m, type, value):
41        m.type, m.value = type, value
42
43    @property
44    def is_fixnum(m):
45        return m.type == LuaType.fixnum
46    @property
47    def is_integer(m):
48        return m.type == LuaType.integer
49    @property
50    def is_float(m):
51        return m.type == LuaType.float
52    @property
53    def is_float_cvt(m):
54        return m.type in (LuaType.integer, LuaType.float)
55    @property
56    def is_integer_cvt(m):
57        return (m.type == LuaType.integer or
58                (m.type == LuaType.float and m.value.is_integer() and is_luaint_in_range(m.value)))
59    @property
60    def is_number(m):
61        return m.type in (LuaType.fixnum, LuaType.integer, LuaType.float)
62    @property
63    def is_string(m):
64        return m.type == LuaType.string
65    
66    @property
67    def is_truthy(m):
68        return not (m.type == LuaType.nil or (m.type == LuaType.boolean and not m.value))
69    @property
70    def float_value(m):
71        return float(m.value)
72    @property
73    def uint_value(m):
74        return int(m.value) & k_luaint_mask # assumes is_integer_cvt, so can't overflow
75    @property
76    def signed_value(m):
77        if m.is_fixnum:
78            return fixnum_to_signed(m.value)
79        else:
80            return m.value

A lua (or pico8) value for the purpose of constant folding

LuaValue(type, value)
40    def __init__(m, type, value):
41        m.type, m.value = type, value
is_fixnum
43    @property
44    def is_fixnum(m):
45        return m.type == LuaType.fixnum
is_integer
46    @property
47    def is_integer(m):
48        return m.type == LuaType.integer
is_float
49    @property
50    def is_float(m):
51        return m.type == LuaType.float
is_float_cvt
52    @property
53    def is_float_cvt(m):
54        return m.type in (LuaType.integer, LuaType.float)
is_integer_cvt
55    @property
56    def is_integer_cvt(m):
57        return (m.type == LuaType.integer or
58                (m.type == LuaType.float and m.value.is_integer() and is_luaint_in_range(m.value)))
is_number
59    @property
60    def is_number(m):
61        return m.type in (LuaType.fixnum, LuaType.integer, LuaType.float)
is_string
62    @property
63    def is_string(m):
64        return m.type == LuaType.string
is_truthy
66    @property
67    def is_truthy(m):
68        return not (m.type == LuaType.nil or (m.type == LuaType.boolean and not m.value))
float_value
69    @property
70    def float_value(m):
71        return float(m.value)
uint_value
72    @property
73    def uint_value(m):
74        return int(m.value) & k_luaint_mask # assumes is_integer_cvt, so can't overflow
signed_value
75    @property
76    def signed_value(m):
77        if m.is_fixnum:
78            return fixnum_to_signed(m.value)
79        else:
80            return m.value
class LuaNil(LuaValue):
82class LuaNil(LuaValue):
83    def __init__(m):
84        super().__init__(LuaType.nil, None)

A lua (or pico8) value for the purpose of constant folding

class LuaBoolean(LuaValue):
86class LuaBoolean(LuaValue):
87    def __init__(m, value):
88        super().__init__(LuaType.boolean, bool(value))

A lua (or pico8) value for the purpose of constant folding

LuaBoolean(value)
87    def __init__(m, value):
88        super().__init__(LuaType.boolean, bool(value))
class LuaFixnum(LuaValue):
90class LuaFixnum(LuaValue):
91    # (value must be a fixnum)
92    def __init__(m, value):
93        super().__init__(LuaType.fixnum, value & k_fixnum_mask)

A lua (or pico8) value for the purpose of constant folding

LuaFixnum(value)
92    def __init__(m, value):
93        super().__init__(LuaType.fixnum, value & k_fixnum_mask)
class LuaInteger(LuaValue):
95class LuaInteger(LuaValue):
96    # (value must be an int)
97    def __init__(m, value):
98        super().__init__(LuaType.integer, num_to_luaint(value))

A lua (or pico8) value for the purpose of constant folding

LuaInteger(value)
97    def __init__(m, value):
98        super().__init__(LuaType.integer, num_to_luaint(value))
class LuaFloat(LuaValue):
100class LuaFloat(LuaValue):
101    # (value must be a float)
102    def __init__(m, value):
103        super().__init__(LuaType.float, float(value))

A lua (or pico8) value for the purpose of constant folding

LuaFloat(value)
102    def __init__(m, value):
103        super().__init__(LuaType.float, float(value))
class LuaString(LuaValue):
105class LuaString(LuaValue):
106    # (value must be a string)
107    def __init__(m, value):
108        super().__init__(LuaType.string, value)

A lua (or pico8) value for the purpose of constant folding

LuaString(value)
107    def __init__(m, value):
108        super().__init__(LuaType.string, value)
k_lua_nil = <LuaNil object>
k_lua_true = <LuaBoolean object>
k_lua_false = <LuaBoolean object>
k_lua_maxint = 32767
def lua_neg(lang, a):
118def lua_neg(lang, a):
119    if a.is_fixnum:
120        return LuaFixnum(-a.value)
121    elif a.is_integer:
122        return LuaInteger(-a.value)
123    elif a.is_float:
124        return LuaFloat(-a.value)
def lua_abs(lang, a):
126def lua_abs(lang, a):
127    if a.is_fixnum and a.value != 0x80000000: # avoid relying on clamping overflow behavior
128        return LuaFixnum(abs(a.signed_value))
129    elif a.is_integer and a.value != -0x8000000000000000: # avoid relying on wrapping overflow behavior
130        return LuaInteger(abs(a.value))
131    elif a.is_float and not float_is_negzero(a.value): # avoid relying on wrong neg-0 behaviour
132        return LuaFloat(abs(a.value))
def lua_floor(lang, a):
134def lua_floor(lang, a):
135    if a.is_fixnum:
136        return LuaFixnum(a.value & 0xffff0000)
137    elif a.is_integer:
138        return a
139    elif a.is_float:
140        try:
141            result = math.floor(a.value)
142            if is_luaint_in_range(result): # avoid relying on wrapping overflow behavior
143                return LuaInteger(result)
144        except (OverflowError, ValueError):
145            pass
def lua_ceil(lang, a):
147def lua_ceil(lang, a):
148    if a.is_fixnum:
149        result = a.value
150        if result & 0xffff:
151            result = (result & 0xffff0000) + 0x10000
152            if result == 0x80000000: # avoid relying on wrapping overflow behavior
153                return
154        return LuaFixnum(result)
155    elif a.is_integer:
156        return a
157    elif a.is_float:
158        try:
159            result = math.ceil(a.value)
160            if is_luaint_in_range(result): # avoid relying on wrapping overflow behavior
161                return LuaInteger(result)
162        except (OverflowError, ValueError):
163            pass
def lua_add(lang, a, b):
165def lua_add(lang, a, b):
166    if a.is_fixnum and b.is_fixnum:
167        return LuaFixnum(a.value + b.value)
168    elif a.is_integer and b.is_integer:
169        return LuaInteger(a.value + b.value)
170    elif a.is_float_cvt and b.is_float_cvt:
171        result = a.float_value + b.float_value
172        if not math.isnan(result):
173            return LuaFloat(result)
def lua_sub(lang, a, b):
175def lua_sub(lang, a, b):
176    if a.is_fixnum and b.is_fixnum:
177        return LuaFixnum(a.value - b.value)
178    elif a.is_integer and b.is_integer:
179        return LuaInteger(a.value - b.value)
180    elif a.is_float_cvt and b.is_float_cvt:
181        result = a.float_value - b.float_value
182        if not math.isnan(result):
183            return LuaFloat(result)
def lua_mul(lang, a, b):
185def lua_mul(lang, a, b):
186    if a.is_fixnum and b.is_fixnum:
187        result = (a.signed_value * b.signed_value) >> 16
188        if is_signed_fixnum_in_range(result): # avoid relying on wrapping overflow behavior (or should we?)
189            return LuaFixnum(result)
190    
191    elif a.is_integer and b.is_integer:
192        return LuaInteger(a.value * b.value)
193    elif a.is_float_cvt and b.is_float_cvt:
194        result = a.float_value * b.float_value
195        if not math.isnan(result):
196            return LuaFloat(result)
def lua_div(lang, a, b):
204def lua_div(lang, a, b):
205    if a.is_fixnum and b.is_fixnum and b.value != 0: # avoid relying on div-by-0 behavior
206        result = _div_trunc(a.signed_value << 16, b.signed_value)
207        if is_signed_fixnum_in_range(result): # avoid relying on clamping overflow behavior
208            return LuaFixnum(result)
209    
210    elif a.is_float_cvt and b.is_float_cvt and b.value != 0: # avoid relying on non-standard div-by-0 behaviour
211        result = a.float_value / b.float_value
212        if not math.isnan(result):
213            return LuaFloat(result)
def lua_idiv(lang, a, b):
215def lua_idiv(lang, a, b):
216    if a.is_fixnum and b.is_fixnum:
217        c = lua_div(lang, a, b)
218        if c:
219            return lua_floor(lang, c)
220
221    elif a.is_integer and b.is_integer and b.value != 0: # avoid relying on non-standard div-by-0 behaviour
222        return LuaInteger(a.value // b.value)
223    elif a.is_float_cvt and b.is_float_cvt and b.value != 0: # avoid relying on non-standard div-by-0 behaviour
224        result = a.float_value // b.float_value
225        if not math.isnan(result):
226            return LuaFloat(result)
def lua_mod(lang, a, b):
228def lua_mod(lang, a, b):
229    if a.is_fixnum and b.is_fixnum and b.value != 0 and not fixnum_is_negative(b.value): # avoid relying on mod-by-0 behavior, or on non-standard mod-by-neg behavior
230        result = a.signed_value % b.signed_value
231        if is_signed_fixnum_in_range(result): # probably always true, but just in case
232            return LuaFixnum(result)
233    
234    elif a.is_integer and b.is_integer and b.value != 0: # avoid relying on non-standard mod-by-0 behavior
235        return LuaInteger(a.value % b.value)
236    elif a.is_float_cvt and b.is_float_cvt and b.value != 0: # avoid relying on non-standard mod-by-0 behavior
237        result = a.float_value % b.float_value
238        if not math.isnan(result):
239            return LuaFloat(result)
def lua_eq(lang, a, b):
241def lua_eq(lang, a, b):
242    if a.is_number and b.is_number:
243        return LuaBoolean(a.value == b.value)
244    else:
245        return LuaBoolean(a.type == b.type and a.value == b.value)
def lua_not_eq(lang, a, b):
247def lua_not_eq(lang, a, b):
248    if a.is_number and b.is_number:
249        return LuaBoolean(a.value != b.value)
250    else:
251        return LuaBoolean(a.type != b.type or a.value != b.value)
def lua_less(lang, a, b):
253def lua_less(lang, a, b):
254    if a.is_number and b.is_number:
255        return LuaBoolean(a.signed_value < b.signed_value)
256    elif a.is_string and b.is_string:
257        return LuaBoolean(a.value < b.value)
def lua_less_eq(lang, a, b):
259def lua_less_eq(lang, a, b):
260    if a.is_number and b.is_number:
261        return LuaBoolean(a.signed_value <= b.signed_value)
262    elif a.is_string and b.is_string:
263        return LuaBoolean(a.value <= b.value)
def lua_greater(lang, a, b):
265def lua_greater(lang, a, b):
266    if a.is_number and b.is_number:
267        return LuaBoolean(a.signed_value > b.signed_value)
268    elif a.is_string and b.is_string:
269        return LuaBoolean(a.value > b.value)
def lua_greater_eq(lang, a, b):
271def lua_greater_eq(lang, a, b):
272    if a.is_number and b.is_number:
273        return LuaBoolean(a.signed_value >= b.signed_value)
274    elif a.is_string and b.is_string:
275        return LuaBoolean(a.value >= b.value)
def lua_max(lang, a, b):
277def lua_max(lang, a, b):
278    if a.is_number and b.is_number:
279        return a if a.signed_value > b.signed_value else b
def lua_min(lang, a, b):
281def lua_min(lang, a, b):
282    if a.is_number and b.is_number:
283        return a if a.signed_value < b.signed_value else b
def lua_mid(lang, a, b, c):
285def lua_mid(lang, a, b, c):
286    if a.is_number and b.is_number and c.is_number:
287        av, bv, cv = a.signed_value, b.signed_value, c.signed_value
288        condab, condbc, condac = av < bv, bv < cv, av < cv
289        return b if condab == condbc else a if condab != condac else c
def lua_bin_not(lang, a):
291def lua_bin_not(lang, a):
292    if a.is_fixnum:
293        return LuaFixnum(~a.value)
294    elif a.is_integer_cvt:
295        return LuaInteger(~a.uint_value)
def lua_bin_and(lang, a, b):
297def lua_bin_and(lang, a, b):
298    if a.is_fixnum and b.is_fixnum:
299        return LuaFixnum(a.value & b.value)
300    elif a.is_integer_cvt and b.is_integer_cvt:
301        return LuaInteger(a.uint_value & b.uint_value)
def lua_bin_or(lang, a, b):
303def lua_bin_or(lang, a, b):
304    if a.is_fixnum and b.is_fixnum:
305        return LuaFixnum(a.value | b.value)
306    elif a.is_integer_cvt and b.is_integer_cvt:
307        return LuaInteger(a.uint_value | b.uint_value)
def lua_bin_xor(lang, a, b):
309def lua_bin_xor(lang, a, b):
310    if a.is_fixnum and b.is_fixnum:
311        return LuaFixnum(a.value ^ b.value)
312    elif a.is_integer_cvt and b.is_integer_cvt:
313        return LuaInteger(a.uint_value ^ b.uint_value)
def lua_shl(lang, a, b):
315def lua_shl(lang, a, b):
316    if a.is_fixnum and b.is_fixnum:
317        if fixnum_is_negative(b.value):
318            if not fixnum_is_negative(a.value): # avoid relying on questionable shift-left-neg-by-neg behaviour
319                return lua_lshr(lang, a, lua_neg(lang, b))
320        elif fixnum_is_whole(b.value): # avoid relying on shift-by-fract behaviour
321            return LuaFixnum(a.value << min(fixnum_to_whole(b.value), 32))
322    
323    elif a.is_integer_cvt and b.is_integer_cvt:
324        if b.value < 0:
325            return lua_shr(lang, a, lua_neg(lang, b))
326        else:
327            return LuaInteger(a.uint_value << min(b.uint_value, 64))
def lua_shr(lang, a, b):
329def lua_shr(lang, a, b):
330    if a.is_fixnum and b.is_fixnum:
331        if fixnum_is_negative(b.value):
332            return lua_shl(lang, a, lua_neg(lang, b))
333        elif fixnum_is_whole(b.value):
334            return LuaFixnum(fixnum_to_signed(a.value) >> min(fixnum_to_whole(b.value), 32))
335    
336    elif a.is_integer_cvt and b.is_integer_cvt:
337        if b.value < 0:
338            return lua_shl(lang, a, lua_neg(lang, b))
339        elif a.value >= 0: # avoid relying on inconsistent shift-right-neg behaviour (for now?)
340            return LuaInteger(a.uint_value >> min(b.uint_value, 64))
def lua_lshr(lang, a, b):
342def lua_lshr(lang, a, b):
343    if a.is_fixnum and b.is_fixnum:
344        if fixnum_is_negative(b.value):
345            return lua_shl(lang, a, lua_neg(lang, b))
346        elif fixnum_is_whole(b.value):
347            return LuaFixnum(a.value >> min(fixnum_to_whole(b.value), 32))
348    # not yet(?) impl. for picotron?
def lua_rotl(lang, a, b):
350def lua_rotl(lang, a, b):
351    if a.is_fixnum and b.is_fixnum:
352        if fixnum_is_negative(b.value):
353            return lua_rotr(lang, a, lua_neg(lang, b))
354        elif fixnum_is_whole(b.value):
355            return LuaFixnum(rotate_left(a.value, fixnum_to_whole(b.value), 32))
356    # not yet(?) impl. for picotron?
def lua_rotr(lang, a, b):
358def lua_rotr(lang, a, b):
359    if a.is_fixnum and b.is_fixnum:
360        if fixnum_is_negative(b.value):
361            return lua_rotl(lang, a, lua_neg(lang, b))
362        elif fixnum_is_whole(b.value):
363            return LuaFixnum(rotate_right(a.value, fixnum_to_whole(b.value), 32))
364    # not yet(?) impl. for picotron?
def lua_not(lang, a):
366def lua_not(lang, a):
367    return LuaBoolean(not a.is_truthy)
def lua_and(lang, a, b):
369def lua_and(lang, a, b):
370    return b if a.is_truthy else a
def lua_or(lang, a, b):
372def lua_or(lang, a, b):
373    return a if a.is_truthy else b
def lua_len(lang, a):
375def lua_len(lang, a):
376    if a.is_string:
377        if lang == Language.pico8 and len(a.value) <= k_lua_maxint: # avoid relying on long string behavior
378            return LuaFixnum(len(a.value) << 16)
379        elif lang == Language.picotron:
380            return LuaInteger(len(encode_luastr(a.value)))
def lua_cat(lang, a, b):
391def lua_cat(lang, a, b):
392    a, b = _lua_tostr(a), _lua_tostr(b)
393    if a and b:
394        return LuaString(a.value + b.value)
k_const_unary_ops = {'-': <function lua_neg>, '~': <function lua_bin_not>, 'not': <function lua_not>, '#': <function lua_len>}
k_const_binary_ops = {'or': <function lua_or>, 'and': <function lua_and>, '!=': <function lua_not_eq>, '~=': <function lua_not_eq>, '==': <function lua_eq>, '<': <function lua_less>, '<=': <function lua_less_eq>, '>': <function lua_greater>, '>=': <function lua_greater_eq>, '|': <function lua_bin_or>, '^^': <function lua_bin_xor>, '~': <function lua_bin_xor>, '&': <function lua_bin_and>, '<<': <function lua_shl>, '>>': <function lua_shr>, '>>>': <function lua_lshr>, '<<>': <function lua_rotl>, '>><': <function lua_rotr>, '..': <function lua_cat>, '+': <function lua_add>, '-': <function lua_sub>, '*': <function lua_mul>, '/': <function lua_div>, '\\': <function lua_idiv>, '%': <function lua_mod>}
k_const_globals = {'abs': (<function lua_abs>, 1, None), 'band': (<function lua_bin_and>, 2, Language.pico8), 'bnot': (<function lua_bin_not>, 1, Language.pico8), 'bor': (<function lua_bin_or>, 2, Language.pico8), 'bxor': (<function lua_bin_xor>, 2, Language.pico8), 'ceil': (<function lua_ceil>, 1, None), 'flr': (<function lua_floor>, 1, None), 'lshr': (<function lua_lshr>, 2, Language.pico8), 'max': (<function lua_max>, 2, None), 'mid': (<function lua_mid>, 3, None), 'min': (<function lua_min>, 2, None), 'rotl': (<function lua_rotl>, 2, Language.pico8), 'rotr': (<function lua_rotr>, 2, Language.pico8), 'shl': (<function lua_shl>, 2, Language.pico8), 'shr': (<function lua_shr>, 2, Language.pico8)}
def const_from_token(token):
449def const_from_token(token):
450    if token.type == TokenType.number:
451        if token.lang == Language.picotron:
452            if isinstance(token.parsed_value, int):
453                return LuaInteger(token.parsed_value)
454            else:
455                return LuaFloat(token.parsed_value)
456        else:
457            return LuaFixnum(token.parsed_value)
458    elif token.type == TokenType.string:
459        return LuaString(token.parsed_value)
460    elif token.value == "nil":
461        return k_lua_nil
462    elif token.value == "true":
463        return k_lua_true
464    elif token.value == "false":
465        return k_lua_false
466    else:
467        return None
def get_const(node):
469def get_const(node):
470    if node.type == NodeType.const:
471        token = node.token
472        constval = const_from_token(token)
473        assert constval, "unexpected const token: %s" % token
474        return constval
475    elif node.type == NodeType.group:
476        return get_const(node.child)
477    else:
478        return getattr(node, "worse_const", None)
def set_const(node, value, ctxt, focus, force):
480def set_const(node, value, ctxt, focus, force):
481    if value.is_number:
482        token = ConstToken(TokenType.number, value.value, node)
483    elif value.type == LuaType.string:
484        token = ConstToken(TokenType.string, value.value, node)
485    elif value.type == LuaType.boolean:
486        token = Token.synthetic(TokenType.keyword, "true" if value.value else "false", node)
487    elif value.type == LuaType.nil:
488        token = Token.synthetic(TokenType.keyword, "nil", node)
489    else:
490        assert False, "unexpected const value: %s" % value
491    
492    if focus == Focus.chars and not force:
493        # the new token may take more chars than before
494        # though it may still be useful when further folded
495        if len(token.value) > len(output_node(node, ctxt)):
496            node.worse_const = value
497            return
498
499    node.replace_with(create_const_node(token))
def fixup_syntax_between(parent, prev, next):
501def fixup_syntax_between(parent, prev, next):
502    nextt = next.first_token()
503    if nextt and nextt.value == "(":
504        prevt = prev.last_token()
505        if prevt.value in (")", "]") or prevt.type == TokenType.ident:
506            i = parent.children.index(prev)
507            parent.insert_token(i+1, TokenType.punct, ";", near_next=True)
def fixup_syntax_after_remove(stmt):
509def fixup_syntax_after_remove(stmt):
510    # after removing stmt (or even just part of stmt), extra semicolons may need to be inserted
511    parent = stmt.parent
512    if parent.type == NodeType.block:
513        stmt_n = len(parent.stmts)
514        stmt_i = parent.stmts.index(stmt)
515        if stmt.type is None:
516            if 0 < stmt_i < stmt_n - 1:
517                fixup_syntax_between(parent, parent.stmts[stmt_i-1], parent.stmts[stmt_i+1])
518        else:
519            if stmt_i > 0:
520                fixup_syntax_between(parent, parent.stmts[stmt_i-1], stmt)
521            if stmt_i < stmt_n - 1:
522                fixup_syntax_between(parent, stmt, parent.stmts[stmt_i+1])
def erase_assign_targets(node, indices):
524def erase_assign_targets(node, indices):
525    if len(node.targets) < len(node.sources) and len(indices) == len(node.targets):
526        indices.pop() # can't deal with this easily otherwise
527
528    def delete_array_item(node, array, i):
529        child_i = node.children.index(array[i])
530        node.remove_child(child_i)
531        
532        # need to delete comma too
533        if i > 0:
534            node.remove_token(child_i - 1, ",")
535        elif len(array) > 1:
536            node.remove_token(child_i, ",")
537        elif node.type == NodeType.local and array is node.sources:
538            node.remove_token(child_i - 1, "=")
539        
540        del array[i]
541
542    for i in reversed(indices):
543        delete_array_item(node, node.targets, i)
544        if i < len(node.sources):
545            delete_array_item(node, node.sources, i)
546    
547    if not node.targets and not node.sources:
548        node.erase()
549    elif not node.sources and node.type != NodeType.local:
550        nil_token = Token.synthetic(TokenType.keyword, "nil", node, append=True)
551        node.sources.append(create_const_node(nil_token))
552        node.append_existing(node.sources[-1])
553    else:
554        assert node.targets # due to the pop above
555    
556    fixup_syntax_after_remove(node)
def create_const_node(token):
558def create_const_node(token):
559    return Node(NodeType.const, [token], token=token)
def create_do_node_if_needed(node):
561def create_do_node_if_needed(node):
562    needed = False
563
564    def check_do_needed(node):
565        nonlocal needed
566        if node.type == NodeType.var and node.new:
567            needed = True
568        elif node.type in (NodeType.return_, NodeType.break_, NodeType.goto):
569            needed = True
570        elif node.type in (NodeType.if_, NodeType.elseif, NodeType.while_, NodeType.repeat, NodeType.for_, NodeType.for_in, NodeType.do):
571            return k_skip_children
572        elif node.type == NodeType.function:
573            if node.target:
574                node.target.traverse_nodes(pre=check_do_needed)
575            return k_skip_children
576
577    node.traverse_nodes(pre=check_do_needed)
578    if needed:
579        do_token = Token.synthetic(TokenType.keyword, "do", node, prepend=True)
580        end_token = Token.synthetic(TokenType.keyword, "end", node, append=True)
581        node = Node(NodeType.do, [do_token, node, end_token], body=node)
582    return node
def create_else_node(node, short=False):
584def create_else_node(node, short=False):
585    else_token = Token.synthetic(TokenType.keyword, "else", node, prepend=True)
586    end_token = Token.synthetic(TokenType.keyword, "end", node, append=True)
587    return Node(NodeType.else_, [else_token, node, end_token], body=node, short=short)
def remove_else_node(node):
589def remove_else_node(node):
590    assert node.children[-1] is node.else_
591    node.remove_child(-1)
592    node.else_ = None
593    end_token = Token.synthetic(TokenType.keyword, "end", node, append=True)
594    node.append_existing(end_token)
def fold_consts(ctxt, minify_opts, root, errors):
596def fold_consts(ctxt, minify_opts, root, errors):
597    lang = ctxt.lang
598    
599    focus = Focus(minify_opts.get("focus"))
600    safe_builtins = minify_opts.get("safe-builtins", False)
601
602    def add_error(msg, node):
603        errors.append(Error(msg, node))
604
605    in_const_ctxt = 0
606    const_ctxt_fail = None
607
608    def skip_special(node):
609        if node.type in (NodeType.local, NodeType.assign):
610            # we traverse these specially in update_node_constval
611            return k_skip_children
612
613    def update_node_constval(node):
614        nonlocal in_const_ctxt, const_ctxt_fail
615        # we don't check NodeType.const/group until needed (in get_const)
616
617        if node.type == NodeType.unary_op:
618            func = k_const_unary_ops.get(node.op, None)
619            if func:
620                child_const = get_const(node.child)
621                if child_const:
622                    constval = func(lang, child_const)
623                    if constval:
624                        set_const(node, constval, ctxt, focus, in_const_ctxt)
625
626        elif node.type == NodeType.binary_op:
627            func = k_const_binary_ops.get(node.op, None)
628            if func:
629                left_const = get_const(node.left)
630                if left_const: # (optimization)
631                    right_const = get_const(node.right)
632                    if right_const:
633                        constval = func(lang, left_const, right_const)
634                    elif func in (lua_and, lua_or): # short-circuit
635                        constval = func(lang, left_const, node.right)
636                    else:
637                        constval = None
638                    
639                    if constval:
640                        if constval is node.right:
641                            node.replace_with(node.right)
642                        else:
643                            set_const(node, constval, ctxt, focus, in_const_ctxt)
644
645        elif node.type == NodeType.var and node.var and not node.new and not node.assignment:
646            if node.var.constval:
647                set_const(node, node.var.constval, ctxt, focus, in_const_ctxt or node.var.is_const)
648            elif node.var.is_const:
649                add_error(f"'{node.name}' is marked as constant but is used above where it is assigned to", node)
650                node.var.is_const = False
651
652        elif node.type in (NodeType.local, NodeType.assign):
653            visit_assign(node)
654        
655        # we assume that in a const context, calls are always to builtins
656        elif (node.type == NodeType.call and node.func.type == NodeType.var and is_root_global_or_builtin_local(node.func) and
657                not node.func.var.reassigned and (not root.has_env or not safe_builtins or in_const_ctxt)):
658            func, num_args, func_lang = k_const_globals.get(node.func.name, (None, None, None))
659            if func and (num_args is None or num_args == len(node.args)) and (func_lang is None or func_lang == lang):
660                arg_consts = []
661                for arg in node.args:
662                    arg_const = get_const(arg)
663                    if arg_const:
664                        arg_consts.append(arg_const)
665                    else:
666                        break # (optimization)
667                else:
668                    constval = func(lang, *arg_consts)
669                    if constval:
670                        set_const(node, constval, ctxt, focus, in_const_ctxt)
671        
672        elif node.type in (NodeType.if_, NodeType.elseif):
673            constval = get_const(node.cond)
674            if constval:
675                if constval.is_truthy:
676                    if node.else_:
677                        node.else_.erase(KeepCommentFlags.first)
678                    
679                    if node.type == NodeType.if_:
680                        node.replace_with(create_do_node_if_needed(node.then))
681                    else:
682                        node.replace_with(create_else_node(node.then, node.short))
683                else:
684                    node.then.erase(keep_comments=False)
685                    if node.else_:
686                        node.else_.first_token().remove_comments()
687
688                    if node.type == NodeType.if_:
689                        if not node.else_:
690                            node.erase(KeepCommentFlags.first)
691                        elif node.else_.type == NodeType.else_:
692                            node.replace_with(create_do_node_if_needed(node.else_.body))
693                        else: # elseif
694                            node.replace_with(node.else_)
695                            node.modify_token(0, "if", expected="elseif")
696                            node.type = NodeType.if_
697                    else:
698                        if not node.else_:
699                            remove_else_node(node.parent)
700                        else:
701                            node.replace_with(node.else_)
702    
703        # store which node was expected to be const but isn't
704        if in_const_ctxt and node.type != NodeType.const and const_ctxt_fail is None:
705            if node.parent.type == NodeType.call and node == node.parent.func:
706                pass
707            else:
708                const_ctxt_fail = node
709
710    def visit_assign(node):
711        nonlocal in_const_ctxt, const_ctxt_fail
712        erasable = []
713
714        for i, target in enumerate(node.targets):
715            target.traverse_nodes(pre=skip_special, post=update_node_constval)
716
717            if target.type == NodeType.var:
718                is_const_ctxt = target.var.is_const
719                # (even if a global is assigned once, it's hard to tell if all its uses are after the assignment, so we close globals under --[[const]])
720                is_const = ((target.kind == VarKind.local and not target.var.reassigned) or
721                            (is_const_ctxt and target.kind == VarKind.global_ and target.var.reassigned <= 1 and target.name not in ctxt.builtins))
722            else:
723                is_const = is_const_ctxt = False
724
725            if is_const_ctxt:
726                in_const_ctxt += 1
727                const_ctxt_fail = None
728                
729            constval = None
730            if is_const and is_const_ctxt != False:
731                if i < len(node.sources):
732                    source = node.sources[i]
733                    source.traverse_nodes(pre=skip_special, post=update_node_constval)
734                    constval = get_const(source)
735                elif not (node.sources and is_vararg_expr(node.sources[-1])):
736                    constval = k_lua_nil
737            else:
738                if i < len(node.sources):
739                    node.sources[i].traverse_nodes(pre=skip_special, post=update_node_constval)
740            
741            if constval:
742                const_unwanted = isinstance(constval, LuaString) or focus == Focus.chars # cases likely to make char count increase too much
743                if is_const_ctxt or not const_unwanted:
744                    erasable.append(i)
745                    if not target.var.constval: # may've been set to something else through ctxt.consts
746                        target.var.constval = constval
747            else:
748                if is_const_ctxt:
749                    reason = ""
750                    if const_ctxt_fail:
751                        reason = f" due to '{const_ctxt_fail.source_text}'"
752                    elif not is_const:
753                        reason = f" due to being reassigned"
754                    add_error(f"Local '{target.name}' is marked as const but its value cannot be determined" + reason, target)
755                    target.var.is_const = False
756                    
757            if is_const_ctxt:
758                in_const_ctxt -= 1
759                const_ctxt_fail = None
760        
761        for i, source in enumerate(node.sources):
762            if i >= len(node.targets): # else, traversed above
763                source.traverse_nodes(pre=skip_special, post=update_node_constval)
764        
765        if erasable:
766            erase_assign_targets(node, erasable)
767
768    root.traverse_nodes(pre=skip_special, post=update_node_constval)
def parse_constant(value, lang, as_str=False):
770def parse_constant(value, lang, as_str=False):
771    if as_str:
772        return LuaString(to_langstr(value, lang))
773
774    tokens, errors = tokenize(Source("<const>", to_langstr(value, lang)), lang=lang)
775    if not errors:
776        token = None
777        if len(tokens) == 1:
778            token = tokens[0]
779        elif len(tokens) == 2 and tokens[0].value in ("-", "~") and tokens[1].type == TokenType.number:
780            token = tokens[1]
781            token.value = tokens[0].value + token.value
782                    
783        if token:
784            constval = const_from_token(token)
785            if constval:
786                return constval