Path: blob/main/python/pylang/src/string_interpolation.py
1396 views
from __python__ import hash_literals # type: ignore123def quoted_string(x):4return '"' + x.replace(RegExp('\\\\', 'g'), '\\\\').replace(5RegExp('"', 'g'), r'\"').replace(RegExp('\n', 'g'), '\\n') + '"'678def render_markup(markup):9pos, key = 0, ''10while pos < markup.length:11ch = markup[pos]12if ch is '!' or ch is ':':13break14key += ch15pos += 116fmtspec = markup[pos:]17prefix = ''18if key.endsWith('='):19prefix = key20key = key[:-1]21return 'ρσ_str.format("' + prefix + '{' + fmtspec + '}", ' + key + ')'222324def interpolate(template, raise_error):25pos = in_brace = 026markup = ''27ans = [""]28while pos < template.length:29ch = template[pos]30if in_brace:31if ch is '{':32in_brace += 133markup += '{'34elif ch is '}':35in_brace -= 136if in_brace > 0:37markup += '}'38else:39ans.push(r'%js [markup]')40ans.push('')41else:42markup += ch43else:44if ch is '{':45if template[pos + 1] is '{':46pos += 147ans[-1] += '{'48else:49in_brace = 150markup = ''51elif ch is '}':52if template[pos + 1] is '}':53pos += 154ans[-1] += '}'55else:56raise_error("f-string: single '}' is not allowed")57else:58ans[-1] += ch5960pos += 16162if in_brace:63raise_error("expected '}' before end of string")6465if ans[-1] is '+':66ans[-1] = ''67for i in range(len(ans)):68if jstype(ans[i]) is 'string':69ans[i] = quoted_string(ans[i])70else:71ans[i] = '+' + render_markup.apply(this, ans[i]) + '+'72return ans.join('')737475