Path: blob/main/python/pylang/src/output/utils.py
1398 views
# vim:fileencoding=utf-81# License: BSD Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>2from __python__ import hash_literals34from ast_types import AST_BlockStatement, is_node_type567def best_of(a):8best = a[0]9len_ = best.length10for i in range(1, a.length):11if a[i].length < len_:12best = a[i]13len_ = best.length14return best151617def make_num(num):18str_ = num.toString(10)19a = [str_.replace(RegExp(r"^0\."), ".").replace("e+", "e")]20m = None2122if Math.floor(num) is num:23if num >= 0:24a.push(25"0x" + num.toString(16).toLowerCase(), # probably pointless26"0" + num.toString(8))27else:28a.push(29"-0x" +30(-num).toString(16).toLowerCase(), # probably pointless31"-0" + (-num).toString(8))3233m = RegExp(r"^(.*?)(0+)$").exec(num)34if m:35a.push(m[1] + "e" + m[2].length)3637else:38m = RegExp(r"^0?\.(0+)(.*)$").exec(num)39if m:40a.push(m[2] + "e-" + (m[1].length + m[2].length),41str_.substr(str_.indexOf(".")))4243return best_of(a)444546def make_block(stmt, output):47if is_node_type(stmt, AST_BlockStatement):48stmt.print(output)49return5051def print_statement():52output.indent()53stmt.print(output)54output.newline()5556output.with_block(print_statement)575859def create_doctring(docstrings):60ans = []61for ds in docstrings:62ds = str.rstrip(ds.value)63lines = []64min_leading_whitespace = ''65for line in ds.split(RegExp(r"$", "gm")):66r = RegExp(r"^\s+").exec(line)67leading_whitespace = ''68if r:69leading_whitespace = r[0].replace(RegExp(r"[\n\r]", "g"),70'') if r else ''71line = line[r[0].length:]72if not str.strip(line):73lines.push(["", ""])74else:75leading_whitespace = leading_whitespace.replace(76RegExp(r"\t", "g"), ' ')77if leading_whitespace and (not min_leading_whitespace78or leading_whitespace.length <79min_leading_whitespace.length):80min_leading_whitespace = leading_whitespace81lines.push([leading_whitespace, line])82for lw, l in lines:83if min_leading_whitespace:84lw = lw[min_leading_whitespace.length:]85ans.push(lw + l)86ans.push('')87return str.rstrip(ans.join('\n'))888990