pico_srcdefs

Basic definitions relating to source code, context, errors, etc.

  1"""Basic definitions relating to source code, context, errors, etc."""
  2
  3from utils import *
  4from pico_preprocess import k_tab_break
  5
  6def get_line_col(text, idx, start=0): # (0-based)
  7    line = 0
  8
  9    while start < idx:
 10        end = text.find("\n", start)
 11        if end < 0 or end >= idx:
 12            break
 13        line += 1
 14        start = end + 1
 15    
 16    return line, idx - start
 17
 18def get_tab_line_col(text, idx, start=0): # (0-based)
 19    tab = 0
 20
 21    while start < idx and tab < 15:
 22        end = text.find(k_tab_break, start)
 23        if end < 0 or end >= idx:
 24            break
 25        tab += 1
 26        start = end + len(k_tab_break)
 27    
 28    line, col = get_line_col(text, idx, start)
 29    return tab, line, col
 30
 31class SourceLocation(Tuple):
 32    """A location in a source file (optionally with a tab)"""
 33    path = tab = line = col = ... # (0-based)
 34
 35def get_source_location(path, text, idx, start_line=0, tabs=False):
 36    if tabs:
 37        tab, line, col = get_tab_line_col(text, idx)
 38    else:
 39        tab, line, col = None, *get_line_col(text, idx)
 40    return SourceLocation(path, tab, line + start_line, col)
 41
 42class Source: # keep this light - created for temp. tokenizations
 43    """A pico8 source file - e.g. either the main one or an included file"""
 44    path = text = ...
 45
 46    def __init__(m, path, text):
 47        m.path, m.text = path, text
 48        
 49    def get_location(m, idx, tabs=False): # (0-based)
 50        return get_source_location(m.path, m.text, idx, tabs=tabs)
 51    
 52    # not a super-source
 53    is_super = False
 54    def __iter__(m):
 55        yield m
 56
 57class CartSource(Source):
 58    """The source of a pico8 cart, maps indexes in the preprocessed code to individual source files"""
 59    def __init__(m, cart, _=None):
 60        m.cart = cart
 61        m.mappings = cart.code_map
 62        # no super().__init__ - we override with properties
 63
 64    def get_location(m, idx, tabs=False):
 65        for mapping in reversed(m.mappings):
 66            if idx >= mapping.idx:
 67                mapped_idx = mapping.src_idx + (idx - mapping.idx)
 68                return get_source_location(mapping.src_path, mapping.src_code, mapped_idx, mapping.src_line, tabs=tabs)
 69        
 70        return super().get_location(idx, tabs)
 71
 72    @property
 73    def path(m):
 74        return m.cart.path
 75        
 76    @property
 77    def text(m):
 78        return m.cart.code
 79
 80    @text.setter
 81    def text(m, val):
 82        m.cart.set_code_without_title(val)
 83
 84class SubLanguageBase:
 85    """Base class of a custom 'sub-language' instance (a language embedded in a pico8 string, see README for more info),
 86    defining how to minify/lint/etc itself.
 87    See readme for documentation & description of members."""
 88    def __init__(m, str, **_):
 89        pass
 90    def get_defined_globals(m, **_):
 91        return ()
 92    def get_used_globals(m, **_):
 93        return ()
 94    def lint(m, **_):
 95        pass
 96    get_unminified_chars = None # or def get_unminified_chars(m, **_):
 97    def get_global_usages(m, **_):
 98        return dict()
 99    def get_member_usages(m, **_):
100        return dict()
101    def get_local_usages(m, **_):
102        return dict()
103    def rename(m, **_):
104        pass
105    minify = None # or def minify(m, **_):
106
107class CompilerBase:
108    """Base class of a custom compiler instance (which can process pico8 code between rename and minify)
109    See readme for documentation & description of members."""
110    def __init__(m, **_):
111        pass
112    def get_dynamic_includes(m, **_):
113        return ()
114    def compile(m, root, **_):
115        pass
116
117@context_manager("finish")
118class ContextBase:
119    """Defines information for how code is to be processed, e.g. the supported builtins, the supported version, the language, etc."""
120    def __init__(m, lang, builtins, local_builtins, builtins_with_callbacks, builtin_callbacks, builtin_members,
121                 extra_builtins=None, not_builtins=None, use_local_builtins=True, extra_local_builtins=None, 
122                 srcmap=False, include_getter=None, sublang_getter=None, compiler_getter=None, default_compiler=None,
123                 version=sys.maxsize, hint_comments=True, consts=None, ignore_transforms=False):
124        m.builtins = builtins.copy()
125        m.local_builtins = local_builtins.copy() if use_local_builtins else set()
126        m.builtins_with_callbacks = builtins_with_callbacks
127        m.builtin_callbacks = builtin_callbacks
128        m.builtin_members = builtin_members
129        
130        if extra_builtins:
131            m.builtins |= set(extra_builtins)
132        if not_builtins:
133            m.builtins -= set(not_builtins)
134            m.local_builtins -= set(not_builtins)
135        if extra_local_builtins:
136            m.builtins |= set(extra_local_builtins)
137            m.local_builtins |= set(extra_local_builtins)
138
139        m.srcmap = [] if srcmap else None
140        m.consts = consts
141        m.ignore_transforms = ignore_transforms
142        m.include_getter = include_getter
143        m.sublang_getter = sublang_getter
144        m.compiler_getter = compiler_getter
145        m.default_compiler = default_compiler
146        m.custom_aliases = None
147        m.hint_comments = hint_comments
148        m.version = version
149        m.lang = lang
150        m.fields = {}
151        m.at_finish = []
152        
153    local_renames = global_renames = member_renames = label_renames = None
154    
155    def add_custom_alias(m, source, target, args):
156        if m.custom_aliases is None:
157            m.custom_aliases = {}
158        m.custom_aliases[source] = (target, args)
159    
160    def map_aliases(m, name, args):
161        while m.custom_aliases and name in m.custom_aliases:
162            name, pre_args = m.custom_aliases[name]
163            if pre_args:
164                if args:
165                    args = pre_args + " " + args
166                else:
167                    args = pre_args
168        return name, args.strip()
169    
170    def get_field(m, name, cls=None):
171        """get a custom field, for convenience"""
172        if name in m.fields:
173            return m.fields[name]
174        elif cls is None:
175            raise Exception(f"field {name} doesn't exist on ctxt")
176        else:
177            field = cls()
178            m.fields[name] = field
179            return field
180    
181    def set_field(m, name, value):
182        """set a custom field, for convenience"""
183        m.fields[name] = value
184    
185    def finish(m):
186        at_finish, m.at_finish = m.at_finish, None
187        for cb in at_finish:
188            cb(ctxt=m)
189
190class ErrorFormat(Enum):
191    common = absolute = tabbed = ...
192
193class Error:
194    """An error (or warning) to be reported together with where in the source it occured"""
195    def __init__(m, msg, token):
196        m.msg, m.token = msg, token
197
198    def __lt__(m, other):
199        return m.token.idx < other.token.idx
200
201    def format(m, fmt=None):
202        fmt = default(fmt, ErrorFormat.common)
203        tabbed = fmt == ErrorFormat.tabbed
204        token = m.token
205        loc = token.source.get_location(token.idx, tabs=tabbed) if token.source else SourceLocation("???", 0, 0, 0)
206        path = path_absolute(loc.path) if fmt == ErrorFormat.absolute else path_relative(loc.path)
207        if tabbed:
208            return f"{path} (tab {loc.tab:X}, line {loc.line + 1}, col {loc.col + 1}): {m.msg}"
209        else:
210            return f"{path}:{loc.line + 1}:{loc.col + 1}: {m.msg}"
211
212    def __str__(m):
213        return m.format()
214
215class Focus(Bitmask):
216    """Defines what to focus on while minifying"""
217    chars = compressed = tokens = ...
218    none = 0
def get_line_col(text, idx, start=0):
 7def get_line_col(text, idx, start=0): # (0-based)
 8    line = 0
 9
10    while start < idx:
11        end = text.find("\n", start)
12        if end < 0 or end >= idx:
13            break
14        line += 1
15        start = end + 1
16    
17    return line, idx - start
def get_tab_line_col(text, idx, start=0):
19def get_tab_line_col(text, idx, start=0): # (0-based)
20    tab = 0
21
22    while start < idx and tab < 15:
23        end = text.find(k_tab_break, start)
24        if end < 0 or end >= idx:
25            break
26        tab += 1
27        start = end + len(k_tab_break)
28    
29    line, col = get_line_col(text, idx, start)
30    return tab, line, col
class SourceLocation(utils.Tuple):
32class SourceLocation(Tuple):
33    """A location in a source file (optionally with a tab)"""
34    path = tab = line = col = ... # (0-based)

A location in a source file (optionally with a tab)

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])

tab

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])

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])

col

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])

def get_source_location(path, text, idx, start_line=0, tabs=False):
36def get_source_location(path, text, idx, start_line=0, tabs=False):
37    if tabs:
38        tab, line, col = get_tab_line_col(text, idx)
39    else:
40        tab, line, col = None, *get_line_col(text, idx)
41    return SourceLocation(path, tab, line + start_line, col)
class Source:
43class Source: # keep this light - created for temp. tokenizations
44    """A pico8 source file - e.g. either the main one or an included file"""
45    path = text = ...
46
47    def __init__(m, path, text):
48        m.path, m.text = path, text
49        
50    def get_location(m, idx, tabs=False): # (0-based)
51        return get_source_location(m.path, m.text, idx, tabs=tabs)
52    
53    # not a super-source
54    is_super = False
55    def __iter__(m):
56        yield m

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

Source(path, text)
47    def __init__(m, path, text):
48        m.path, m.text = path, text
def get_location(m, idx, tabs=False):
50    def get_location(m, idx, tabs=False): # (0-based)
51        return get_source_location(m.path, m.text, idx, tabs=tabs)
is_super = False
path = Ellipsis
text = Ellipsis
class CartSource(Source):
58class CartSource(Source):
59    """The source of a pico8 cart, maps indexes in the preprocessed code to individual source files"""
60    def __init__(m, cart, _=None):
61        m.cart = cart
62        m.mappings = cart.code_map
63        # no super().__init__ - we override with properties
64
65    def get_location(m, idx, tabs=False):
66        for mapping in reversed(m.mappings):
67            if idx >= mapping.idx:
68                mapped_idx = mapping.src_idx + (idx - mapping.idx)
69                return get_source_location(mapping.src_path, mapping.src_code, mapped_idx, mapping.src_line, tabs=tabs)
70        
71        return super().get_location(idx, tabs)
72
73    @property
74    def path(m):
75        return m.cart.path
76        
77    @property
78    def text(m):
79        return m.cart.code
80
81    @text.setter
82    def text(m, val):
83        m.cart.set_code_without_title(val)

The source of a pico8 cart, maps indexes in the preprocessed code to individual source files

CartSource(cart, _=None)
60    def __init__(m, cart, _=None):
61        m.cart = cart
62        m.mappings = cart.code_map
63        # no super().__init__ - we override with properties
def get_location(m, idx, tabs=False):
65    def get_location(m, idx, tabs=False):
66        for mapping in reversed(m.mappings):
67            if idx >= mapping.idx:
68                mapped_idx = mapping.src_idx + (idx - mapping.idx)
69                return get_source_location(mapping.src_path, mapping.src_code, mapped_idx, mapping.src_line, tabs=tabs)
70        
71        return super().get_location(idx, tabs)
path
73    @property
74    def path(m):
75        return m.cart.path

The type of the Ellipsis singleton.

text
77    @property
78    def text(m):
79        return m.cart.code

The type of the Ellipsis singleton.

Inherited Members
Source
is_super
class SubLanguageBase:
 85class SubLanguageBase:
 86    """Base class of a custom 'sub-language' instance (a language embedded in a pico8 string, see README for more info),
 87    defining how to minify/lint/etc itself.
 88    See readme for documentation & description of members."""
 89    def __init__(m, str, **_):
 90        pass
 91    def get_defined_globals(m, **_):
 92        return ()
 93    def get_used_globals(m, **_):
 94        return ()
 95    def lint(m, **_):
 96        pass
 97    get_unminified_chars = None # or def get_unminified_chars(m, **_):
 98    def get_global_usages(m, **_):
 99        return dict()
100    def get_member_usages(m, **_):
101        return dict()
102    def get_local_usages(m, **_):
103        return dict()
104    def rename(m, **_):
105        pass
106    minify = None # or def minify(m, **_):

Base class of a custom 'sub-language' instance (a language embedded in a pico8 string, see README for more info), defining how to minify/lint/etc itself. See readme for documentation & description of members.

SubLanguageBase(str, **_)
89    def __init__(m, str, **_):
90        pass
def get_defined_globals(m, **_):
91    def get_defined_globals(m, **_):
92        return ()
def get_used_globals(m, **_):
93    def get_used_globals(m, **_):
94        return ()
def lint(m, **_):
95    def lint(m, **_):
96        pass
get_unminified_chars = None
def get_global_usages(m, **_):
98    def get_global_usages(m, **_):
99        return dict()
def get_member_usages(m, **_):
100    def get_member_usages(m, **_):
101        return dict()
def get_local_usages(m, **_):
102    def get_local_usages(m, **_):
103        return dict()
def rename(m, **_):
104    def rename(m, **_):
105        pass
minify = None
class CompilerBase:
108class CompilerBase:
109    """Base class of a custom compiler instance (which can process pico8 code between rename and minify)
110    See readme for documentation & description of members."""
111    def __init__(m, **_):
112        pass
113    def get_dynamic_includes(m, **_):
114        return ()
115    def compile(m, root, **_):
116        pass

Base class of a custom compiler instance (which can process pico8 code between rename and minify) See readme for documentation & description of members.

CompilerBase(**_)
111    def __init__(m, **_):
112        pass
def get_dynamic_includes(m, **_):
113    def get_dynamic_includes(m, **_):
114        return ()
def compile(m, root, **_):
115    def compile(m, root, **_):
116        pass
@context_manager('finish')
class ContextBase:
118@context_manager("finish")
119class ContextBase:
120    """Defines information for how code is to be processed, e.g. the supported builtins, the supported version, the language, etc."""
121    def __init__(m, lang, builtins, local_builtins, builtins_with_callbacks, builtin_callbacks, builtin_members,
122                 extra_builtins=None, not_builtins=None, use_local_builtins=True, extra_local_builtins=None, 
123                 srcmap=False, include_getter=None, sublang_getter=None, compiler_getter=None, default_compiler=None,
124                 version=sys.maxsize, hint_comments=True, consts=None, ignore_transforms=False):
125        m.builtins = builtins.copy()
126        m.local_builtins = local_builtins.copy() if use_local_builtins else set()
127        m.builtins_with_callbacks = builtins_with_callbacks
128        m.builtin_callbacks = builtin_callbacks
129        m.builtin_members = builtin_members
130        
131        if extra_builtins:
132            m.builtins |= set(extra_builtins)
133        if not_builtins:
134            m.builtins -= set(not_builtins)
135            m.local_builtins -= set(not_builtins)
136        if extra_local_builtins:
137            m.builtins |= set(extra_local_builtins)
138            m.local_builtins |= set(extra_local_builtins)
139
140        m.srcmap = [] if srcmap else None
141        m.consts = consts
142        m.ignore_transforms = ignore_transforms
143        m.include_getter = include_getter
144        m.sublang_getter = sublang_getter
145        m.compiler_getter = compiler_getter
146        m.default_compiler = default_compiler
147        m.custom_aliases = None
148        m.hint_comments = hint_comments
149        m.version = version
150        m.lang = lang
151        m.fields = {}
152        m.at_finish = []
153        
154    local_renames = global_renames = member_renames = label_renames = None
155    
156    def add_custom_alias(m, source, target, args):
157        if m.custom_aliases is None:
158            m.custom_aliases = {}
159        m.custom_aliases[source] = (target, args)
160    
161    def map_aliases(m, name, args):
162        while m.custom_aliases and name in m.custom_aliases:
163            name, pre_args = m.custom_aliases[name]
164            if pre_args:
165                if args:
166                    args = pre_args + " " + args
167                else:
168                    args = pre_args
169        return name, args.strip()
170    
171    def get_field(m, name, cls=None):
172        """get a custom field, for convenience"""
173        if name in m.fields:
174            return m.fields[name]
175        elif cls is None:
176            raise Exception(f"field {name} doesn't exist on ctxt")
177        else:
178            field = cls()
179            m.fields[name] = field
180            return field
181    
182    def set_field(m, name, value):
183        """set a custom field, for convenience"""
184        m.fields[name] = value
185    
186    def finish(m):
187        at_finish, m.at_finish = m.at_finish, None
188        for cb in at_finish:
189            cb(ctxt=m)

Defines information for how code is to be processed, e.g. the supported builtins, the supported version, the language, etc.

ContextBase( lang, builtins, local_builtins, builtins_with_callbacks, builtin_callbacks, builtin_members, extra_builtins=None, not_builtins=None, use_local_builtins=True, extra_local_builtins=None, srcmap=False, include_getter=None, sublang_getter=None, compiler_getter=None, default_compiler=None, version=9223372036854775807, hint_comments=True, consts=None, ignore_transforms=False)
121    def __init__(m, lang, builtins, local_builtins, builtins_with_callbacks, builtin_callbacks, builtin_members,
122                 extra_builtins=None, not_builtins=None, use_local_builtins=True, extra_local_builtins=None, 
123                 srcmap=False, include_getter=None, sublang_getter=None, compiler_getter=None, default_compiler=None,
124                 version=sys.maxsize, hint_comments=True, consts=None, ignore_transforms=False):
125        m.builtins = builtins.copy()
126        m.local_builtins = local_builtins.copy() if use_local_builtins else set()
127        m.builtins_with_callbacks = builtins_with_callbacks
128        m.builtin_callbacks = builtin_callbacks
129        m.builtin_members = builtin_members
130        
131        if extra_builtins:
132            m.builtins |= set(extra_builtins)
133        if not_builtins:
134            m.builtins -= set(not_builtins)
135            m.local_builtins -= set(not_builtins)
136        if extra_local_builtins:
137            m.builtins |= set(extra_local_builtins)
138            m.local_builtins |= set(extra_local_builtins)
139
140        m.srcmap = [] if srcmap else None
141        m.consts = consts
142        m.ignore_transforms = ignore_transforms
143        m.include_getter = include_getter
144        m.sublang_getter = sublang_getter
145        m.compiler_getter = compiler_getter
146        m.default_compiler = default_compiler
147        m.custom_aliases = None
148        m.hint_comments = hint_comments
149        m.version = version
150        m.lang = lang
151        m.fields = {}
152        m.at_finish = []
def add_custom_alias(m, source, target, args):
156    def add_custom_alias(m, source, target, args):
157        if m.custom_aliases is None:
158            m.custom_aliases = {}
159        m.custom_aliases[source] = (target, args)
def map_aliases(m, name, args):
161    def map_aliases(m, name, args):
162        while m.custom_aliases and name in m.custom_aliases:
163            name, pre_args = m.custom_aliases[name]
164            if pre_args:
165                if args:
166                    args = pre_args + " " + args
167                else:
168                    args = pre_args
169        return name, args.strip()
def get_field(m, name, cls=None):
171    def get_field(m, name, cls=None):
172        """get a custom field, for convenience"""
173        if name in m.fields:
174            return m.fields[name]
175        elif cls is None:
176            raise Exception(f"field {name} doesn't exist on ctxt")
177        else:
178            field = cls()
179            m.fields[name] = field
180            return field

get a custom field, for convenience

def set_field(m, name, value):
182    def set_field(m, name, value):
183        """set a custom field, for convenience"""
184        m.fields[name] = value

set a custom field, for convenience

def finish(m):
186    def finish(m):
187        at_finish, m.at_finish = m.at_finish, None
188        for cb in at_finish:
189            cb(ctxt=m)
local_renames = None
global_renames = None
member_renames = None
label_renames = None
class ErrorFormat(utils.Enum):
191class ErrorFormat(Enum):
192    common = absolute = tabbed = ...

If a class has Enum as a baseclass, it's transformed into an enum. All non-private attributes of the class other than functions and descriptors become enum members. Atributes with a value of ... receive values automatically. Inherited classes behave like regular classes unless they have Enum as a direct baseclass. Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter Atributes with a name ending with _ can be referred to without the _.

ErrorFormat(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
class Error:
194class Error:
195    """An error (or warning) to be reported together with where in the source it occured"""
196    def __init__(m, msg, token):
197        m.msg, m.token = msg, token
198
199    def __lt__(m, other):
200        return m.token.idx < other.token.idx
201
202    def format(m, fmt=None):
203        fmt = default(fmt, ErrorFormat.common)
204        tabbed = fmt == ErrorFormat.tabbed
205        token = m.token
206        loc = token.source.get_location(token.idx, tabs=tabbed) if token.source else SourceLocation("???", 0, 0, 0)
207        path = path_absolute(loc.path) if fmt == ErrorFormat.absolute else path_relative(loc.path)
208        if tabbed:
209            return f"{path} (tab {loc.tab:X}, line {loc.line + 1}, col {loc.col + 1}): {m.msg}"
210        else:
211            return f"{path}:{loc.line + 1}:{loc.col + 1}: {m.msg}"
212
213    def __str__(m):
214        return m.format()

An error (or warning) to be reported together with where in the source it occured

Error(msg, token)
196    def __init__(m, msg, token):
197        m.msg, m.token = msg, token
def format(m, fmt=None):
202    def format(m, fmt=None):
203        fmt = default(fmt, ErrorFormat.common)
204        tabbed = fmt == ErrorFormat.tabbed
205        token = m.token
206        loc = token.source.get_location(token.idx, tabs=tabbed) if token.source else SourceLocation("???", 0, 0, 0)
207        path = path_absolute(loc.path) if fmt == ErrorFormat.absolute else path_relative(loc.path)
208        if tabbed:
209            return f"{path} (tab {loc.tab:X}, line {loc.line + 1}, col {loc.col + 1}): {m.msg}"
210        else:
211            return f"{path}:{loc.line + 1}:{loc.col + 1}: {m.msg}"
class Focus(utils.Bitmask):
216class Focus(Bitmask):
217    """Defines what to focus on while minifying"""
218    chars = compressed = tokens = ...
219    none = 0

Defines what to focus on while minifying

Focus(value=None, **kwargs)
272        def __init__(m, value = None, **kwargs):
273            if value is None:
274                m.value = 0
275            elif isinstance(value, int) and (value & full_mask) == value:
276                m.value = value
277            elif isinstance(value, str) and value in full_name_mask_map:
278                m.value = full_name_mask_map[value]
279            elif isinstance(value, m.__class__):
280                m.value = value.value
281            elif isinstance(value, (tuple, list)):
282                m.value = reduce(lambda x,y:x|y, (full_name_mask_map[part] for part in value), 0)
283            else:
284                raise ValueError(f"{value} not value of {cls_name}")
285        
286            if kwargs:
287                for key, value in kwargs.items():
288                    setattr(m, key, value)
none
chars
compressed
tokens
value