@@ -24,13 +24,53 @@ Various strategies exist, how it could be removed:
24
24
so that the statement could once again be converted to AST to check its validity.
25
25
- nothing could be remembered - on removal surrounding expression could be detected and validated.
26
26
27
- ### Solution for incomplete imports
28
- Memorise the places of an original AST expression and evaluate its validity after applied changes.
29
- If the statement is no longer valid and it is import expression - remove it all together.
30
27
31
- The chosen approach will be easiest to implement and efficient.
28
+ ## Chosen solution
29
+ AST node can be modified and rendered back as valid code.
30
+ AST node should have methods BEFORE and AFTER handling its child nodes.
32
31
32
+ Compare original code chunk with cleaned up one and remember parts to remove during AST parsing.
33
33
34
+ After walking a node:
35
+ If node is only partially unused:
36
+ Modify the node, which is being walked.
37
+ Render the node.
38
+ Find the diff between original and modified nodes.
39
+ Save the unused parts: so that those get removed during rendering.
40
+
41
+ During removal part no fixes should be applied, only removable code parts should be provided (no AST adjustmnets to make them valid).
42
+ Currently implemented adjustments for import, context manager, pass for empty code blocks should be removed from the writing to file part.
43
+
44
+ This examples demonstrates, how AST nodes can be fixed:
45
+ ```
46
+ import ast
47
+
48
+
49
+ def print_ast(node: ast.AST) -> None:
50
+ print(ast.dump(node, indent=4)) # type: ignore
51
+
52
+
53
+ nodes = ast.parse("""
54
+ from labas import (
55
+ foo as spam,
56
+ bar
57
+ )
58
+ """)
59
+
60
+ # Apply code clean-up rules:
61
+ nodes.body[0].names.pop()
62
+ nodes.body[0].names.pop()
63
+
64
+ # Show nodes after clean-up
65
+ print("Fixed and cleaned up code, which can get merged")
66
+ print_ast(nodes)
67
+
68
+ # Show code after clean-up
69
+ print("Fixed and cleaned up code, which can get merged")
70
+ print(ast.unparse(nodes))
71
+ ```
72
+
73
+ ## Examples of code adjustments
34
74
### Empty code block
35
75
Another case is when all expressions are being removed from a block, e.g.
36
76
0 commit comments