pico_process

Definition of the pico8 context (builtins, etc) and functions to do all our processing (delegating to individual modules)

  1"""Definition of the pico8 context (builtins, etc) and functions to do all our processing (delegating to individual modules)"""
  2
  3from utils import *
  4from pico_defs import Language, from_langstr
  5from pico_compress import print_size
  6from pico_srcdefs import *
  7from pico_tokenize import tokenize, count_tokens
  8from pico_parse import parse, create_super_root, get_sub_root
  9from pico_lint import lint_code
 10from pico_minify import minify_code
 11from pico_unminify import unminify_code
 12from pico_constfold import fold_consts
 13from pico_output import output_code, output_needs_comments
 14from pico_rename import rename_tokens
 15
 16# re-export some things for old examples to keep working.
 17from pico_tokenize import is_identifier, is_ident_char, TokenType
 18from pico_parse import Local, Global, Scope
 19
 20# when adding new builtins:
 21#   check whether to update builtins_copied_to_locals (find 'local ...=...' script inside pico8 binary; e.g. `strings $(which pico8) | grep "^local "`)
 22#   consider whether to update builtins_with_callbacks
 23
 24builtin_globals = {
 25    # normal
 26    "abs", "add", "all", "assert", "atan2", "btn", "btnp",
 27    "camera", "cartdata", "ceil", "chr", "circ", "circfill",
 28    "clip", "cls", "cocreate", "color", "coresume", "cos",
 29    "costatus", "count", "cstore", "cursor", "del", "deli",
 30    "dget", "dset", "extcmd", "fget", "fillp", "flip",
 31    "flr", "foreach", "fset", "getmetatable", "ipairs", "inext",
 32    "line", "load", "ls", "map", "max", "memcpy", "memset",
 33    "menuitem", "mget", "mid", "min", "mset", "music",
 34    "next", "ord", "oval", "ovalfill", "pack", "pairs",
 35    "pal", "palt", "peek", "peek2", "peek4", "pget",
 36    "poke", "poke2", "poke4", "print", "printh", "pset",
 37    "rawequal", "rawget", "rawlen", "rawset", "rect",
 38    "rectfill", "reload", "reset", "rnd", "rrect", "rrectfill",
 39    "run", "select", "setmetatable",
 40    "serial", "sfx", "sget", "sgn", "sin", "split",
 41    "spr", "sqrt", "srand", "sset", "sspr", "stat", "stop",
 42    "sub", "time", "tline", "tonum", "tostr", "trace", "type",
 43    "unpack", "yield", "t",
 44    # deprecated
 45    "band", "bnot", "bor", "bxor",
 46    "lshr", "rotl", "rotr", "shl", "shr",
 47    "mapdraw", 
 48    # undocumented
 49    "holdframe", "_set_fps", "_update_buttons", "_mark_cpu",
 50    "_startframe", "_update_framerate", "_set_mainloop_exists",
 51    "_map_display", "_get_menu_item_selected", "_pausemenu",
 52    "set_draw_slice", "tostring",
 53}
 54
 55# pattern builtins
 56builtin_globals |= set(chr(ch) for ch in range(0x80, 0x9a))
 57
 58# subset of builtins that pico8 copies to top-level locals
 59# (builtins included here must also be in builtin_globals)
 60builtins_copied_to_locals = {
 61    "time", "sub", "chr", "ord", "tostr", "tonum", "add",
 62    "del", "deli", "clip", "color", "pal", "palt", "fillp",
 63    "pget", "pset", "sget", "sset", "fget", "fset",
 64    "circ", "circfill", "rect", "rectfill", "oval", "ovalfill",
 65    "line", "spr", "sspr",
 66    "mget", "mset", "tline", "peek", "poke", "peek2", "poke2",
 67    "peek4", "poke4", "memcpy", "memset", "max", "min", "mid",
 68    "flr", "ceil", "cos", "sin", "atan2", "srand", "band", # note: rnd is missing due to a pico8 typo
 69    "bor", "bxor", "bnot", "shl", "shr", "lshr", "rotl", "rotr",
 70}
 71
 72# subset of builtins that may call user code before returning, NOT including far-fetched stuff like metamethods
 73# (builtins included here must also be in builtin_globals)
 74builtins_with_callbacks = {
 75    "coresume", "foreach", "yield",
 76}
 77
 78# callbacks that are called by the builtin mainloop logic
 79builtin_callbacks = {
 80    "_init", "_draw", "_update", "_update60",
 81}
 82
 83# table members that are used by builtins
 84builtin_members = {
 85    # pack()
 86    "n",
 87    # metamethods:
 88    "__index", "__newindex", "__len", "__eq", "__lt", "__le",
 89    "__add", "__sub", "__mul", "__div", "__idiv", "__mod",
 90    "__pow", "__and", "__or", "__xor", "__shl", "__shr",
 91    "__lshr", "__rotl", "__rotr", "__concat", "__unm", "__not",
 92    "__peek", "__peek2", "__peek4", "__call", "__tostring",
 93    "__pairs", "__ipairs", "__metatable", "__gc", "__mode",
 94}
 95
 96class PicoContext(ContextBase):
 97    """Specialization of ContextBase to pico8 - specifying its builtins, etc."""
 98    def __init__(m, **opts):
 99        super().__init__(Language.pico8, builtin_globals, builtins_copied_to_locals, builtins_with_callbacks, builtin_callbacks, builtin_members, **opts)
100
101def print_token_count(num_tokens, **kwargs):
102    print_size("tokens", num_tokens, 8192, **kwargs)
103
104def fixup_process_args(args):
105    if args is True:
106        args = {}
107    args_set = isinstance(args, dict)
108    return args_set, args
109
110def process_compiler(token):
111    token.compiler.compile(token.compiler_root)
112    token.compiler_node.erase(keep_comments=False)
113    # compiler outputs are processed via placeholders
114
115def process_placeholder(ctxt, token, errors):
116    ph_name, ph_args = token.placeholder_name, token.placeholder_args
117    include_func = ctxt.include_getter(ph_name, placeholder=True)
118    if include_func:
119        ph_str = include_func(args=ph_args.strip(), ctxt=ctxt)
120        if ph_str != None:
121            ph_source = Source(ph_name, ph_str)
122            ph_tokens, ph_errors = tokenize(ph_source, ctxt, inner=True)
123            if not ph_errors:
124                ph_root, ph_errors = parse(ph_source, ph_tokens, ctxt, for_expr=token.placeholder_expr)
125                if not ph_errors:
126                    token.parent.replace_with(ph_root)
127                    return
128            errors += ph_errors
129    
130    eprint(f"placeholder '{ph_name}' is not recognized")
131
132def process_code(ctxt, source, input_count=False, count=False, lint=False, minify=False, rename=False, unminify=False, 
133                 stop_on_lint=True, count_is_optional=False, preproc=None):
134    """Do everything (minify, lint, etc) to the code that was requested - including parsing/tokenizing it if/as needed"""
135
136    need_lint, lint = fixup_process_args(lint)
137    need_minify, minify = fixup_process_args(minify)
138    need_rename, rename = fixup_process_args(rename)
139    need_unminify, unminify = fixup_process_args(unminify)
140
141    if not need_lint and not need_minify and not need_unminify and not ((count or input_count) and not count_is_optional) and not preproc:
142        return True, ()
143    
144    need_parse = need_lint or need_minify or need_unminify or preproc
145    need_all_comments = need_unminify or (need_minify and output_needs_comments(minify))
146
147    errors = ()
148    root = create_super_root() if source.is_super else None
149    subsrc_count = 0
150    for subsrc in source:
151        subsrc_count += 1
152        tokens, errors = tokenize(subsrc, ctxt, need_all_comments)
153        if not errors and need_parse:
154            root, errors = parse(subsrc, tokens, ctxt, root)
155        if errors:
156            return False, errors
157
158    if subsrc_count:
159        if source.is_super:
160            source.sort_root(root)
161
162        if input_count:
163            assert not source.is_super
164            print_token_count(count_tokens(tokens), prefix="input", handler=input_count)
165
166        if need_lint:
167            errors = lint_code(ctxt, root, lint)
168
169        if preproc: # can do linting and early transformations
170            def add_error(msg, node):
171                errors.append(Error(msg, node))
172            preproc(root, add_error)
173        
174        if not errors or not stop_on_lint:        
175            if need_minify:
176                simplify_code(ctxt, root, minify, errors)
177                
178                if need_rename:
179                    rename_tokens(ctxt, root, rename)
180                
181                transform_code(ctxt, root, minify, errors)
182
183                minify_code(ctxt, root, minify)
184
185                for subsrc in source:
186                    subsrc.text = output_code(ctxt, get_sub_root(root, subsrc), minify)
187            
188            if need_unminify:
189                for subsrc in source:
190                    subsrc.text = unminify_code(get_sub_root(root, subsrc), unminify)
191
192            if count:
193                assert not source.is_super
194                new_tokens = root.get_tokens() if need_parse else tokens
195                print_token_count(count_tokens(new_tokens), handler=count)
196
197    return True, errors
198
199def simplify_code(ctxt, root, minify, errors):
200    fold = minify.get("consts", True)
201        
202    if fold:
203        fold_consts(ctxt, minify, root, errors)
204
205def transform_code(ctxt, root, minify, errors):
206    transform = minify.get("transform", True)
207        
208    if transform:
209        for compiler_token in root.compiler_tokens:
210            process_compiler(compiler_token)
211        
212        for placeholder_token in root.placeholders:
213            process_placeholder(ctxt, placeholder_token, errors)
214
215def echo_code(code, ctxt, echo=True):
216    code = from_langstr(code, ctxt.lang)
217    if echo == True:
218        for line in code.splitlines():
219            print(line)
220    else:
221        file_write_maybe_text(echo, code)    
builtin_globals = {'\x81', 'del', 'assert', 'menuitem', 'rotr', 'next', 'rawequal', 'pget', 'map', 'band', 'memcpy', 'color', '_mark_cpu', 'atan2', 'fset', '_update_buttons', '\x84', 'mapdraw', 'stat', 'poke', 'rnd', '\x8e', 'dset', 'serial', 'min', 'unpack', 'cartdata', 'add', 'ipairs', 'lshr', 'fillp', 'inext', '\x93', 'spr', '_update_framerate', 't', '\x8c', '\x95', 'split', 'cocreate', '\x90', 'print', 'holdframe', 'ls', 'rawset', 'sspr', 'srand', 'sub', 'fget', 'rrectfill', 'shl', 'mget', 'run', 'sin', '\x87', 'load', '_pausemenu', '\x96', 'cos', 'setmetatable', 'set_draw_slice', 'bnot', 'bxor', 'sfx', 'tostring', '\x8f', 'cls', 'all', 'deli', '\x89', 'chr', 'tostr', '\x83', 'extcmd', 'mid', 'flip', 'sset', 'pal', 'ceil', 'count', 'foreach', 'tonum', 'reset', 'type', 'poke2', 'circ', 'btnp', 'palt', 'rrect', 'rotl', '\x85', 'yield', 'abs', '\x80', '\x98', '\x94', '_set_fps', 'pairs', 'max', 'flr', '\x8b', 'select', 'sqrt', 'reload', 'ovalfill', 'clip', 'coresume', 'sgn', '_map_display', '\x82', 'printh', 'pset', 'stop', 'btn', 'oval', 'mset', 'rawget', 'music', 'cstore', 'peek2', 'peek', '\x86', 'memset', 'costatus', 'time', 'dget', 'line', 'trace', '_get_menu_item_selected', 'shr', '\x8a', '_startframe', 'getmetatable', 'bor', 'rectfill', 'pack', '\x97', '\x88', '\x91', '\x99', 'peek4', 'poke4', 'tline', 'cursor', 'camera', 'rawlen', 'ord', 'circfill', 'sget', '_set_mainloop_exists', 'rect', '\x8d', '\x92'}
builtins_copied_to_locals = {'ceil', 'mset', 'del', 'rotr', 'tonum', 'sspr', 'srand', 'peek2', 'sub', 'peek', 'poke2', 'fget', 'pget', 'circ', 'memset', 'band', 'memcpy', 'color', 'time', 'palt', 'atan2', 'fset', 'line', 'shl', 'rotl', 'mget', 'poke', 'shr', 'sin', 'min', 'max', 'bor', 'rectfill', 'flr', 'cos', 'peek4', 'poke4', 'add', 'tline', 'bxor', 'ovalfill', 'bnot', 'lshr', 'fillp', 'deli', 'clip', 'chr', 'tostr', 'spr', 'ord', 'circfill', 'sget', 'pset', 'rect', 'mid', 'sset', 'pal', 'oval'}
builtins_with_callbacks = {'foreach', 'yield', 'coresume'}
builtin_callbacks = {'_update', '_update60', '_draw', '_init'}
builtin_members = {'__newindex', 'n', '__lshr', '__concat', '__mode', '__lt', '__metatable', '__gc', '__div', '__len', '__idiv', '__shl', '__pow', '__xor', '__peek', '__rotr', '__call', '__and', '__pairs', '__eq', '__ipairs', '__or', '__rotl', '__sub', '__mul', '__peek2', '__unm', '__add', '__index', '__peek4', '__le', '__shr', '__not', '__tostring', '__mod'}
class PicoContext(pico_srcdefs.ContextBase):
 97class PicoContext(ContextBase):
 98    """Specialization of ContextBase to pico8 - specifying its builtins, etc."""
 99    def __init__(m, **opts):
100        super().__init__(Language.pico8, builtin_globals, builtins_copied_to_locals, builtins_with_callbacks, builtin_callbacks, builtin_members, **opts)

Specialization of ContextBase to pico8 - specifying its builtins, etc.

PicoContext(**opts)
 99    def __init__(m, **opts):
100        super().__init__(Language.pico8, builtin_globals, builtins_copied_to_locals, builtins_with_callbacks, builtin_callbacks, builtin_members, **opts)
def fixup_process_args(args):
105def fixup_process_args(args):
106    if args is True:
107        args = {}
108    args_set = isinstance(args, dict)
109    return args_set, args
def process_compiler(token):
111def process_compiler(token):
112    token.compiler.compile(token.compiler_root)
113    token.compiler_node.erase(keep_comments=False)
114    # compiler outputs are processed via placeholders
def process_placeholder(ctxt, token, errors):
116def process_placeholder(ctxt, token, errors):
117    ph_name, ph_args = token.placeholder_name, token.placeholder_args
118    include_func = ctxt.include_getter(ph_name, placeholder=True)
119    if include_func:
120        ph_str = include_func(args=ph_args.strip(), ctxt=ctxt)
121        if ph_str != None:
122            ph_source = Source(ph_name, ph_str)
123            ph_tokens, ph_errors = tokenize(ph_source, ctxt, inner=True)
124            if not ph_errors:
125                ph_root, ph_errors = parse(ph_source, ph_tokens, ctxt, for_expr=token.placeholder_expr)
126                if not ph_errors:
127                    token.parent.replace_with(ph_root)
128                    return
129            errors += ph_errors
130    
131    eprint(f"placeholder '{ph_name}' is not recognized")
def process_code( ctxt, source, input_count=False, count=False, lint=False, minify=False, rename=False, unminify=False, stop_on_lint=True, count_is_optional=False, preproc=None):
133def process_code(ctxt, source, input_count=False, count=False, lint=False, minify=False, rename=False, unminify=False, 
134                 stop_on_lint=True, count_is_optional=False, preproc=None):
135    """Do everything (minify, lint, etc) to the code that was requested - including parsing/tokenizing it if/as needed"""
136
137    need_lint, lint = fixup_process_args(lint)
138    need_minify, minify = fixup_process_args(minify)
139    need_rename, rename = fixup_process_args(rename)
140    need_unminify, unminify = fixup_process_args(unminify)
141
142    if not need_lint and not need_minify and not need_unminify and not ((count or input_count) and not count_is_optional) and not preproc:
143        return True, ()
144    
145    need_parse = need_lint or need_minify or need_unminify or preproc
146    need_all_comments = need_unminify or (need_minify and output_needs_comments(minify))
147
148    errors = ()
149    root = create_super_root() if source.is_super else None
150    subsrc_count = 0
151    for subsrc in source:
152        subsrc_count += 1
153        tokens, errors = tokenize(subsrc, ctxt, need_all_comments)
154        if not errors and need_parse:
155            root, errors = parse(subsrc, tokens, ctxt, root)
156        if errors:
157            return False, errors
158
159    if subsrc_count:
160        if source.is_super:
161            source.sort_root(root)
162
163        if input_count:
164            assert not source.is_super
165            print_token_count(count_tokens(tokens), prefix="input", handler=input_count)
166
167        if need_lint:
168            errors = lint_code(ctxt, root, lint)
169
170        if preproc: # can do linting and early transformations
171            def add_error(msg, node):
172                errors.append(Error(msg, node))
173            preproc(root, add_error)
174        
175        if not errors or not stop_on_lint:        
176            if need_minify:
177                simplify_code(ctxt, root, minify, errors)
178                
179                if need_rename:
180                    rename_tokens(ctxt, root, rename)
181                
182                transform_code(ctxt, root, minify, errors)
183
184                minify_code(ctxt, root, minify)
185
186                for subsrc in source:
187                    subsrc.text = output_code(ctxt, get_sub_root(root, subsrc), minify)
188            
189            if need_unminify:
190                for subsrc in source:
191                    subsrc.text = unminify_code(get_sub_root(root, subsrc), unminify)
192
193            if count:
194                assert not source.is_super
195                new_tokens = root.get_tokens() if need_parse else tokens
196                print_token_count(count_tokens(new_tokens), handler=count)
197
198    return True, errors

Do everything (minify, lint, etc) to the code that was requested - including parsing/tokenizing it if/as needed

def simplify_code(ctxt, root, minify, errors):
200def simplify_code(ctxt, root, minify, errors):
201    fold = minify.get("consts", True)
202        
203    if fold:
204        fold_consts(ctxt, minify, root, errors)
def transform_code(ctxt, root, minify, errors):
206def transform_code(ctxt, root, minify, errors):
207    transform = minify.get("transform", True)
208        
209    if transform:
210        for compiler_token in root.compiler_tokens:
211            process_compiler(compiler_token)
212        
213        for placeholder_token in root.placeholders:
214            process_placeholder(ctxt, placeholder_token, errors)
def echo_code(code, ctxt, echo=True):
216def echo_code(code, ctxt, echo=True):
217    code = from_langstr(code, ctxt.lang)
218    if echo == True:
219        for line in code.splitlines():
220            print(line)
221    else:
222        file_write_maybe_text(echo, code)