pico_output
Functions for writing a syntax tree into a string (either minifying or preserving whitespace)
1"""Functions for writing a syntax tree into a string (either minifying or preserving whitespace)""" 2 3from utils import * 4from pico_defs import k_fixnum_mask, k_luaint_mask, float_is_negative 5from pico_srcdefs import Source 6from pico_tokenize import tokenize, parse_fixnum 7from pico_tokenize import Token, k_char_escapes, Comment, CommentHint, k_keep_prefix 8from pico_parse import k_nested 9 10def float_str_add_1(str): 11 if not str: 12 return "1" 13 elif str[-1] == ".": 14 return float_str_add_1(str[:-1]) + "." 15 elif str[-1] == "9": 16 return float_str_add_1(str[:-1]) + "0" 17 else: 18 return str[:-1] + chr(ord(str[-1]) + 1) 19 20def float_str_minify(str, parse, cmpval, keep_float=False): 21 ok = parse(str) == cmpval 22 23 while "." in str: 24 ch = str[-1] 25 if ch == '.': 26 if not keep_float: 27 str = str[:-1] 28 break 29 elif ch == "0" and ok: # easy case 30 str = str[:-1] 31 continue 32 33 nextvalue = str[:-1] 34 nextupvalue = float_str_add_1(nextvalue) 35 if parse(nextvalue) == cmpval: 36 str = nextvalue 37 ok = True 38 elif parse(nextupvalue) == cmpval: 39 str = nextupvalue 40 ok = True 41 else: 42 check(ok, "float_str_minify error") 43 break 44 45 if str.startswith("0.") and str != "0.": 46 str = str[1:] 47 return str 48 49# essentially only returns decvalue right now, given mostly non-fract. inputs 50# TODO: test with fract-ish inputs to see what's best to do. 51def format_fixnum(value, sign=None, base=None): 52 """format a fixnum to a pico8 string""" 53 if sign: 54 if sign == '-': 55 value = -value & k_fixnum_mask 56 elif sign == '~': 57 value = ~value & k_fixnum_mask 58 else: 59 throw("invalid sign") 60 61 intvalue = value >> 16 62 dotvalue = value & 0xffff 63 64 if base is None or base == 16: 65 hexvalue = "0x%x" % intvalue 66 if dotvalue: 67 hexvalue = "0x" if hexvalue == "0x0" else hexvalue 68 hexvalue += (".%04x" % dotvalue).rstrip('0') 69 70 if base: 71 minvalue = hexvalue 72 73 if base is None or base == 10: 74 numvalue = value / (1 << 16) 75 decvalue = float_str_minify("%.6f" % numvalue, parse_fixnum, value) 76 77 if base: 78 minvalue = decvalue 79 80 if not base: 81 minvalue = hexvalue if len(hexvalue) < len(decvalue) else decvalue 82 83 if sign: 84 minvalue = sign + minvalue 85 86 if sign is None and value & 0x80000000 and value != 0x80000000: 87 negvalue = format_fixnum(value, sign='-', base=base) 88 if len(negvalue) < len(minvalue): 89 minvalue = negvalue 90 91 notvalue = format_fixnum(value, sign='~', base=base) 92 if len(notvalue) < len(minvalue): 93 minvalue = notvalue 94 95 return minvalue 96 97def float_sign(value): 98 return "-" if float_is_negative(value) else "" 99 100def float_hex(value, hexdigits, keep_float=False): # like value.hex(), except doesn't use an exponent 101 hexval = hex(int(abs(value) * (1 << (hexdigits * 4))))[2:].rjust(hexdigits, '0') 102 result = f"0x{hexval[:-hexdigits]}.{hexval[-hexdigits:]}".rstrip("0") 103 if not keep_float: 104 result = result.rstrip(".") 105 if result in ("0x", "0x."): 106 result = "0x0" 107 return float_sign(value) + result 108 109def format_luanum(value, sign=None, base=None, allow_not=True): 110 """format a luanum to a picotron string""" 111 if isinstance(value, int): 112 if sign: 113 if sign == '-': 114 value = -value 115 elif sign == '~': 116 value = ~value 117 else: 118 throw("invalid sign") 119 120 value &= k_luaint_mask 121 122 if base is None or base == 16: 123 hexvalue = "0x%x" % value 124 if base: 125 minvalue = hexvalue 126 127 if base is None or base == 10: 128 decvalue = "%d" % value 129 if base: 130 minvalue = decvalue 131 132 if not base: 133 if value >= 0x8000000000000000: 134 minvalue = hexvalue # else, it won't be parsed as an integer 135 else: 136 minvalue = hexvalue if len(hexvalue) < len(decvalue) else decvalue 137 138 if sign: 139 minvalue = sign + minvalue 140 141 if sign is None and value & 0x8000000000000000 and value != 0x8000000000000000: 142 negvalue = format_luanum(value, sign='-', base=base) 143 if len(negvalue) < len(minvalue): 144 minvalue = negvalue 145 146 if allow_not: 147 notvalue = format_luanum(value, sign='~', base=base) 148 if len(notvalue) < len(minvalue): 149 minvalue = notvalue 150 151 else: # float 152 parens = False 153 if e(sign) and sign != float_sign(value): 154 # only thing we can do is surround result in parens 155 sign = None 156 parens = True 157 158 if sign is None: 159 sign = float_sign(value) 160 161 value = abs(value) 162 163 if math.isinf(value): 164 if base == 16: 165 minvalue = "0x1p1111" 166 else: 167 minvalue = "1e333" 168 169 elif math.isnan(value): 170 raise ValueError("nan not supported") # could output <inf>*0 in parens? (0/0 doesn't currently nan) 171 172 else: 173 # TODO: this is very not optimal (but at least it's correct this time...) 174 175 if base is None or base == 16: 176 manvalue, expvalue = math.frexp(value) 177 manvalue *= 2; expvalue -= 1 # the 1..2 range is better for us 178 expvalue = f"{float_hex(manvalue, 56)}p{expvalue}" 179 180 if value == 0 or 1e-4 <= value <= 1e24: 181 hexvalue = float_hex(value, 88, keep_float=True) 182 hexvalue = expvalue if len(expvalue) < len(hexvalue) else hexvalue 183 else: 184 hexvalue = expvalue 185 186 if base: 187 minvalue = hexvalue 188 189 if base is None or base == 10: 190 manstr, expstr = ("%.19e" % value).split("e") 191 expstr = f"e{int(expstr)}" 192 expvalue = float_str_minify(manstr, lambda v: float(v + expstr), value) + expstr 193 194 if value == 0 or 1e-3 <= value <= 1e21: 195 decvalue = float_str_minify("%.24f" % value, float, value, keep_float=True) 196 decvalue = expvalue if len(expvalue) < len(decvalue) else decvalue 197 else: 198 decvalue = expvalue 199 200 if base: 201 minvalue = decvalue 202 203 if not base: 204 minvalue = hexvalue if len(hexvalue) < len(decvalue) else decvalue 205 206 minvalue = sign + minvalue 207 if parens: 208 minvalue = "(" + minvalue + ")" 209 210 return minvalue 211 212k_char_escapes_rev = {v: k for k, v in k_char_escapes.items() if k != '\n'} 213k_char_escapes_rev.update({"\0": "0", "\x0e": "14", "\x0f": "15"}) 214 215k_char_escapes_rev_min = {k: v for k, v in k_char_escapes_rev.items() if k in "\0\n\r\"'\\"} 216 217def get_long_brackets_equals(value): 218 for i in itertools.count(): 219 eqs = "=" * i 220 if f"]{eqs}]" not in value: 221 return eqs 222 223def format_string_literal(value, use_ctrl_chars=True, use_complex_long=True, long=None, quote=None): 224 """format a pico8 string to a pico8 string literal""" 225 226 if long != False: 227 if "\0" not in value and "\r" not in value and (use_complex_long or "]]" not in value): 228 newline = "\n" if value.startswith("\n") else "" 229 230 eqs = get_long_brackets_equals(value) 231 strlong = f"[{eqs}[{newline}{value}]{eqs}]" 232 if long == True: 233 return strlong 234 else: 235 strlong = None 236 long = False 237 238 if long != True: 239 if quote is None: 240 quote = '"' if value.count('"') <= value.count("'") else "'" 241 242 exclude_esc = "'" if quote == '"' else '"' 243 244 char_escapes_rev = k_char_escapes_rev_min if use_ctrl_chars else k_char_escapes_rev 245 246 litparts = [] 247 for i, ch in enumerate(value): 248 if ch in char_escapes_rev and ch != exclude_esc: 249 esc = char_escapes_rev[ch] 250 if esc.isdigit() and i + 1 < len(value) and value[i + 1].isdigit(): 251 esc = esc.rjust(3, '0') 252 litparts.append("\\" + esc) 253 else: 254 litparts.append(ch) 255 256 strlit = '%s%s%s' % (quote, "".join(litparts), quote) 257 if long == False: 258 return strlit 259 260 return strlong if len(strlong) < len(strlit) else strlit 261 262def need_whitespace_between(ctxt, prev, next): 263 if isinstance(prev, Comment) or isinstance(next, Comment): 264 return False 265 266 combined = prev.value + next.value 267 ct, ce = tokenize(Source("<output>", combined), lang=ctxt.lang) # TODO: optimize? 268 return ce or len(ct) != 2 or (ct[0].type, ct[0].value, ct[1].type, ct[1].value) != (prev.type, prev.value, next.type, next.value) 269 270def is_non_nested_short(node): 271 # k_nested is set for shorthands used in the middle of a line 272 return node.short and node.short is not k_nested 273 274def get_orig_wspace(pre, post, ctxt, allow_linebreaks, need_linebreak=False): 275 source = default(pre.source, post.source) 276 text = source.text[pre.endidx:post.idx] 277 278 if text and not text.isspace(): 279 tokens, _ = tokenize(Source("<output>", text), lang=ctxt.lang) # TODO: optimize? 280 if tokens: 281 if "\n" in text and allow_linebreaks: 282 need_linebreak = True 283 text = text[tokens[-1].endidx:] or text[:tokens[0].idx] 284 285 newlines = min(text.count("\n"), 2) 286 if newlines: 287 text = text[text.rfind("\n")+1:] 288 289 num_lspace = len(text) - len(text.lstrip(" ")) 290 num_rspace = len(text) - len(text.rstrip(" ")) 291 text = "\n" * newlines + " " * max(num_lspace, num_rspace) 292 293 if not allow_linebreaks and "\n" in text: 294 text = text[:text.index("\n")] + " " 295 if need_linebreak and "\n" not in text: 296 text += "\n" 297 298 return text 299 300def output_node(root, ctxt, minify=True, minify_wspace=None, minify_lines=None, exclude_comments=None): 301 """convert a root back to a string, inserting as little whitespace as possible (under minify_wspace), 302 or using original whitespace (optionally except comments)""" 303 minify_wspace = default(minify_wspace, minify) 304 minify_lines = default(minify_lines, minify) 305 exclude_comments = default(exclude_comments, minify) 306 307 output = [] 308 prev_token_or_comment = Token.none 309 need_linebreak = False 310 short_level = 0 311 312 def wspace_output(next_token_or_comment, can_need_linebreak=True): 313 nonlocal prev_token_or_comment, need_linebreak 314 prev, next = prev_token_or_comment, next_token_or_comment 315 316 if minify_wspace: 317 # (modified tokens may require whitespace not previously required - e.g. 0b/0x) 318 if (prev.endidx < next.idx or prev.source != next.source or prev.modified or next.modified) and prev.value: 319 # TODO: can we systemtically add whitespace to imrpove compression? (failed so far) 320 321 if ((need_linebreak and can_need_linebreak) or 322 (not minify_lines and next.vline != prev.vline and not prev.value.endswith("\n"))): 323 output.append("\n") 324 need_linebreak = False 325 elif need_whitespace_between(ctxt, prev, next): 326 output.append(" ") 327 328 else: 329 allow_linebreaks = next.vline != prev.vline 330 wspace = get_orig_wspace(prev, next, ctxt, allow_linebreaks, need_linebreak and can_need_linebreak) 331 332 if not wspace and prev.value != None and need_whitespace_between(ctxt, prev, next): 333 wspace += " " 334 335 output.append(wspace) 336 if "\n" in wspace: 337 need_linebreak = False 338 339 prev_token_or_comment = next 340 341 def comment_output(comment, allow_linebreaks): 342 nonlocal prev_token_or_comment, need_linebreak 343 344 if exclude_comments: 345 if comment.hint == CommentHint.keep: 346 comment_text = comment.value.replace(comment.hintprefix + k_keep_prefix, "", 1) 347 else: 348 return 349 else: 350 comment_text = comment.value 351 352 if not allow_linebreaks and "\n" in comment_text: 353 if comment.isblock: 354 comment_text = re.sub(r"\n\s*", " ", comment_text) 355 else: 356 eqs = get_long_brackets_equals(comment_text) 357 comment_text = f"--[{eqs}[{comment_text[2:-1]}]{eqs}]" 358 359 wspace_output(comment, can_need_linebreak=False) 360 output.append(comment_text) 361 362 if need_linebreak and "\n" in comment_text: 363 need_linebreak = False 364 365 def token_output(token): 366 if token.children: 367 allow_linebreaks = prev_token_or_comment.vline != token.vline 368 369 for comment in token.children: 370 comment_output(comment, allow_linebreaks) 371 372 if token.value != None: 373 wspace_output(token) 374 output.append(token.value) 375 376 def pre_node_output(node): 377 nonlocal short_level 378 if is_non_nested_short(node): 379 short_level += 1 380 381 def post_node_output(node): 382 nonlocal short_level, need_linebreak 383 if is_non_nested_short(node): 384 short_level -= 1 385 if short_level == 0: 386 need_linebreak = True 387 388 root.traverse_nodes(tokens=token_output, pre=pre_node_output, post=post_node_output) 389 return "".join(output) 390 391def output_code(ctxt, root, minify_opts): 392 minify_lines = minify_opts.get("lines", True) 393 minify_wspace = minify_opts.get("wspace", True) 394 minify_comments = minify_opts.get("comments", True) 395 396 return output_node(root, ctxt, None, minify_wspace, minify_lines, minify_comments) 397 398def output_needs_comments(minify_opts): 399 return not minify_opts.get("comments", True)
def
float_str_add_1(str):
def
float_str_minify(str, parse, cmpval, keep_float=False):
21def float_str_minify(str, parse, cmpval, keep_float=False): 22 ok = parse(str) == cmpval 23 24 while "." in str: 25 ch = str[-1] 26 if ch == '.': 27 if not keep_float: 28 str = str[:-1] 29 break 30 elif ch == "0" and ok: # easy case 31 str = str[:-1] 32 continue 33 34 nextvalue = str[:-1] 35 nextupvalue = float_str_add_1(nextvalue) 36 if parse(nextvalue) == cmpval: 37 str = nextvalue 38 ok = True 39 elif parse(nextupvalue) == cmpval: 40 str = nextupvalue 41 ok = True 42 else: 43 check(ok, "float_str_minify error") 44 break 45 46 if str.startswith("0.") and str != "0.": 47 str = str[1:] 48 return str
def
format_fixnum(value, sign=None, base=None):
52def format_fixnum(value, sign=None, base=None): 53 """format a fixnum to a pico8 string""" 54 if sign: 55 if sign == '-': 56 value = -value & k_fixnum_mask 57 elif sign == '~': 58 value = ~value & k_fixnum_mask 59 else: 60 throw("invalid sign") 61 62 intvalue = value >> 16 63 dotvalue = value & 0xffff 64 65 if base is None or base == 16: 66 hexvalue = "0x%x" % intvalue 67 if dotvalue: 68 hexvalue = "0x" if hexvalue == "0x0" else hexvalue 69 hexvalue += (".%04x" % dotvalue).rstrip('0') 70 71 if base: 72 minvalue = hexvalue 73 74 if base is None or base == 10: 75 numvalue = value / (1 << 16) 76 decvalue = float_str_minify("%.6f" % numvalue, parse_fixnum, value) 77 78 if base: 79 minvalue = decvalue 80 81 if not base: 82 minvalue = hexvalue if len(hexvalue) < len(decvalue) else decvalue 83 84 if sign: 85 minvalue = sign + minvalue 86 87 if sign is None and value & 0x80000000 and value != 0x80000000: 88 negvalue = format_fixnum(value, sign='-', base=base) 89 if len(negvalue) < len(minvalue): 90 minvalue = negvalue 91 92 notvalue = format_fixnum(value, sign='~', base=base) 93 if len(notvalue) < len(minvalue): 94 minvalue = notvalue 95 96 return minvalue
format a fixnum to a pico8 string
def
float_sign(value):
def
float_hex(value, hexdigits, keep_float=False):
101def float_hex(value, hexdigits, keep_float=False): # like value.hex(), except doesn't use an exponent 102 hexval = hex(int(abs(value) * (1 << (hexdigits * 4))))[2:].rjust(hexdigits, '0') 103 result = f"0x{hexval[:-hexdigits]}.{hexval[-hexdigits:]}".rstrip("0") 104 if not keep_float: 105 result = result.rstrip(".") 106 if result in ("0x", "0x."): 107 result = "0x0" 108 return float_sign(value) + result
def
format_luanum(value, sign=None, base=None, allow_not=True):
110def format_luanum(value, sign=None, base=None, allow_not=True): 111 """format a luanum to a picotron string""" 112 if isinstance(value, int): 113 if sign: 114 if sign == '-': 115 value = -value 116 elif sign == '~': 117 value = ~value 118 else: 119 throw("invalid sign") 120 121 value &= k_luaint_mask 122 123 if base is None or base == 16: 124 hexvalue = "0x%x" % value 125 if base: 126 minvalue = hexvalue 127 128 if base is None or base == 10: 129 decvalue = "%d" % value 130 if base: 131 minvalue = decvalue 132 133 if not base: 134 if value >= 0x8000000000000000: 135 minvalue = hexvalue # else, it won't be parsed as an integer 136 else: 137 minvalue = hexvalue if len(hexvalue) < len(decvalue) else decvalue 138 139 if sign: 140 minvalue = sign + minvalue 141 142 if sign is None and value & 0x8000000000000000 and value != 0x8000000000000000: 143 negvalue = format_luanum(value, sign='-', base=base) 144 if len(negvalue) < len(minvalue): 145 minvalue = negvalue 146 147 if allow_not: 148 notvalue = format_luanum(value, sign='~', base=base) 149 if len(notvalue) < len(minvalue): 150 minvalue = notvalue 151 152 else: # float 153 parens = False 154 if e(sign) and sign != float_sign(value): 155 # only thing we can do is surround result in parens 156 sign = None 157 parens = True 158 159 if sign is None: 160 sign = float_sign(value) 161 162 value = abs(value) 163 164 if math.isinf(value): 165 if base == 16: 166 minvalue = "0x1p1111" 167 else: 168 minvalue = "1e333" 169 170 elif math.isnan(value): 171 raise ValueError("nan not supported") # could output <inf>*0 in parens? (0/0 doesn't currently nan) 172 173 else: 174 # TODO: this is very not optimal (but at least it's correct this time...) 175 176 if base is None or base == 16: 177 manvalue, expvalue = math.frexp(value) 178 manvalue *= 2; expvalue -= 1 # the 1..2 range is better for us 179 expvalue = f"{float_hex(manvalue, 56)}p{expvalue}" 180 181 if value == 0 or 1e-4 <= value <= 1e24: 182 hexvalue = float_hex(value, 88, keep_float=True) 183 hexvalue = expvalue if len(expvalue) < len(hexvalue) else hexvalue 184 else: 185 hexvalue = expvalue 186 187 if base: 188 minvalue = hexvalue 189 190 if base is None or base == 10: 191 manstr, expstr = ("%.19e" % value).split("e") 192 expstr = f"e{int(expstr)}" 193 expvalue = float_str_minify(manstr, lambda v: float(v + expstr), value) + expstr 194 195 if value == 0 or 1e-3 <= value <= 1e21: 196 decvalue = float_str_minify("%.24f" % value, float, value, keep_float=True) 197 decvalue = expvalue if len(expvalue) < len(decvalue) else decvalue 198 else: 199 decvalue = expvalue 200 201 if base: 202 minvalue = decvalue 203 204 if not base: 205 minvalue = hexvalue if len(hexvalue) < len(decvalue) else decvalue 206 207 minvalue = sign + minvalue 208 if parens: 209 minvalue = "(" + minvalue + ")" 210 211 return minvalue
format a luanum to a picotron string
k_char_escapes_rev =
{'\x01': '*', '\x02': '#', '\x03': '-', '\x04': '|', '\x05': '+', '\x06': '^', '\x07': 'a', '\x08': 'b', '\t': 't', '\n': 'n', '\x0b': 'v', '\x0c': 'f', '\r': 'r', '\\': '\\', '"': '"', "'": "'", '\x00': '0', '\x0e': '14', '\x0f': '15'}
k_char_escapes_rev_min =
{'\n': 'n', '\r': 'r', '\\': '\\', '"': '"', "'": "'", '\x00': '0'}
def
get_long_brackets_equals(value):
def
format_string_literal( value, use_ctrl_chars=True, use_complex_long=True, long=None, quote=None):
224def format_string_literal(value, use_ctrl_chars=True, use_complex_long=True, long=None, quote=None): 225 """format a pico8 string to a pico8 string literal""" 226 227 if long != False: 228 if "\0" not in value and "\r" not in value and (use_complex_long or "]]" not in value): 229 newline = "\n" if value.startswith("\n") else "" 230 231 eqs = get_long_brackets_equals(value) 232 strlong = f"[{eqs}[{newline}{value}]{eqs}]" 233 if long == True: 234 return strlong 235 else: 236 strlong = None 237 long = False 238 239 if long != True: 240 if quote is None: 241 quote = '"' if value.count('"') <= value.count("'") else "'" 242 243 exclude_esc = "'" if quote == '"' else '"' 244 245 char_escapes_rev = k_char_escapes_rev_min if use_ctrl_chars else k_char_escapes_rev 246 247 litparts = [] 248 for i, ch in enumerate(value): 249 if ch in char_escapes_rev and ch != exclude_esc: 250 esc = char_escapes_rev[ch] 251 if esc.isdigit() and i + 1 < len(value) and value[i + 1].isdigit(): 252 esc = esc.rjust(3, '0') 253 litparts.append("\\" + esc) 254 else: 255 litparts.append(ch) 256 257 strlit = '%s%s%s' % (quote, "".join(litparts), quote) 258 if long == False: 259 return strlit 260 261 return strlong if len(strlong) < len(strlit) else strlit
format a pico8 string to a pico8 string literal
def
need_whitespace_between(ctxt, prev, next):
263def need_whitespace_between(ctxt, prev, next): 264 if isinstance(prev, Comment) or isinstance(next, Comment): 265 return False 266 267 combined = prev.value + next.value 268 ct, ce = tokenize(Source("<output>", combined), lang=ctxt.lang) # TODO: optimize? 269 return ce or len(ct) != 2 or (ct[0].type, ct[0].value, ct[1].type, ct[1].value) != (prev.type, prev.value, next.type, next.value)
def
is_non_nested_short(node):
def
get_orig_wspace(pre, post, ctxt, allow_linebreaks, need_linebreak=False):
275def get_orig_wspace(pre, post, ctxt, allow_linebreaks, need_linebreak=False): 276 source = default(pre.source, post.source) 277 text = source.text[pre.endidx:post.idx] 278 279 if text and not text.isspace(): 280 tokens, _ = tokenize(Source("<output>", text), lang=ctxt.lang) # TODO: optimize? 281 if tokens: 282 if "\n" in text and allow_linebreaks: 283 need_linebreak = True 284 text = text[tokens[-1].endidx:] or text[:tokens[0].idx] 285 286 newlines = min(text.count("\n"), 2) 287 if newlines: 288 text = text[text.rfind("\n")+1:] 289 290 num_lspace = len(text) - len(text.lstrip(" ")) 291 num_rspace = len(text) - len(text.rstrip(" ")) 292 text = "\n" * newlines + " " * max(num_lspace, num_rspace) 293 294 if not allow_linebreaks and "\n" in text: 295 text = text[:text.index("\n")] + " " 296 if need_linebreak and "\n" not in text: 297 text += "\n" 298 299 return text
def
output_node( root, ctxt, minify=True, minify_wspace=None, minify_lines=None, exclude_comments=None):
301def output_node(root, ctxt, minify=True, minify_wspace=None, minify_lines=None, exclude_comments=None): 302 """convert a root back to a string, inserting as little whitespace as possible (under minify_wspace), 303 or using original whitespace (optionally except comments)""" 304 minify_wspace = default(minify_wspace, minify) 305 minify_lines = default(minify_lines, minify) 306 exclude_comments = default(exclude_comments, minify) 307 308 output = [] 309 prev_token_or_comment = Token.none 310 need_linebreak = False 311 short_level = 0 312 313 def wspace_output(next_token_or_comment, can_need_linebreak=True): 314 nonlocal prev_token_or_comment, need_linebreak 315 prev, next = prev_token_or_comment, next_token_or_comment 316 317 if minify_wspace: 318 # (modified tokens may require whitespace not previously required - e.g. 0b/0x) 319 if (prev.endidx < next.idx or prev.source != next.source or prev.modified or next.modified) and prev.value: 320 # TODO: can we systemtically add whitespace to imrpove compression? (failed so far) 321 322 if ((need_linebreak and can_need_linebreak) or 323 (not minify_lines and next.vline != prev.vline and not prev.value.endswith("\n"))): 324 output.append("\n") 325 need_linebreak = False 326 elif need_whitespace_between(ctxt, prev, next): 327 output.append(" ") 328 329 else: 330 allow_linebreaks = next.vline != prev.vline 331 wspace = get_orig_wspace(prev, next, ctxt, allow_linebreaks, need_linebreak and can_need_linebreak) 332 333 if not wspace and prev.value != None and need_whitespace_between(ctxt, prev, next): 334 wspace += " " 335 336 output.append(wspace) 337 if "\n" in wspace: 338 need_linebreak = False 339 340 prev_token_or_comment = next 341 342 def comment_output(comment, allow_linebreaks): 343 nonlocal prev_token_or_comment, need_linebreak 344 345 if exclude_comments: 346 if comment.hint == CommentHint.keep: 347 comment_text = comment.value.replace(comment.hintprefix + k_keep_prefix, "", 1) 348 else: 349 return 350 else: 351 comment_text = comment.value 352 353 if not allow_linebreaks and "\n" in comment_text: 354 if comment.isblock: 355 comment_text = re.sub(r"\n\s*", " ", comment_text) 356 else: 357 eqs = get_long_brackets_equals(comment_text) 358 comment_text = f"--[{eqs}[{comment_text[2:-1]}]{eqs}]" 359 360 wspace_output(comment, can_need_linebreak=False) 361 output.append(comment_text) 362 363 if need_linebreak and "\n" in comment_text: 364 need_linebreak = False 365 366 def token_output(token): 367 if token.children: 368 allow_linebreaks = prev_token_or_comment.vline != token.vline 369 370 for comment in token.children: 371 comment_output(comment, allow_linebreaks) 372 373 if token.value != None: 374 wspace_output(token) 375 output.append(token.value) 376 377 def pre_node_output(node): 378 nonlocal short_level 379 if is_non_nested_short(node): 380 short_level += 1 381 382 def post_node_output(node): 383 nonlocal short_level, need_linebreak 384 if is_non_nested_short(node): 385 short_level -= 1 386 if short_level == 0: 387 need_linebreak = True 388 389 root.traverse_nodes(tokens=token_output, pre=pre_node_output, post=post_node_output) 390 return "".join(output)
convert a root back to a string, inserting as little whitespace as possible (under minify_wspace), or using original whitespace (optionally except comments)
def
output_code(ctxt, root, minify_opts):
def
output_needs_comments(minify_opts):