Created
April 29, 2013 21:01
-
-
Save jd/5484743 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(if (if 1 2) 1) | |
Generates the tree | |
ast.stmt.If | |
`-> ast.stmt.If | |
`-> ast.expr.Num | |
`-> ast.expr.Num | |
`-> ast.expr.Num | |
Can we detect what's embedded into an ast.stmt automagically? No, we don't the fields. | |
Let's build our own ast.stmt classes | |
class HyAst(object): | |
"""Classes that stores the fields!" | |
class If(ast.stmt.If, HyAst): | |
"""Like if but we can retrieve the sub-stmt, sub-expr, etc""" | |
Now we build a tree with the HyAst version, which is the same: | |
HyAst.stmt.If | |
`-> HyAst.stmt.If | |
`-> HyAst.expr.Num | |
`-> HyAst.expr.Num | |
`-> HyAst.expr.Num | |
Except that we have a special method to check "if a stmt refers a stmt". | |
In such a case, like the if if, we wrap the stmt into a ast.FunctionDef, and we replace it by a Call. | |
Where to place the FunctionDef? Well, just before the stmt that was embedding the other stmt. | |
So we build our FunctionDef, insert before the stmt, and replace the stmt by a expr.Call. | |
[ | |
HyAst.stmt.FunctionDef(foobar_1) | |
`-> HyAst.stmt.if | |
`-> HyAst.expr.Num | |
`-> HyAst.expr.Num | |
HyAst.stmt.If | |
`-> HyAst.expr.Call(foobar_1) | |
`-> HyAst.expr.Num | |
] | |
We know that we need to replace a stmt by an expr (= by a function call i.e. expr.Call) as soon as we have something like in our tree: | |
anything -> stmt | |
=========== | |
Second example just for the sake to see if it works: | |
(if 1 (if 2 3)) | |
AST is: | |
If | |
`-> Num(1) | |
`-> If | |
`-> Num(2) | |
`-> Num(3) | |
How I see stmt.If -> stmt.If | |
I mangle :-D | |
FunctionDef(foobar_1) | |
`-> If | |
`-> Num(2) | |
`-> Num(3) | |
If | |
`-> Num(1) | |
`-> Call(foobar_1) | |
====== | |
3rd example | |
(if (setv x 1) x) | |
stmt.If | |
`-> stmt.Assign(x=1) | |
`-> expr.Name(x) | |
OH STMT -> STMT AGAIN! C'MON! | |
stmt.FunctionDef(foobar_1) | |
`-> stmt.Assign(x=1) | |
stmt.If | |
`-> expr.Call(foobar_1) | |
`-> expr.Name(x) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment