Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/src/string_interpolation.py
1396 views
1
from __python__ import hash_literals # type: ignore
2
3
4
def quoted_string(x):
5
return '"' + x.replace(RegExp('\\\\', 'g'), '\\\\').replace(
6
RegExp('"', 'g'), r'\"').replace(RegExp('\n', 'g'), '\\n') + '"'
7
8
9
def render_markup(markup):
10
pos, key = 0, ''
11
while pos < markup.length:
12
ch = markup[pos]
13
if ch is '!' or ch is ':':
14
break
15
key += ch
16
pos += 1
17
fmtspec = markup[pos:]
18
prefix = ''
19
if key.endsWith('='):
20
prefix = key
21
key = key[:-1]
22
return 'ρσ_str.format("' + prefix + '{' + fmtspec + '}", ' + key + ')'
23
24
25
def interpolate(template, raise_error):
26
pos = in_brace = 0
27
markup = ''
28
ans = [""]
29
while pos < template.length:
30
ch = template[pos]
31
if in_brace:
32
if ch is '{':
33
in_brace += 1
34
markup += '{'
35
elif ch is '}':
36
in_brace -= 1
37
if in_brace > 0:
38
markup += '}'
39
else:
40
ans.push(r'%js [markup]')
41
ans.push('')
42
else:
43
markup += ch
44
else:
45
if ch is '{':
46
if template[pos + 1] is '{':
47
pos += 1
48
ans[-1] += '{'
49
else:
50
in_brace = 1
51
markup = ''
52
elif ch is '}':
53
if template[pos + 1] is '}':
54
pos += 1
55
ans[-1] += '}'
56
else:
57
raise_error("f-string: single '}' is not allowed")
58
else:
59
ans[-1] += ch
60
61
pos += 1
62
63
if in_brace:
64
raise_error("expected '}' before end of string")
65
66
if ans[-1] is '+':
67
ans[-1] = ''
68
for i in range(len(ans)):
69
if jstype(ans[i]) is 'string':
70
ans[i] = quoted_string(ans[i])
71
else:
72
ans[i] = '+' + render_markup.apply(this, ans[i]) + '+'
73
return ans.join('')
74
75