Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple DefUse Analysis #28

Open
aliraza0337 opened this issue May 2, 2021 · 4 comments
Open

Simple DefUse Analysis #28

aliraza0337 opened this issue May 2, 2021 · 4 comments

Comments

@aliraza0337
Copy link

Hi, I have been trying to perform a simple DefUse analysis on my code. Essentially, I just want to know for a given line of code, which other lines of code should be executed before it.

code = open("my_code.py", "r").read()
module = ast.parse(code)
duc = beniget.DefUseChains()
duc.visit(module)

From the example in the code, I know the duc should contain the required information in the duc.chains. But I am a little confused about the right way to access the information. For example, I know each line of code would be presented as a node in module and I can access it by doing module.body[line #], how can I look it up in the duc.chains? I have tried different ways and unfortunately no luck.

@serge-sans-paille
Copy link
Owner

You shouldn't take a line a approach, but a node approach:

for d in duc.locals[module]:
    print(d.name()) # prints the name of each defined identifier.
    print(d.node) # the node that actually holds the definition. Generally an `ast.Name` or and `ast.FunctionDef`
    print(d.users())  # the users of that definition

hope it helps?

@TitovS
Copy link

TitovS commented May 13, 2021

Could I also ask here? I have a close task - I need to find all usages of definitions and return links between definition and uses on module level.

Until now, I've built DefUseChains, traversed each chain, found all chain ends and then with ancestors linked each start and end of the chain to the first ancestor. It seems that the solution that you provided solves the same problem but much easier, however I've run both solutions on the same piece of code and got different amount of these links. Am I missing something and which approach will be better for this problem?

Later today I will try to come up with a reproducible example.

@serge-sans-paille
Copy link
Owner

@TitovS : the snippet above only finds top-level definition, while yours would also find inner definition, maybe that's the reason?

@tristanlatr
Copy link
Contributor

I suggest we close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants