picotron_defs

Definitions specific to picotron

  1"""Definitions specific to picotron"""
  2
  3from utils import *
  4from media_utils import Color
  5from pico_defs import Language, decode_luastr, encode_luastr, k_palette
  6from pico_srcdefs import ContextBase, Source, get_source_location
  7from pico_tokenize import TokenType
  8from pico_parse import NodeType, is_root_global_or_builtin_local
  9import fnmatch
 10
 11k_palette_64 = [
 12    *k_palette[:16],
 13    Color(0x24, 0x63, 0xB0, 0xff),
 14    Color(0x00, 0xA5, 0xA1, 0xff),
 15    Color(0x65, 0x46, 0x88, 0xff),
 16    Color(0x12, 0x53, 0x59, 0xff),
 17    Color(0x74, 0x2F, 0x29, 0xff),
 18    Color(0x45, 0x2D, 0x32, 0xff),
 19    Color(0xA2, 0x88, 0x79, 0xff),
 20    Color(0xFF, 0xAC, 0xC5, 0xff),
 21    Color(0xB9, 0x00, 0x3E, 0xff),
 22    Color(0xE2, 0x6B, 0x02, 0xff),
 23    Color(0x95, 0xF0, 0x42, 0xff),
 24    Color(0x00, 0xB2, 0x51, 0xff),
 25    Color(0x64, 0xDF, 0xF6, 0xff),
 26    Color(0xBD, 0x9A, 0xDF, 0xff),
 27    Color(0xE4, 0x0D, 0xAB, 0xff),
 28    Color(0xFF, 0x85, 0x57, 0xff),
 29]
 30
 31def get_default_picotron_runtime():
 32    runtime = 21 # TODO - update as newer versions get more common
 33    return maybe_int(os.getenv("PICOTRON_RUNTIME_VERSION_ID"), runtime)
 34
 35def get_latest_picotron_runtime():
 36    if os.getenv("PICO8_VERSION_LATEST_IS_DEFAULT"): # for tests
 37        return get_default_picotron_runtime ()
 38    else:
 39        return 27 # TODO - update as I get around to testing new versions (and maybe create a map between version string and runtime version?)
 40
 41def get_picotron_version_id(runtime):
 42    return 2 # always for now?
 43
 44builtin_globals = {
 45    "USERDATA", "_G", "_VERSION", "abs", "add",  "all", "apply_delta",
 46    "assert", "atan2", "blit", "btn", "btnp", "camera", "cd",
 47    "ceil", "chr", "circ", "circfill", "clear_key", "clip",
 48    "cls", "cocreate", "collectgarbage", "color", "coresume", "coroutine",
 49    "cos", "costatus", "count", "cp", "create_delta", "create_gui",
 50    "create_process", "create_socket", "create_undo_stack", "cursor",
 51    "date", "debug", "del", "deli", "env", "error", "exit",
 52    "fetch", "fetch_metadata", "fget", "fillp", "flip", "flr", "foreach",
 53    "fset", "fstat", "fullpath", "get", "get_clipboard", "get_display",
 54    "get_draw_target", "get_spr", "getmetatable", "include", "ipairs",
 55    "key", "keyp", "line", "load", "ls", "map", "math", "max", "memcpy",
 56    "memmap", "memset", "menuitem", "mget", "mid", "min", "mkdir",
 57    "mount", "mouse", "mouselock", "mset", "music", "mv", "next",
 58    "note", "notify", "on_event", "open", "ord", "oval", "ovalfill", "pack",
 59    "pairs", "pal", "palt", "pcall", "peek", "peek2", "peek4", "peek8",
 60    "peektext", "pget", "pid", "pod", "poke", "poke2", "poke4", "poke8",
 61    "print", "printh", "pset", "pwd", "pwf", "rawequal", "rawget",
 62    "rawlen", "rawset", "readtext", "rect", "rectfill", "reset", "rm",
 63    "rnd", "rrect", "rrectfill", "select", "send_message", "set",
 64    "set_clipboard", "set_draw_target", "set_spr", "setmetatable",
 65    "sfx", "sgn", "sin", "split", "spr", "sqrt", "srand", "sspr", "stat",
 66    "stop", "store", "store_metadata", "string", "sub", "t", "table",
 67    "theme", "time", "tline3d", "tokenoid", "tonum", "tonumber", "tostr",
 68    "tostring", "type", "unmap", "unpack", "unpod", "userdata", "utf8",
 69    "vec", "vid", "warn", "window", "wrangle_working_file", "yield",
 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    "create_process", "include", "load",
 77    # TODO: any others?
 78}
 79    
 80builtin_callbacks = {
 81    "_init", "_draw", "_update",
 82    # TODO: any others?
 83}
 84
 85# TODO: there are likely tons more not covered here...
 86builtin_members = {
 87    # USERDATA
 88    "abs", "add", "attribs", "band", "blit", "bor", "bxor", "clear", "column",
 89    "convert", "copy", "cross", "distance", "div", "dot", "get", "height",
 90    "idiv", "lerp", "magnitude", "matmul", "matmul2d", "matmul3d", "max", "min",
 91    "mod", "mul", "mutate", "peek", "poke", "pow", "row", "set", "sgn", "sgn0",
 92    "shl", "shr", "sort", "sub", "take", "transpose", "width",
 93    # coroutine
 94    "close", "create", "isyieldable", "resume", "running", "status",
 95    "wrap", "yield",
 96    # debug
 97    "debug", "gethook", "getinfo", "getlocal", "getmetatable", "getregistry",
 98    "getupvalue", "getuservalue", "setcstacklimit", "sethook", "setlocal",
 99    "setmetatable", "setupvalue", "setuservalue", "traceback", "upvalueid",
100    "upvaluejoin",
101    # math
102    "abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "floor",
103    "fmod", "huge", "log", "max", "maxinteger", "min", "mininteger",
104    "modf", "pi", "rad", "random", "randomseed", "sin", "sqrt", "tan",
105    "tointeger", "type", "ult",
106    # string
107    "basename", "byte", "char", "dirname", "dump", "ext", "find",
108    "format", "gmatch", "gsub", "hloc", "len", "lower", "match",
109    "pack", "packsize", "path", "rep", "reverse", "sub", "unpack",
110    "upper",
111    # table
112    "concat", "insert", "move", "pack", "remove", "unpack",
113    # utf8
114    "char", "charpattern", "codepoint", "codes", "len", "offset",
115
116    # env()
117    "argv", "parent_pid", "path", "window_attribs",
118    # create_gui()
119    "child", "clip_to_parent", "draw_all", "el_at_pointer", "el_at_xy",
120    "get_keyboard_focus_element", "get_pointer_element", "head",
121    "height", "height_rel", "id", "new", "sx", "sy", "t0", "update_all",
122    "width", "width_rel", "x", "y", "z",
123    # create_gui() meta
124    "attach", "attach_button", "attach_field", "attach_pulldown",
125    "attach_pulldown_item", "attach_scrollbars", "attach_text_editor",
126    "bring_to_front", "detach", "draw", "event", "has_keyboard_focus",
127    "new", "push_to_back", "set_keyboard_focus",
128
129    # window attrs
130    "x", "y", "z", "dx", "dy", "width", "height", "title", "pauseable",
131    "wallpaper", "fullscreen", "tabbed", "show_in_workspace", "autoclose",
132    "moveable", "resizeable", "has_frame", "video_mode", "cursor", "squashable",
133    # more gui stuff (INCOMPLETE...)
134    "action", "divider", "label", "bgcol", "fgcol", "border", "hidden", "ghost",
135    "justify", "vjustify", "parent", "child", "min_width", "min_height",
136    "squash_to_parent", "confine_to_parent", "squash_to_clip", "confine_to_clip",
137    "click", "tap", "drag", "autohide",
138    
139    # event msgs
140    "items", "filename", "attrib", "fullpath",
141
142    # pod metadata
143    "created", "modified", "pod_type", "pod_format", "revision", "icon",
144
145    # pack()
146    "n",
147    # metamethods
148    "__add", "__band", "__bnot", "__bor", "__bxor", "__close",
149    "__call", "__concat", "__div", "__eq", "__gc", "__idiv",
150    "__index", "__lt", "__le", "__len", "__metatable", "__mod",
151    "__mode", "__mul", "__name", "__newindex", "__pairs", "__pow",
152    "__shl", "__shr", "__sub", "__tostring", "__unm",
153}
154
155class PicotronContext(ContextBase):
156    """Specialization of ContextBase to picotron"""
157    def __init__(m, **opts):
158        super().__init__(Language.picotron, builtin_globals, set(), builtins_with_callbacks, builtin_callbacks, builtin_members, **opts)
159
160class Cart64Glob:
161    def __init__(m, patterns):
162        m.regexes = []
163        for pattern in patterns:
164            action = True
165            if pattern.startswith("!"):
166                action = False
167                pattern = pattern[1:]
168            m.regexes.append((re.compile(fnmatch.translate(pattern)), action))
169
170    def matches(m, path):
171        result = False
172        for regex, action in m.regexes:
173            if regex.match(path):
174                result = action
175                if not result:
176                    return False
177        return result     
178    
179class Cart64Source(Source):
180    """The source of a picotron cart, consists of multiple sub-sources, one for each source file"""
181
182    class SubSource(Source):
183        def __init__(m, parent, fspath, file):
184            m.parent, m.fspath, m.file = parent, fspath, file
185            # no super().__init__ - we override with properties
186        
187        @property
188        def key(m):
189            return m.fspath
190
191        @property
192        def path(m):
193            return m.parent.path + "/" + m.fspath
194
195        def get_location(m, idx, tabs=False): # (0-based)
196            return get_source_location(m.path, m.text, idx, m.file.line)
197
198        @property
199        def text(m):
200            return decode_luastr(m.file.raw_payload)
201
202        @text.setter
203        def text(m, val):
204            m.file.raw_payload = encode_luastr(val)
205        
206    def __init__(m, cart, code_patterns=None):
207        m.cart = cart
208        # no super().__init__ - we override with properties
209        m.subsources = []
210        glob = Cart64Glob(code_patterns) if code_patterns else None
211        for path, file in m.cart.files.items():
212            if file.is_raw: # else, definitely not a source file
213                if glob.matches(path) if glob else path.endswith(".lua"):
214                    m.subsources.append(m.SubSource(m, path, file))
215
216    @property
217    def path(m):
218        return m.cart.path
219        
220    @property
221    def text(m):
222        fail("super-source misuse")
223        
224    is_super = True
225    def __iter__(m):
226        return iter(m.subsources)
227    
228    @staticmethod
229    def topologic_sort(graph): # should sort by dep order and (TODO) gracefully ignore cycles
230        backcount = CounterDictionary()
231        for node, deps in graph.items():
232            for dep in deps:
233                backcount[dep] += 1
234        
235        next = [node for node in graph if backcount[node] == 0]
236        result = []
237        while next:
238            node = next.pop()
239            result.append(node)
240
241            for dep in graph[node]:
242                backcount[dep] -= 1
243                if backcount[dep] == 0:
244                    next.append(dep)
245        
246        for node, count in backcount.items():
247            if count != 0:
248                result.append(node)
249        
250        result.reverse()
251        return result
252
253    def sort_root(m, root):
254        deps = {}
255
256        for node in root.roots.values():
257            node_deps = []
258
259            def find_includes(node):
260                # since this is best-effort, we don't check var.reassigned/etc
261                if node.type == NodeType.call and node.func.type == NodeType.var and is_root_global_or_builtin_local(node.func) and node.func.var.name == "include":
262                    arg = list_get(node.args, 0)
263                    if arg.type == NodeType.const and arg.token.type == TokenType.string:
264                        include = arg.token.parsed_value
265                        # we assume include is an absolute path in the cart (we can't deal with much else)
266                        # TODO: could handle . and .. and //, though?
267                        deproot = root.roots.get(include)
268                        if deproot:
269                            node_deps.append(deproot)
270                            
271            node.traverse_nodes(find_includes, extra=True)
272            deps[node] = node_deps
273
274        root.children = m.topologic_sort(deps)
k_palette_64 = [Color(r=0, g=0, b=0, a=255), Color(r=29, g=43, b=83, a=255), Color(r=126, g=37, b=83, a=255), Color(r=0, g=135, b=81, a=255), Color(r=171, g=82, b=54, a=255), Color(r=95, g=87, b=79, a=255), Color(r=194, g=195, b=199, a=255), Color(r=255, g=241, b=232, a=255), Color(r=255, g=0, b=77, a=255), Color(r=255, g=163, b=0, a=255), Color(r=255, g=236, b=39, a=255), Color(r=0, g=228, b=54, a=255), Color(r=41, g=173, b=255, a=255), Color(r=131, g=118, b=156, a=255), Color(r=255, g=119, b=168, a=255), Color(r=255, g=204, b=170, a=255), Color(r=36, g=99, b=176, a=255), Color(r=0, g=165, b=161, a=255), Color(r=101, g=70, b=136, a=255), Color(r=18, g=83, b=89, a=255), Color(r=116, g=47, b=41, a=255), Color(r=69, g=45, b=50, a=255), Color(r=162, g=136, b=121, a=255), Color(r=255, g=172, b=197, a=255), Color(r=185, g=0, b=62, a=255), Color(r=226, g=107, b=2, a=255), Color(r=149, g=240, b=66, a=255), Color(r=0, g=178, b=81, a=255), Color(r=100, g=223, b=246, a=255), Color(r=189, g=154, b=223, a=255), Color(r=228, g=13, b=171, a=255), Color(r=255, g=133, b=87, a=255)]
def get_default_picotron_runtime():
32def get_default_picotron_runtime():
33    runtime = 21 # TODO - update as newer versions get more common
34    return maybe_int(os.getenv("PICOTRON_RUNTIME_VERSION_ID"), runtime)
def get_latest_picotron_runtime():
36def get_latest_picotron_runtime():
37    if os.getenv("PICO8_VERSION_LATEST_IS_DEFAULT"): # for tests
38        return get_default_picotron_runtime ()
39    else:
40        return 27 # TODO - update as I get around to testing new versions (and maybe create a map between version string and runtime version?)
def get_picotron_version_id(runtime):
42def get_picotron_version_id(runtime):
43    return 2 # always for now?
builtin_globals = {'fetch', 'del', 'assert', 'menuitem', 'next', 'rawequal', 'pget', 'mouse', 'map', 'memcpy', 'color', 'atan2', 'fset', 'create_undo_stack', 'get_clipboard', 'get_spr', 'stat', 'poke', 'pwf', 'rnd', 'pod', 'min', 'unpack', 'create_process', 'add', 'ipairs', 'fillp', 'spr', '_VERSION', 't', 'pcall', 'pwd', 'mount', 'split', 'cocreate', 'math', 'keyp', 'print', 'utf8', 'ls', 'rawset', 'create_delta', 'mkdir', 'notify', 'sspr', 'srand', 'sub', 'tline3d', 'fget', 'rrectfill', 'set_draw_target', 'wrangle_working_file', '_G', 'fstat', 'set_clipboard', 'include', 'open', 'unmap', 'mget', 'collectgarbage', 'mv', 'send_message', 'sin', 'load', 'cos', 'setmetatable', 'store', 'userdata', 'peek8', 'window', 'sfx', 'tostring', 'set', 'all', 'cls', 'deli', 'key', 'chr', 'tostr', 'vec', 'mid', 'flip', 'pal', 'date', 'ceil', 'count', 'foreach', 'tonum', 'reset', 'type', 'set_spr', 'exit', 'poke2', 'mouselock', 'circ', 'store_metadata', 'btnp', 'palt', 'peektext', 'rrect', 'yield', 'abs', 'poke8', 'memmap', 'USERDATA', 'create_gui', 'max', 'pairs', 'warn', 'flr', 'select', 'sqrt', 'coroutine', 'note', 'ovalfill', 'rm', 'theme', 'clip', 'table', 'coresume', 'sgn', 'printh', 'pset', 'stop', 'get_display', 'string', 'btn', 'fullpath', 'oval', 'vid', 'mset', 'rawget', 'music', 'peek2', 'clear_key', 'peek', 'debug', 'get_draw_target', 'blit', 'memset', 'costatus', 'time', 'env', 'pid', 'line', 'readtext', 'tokenoid', 'error', 'get', 'tonumber', 'getmetatable', 'create_socket', 'rectfill', 'pack', 'unpod', 'peek4', 'poke4', 'cp', 'cursor', 'camera', 'rawlen', 'apply_delta', 'on_event', 'circfill', 'ord', 'rect', 'fetch_metadata', 'cd'}
builtins_with_callbacks = {'load', 'coresume', 'include', 'foreach', 'yield', 'create_process'}
builtin_callbacks = {'_init', '_draw', '_update'}
builtin_members = {'rep', 'deg', 'wrap', '__concat', 'detach', 'tointeger', 'band', 'getupvalue', 't0', 'width', 'getinfo', 'idiv', 'maxinteger', 'get_pointer_element', 'attach', '__name', 'attach_scrollbars', 'poke', 'close', '__pairs', 'min', 'unpack', 'el_at_xy', 'status', '__bxor', 'dx', 'fgcol', 'ext', 'add', 'created', 'pod_type', 'getuservalue', 'squash_to_parent', 'create', 'hidden', 'format', 'parent_pid', '__index', '__le', 'drag', 'mutate', 'x', 'el_at_pointer', 'random', 'len', 'bring_to_front', 'attrib', 'row', 'hloc', 'modified', 'n', 'sx', 'title', 'insert', 'running', 'attach_text_editor', 'dot', 'lerp', 'sub', 'dirname', 'concat', 'update_all', 'resume', 'move', 'dy', 'tan', 'gethook', 'copy', 'shl', 'items', 'attribs', 'rad', 'sin', 'vjustify', 'confine_to_parent', 'setcstacklimit', 'char', 'setmetatable', 'cos', 'dump', 'window_attribs', 'mod', 'argv', 'bxor', 'lower', 'convert', 'column', 'set', 'sgn0', 'log', 'basename', 'attach_pulldown', 'ult', 'attach_pulldown_item', 'wallpaper', 'getregistry', 'tap', 'distance', 'mininteger', 'randomseed', '__shr', 'byte', 'event', '__tostring', 'ceil', 'squashable', 'setupvalue', 'min_height', 'floor', 'type', 'mul', 'confine_to_clip', '__metatable', 'width_rel', 'matmul2d', 'gsub', 'autohide', 'clear', 'traceback', 'set_keyboard_focus', '__shl', 'yield', 'abs', 'attach_field', 'sy', 'parent', 'path', 'filename', 'clip_to_parent', 'video_mode', 'codepoint', 'codes', 'asin', 'max', 'upper', 'draw', 'push_to_back', 'pauseable', '__band', 'acos', 'sqrt', 'ghost', 'setlocal', 'take', 'transpose', 'id', 'exp', 'y', 'sgn', 'cross', 'div', 'setuservalue', 'sethook', 'action', 'fullpath', 'matmul', 'height', 'bgcol', '__mod', 'upvalueid', 'draw_all', '__bnot', '__newindex', 'resizeable', '__close', 'child', 'moveable', 'autoclose', 'min_width', 'fullscreen', 'revision', 'isyieldable', '__lt', '__mode', 'peek', 'has_frame', 'debug', '__gc', 'blit', 'pod_format', '__div', '__len', '__idiv', 'label', 'head', 'z', 'packsize', 'getlocal', 'show_in_workspace', 'fmod', 'tabbed', 'shr', 'attach_button', 'get', 'modf', 'gmatch', 'new', 'justify', '__call', 'getmetatable', 'find', 'divider', 'pi', 'bor', '__eq', 'pack', 'height_rel', 'huge', 'magnitude', 'upvaluejoin', 'border', 'squash_to_clip', '__bor', 'sort', '__sub', '__mul', 'get_keyboard_focus_element', 'cursor', 'remove', 'charpattern', 'offset', '__unm', 'click', '__add', 'matmul3d', 'pow', 'reverse', 'atan', 'icon', 'has_keyboard_focus', '__pow', 'match'}
class PicotronContext(pico_srcdefs.ContextBase):
156class PicotronContext(ContextBase):
157    """Specialization of ContextBase to picotron"""
158    def __init__(m, **opts):
159        super().__init__(Language.picotron, builtin_globals, set(), builtins_with_callbacks, builtin_callbacks, builtin_members, **opts)

Specialization of ContextBase to picotron

PicotronContext(**opts)
158    def __init__(m, **opts):
159        super().__init__(Language.picotron, builtin_globals, set(), builtins_with_callbacks, builtin_callbacks, builtin_members, **opts)
class Cart64Glob:
161class Cart64Glob:
162    def __init__(m, patterns):
163        m.regexes = []
164        for pattern in patterns:
165            action = True
166            if pattern.startswith("!"):
167                action = False
168                pattern = pattern[1:]
169            m.regexes.append((re.compile(fnmatch.translate(pattern)), action))
170
171    def matches(m, path):
172        result = False
173        for regex, action in m.regexes:
174            if regex.match(path):
175                result = action
176                if not result:
177                    return False
178        return result     
Cart64Glob(patterns)
162    def __init__(m, patterns):
163        m.regexes = []
164        for pattern in patterns:
165            action = True
166            if pattern.startswith("!"):
167                action = False
168                pattern = pattern[1:]
169            m.regexes.append((re.compile(fnmatch.translate(pattern)), action))
def matches(m, path):
171    def matches(m, path):
172        result = False
173        for regex, action in m.regexes:
174            if regex.match(path):
175                result = action
176                if not result:
177                    return False
178        return result     
class Cart64Source(pico_srcdefs.Source):
180class Cart64Source(Source):
181    """The source of a picotron cart, consists of multiple sub-sources, one for each source file"""
182
183    class SubSource(Source):
184        def __init__(m, parent, fspath, file):
185            m.parent, m.fspath, m.file = parent, fspath, file
186            # no super().__init__ - we override with properties
187        
188        @property
189        def key(m):
190            return m.fspath
191
192        @property
193        def path(m):
194            return m.parent.path + "/" + m.fspath
195
196        def get_location(m, idx, tabs=False): # (0-based)
197            return get_source_location(m.path, m.text, idx, m.file.line)
198
199        @property
200        def text(m):
201            return decode_luastr(m.file.raw_payload)
202
203        @text.setter
204        def text(m, val):
205            m.file.raw_payload = encode_luastr(val)
206        
207    def __init__(m, cart, code_patterns=None):
208        m.cart = cart
209        # no super().__init__ - we override with properties
210        m.subsources = []
211        glob = Cart64Glob(code_patterns) if code_patterns else None
212        for path, file in m.cart.files.items():
213            if file.is_raw: # else, definitely not a source file
214                if glob.matches(path) if glob else path.endswith(".lua"):
215                    m.subsources.append(m.SubSource(m, path, file))
216
217    @property
218    def path(m):
219        return m.cart.path
220        
221    @property
222    def text(m):
223        fail("super-source misuse")
224        
225    is_super = True
226    def __iter__(m):
227        return iter(m.subsources)
228    
229    @staticmethod
230    def topologic_sort(graph): # should sort by dep order and (TODO) gracefully ignore cycles
231        backcount = CounterDictionary()
232        for node, deps in graph.items():
233            for dep in deps:
234                backcount[dep] += 1
235        
236        next = [node for node in graph if backcount[node] == 0]
237        result = []
238        while next:
239            node = next.pop()
240            result.append(node)
241
242            for dep in graph[node]:
243                backcount[dep] -= 1
244                if backcount[dep] == 0:
245                    next.append(dep)
246        
247        for node, count in backcount.items():
248            if count != 0:
249                result.append(node)
250        
251        result.reverse()
252        return result
253
254    def sort_root(m, root):
255        deps = {}
256
257        for node in root.roots.values():
258            node_deps = []
259
260            def find_includes(node):
261                # since this is best-effort, we don't check var.reassigned/etc
262                if node.type == NodeType.call and node.func.type == NodeType.var and is_root_global_or_builtin_local(node.func) and node.func.var.name == "include":
263                    arg = list_get(node.args, 0)
264                    if arg.type == NodeType.const and arg.token.type == TokenType.string:
265                        include = arg.token.parsed_value
266                        # we assume include is an absolute path in the cart (we can't deal with much else)
267                        # TODO: could handle . and .. and //, though?
268                        deproot = root.roots.get(include)
269                        if deproot:
270                            node_deps.append(deproot)
271                            
272            node.traverse_nodes(find_includes, extra=True)
273            deps[node] = node_deps
274
275        root.children = m.topologic_sort(deps)

The source of a picotron cart, consists of multiple sub-sources, one for each source file

Cart64Source(cart, code_patterns=None)
207    def __init__(m, cart, code_patterns=None):
208        m.cart = cart
209        # no super().__init__ - we override with properties
210        m.subsources = []
211        glob = Cart64Glob(code_patterns) if code_patterns else None
212        for path, file in m.cart.files.items():
213            if file.is_raw: # else, definitely not a source file
214                if glob.matches(path) if glob else path.endswith(".lua"):
215                    m.subsources.append(m.SubSource(m, path, file))
path
217    @property
218    def path(m):
219        return m.cart.path

The type of the Ellipsis singleton.

text
221    @property
222    def text(m):
223        fail("super-source misuse")

The type of the Ellipsis singleton.

is_super = True
@staticmethod
def topologic_sort(graph):
229    @staticmethod
230    def topologic_sort(graph): # should sort by dep order and (TODO) gracefully ignore cycles
231        backcount = CounterDictionary()
232        for node, deps in graph.items():
233            for dep in deps:
234                backcount[dep] += 1
235        
236        next = [node for node in graph if backcount[node] == 0]
237        result = []
238        while next:
239            node = next.pop()
240            result.append(node)
241
242            for dep in graph[node]:
243                backcount[dep] -= 1
244                if backcount[dep] == 0:
245                    next.append(dep)
246        
247        for node, count in backcount.items():
248            if count != 0:
249                result.append(node)
250        
251        result.reverse()
252        return result
def sort_root(m, root):
254    def sort_root(m, root):
255        deps = {}
256
257        for node in root.roots.values():
258            node_deps = []
259
260            def find_includes(node):
261                # since this is best-effort, we don't check var.reassigned/etc
262                if node.type == NodeType.call and node.func.type == NodeType.var and is_root_global_or_builtin_local(node.func) and node.func.var.name == "include":
263                    arg = list_get(node.args, 0)
264                    if arg.type == NodeType.const and arg.token.type == TokenType.string:
265                        include = arg.token.parsed_value
266                        # we assume include is an absolute path in the cart (we can't deal with much else)
267                        # TODO: could handle . and .. and //, though?
268                        deproot = root.roots.get(include)
269                        if deproot:
270                            node_deps.append(deproot)
271                            
272            node.traverse_nodes(find_includes, extra=True)
273            deps[node] = node_deps
274
275        root.children = m.topologic_sort(deps)
Inherited Members
pico_srcdefs.Source
get_location
class Cart64Source.SubSource(pico_srcdefs.Source):
183    class SubSource(Source):
184        def __init__(m, parent, fspath, file):
185            m.parent, m.fspath, m.file = parent, fspath, file
186            # no super().__init__ - we override with properties
187        
188        @property
189        def key(m):
190            return m.fspath
191
192        @property
193        def path(m):
194            return m.parent.path + "/" + m.fspath
195
196        def get_location(m, idx, tabs=False): # (0-based)
197            return get_source_location(m.path, m.text, idx, m.file.line)
198
199        @property
200        def text(m):
201            return decode_luastr(m.file.raw_payload)
202
203        @text.setter
204        def text(m, val):
205            m.file.raw_payload = encode_luastr(val)

A pico8 source file - e.g. either the main one or an included file

Cart64Source.SubSource(parent, fspath, file)
184        def __init__(m, parent, fspath, file):
185            m.parent, m.fspath, m.file = parent, fspath, file
186            # no super().__init__ - we override with properties
key
188        @property
189        def key(m):
190            return m.fspath
path
192        @property
193        def path(m):
194            return m.parent.path + "/" + m.fspath

The type of the Ellipsis singleton.

def get_location(m, idx, tabs=False):
196        def get_location(m, idx, tabs=False): # (0-based)
197            return get_source_location(m.path, m.text, idx, m.file.line)
text
199        @property
200        def text(m):
201            return decode_luastr(m.file.raw_payload)

The type of the Ellipsis singleton.

Inherited Members
pico_srcdefs.Source
is_super