pico_preprocess

Functions to preprocess pico8 source - that is handle #include-s

  1"""Functions to preprocess pico8 source - that is handle #include-s"""
  2
  3from utils import *
  4
  5class CodeMapping(Tuple):
  6    """Specifies that code starting at index 'idx' maps to the given source starting at index 'src_idx'"""
  7    idx = src_path = src_code = src_idx = src_line = ...
  8
  9k_long_brackets_re = re.compile(r"\[(=*)\[(.*?)\]\1\]", re.S)
 10k_wspace = " \t\r\n"
 11
 12def preprocess_code(path, code, start_line=0, **opts):
 13    """preprocess the given pico8 code (e.g. handle #include-s)"""
 14    outparts = []
 15    outmappings = []
 16    i = start_i = out_i = 0
 17    
 18    def skip_long_brackets():
 19        nonlocal i
 20        m = k_long_brackets_re.match(code, i)
 21        if m:
 22            i = m.end()
 23            return True
 24
 25    def flush_output():
 26        nonlocal start_i, out_i
 27        if i > start_i:
 28            outparts.append(code[start_i:i])
 29            outmappings.append(CodeMapping(out_i, path, code, start_i, start_line))
 30            out_i += (i - start_i)
 31        start_i = i
 32
 33    while i < len(code):
 34        ch = code[i]
 35
 36        if ch == '-' and list_get(code, i + 1) == '-': # comment
 37            i += 2
 38            if not skip_long_brackets():
 39                while list_get(code, i) not in ('\n', None):
 40                    i += 1
 41
 42        elif ch == '[' and list_get(code, i + 1) == '[': # long string
 43            skip_long_brackets()
 44
 45        elif ch in ('"', "'"): # string
 46            i += 1
 47            while list_get(code, i) not in (ch, None):
 48                i += 2 if code[i] == '\\' else 1
 49            i += 1
 50
 51        elif ch != '#':
 52            i += 1
 53
 54        elif list_get(code, i + 1, '') not in k_wspace and list_get(code, i + 1) != '(': # normal directive
 55            # is it at the start of the line? (potentially with some whitespace before)
 56            hash_i = i
 57            while list_get(code, i - 1, '') in k_wspace:
 58                if i == 0 or code[i - 1] == '\n':
 59                    break
 60                i -= 1
 61            else:
 62                i = hash_i + 1
 63                continue
 64
 65            flush_output()
 66            end_i = code.find("\n", hash_i)
 67            end_i = end_i if end_i >= 0 else len(code)
 68
 69            args = code[hash_i:end_i].split(maxsplit=1)
 70            if len(args) == 2 and args[0] == "#include":
 71                out_i = read_included_cart(path, args[1], out_i, outparts, outmappings, **opts)
 72                i, start_i, out_i = end_i, end_i, out_i
 73            else:
 74                i = hash_i + 1
 75
 76        else:
 77            i += 1
 78
 79    flush_output()
 80    return "".join(outparts), outmappings
 81
 82class IncludeNotFoundError(CheckError):
 83    pass
 84
 85def read_included_cart(orig_path, inc_name, out_i, outparts, outmappings, include_notifier=None, **opts):
 86    tab_idx = None
 87    if re.fullmatch(r".*:[0-9a-fA-F]", inc_name):
 88        tab_idx = int(inc_name[-1], 16)
 89        inc_name = inc_name[:-2]
 90
 91    inc_path = path_join(path_dirname(orig_path), inc_name)
 92    if not path_exists(inc_path):
 93        # windows path outside windows, maybe?
 94        inc_path = inc_path.replace("\\", "/")
 95        
 96    if include_notifier: # before existance check, so that a fs watcher can catch it appearing
 97        include_notifier(inc_path)
 98
 99    if not path_exists(inc_path):
100        raise IncludeNotFoundError(f"cannot open included cart at: {inc_path}")
101    
102    inc_cart = read_cart(inc_path, include_notifier=include_notifier, **opts)
103    if e(tab_idx):
104        trim_cart_to_tab(inc_cart, tab_idx)
105
106    if inc_cart.code_map:
107        for map in inc_cart.code_map:
108            outmappings.append(CodeMapping(out_i + map.idx, map.src_path, map.src_code, map.src_idx, map.src_line))
109    else:
110        outmappings.append(CodeMapping(out_i, inc_path, inc_cart.code, 0, 0))
111    outparts.append(inc_cart.code)
112
113    return out_i + len(inc_cart.code)
114
115k_tab_break = "\n-->8\n" # yes, pico8 doesn't accept consecutive/initial/final tab breaks
116
117def trim_cart_to_tab(cart, target_tab):
118    tab = start = 0
119    limit = len(cart.code)
120    while start < limit:
121        end = cart.code.find(k_tab_break, start)
122        if end < 0:
123            end = limit
124
125        if tab == target_tab:
126            break
127
128        tab += 1
129        start = end + len(k_tab_break)
130    else:
131        throw(f"Couldn't find tab {target_tab} in cart: {cart.path}")
132
133    cart.code = cart.code[start:end]
134
135    new_code_map = []
136    for map in cart.code_map:
137        if map.idx > end:
138            break
139
140        if map.idx <= start:
141            new_code_map.clear()
142        
143        new_idx = max(map.idx - start, 0)
144        new_src_idx = map.src_idx + (start if map.src_path == cart.path else 0)
145
146        new_code_map.append(CodeMapping(new_idx, map.src_path, map.src_code, new_src_idx, map.src_line))
147    cart.code_map = new_code_map
148
149from pico_cart import read_cart
class CodeMapping(utils.Tuple):
6class CodeMapping(Tuple):
7    """Specifies that code starting at index 'idx' maps to the given source starting at index 'src_idx'"""
8    idx = src_path = src_code = src_idx = src_line = ...

Specifies that code starting at index 'idx' maps to the given source starting at index 'src_idx'

idx

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

src_path

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

src_code

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

src_idx

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

src_line

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

k_long_brackets_re = re.compile('\\[(=*)\\[(.*?)\\]\\1\\]', re.DOTALL)
k_wspace = ' \t\r\n'
def preprocess_code(path, code, start_line=0, **opts):
13def preprocess_code(path, code, start_line=0, **opts):
14    """preprocess the given pico8 code (e.g. handle #include-s)"""
15    outparts = []
16    outmappings = []
17    i = start_i = out_i = 0
18    
19    def skip_long_brackets():
20        nonlocal i
21        m = k_long_brackets_re.match(code, i)
22        if m:
23            i = m.end()
24            return True
25
26    def flush_output():
27        nonlocal start_i, out_i
28        if i > start_i:
29            outparts.append(code[start_i:i])
30            outmappings.append(CodeMapping(out_i, path, code, start_i, start_line))
31            out_i += (i - start_i)
32        start_i = i
33
34    while i < len(code):
35        ch = code[i]
36
37        if ch == '-' and list_get(code, i + 1) == '-': # comment
38            i += 2
39            if not skip_long_brackets():
40                while list_get(code, i) not in ('\n', None):
41                    i += 1
42
43        elif ch == '[' and list_get(code, i + 1) == '[': # long string
44            skip_long_brackets()
45
46        elif ch in ('"', "'"): # string
47            i += 1
48            while list_get(code, i) not in (ch, None):
49                i += 2 if code[i] == '\\' else 1
50            i += 1
51
52        elif ch != '#':
53            i += 1
54
55        elif list_get(code, i + 1, '') not in k_wspace and list_get(code, i + 1) != '(': # normal directive
56            # is it at the start of the line? (potentially with some whitespace before)
57            hash_i = i
58            while list_get(code, i - 1, '') in k_wspace:
59                if i == 0 or code[i - 1] == '\n':
60                    break
61                i -= 1
62            else:
63                i = hash_i + 1
64                continue
65
66            flush_output()
67            end_i = code.find("\n", hash_i)
68            end_i = end_i if end_i >= 0 else len(code)
69
70            args = code[hash_i:end_i].split(maxsplit=1)
71            if len(args) == 2 and args[0] == "#include":
72                out_i = read_included_cart(path, args[1], out_i, outparts, outmappings, **opts)
73                i, start_i, out_i = end_i, end_i, out_i
74            else:
75                i = hash_i + 1
76
77        else:
78            i += 1
79
80    flush_output()
81    return "".join(outparts), outmappings

preprocess the given pico8 code (e.g. handle #include-s)

class IncludeNotFoundError(utils.CheckError):
83class IncludeNotFoundError(CheckError):
84    pass

An error meant to be caught and displayed as-is, like AssertionError but for user errors

def read_included_cart( orig_path, inc_name, out_i, outparts, outmappings, include_notifier=None, **opts):
 86def read_included_cart(orig_path, inc_name, out_i, outparts, outmappings, include_notifier=None, **opts):
 87    tab_idx = None
 88    if re.fullmatch(r".*:[0-9a-fA-F]", inc_name):
 89        tab_idx = int(inc_name[-1], 16)
 90        inc_name = inc_name[:-2]
 91
 92    inc_path = path_join(path_dirname(orig_path), inc_name)
 93    if not path_exists(inc_path):
 94        # windows path outside windows, maybe?
 95        inc_path = inc_path.replace("\\", "/")
 96        
 97    if include_notifier: # before existance check, so that a fs watcher can catch it appearing
 98        include_notifier(inc_path)
 99
100    if not path_exists(inc_path):
101        raise IncludeNotFoundError(f"cannot open included cart at: {inc_path}")
102    
103    inc_cart = read_cart(inc_path, include_notifier=include_notifier, **opts)
104    if e(tab_idx):
105        trim_cart_to_tab(inc_cart, tab_idx)
106
107    if inc_cart.code_map:
108        for map in inc_cart.code_map:
109            outmappings.append(CodeMapping(out_i + map.idx, map.src_path, map.src_code, map.src_idx, map.src_line))
110    else:
111        outmappings.append(CodeMapping(out_i, inc_path, inc_cart.code, 0, 0))
112    outparts.append(inc_cart.code)
113
114    return out_i + len(inc_cart.code)
k_tab_break = '\n-->8\n'
def trim_cart_to_tab(cart, target_tab):
118def trim_cart_to_tab(cart, target_tab):
119    tab = start = 0
120    limit = len(cart.code)
121    while start < limit:
122        end = cart.code.find(k_tab_break, start)
123        if end < 0:
124            end = limit
125
126        if tab == target_tab:
127            break
128
129        tab += 1
130        start = end + len(k_tab_break)
131    else:
132        throw(f"Couldn't find tab {target_tab} in cart: {cart.path}")
133
134    cart.code = cart.code[start:end]
135
136    new_code_map = []
137    for map in cart.code_map:
138        if map.idx > end:
139            break
140
141        if map.idx <= start:
142            new_code_map.clear()
143        
144        new_idx = max(map.idx - start, 0)
145        new_src_idx = map.src_idx + (start if map.src_path == cart.path else 0)
146
147        new_code_map.append(CodeMapping(new_idx, map.src_path, map.src_code, new_src_idx, map.src_line))
148    cart.code_map = new_code_map