forked from dflook/python-minifier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathf_string.py
More file actions
426 lines (316 loc) · 12.9 KB
/
f_string.py
File metadata and controls
426 lines (316 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
"""
FString unparsing
This whole module feels like a hack.
Mostly because FStrings feel like a hack.
"""
import ast
import copy
import re
from python_minifier import UnstableMinification
from python_minifier.ast_compare import CompareError
from python_minifier.ast_compare import compare_ast
from python_minifier.expression_printer import ExpressionPrinter
from python_minifier.ministring import MiniString
from python_minifier.token_printer import TokenTypes
from python_minifier.util import is_ast_node
class FString(object):
"""
An F-string in the expression part of another f-string
"""
def __init__(self, node, allowed_quotes):
assert isinstance(node, ast.JoinedStr)
self.node = node
self.allowed_quotes = allowed_quotes
def is_correct_ast(self, code):
try:
c = ast.parse(code, 'FString candidate', mode='eval')
compare_ast(self.node, c.body)
return True
except Exception as e:
return False
def complete_debug_specifier(self, partial_specifier_candidates, value_node):
assert isinstance(value_node, ast.FormattedValue)
conversion = ''
if value_node.conversion == 115:
conversion = '!s'
elif value_node.conversion == 114 and value_node.format_spec is not None:
# This is the default for debug specifiers, unless there's a format_spec
conversion = '!r'
elif value_node.conversion == 97:
conversion = '!a'
conversion_candidates = [x + conversion for x in partial_specifier_candidates]
if value_node.format_spec is not None:
conversion_candidates = [c + ':' + fs for c in conversion_candidates for fs in FormatSpec(value_node.format_spec, self.allowed_quotes).candidates()]
return [x + '}' for x in conversion_candidates]
def candidates(self):
actual_candidates = []
for quote in self.allowed_quotes:
candidates = ['']
debug_specifier_candidates = []
nested_allowed = copy.copy(self.allowed_quotes)
nested_allowed.remove(quote)
for v in self.node.values:
if is_ast_node(v, ast.Str):
# Could this be used as a debug specifier?
if len(candidates) < 10:
debug_specifier = re.match(r'.*=\s*$', v.s)
if debug_specifier:
# Maybe!
try:
debug_specifier_candidates = [x + '{' + v.s for x in candidates]
except Exception as e:
continue
try:
candidates = [x + self.str_for(v.s, quote) for x in candidates]
except Exception as e:
continue
elif isinstance(v, ast.FormattedValue):
try:
completed = self.complete_debug_specifier(debug_specifier_candidates, v)
candidates = [
x + y for x in candidates for y in FormattedValue(v, nested_allowed).get_candidates()
] + completed
debug_specifier_candidates = []
except Exception as e:
continue
else:
raise RuntimeError('Unexpected JoinedStr value')
actual_candidates += ['f' + quote + x + quote for x in candidates]
actual_candidates = filter(self.is_correct_ast, actual_candidates)
return actual_candidates
def str_for(self, s, quote):
return s.replace('{', '{{').replace('}', '}}')
class OuterFString(FString):
"""
The outermost f-string
Whereas the FString object assumes backslashes are disallowed, this
OuterFString is free to use backslashes in the Str parts
"""
def __init__(self, node):
assert isinstance(node, ast.JoinedStr)
super(OuterFString, self).__init__(node, ['"', "'", '"""', "'''"])
def __str__(self):
if len(self.node.values) == 0:
return 'f' + min(self.allowed_quotes, key=len) * 2
candidates = list(self.candidates())
for candidate in candidates:
try:
minified_f_string = ast.parse(candidate, 'python_minifier.f_string output', mode='eval').body
except SyntaxError as syntax_error:
raise UnstableMinification(syntax_error, '', candidate)
try:
compare_ast(self.node, minified_f_string)
except CompareError as compare_error:
raise UnstableMinification(compare_error, '', candidate)
if not candidates:
raise ValueError('Unable to create representation for f-string')
return min(candidates, key=len)
def str_for(self, s, quote):
mini_s = str(MiniString(s, quote)).replace('{', '{{').replace('}', '}}')
if mini_s == '':
return '\\\n'
return mini_s
class FormattedValue(ExpressionPrinter):
"""
An F-String Expression Part
"""
def __init__(self, node, allowed_quotes):
super(FormattedValue, self).__init__()
assert isinstance(node, ast.FormattedValue)
self.node = node
self.allowed_quotes = allowed_quotes
self.candidates = ['']
def get_candidates(self):
self.printer.delimiter('{')
if self.is_curly(self.node.value):
self.printer.delimiter(' ')
self._expression(self.node.value)
if self.node.conversion == 115:
self.printer.append('!s', TokenTypes.Delimiter)
elif self.node.conversion == 114:
self.printer.append('!r', TokenTypes.Delimiter)
elif self.node.conversion == 97:
self.printer.append('!a', TokenTypes.Delimiter)
if self.node.format_spec is not None:
self.printer.delimiter(':')
self._append(FormatSpec(self.node.format_spec, self.allowed_quotes).candidates())
self.printer.delimiter('}')
self._finalize()
return self.candidates
def is_curly(self, node):
if isinstance(node, (ast.SetComp, ast.DictComp, ast.Set, ast.Dict)):
return True
if isinstance(node, (ast.Expr, ast.Attribute, ast.Subscript)):
return self.is_curly(node.value)
if isinstance(node, (ast.Compare, ast.BinOp)):
return self.is_curly(node.left)
if isinstance(node, ast.Call):
return self.is_curly(node.func)
if isinstance(node, ast.BoolOp):
return self.is_curly(node.values[0])
if isinstance(node, ast.IfExp):
return self.is_curly(node.body)
return False
def visit_Str(self, node):
self.printer.append(str(Str(node.s, self.allowed_quotes)), TokenTypes.NonNumberLiteral)
def visit_Bytes(self, node):
self.printer.append(str(Bytes(node.s, self.allowed_quotes)), TokenTypes.NonNumberLiteral)
def visit_JoinedStr(self, node):
assert isinstance(node, ast.JoinedStr)
if self.printer.previous_token in [TokenTypes.Identifier, TokenTypes.Keyword, TokenTypes.SoftKeyword]:
self.printer.delimiter(' ')
self._append(FString(node, allowed_quotes=self.allowed_quotes).candidates())
def _finalize(self):
self.candidates = [x + str(self.printer) for x in self.candidates]
self.printer._code = ''
def _append(self, candidates):
self._finalize()
self.candidates = [x + y for x in self.candidates for y in candidates]
class Str(object):
"""
A Str node inside an f-string expression
May use any of the allowed quotes, no backslashes!
"""
def __init__(self, s, allowed_quotes):
self._s = s
self.allowed_quotes = allowed_quotes
self.current_quote = None
def _can_quote(self, c):
if self.current_quote is None:
return False
if (c == '\n' or c == '\r') and len(self.current_quote) == 1:
return False
if c == self.current_quote[0]:
return False
return True
def _get_quote(self, c):
for quote in self.allowed_quotes:
if c == '\n' or c == '\r':
if len(quote) == 3:
return quote
elif c != quote:
return quote
raise ValueError('Couldn\'t find a quote')
def _literals(self):
l = ''
for c in self._s:
if not self._can_quote(c):
if l:
l += self.current_quote
yield l
l = ''
self.current_quote = self._get_quote(c)
if l == '':
l += self.current_quote
l += c
if l:
l += self.current_quote
yield l
def __str__(self):
if self._s == '':
return str(min(self.allowed_quotes, key=len)) * 2
if '\0' in self._s or '\\' in self._s:
raise ValueError('Impossible to represent a %r character in f-string expression part')
if '\n' in self._s or '\r' in self._s:
if '"""' not in self.allowed_quotes and "'''" not in self.allowed_quotes:
raise ValueError(
'Impossible to represent newline character in f-string expression part without a long quote'
)
candidates = []
for start_quote in self.allowed_quotes:
self.current_quote = start_quote
s = ''
for l in self._literals():
if s and s[-1] == l[0]:
s += ' '
s += l
if eval(s) == self._s:
candidates.append(s)
if candidates:
return min(candidates, key=len)
else:
raise ValueError('Unable to string')
class FormatSpec(object):
"""
A FormattedValue format spec
The AST looks like another f-string. This time there are no quotes.
"""
def __init__(self, node, allowed_quotes):
assert isinstance(node, ast.JoinedStr)
self.node = node
self.allowed_quotes = allowed_quotes
def candidates(self):
candidates = ['']
for v in self.node.values:
if is_ast_node(v, ast.Str):
candidates = [x + self.str_for(v.s) for x in candidates]
elif isinstance(v, ast.FormattedValue):
candidates = [
x + y for x in candidates for y in FormattedValue(v, self.allowed_quotes).get_candidates()
]
else:
raise RuntimeError('Unexpected JoinedStr value')
return candidates
def str_for(self, s):
return s.replace('{', '{{').replace('}', '}}')
class Bytes(object):
"""
A Bytes node inside an f-string expression
May use any of the allowed quotes, no backslashes!
"""
def __init__(self, b, allowed_quotes):
self._b = b
self.allowed_quotes = allowed_quotes
self.current_quote = None
def _can_quote(self, c):
if self.current_quote is None:
return False
if (c == ord(b'\n') or c == ord(b'\r')) and len(self.current_quote) == 1:
return False
if chr(c) == self.current_quote[0]:
return False
return True
def _get_quote(self, c):
for quote in self.allowed_quotes:
if c == ord(b'\n') or c == ord(b'\r'):
if len(quote) == 3:
return quote
elif chr(c) != quote:
return quote
raise ValueError('Couldn\'t find a quote')
def _literals(self):
l = ''
for b in self._b:
if not self._can_quote(b):
if l:
l += self.current_quote
yield l
l = ''
self.current_quote = self._get_quote(b)
if l == '':
l = 'b' + self.current_quote
l += chr(b)
if l:
l += self.current_quote
yield l
def __str__(self):
if self._b == b'':
return 'b' + str(min(self.allowed_quotes, key=len)) * 2
if b'\0' in self._b or b'\\' in self._b:
raise ValueError('Impossible to represent a %r character in f-string expression part')
if b'\n' in self._b or b'\r' in self._b:
if '"""' not in self.allowed_quotes and "'''" not in self.allowed_quotes:
raise ValueError(
'Impossible to represent newline character in f-string expression part without a long quote'
)
candidates = []
for start_quote in self.allowed_quotes:
self.current_quote = start_quote
s = ''
for l in self._literals():
if s and s[-1] == l[0]:
s += ' '
s += l
assert eval(s) == self._b
candidates.append(s)
return min(candidates, key=len)