-
Notifications
You must be signed in to change notification settings - Fork 5
/
ast_utils.py
513 lines (453 loc) · 16 KB
/
ast_utils.py
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
"""
ast_utils, bunch of helpers for converting input into ast.* output
"""
from ast import (
AnnAssign,
Name,
Load,
Store,
Constant,
Dict,
Module,
ClassDef,
Subscript,
Tuple,
Expr,
Call,
Attribute,
keyword,
parse,
walk,
FunctionDef,
Str,
NameConstant,
Assign,
arg,
)
from doctrans.defaults_utils import extract_default
from doctrans.pure_utils import simple_types, rpartial, PY3_8, strip_split
def param2ast(param):
"""
Converts a param to an AnnAssign
:param param: dict of shape {'name': ..., 'typ': ..., 'doc': ..., 'default': ..., 'required': ... }
:type param: ```dict```
:return: AST node (AnnAssign)
:rtype: ```AnnAssign```
"""
if param["typ"] in simple_types:
return AnnAssign(
annotation=Name(ctx=Load(), id=param["typ"]),
simple=1,
target=Name(ctx=Store(), id=param["name"]),
value=set_value(
kind=None, value=param.get("default", simple_types[param["typ"]])
),
)
elif param["typ"] == "dict" or param["typ"].startswith("*"):
return AnnAssign(
annotation=Name(ctx=Load(), id="dict"),
simple=1,
target=Name(ctx=Store(), id=param["name"]),
value=Dict(keys=[], values=param.get("default", [])),
)
else:
annotation = parse(param["typ"]).body[0].value
if param.get("default") and not determine_quoting(annotation):
value = (
parse(param["default"]).body[0].value
if "default" in param
else Name(ctx=Load(), id=None)
)
else:
value = set_value(kind=None, value=param.get("default"))
return AnnAssign(
annotation=annotation,
simple=1,
target=Name(ctx=Store(), id=param["name"]),
value=value,
)
def to_class_def(ast, class_name=None):
"""
Converts an AST to an `ast.ClassDef`
:param ast: Class AST or Module AST
:type ast: ```Union[ast.Module, ast.ClassDef]```
:param class_name: Name of `class`. If None, gives first found.
:type class_name: ```Optional[str]```
:return: ClassDef
:rtype: ```ast.ClassDef```
"""
if isinstance(ast, Module):
classes_it = filter(rpartial(isinstance, ClassDef), ast.body)
if class_name is not None:
return next(filter(lambda node: node.name == class_name, classes_it,))
classes = tuple(classes_it)
if len(classes) > 1: # We could convert every one I guess?
raise NotImplementedError()
elif len(classes) > 0:
return classes[0]
else:
raise TypeError("No ClassDef in AST")
elif isinstance(ast, ClassDef):
assert class_name is None or ast.name == class_name
return ast
else:
raise NotImplementedError(type(ast).__name__)
def param2argparse_param(param, emit_default_doc=True):
"""
Converts a param to an Expr `argparse.add_argument` call
:param param: dict of shape {'name': ..., 'typ': ..., 'doc': ..., 'default': ..., 'required': ... }
:type param: ```dict```
:param emit_default_doc: Whether help/docstring should include 'With default' text
:type emit_default_doc: ```bool``
:return: `argparse.add_argument` call—with arguments—as an AST node
:rtype: ```Expr```
"""
typ, choices, required = "str", None, True
if param["typ"] in simple_types:
typ = param["typ"]
elif param["typ"] == "dict":
typ = "loads"
required = not param["name"].endswith("kwargs")
else:
parsed_type = parse(param["typ"]).body[0]
for node in walk(parsed_type):
if isinstance(node, Tuple):
maybe_choices = tuple(
get_value(elt)
for elt in node.elts
if isinstance(elt, (Constant, Str))
)
if len(maybe_choices) == len(node.elts):
choices = maybe_choices
elif isinstance(node, Name):
if node.id == "Optional":
required = False
elif node.id in simple_types:
typ = node.id
elif node.id not in frozenset(("Union",)):
typ = "globals().__getitem__"
doc, _default = extract_default(param["doc"], emit_default_doc=emit_default_doc)
default = param.get("default", _default)
return Expr(
value=Call(
args=[set_value(kind=None, value="--{param[name]}".format(param=param))],
func=Attribute(
attr="add_argument",
ctx=Load(),
value=Name(ctx=Load(), id="argument_parser"),
),
keywords=list(
filter(
None,
(
keyword(
arg="type",
value=Attribute(
attr="__getitem__",
ctx=Load(),
value=Call(
args=[],
func=Name(ctx=Load(), id="globals"),
keywords=[],
),
)
if typ == "globals().__getitem__"
else Name(ctx=Load(), id=typ),
),
choices
if choices is None
else keyword(
arg="choices",
value=Tuple(
ctx=Load(),
elts=[
set_value(kind=None, value=choice)
for choice in choices
],
),
),
keyword(arg="help", value=set_value(kind=None, value=doc)),
keyword(
arg="required",
value=(
Constant(kind=None, value=True)
if PY3_8
else NameConstant(value=True)
),
)
if required
else None,
default
if default is None
else keyword(
arg="default", value=set_value(kind=None, value=default)
),
),
)
),
)
)
def determine_quoting(node):
"""
Determine whether the input needs to be quoted
:param node: AST node
:type node: ```Union[Subscript, Tuple, Name, Attribute]```
:returns: True if input needs quoting
:rtype: ```bool```
"""
if isinstance(node, Subscript) and isinstance(node.value, Name):
if node.value.id == "Optional":
return determine_quoting(get_value(node.slice))
elif node.value.id in frozenset(("Union", "Literal")):
if all(isinstance(elt, Subscript) for elt in get_value(node.slice).elts):
return any(determine_quoting(elt) for elt in get_value(node.slice).elts)
return any(
(
isinstance(elt, Constant)
and elt.kind is None
and isinstance(elt.value, str)
or (isinstance(elt, Str) or elt.id == "str")
)
for elt in get_value(node.slice).elts
)
elif node.value.id == "Tuple":
return any(determine_quoting(elt) for elt in get_value(node.slice).elts)
else:
raise NotImplementedError(node.value.id)
elif isinstance(node, Name):
return node.id == "str"
elif isinstance(node, Attribute):
return determine_quoting(node.value)
else:
raise NotImplementedError(type(node).__name__)
def get_function_type(function):
"""
Get the type of the function
:param function: AST function node
:type function: ```FunctionDef```
:returns: None is a loose function (def f()`), others self-explanatory
:rtype: ```Optional[Literal['self', 'cls']]```
"""
assert isinstance(function, FunctionDef), "{typ} != FunctionDef".format(
typ=type(function).__name__
)
if function.args is None or len(function.args.args) == 0:
return None
elif function.args.args[0].arg in frozenset(("self", "cls")):
return function.args.args[0].arg
return None
def get_value(node):
"""
Get the value from a Constant or a Str… or anything with a `.value`
:param node: AST node
:type node: ```Union[Constant, Str]```
:returns: Probably a string, but could be any constant value
:rtype: ```Optional[Union[str, int, float, bool]]```
"""
if isinstance(node, Str):
return node.s
elif isinstance(node, Constant) or hasattr(node, "value"):
return node.value
elif isinstance(node, (Tuple, Name)): # It used to be Index in Python < 3.9
return node
else:
raise NotImplementedError(type(node).__name__)
def set_value(value, kind=None):
"""
Creates a Constant or a Str depending on Python version in use
:param value: AST node
:type value: ```Any```
:param kind: AST node
:type kind: ```Optional[Any]```
:returns: Probably a string, but could be any constant value
:rtype: ```Union[Constant, Str, NameConstant]```
"""
if not PY3_8:
if isinstance(value, str):
return Str(s=value)
elif value is None:
return NameConstant(value=value)
return Constant(kind=kind, value=value)
def is_argparse_add_argument(node):
"""
Checks if AST node is a call to `argument_parser.add_argument`
:param node: AST node
:type node: ```AST```
:returns: Whether the input is the call to `argument_parser.add_argument`
:rtype: ```bool```
"""
return (
isinstance(node, Expr)
and isinstance(node.value, Call)
and isinstance(node.value.func, Attribute)
and isinstance(node.value.func.value, Name)
and node.value.func.value.id == "argument_parser"
and node.value.func.attr == "add_argument"
)
def is_argparse_description(node):
"""
Checks if AST node is `argument_parser.description`
:param node: AST node
:type node: ```AST```
:returns: Whether the input is the call to `argument_parser.description`
:rtype: ```bool```
"""
return (
isinstance(node, Assign)
and len(node.targets) == 1
and isinstance(node.targets[0], Attribute)
and node.targets[0].attr == "description"
and isinstance(node.targets[0].value, Name)
and node.targets[0].value.id == "argument_parser"
and isinstance(node.value, (Constant, Str))
)
def find_in_ast(query, node):
"""
Find and return the param from within the value
:param query: Location within AST of property.
Can be top level like `a` for `a=5` or E.g., `A.F` for `class A: F`, `f.g` for `def f(g): pass`
:type query: ```str```
:param node: AST node (must have a `body`)
:type node: ```AST```
:returns: AST node that was found, or None if nothing was found
:rtype: ```Optional[AST]```
"""
query_l = list(strip_split(query, "."))
cursor = node.body
while len(query_l):
search = query_l.pop(0)
if len(query_l) == 0 and hasattr(node, "name") and node.name == search:
return node
for node in cursor:
if isinstance(node, FunctionDef):
if len(query_l):
search = query_l.pop(0)
_cursor = next(
filter(
lambda idx_arg: idx_arg[1].arg == search,
enumerate(node.args.args),
),
None,
)
if _cursor is not None:
if len(node.args.defaults) > _cursor[0]:
setattr(_cursor[1], "default", node.args.defaults[_cursor[0]])
cursor = _cursor[1]
# print_ast(cursor)
if len(query_l) == 0:
return cursor
elif (
isinstance(node, AnnAssign)
and isinstance(node.target, Name)
and node.target.id == search
):
return node
elif hasattr(node, "name") and node.name == search:
cursor = node.body
break
return None
# def replace_in_ast(query, node, replacement_node):
# """
# Find and return the param from within the value
#
# :param query: Location within AST of property.
# Can be top level like `a` for `a=5` or E.g., `A.F` for `class A: F`, `f.g` for `def f(g): pass`
# :type query: ```str```
#
# :param node: AST node (must have a `body`)
# :type node: ```AST```
#
# :param replacement_node: Replacement AST node
# :type replacement_node: ```AST```
#
# :returns: AST node that was found, or None if nothing was found
# :rtype: ```Optional[AST]```
# """
# return RewriteAtQuery(query).visit(node)
#
#
# class RewriteAtQuery(NodeTransformer):
# def __init__(self, query):
# self.i = 0
# self.query = tuple(strip_split(query, "."))
# self.max_i = len(self.query)
# self.found = [[]]
#
# def visit_Module(self, node: Module):
# self.found[self.i].append(node.name)
# return node
#
# def visit_ClassDef(self, node: ClassDef):
# self.found[self.i].append(node.name)
# return node
#
# def visit_FunctionDef(self, node: FunctionDef):
# self.found[self.i].append(node.name)
# return node
#
# def visit_arg(self, node: arg):
# self.found[self.i].append(node.name)
# pp(self.found)
# return node
#
# def visit_arguments(self, node: arguments):
# self.found[self.i].append(node.name)
# pp(self.found)
# return node
#
# '''
# def generic_visit(self, node):
# print(self.i, 'found node:', node, ';')
# if self.i < self.max_i:
# self.i += 1
# if isinstance(node, FunctionDef):
# _cursor = next(
# filter(
# lambda idx_arg: idx_arg[1].arg == search,
# enumerate(node.args.args),
# ),
# None,
# )
# if _cursor is not None:
# if len(node.args.defaults) > _cursor[0]:
# setattr(_cursor[1], "default", node.args.defaults[_cursor[0]])
# cursor = _cursor[1]
# # print_ast(cursor)
# if len(query_l) == 0:
# return cursor
# if hasattr(node, 'body'):
# for _node in node.body:
# self.generic_visit(_node)
# '''
def emit_ann_assign(node):
"""
Produce an `AnnAssign` from the input
:param node: AST node
:type node: ```AST```
:returns: Something which parses to the form of `a=5`
:rtype: ```AnnAssign```
"""
if isinstance(node, AnnAssign):
return node
elif isinstance(node, arg):
return AnnAssign(
annotation=node.annotation,
simple=1,
target=Name(ctx=Store(), id=node.arg),
value=node.default if hasattr(node, "default") else None,
)
else:
raise NotImplementedError(type(node).__name__)
__all__ = [
"param2ast",
"to_class_def",
"param2argparse_param",
"determine_quoting",
"find_in_ast",
"get_function_type",
"emit_ann_assign",
"get_value",
"set_value",
"is_argparse_add_argument",
"is_argparse_description",
]