-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactions.py
More file actions
624 lines (478 loc) · 20.3 KB
/
actions.py
File metadata and controls
624 lines (478 loc) · 20.3 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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
import keyword
import ast
from copy import deepcopy
import core_logic
import make_nodes
import operations
import validators
# TODO: Remove the current attr (Go back one)
# TODO: Have a blank line on top of for and while
# TODO: Actions that replaces the parent with the selected node
# (If the types match), or maybe yank, up, put does the job.
# TODO: A way to paste from stack overflow
# TODO: A way of inserting None
# TODO: Default values for function parameters
# TODO: Have a lambda use the selected expression as it's initial body
# TODO: A way of inserting \n
def is_renameable(node):
return ( hasattr(node, "id")
or hasattr(node, "name")
# Checking for 'asname', for aliases isn't needed
# because they already have a name attribute
or hasattr(node, "module")
or hasattr(node, "attr")
or hasattr(node, "arg")
or isinstance(node, ast.Global)
or isinstance(node, ast.Nonlocal)
or has_string_value(node)
)
def has_string_value(node):
value = getattr(node, "value", False)
if not value:
return False
return type(value) == str
def rename(new_name, node, maybe_index):
if hasattr(node, "id"):
node.id = new_name
# Only rename by asname if it's not empty
elif hasattr(node, "asname") and node.asname is not None:
node.asname = new_name
elif hasattr(node, "name"):
node.name = new_name
elif hasattr(node, "module"):
node.module = new_name
elif hasattr(node, "attr"):
node.attr = new_name
elif hasattr(node, "arg"):
node.arg = new_name
elif has_string_value(node):
node.value = new_name
# Must come after, otherwise imports, that have both names and a string value
# will be renamed by index when they don't need to
elif hasattr(node, "names"):
node.names[maybe_index] = new_name
else:
raise ValueError(
f"{node.__class__.__name__} node isn't renameable"
)
return node
def is_identifier(ident: str) -> bool:
"""Determines if string is valid Python identifier."""
if not ident.isidentifier():
return False
if keyword.iskeyword(ident):
return False
return True
def user_input_rename(node, get_user_input):
# TODO: Enforce naming conventions
# (like classes should start with a capital letter)
if not is_renameable(node):
print("Can't rename this type of node")
return []
new_name = get_user_input("Rename to: ")
if not is_identifier(new_name):
print("Invalid name")
return []
# global and nonlocal keywords are annoying:
# they have a list of identifiers instead of list of nodes,
# so we can't select them with the cursor.
# Instead, we ask for the index explicitly
if type(node) == ast.Global or type(node) == ast.Nonlocal:
try:
index = int(get_user_input("Rename at index: "))
except ValueError:
print("Bad index")
return []
if index >= len(node.names):
print("Bad index")
return []
rename(new_name, node, index)
else:
rename(new_name, node, None)
# The [] means not to move the cursor
return []
# TODO: Skip moving through Expr nodes for a better moving experience: No repeated
# No repeated down presses without a visual change
def move_cursor_down(node, _):
children = core_logic.list_children(node)
# Ensure the selected node has children
if children == []:
return []
print(children[0].__class__.__name__)
# Move the cursor down
return [0]
def move_cursor_left(cursor_trail, ast, _):
if cursor_trail == []:
return
# decrement in one the index of the last child
# effectively moving back to the previous sibling
cursor_trail.append(cursor_trail.pop() - 1)
current_node = core_logic.get_node_at_cursor(cursor_trail, ast)
print(current_node.__class__.__name__)
# TODO: Also skip the Expr nodes
def move_cursor_up(cursor_trail, ast, _):
if cursor_trail == []:
return
cursor_trail.pop()
current_node = core_logic.get_node_at_cursor(cursor_trail, ast)
print(current_node.__class__.__name__)
def move_cursor_right(cursor_trail, ast, _):
if cursor_trail == []:
return
# Increment in one the index of the last child
# Effectively moving to the next sibling
cursor_trail.append(cursor_trail.pop() + 1)
current_node = core_logic.get_node_at_cursor(cursor_trail, ast)
print(current_node.__class__.__name__)
# TODO: Move to the inserted node (hopefully it's the first child)
def insert(cursor_trail, tree, _):
"""Adds an element inside the node.
It's useful to unempty an empty container (like a list)
before populating it using "append" """
selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
if hasattr(selected_node, "bases"):
# Add a new base class to the class
selected_node.bases.append(ast.Name(id="BaseClass", ctx=ast.Load()))
# It doesn't make sense to insert into a body because they can't ever be empty
# Except for the Module node
elif isinstance(selected_node, ast.Module):
selected_node.body.append(make_nodes.make_pass())
elif isinstance(selected_node, ast.arguments):
arg = make_nodes.make_arg()
# Make the name unique
arg.arg = core_logic.get_unique_name(arg.arg, selected_node)
selected_node.args.append(arg)
return [0]
# Call has the args list as a list of expressions
# That's different from function definitions, where it's a list of arguments
# The grammar is really confusing when it comes to those "args"
elif isinstance(selected_node, ast.Call):
arg = make_nodes.make_expression()
selected_node.args.append(arg)
return [0]
elif hasattr(selected_node, "elts"):
ctx = core_logic.get_immediate_context(cursor_trail, tree)
selected_node.elts.append(make_nodes.make_expression(ctx=ctx))
return [-1]
else:
print("Can't insert inside this node")
return []
# TODO: Multiple exceptions for the try block
def append(cursor_trail, tree, _):
selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
# Don't touch the module
if isinstance(selected_node, ast.Module):
return
parent = core_logic.get_node_at_cursor(cursor_trail[:-1], tree)
fieldname, index = core_logic.get_field_name_for_child(parent, selected_node)
if index is not None:
children = getattr(parent, fieldname)
children.insert(index + 1, deepcopy(selected_node))
# A dictionary should always have the same amount of keys and values
# So let's be careful and keep them synced
if type(parent) == ast.Dict:
if fieldname == "keys":
parent.values.insert(index + 1, deepcopy(parent.values[index]))
if fieldname == "values":
parent.keys.insert(index + 1, deepcopy(parent.keys[index]))
# Comparisons are similar:
# They should have the same number of comparators and comparands
if type(parent) == ast.Compare:
parent.ops.insert(index + 1, deepcopy(parent.ops[index]))
# In the case we are within function arguments
# two of them with the same name can break stuff.
# So let's give the new one a different name
if type(selected_node) == ast.arg:
children[index + 1].arg = core_logic.get_unique_name(selected_node.arg, parent)
return
# If we haven't returned yet, we can't append to it
print("Can't append to this type of node")
# TODO: Recalculate the index after deleting
# to avoid the weird cursor jumps because of the wrapping around
def delete(cursor_trail, tree, _):
# Don't touch the module
if cursor_trail == []:
return
selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
parent = core_logic.get_node_at_cursor(cursor_trail[:-1], tree)
fieldname, index = core_logic.get_field_name_for_child(parent, selected_node)
if index is not None:
children_list = getattr(parent, fieldname)
# A try block needs to have at least one of those not empty
if fieldname == "handlers" or fieldname == "finalbody":
if len(parent.handlers) + len(parent.finalbody) == 1:
print("A Try block needs handlers or a finally")
return
if isinstance(parent, ast.Dict):
# If it's a dictionary, keep the key value pairs synced
# by deleting the correspondig key/value
if fieldname == "keys":
parent.values.pop(index)
if fieldname == "values":
parent.keys.pop(index)
if isinstance(parent, ast.BoolOp):
if len(children_list) < 3:
print("A boolean operation must have at least 2 operands")
return
# These kinds of nodes can't be empty
elif ( fieldname == "names"
or fieldname == "body"
or fieldname == "items"
or fieldname == "targets"):
if len(children_list) < 2:
print("This can't be empty")
return
children_list.pop(index)
# If there are no more children, move up
if len(children_list) == 0:
cursor_trail.pop()
else:
# setattr(parent, fieldname, None)
pass
def insert_annotation(cursor_trail, tree, _):
selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
default_annotation = ast.Name(id="annotation", ctx=ast.Load())
if hasattr(selected_node, "returns"):
# Toggle the return annotation
if selected_node.returns is None:
selected_node.returns = default_annotation
else:
selected_node.returns = None
# The assignments must come befor the generic annotation case
# Because otherwise the annotated assignment's annotation will be
# erroneously set to None
elif isinstance(selected_node, ast.Assign):
# Make it into an annotated assign
annotated_assign = ast.AnnAssign(
target=selected_node.targets[0],
annotation=default_annotation,
value=selected_node.value,
# TODO: What does simple mean?
simple=1
)
core_logic.set_node_at_cursor(cursor_trail, tree, annotated_assign)
elif isinstance(selected_node, ast.AnnAssign):
# Make it into a regular assign
value = selected_node.value
assign = ast.Assign(
targets=[selected_node.target],
value = value if value is not None else make_node.make_expression()
)
core_logic.set_node_at_cursor(cursor_trail, tree, assign)
elif hasattr(selected_node, "annotation"):
# Toggle the annotation
if selected_node.annotation is None:
selected_node.annotation = default_annotation
else:
selected_node.annotation = None
else:
print("This node can't have type annotations")
return []
def insert_int(cursor_trail, tree, get_input):
selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
if not validators.is_simple_expression(cursor_trail, tree):
print("Can't have an int here")
return
try:
n = int(get_input("int: "))
except ValueError:
print("Invalid int")
return
constant = ast.Constant(value=n, kind=None)
core_logic.set_node_at_cursor(cursor_trail, tree, constant)
def extend(cursor_trail, tree, _):
""" Bulks up the selected node.
Specifically how depends on the node"""
# If -> add else
# For (Async too) -> add else
# While -> add else
# Try -> add else. (TODO: Do something about the finnaly block too)
# Function (Async too) -> add decorator
# Class -> add decorator
# Assign -> Augmented Assign
# Raise -> Add the cause (as in "raise foo from bar")
# Assert -> Add the message
# Import -> ImportFrom
# alias -> add an asname (Which is kind of the whole point of the alias node)
# comprehension -> add an if clause
# yield -> add the thing to yield
# Name -> starred
# Index -> Slice
selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
# The if expression has an orelse field that is an expression, not a list of statements
if hasattr(selected_node, "orelse") and not isinstance(selected_node, ast.IfExp):
# Toggle the else branch
if selected_node.orelse == []:
selected_node.orelse = [ast.Pass()]
else:
selected_node.orelse = []
elif hasattr(selected_node, "decorator_list"):
# Toggle the decorator_list
if selected_node.decorator_list == []:
selected_node.decorator_list = [ast.Name(id="decorator", ctx=ast.Load())]
else:
selected_node.decorator_list = []
elif isinstance(selected_node, ast.Raise):
# toggle the cause
if selected_node.cause is None:
selected_node.cause = ast.Name(id="cause", ctx=ast.Load())
else:
selected_node.cause = None
elif isinstance(selected_node, ast.Assert):
# toggle the message
if selected_node.msg is None:
selected_node.msg = ast.Constant(value="message", kind=None)
else:
selected_node.msg = None
elif isinstance(selected_node, ast.Import):
# TODO: Break up an import as a bunch of ImportFrom instead of losing info
# by just creating a single one
new_names = selected_node.names
new_names = [make_nodes.make_alias()] if new_names == [] else selected_node.names
new_import = ast.ImportFrom(
module = selected_node.names[0].name,
names = selected_node.names,
# TODO: What does level mean? (Is it like going up in the folder hierarchy?)
# Even though the grammar allows level to be None, that makes astor break
# So, let's initialize it to 0 (Still don't quite know what that means)
level = 0
)
core_logic.set_node_at_cursor(cursor_trail, tree, new_import)
elif isinstance(selected_node, ast.ImportFrom):
new_import = ast.Import(names=selected_node.names)
core_logic.set_node_at_cursor(cursor_trail, tree, new_import)
elif isinstance(selected_node, ast.alias):
# Toggle the asname
if selected_node.asname is None:
selected_node.asname = "alias"
else:
selected_node.asname = None
elif isinstance(selected_node, ast.comprehension):
# Toggle the if clause
if selected_node.ifs == []:
selected_node.ifs = [make_nodes.make_expression()]
else:
selected_node.ifs = []
elif isinstance(selected_node, ast.Yield):
# Toggle the thing to yield
if selected_node.value is None:
selected_node.value = make_nodes.make_expression()
else:
selected_node.value = None
elif isinstance(selected_node, ast.Name):
# Make it into an ast.Starred
if not core_logic.core_is_within_field(
cursor_trail,
tree,
ast.Assign,
"targets"
):
print("Can't have a starred variable outside of an assignment")
return
# Does this check make the above one useless?
parent = core_logic.get_node_at_cursor(cursor_trail[:-1], tree)
if not (isinstance(parent, ast.Tuple) or isinstance(parent, ast.List)):
print("A starred expression must be within a list or a tuple")
return
parent = core_logic.get_node_at_cursor(cursor_trail[:-1], tree)
if isinstance(parent, ast.Assign) and len(parent.targets) <= 1:
print("A starred expression can't be alone in an assignment")
return
# TODO: Make starred's work for function params
starred = ast.Starred(
value = selected_node,
ctx = selected_node.ctx
)
core_logic.set_node_at_cursor(cursor_trail, tree, starred)
elif (isinstance(selected_node, ast.Starred)
and isinstance((name := selected_node.value), ast.Name)) :
# Change the node to be the name
core_logic.set_node_at_cursor(cursor_trail, tree, name)
elif isinstance(selected_node, ast.Index):
slice = ast.Slice(
lower=selected_node.value,
upper=make_nodes.make_expression(),
step=None
)
core_logic.set_node_at_cursor(cursor_trail, tree, slice)
elif isinstance(selected_node, ast.Slice):
index = ast.Index(
value=selected_node.lower,
)
core_logic.set_node_at_cursor(cursor_trail, tree, index)
else:
# TODO: Change all of the "this node" to the node's class
print("Can't extend this node")
return []
def yank(cursor_trail, tree, _):
selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
# TODO: Multi level undo
tree.states_for_actions["yanked"] = deepcopy(selected_node)
def put(cursor_trail, tree, _):
selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
try:
yanked = tree.states_for_actions["yanked"]
except KeyError:
print("No yanked node")
return
# Or they have the same type
# or they are both statements
# or they are both expressions
# or it's an expression being pasted into a statement
# (In this case we'll wrap it into an Expr)
# otherwise, we can't paste here
if not (
(type(selected_node) == type(yanked))
or (isinstance(selected_node, ast.stmt) and isinstance(yanked, ast.stmt))
or (isinstance(selected_node, ast.stmt) and isinstance(yanked, ast.expr))
or (isinstance(selected_node, ast.expr) and isinstance(yanked, ast.expr))
):
print("Cannot paste here, the type is different")
return
if isinstance(selected_node, ast.stmt) and isinstance(yanked, ast.expr):
# Fix the type by wrapping the expression into an Expr
# Making both into ast.stmt
yanked = ast.Expr(value=yanked)
# TODO: Add the mirror logic for unwrapping an Expr into it's value
core_logic.set_node_at_cursor(cursor_trail, tree, yanked)
# Local actions only interact with the current node and it's children
# While contextual (non local) actions can interact with the whole AST
# The actions should be roughly ordered by complexity
# Simpler ones, like moving the cursor, coming first
actions = {
# "action" : (function, is_local?)
"cursor_down" : (move_cursor_down, True),
"cursor_up" : (move_cursor_up, False),
"cursor_right" : (move_cursor_right, False),
"cursor_left" : (move_cursor_left, False),
"rename" : (user_input_rename, True),
"append" : (append, False),
"insert" : (insert, False),
"delete" : (delete, False),
"insert_int" : (insert_int, False),
"type_annotation" : (insert_annotation, False),
"extend" : (extend, False),
# Binary operations
"add" : operations.to_operation(ast.Add),
"subtract" : operations.to_operation(ast.Sub),
"multiply" : operations.to_operation(ast.Mult),
"divide" : operations.to_operation(ast.Div),
"mod" : operations.to_operation(ast.Mod),
"pow" : operations.to_operation(ast.Pow),
# Comparisons
"equals" : operations.to_comparison(ast.Eq),
"greater_than" : operations.to_comparison(ast.Gt),
"greater_than_equals" : operations.to_comparison(ast.GtE),
"less_than" : operations.to_comparison(ast.Lt),
"less_than_equals" : operations.to_comparison(ast.LtE),
"is" : operations.to_comparison(ast.Is),
"in" : operations.to_comparison(ast.In),
# Boolean operation
"and" : operations.to_bool_op(ast.And),
"or" : operations.to_bool_op(ast.Or),
"yank": (yank, False),
"put": (put, False)
}
# Add the node making functions from the make_nodes file
for key in make_nodes.nodes.keys():
actions["make_" + key] = make_nodes.make_node(key)