pico_tokenize

Definitions of pico8 tokens, and functions for parsing them from a string

  1"""Definitions of pico8 tokens, and functions for parsing them from a string"""
  2
  3from utils import *
  4from pico_preprocess import k_wspace
  5from pico_defs import Language, k_fixnum_mask, num_to_fixnum, num_to_luaint, is_luaint_in_range
  6from pico_srcdefs import Error, Source
  7
  8keywords = {
  9    "and", "break", "do", "else", "elseif", "end", "false", 
 10    "for", "function", "goto", "if", "in", "local", "nil", 
 11    "not", "or", "repeat", "return", "then", "true", "until",
 12    "while"
 13}
 14
 15def split_hint_args(data, ctxt=None):
 16    name, args = list_unpack(data.strip().split(" ", 1), 2, "")
 17    name, args = name.strip(), args.strip()
 18    if ctxt and ctxt.map_aliases:
 19        name, args = ctxt.map_aliases(name, args)
 20    return name, args
 21
 22class StopTraverse(BaseException):
 23    pass
 24
 25k_skip_children = True # value returnable from traverse's pre-function
 26
 27class KeepCommentFlags(Bitmask):
 28    first = last = ...
 29
 30class TokenNodeBase:
 31    """Baseclass for syntax Tokens, syntax Nodes, and Comments.
 32    The syntax tree is comprised of these and can be traversed via traverse_nodes or traverse_tokens"""
 33
 34    def __init__(m):
 35        m.parent, m.children = None, ()
 36
 37    def __repr__(m):
 38        return "%s(type=%s)" % (typename(m), m.type)
 39
 40    def __str__(m):
 41        reprlist = []
 42        for key, val in m.__dict__.items():
 43            if key in ("parent", "children", "idx", "endidx", "vline", "lang", "modified", "source",
 44                       "scope", "extra_i", "extra_children", "stmts", "globals", "members"):
 45                continue
 46            reprlist.append("%s=%r" % (key, val))
 47        return "%s(%s)" % (typename(m), ", ".join(reprlist))
 48    
 49    @property
 50    def is_token(m):
 51        return False
 52    @property
 53    def is_node(m):
 54        return False
 55
 56    @property
 57    def source_text(m):
 58        if m.source and m.idx != None and m.endidx != None:
 59            return m.source.text[m.idx:m.endidx]
 60        else:
 61            return None
 62    
 63    def find_parent(m, type):
 64        parent = m.parent
 65        while parent and parent.type != type:
 66            parent = parent.parent
 67        return parent
 68
 69    def _sibling(m, delta):
 70        parent = m.parent
 71        if parent is None:
 72            return None
 73        i = parent.children.index(m) + delta
 74        return list_get(parent.children, i)
 75
 76    def next_sibling(m): return m._sibling(1)
 77    def prev_sibling(m): return m._sibling(-1)
 78
 79    def _adjacent(m, delta):
 80        while m:
 81            sib = m._sibling(delta)
 82            if sib:
 83                return sib
 84            m = m.parent
 85        return None
 86
 87    def _find_token(m, delta, adjacent=False):
 88        i = 0 if delta > 0 else -1
 89        if adjacent:
 90            m = m._adjacent(delta)
 91        while m and m.is_node:
 92            if m.children:
 93                m = m.children[i]
 94            else:
 95                m = m._adjacent(delta)
 96        return m if m else Token.none
 97
 98    def next_token(m): return m._find_token(1, adjacent=True)
 99    def prev_token(m): return m._find_token(-1, adjacent=True)
100
101    def first_token(m): return m._find_token(1)
102    def last_token(m): return m._find_token(-1)
103
104    def find_or_create_token(m, child_i=0, last=False):
105        for_child = child_i < len(m.children) and not last
106        if for_child:
107            m = m.children[child_i]
108        token = m.first_token() if for_child else m.next_token()
109        is_after = True
110        if token is Token.none:
111            token = m.next_token() if for_child else m.last_token()
112            is_after = for_child
113            if token is Token.none:
114                token = m.prev_token()
115                is_after = False
116                if token is Token.none:
117                    token = Token.dummy(m.source)
118                    # we should only reach here when m is an empty node of some kind
119                    m.append_existing(token)
120        return token, is_after
121
122    def traverse_nodes(m, pre=None, post=None, tokens=None, extra=False):
123        skip = pre(m) if pre else None
124        if not skip:
125            for child in m.children:
126                if child.is_node:
127                    child.traverse_nodes(pre, post, tokens, extra)
128                elif tokens:
129                    tokens(child)
130            if extra and hasattr(m, "extra_children"):
131                for child in m.extra_children:
132                    child.traverse_nodes(pre, post, tokens, extra)
133        if post: post(m)
134
135    def traverse_tokens(m, visit):
136        if m.is_token:
137            visit(m)
138        else:
139            for child in m.children:
140                if child.is_node:
141                    child.traverse_tokens(visit)
142                else:
143                    visit(child)
144    
145    def traverse_parents(m, visit):
146        parent = m.parent
147        while parent:
148            visit(parent)
149            parent = parent.parent
150
151    def collect_comments(m, irrelevant=False, flags=None):
152        comments = []
153        def visit(token):
154            nonlocal comments
155            comments += token.children
156        
157        if isinstance(flags, KeepCommentFlags):
158            first_token = m.first_token() if flags.first else None
159            last_token = m.last_token() if flags.last else None
160            if first_token:
161                visit(first_token)
162            if last_token and last_token != first_token:
163                visit(last_token)
164        else:
165            m.traverse_tokens(visit)
166
167        if irrelevant:
168            comments = [c for c in comments if c.hint != CommentHint.auto]
169        return comments
170
171    def add_extra_child(m, child):
172        if not hasattr(m, "extra_children"):
173            m.extra_children = []
174        child.parent = m
175        child.extra_i = len(m.extra_children)
176        m.extra_children.append(child)
177    
178    def is_extra_child(m):
179        return hasattr(m, "extra_i")
180    
181    def move(m): # create a "destructive" copy - old object is no longer usable unless replaced
182        cpy = copy(m)
183        for child in cpy.children:
184            child.parent = cpy
185        m.erase()
186        return cpy
187
188    def copy(m):
189        cpy = copy(m)
190        cpy.children = [child.copy() for child in m.children]
191        for child in cpy.children:
192            child.parent = cpy
193        for key, val in cpy.__dict__.items():
194            idx = list_find(m.children, val)
195            if idx >= 0:
196                cpy.__dict__[key] = cpy.children[idx]
197        return cpy
198
199class TokenType(Enum):
200    number = string = ident = keyword = punct = ...
201    compiler = ... # special
202
203class Token(TokenNodeBase):
204    """A pico8 token, at 'source'.text['idx':'endidx'] (which is equal to its 'value'). Its 'type' is a TokenType.
205    For number/string tokens, the actual value is 'parsed_value'
206    Its children are the comments *before* it, if any."""
207
208    def __init__(m, type, value, source, idx, endidx, vline, lang, modified=False):
209        super().__init__()
210        m.type, m.value, m.source, m.idx, m.endidx, m.vline, m.lang, m.modified = type, value, source, idx, endidx, vline, lang, modified
211    
212    @property
213    def is_token(m):
214        return True
215
216    def check(m, expected):
217        if isinstance(expected, tuple):
218            assert m.value in expected
219        else:
220            assert m.value == expected
221
222    def modify(m, value, expected=None):
223        if expected != None:
224            m.check(expected)
225        m.value = value
226        m.modified = True
227        lazy_property.clear(m, "parsed_value")
228    
229    def erase(m, expected=None):
230        if expected != None:
231            m.check(expected)
232        m.type, m.value, m.modified = None, None, True
233
234    def add_comments(m, comments, first=False):
235        if m.children == ():
236            m.children = []
237        if first:
238            m.children[0:0] = comments
239        else:
240            m.children += comments
241    
242    def remove_comments(m):
243        m.children = ()
244
245    @lazy_property
246    def parsed_value(m):
247        if m.type == TokenType.number:
248            if m.lang == Language.picotron:
249                return parse_luanum(m.value)
250            else:
251                return parse_fixnum(m.value)
252        elif m.type == TokenType.string:
253            return parse_string_literal(m.value, m.lang)
254        else:
255            return None
256
257    @classmethod
258    def dummy(cls, source):
259        idx = len(source.text) if source else 0
260        vline = sys.maxsize if source else 0
261        return cls(None, None, source, idx, idx, vline, None)
262
263    @classmethod
264    def synthetic(cls, type, value, other, append=False, prepend=False):
265        idx = other.endidx if append else other.idx
266        endidx = other.idx if prepend else other.endidx
267        return cls(type, value, other.source, idx, endidx, other.vline, other.lang, modified=True)
268
269Token.none = Token.dummy(None)
270
271class CommentHint(Enum):
272    none = auto = preserve = lint = keep = ...
273
274k_keep_prefix = "keep:"
275
276class Comment(TokenNodeBase):
277    """A pico8 comment, optionally holding some kind of hint"""
278
279    def __init__(m, isblock, hint, hintdata=None, hintprefix="", source=None, idx=None, endidx=None, vline=None, modified=False):
280        super().__init__()
281        m.isblock, m.hint, m.hintdata, m.hintprefix = isblock, hint, hintdata, hintprefix
282        m.source, m.idx, m.endidx, m.vline, m.modified = source, idx, endidx, vline, modified
283
284    def modify(m, value):
285        m.value = value
286        m.modified = True
287
288    @property
289    def value(m):
290        return m.source_text
291
292def is_ident_char(ch, lang=Language.pico8):
293    return ('0' <= ch <= '9' or 'a' <= ch <= 'z' or 'A' <= ch <= 'Z' or ch == '_' or
294            (lang == Language.pico8 and (ch in ('\x1e', '\x1f') or ch >= '\x80')))
295
296def is_identifier(str, lang=Language.pico8):
297    return str and all(is_ident_char(ch, lang) for ch in str) and not str[:1].isdigit() and str not in keywords
298    
299k_identifier_split_re = r"([0-9A-Za-z_\x1e\x1f\x80-\xff]+)"
300
301k_hint_split_re = re.compile(r"[\s,]+")
302
303class VarKind(Enum):
304    local = global_ = member = label = ...
305    
306class NextTokenMods:
307    def __init__(m):
308        m.var_kind = m.keys_kind = m.is_const = m.func_kind = m.merge_prev = m.force_safe = m.sublang = m.rename = m.placeholder = None
309        m.comments = None
310        
311    def add_comment(m, cmt):
312        if m.comments is None:
313            m.comments = []
314        m.comments.append(cmt)
315
316def tokenize(source, ctxt=None, all_comments=False, lang=None, inner=False):
317    """Parse a string (in source.text), returning a list of tokens and a list of errors"""
318
319    text = source.text
320    idx = 0
321    vline = 0
322    tokens = []
323    errors = []
324    real_tokens = None
325    next_mods = None
326    if lang is None:
327        lang = ctxt.lang if ctxt else Language.pico8
328    
329    is_pico8 = lang == Language.pico8
330    is_picotron = lang == Language.picotron
331
332    def peek(off=0):
333        i = idx + off
334        return text[i] if 0 <= i < len(text) else ''
335
336    def take():
337        nonlocal idx
338        ch = peek()
339        idx += 1
340        return ch
341
342    def accept(ch,):
343        nonlocal idx
344        if peek() == ch:
345            idx += 1
346            return True
347        return False
348
349    def accept_one_of(*chs):
350        nonlocal idx
351        if peek() in chs:
352            idx += 1
353            return True
354        return False
355
356    def get_next_mods():
357        nonlocal next_mods
358        if next_mods is None:
359            next_mods = NextTokenMods()
360        return next_mods
361
362    def add_token(type, start, end_off=0, value=None):
363        end = idx + end_off
364        if value is None and type is not None: # (dummy tokens have type==value==None)
365            value = text[start:end]
366        token = Token(type, value, source, start, end, vline, lang)
367        tokens.append(token)
368        
369        nonlocal next_mods
370        if next_mods != None:
371            add_next_mods(token, next_mods)
372            next_mods = None
373        return token
374
375    def add_error(msg, off=-1):
376        add_token(None, idx + off) # error token
377        errors.append(Error(msg, tokens[-1]))
378
379    def add_dyn_include(include_data):
380        if ctxt and ctxt.include_getter and not ctxt.ignore_transforms:
381            include_name, include_args = split_hint_args(include_data, ctxt)
382            include_func = ctxt.include_getter(include_name)
383            if include_func:
384                included_str = include_func(args=include_args, ctxt=ctxt)
385                if included_str != None:
386                    included_tokens, included_errors = tokenize(Source(include_name, included_str), ctxt, all_comments, inner=True)
387                    tokens.extend(included_tokens)
388                    errors.extend(included_errors)
389                    return
390            eprint("warning - ignoring unrecognized dynamic include '%s'" % include_name)
391
392    def add_sublang(token, sublang_data):
393        if ctxt and ctxt.sublang_getter and token.type == TokenType.string:
394            sublang_name, sublang_args = split_hint_args(sublang_data, ctxt)
395
396            sublang_cls = ctxt.sublang_getter(sublang_name)
397            if sublang_cls:
398                add_lang_error = lambda msg: add_error(f"{sublang_name}: {msg}")
399                token.sublang_name = sublang_name
400                token.sublang = sublang_cls(token.parsed_value, args=sublang_args,
401                                            ctxt=ctxt, on_error=add_lang_error)
402            else:
403                eprint("warning - ignoring unrecognized language '%s'" % sublang_name)
404
405    def switch_compiler(compiler_data):
406        nonlocal real_tokens, tokens
407        if real_tokens != None:
408            real_tokens, tokens = None, real_tokens
409
410        if compiler_data != None:
411            if ctxt and ctxt.compiler_getter and not ctxt.ignore_transforms:
412                compiler_name, compiler_args = split_hint_args(compiler_data, ctxt)
413                if compiler_name != "none":
414                    compiler_cls = ctxt.compiler_getter(compiler_name)
415                    if compiler_cls:
416                        curr_compiler = compiler_cls(args=compiler_args, ctxt=ctxt, src=source)
417                        for dyn_include in curr_compiler.get_dynamic_includes():
418                            add_dyn_include(dyn_include)
419                        
420                        compiler_token = add_token(TokenType.compiler, idx, value="`compiler`")
421                        compiler_token.compiler_name = compiler_name
422                        compiler_token.compiler = curr_compiler
423                        compiler_token.compiler_tokens = []
424                        real_tokens, tokens = tokens, compiler_token.compiler_tokens
425
426                    else:
427                        eprint("warning - ignoring unrecognized compiler '%s'" % compiler_name)
428
429    def add_next_mods(token, mods):
430        if mods.comments != None:
431            token.children = mods.comments        
432        if mods.var_kind != None:
433            token.var_kind = mods.var_kind
434        if mods.keys_kind != None:
435            token.keys_kind = mods.keys_kind
436        if mods.is_const != None:
437            token.is_const = mods.is_const
438        if mods.func_kind != None:
439            token.func_kind = mods.func_kind
440        if mods.merge_prev != None:
441            token.merge_prev = mods.merge_prev
442        if mods.force_safe != None:
443            token.force_safe = mods.force_safe
444        if mods.rename != None:
445            token.rename = mods.rename
446        if mods.placeholder != None:
447            token.placeholder_name, token.placeholder_args = split_hint_args(mods.placeholder[0], ctxt)
448            token.placeholder_expr = mods.placeholder[1]
449            if not (token.type == TokenType.string if token.placeholder_expr else token.value == 'do'):
450                eprint(f"invalid usage of $placeholder: {token.placeholder_name}")
451        if mods.sublang != None:
452            add_sublang(token, mods.sublang)
453
454    def process_comment(orig_idx, comment, isblock):
455        hint, hintdata, hintprefix = CommentHint.none, None, ""
456
457        if ctxt and ctxt.hint_comments:
458            proper = False
459            if comment.startswith("$"):
460                comment = comment[1:]
461                hintprefix = "$"
462                proper = True
463
464            if comment.startswith("lint:"):
465                lints = k_hint_split_re.split(str_after_first(comment, ":"))
466                lints = [lint for lint in lints if lint]
467                hint, hintdata = CommentHint.lint, lints
468
469                for lint in lints:
470                    if lint.startswith("func::"):
471                        get_next_mods().func_kind = str_after_first(lint, "::")
472
473            elif comment.startswith("preserve:"):
474                preserves = k_hint_split_re.split(str_after_first(comment, ":"))
475                preserves = [preserve for preserve in preserves if preserve]
476                hint, hintdata = CommentHint.preserve, preserves
477
478            elif comment.startswith(k_keep_prefix):
479                hint = CommentHint.keep
480                
481            elif comment.startswith("dynamic-include:") and proper:
482                add_dyn_include(str_after_first(comment, ":"))
483                hint = CommentHint.auto
484            
485            elif (comment.startswith("def-alias:") and proper) or comment.startswith("deflanguage:"): # deflanguage is deprecated
486                alias_name, alias_value = list_unpack(str_after_first(comment, ":").split("=", 1), 2, "")
487                dest_name, dest_args = split_hint_args(alias_value, ctxt)
488                if ctxt and ctxt.add_custom_alias:
489                    ctxt.add_custom_alias(alias_name.strip(), dest_name, dest_args)
490                hint = CommentHint.auto
491                
492            elif comment.startswith("switch-compiler:") and proper:
493                switch_compiler(str_after_first(comment, ":"))
494                hint = CommentHint.auto
495
496            elif isblock:
497                hint = CommentHint.auto
498                if comment in ("global", "nameof"): # nameof is deprecated
499                    get_next_mods().var_kind = VarKind.global_
500                elif comment in ("member", "memberof"): # memberof is deprecated
501                    get_next_mods().var_kind = VarKind.member
502                elif comment in ("preserve", "string"): # string is deprecated
503                    get_next_mods().var_kind = False
504                elif comment == "global-keys":
505                    get_next_mods().keys_kind = VarKind.global_
506                elif comment == "member-keys":
507                    get_next_mods().keys_kind = VarKind.member
508                elif comment in ("preserve-keys", "string-keys"): # string-keys is deprecated
509                    get_next_mods().keys_kind = False
510                elif comment == "no-merge":
511                    get_next_mods().merge_prev = False
512                elif comment == "const":
513                    get_next_mods().is_const = True
514                elif comment == "non-const":
515                    get_next_mods().is_const = False
516                elif comment == "force-safe":
517                    get_next_mods().force_safe = True
518                elif comment.startswith("language::"):
519                    get_next_mods().sublang = str_after_first(comment, "::")
520                elif comment.startswith("rename::") and not any(ch.isspace() for ch in comment):
521                    get_next_mods().rename = str_after_first(comment, "::")
522                elif comment.startswith("placeholder-expr::") and proper:
523                    get_next_mods().placeholder = (str_after_first(comment, "::"), True)
524                elif comment.startswith("placeholder-stmt::") and proper:
525                    get_next_mods().placeholder = (str_after_first(comment, "::"), False)
526                else:
527                    hint = CommentHint.none
528        
529            if proper and hint == CommentHint.none:
530                eprint(f"unrecognized $-comment '{comment}'")
531            # at some point, warn about improper comments and so on?
532
533        if all_comments or (hint != CommentHint.none and hint != CommentHint.auto):
534            get_next_mods().add_comment(Comment(isblock, hint, hintdata, hintprefix, source, orig_idx, idx, vline))
535        
536    def tokenize_line_comment():
537        nonlocal vline
538        orig_idx = idx
539        while take() not in ('\n', ''): pass
540
541        process_comment(orig_idx - 2, text[orig_idx:idx], isblock=False)
542        vline += 1
543
544    def tokenize_long_brackets(off):
545        nonlocal idx
546        idx += off
547        orig_idx = idx
548
549        if accept('['):
550            pad_idx = idx
551            while accept('='): pass
552            pad = text[pad_idx:idx]
553
554            if accept('['):
555                start_i = idx
556                end_i = text.find(f"]{pad}]", idx)
557                if end_i >= 0:
558                    idx = end_i + len(pad) + 2
559                    return True, orig_idx, start_i, end_i
560                
561                add_error("Unterminated long comment (no longer accepted by pico8)", 0)
562        
563        return False, orig_idx, None, None
564
565    def tokenize_long_comment():
566        nonlocal idx
567        ok, orig_idx, start, end = tokenize_long_brackets(0)
568        if ok:
569            process_comment(orig_idx - 2, text[start:end], isblock=True)
570        else:
571            idx = orig_idx
572        return ok
573
574    def tokenize_number(off):
575        nonlocal idx
576        idx += off
577        orig_idx = idx
578
579        if is_picotron:
580            is_hex = peek() == '0' and peek(1) in ('x', 'X')
581
582            while True:
583                ch = peek()
584                if (is_ident_char(ch, lang) or ch == '.' or
585                        (ch in ('-', '+') and peek(-1) in (('p', 'P') if is_hex else ('e', 'E')))):
586                    idx += 1
587                else:
588                    break
589
590        else:
591            ch = peek()
592            if ch == '0' and peek(1) in ('b', 'B'):
593                idx += 2
594                digits = "01"
595            elif ch == '0' and peek(1) in ('x', 'X'):
596                idx += 2
597                digits = "0123456789aAbBcCdDeEfF"
598            else:
599                digits = "0123456789"
600
601            while True:
602                ch = peek()
603                if ch and ch in digits:
604                    idx += 1
605                elif ch == '.':
606                    idx += 1
607                else:
608                    break
609
610        add_token(TokenType.number, orig_idx)
611
612    def tokenize_ident(off):
613        nonlocal idx
614        idx += off
615        orig_idx = idx
616        
617        while is_ident_char(peek(), lang):
618            idx += 1
619            
620        if text[orig_idx:idx] in keywords:
621            add_token(TokenType.keyword, orig_idx)
622        else:
623            add_token(TokenType.ident, orig_idx)
624
625    def tokenize_string(off):
626        nonlocal idx
627        orig_idx = idx + off
628        idx = orig_idx + 1
629        quote = text[orig_idx]
630
631        while True:
632            ch = take()
633            if ch in ('\n', ''):
634                add_error("Unterminated string", orig_idx - idx)
635                break
636            elif ch == '\\':
637                if accept('z'): # skip line breaks
638                    while peek() in k_wspace:
639                        take()
640                else:
641                    take() # at least
642            elif ch == quote:
643                break
644
645        add_token(TokenType.string, orig_idx)
646
647    def tokenize_long_string(off):
648        ok, orig_idx, _, _ = tokenize_long_brackets(off)
649        if ok:
650            add_token(TokenType.string, orig_idx)
651        else:
652            add_error("Invalid long brackets")
653    
654    if ctxt and ctxt.default_compiler and not inner:
655        switch_compiler(ctxt.default_compiler)
656
657    while idx < len(text):
658        ch = take()
659
660        if ch in k_wspace: # whitespace
661            if ch == "\n":
662                vline += 1
663
664        elif '0' <= ch <= '9' or (ch == '.' and '0' <= peek() <= '9'): # number
665            tokenize_number(-1)
666
667        elif is_ident_char(ch, lang): # identifier
668            tokenize_ident(-1)
669
670        elif ch in ('"', "'"): # string
671            tokenize_string(-1)
672
673        elif ch == '[' and accept_one_of('=', '['): # long string
674            tokenize_long_string(-2)
675
676        elif ch == '-' and accept('-'): # comment
677            if not tokenize_long_comment():
678                tokenize_line_comment()
679
680        elif ch == '/' and is_pico8 and accept('/'): # c-style comment
681            tokenize_line_comment()
682
683        elif ch in "+-*/\\%&|^<>=~#()[]{};,?@$.:": # punctuation
684            orig_idx = idx - 1
685            if ch in ".:/^<>" and accept(ch):
686                if ch in (".>" if is_pico8 else ".") and accept(ch):
687                    if ch == ">": accept('=')
688                elif ch in "<>" and is_pico8 and accept(">" if ch == "<" else "<"):
689                    accept('=')
690                elif ch in "./^<>":
691                    accept('=')
692            elif ch in "+-*/\\%&|^<>=~":
693                accept('=')
694            add_token(TokenType.punct, orig_idx)
695
696        elif ch == '!' and accept('='): # alt. punctuation
697            add_token(TokenType.punct, idx - 2)
698
699        else:
700            add_error("invalid character")
701    
702    if (next_mods or all_comments) and not inner:
703        add_token(None, idx) # end token, for ending whitespace/comments/etc (TBD: lost if inner...)
704
705    if real_tokens != None:
706        switch_compiler(None)
707    return tokens, errors
708    
709
710def count_tokens(tokens):
711    count = 0
712    for i, token in enumerate(tokens):
713        if token.children:
714            for comment in token.children:
715                if comment.hint == CommentHint.lint and "count::stop" in comment.hintdata:
716                    return count
717
718        if token.value in (",", ".", ":", ";", "::", ")", "]", "}", "end", "local", None):
719            continue
720
721        if (token.value in ("-", "~") and i+1 < len(tokens) and tokens[i+1].type == TokenType.number and
722                token.endidx == tokens[i+1].idx and
723                i-1 >= 0 and tokens[i-1].type not in (TokenType.number, TokenType.string, TokenType.ident) and
724                tokens[i-1].value not in (")", "]", "}", ";", "end")):
725            continue
726
727        count += 1
728    return count
729
730def parse_fixnum(origstr):
731    """parse a fixnum from a pico8 string"""
732    str = origstr.lower()
733    
734    neg = bnot = False
735    if str.startswith("-"):
736        str = str[1:]
737        neg = True
738    elif str.startswith("~"):
739        str = str[1:]
740        bnot = True
741
742    digits = "0123456789"
743    if str.startswith("0x"):
744        digits += "abcdef"
745        str = str[2:]
746    elif str.startswith("0b"):
747        digits = "01"
748        str = str[2:]
749    base = len(digits)
750
751    value = 0
752    while str and str[0] in digits:
753        value = (value * base) + digits.index(str[0])
754        str = str[1:]
755
756    if str and str[0] == '.':
757        str = str[1:]
758        dotvalue = 0
759        dotdigits = 0
760        while str and str[0] in digits:
761            dotvalue = (dotvalue * base) + digits.index(str[0])
762            dotdigits += 1
763            str = str[1:]
764        
765        value += dotvalue / (base ** dotdigits)
766    
767    if str:
768        throw(f"Invalid pico8 number: {origstr}")
769
770    fixnum = num_to_fixnum(value)
771    if neg:
772        fixnum = -fixnum & k_fixnum_mask
773    elif bnot:
774        fixnum = ~fixnum & k_fixnum_mask
775
776    return fixnum
777
778def parse_luanum(origstr):
779    """Parse a picotron lua number from a string"""
780    str = origstr.lower()
781
782    neg = False
783    if str.startswith("-"):
784        str = str[1:]
785        neg = True
786
787    try:
788        if str.startswith("0x"):
789            if "." in str or "p" in str:
790                try:
791                    value = float.fromhex(str)
792                except OverflowError:
793                    value = float('inf')
794            else:
795                value = num_to_luaint(int(str, base=16))
796        
797        elif str.startswith("0b"):
798            # TODO: recheck this if ever fixed to support exponents?
799            # TODO: recheck this if current 0b2 through 0bf bug stays around, and support it if so?
800            dotpos = str.find(".")
801            if dotpos >= 0:
802                str = str_replace_at(str, dotpos, 1, "")
803            value = int(str, base=2)
804            if dotpos >= 0:
805                try:
806                    value = math.ldexp(value, dotpos - len(str))
807                except OverflowError:
808                    value = float('inf')
809            else:
810                value = num_to_luaint(value)
811            
812        else:
813            if "." in str or "e" in str:
814                value = float(str) # no OverflowError here
815            else:
816                value = int(str)
817                if is_luaint_in_range(value): # intentionally disregarding the possibility of 'neg'
818                    value = num_to_luaint(value)
819                else:
820                    value = float(value)
821    except ValueError:
822        throw(f"Invalid lua number: {origstr}")
823    
824    if neg:
825        value = -value
826    return value
827
828k_char_escapes = {
829    '*': '\1', '#': '\2', '-': '\3', '|': '\4', '+': '\5', '^': '\6',
830    'a': '\a', 'b': '\b', 't': '\t', 'n': '\n', 'v': '\v', 'f': '\f', 'r': '\r',
831    '\\': '\\', '"': '"', "'": "'", '\n': '\n',
832}
833
834def lang_chr(value, lang):
835    if lang == Language.pico8 or value < 0x80:
836        return chr(value)
837    else:
838        return chr(0xdc00 + value) # surrogate escape
839
840def ext_unicode_to_lang_str(value, lang):
841    if value < 0x80:
842        return lang_chr(value, lang)
843    
844    suffix = ""
845    count = 0
846    while value >= (0x40 >> count):
847        suffix = lang_chr(0x80 + (value & 0x3f), lang) + suffix
848        value >>= 6
849        count += 1
850    return lang_chr(((-0x80 >> count) & 0xff) + value, lang) + suffix
851
852def parse_char_escape(str, pos, lang):
853    "parse an escape sequence (pos is the position of the '\\', which isn't checked)"
854
855    esc = str_get(str, pos + 1)
856    esc_ch = k_char_escapes.get(esc)
857    if esc_ch:
858        return esc_ch, pos + 2
859
860    elif esc == 'z':
861        end = pos + 2
862        while str_get(str, end) in k_wspace:
863            end += 1
864        return "", end
865
866    elif esc == 'x':
867        end = pos + 4
868        hex_esc = str[pos + 2 : end]
869        value = maybe_int(hex_esc, base=16)
870        if value is None:
871            throw(f"Invalid hex escape: '{hex_esc}' in: '{str}'")
872        return lang_chr(value, lang), end
873
874    elif '0' <= esc <= '9':
875        end = pos + 2
876        while end < pos + 4 and '0' <= str_get(str, end, '') <= '9':
877            end += 1
878        dec_esc = str[pos + 1 : end]
879        value = maybe_int(dec_esc)
880        if value is None or value >= 256:
881            throw(f"Invalid dec escape: '{dec_esc}' in: '{str}'")
882        return lang_chr(value, lang), end
883
884    elif lang == Language.picotron and esc == 'u':
885        check(str_get(str, pos + 2) == "{", f"Invalid unicode escape in: '{str}'")
886        end = str.find("}", pos) + 1
887        check(end > 0, f"Unterminated unicode escape in: '{str}'")
888        uni_esc = str[pos + 3 : end - 1]
889        value = maybe_int(uni_esc, base=16)
890        if value is None or value >= 0x80000000:
891            throw(f"Invalid uni escape: '{uni_esc}' in: '{str}'")
892        return ext_unicode_to_lang_str(value, lang), end
893
894    else:
895        throw(f"Invalid escape: '{esc}' in: '{str}'")    
896
897def parse_string_literal(str, lang=Language.pico8):
898    """parse a pico8 string from a pico8 string literal"""
899    if str.startswith("["):
900        start = str.index("[", 1) + 1
901        lit = str[start:-start]
902        lit = re.sub(r"\n\r?|\r\n?", "\n", lit)
903        if lit.startswith('\n'):
904            lit = lit[1:]
905        return lit
906
907    else:
908        litparts = []
909        str = str[1:-1]
910        start = 0
911        while start < len(str):
912            end = str.find('\\', start)
913            if end < 0:
914                litparts.append(str[start:])
915                break
916
917            if end > start:
918                litparts.append(str[start:end])
919
920            esc, start = parse_char_escape(str, end, lang)
921            litparts.append(esc)
922                
923        return "".join(litparts)
keywords = {'return', 'until', 'nil', 'or', 'and', 'while', 'false', 'in', 'then', 'if', 'do', 'goto', 'else', 'not', 'end', 'true', 'local', 'elseif', 'break', 'for', 'function', 'repeat'}
def split_hint_args(data, ctxt=None):
16def split_hint_args(data, ctxt=None):
17    name, args = list_unpack(data.strip().split(" ", 1), 2, "")
18    name, args = name.strip(), args.strip()
19    if ctxt and ctxt.map_aliases:
20        name, args = ctxt.map_aliases(name, args)
21    return name, args
class StopTraverse(builtins.BaseException):
23class StopTraverse(BaseException):
24    pass

Common base class for all exceptions

k_skip_children = True
class KeepCommentFlags(utils.Bitmask):
28class KeepCommentFlags(Bitmask):
29    first = last = ...

If a class has Bitmask as a baseclass, it's transformed into a bitmask. All non-private attributes of the class other than functions and descriptors become bitmask fields. Atributes with a value of ... receive bits automatically. A bitmask is like a struct, but with its fields mapped into a single bitmask integer. Bitmasks can also be manipulated via: & | ^ Inherited classes behave like regular classes unless they have Bitmask as a direct baseclass. Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter Atributes with a name ending with _ can be referred to without the _.

KeepCommentFlags(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)
first
last
value
class TokenNodeBase:
 31class TokenNodeBase:
 32    """Baseclass for syntax Tokens, syntax Nodes, and Comments.
 33    The syntax tree is comprised of these and can be traversed via traverse_nodes or traverse_tokens"""
 34
 35    def __init__(m):
 36        m.parent, m.children = None, ()
 37
 38    def __repr__(m):
 39        return "%s(type=%s)" % (typename(m), m.type)
 40
 41    def __str__(m):
 42        reprlist = []
 43        for key, val in m.__dict__.items():
 44            if key in ("parent", "children", "idx", "endidx", "vline", "lang", "modified", "source",
 45                       "scope", "extra_i", "extra_children", "stmts", "globals", "members"):
 46                continue
 47            reprlist.append("%s=%r" % (key, val))
 48        return "%s(%s)" % (typename(m), ", ".join(reprlist))
 49    
 50    @property
 51    def is_token(m):
 52        return False
 53    @property
 54    def is_node(m):
 55        return False
 56
 57    @property
 58    def source_text(m):
 59        if m.source and m.idx != None and m.endidx != None:
 60            return m.source.text[m.idx:m.endidx]
 61        else:
 62            return None
 63    
 64    def find_parent(m, type):
 65        parent = m.parent
 66        while parent and parent.type != type:
 67            parent = parent.parent
 68        return parent
 69
 70    def _sibling(m, delta):
 71        parent = m.parent
 72        if parent is None:
 73            return None
 74        i = parent.children.index(m) + delta
 75        return list_get(parent.children, i)
 76
 77    def next_sibling(m): return m._sibling(1)
 78    def prev_sibling(m): return m._sibling(-1)
 79
 80    def _adjacent(m, delta):
 81        while m:
 82            sib = m._sibling(delta)
 83            if sib:
 84                return sib
 85            m = m.parent
 86        return None
 87
 88    def _find_token(m, delta, adjacent=False):
 89        i = 0 if delta > 0 else -1
 90        if adjacent:
 91            m = m._adjacent(delta)
 92        while m and m.is_node:
 93            if m.children:
 94                m = m.children[i]
 95            else:
 96                m = m._adjacent(delta)
 97        return m if m else Token.none
 98
 99    def next_token(m): return m._find_token(1, adjacent=True)
100    def prev_token(m): return m._find_token(-1, adjacent=True)
101
102    def first_token(m): return m._find_token(1)
103    def last_token(m): return m._find_token(-1)
104
105    def find_or_create_token(m, child_i=0, last=False):
106        for_child = child_i < len(m.children) and not last
107        if for_child:
108            m = m.children[child_i]
109        token = m.first_token() if for_child else m.next_token()
110        is_after = True
111        if token is Token.none:
112            token = m.next_token() if for_child else m.last_token()
113            is_after = for_child
114            if token is Token.none:
115                token = m.prev_token()
116                is_after = False
117                if token is Token.none:
118                    token = Token.dummy(m.source)
119                    # we should only reach here when m is an empty node of some kind
120                    m.append_existing(token)
121        return token, is_after
122
123    def traverse_nodes(m, pre=None, post=None, tokens=None, extra=False):
124        skip = pre(m) if pre else None
125        if not skip:
126            for child in m.children:
127                if child.is_node:
128                    child.traverse_nodes(pre, post, tokens, extra)
129                elif tokens:
130                    tokens(child)
131            if extra and hasattr(m, "extra_children"):
132                for child in m.extra_children:
133                    child.traverse_nodes(pre, post, tokens, extra)
134        if post: post(m)
135
136    def traverse_tokens(m, visit):
137        if m.is_token:
138            visit(m)
139        else:
140            for child in m.children:
141                if child.is_node:
142                    child.traverse_tokens(visit)
143                else:
144                    visit(child)
145    
146    def traverse_parents(m, visit):
147        parent = m.parent
148        while parent:
149            visit(parent)
150            parent = parent.parent
151
152    def collect_comments(m, irrelevant=False, flags=None):
153        comments = []
154        def visit(token):
155            nonlocal comments
156            comments += token.children
157        
158        if isinstance(flags, KeepCommentFlags):
159            first_token = m.first_token() if flags.first else None
160            last_token = m.last_token() if flags.last else None
161            if first_token:
162                visit(first_token)
163            if last_token and last_token != first_token:
164                visit(last_token)
165        else:
166            m.traverse_tokens(visit)
167
168        if irrelevant:
169            comments = [c for c in comments if c.hint != CommentHint.auto]
170        return comments
171
172    def add_extra_child(m, child):
173        if not hasattr(m, "extra_children"):
174            m.extra_children = []
175        child.parent = m
176        child.extra_i = len(m.extra_children)
177        m.extra_children.append(child)
178    
179    def is_extra_child(m):
180        return hasattr(m, "extra_i")
181    
182    def move(m): # create a "destructive" copy - old object is no longer usable unless replaced
183        cpy = copy(m)
184        for child in cpy.children:
185            child.parent = cpy
186        m.erase()
187        return cpy
188
189    def copy(m):
190        cpy = copy(m)
191        cpy.children = [child.copy() for child in m.children]
192        for child in cpy.children:
193            child.parent = cpy
194        for key, val in cpy.__dict__.items():
195            idx = list_find(m.children, val)
196            if idx >= 0:
197                cpy.__dict__[key] = cpy.children[idx]
198        return cpy

Baseclass for syntax Tokens, syntax Nodes, and Comments. The syntax tree is comprised of these and can be traversed via traverse_nodes or traverse_tokens

is_token
50    @property
51    def is_token(m):
52        return False
is_node
53    @property
54    def is_node(m):
55        return False
source_text
57    @property
58    def source_text(m):
59        if m.source and m.idx != None and m.endidx != None:
60            return m.source.text[m.idx:m.endidx]
61        else:
62            return None
def find_parent(m, type):
64    def find_parent(m, type):
65        parent = m.parent
66        while parent and parent.type != type:
67            parent = parent.parent
68        return parent
def next_sibling(m):
77    def next_sibling(m): return m._sibling(1)
def prev_sibling(m):
78    def prev_sibling(m): return m._sibling(-1)
def next_token(m):
99    def next_token(m): return m._find_token(1, adjacent=True)
def prev_token(m):
100    def prev_token(m): return m._find_token(-1, adjacent=True)
def first_token(m):
102    def first_token(m): return m._find_token(1)
def last_token(m):
103    def last_token(m): return m._find_token(-1)
def find_or_create_token(m, child_i=0, last=False):
105    def find_or_create_token(m, child_i=0, last=False):
106        for_child = child_i < len(m.children) and not last
107        if for_child:
108            m = m.children[child_i]
109        token = m.first_token() if for_child else m.next_token()
110        is_after = True
111        if token is Token.none:
112            token = m.next_token() if for_child else m.last_token()
113            is_after = for_child
114            if token is Token.none:
115                token = m.prev_token()
116                is_after = False
117                if token is Token.none:
118                    token = Token.dummy(m.source)
119                    # we should only reach here when m is an empty node of some kind
120                    m.append_existing(token)
121        return token, is_after
def traverse_nodes(m, pre=None, post=None, tokens=None, extra=False):
123    def traverse_nodes(m, pre=None, post=None, tokens=None, extra=False):
124        skip = pre(m) if pre else None
125        if not skip:
126            for child in m.children:
127                if child.is_node:
128                    child.traverse_nodes(pre, post, tokens, extra)
129                elif tokens:
130                    tokens(child)
131            if extra and hasattr(m, "extra_children"):
132                for child in m.extra_children:
133                    child.traverse_nodes(pre, post, tokens, extra)
134        if post: post(m)
def traverse_tokens(m, visit):
136    def traverse_tokens(m, visit):
137        if m.is_token:
138            visit(m)
139        else:
140            for child in m.children:
141                if child.is_node:
142                    child.traverse_tokens(visit)
143                else:
144                    visit(child)
def traverse_parents(m, visit):
146    def traverse_parents(m, visit):
147        parent = m.parent
148        while parent:
149            visit(parent)
150            parent = parent.parent
def collect_comments(m, irrelevant=False, flags=None):
152    def collect_comments(m, irrelevant=False, flags=None):
153        comments = []
154        def visit(token):
155            nonlocal comments
156            comments += token.children
157        
158        if isinstance(flags, KeepCommentFlags):
159            first_token = m.first_token() if flags.first else None
160            last_token = m.last_token() if flags.last else None
161            if first_token:
162                visit(first_token)
163            if last_token and last_token != first_token:
164                visit(last_token)
165        else:
166            m.traverse_tokens(visit)
167
168        if irrelevant:
169            comments = [c for c in comments if c.hint != CommentHint.auto]
170        return comments
def add_extra_child(m, child):
172    def add_extra_child(m, child):
173        if not hasattr(m, "extra_children"):
174            m.extra_children = []
175        child.parent = m
176        child.extra_i = len(m.extra_children)
177        m.extra_children.append(child)
def is_extra_child(m):
179    def is_extra_child(m):
180        return hasattr(m, "extra_i")
def move(m):
182    def move(m): # create a "destructive" copy - old object is no longer usable unless replaced
183        cpy = copy(m)
184        for child in cpy.children:
185            child.parent = cpy
186        m.erase()
187        return cpy
def copy(m):
189    def copy(m):
190        cpy = copy(m)
191        cpy.children = [child.copy() for child in m.children]
192        for child in cpy.children:
193            child.parent = cpy
194        for key, val in cpy.__dict__.items():
195            idx = list_find(m.children, val)
196            if idx >= 0:
197                cpy.__dict__[key] = cpy.children[idx]
198        return cpy
class TokenType(utils.Enum):
200class TokenType(Enum):
201    number = string = ident = keyword = punct = ...
202    compiler = ... # special

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 _.

TokenType(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}")
compiler = TokenType.compiler
value
number = TokenType.number
string = TokenType.string
ident = TokenType.ident
keyword = TokenType.keyword
punct = TokenType.punct
class Token(TokenNodeBase):
204class Token(TokenNodeBase):
205    """A pico8 token, at 'source'.text['idx':'endidx'] (which is equal to its 'value'). Its 'type' is a TokenType.
206    For number/string tokens, the actual value is 'parsed_value'
207    Its children are the comments *before* it, if any."""
208
209    def __init__(m, type, value, source, idx, endidx, vline, lang, modified=False):
210        super().__init__()
211        m.type, m.value, m.source, m.idx, m.endidx, m.vline, m.lang, m.modified = type, value, source, idx, endidx, vline, lang, modified
212    
213    @property
214    def is_token(m):
215        return True
216
217    def check(m, expected):
218        if isinstance(expected, tuple):
219            assert m.value in expected
220        else:
221            assert m.value == expected
222
223    def modify(m, value, expected=None):
224        if expected != None:
225            m.check(expected)
226        m.value = value
227        m.modified = True
228        lazy_property.clear(m, "parsed_value")
229    
230    def erase(m, expected=None):
231        if expected != None:
232            m.check(expected)
233        m.type, m.value, m.modified = None, None, True
234
235    def add_comments(m, comments, first=False):
236        if m.children == ():
237            m.children = []
238        if first:
239            m.children[0:0] = comments
240        else:
241            m.children += comments
242    
243    def remove_comments(m):
244        m.children = ()
245
246    @lazy_property
247    def parsed_value(m):
248        if m.type == TokenType.number:
249            if m.lang == Language.picotron:
250                return parse_luanum(m.value)
251            else:
252                return parse_fixnum(m.value)
253        elif m.type == TokenType.string:
254            return parse_string_literal(m.value, m.lang)
255        else:
256            return None
257
258    @classmethod
259    def dummy(cls, source):
260        idx = len(source.text) if source else 0
261        vline = sys.maxsize if source else 0
262        return cls(None, None, source, idx, idx, vline, None)
263
264    @classmethod
265    def synthetic(cls, type, value, other, append=False, prepend=False):
266        idx = other.endidx if append else other.idx
267        endidx = other.idx if prepend else other.endidx
268        return cls(type, value, other.source, idx, endidx, other.vline, other.lang, modified=True)

A pico8 token, at 'source'.text['idx':'endidx'] (which is equal to its 'value'). Its 'type' is a TokenType. For number/string tokens, the actual value is 'parsed_value' Its children are the comments before it, if any.

Token(type, value, source, idx, endidx, vline, lang, modified=False)
209    def __init__(m, type, value, source, idx, endidx, vline, lang, modified=False):
210        super().__init__()
211        m.type, m.value, m.source, m.idx, m.endidx, m.vline, m.lang, m.modified = type, value, source, idx, endidx, vline, lang, modified
is_token
213    @property
214    def is_token(m):
215        return True
def check(m, expected):
217    def check(m, expected):
218        if isinstance(expected, tuple):
219            assert m.value in expected
220        else:
221            assert m.value == expected
def modify(m, value, expected=None):
223    def modify(m, value, expected=None):
224        if expected != None:
225            m.check(expected)
226        m.value = value
227        m.modified = True
228        lazy_property.clear(m, "parsed_value")
def erase(m, expected=None):
230    def erase(m, expected=None):
231        if expected != None:
232            m.check(expected)
233        m.type, m.value, m.modified = None, None, True
def add_comments(m, comments, first=False):
235    def add_comments(m, comments, first=False):
236        if m.children == ():
237            m.children = []
238        if first:
239            m.children[0:0] = comments
240        else:
241            m.children += comments
def remove_comments(m):
243    def remove_comments(m):
244        m.children = ()
def parsed_value(unknown):

Method decorator that turns it into a lazily-evaluated property

@classmethod
def dummy(cls, source):
258    @classmethod
259    def dummy(cls, source):
260        idx = len(source.text) if source else 0
261        vline = sys.maxsize if source else 0
262        return cls(None, None, source, idx, idx, vline, None)
@classmethod
def synthetic(cls, type, value, other, append=False, prepend=False):
264    @classmethod
265    def synthetic(cls, type, value, other, append=False, prepend=False):
266        idx = other.endidx if append else other.idx
267        endidx = other.idx if prepend else other.endidx
268        return cls(type, value, other.source, idx, endidx, other.vline, other.lang, modified=True)
none = Token(type=None)
class CommentHint(utils.Enum):
272class CommentHint(Enum):
273    none = auto = preserve = lint = keep = ...

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 _.

CommentHint(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
k_keep_prefix = 'keep:'
class Comment(TokenNodeBase):
277class Comment(TokenNodeBase):
278    """A pico8 comment, optionally holding some kind of hint"""
279
280    def __init__(m, isblock, hint, hintdata=None, hintprefix="", source=None, idx=None, endidx=None, vline=None, modified=False):
281        super().__init__()
282        m.isblock, m.hint, m.hintdata, m.hintprefix = isblock, hint, hintdata, hintprefix
283        m.source, m.idx, m.endidx, m.vline, m.modified = source, idx, endidx, vline, modified
284
285    def modify(m, value):
286        m.value = value
287        m.modified = True
288
289    @property
290    def value(m):
291        return m.source_text

A pico8 comment, optionally holding some kind of hint

Comment( isblock, hint, hintdata=None, hintprefix='', source=None, idx=None, endidx=None, vline=None, modified=False)
280    def __init__(m, isblock, hint, hintdata=None, hintprefix="", source=None, idx=None, endidx=None, vline=None, modified=False):
281        super().__init__()
282        m.isblock, m.hint, m.hintdata, m.hintprefix = isblock, hint, hintdata, hintprefix
283        m.source, m.idx, m.endidx, m.vline, m.modified = source, idx, endidx, vline, modified
def modify(m, value):
285    def modify(m, value):
286        m.value = value
287        m.modified = True
value
289    @property
290    def value(m):
291        return m.source_text
def is_ident_char(ch, lang=Language.pico8):
293def is_ident_char(ch, lang=Language.pico8):
294    return ('0' <= ch <= '9' or 'a' <= ch <= 'z' or 'A' <= ch <= 'Z' or ch == '_' or
295            (lang == Language.pico8 and (ch in ('\x1e', '\x1f') or ch >= '\x80')))
def is_identifier(str, lang=Language.pico8):
297def is_identifier(str, lang=Language.pico8):
298    return str and all(is_ident_char(ch, lang) for ch in str) and not str[:1].isdigit() and str not in keywords
k_identifier_split_re = '([0-9A-Za-z_\\x1e\\x1f\\x80-\\xff]+)'
k_hint_split_re = re.compile('[\\s,]+')
class VarKind(utils.Enum):
304class VarKind(Enum):
305    local = global_ = member = label = ...

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 _.

VarKind(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
local = VarKind.local
global_ = VarKind.global
global = VarKind.global
member = VarKind.member
label = VarKind.label
class NextTokenMods:
307class NextTokenMods:
308    def __init__(m):
309        m.var_kind = m.keys_kind = m.is_const = m.func_kind = m.merge_prev = m.force_safe = m.sublang = m.rename = m.placeholder = None
310        m.comments = None
311        
312    def add_comment(m, cmt):
313        if m.comments is None:
314            m.comments = []
315        m.comments.append(cmt)
def add_comment(m, cmt):
312    def add_comment(m, cmt):
313        if m.comments is None:
314            m.comments = []
315        m.comments.append(cmt)
def tokenize(source, ctxt=None, all_comments=False, lang=None, inner=False):
317def tokenize(source, ctxt=None, all_comments=False, lang=None, inner=False):
318    """Parse a string (in source.text), returning a list of tokens and a list of errors"""
319
320    text = source.text
321    idx = 0
322    vline = 0
323    tokens = []
324    errors = []
325    real_tokens = None
326    next_mods = None
327    if lang is None:
328        lang = ctxt.lang if ctxt else Language.pico8
329    
330    is_pico8 = lang == Language.pico8
331    is_picotron = lang == Language.picotron
332
333    def peek(off=0):
334        i = idx + off
335        return text[i] if 0 <= i < len(text) else ''
336
337    def take():
338        nonlocal idx
339        ch = peek()
340        idx += 1
341        return ch
342
343    def accept(ch,):
344        nonlocal idx
345        if peek() == ch:
346            idx += 1
347            return True
348        return False
349
350    def accept_one_of(*chs):
351        nonlocal idx
352        if peek() in chs:
353            idx += 1
354            return True
355        return False
356
357    def get_next_mods():
358        nonlocal next_mods
359        if next_mods is None:
360            next_mods = NextTokenMods()
361        return next_mods
362
363    def add_token(type, start, end_off=0, value=None):
364        end = idx + end_off
365        if value is None and type is not None: # (dummy tokens have type==value==None)
366            value = text[start:end]
367        token = Token(type, value, source, start, end, vline, lang)
368        tokens.append(token)
369        
370        nonlocal next_mods
371        if next_mods != None:
372            add_next_mods(token, next_mods)
373            next_mods = None
374        return token
375
376    def add_error(msg, off=-1):
377        add_token(None, idx + off) # error token
378        errors.append(Error(msg, tokens[-1]))
379
380    def add_dyn_include(include_data):
381        if ctxt and ctxt.include_getter and not ctxt.ignore_transforms:
382            include_name, include_args = split_hint_args(include_data, ctxt)
383            include_func = ctxt.include_getter(include_name)
384            if include_func:
385                included_str = include_func(args=include_args, ctxt=ctxt)
386                if included_str != None:
387                    included_tokens, included_errors = tokenize(Source(include_name, included_str), ctxt, all_comments, inner=True)
388                    tokens.extend(included_tokens)
389                    errors.extend(included_errors)
390                    return
391            eprint("warning - ignoring unrecognized dynamic include '%s'" % include_name)
392
393    def add_sublang(token, sublang_data):
394        if ctxt and ctxt.sublang_getter and token.type == TokenType.string:
395            sublang_name, sublang_args = split_hint_args(sublang_data, ctxt)
396
397            sublang_cls = ctxt.sublang_getter(sublang_name)
398            if sublang_cls:
399                add_lang_error = lambda msg: add_error(f"{sublang_name}: {msg}")
400                token.sublang_name = sublang_name
401                token.sublang = sublang_cls(token.parsed_value, args=sublang_args,
402                                            ctxt=ctxt, on_error=add_lang_error)
403            else:
404                eprint("warning - ignoring unrecognized language '%s'" % sublang_name)
405
406    def switch_compiler(compiler_data):
407        nonlocal real_tokens, tokens
408        if real_tokens != None:
409            real_tokens, tokens = None, real_tokens
410
411        if compiler_data != None:
412            if ctxt and ctxt.compiler_getter and not ctxt.ignore_transforms:
413                compiler_name, compiler_args = split_hint_args(compiler_data, ctxt)
414                if compiler_name != "none":
415                    compiler_cls = ctxt.compiler_getter(compiler_name)
416                    if compiler_cls:
417                        curr_compiler = compiler_cls(args=compiler_args, ctxt=ctxt, src=source)
418                        for dyn_include in curr_compiler.get_dynamic_includes():
419                            add_dyn_include(dyn_include)
420                        
421                        compiler_token = add_token(TokenType.compiler, idx, value="`compiler`")
422                        compiler_token.compiler_name = compiler_name
423                        compiler_token.compiler = curr_compiler
424                        compiler_token.compiler_tokens = []
425                        real_tokens, tokens = tokens, compiler_token.compiler_tokens
426
427                    else:
428                        eprint("warning - ignoring unrecognized compiler '%s'" % compiler_name)
429
430    def add_next_mods(token, mods):
431        if mods.comments != None:
432            token.children = mods.comments        
433        if mods.var_kind != None:
434            token.var_kind = mods.var_kind
435        if mods.keys_kind != None:
436            token.keys_kind = mods.keys_kind
437        if mods.is_const != None:
438            token.is_const = mods.is_const
439        if mods.func_kind != None:
440            token.func_kind = mods.func_kind
441        if mods.merge_prev != None:
442            token.merge_prev = mods.merge_prev
443        if mods.force_safe != None:
444            token.force_safe = mods.force_safe
445        if mods.rename != None:
446            token.rename = mods.rename
447        if mods.placeholder != None:
448            token.placeholder_name, token.placeholder_args = split_hint_args(mods.placeholder[0], ctxt)
449            token.placeholder_expr = mods.placeholder[1]
450            if not (token.type == TokenType.string if token.placeholder_expr else token.value == 'do'):
451                eprint(f"invalid usage of $placeholder: {token.placeholder_name}")
452        if mods.sublang != None:
453            add_sublang(token, mods.sublang)
454
455    def process_comment(orig_idx, comment, isblock):
456        hint, hintdata, hintprefix = CommentHint.none, None, ""
457
458        if ctxt and ctxt.hint_comments:
459            proper = False
460            if comment.startswith("$"):
461                comment = comment[1:]
462                hintprefix = "$"
463                proper = True
464
465            if comment.startswith("lint:"):
466                lints = k_hint_split_re.split(str_after_first(comment, ":"))
467                lints = [lint for lint in lints if lint]
468                hint, hintdata = CommentHint.lint, lints
469
470                for lint in lints:
471                    if lint.startswith("func::"):
472                        get_next_mods().func_kind = str_after_first(lint, "::")
473
474            elif comment.startswith("preserve:"):
475                preserves = k_hint_split_re.split(str_after_first(comment, ":"))
476                preserves = [preserve for preserve in preserves if preserve]
477                hint, hintdata = CommentHint.preserve, preserves
478
479            elif comment.startswith(k_keep_prefix):
480                hint = CommentHint.keep
481                
482            elif comment.startswith("dynamic-include:") and proper:
483                add_dyn_include(str_after_first(comment, ":"))
484                hint = CommentHint.auto
485            
486            elif (comment.startswith("def-alias:") and proper) or comment.startswith("deflanguage:"): # deflanguage is deprecated
487                alias_name, alias_value = list_unpack(str_after_first(comment, ":").split("=", 1), 2, "")
488                dest_name, dest_args = split_hint_args(alias_value, ctxt)
489                if ctxt and ctxt.add_custom_alias:
490                    ctxt.add_custom_alias(alias_name.strip(), dest_name, dest_args)
491                hint = CommentHint.auto
492                
493            elif comment.startswith("switch-compiler:") and proper:
494                switch_compiler(str_after_first(comment, ":"))
495                hint = CommentHint.auto
496
497            elif isblock:
498                hint = CommentHint.auto
499                if comment in ("global", "nameof"): # nameof is deprecated
500                    get_next_mods().var_kind = VarKind.global_
501                elif comment in ("member", "memberof"): # memberof is deprecated
502                    get_next_mods().var_kind = VarKind.member
503                elif comment in ("preserve", "string"): # string is deprecated
504                    get_next_mods().var_kind = False
505                elif comment == "global-keys":
506                    get_next_mods().keys_kind = VarKind.global_
507                elif comment == "member-keys":
508                    get_next_mods().keys_kind = VarKind.member
509                elif comment in ("preserve-keys", "string-keys"): # string-keys is deprecated
510                    get_next_mods().keys_kind = False
511                elif comment == "no-merge":
512                    get_next_mods().merge_prev = False
513                elif comment == "const":
514                    get_next_mods().is_const = True
515                elif comment == "non-const":
516                    get_next_mods().is_const = False
517                elif comment == "force-safe":
518                    get_next_mods().force_safe = True
519                elif comment.startswith("language::"):
520                    get_next_mods().sublang = str_after_first(comment, "::")
521                elif comment.startswith("rename::") and not any(ch.isspace() for ch in comment):
522                    get_next_mods().rename = str_after_first(comment, "::")
523                elif comment.startswith("placeholder-expr::") and proper:
524                    get_next_mods().placeholder = (str_after_first(comment, "::"), True)
525                elif comment.startswith("placeholder-stmt::") and proper:
526                    get_next_mods().placeholder = (str_after_first(comment, "::"), False)
527                else:
528                    hint = CommentHint.none
529        
530            if proper and hint == CommentHint.none:
531                eprint(f"unrecognized $-comment '{comment}'")
532            # at some point, warn about improper comments and so on?
533
534        if all_comments or (hint != CommentHint.none and hint != CommentHint.auto):
535            get_next_mods().add_comment(Comment(isblock, hint, hintdata, hintprefix, source, orig_idx, idx, vline))
536        
537    def tokenize_line_comment():
538        nonlocal vline
539        orig_idx = idx
540        while take() not in ('\n', ''): pass
541
542        process_comment(orig_idx - 2, text[orig_idx:idx], isblock=False)
543        vline += 1
544
545    def tokenize_long_brackets(off):
546        nonlocal idx
547        idx += off
548        orig_idx = idx
549
550        if accept('['):
551            pad_idx = idx
552            while accept('='): pass
553            pad = text[pad_idx:idx]
554
555            if accept('['):
556                start_i = idx
557                end_i = text.find(f"]{pad}]", idx)
558                if end_i >= 0:
559                    idx = end_i + len(pad) + 2
560                    return True, orig_idx, start_i, end_i
561                
562                add_error("Unterminated long comment (no longer accepted by pico8)", 0)
563        
564        return False, orig_idx, None, None
565
566    def tokenize_long_comment():
567        nonlocal idx
568        ok, orig_idx, start, end = tokenize_long_brackets(0)
569        if ok:
570            process_comment(orig_idx - 2, text[start:end], isblock=True)
571        else:
572            idx = orig_idx
573        return ok
574
575    def tokenize_number(off):
576        nonlocal idx
577        idx += off
578        orig_idx = idx
579
580        if is_picotron:
581            is_hex = peek() == '0' and peek(1) in ('x', 'X')
582
583            while True:
584                ch = peek()
585                if (is_ident_char(ch, lang) or ch == '.' or
586                        (ch in ('-', '+') and peek(-1) in (('p', 'P') if is_hex else ('e', 'E')))):
587                    idx += 1
588                else:
589                    break
590
591        else:
592            ch = peek()
593            if ch == '0' and peek(1) in ('b', 'B'):
594                idx += 2
595                digits = "01"
596            elif ch == '0' and peek(1) in ('x', 'X'):
597                idx += 2
598                digits = "0123456789aAbBcCdDeEfF"
599            else:
600                digits = "0123456789"
601
602            while True:
603                ch = peek()
604                if ch and ch in digits:
605                    idx += 1
606                elif ch == '.':
607                    idx += 1
608                else:
609                    break
610
611        add_token(TokenType.number, orig_idx)
612
613    def tokenize_ident(off):
614        nonlocal idx
615        idx += off
616        orig_idx = idx
617        
618        while is_ident_char(peek(), lang):
619            idx += 1
620            
621        if text[orig_idx:idx] in keywords:
622            add_token(TokenType.keyword, orig_idx)
623        else:
624            add_token(TokenType.ident, orig_idx)
625
626    def tokenize_string(off):
627        nonlocal idx
628        orig_idx = idx + off
629        idx = orig_idx + 1
630        quote = text[orig_idx]
631
632        while True:
633            ch = take()
634            if ch in ('\n', ''):
635                add_error("Unterminated string", orig_idx - idx)
636                break
637            elif ch == '\\':
638                if accept('z'): # skip line breaks
639                    while peek() in k_wspace:
640                        take()
641                else:
642                    take() # at least
643            elif ch == quote:
644                break
645
646        add_token(TokenType.string, orig_idx)
647
648    def tokenize_long_string(off):
649        ok, orig_idx, _, _ = tokenize_long_brackets(off)
650        if ok:
651            add_token(TokenType.string, orig_idx)
652        else:
653            add_error("Invalid long brackets")
654    
655    if ctxt and ctxt.default_compiler and not inner:
656        switch_compiler(ctxt.default_compiler)
657
658    while idx < len(text):
659        ch = take()
660
661        if ch in k_wspace: # whitespace
662            if ch == "\n":
663                vline += 1
664
665        elif '0' <= ch <= '9' or (ch == '.' and '0' <= peek() <= '9'): # number
666            tokenize_number(-1)
667
668        elif is_ident_char(ch, lang): # identifier
669            tokenize_ident(-1)
670
671        elif ch in ('"', "'"): # string
672            tokenize_string(-1)
673
674        elif ch == '[' and accept_one_of('=', '['): # long string
675            tokenize_long_string(-2)
676
677        elif ch == '-' and accept('-'): # comment
678            if not tokenize_long_comment():
679                tokenize_line_comment()
680
681        elif ch == '/' and is_pico8 and accept('/'): # c-style comment
682            tokenize_line_comment()
683
684        elif ch in "+-*/\\%&|^<>=~#()[]{};,?@$.:": # punctuation
685            orig_idx = idx - 1
686            if ch in ".:/^<>" and accept(ch):
687                if ch in (".>" if is_pico8 else ".") and accept(ch):
688                    if ch == ">": accept('=')
689                elif ch in "<>" and is_pico8 and accept(">" if ch == "<" else "<"):
690                    accept('=')
691                elif ch in "./^<>":
692                    accept('=')
693            elif ch in "+-*/\\%&|^<>=~":
694                accept('=')
695            add_token(TokenType.punct, orig_idx)
696
697        elif ch == '!' and accept('='): # alt. punctuation
698            add_token(TokenType.punct, idx - 2)
699
700        else:
701            add_error("invalid character")
702    
703    if (next_mods or all_comments) and not inner:
704        add_token(None, idx) # end token, for ending whitespace/comments/etc (TBD: lost if inner...)
705
706    if real_tokens != None:
707        switch_compiler(None)
708    return tokens, errors

Parse a string (in source.text), returning a list of tokens and a list of errors

def count_tokens(tokens):
711def count_tokens(tokens):
712    count = 0
713    for i, token in enumerate(tokens):
714        if token.children:
715            for comment in token.children:
716                if comment.hint == CommentHint.lint and "count::stop" in comment.hintdata:
717                    return count
718
719        if token.value in (",", ".", ":", ";", "::", ")", "]", "}", "end", "local", None):
720            continue
721
722        if (token.value in ("-", "~") and i+1 < len(tokens) and tokens[i+1].type == TokenType.number and
723                token.endidx == tokens[i+1].idx and
724                i-1 >= 0 and tokens[i-1].type not in (TokenType.number, TokenType.string, TokenType.ident) and
725                tokens[i-1].value not in (")", "]", "}", ";", "end")):
726            continue
727
728        count += 1
729    return count
def parse_fixnum(origstr):
731def parse_fixnum(origstr):
732    """parse a fixnum from a pico8 string"""
733    str = origstr.lower()
734    
735    neg = bnot = False
736    if str.startswith("-"):
737        str = str[1:]
738        neg = True
739    elif str.startswith("~"):
740        str = str[1:]
741        bnot = True
742
743    digits = "0123456789"
744    if str.startswith("0x"):
745        digits += "abcdef"
746        str = str[2:]
747    elif str.startswith("0b"):
748        digits = "01"
749        str = str[2:]
750    base = len(digits)
751
752    value = 0
753    while str and str[0] in digits:
754        value = (value * base) + digits.index(str[0])
755        str = str[1:]
756
757    if str and str[0] == '.':
758        str = str[1:]
759        dotvalue = 0
760        dotdigits = 0
761        while str and str[0] in digits:
762            dotvalue = (dotvalue * base) + digits.index(str[0])
763            dotdigits += 1
764            str = str[1:]
765        
766        value += dotvalue / (base ** dotdigits)
767    
768    if str:
769        throw(f"Invalid pico8 number: {origstr}")
770
771    fixnum = num_to_fixnum(value)
772    if neg:
773        fixnum = -fixnum & k_fixnum_mask
774    elif bnot:
775        fixnum = ~fixnum & k_fixnum_mask
776
777    return fixnum

parse a fixnum from a pico8 string

def parse_luanum(origstr):
779def parse_luanum(origstr):
780    """Parse a picotron lua number from a string"""
781    str = origstr.lower()
782
783    neg = False
784    if str.startswith("-"):
785        str = str[1:]
786        neg = True
787
788    try:
789        if str.startswith("0x"):
790            if "." in str or "p" in str:
791                try:
792                    value = float.fromhex(str)
793                except OverflowError:
794                    value = float('inf')
795            else:
796                value = num_to_luaint(int(str, base=16))
797        
798        elif str.startswith("0b"):
799            # TODO: recheck this if ever fixed to support exponents?
800            # TODO: recheck this if current 0b2 through 0bf bug stays around, and support it if so?
801            dotpos = str.find(".")
802            if dotpos >= 0:
803                str = str_replace_at(str, dotpos, 1, "")
804            value = int(str, base=2)
805            if dotpos >= 0:
806                try:
807                    value = math.ldexp(value, dotpos - len(str))
808                except OverflowError:
809                    value = float('inf')
810            else:
811                value = num_to_luaint(value)
812            
813        else:
814            if "." in str or "e" in str:
815                value = float(str) # no OverflowError here
816            else:
817                value = int(str)
818                if is_luaint_in_range(value): # intentionally disregarding the possibility of 'neg'
819                    value = num_to_luaint(value)
820                else:
821                    value = float(value)
822    except ValueError:
823        throw(f"Invalid lua number: {origstr}")
824    
825    if neg:
826        value = -value
827    return value

Parse a picotron lua number from a string

k_char_escapes = {'*': '\x01', '#': '\x02', '-': '\x03', '|': '\x04', '+': '\x05', '^': '\x06', 'a': '\x07', 'b': '\x08', 't': '\t', 'n': '\n', 'v': '\x0b', 'f': '\x0c', 'r': '\r', '\\': '\\', '"': '"', "'": "'", '\n': '\n'}
def lang_chr(value, lang):
835def lang_chr(value, lang):
836    if lang == Language.pico8 or value < 0x80:
837        return chr(value)
838    else:
839        return chr(0xdc00 + value) # surrogate escape
def ext_unicode_to_lang_str(value, lang):
841def ext_unicode_to_lang_str(value, lang):
842    if value < 0x80:
843        return lang_chr(value, lang)
844    
845    suffix = ""
846    count = 0
847    while value >= (0x40 >> count):
848        suffix = lang_chr(0x80 + (value & 0x3f), lang) + suffix
849        value >>= 6
850        count += 1
851    return lang_chr(((-0x80 >> count) & 0xff) + value, lang) + suffix
def parse_char_escape(str, pos, lang):
853def parse_char_escape(str, pos, lang):
854    "parse an escape sequence (pos is the position of the '\\', which isn't checked)"
855
856    esc = str_get(str, pos + 1)
857    esc_ch = k_char_escapes.get(esc)
858    if esc_ch:
859        return esc_ch, pos + 2
860
861    elif esc == 'z':
862        end = pos + 2
863        while str_get(str, end) in k_wspace:
864            end += 1
865        return "", end
866
867    elif esc == 'x':
868        end = pos + 4
869        hex_esc = str[pos + 2 : end]
870        value = maybe_int(hex_esc, base=16)
871        if value is None:
872            throw(f"Invalid hex escape: '{hex_esc}' in: '{str}'")
873        return lang_chr(value, lang), end
874
875    elif '0' <= esc <= '9':
876        end = pos + 2
877        while end < pos + 4 and '0' <= str_get(str, end, '') <= '9':
878            end += 1
879        dec_esc = str[pos + 1 : end]
880        value = maybe_int(dec_esc)
881        if value is None or value >= 256:
882            throw(f"Invalid dec escape: '{dec_esc}' in: '{str}'")
883        return lang_chr(value, lang), end
884
885    elif lang == Language.picotron and esc == 'u':
886        check(str_get(str, pos + 2) == "{", f"Invalid unicode escape in: '{str}'")
887        end = str.find("}", pos) + 1
888        check(end > 0, f"Unterminated unicode escape in: '{str}'")
889        uni_esc = str[pos + 3 : end - 1]
890        value = maybe_int(uni_esc, base=16)
891        if value is None or value >= 0x80000000:
892            throw(f"Invalid uni escape: '{uni_esc}' in: '{str}'")
893        return ext_unicode_to_lang_str(value, lang), end
894
895    else:
896        throw(f"Invalid escape: '{esc}' in: '{str}'")    

parse an escape sequence (pos is the position of the '\', which isn't checked)

def parse_string_literal(str, lang=Language.pico8):
898def parse_string_literal(str, lang=Language.pico8):
899    """parse a pico8 string from a pico8 string literal"""
900    if str.startswith("["):
901        start = str.index("[", 1) + 1
902        lit = str[start:-start]
903        lit = re.sub(r"\n\r?|\r\n?", "\n", lit)
904        if lit.startswith('\n'):
905            lit = lit[1:]
906        return lit
907
908    else:
909        litparts = []
910        str = str[1:-1]
911        start = 0
912        while start < len(str):
913            end = str.find('\\', start)
914            if end < 0:
915                litparts.append(str[start:])
916                break
917
918            if end > start:
919                litparts.append(str[start:end])
920
921            esc, start = parse_char_escape(str, end, lang)
922            litparts.append(esc)
923                
924        return "".join(litparts)

parse a pico8 string from a pico8 string literal