Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/src/output/utils.py
1398 views
1
# vim:fileencoding=utf-8
2
# License: BSD Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
3
from __python__ import hash_literals
4
5
from ast_types import AST_BlockStatement, is_node_type
6
7
8
def best_of(a):
9
best = a[0]
10
len_ = best.length
11
for i in range(1, a.length):
12
if a[i].length < len_:
13
best = a[i]
14
len_ = best.length
15
return best
16
17
18
def make_num(num):
19
str_ = num.toString(10)
20
a = [str_.replace(RegExp(r"^0\."), ".").replace("e+", "e")]
21
m = None
22
23
if Math.floor(num) is num:
24
if num >= 0:
25
a.push(
26
"0x" + num.toString(16).toLowerCase(), # probably pointless
27
"0" + num.toString(8))
28
else:
29
a.push(
30
"-0x" +
31
(-num).toString(16).toLowerCase(), # probably pointless
32
"-0" + (-num).toString(8))
33
34
m = RegExp(r"^(.*?)(0+)$").exec(num)
35
if m:
36
a.push(m[1] + "e" + m[2].length)
37
38
else:
39
m = RegExp(r"^0?\.(0+)(.*)$").exec(num)
40
if m:
41
a.push(m[2] + "e-" + (m[1].length + m[2].length),
42
str_.substr(str_.indexOf(".")))
43
44
return best_of(a)
45
46
47
def make_block(stmt, output):
48
if is_node_type(stmt, AST_BlockStatement):
49
stmt.print(output)
50
return
51
52
def print_statement():
53
output.indent()
54
stmt.print(output)
55
output.newline()
56
57
output.with_block(print_statement)
58
59
60
def create_doctring(docstrings):
61
ans = []
62
for ds in docstrings:
63
ds = str.rstrip(ds.value)
64
lines = []
65
min_leading_whitespace = ''
66
for line in ds.split(RegExp(r"$", "gm")):
67
r = RegExp(r"^\s+").exec(line)
68
leading_whitespace = ''
69
if r:
70
leading_whitespace = r[0].replace(RegExp(r"[\n\r]", "g"),
71
'') if r else ''
72
line = line[r[0].length:]
73
if not str.strip(line):
74
lines.push(["", ""])
75
else:
76
leading_whitespace = leading_whitespace.replace(
77
RegExp(r"\t", "g"), ' ')
78
if leading_whitespace and (not min_leading_whitespace
79
or leading_whitespace.length <
80
min_leading_whitespace.length):
81
min_leading_whitespace = leading_whitespace
82
lines.push([leading_whitespace, line])
83
for lw, l in lines:
84
if min_leading_whitespace:
85
lw = lw[min_leading_whitespace.length:]
86
ans.push(lw + l)
87
ans.push('')
88
return str.rstrip(ans.join('\n'))
89
90