run_shrinko

The main logic for the shrinko command line

  1"""The main logic for the shrinko command line"""
  2
  3from utils import *
  4from pico_process import PicoContext, process_code, CartSource, ErrorFormat
  5from pico_compress import write_code_size, write_compressed_size, CompressionTracer
  6from pico_cart import CartFormat, read_cart, write_cart, get_bbs_cart_url
  7from pico_cart import merge_cart, write_cart_version, k_pico_sections
  8from pico_export import read_cart_export, read_pod_file, ListOp
  9from pico_tokenize import k_hint_split_re
 10from pico_constfold import parse_constant
 11from pico_defs import Language, get_latest_pico8_version, parse_pico8_version
 12from pico_preprocess import IncludeNotFoundError
 13from picotron_defs import PicotronContext, Cart64Source, get_latest_picotron_runtime
 14from picotron_cart import Cart64Format, read_cart64, write_cart64, merge_cart64, filter_cart64, preproc_cart64
 15from picotron_cart import write_cart64_compressed_size, write_cart64_version
 16from picotron_export import read_cart64_export, read_sysrom_file
 17import argparse
 18
 19k_version_raw = '1.2.7.6' # should have 4 parts, used directly by build script (last part becomes letter 0->'', 1->b, etc.)
 20
 21def get_version():
 22    """convert our raw version to pico-style version"""
 23    version, lastdigit = k_version_raw.rsplit(".", 1)
 24    lastdigit = int(lastdigit)
 25    lastchar = string.ascii_lowercase[lastdigit] if lastdigit else ""
 26    return version + lastchar
 27
 28def SplitBySeps(val):
 29    return k_hint_split_re.split(val)
 30
 31def IntSplitBySeps(val):
 32    return [int(val) for val in SplitBySeps(val)]
 33
 34def Indent(val):
 35    return "\t" if val == "tabs" else " " * int(val)
 36
 37def EnumFromStr(enum_type):
 38    def cvt(name):
 39        return enum_type(name.replace("-", "_").replace(" ", "_"))
 40    cvt.__name__ = enum_type.__name__
 41    return cvt
 42
 43def EnumList(enum_type, pred=None):
 44    list = enum_type._values
 45    if pred:
 46        list = filter(lambda name: pred(enum_type(name)), list)
 47    return ", ".join(str.replace("_", "-") for str in list)
 48
 49def ParsableCountHandler(prefix, name, size, limit):
 50    print(f"count:{prefix}:{name}:{size}:{limit}")
 51
 52def lang_not_supported():
 53    throw("operation not supported for this language")
 54def lang_do_nothing(*_, **__):
 55    pass
 56
 57def find_in_builtin_script(name, kwargs, func_name):
 58    import importlib
 59    module_name = "scripts." + str_before_first(name, ".")
 60    try:
 61        module = importlib.import_module(module_name)
 62    except ModuleNotFoundError:
 63        from run_pico import import_pico_script
 64        try:
 65            module = import_pico_script(module_name)
 66        except ModuleNotFoundError:
 67            return None
 68        except IncludeNotFoundError as e:
 69            eprint(f"{e} - could you be missing a 'git submodule update --init'?")
 70            return None
 71    func = getattr(module, func_name, None)
 72    if func:
 73        return func(name, **kwargs)
 74
 75class OneShotFileChangeWatcher:
 76    def __init__(m):
 77        try:
 78            import watchdog.events, watchdog.observers, threading
 79        except ImportError:
 80            throw("You need watchdog to use --watch (do 'python -m pip install watchdog')")
 81
 82        class Handler(watchdog.events.FileSystemEventHandler):
 83            def on_path(mh, path):
 84                dir, name = path_split_name(path)
 85                if dir in m.files_per_dir and name in m.files_per_dir[dir] and not m.event.is_set():
 86                    eprint("%s changed - repeating operation" % name)
 87                    m.event.set()
 88
 89            def on_modified(mh, ev):
 90                mh.on_path(ev.src_path)
 91            
 92            on_deleted = on_created = on_modified
 93
 94            def on_moved(mh, ev):
 95                mh.on_path(ev.src_path)
 96                mh.on_path(ev.dest_path)
 97
 98        # we support older versions of watchdog, so can't schedule files yet
 99        # (plus, we support non-existent files, not sure if watchdog's file scheduling does)
100        m.files_per_dir = defaultdict(set)
101        # high timeout (like the default) seems 'blocky' on some watchdog versions...
102        m.observer = watchdog.observers.Observer(timeout=0.1)
103        m.handler = Handler()
104        m.event = threading.Event()
105        m.filter = (watchdog.events.FileModifiedEvent, watchdog.events.FileCreatedEvent,
106                    watchdog.events.FileDeletedEvent, watchdog.events.FileMovedEvent)
107
108    def add(m, path):
109        if not isinstance(path, CustomPath):
110            dir, name = path_split_name(path_absolute(path))
111            if path_exists(dir):
112                m.files_per_dir[dir].add(name)
113
114    def wait(m):
115        for dir in m.files_per_dir:
116            m.observer.schedule(m.handler, dir, event_filter=m.filter)
117        
118        m.observer.start()
119        try:
120            # use timeout to allow ctrl+c on windows on earlier python versions
121            while not m.event.wait(timeout=0.5): pass
122        except KeyboardInterrupt:
123            return False
124        finally:
125            m.observer.stop()
126            m.observer.join()
127            
128        time.sleep(0.05) # debounce, for platforms that ignore timeout param
129        return True
130
131class ErrCodes:
132    ok = 0; err = 1; warn = 2; fail = 3; include = 4
133
134def create_main(lang):
135    """Return a 'main' function for the given language. The main function optionally receives raw arguments and returns an exit code"""
136
137    is_pico8 = lang == Language.pico8
138    is_picotron = lang == Language.picotron
139
140    if is_pico8:
141        CartFormatCls = CartFormat
142        CartSourceCls = CartSource
143        ContextCls = PicoContext
144
145        read_cart_func = read_cart
146        read_cart_export_func = read_cart_export
147        read_pico_dat_func = read_pod_file
148        merge_cart_func = merge_cart
149        filter_cart_func = lang_not_supported
150        preproc_cart_func = lang_not_supported
151        write_cart_func = write_cart
152        write_code_size_func = write_code_size
153        write_compressed_size_func = write_compressed_size
154        write_cart_version_func = write_cart_version
155        get_latest_version_func = get_latest_pico8_version
156        parse_version_func = parse_pico8_version
157
158        shrinko_name = "shrinko8"
159        pico_name = "pico8"
160        label_section = "label"
161
162    elif is_picotron:
163        CartFormatCls = Cart64Format
164        CartSourceCls = Cart64Source
165        ContextCls = PicotronContext
166        
167        read_cart_func = read_cart64
168        read_cart_export_func = read_cart64_export
169        read_pico_dat_func = read_sysrom_file
170        merge_cart_func = merge_cart64
171        filter_cart_func = filter_cart64
172        preproc_cart_func = preproc_cart64
173        write_cart_func = write_cart64
174        write_code_size_func = lang_do_nothing
175        write_compressed_size_func = write_cart64_compressed_size
176        write_cart_version_func = write_cart64_version
177        get_latest_version_func = get_latest_picotron_runtime
178        parse_version_func = int
179        
180        shrinko_name = "shrinkotron"
181        pico_name = "picotron"
182        label_section = "label.png"
183        default_keep_meta_keys = ("runtime",)
184    
185    else:
186        fail("unknown language")
187
188    def create_parser():
189        if is_pico8:
190            sections_str = "sections"
191            sections_desc = "comma separated list of sections out of {%s}" % ",".join(k_pico_sections)
192            version_desc = "either a string like 'v0.2.6b' or a raw number from the p8 'version' field like '42'"
193        else:
194            sections_str = "files"
195            sections_desc = "comma separated list of files (can use wildcards and ! for exclude)"
196            version_desc = "Same as 'runtime' field of the root .info.pod"
197        sections_meta = sections_str.upper()
198
199        parser = argparse.ArgumentParser()
200        parser.add_argument("input", help="input file, can be in any format. ('-' for stdin)", nargs='?')
201        parser.add_argument("additional_inputs", help="extra input files. (for use when creating exports)", nargs='*')
202        parser.add_argument("output", help="output file. ('-' for stdout)", nargs='?')
203        parser.add_argument("-f", "--format", type=EnumFromStr(CartFormatCls),
204                            help="output cart format {%s}" % EnumList(CartFormatCls, lambda e: e.is_output and e.is_exposed))
205        parser.add_argument("-F", "--input-format", type=EnumFromStr(CartFormatCls),
206                            help="input cart format {%s}" % EnumList(CartFormatCls, lambda e: e.is_input and e.is_exposed))
207        parser.add_argument("-i", "--in-place", action="store_true", help="modify the input file in-place")
208        parser.add_argument("-w", "--watch", action="store_true", help="watch for changes in the source file(s) (and any includes) and repeat the operation on change")
209        if is_pico8:
210            parser.add_argument("-u", "--unicode-caps", action="store_true", help="write capitals as italicized unicode characters (better for copy/paste)")
211        else:
212            parser.set_defaults(unicode_caps=False)
213
214        pgroup = parser.add_argument_group("minify options")
215        pgroup.add_argument("-m", "--minify", action="store_true", help="enable minification of the cart")
216        pgroup.add_argument("-M", "--minify-safe-only", action="store_true", help="only do minification that's always safe to do")
217        pgroup.add_argument("--minify-consts-only", action="store_true", help="only do constant folding - no other minification")
218        pgroup.add_argument("--minify-transform-only", action="store_true", help="only do transformations - no other minification")
219        if is_pico8:
220            pgroup.add_argument("-ot", "--focus-tokens", action="store_true", help="when minifying, focus on reducing the amount of tokens")
221            pgroup.add_argument("-oc", "--focus-chars", action="store_true", help="when minifying, focus on reducing the amount of characters")
222            pgroup.add_argument("-ob", "--focus-compressed", action="store_true", help="when minifying, focus on reducing the code's compressed size")
223        else:
224            pgroup.set_defaults(focus_tokens=False, focus_chars=False, focus_compressed=True)
225        pgroup.add_argument("--no-minify-rename", action="store_true", help="disable variable renaming in minification")
226        pgroup.add_argument("--no-minify-consts", action="store_true", help="disable constant folding in minification")
227        pgroup.add_argument("--no-minify-spaces", action="store_true", help="disable space removal in minification")
228        pgroup.add_argument("--no-minify-lines", action="store_true", help="disable line removal in minification")
229        pgroup.add_argument("--no-minify-comments", action="store_true", help="disable comment removal in minification (requires --no-minify-spaces)")
230        pgroup.add_argument("--no-minify-tokens", action="store_true", help="disable token removal/changes in minification")
231        pgroup.add_argument("--no-minify-reorder", action="store_true", help="disable statement reordering in minification")
232        pgroup.add_argument("--no-minify-transform", action="store_true", help="disable transformations (--$switch-compiler & --$dynamic-include) in minification")
233        pgroup.add_argument("-p", "--preserve", type=SplitBySeps, action="extend", help='preserve specific identifiers in minification, e.g. "global1, global2, *.member2, table3.*"')
234        pgroup.add_argument("--no-preserve", type=SplitBySeps, action="extend", help='do not preserve specific built-in identifiers in minification, e.g. "circfill, rectfill"')
235        pgroup.add_argument("--rename-members-as-globals", action="store_true", help='rename globals and members the same way (same as --preserve "*=*.*")')
236        pgroup.add_argument("--rename-safe-only", action="store_true", help="only do renaming that's always safe to do (subset of --minify-safe-only)")
237        pgroup.add_argument("--reorder-safe-only", action="store_true", help="only do statement reordering that's always safe to do (subset of --minify-safe-only)")
238        pgroup.add_argument("--builtins-safe-only", action="store_true", help="only assume a function is builtin when it's always safe to do (subset of --minify-safe-only)")
239        pgroup.add_argument("--rename-map", help="log renaming of identifiers (from minify step) to this file")
240        pgroup.add_argument("--const", nargs=2, action="append", metavar=("NAME", "VALUE"), help="define a constant that will be replaced with the VALUE across the entire file")
241        pgroup.add_argument("--str-const", nargs=2, action="append", metavar=("NAME", "VALUE"), help="same as --const, but the value is interpreted as a string")
242        pgroup.add_argument("--default-compiler", help="same as a '--$switch-compiler: VALUE' hint at the beginning of the file")
243
244        pgroup = parser.add_argument_group("lint options")
245        pgroup.add_argument("-l", "--lint", action="store_true", help="enable checking the cart for common issues")
246        pgroup.add_argument("--no-lint-unused", action="store_true", help="don't print lint warnings on unused variables")
247        pgroup.add_argument("--no-lint-unused-global", action="store_true", help="don't print lint warnings on unused global variables")
248        pgroup.add_argument("--no-lint-duplicate", action="store_true", help="don't print lint warnings on duplicate variables")
249        pgroup.add_argument("--no-lint-duplicate-global", action="store_true", help="don't print lint warnings on duplicate variables between a local and a global")
250        pgroup.add_argument("--no-lint-undefined", action="store_true", help="don't print lint warnings on undefined variables")
251        pgroup.add_argument("--no-lint-fail", action="store_true", help="create output cart even if there were lint warnings")
252        pgroup.add_argument("--lint-global", type=SplitBySeps, action="extend", help="don't print lint warnings for these globals (same as '--$lint:' comment)")
253        pgroup.add_argument("--error-format", type=EnumFromStr(ErrorFormat), help="how to format lint warnings & compilation errors {%s}" % EnumList(ErrorFormat))
254
255        pgroup = parser.add_argument_group("count options")
256        pgroup.add_argument("-c", "--count", action="store_true", help="enable printing token count, character count & compressed size")
257        pgroup.add_argument("--input-count", action="store_true", help="enable printing input token count, character count & compressed size")
258        pgroup.add_argument("--parsable-count", action="store_true", help="output counts in a stable, parsable format")
259        pgroup.add_argument("--no-count-compress", action="store_true", help="do not compress the cart just to print the compressed size")
260        pgroup.add_argument("--no-count-tokenize", action="store_true",
261                            help="do not tokenize the cart just to print the token count" if is_pico8 else argparse.SUPPRESS)
262
263        pgroup = parser.add_argument_group("unminify options")
264        pgroup.add_argument("-U", "--unminify", action="store_true", help="enable unminification of the cart")
265        pgroup.add_argument("--unminify-indent", type=Indent, help="indentation when unminifying - either 'tabs' or a number of spaces (default: 2)", default="2")
266
267        pgroup = parser.add_argument_group("image options")
268        pgroup.add_argument("--label", help=f"image to use as the label (default: taken from __label__ like {lang} does)")
269        pgroup.add_argument("--title", action="append", 
270                            help=f"text to use as the title (default: taken from first two comments like {lang} does). Use twice for a second line")
271        pgroup.add_argument("--template-image", help=f"template image to use for png carts, instead of the default {lang} template")
272        pgroup.add_argument("--template-only", action="store_true", help="when creating the png cart, ignore the label & title, using just the template")
273        pgroup.add_argument("--palette", type=IntSplitBySeps, help="palette to use when importing/exporting spritesheets - a comma-separated list of indices")
274
275        pgroup = parser.add_argument_group("version options")
276        pgroup.add_argument("--version", action="store_true", help=f"print version of cart. (if no cart is provided - print {shrinko_name} version and exit)")
277        pgroup.add_argument("--output-version", type=parse_version_func, help=f"the version to convert the cart to. ({version_desc})")
278        pgroup.add_argument("--update-version", action="store_true", help=f"convert the cart to the latest supported version")
279
280        pgroup = parser.add_argument_group("misc. options")
281        pgroup.add_argument("-s", "--script", action="append", help=f"manipulate the cart via a custom script (python or {pico_name}) - see README for api details")
282        pgroup.add_argument("--script-args", nargs=argparse.REMAINDER, help="send arguments directly to --script", default=())
283        pgroup.add_argument("--extra-output", nargs='+', action="append", metavar=("OUTPUT [FORMAT]", ""),
284                            help="additional output file to produce (and optionally, the format to use)")
285
286        if is_picotron:
287            pgroup = parser.add_argument_group("picotron filesystem options")
288            pgroup.add_argument("--list", action="store_true", help="list all files inside the cart")
289            pgroup.add_argument("--filter", type=SplitBySeps, action="extend", help=f"specify a {sections_desc} to keep in the output")
290            pgroup.add_argument("--insert", nargs='+', action="append", metavar=(f"INPUT [FSPATH [FILTER]]", ""),
291                                help=f"insert the specified file or directory INPUT into FSPATH. (FILTER can be a {sections_desc} to insert - relative to cart root)")
292            pgroup.add_argument("--extract", nargs='+', action="append", metavar=(f"FSPATH [OUTPUT]", ""),
293                                help=f"extract the specified file or directory from FSPATH to OUTPUT ")
294            pgroup.set_defaults(list_includes=None)
295        else:
296            pgroup.add_argument("--list-includes", action="store_true", help="list all includes inside the cart")
297            pgroup.set_defaults(filter=None, insert=None, extract=None)
298        
299        pgroup.add_argument("--merge", nargs='+', action="append", metavar=(f"INPUT {sections_meta} [FORMAT]", ""),
300                            help=f"merge {sections_str} from the specified INPUT file, where {sections_meta} is a {sections_desc}")
301
302        if is_pico8:
303            pgroup = parser.add_argument_group("cart export options (for use with the formats: %s)" % EnumList(CartFormatCls, lambda e: e.is_export and e.is_exposed))
304            pgroup.add_argument("--list", action="store_true", help="list all cart names inside the export")
305            pgroup.add_argument("--dump", help="dump all carts inside the export to the specified folder. -f can be used to specify the output format")
306            pgroup.add_argument("--cart", help="name of cart to extract from the export")
307            pgroup.add_argument("--pico8-dat", dest="pico_dat", help="path to the pico8.dat file in the pico8 directory. needed to create new exports")
308            pgroup.add_argument("--output-cart", help="override name to use for the main cart in the export")
309            pgroup.add_argument("--extra-input", nargs='+', action="append", metavar=("INPUT [FORMAT [NAME]]", ""),
310                                help="additional input file to place in export (and optionally, the format of the file & the name to use for it in the export)")
311        else:
312            pgroup.add_argument("--dump", help="dump the cart/system/etc. inside a sysrom.dat to the specified folder. -f can set the output format of carts (e.g '-f dir')")
313            pgroup.add_argument("--picotron-dat", dest="pico_dat", help="path to the picotron.dat file in the picotron directory. needed to create exports")
314            pgroup.set_defaults(cart=None, output_cart=None, extra_input=())
315
316        if is_picotron:
317            pgroup = parser.add_argument_group("picotron filesystem advanced options")
318            pgroup.add_argument("--code-files", dest="code_sections", type=SplitBySeps, action="extend",
319                                help=f"specify a {sections_desc} that contain lua code to process (default: *.lua)")
320            pgroup.add_argument("--delete-meta", type=SplitBySeps, action="extend",
321                                help=f"specify a {sections_desc} to delete metadata of (default: * if minifying unsafely, else none)")
322            pgroup.add_argument("--keep-meta-keys", type=SplitBySeps, action="extend",
323                                help=f"specify a comma separated list of metadata keys (can use wildcards and ! for exclude) "
324                                f"to always keep (default & recommended: {','.join(default_keep_meta_keys)})")
325            pgroup.add_argument("--delete-label", action="store_true", default=None, help="always delete the label")
326            pgroup.add_argument("--keep-label", action="store_false", dest="delete_label", help="always keep the label")
327            pgroup.add_argument("--keep-pod-compression", action="store_true", help="keep compression of all pod files as-is")
328            pgroup.add_argument("-u", "--uncompress-pods", action="store_true", help="uncompress all pod files to plain text")
329            pgroup.add_argument("--base64-pods", action="store_true", help="base64 all pod files")
330        else:
331            pgroup.set_defaults(code_sections=None, delete_meta=None, keep_meta_keys=None, keep_label=None,
332                                uncompress_pods=None, keep_pod_compression=None, base64_pods=None)
333
334        pgroup = parser.add_argument_group("other interesting options (semi-undocumented)")
335        pgroup.add_argument("--bbs", action="store_true", help="interpret input as a bbs cart id, e.g. '#...' and download it from the bbs")
336        pgroup.add_argument("--url", action="store_true", help="interpret input as a URL, and download it from the internet")
337        if is_pico8:
338            pgroup.add_argument("--dump-misc-too", action="store_true", help="causes --dump to also dump misc. files inside the export")
339            pgroup.set_defaults(avoid_base64=False)
340        else:
341            pgroup.add_argument("--avoid-base64", action="store_true", help=f"avoid using base64 in p64 files whenever possible")
342            pgroup.set_defaults(dump_misc_too=True)
343
344        if is_pico8:
345            pgroup = parser.add_argument_group("export editing options (semi-undocumented)")
346            pgroup.add_argument("--insert-cart", nargs="*", metavar=("NAME", "BEFORE"), help="add the cart to an existing export. (The default name is the input cart's name)")
347            pgroup.add_argument("--replace-cart", nargs="*", metavar=("NAME"), help="replace the cart with the given name (Default: main cart) in the export")
348            pgroup.add_argument("--delete-cart", nargs=1, help="delete the cart with the given name from the export")
349            pgroup.add_argument("--rename-cart", nargs=2, metavar=("OLD", "NEW"), help="rename the cart with the given name in the export")
350        else:
351            pgroup.set_defaults(insert_cart=None, replace_cart=None, delete_cart=None, rename_cart=None)
352
353        pgroup = parser.add_argument_group("compression options (semi-undocumented)")
354        if is_pico8:
355            pgroup.add_argument("--keep-compression", action="store_true", help="keep existing compression, instead of re-compressing")
356            pgroup.add_argument("--force-compression", action="store_true", help="force code compression even if code fits")
357            pgroup.add_argument("--old-compression", action="store_true", help="compress with the old pre-v0.2.0 compression scheme")
358        else:
359            pgroup.set_defaults(keep_compression=False, force_compression=False, old_compression=False)
360        pgroup.add_argument("--optimize-png-compression", action="store_true", help="when generating a png, also optimize the size of the png itself (no effect on cart size)")
361        pgroup.add_argument("--fast-compression", action="store_true", help="force fast but very poor compression")
362        pgroup.add_argument("--trace-compression", help="trace the compressed symbols and their cost into this file")
363        pgroup.add_argument("--trace-input-compression", help="trace the input's compressed symbols and their cost into this file")
364
365        pgroup = parser.add_argument_group("other uninteresting options (semi-undocumented)")
366        pgroup.add_argument("--ignore-hints", action="store_true", help=f"ignore {shrinko_name} hint comments")
367        pgroup.add_argument("--builtin", type=SplitBySeps, action="extend", help=f"treat identifier(s) as a {pico_name} builtin (for minify, lint, etc.)")
368        pgroup.add_argument("--not-builtin", type=SplitBySeps, action="extend", help=f"do not treat identifier(s) as a {pico_name} builtin (for minify, lint, etc.)")
369        pgroup.add_argument("--export-name", help="name to use for the export (by default, taken from output name)")
370        pgroup.add_argument("--clean-output-dir", action="store_true",
371                            help="when the output is a directory, delete any existing files and subdirectories from the directory first (use with caution!)")
372        if is_pico8:
373            pgroup.add_argument("--global-builtins-only", action="store_true", help="assume all builtins are global, corresponds to pico8's -global_api option")
374            pgroup.add_argument("--local-builtin", type=SplitBySeps, action="extend", help="treat identifier(s) as a local builtin (probably no use outside of testing)")
375            pgroup.add_argument("--output-sections", type=SplitBySeps, action="extend", help=f"specifies a {sections_desc} to write to the p8")
376        else:
377            pgroup.set_defaults(global_builtins_only=False, local_builtin=None, output_sections=None)
378        
379        return parser
380
381    def default_format(input, for_output=False):
382        ext = path_extension(input)[1:].lower()
383        if ext in CartFormatCls._values and CartFormatCls(ext).is_ext:
384            return CartFormatCls(ext)
385        elif CartFormatCls.default_dir and path_is_native(input) and (path_is_dir(input) or not path_basename(input)):
386            return CartFormatCls.default_dir
387        elif for_output:
388            return CartFormatCls.default_src
389        else:
390            return None
391
392    def main_inner(args):
393        if args.version and not args.input:
394            print("v" + get_version())
395            return
396        
397        if args.watch:
398            args.watch = OneShotFileChangeWatcher()
399
400        if args.additional_inputs and not args.output:
401            args.output = args.additional_inputs[-1] # argparse doesn't support nargs=* followed by nargs=?
402            del args.additional_inputs[-1]
403        
404        if args.in_place:
405            if args.output:
406                throw("Cannot specify output cart with --in-place")
407            args.output = args.input
408            if args.input_format and not args.format:
409                args.format = args.input_format
410            
411        if not args.input:
412            throw("No input file specified")
413        
414        if args.delete_cart or args.rename_cart:
415            if args.output:
416                throw("Only need to specify a single cart when using --delete-cart or --rename-cart")
417            args.input, args.output = None, args.input
418
419        if args.input == "-":
420            args.input = StdPath("-")
421        if args.output == "-":
422            args.output = StdPath("-")
423
424        if args.url:
425            args.input = URLPath(args.input)
426        elif args.bbs:
427            args.input = URLPath(get_bbs_cart_url(args.input, lang))
428            args.input_format = CartFormatCls.png
429
430        if (not args.lint and not args.count and not args.output and not args.input_count and not args.version and
431            not args.list and not args.dump and not args.script and not args.extract and not args.list_includes):
432            throw("No operation (--lint/--count/--script/etc) or output file specified")
433        if args.format and not args.output and not args.dump:
434            throw("Output should be specified under --format")
435        if args.minify and not args.output and not args.count:
436            throw("Output (or --count) should be specified under --minify")
437        if args.minify and args.keep_compression:
438            throw("Can't modify code and keep compression")
439        if (args.list or args.dump) and (args.output or args.lint or args.count):
440            throw("--list & --dump can't be combined with most other options")
441        if (e(args.delete_cart) + e(args.rename_cart) + e(args.insert_cart) + e(args.replace_cart)) > 1:
442            throw("Can only specify one of --insert/replace/delete/rename-cart")
443            
444        if not args.input_format and args.input:
445            args.input_format = default_format(args.input)
446            if args.in_place and not args.format:
447                args.format = args.input_format
448
449        if not args.format and args.output:
450            args.format = default_format(args.output, for_output=True)
451
452        if args.lint:
453            args.lint = {
454                "unused": not args.no_lint_unused,
455                "unused-global": not args.no_lint_unused_global,
456                "duplicate": not args.no_lint_duplicate,
457                "duplicate-global": not args.no_lint_duplicate_global,
458                "undefined": not args.no_lint_undefined,
459                "globals": args.lint_global or (),
460            }
461        
462        args.focus = []
463        if args.focus_chars:
464            args.focus.append("chars")
465        if args.focus_compressed:
466            args.focus.append("compressed")
467        if args.focus_tokens:
468            args.focus.append("tokens")
469
470        minify_limited = args.minify_consts_only or args.minify_transform_only
471        if args.minify or args.minify_safe_only or minify_limited:
472            args.minify = {
473                "safe-reorder": args.minify_safe_only or args.reorder_safe_only,
474                "safe-builtins": args.minify_safe_only or args.builtins_safe_only,
475                "lines": not minify_limited and not args.no_minify_lines,
476                "wspace": not minify_limited and not args.no_minify_spaces,
477                "comments": not minify_limited and not args.no_minify_comments,
478                "tokens": not minify_limited and not args.no_minify_tokens,
479                "reorder": not minify_limited and not args.no_minify_reorder,
480                "consts": (not minify_limited or args.minify_consts_only) and not args.no_minify_consts,
481                "transform": (not minify_limited or args.minify_transform_only) and not args.no_minify_transform,
482                "focus": args.focus,
483            }
484
485        args.rename = bool(args.minify) and not args.no_minify_rename and not minify_limited
486        if args.rename:
487            if args.no_preserve:
488                args.preserve = (args.preserve or []) + [f"!{item}" for item in args.no_preserve]
489            if args.rename_members_as_globals:
490                args.preserve = (args.preserve or []) + ["*=*.*"]
491            args.rename = {
492                "safe-only": args.minify_safe_only or args.rename_safe_only,
493                "focus": args.focus,
494                "rules": args.preserve or (),
495            }
496
497        if args.unminify:
498            args.unminify = {
499                "indent": args.unminify_indent
500            }
501        
502        if args.const or args.str_const:
503            if args.const:
504                args.const = {name: parse_constant(val, lang) or throw(f"cannot parse const <{val}>. If it's meant to be a string, try using --str-const instead") 
505                            for name, val in args.const}
506            if args.str_const:
507                args.const = args.const or {}
508                args.const.update({name: parse_constant(val, lang, as_str=True) for name, val in args.str_const})
509
510        if is_picotron and not args.delete_meta and args.minify and not args.minify_safe_only:
511            args.delete_meta = ["*"]
512        if is_picotron and not args.keep_meta_keys:
513            args.keep_meta_keys = default_keep_meta_keys
514
515        args.preproc_cb, args.postproc_cb, args.preproc_syntax_cb = None, None, None
516        args.include_cb = lambda name, **kwargs: find_in_builtin_script(name, kwargs, "include_main")
517        args.sublang_cb = lambda name, **kwargs: find_in_builtin_script(name, kwargs, "sublanguage_main")
518        args.compiler_cb = lambda name, **kwargs: find_in_builtin_script(name, kwargs, "compiler_main")
519        if args.script:
520            for script in args.script:
521                if args.watch:
522                    args.watch.add(script) # doesn't extend to imports, though
523
524                script_ext = path_extension(script).lower()
525                if script_ext == ".py":
526                    script_obj = exec_script_by_path(script)
527                elif script_ext in (".lua", ".p8"):
528                    from run_pico import exec_pico_script_by_path, lua_type
529                    script_obj = exec_pico_script_by_path(script)
530                    if lua_type(script_obj) != "table":
531                        eprint(f"WARNING: script '{script}' didn't return a table")
532                        continue
533                else:
534                    throw(f"unrecognized script extension {script_ext} (can be .py/.lua/.p8)")
535
536                preproc_main, postproc_main, preproc_syntax_main, include_main, sublang_main, compiler_main = tuple(
537                    getattr(script_obj, name, None) for name in 
538                          ("preprocess_main", "postprocess_main", "preprocess_syntax_main", "include_main", "sublanguage_main", "compiler_main"))
539                args.preproc_cb = func_union(args.preproc_cb, preproc_main)
540                args.postproc_cb = func_union(postproc_main, args.postproc_cb) # (reverse order)
541                args.preproc_syntax_cb = func_union(args.preproc_syntax_cb, preproc_syntax_main)
542                args.include_cb = func_union(include_main, args.include_cb, return_early=e) # (reverse order)
543                args.sublang_cb = func_union(sublang_main, args.sublang_cb, return_early=e) # (reverse order)
544                args.compiler_cb = func_union(compiler_main, args.compiler_cb, return_early=e) # (reverse order)
545
546        base_count_handler = ParsableCountHandler if args.parsable_count else True
547        if args.input_count:
548            args.input_count = base_count_handler
549        if args.count:
550            args.count = base_count_handler
551
552        if args.trace_input_compression:
553            args.trace_input_compression = CompressionTracer(args.trace_input_compression, lang)
554        if args.trace_compression:
555            args.trace_compression = CompressionTracer(args.trace_compression, lang)
556
557        if args.input:
558            cart, extra_carts = handle_input(args)
559            if cart is None: # e.g. list/dump case
560                return ErrCodes.ok
561            
562            passed, ok = handle_processing(args, cart, extra_carts)
563            if not passed:
564                return ErrCodes.warn if ok else ErrCodes.err
565            
566        else: # output-only operations
567            cart, extra_carts = None, ()
568
569        handle_output(args, cart, extra_carts)
570
571    class InputDef(Tuple):
572        input = format = name = sections = fspath = None
573
574    def on_include(args, path):
575        if args.watch:
576            args.watch.add(path)
577        if args.list_includes:
578            print(path_relative(path))
579
580    def handle_input(args):
581        allow_extra_input = is_pico8 and args.format and args.format.is_export
582
583        common_input_args = dict(keep_compression=args.keep_compression, palette=args.palette,
584                                 debug_handler=args.trace_input_compression, size_handler=args.input_count,
585                                 include_notifier=lambda path: on_include(args, path))
586
587        # read the main cart
588        extra_carts = []
589        try:
590            if args.watch:
591                args.watch.add(args.input)
592
593            if (is_pico8 and args.list) or args.dump:
594                export = read_cart_export_func(args.input, args.input_format)
595                if args.list:
596                    for entry in export.list_carts():
597                        print(entry)
598                else:
599                    dir_create(args.dump, delete_existing=args.clean_output_dir)
600                    export.dump_contents(args.dump, default(args.format, CartFormatCls.default_src), misc=args.dump_misc_too)
601                return None, None
602
603            main_cart = read_cart_func(args.input, args.input_format, cart_name=args.cart,
604                                       extra_carts=extra_carts if allow_extra_input and not args.cart else None,
605                                       **common_input_args)
606        except OSError as err:
607            throw(f"cannot read cart: {err}")
608        
609        # collect additional carts to read
610        if args.additional_inputs:
611            if not args.extra_input:
612                args.extra_input = []
613            for input in args.additional_inputs:
614                args.extra_input.append((input,))
615
616        extra_inputs = []
617        if args.extra_input:
618            if not allow_extra_input:
619                throw("--extra-input can only be used when creating exports")
620            
621            for extra in args.extra_input:
622                if len(extra) == 1:
623                    extra_inputs.append(InputDef(extra[0], default_format(extra[0], for_output=True)))
624                elif 3 >= len(extra) >= 2:
625                    extra_inputs.append(InputDef(extra[0], CartFormatCls(extra[1]), name=list_get(extra, 2)))
626                else:
627                    throw("too many arguments to --extra-output")
628        
629        if args.insert:
630            for insert in args.insert:
631                if len(insert) == 1:
632                    extra_inputs.append(InputDef(insert[0], CartFormatCls.fs, fspath=path_basename(insert[0])))
633                elif len(insert) == 2:
634                    extra_inputs.append(InputDef(insert[0], CartFormatCls.fs, fspath=insert[1]))
635                elif len(insert) == 3:
636                    extra_inputs.append(InputDef(insert[0], CartFormatCls.fs, fspath=insert[1], sections=SplitBySeps(insert[2])))
637                else:
638                    throw("too many arguments to --insert (must be 1 through 3)")
639
640        if args.merge:
641            for merge in args.merge:
642                if len(merge) == 2:
643                    extra_inputs.append(InputDef(merge[0], default_format(merge[0]), sections=SplitBySeps(merge[1])))
644                elif len(merge) == 3:
645                    extra_inputs.append(InputDef(merge[0], CartFormatCls(merge[2]), sections=SplitBySeps(merge[1])))
646                else:
647                    throw("too many or few arguments to --merge (must be 2 or 3)")
648        
649        if args.label:
650            extra_inputs.append(InputDef(args.label, CartFormatCls.label, sections=(label_section,)))
651        if args.title:
652            main_cart.set_raw_title(args.title)
653
654        # read additional carts
655        for input, input_format, input_name, merge_sections, fspath in extra_inputs:
656            if args.watch:
657                args.watch.add(input)
658                               
659            cart = read_cart_func(input, input_format, fspath=fspath, sections=merge_sections, **common_input_args)
660            
661            if input_name:
662                cart.name = input_name
663            
664            if e(merge_sections) or e(fspath):
665                merge_cart_func(main_cart, cart, merge_sections)
666            else:
667                extra_carts.append(cart)
668        
669        if is_picotron and args.list:
670            for path in main_cart.files:
671                print(path)
672            return None, None
673
674        return main_cart, extra_carts
675
676    def handle_processing(args, main_cart, extra_carts):
677        had_warns = False
678
679        for cart in itertools.chain((main_cart,), extra_carts):
680            if args.update_version:
681                cart.set_version(get_latest_version_func())
682            elif e(args.output_version):
683                cart.set_version(args.output_version)
684        
685            if args.filter:
686                filter_cart_func(cart, args.filter)
687
688            if is_picotron:
689                preproc_cart_func(cart, delete_meta=args.delete_meta, keep_meta_keys=args.keep_meta_keys,
690                                  delete_label=default(args.delete_label, args.format == CartFormatCls.png),
691                                  keep_pod_compression=args.keep_pod_compression,
692                                  uncompress_pods=args.uncompress_pods, base64_pods=args.base64_pods,
693                                  # binary formats are already compressed, so pod compression just hurts
694                                  need_pod_compression=args.format and args.format.is_src)
695
696            src = CartSourceCls(cart, args.code_sections)
697            
698            if args.input_count:
699                write_code_size_func(cart, handler=args.input_count, input=True)
700                
701            with ContextCls(extra_builtins=args.builtin, not_builtins=args.not_builtin, 
702                            use_local_builtins=not args.global_builtins_only,
703                            extra_local_builtins=args.local_builtin,
704                            srcmap=args.rename_map, version=cart.version_id, include_getter=args.include_cb,
705                            sublang_getter=args.sublang_cb, compiler_getter=args.compiler_cb,
706                            default_compiler=args.default_compiler,
707                            hint_comments=not args.ignore_hints, consts=args.const,
708                            ignore_transforms=args.no_minify_transform) as ctxt:
709                if args.preproc_cb:
710                    args.preproc_cb(cart=cart, src=src, ctxt=ctxt, args=args)
711
712                def preproc_syntax_call(root, on_error):
713                    args.preproc_syntax_cb(cart=cart, src=src, root=root, on_error=on_error, ctxt=ctxt, args=args)
714
715                ok, errors = process_code(ctxt, src,
716                                        input_count=is_pico8 and args.input_count,
717                                        count=is_pico8 and args.count,
718                                        lint=args.lint, minify=args.minify, rename=args.rename,
719                                        unminify=args.unminify, stop_on_lint=not args.no_lint_fail,
720                                        count_is_optional=args.no_count_tokenize,
721                                        preproc=preproc_syntax_call if args.preproc_syntax_cb else None)
722                if errors:
723                    had_warns = True
724
725                    if not ok:
726                        print("Compilation errors:")
727                    elif args.lint:
728                        print("Lint warnings:")
729                    else:
730                        print("Hint usage warnings:")
731                    
732                    for error in sorted(errors):
733                        print(error.format(args.error_format))
734                    
735                    if not ok or (args.lint and not args.no_lint_fail):
736                        return False, ok
737
738                if args.rename_map:
739                    file_write_maybe_text(args.rename_map, "\n".join(ctxt.srcmap))
740                    
741                if args.postproc_cb:
742                    args.postproc_cb(cart=cart, args=args, ctxt=ctxt)
743                
744                if args.count:
745                    write_code_size_func(cart, handler=args.count)
746                    if not (args.output and not args.format.is_src) and not args.no_count_compress: # else, will be done in write_cart
747                        write_compressed_size_func(cart, handler=args.count, fast_compress=args.fast_compression, debug_handler=args.trace_compression)
748                
749                if args.version:
750                    write_cart_version_func(cart)
751        
752        return True, not had_warns
753
754    class OutputDef(Tuple):
755        output = format = fspath = None
756
757    def handle_output(args, cart, extra_carts):
758        if e(args.insert_cart):
759            output_cart_op = ListOp.insert
760            output_cart_name, output_cart_target = list_unpack(args.insert_cart, 2)
761        elif e(args.replace_cart):
762            output_cart_op = ListOp.replace
763            output_cart_name, output_cart_target = list_unpack(args.replace_cart, 2)
764        elif e(args.delete_cart):
765            output_cart_op = ListOp.delete
766            output_cart_name, output_cart_target = list_unpack(args.delete_cart, 2)
767        elif e(args.rename_cart):
768            output_cart_op = ListOp.rename
769            output_cart_name, output_cart_target = list_unpack(args.rename_cart, 2)
770        else:
771            output_cart_op = output_cart_target = None
772            output_cart_name = args.output_cart
773
774        all_outputs = []
775        if args.output:
776            all_outputs.append(OutputDef(args.output, args.format))
777        
778        if args.extra_output:
779            for extra in args.extra_output:
780                if len(extra) == 1:
781                    all_outputs.append(OutputDef(extra[0], default_format(extra[0], for_output=True)))
782                elif len(extra) == 2:
783                    all_outputs.append(OutputDef(extra[0], CartFormatCls(extra[1])))
784                else:
785                    throw("too many arguments to --extra-output (must be 1 or 2)")
786        
787        if args.extract:
788            for extract in args.extract:
789                if len(extract) == 1:
790                    all_outputs.append(OutputDef(path_basename(extract[0]), CartFormatCls.fs, extract[0]))
791                elif len(extract) == 2:
792                    all_outputs.append(OutputDef(extract[1], CartFormatCls.fs, extract[0]))
793                else:
794                    throw("too many arguments to --extract (must be 1 or 2)")
795
796        for output, format, fspath in all_outputs:
797            target_export, pico_dat = None, None
798            if format.is_export:
799                if e(output_cart_op):
800                    try:
801                        target_export = read_cart_export_func(output, format)
802                    except OSError as err:
803                        throw(f"cannot read export for editing: {err}")
804                else:
805                    if not args.pico_dat:
806                        throw(f"Creating a new export requires passing --{pico_name}-dat <path to {pico_name}.dat>")
807                    try:
808                        pico_dat = read_pico_dat_func(args.pico_dat)
809                    except OSError as err:
810                        throw(f"cannot read {pico_name} dat: {err}")
811
812            try:
813                write_cart_func(output, cart, format, extra_carts=extra_carts, fspath=fspath,
814                                delete_existing=args.clean_output_dir,
815                                size_handler=args.count, debug_handler=args.trace_compression,
816                                unicode_caps=args.unicode_caps, old_compress=args.old_compression,
817                                force_compress=args.count or args.force_compression,
818                                fast_compress=args.fast_compression, keep_compression=args.keep_compression,
819                                template_image=args.template_image, template_only=args.template_only,
820                                optimize_image=args.optimize_png_compression, palette=args.palette,
821                                sections=args.output_sections, avoid_base64=args.avoid_base64,
822                                cart_op=output_cart_op, cart_name=output_cart_name, target_name=output_cart_target,
823                                target_export=target_export, export_name=args.export_name, pico_dat=pico_dat)
824            except OSError as err:
825                throw(f"cannot write cart: {err}")
826
827    parser = create_parser()
828
829    def main_once(args):
830        try:
831            result = main_inner(args)
832            return result
833
834        except CheckError as err:
835            sys.stdout.flush()
836            eprint("ERROR: " + str(err))
837            if isinstance(err, IncludeNotFoundError):
838                errcode = ErrCodes.include
839            else:
840                errcode = ErrCodes.fail
841            return errcode
842
843        except Exception:
844            if not args.watch:
845                raise # ideally we won't have any raw exceptions
846            traceback.print_exc()
847            return ErrCodes.fail
848            
849    def main(raw_args=None):
850        raw_args = default(raw_args, sys.argv[1:])
851
852        if not raw_args: # help is better than usage
853            parser.print_help(sys.stderr)
854            return ErrCodes.err
855        
856        first = True
857        while True:
858            args = parser.parse_intermixed_args(raw_args)
859            errcode = main_once(args)
860
861            if not args.watch or args.watch == True:
862                return errcode
863
864            eprint(f"{'Starting' if first else 'Resuming'} watch... (Ctrl+C to terminate)\n")
865            first = False
866            
867            if not args.watch.wait():
868                return errcode
869
870    return main
871
872if __name__ == "__main__":
873    eprint("The correct script to run is shrinko8.py (or shrinkotron.py)")
k_version_raw = '1.2.7.6'
def get_version():
22def get_version():
23    """convert our raw version to pico-style version"""
24    version, lastdigit = k_version_raw.rsplit(".", 1)
25    lastdigit = int(lastdigit)
26    lastchar = string.ascii_lowercase[lastdigit] if lastdigit else ""
27    return version + lastchar

convert our raw version to pico-style version

def SplitBySeps(val):
29def SplitBySeps(val):
30    return k_hint_split_re.split(val)
def IntSplitBySeps(val):
32def IntSplitBySeps(val):
33    return [int(val) for val in SplitBySeps(val)]
def Indent(val):
35def Indent(val):
36    return "\t" if val == "tabs" else " " * int(val)
def EnumFromStr(enum_type):
38def EnumFromStr(enum_type):
39    def cvt(name):
40        return enum_type(name.replace("-", "_").replace(" ", "_"))
41    cvt.__name__ = enum_type.__name__
42    return cvt
def EnumList(enum_type, pred=None):
44def EnumList(enum_type, pred=None):
45    list = enum_type._values
46    if pred:
47        list = filter(lambda name: pred(enum_type(name)), list)
48    return ", ".join(str.replace("_", "-") for str in list)
def ParsableCountHandler(prefix, name, size, limit):
50def ParsableCountHandler(prefix, name, size, limit):
51    print(f"count:{prefix}:{name}:{size}:{limit}")
def lang_not_supported():
53def lang_not_supported():
54    throw("operation not supported for this language")
def lang_do_nothing(*_, **__):
55def lang_do_nothing(*_, **__):
56    pass
def find_in_builtin_script(name, kwargs, func_name):
58def find_in_builtin_script(name, kwargs, func_name):
59    import importlib
60    module_name = "scripts." + str_before_first(name, ".")
61    try:
62        module = importlib.import_module(module_name)
63    except ModuleNotFoundError:
64        from run_pico import import_pico_script
65        try:
66            module = import_pico_script(module_name)
67        except ModuleNotFoundError:
68            return None
69        except IncludeNotFoundError as e:
70            eprint(f"{e} - could you be missing a 'git submodule update --init'?")
71            return None
72    func = getattr(module, func_name, None)
73    if func:
74        return func(name, **kwargs)
class OneShotFileChangeWatcher:
 76class OneShotFileChangeWatcher:
 77    def __init__(m):
 78        try:
 79            import watchdog.events, watchdog.observers, threading
 80        except ImportError:
 81            throw("You need watchdog to use --watch (do 'python -m pip install watchdog')")
 82
 83        class Handler(watchdog.events.FileSystemEventHandler):
 84            def on_path(mh, path):
 85                dir, name = path_split_name(path)
 86                if dir in m.files_per_dir and name in m.files_per_dir[dir] and not m.event.is_set():
 87                    eprint("%s changed - repeating operation" % name)
 88                    m.event.set()
 89
 90            def on_modified(mh, ev):
 91                mh.on_path(ev.src_path)
 92            
 93            on_deleted = on_created = on_modified
 94
 95            def on_moved(mh, ev):
 96                mh.on_path(ev.src_path)
 97                mh.on_path(ev.dest_path)
 98
 99        # we support older versions of watchdog, so can't schedule files yet
100        # (plus, we support non-existent files, not sure if watchdog's file scheduling does)
101        m.files_per_dir = defaultdict(set)
102        # high timeout (like the default) seems 'blocky' on some watchdog versions...
103        m.observer = watchdog.observers.Observer(timeout=0.1)
104        m.handler = Handler()
105        m.event = threading.Event()
106        m.filter = (watchdog.events.FileModifiedEvent, watchdog.events.FileCreatedEvent,
107                    watchdog.events.FileDeletedEvent, watchdog.events.FileMovedEvent)
108
109    def add(m, path):
110        if not isinstance(path, CustomPath):
111            dir, name = path_split_name(path_absolute(path))
112            if path_exists(dir):
113                m.files_per_dir[dir].add(name)
114
115    def wait(m):
116        for dir in m.files_per_dir:
117            m.observer.schedule(m.handler, dir, event_filter=m.filter)
118        
119        m.observer.start()
120        try:
121            # use timeout to allow ctrl+c on windows on earlier python versions
122            while not m.event.wait(timeout=0.5): pass
123        except KeyboardInterrupt:
124            return False
125        finally:
126            m.observer.stop()
127            m.observer.join()
128            
129        time.sleep(0.05) # debounce, for platforms that ignore timeout param
130        return True
def add(m, path):
109    def add(m, path):
110        if not isinstance(path, CustomPath):
111            dir, name = path_split_name(path_absolute(path))
112            if path_exists(dir):
113                m.files_per_dir[dir].add(name)
def wait(m):
115    def wait(m):
116        for dir in m.files_per_dir:
117            m.observer.schedule(m.handler, dir, event_filter=m.filter)
118        
119        m.observer.start()
120        try:
121            # use timeout to allow ctrl+c on windows on earlier python versions
122            while not m.event.wait(timeout=0.5): pass
123        except KeyboardInterrupt:
124            return False
125        finally:
126            m.observer.stop()
127            m.observer.join()
128            
129        time.sleep(0.05) # debounce, for platforms that ignore timeout param
130        return True
class ErrCodes:
132class ErrCodes:
133    ok = 0; err = 1; warn = 2; fail = 3; include = 4
ok = 0
err = 1
warn = 2
fail = 3
include = 4
def create_main(lang):
135def create_main(lang):
136    """Return a 'main' function for the given language. The main function optionally receives raw arguments and returns an exit code"""
137
138    is_pico8 = lang == Language.pico8
139    is_picotron = lang == Language.picotron
140
141    if is_pico8:
142        CartFormatCls = CartFormat
143        CartSourceCls = CartSource
144        ContextCls = PicoContext
145
146        read_cart_func = read_cart
147        read_cart_export_func = read_cart_export
148        read_pico_dat_func = read_pod_file
149        merge_cart_func = merge_cart
150        filter_cart_func = lang_not_supported
151        preproc_cart_func = lang_not_supported
152        write_cart_func = write_cart
153        write_code_size_func = write_code_size
154        write_compressed_size_func = write_compressed_size
155        write_cart_version_func = write_cart_version
156        get_latest_version_func = get_latest_pico8_version
157        parse_version_func = parse_pico8_version
158
159        shrinko_name = "shrinko8"
160        pico_name = "pico8"
161        label_section = "label"
162
163    elif is_picotron:
164        CartFormatCls = Cart64Format
165        CartSourceCls = Cart64Source
166        ContextCls = PicotronContext
167        
168        read_cart_func = read_cart64
169        read_cart_export_func = read_cart64_export
170        read_pico_dat_func = read_sysrom_file
171        merge_cart_func = merge_cart64
172        filter_cart_func = filter_cart64
173        preproc_cart_func = preproc_cart64
174        write_cart_func = write_cart64
175        write_code_size_func = lang_do_nothing
176        write_compressed_size_func = write_cart64_compressed_size
177        write_cart_version_func = write_cart64_version
178        get_latest_version_func = get_latest_picotron_runtime
179        parse_version_func = int
180        
181        shrinko_name = "shrinkotron"
182        pico_name = "picotron"
183        label_section = "label.png"
184        default_keep_meta_keys = ("runtime",)
185    
186    else:
187        fail("unknown language")
188
189    def create_parser():
190        if is_pico8:
191            sections_str = "sections"
192            sections_desc = "comma separated list of sections out of {%s}" % ",".join(k_pico_sections)
193            version_desc = "either a string like 'v0.2.6b' or a raw number from the p8 'version' field like '42'"
194        else:
195            sections_str = "files"
196            sections_desc = "comma separated list of files (can use wildcards and ! for exclude)"
197            version_desc = "Same as 'runtime' field of the root .info.pod"
198        sections_meta = sections_str.upper()
199
200        parser = argparse.ArgumentParser()
201        parser.add_argument("input", help="input file, can be in any format. ('-' for stdin)", nargs='?')
202        parser.add_argument("additional_inputs", help="extra input files. (for use when creating exports)", nargs='*')
203        parser.add_argument("output", help="output file. ('-' for stdout)", nargs='?')
204        parser.add_argument("-f", "--format", type=EnumFromStr(CartFormatCls),
205                            help="output cart format {%s}" % EnumList(CartFormatCls, lambda e: e.is_output and e.is_exposed))
206        parser.add_argument("-F", "--input-format", type=EnumFromStr(CartFormatCls),
207                            help="input cart format {%s}" % EnumList(CartFormatCls, lambda e: e.is_input and e.is_exposed))
208        parser.add_argument("-i", "--in-place", action="store_true", help="modify the input file in-place")
209        parser.add_argument("-w", "--watch", action="store_true", help="watch for changes in the source file(s) (and any includes) and repeat the operation on change")
210        if is_pico8:
211            parser.add_argument("-u", "--unicode-caps", action="store_true", help="write capitals as italicized unicode characters (better for copy/paste)")
212        else:
213            parser.set_defaults(unicode_caps=False)
214
215        pgroup = parser.add_argument_group("minify options")
216        pgroup.add_argument("-m", "--minify", action="store_true", help="enable minification of the cart")
217        pgroup.add_argument("-M", "--minify-safe-only", action="store_true", help="only do minification that's always safe to do")
218        pgroup.add_argument("--minify-consts-only", action="store_true", help="only do constant folding - no other minification")
219        pgroup.add_argument("--minify-transform-only", action="store_true", help="only do transformations - no other minification")
220        if is_pico8:
221            pgroup.add_argument("-ot", "--focus-tokens", action="store_true", help="when minifying, focus on reducing the amount of tokens")
222            pgroup.add_argument("-oc", "--focus-chars", action="store_true", help="when minifying, focus on reducing the amount of characters")
223            pgroup.add_argument("-ob", "--focus-compressed", action="store_true", help="when minifying, focus on reducing the code's compressed size")
224        else:
225            pgroup.set_defaults(focus_tokens=False, focus_chars=False, focus_compressed=True)
226        pgroup.add_argument("--no-minify-rename", action="store_true", help="disable variable renaming in minification")
227        pgroup.add_argument("--no-minify-consts", action="store_true", help="disable constant folding in minification")
228        pgroup.add_argument("--no-minify-spaces", action="store_true", help="disable space removal in minification")
229        pgroup.add_argument("--no-minify-lines", action="store_true", help="disable line removal in minification")
230        pgroup.add_argument("--no-minify-comments", action="store_true", help="disable comment removal in minification (requires --no-minify-spaces)")
231        pgroup.add_argument("--no-minify-tokens", action="store_true", help="disable token removal/changes in minification")
232        pgroup.add_argument("--no-minify-reorder", action="store_true", help="disable statement reordering in minification")
233        pgroup.add_argument("--no-minify-transform", action="store_true", help="disable transformations (--$switch-compiler & --$dynamic-include) in minification")
234        pgroup.add_argument("-p", "--preserve", type=SplitBySeps, action="extend", help='preserve specific identifiers in minification, e.g. "global1, global2, *.member2, table3.*"')
235        pgroup.add_argument("--no-preserve", type=SplitBySeps, action="extend", help='do not preserve specific built-in identifiers in minification, e.g. "circfill, rectfill"')
236        pgroup.add_argument("--rename-members-as-globals", action="store_true", help='rename globals and members the same way (same as --preserve "*=*.*")')
237        pgroup.add_argument("--rename-safe-only", action="store_true", help="only do renaming that's always safe to do (subset of --minify-safe-only)")
238        pgroup.add_argument("--reorder-safe-only", action="store_true", help="only do statement reordering that's always safe to do (subset of --minify-safe-only)")
239        pgroup.add_argument("--builtins-safe-only", action="store_true", help="only assume a function is builtin when it's always safe to do (subset of --minify-safe-only)")
240        pgroup.add_argument("--rename-map", help="log renaming of identifiers (from minify step) to this file")
241        pgroup.add_argument("--const", nargs=2, action="append", metavar=("NAME", "VALUE"), help="define a constant that will be replaced with the VALUE across the entire file")
242        pgroup.add_argument("--str-const", nargs=2, action="append", metavar=("NAME", "VALUE"), help="same as --const, but the value is interpreted as a string")
243        pgroup.add_argument("--default-compiler", help="same as a '--$switch-compiler: VALUE' hint at the beginning of the file")
244
245        pgroup = parser.add_argument_group("lint options")
246        pgroup.add_argument("-l", "--lint", action="store_true", help="enable checking the cart for common issues")
247        pgroup.add_argument("--no-lint-unused", action="store_true", help="don't print lint warnings on unused variables")
248        pgroup.add_argument("--no-lint-unused-global", action="store_true", help="don't print lint warnings on unused global variables")
249        pgroup.add_argument("--no-lint-duplicate", action="store_true", help="don't print lint warnings on duplicate variables")
250        pgroup.add_argument("--no-lint-duplicate-global", action="store_true", help="don't print lint warnings on duplicate variables between a local and a global")
251        pgroup.add_argument("--no-lint-undefined", action="store_true", help="don't print lint warnings on undefined variables")
252        pgroup.add_argument("--no-lint-fail", action="store_true", help="create output cart even if there were lint warnings")
253        pgroup.add_argument("--lint-global", type=SplitBySeps, action="extend", help="don't print lint warnings for these globals (same as '--$lint:' comment)")
254        pgroup.add_argument("--error-format", type=EnumFromStr(ErrorFormat), help="how to format lint warnings & compilation errors {%s}" % EnumList(ErrorFormat))
255
256        pgroup = parser.add_argument_group("count options")
257        pgroup.add_argument("-c", "--count", action="store_true", help="enable printing token count, character count & compressed size")
258        pgroup.add_argument("--input-count", action="store_true", help="enable printing input token count, character count & compressed size")
259        pgroup.add_argument("--parsable-count", action="store_true", help="output counts in a stable, parsable format")
260        pgroup.add_argument("--no-count-compress", action="store_true", help="do not compress the cart just to print the compressed size")
261        pgroup.add_argument("--no-count-tokenize", action="store_true",
262                            help="do not tokenize the cart just to print the token count" if is_pico8 else argparse.SUPPRESS)
263
264        pgroup = parser.add_argument_group("unminify options")
265        pgroup.add_argument("-U", "--unminify", action="store_true", help="enable unminification of the cart")
266        pgroup.add_argument("--unminify-indent", type=Indent, help="indentation when unminifying - either 'tabs' or a number of spaces (default: 2)", default="2")
267
268        pgroup = parser.add_argument_group("image options")
269        pgroup.add_argument("--label", help=f"image to use as the label (default: taken from __label__ like {lang} does)")
270        pgroup.add_argument("--title", action="append", 
271                            help=f"text to use as the title (default: taken from first two comments like {lang} does). Use twice for a second line")
272        pgroup.add_argument("--template-image", help=f"template image to use for png carts, instead of the default {lang} template")
273        pgroup.add_argument("--template-only", action="store_true", help="when creating the png cart, ignore the label & title, using just the template")
274        pgroup.add_argument("--palette", type=IntSplitBySeps, help="palette to use when importing/exporting spritesheets - a comma-separated list of indices")
275
276        pgroup = parser.add_argument_group("version options")
277        pgroup.add_argument("--version", action="store_true", help=f"print version of cart. (if no cart is provided - print {shrinko_name} version and exit)")
278        pgroup.add_argument("--output-version", type=parse_version_func, help=f"the version to convert the cart to. ({version_desc})")
279        pgroup.add_argument("--update-version", action="store_true", help=f"convert the cart to the latest supported version")
280
281        pgroup = parser.add_argument_group("misc. options")
282        pgroup.add_argument("-s", "--script", action="append", help=f"manipulate the cart via a custom script (python or {pico_name}) - see README for api details")
283        pgroup.add_argument("--script-args", nargs=argparse.REMAINDER, help="send arguments directly to --script", default=())
284        pgroup.add_argument("--extra-output", nargs='+', action="append", metavar=("OUTPUT [FORMAT]", ""),
285                            help="additional output file to produce (and optionally, the format to use)")
286
287        if is_picotron:
288            pgroup = parser.add_argument_group("picotron filesystem options")
289            pgroup.add_argument("--list", action="store_true", help="list all files inside the cart")
290            pgroup.add_argument("--filter", type=SplitBySeps, action="extend", help=f"specify a {sections_desc} to keep in the output")
291            pgroup.add_argument("--insert", nargs='+', action="append", metavar=(f"INPUT [FSPATH [FILTER]]", ""),
292                                help=f"insert the specified file or directory INPUT into FSPATH. (FILTER can be a {sections_desc} to insert - relative to cart root)")
293            pgroup.add_argument("--extract", nargs='+', action="append", metavar=(f"FSPATH [OUTPUT]", ""),
294                                help=f"extract the specified file or directory from FSPATH to OUTPUT ")
295            pgroup.set_defaults(list_includes=None)
296        else:
297            pgroup.add_argument("--list-includes", action="store_true", help="list all includes inside the cart")
298            pgroup.set_defaults(filter=None, insert=None, extract=None)
299        
300        pgroup.add_argument("--merge", nargs='+', action="append", metavar=(f"INPUT {sections_meta} [FORMAT]", ""),
301                            help=f"merge {sections_str} from the specified INPUT file, where {sections_meta} is a {sections_desc}")
302
303        if is_pico8:
304            pgroup = parser.add_argument_group("cart export options (for use with the formats: %s)" % EnumList(CartFormatCls, lambda e: e.is_export and e.is_exposed))
305            pgroup.add_argument("--list", action="store_true", help="list all cart names inside the export")
306            pgroup.add_argument("--dump", help="dump all carts inside the export to the specified folder. -f can be used to specify the output format")
307            pgroup.add_argument("--cart", help="name of cart to extract from the export")
308            pgroup.add_argument("--pico8-dat", dest="pico_dat", help="path to the pico8.dat file in the pico8 directory. needed to create new exports")
309            pgroup.add_argument("--output-cart", help="override name to use for the main cart in the export")
310            pgroup.add_argument("--extra-input", nargs='+', action="append", metavar=("INPUT [FORMAT [NAME]]", ""),
311                                help="additional input file to place in export (and optionally, the format of the file & the name to use for it in the export)")
312        else:
313            pgroup.add_argument("--dump", help="dump the cart/system/etc. inside a sysrom.dat to the specified folder. -f can set the output format of carts (e.g '-f dir')")
314            pgroup.add_argument("--picotron-dat", dest="pico_dat", help="path to the picotron.dat file in the picotron directory. needed to create exports")
315            pgroup.set_defaults(cart=None, output_cart=None, extra_input=())
316
317        if is_picotron:
318            pgroup = parser.add_argument_group("picotron filesystem advanced options")
319            pgroup.add_argument("--code-files", dest="code_sections", type=SplitBySeps, action="extend",
320                                help=f"specify a {sections_desc} that contain lua code to process (default: *.lua)")
321            pgroup.add_argument("--delete-meta", type=SplitBySeps, action="extend",
322                                help=f"specify a {sections_desc} to delete metadata of (default: * if minifying unsafely, else none)")
323            pgroup.add_argument("--keep-meta-keys", type=SplitBySeps, action="extend",
324                                help=f"specify a comma separated list of metadata keys (can use wildcards and ! for exclude) "
325                                f"to always keep (default & recommended: {','.join(default_keep_meta_keys)})")
326            pgroup.add_argument("--delete-label", action="store_true", default=None, help="always delete the label")
327            pgroup.add_argument("--keep-label", action="store_false", dest="delete_label", help="always keep the label")
328            pgroup.add_argument("--keep-pod-compression", action="store_true", help="keep compression of all pod files as-is")
329            pgroup.add_argument("-u", "--uncompress-pods", action="store_true", help="uncompress all pod files to plain text")
330            pgroup.add_argument("--base64-pods", action="store_true", help="base64 all pod files")
331        else:
332            pgroup.set_defaults(code_sections=None, delete_meta=None, keep_meta_keys=None, keep_label=None,
333                                uncompress_pods=None, keep_pod_compression=None, base64_pods=None)
334
335        pgroup = parser.add_argument_group("other interesting options (semi-undocumented)")
336        pgroup.add_argument("--bbs", action="store_true", help="interpret input as a bbs cart id, e.g. '#...' and download it from the bbs")
337        pgroup.add_argument("--url", action="store_true", help="interpret input as a URL, and download it from the internet")
338        if is_pico8:
339            pgroup.add_argument("--dump-misc-too", action="store_true", help="causes --dump to also dump misc. files inside the export")
340            pgroup.set_defaults(avoid_base64=False)
341        else:
342            pgroup.add_argument("--avoid-base64", action="store_true", help=f"avoid using base64 in p64 files whenever possible")
343            pgroup.set_defaults(dump_misc_too=True)
344
345        if is_pico8:
346            pgroup = parser.add_argument_group("export editing options (semi-undocumented)")
347            pgroup.add_argument("--insert-cart", nargs="*", metavar=("NAME", "BEFORE"), help="add the cart to an existing export. (The default name is the input cart's name)")
348            pgroup.add_argument("--replace-cart", nargs="*", metavar=("NAME"), help="replace the cart with the given name (Default: main cart) in the export")
349            pgroup.add_argument("--delete-cart", nargs=1, help="delete the cart with the given name from the export")
350            pgroup.add_argument("--rename-cart", nargs=2, metavar=("OLD", "NEW"), help="rename the cart with the given name in the export")
351        else:
352            pgroup.set_defaults(insert_cart=None, replace_cart=None, delete_cart=None, rename_cart=None)
353
354        pgroup = parser.add_argument_group("compression options (semi-undocumented)")
355        if is_pico8:
356            pgroup.add_argument("--keep-compression", action="store_true", help="keep existing compression, instead of re-compressing")
357            pgroup.add_argument("--force-compression", action="store_true", help="force code compression even if code fits")
358            pgroup.add_argument("--old-compression", action="store_true", help="compress with the old pre-v0.2.0 compression scheme")
359        else:
360            pgroup.set_defaults(keep_compression=False, force_compression=False, old_compression=False)
361        pgroup.add_argument("--optimize-png-compression", action="store_true", help="when generating a png, also optimize the size of the png itself (no effect on cart size)")
362        pgroup.add_argument("--fast-compression", action="store_true", help="force fast but very poor compression")
363        pgroup.add_argument("--trace-compression", help="trace the compressed symbols and their cost into this file")
364        pgroup.add_argument("--trace-input-compression", help="trace the input's compressed symbols and their cost into this file")
365
366        pgroup = parser.add_argument_group("other uninteresting options (semi-undocumented)")
367        pgroup.add_argument("--ignore-hints", action="store_true", help=f"ignore {shrinko_name} hint comments")
368        pgroup.add_argument("--builtin", type=SplitBySeps, action="extend", help=f"treat identifier(s) as a {pico_name} builtin (for minify, lint, etc.)")
369        pgroup.add_argument("--not-builtin", type=SplitBySeps, action="extend", help=f"do not treat identifier(s) as a {pico_name} builtin (for minify, lint, etc.)")
370        pgroup.add_argument("--export-name", help="name to use for the export (by default, taken from output name)")
371        pgroup.add_argument("--clean-output-dir", action="store_true",
372                            help="when the output is a directory, delete any existing files and subdirectories from the directory first (use with caution!)")
373        if is_pico8:
374            pgroup.add_argument("--global-builtins-only", action="store_true", help="assume all builtins are global, corresponds to pico8's -global_api option")
375            pgroup.add_argument("--local-builtin", type=SplitBySeps, action="extend", help="treat identifier(s) as a local builtin (probably no use outside of testing)")
376            pgroup.add_argument("--output-sections", type=SplitBySeps, action="extend", help=f"specifies a {sections_desc} to write to the p8")
377        else:
378            pgroup.set_defaults(global_builtins_only=False, local_builtin=None, output_sections=None)
379        
380        return parser
381
382    def default_format(input, for_output=False):
383        ext = path_extension(input)[1:].lower()
384        if ext in CartFormatCls._values and CartFormatCls(ext).is_ext:
385            return CartFormatCls(ext)
386        elif CartFormatCls.default_dir and path_is_native(input) and (path_is_dir(input) or not path_basename(input)):
387            return CartFormatCls.default_dir
388        elif for_output:
389            return CartFormatCls.default_src
390        else:
391            return None
392
393    def main_inner(args):
394        if args.version and not args.input:
395            print("v" + get_version())
396            return
397        
398        if args.watch:
399            args.watch = OneShotFileChangeWatcher()
400
401        if args.additional_inputs and not args.output:
402            args.output = args.additional_inputs[-1] # argparse doesn't support nargs=* followed by nargs=?
403            del args.additional_inputs[-1]
404        
405        if args.in_place:
406            if args.output:
407                throw("Cannot specify output cart with --in-place")
408            args.output = args.input
409            if args.input_format and not args.format:
410                args.format = args.input_format
411            
412        if not args.input:
413            throw("No input file specified")
414        
415        if args.delete_cart or args.rename_cart:
416            if args.output:
417                throw("Only need to specify a single cart when using --delete-cart or --rename-cart")
418            args.input, args.output = None, args.input
419
420        if args.input == "-":
421            args.input = StdPath("-")
422        if args.output == "-":
423            args.output = StdPath("-")
424
425        if args.url:
426            args.input = URLPath(args.input)
427        elif args.bbs:
428            args.input = URLPath(get_bbs_cart_url(args.input, lang))
429            args.input_format = CartFormatCls.png
430
431        if (not args.lint and not args.count and not args.output and not args.input_count and not args.version and
432            not args.list and not args.dump and not args.script and not args.extract and not args.list_includes):
433            throw("No operation (--lint/--count/--script/etc) or output file specified")
434        if args.format and not args.output and not args.dump:
435            throw("Output should be specified under --format")
436        if args.minify and not args.output and not args.count:
437            throw("Output (or --count) should be specified under --minify")
438        if args.minify and args.keep_compression:
439            throw("Can't modify code and keep compression")
440        if (args.list or args.dump) and (args.output or args.lint or args.count):
441            throw("--list & --dump can't be combined with most other options")
442        if (e(args.delete_cart) + e(args.rename_cart) + e(args.insert_cart) + e(args.replace_cart)) > 1:
443            throw("Can only specify one of --insert/replace/delete/rename-cart")
444            
445        if not args.input_format and args.input:
446            args.input_format = default_format(args.input)
447            if args.in_place and not args.format:
448                args.format = args.input_format
449
450        if not args.format and args.output:
451            args.format = default_format(args.output, for_output=True)
452
453        if args.lint:
454            args.lint = {
455                "unused": not args.no_lint_unused,
456                "unused-global": not args.no_lint_unused_global,
457                "duplicate": not args.no_lint_duplicate,
458                "duplicate-global": not args.no_lint_duplicate_global,
459                "undefined": not args.no_lint_undefined,
460                "globals": args.lint_global or (),
461            }
462        
463        args.focus = []
464        if args.focus_chars:
465            args.focus.append("chars")
466        if args.focus_compressed:
467            args.focus.append("compressed")
468        if args.focus_tokens:
469            args.focus.append("tokens")
470
471        minify_limited = args.minify_consts_only or args.minify_transform_only
472        if args.minify or args.minify_safe_only or minify_limited:
473            args.minify = {
474                "safe-reorder": args.minify_safe_only or args.reorder_safe_only,
475                "safe-builtins": args.minify_safe_only or args.builtins_safe_only,
476                "lines": not minify_limited and not args.no_minify_lines,
477                "wspace": not minify_limited and not args.no_minify_spaces,
478                "comments": not minify_limited and not args.no_minify_comments,
479                "tokens": not minify_limited and not args.no_minify_tokens,
480                "reorder": not minify_limited and not args.no_minify_reorder,
481                "consts": (not minify_limited or args.minify_consts_only) and not args.no_minify_consts,
482                "transform": (not minify_limited or args.minify_transform_only) and not args.no_minify_transform,
483                "focus": args.focus,
484            }
485
486        args.rename = bool(args.minify) and not args.no_minify_rename and not minify_limited
487        if args.rename:
488            if args.no_preserve:
489                args.preserve = (args.preserve or []) + [f"!{item}" for item in args.no_preserve]
490            if args.rename_members_as_globals:
491                args.preserve = (args.preserve or []) + ["*=*.*"]
492            args.rename = {
493                "safe-only": args.minify_safe_only or args.rename_safe_only,
494                "focus": args.focus,
495                "rules": args.preserve or (),
496            }
497
498        if args.unminify:
499            args.unminify = {
500                "indent": args.unminify_indent
501            }
502        
503        if args.const or args.str_const:
504            if args.const:
505                args.const = {name: parse_constant(val, lang) or throw(f"cannot parse const <{val}>. If it's meant to be a string, try using --str-const instead") 
506                            for name, val in args.const}
507            if args.str_const:
508                args.const = args.const or {}
509                args.const.update({name: parse_constant(val, lang, as_str=True) for name, val in args.str_const})
510
511        if is_picotron and not args.delete_meta and args.minify and not args.minify_safe_only:
512            args.delete_meta = ["*"]
513        if is_picotron and not args.keep_meta_keys:
514            args.keep_meta_keys = default_keep_meta_keys
515
516        args.preproc_cb, args.postproc_cb, args.preproc_syntax_cb = None, None, None
517        args.include_cb = lambda name, **kwargs: find_in_builtin_script(name, kwargs, "include_main")
518        args.sublang_cb = lambda name, **kwargs: find_in_builtin_script(name, kwargs, "sublanguage_main")
519        args.compiler_cb = lambda name, **kwargs: find_in_builtin_script(name, kwargs, "compiler_main")
520        if args.script:
521            for script in args.script:
522                if args.watch:
523                    args.watch.add(script) # doesn't extend to imports, though
524
525                script_ext = path_extension(script).lower()
526                if script_ext == ".py":
527                    script_obj = exec_script_by_path(script)
528                elif script_ext in (".lua", ".p8"):
529                    from run_pico import exec_pico_script_by_path, lua_type
530                    script_obj = exec_pico_script_by_path(script)
531                    if lua_type(script_obj) != "table":
532                        eprint(f"WARNING: script '{script}' didn't return a table")
533                        continue
534                else:
535                    throw(f"unrecognized script extension {script_ext} (can be .py/.lua/.p8)")
536
537                preproc_main, postproc_main, preproc_syntax_main, include_main, sublang_main, compiler_main = tuple(
538                    getattr(script_obj, name, None) for name in 
539                          ("preprocess_main", "postprocess_main", "preprocess_syntax_main", "include_main", "sublanguage_main", "compiler_main"))
540                args.preproc_cb = func_union(args.preproc_cb, preproc_main)
541                args.postproc_cb = func_union(postproc_main, args.postproc_cb) # (reverse order)
542                args.preproc_syntax_cb = func_union(args.preproc_syntax_cb, preproc_syntax_main)
543                args.include_cb = func_union(include_main, args.include_cb, return_early=e) # (reverse order)
544                args.sublang_cb = func_union(sublang_main, args.sublang_cb, return_early=e) # (reverse order)
545                args.compiler_cb = func_union(compiler_main, args.compiler_cb, return_early=e) # (reverse order)
546
547        base_count_handler = ParsableCountHandler if args.parsable_count else True
548        if args.input_count:
549            args.input_count = base_count_handler
550        if args.count:
551            args.count = base_count_handler
552
553        if args.trace_input_compression:
554            args.trace_input_compression = CompressionTracer(args.trace_input_compression, lang)
555        if args.trace_compression:
556            args.trace_compression = CompressionTracer(args.trace_compression, lang)
557
558        if args.input:
559            cart, extra_carts = handle_input(args)
560            if cart is None: # e.g. list/dump case
561                return ErrCodes.ok
562            
563            passed, ok = handle_processing(args, cart, extra_carts)
564            if not passed:
565                return ErrCodes.warn if ok else ErrCodes.err
566            
567        else: # output-only operations
568            cart, extra_carts = None, ()
569
570        handle_output(args, cart, extra_carts)
571
572    class InputDef(Tuple):
573        input = format = name = sections = fspath = None
574
575    def on_include(args, path):
576        if args.watch:
577            args.watch.add(path)
578        if args.list_includes:
579            print(path_relative(path))
580
581    def handle_input(args):
582        allow_extra_input = is_pico8 and args.format and args.format.is_export
583
584        common_input_args = dict(keep_compression=args.keep_compression, palette=args.palette,
585                                 debug_handler=args.trace_input_compression, size_handler=args.input_count,
586                                 include_notifier=lambda path: on_include(args, path))
587
588        # read the main cart
589        extra_carts = []
590        try:
591            if args.watch:
592                args.watch.add(args.input)
593
594            if (is_pico8 and args.list) or args.dump:
595                export = read_cart_export_func(args.input, args.input_format)
596                if args.list:
597                    for entry in export.list_carts():
598                        print(entry)
599                else:
600                    dir_create(args.dump, delete_existing=args.clean_output_dir)
601                    export.dump_contents(args.dump, default(args.format, CartFormatCls.default_src), misc=args.dump_misc_too)
602                return None, None
603
604            main_cart = read_cart_func(args.input, args.input_format, cart_name=args.cart,
605                                       extra_carts=extra_carts if allow_extra_input and not args.cart else None,
606                                       **common_input_args)
607        except OSError as err:
608            throw(f"cannot read cart: {err}")
609        
610        # collect additional carts to read
611        if args.additional_inputs:
612            if not args.extra_input:
613                args.extra_input = []
614            for input in args.additional_inputs:
615                args.extra_input.append((input,))
616
617        extra_inputs = []
618        if args.extra_input:
619            if not allow_extra_input:
620                throw("--extra-input can only be used when creating exports")
621            
622            for extra in args.extra_input:
623                if len(extra) == 1:
624                    extra_inputs.append(InputDef(extra[0], default_format(extra[0], for_output=True)))
625                elif 3 >= len(extra) >= 2:
626                    extra_inputs.append(InputDef(extra[0], CartFormatCls(extra[1]), name=list_get(extra, 2)))
627                else:
628                    throw("too many arguments to --extra-output")
629        
630        if args.insert:
631            for insert in args.insert:
632                if len(insert) == 1:
633                    extra_inputs.append(InputDef(insert[0], CartFormatCls.fs, fspath=path_basename(insert[0])))
634                elif len(insert) == 2:
635                    extra_inputs.append(InputDef(insert[0], CartFormatCls.fs, fspath=insert[1]))
636                elif len(insert) == 3:
637                    extra_inputs.append(InputDef(insert[0], CartFormatCls.fs, fspath=insert[1], sections=SplitBySeps(insert[2])))
638                else:
639                    throw("too many arguments to --insert (must be 1 through 3)")
640
641        if args.merge:
642            for merge in args.merge:
643                if len(merge) == 2:
644                    extra_inputs.append(InputDef(merge[0], default_format(merge[0]), sections=SplitBySeps(merge[1])))
645                elif len(merge) == 3:
646                    extra_inputs.append(InputDef(merge[0], CartFormatCls(merge[2]), sections=SplitBySeps(merge[1])))
647                else:
648                    throw("too many or few arguments to --merge (must be 2 or 3)")
649        
650        if args.label:
651            extra_inputs.append(InputDef(args.label, CartFormatCls.label, sections=(label_section,)))
652        if args.title:
653            main_cart.set_raw_title(args.title)
654
655        # read additional carts
656        for input, input_format, input_name, merge_sections, fspath in extra_inputs:
657            if args.watch:
658                args.watch.add(input)
659                               
660            cart = read_cart_func(input, input_format, fspath=fspath, sections=merge_sections, **common_input_args)
661            
662            if input_name:
663                cart.name = input_name
664            
665            if e(merge_sections) or e(fspath):
666                merge_cart_func(main_cart, cart, merge_sections)
667            else:
668                extra_carts.append(cart)
669        
670        if is_picotron and args.list:
671            for path in main_cart.files:
672                print(path)
673            return None, None
674
675        return main_cart, extra_carts
676
677    def handle_processing(args, main_cart, extra_carts):
678        had_warns = False
679
680        for cart in itertools.chain((main_cart,), extra_carts):
681            if args.update_version:
682                cart.set_version(get_latest_version_func())
683            elif e(args.output_version):
684                cart.set_version(args.output_version)
685        
686            if args.filter:
687                filter_cart_func(cart, args.filter)
688
689            if is_picotron:
690                preproc_cart_func(cart, delete_meta=args.delete_meta, keep_meta_keys=args.keep_meta_keys,
691                                  delete_label=default(args.delete_label, args.format == CartFormatCls.png),
692                                  keep_pod_compression=args.keep_pod_compression,
693                                  uncompress_pods=args.uncompress_pods, base64_pods=args.base64_pods,
694                                  # binary formats are already compressed, so pod compression just hurts
695                                  need_pod_compression=args.format and args.format.is_src)
696
697            src = CartSourceCls(cart, args.code_sections)
698            
699            if args.input_count:
700                write_code_size_func(cart, handler=args.input_count, input=True)
701                
702            with ContextCls(extra_builtins=args.builtin, not_builtins=args.not_builtin, 
703                            use_local_builtins=not args.global_builtins_only,
704                            extra_local_builtins=args.local_builtin,
705                            srcmap=args.rename_map, version=cart.version_id, include_getter=args.include_cb,
706                            sublang_getter=args.sublang_cb, compiler_getter=args.compiler_cb,
707                            default_compiler=args.default_compiler,
708                            hint_comments=not args.ignore_hints, consts=args.const,
709                            ignore_transforms=args.no_minify_transform) as ctxt:
710                if args.preproc_cb:
711                    args.preproc_cb(cart=cart, src=src, ctxt=ctxt, args=args)
712
713                def preproc_syntax_call(root, on_error):
714                    args.preproc_syntax_cb(cart=cart, src=src, root=root, on_error=on_error, ctxt=ctxt, args=args)
715
716                ok, errors = process_code(ctxt, src,
717                                        input_count=is_pico8 and args.input_count,
718                                        count=is_pico8 and args.count,
719                                        lint=args.lint, minify=args.minify, rename=args.rename,
720                                        unminify=args.unminify, stop_on_lint=not args.no_lint_fail,
721                                        count_is_optional=args.no_count_tokenize,
722                                        preproc=preproc_syntax_call if args.preproc_syntax_cb else None)
723                if errors:
724                    had_warns = True
725
726                    if not ok:
727                        print("Compilation errors:")
728                    elif args.lint:
729                        print("Lint warnings:")
730                    else:
731                        print("Hint usage warnings:")
732                    
733                    for error in sorted(errors):
734                        print(error.format(args.error_format))
735                    
736                    if not ok or (args.lint and not args.no_lint_fail):
737                        return False, ok
738
739                if args.rename_map:
740                    file_write_maybe_text(args.rename_map, "\n".join(ctxt.srcmap))
741                    
742                if args.postproc_cb:
743                    args.postproc_cb(cart=cart, args=args, ctxt=ctxt)
744                
745                if args.count:
746                    write_code_size_func(cart, handler=args.count)
747                    if not (args.output and not args.format.is_src) and not args.no_count_compress: # else, will be done in write_cart
748                        write_compressed_size_func(cart, handler=args.count, fast_compress=args.fast_compression, debug_handler=args.trace_compression)
749                
750                if args.version:
751                    write_cart_version_func(cart)
752        
753        return True, not had_warns
754
755    class OutputDef(Tuple):
756        output = format = fspath = None
757
758    def handle_output(args, cart, extra_carts):
759        if e(args.insert_cart):
760            output_cart_op = ListOp.insert
761            output_cart_name, output_cart_target = list_unpack(args.insert_cart, 2)
762        elif e(args.replace_cart):
763            output_cart_op = ListOp.replace
764            output_cart_name, output_cart_target = list_unpack(args.replace_cart, 2)
765        elif e(args.delete_cart):
766            output_cart_op = ListOp.delete
767            output_cart_name, output_cart_target = list_unpack(args.delete_cart, 2)
768        elif e(args.rename_cart):
769            output_cart_op = ListOp.rename
770            output_cart_name, output_cart_target = list_unpack(args.rename_cart, 2)
771        else:
772            output_cart_op = output_cart_target = None
773            output_cart_name = args.output_cart
774
775        all_outputs = []
776        if args.output:
777            all_outputs.append(OutputDef(args.output, args.format))
778        
779        if args.extra_output:
780            for extra in args.extra_output:
781                if len(extra) == 1:
782                    all_outputs.append(OutputDef(extra[0], default_format(extra[0], for_output=True)))
783                elif len(extra) == 2:
784                    all_outputs.append(OutputDef(extra[0], CartFormatCls(extra[1])))
785                else:
786                    throw("too many arguments to --extra-output (must be 1 or 2)")
787        
788        if args.extract:
789            for extract in args.extract:
790                if len(extract) == 1:
791                    all_outputs.append(OutputDef(path_basename(extract[0]), CartFormatCls.fs, extract[0]))
792                elif len(extract) == 2:
793                    all_outputs.append(OutputDef(extract[1], CartFormatCls.fs, extract[0]))
794                else:
795                    throw("too many arguments to --extract (must be 1 or 2)")
796
797        for output, format, fspath in all_outputs:
798            target_export, pico_dat = None, None
799            if format.is_export:
800                if e(output_cart_op):
801                    try:
802                        target_export = read_cart_export_func(output, format)
803                    except OSError as err:
804                        throw(f"cannot read export for editing: {err}")
805                else:
806                    if not args.pico_dat:
807                        throw(f"Creating a new export requires passing --{pico_name}-dat <path to {pico_name}.dat>")
808                    try:
809                        pico_dat = read_pico_dat_func(args.pico_dat)
810                    except OSError as err:
811                        throw(f"cannot read {pico_name} dat: {err}")
812
813            try:
814                write_cart_func(output, cart, format, extra_carts=extra_carts, fspath=fspath,
815                                delete_existing=args.clean_output_dir,
816                                size_handler=args.count, debug_handler=args.trace_compression,
817                                unicode_caps=args.unicode_caps, old_compress=args.old_compression,
818                                force_compress=args.count or args.force_compression,
819                                fast_compress=args.fast_compression, keep_compression=args.keep_compression,
820                                template_image=args.template_image, template_only=args.template_only,
821                                optimize_image=args.optimize_png_compression, palette=args.palette,
822                                sections=args.output_sections, avoid_base64=args.avoid_base64,
823                                cart_op=output_cart_op, cart_name=output_cart_name, target_name=output_cart_target,
824                                target_export=target_export, export_name=args.export_name, pico_dat=pico_dat)
825            except OSError as err:
826                throw(f"cannot write cart: {err}")
827
828    parser = create_parser()
829
830    def main_once(args):
831        try:
832            result = main_inner(args)
833            return result
834
835        except CheckError as err:
836            sys.stdout.flush()
837            eprint("ERROR: " + str(err))
838            if isinstance(err, IncludeNotFoundError):
839                errcode = ErrCodes.include
840            else:
841                errcode = ErrCodes.fail
842            return errcode
843
844        except Exception:
845            if not args.watch:
846                raise # ideally we won't have any raw exceptions
847            traceback.print_exc()
848            return ErrCodes.fail
849            
850    def main(raw_args=None):
851        raw_args = default(raw_args, sys.argv[1:])
852
853        if not raw_args: # help is better than usage
854            parser.print_help(sys.stderr)
855            return ErrCodes.err
856        
857        first = True
858        while True:
859            args = parser.parse_intermixed_args(raw_args)
860            errcode = main_once(args)
861
862            if not args.watch or args.watch == True:
863                return errcode
864
865            eprint(f"{'Starting' if first else 'Resuming'} watch... (Ctrl+C to terminate)\n")
866            first = False
867            
868            if not args.watch.wait():
869                return errcode
870
871    return main

Return a 'main' function for the given language. The main function optionally receives raw arguments and returns an exit code