-
Notifications
You must be signed in to change notification settings - Fork 29
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
Question: How to walk/visit the AST? #108
Comments
Hi, |
Hey there. I found the visitor.rs module but cannot import it. are there any updates? |
Is the module public? |
I'm decently new to rust but from my understanding it is: #[cfg(feature = "visitor")] I've also enabled the feature @fanninpm |
The following line likely needs to be changed to say Line 46 in 9ce55ae
|
Ok should i open a PR? |
Give it a shot! |
Isn't this line allow to import |
I'm very new to rust and was also trying to walk the AST in order to find all usages of a particular function. |
Hi all, I'll write down a brief explanation of how to add the visitor and how to utilize it. [dependencies]
rustpython-ast = { version = "0.4.0", features = ["visitor"] }
rustpython-parser = "0.4.0" Once you did that, you can use the crate like so: use rustpython_ast::Visitor; Visitor is a public trait, which means you'll have to create an implementation. struct AttributeCounter {
attributes_count: usize
}
// Here you implement the trait for a struct
impl Visitor for AttributeCounter {
// We'll get to this later
} Nice! The Visitor is built to be a recursive walker/visitor, starting with the function impl Visitor for AttributeCounter {
fn visit_expr_attribute(&mut self, node: ExprAttribute) {
self.attributes_count += 1;
}
} Great, it now counts attributes! impl Visitor for AttributeCounter {
fn visit_expr_attribute(&mut self, node: ExprAttribute) {
self.attributes_count += 1;
self.generic_visit_expr_attribute(node);
}
} Now the visitor will visit the whole AST and count any attributes for you. |
I'm trying to extract all the imports from a python file. To do this I'm using the
rustpython_parser::parse
function to get an AST and then iterating over all the statements in thebody
to findStmt::Import
andStmt::ImportFrom
. This works for imports defined at the root of the file, however misses any imports defined inside e.g. function/class definitions etc. So I think what I really want to do is walk the AST and visit all the nodes. Is there some way to achieve this with one of the rustpython packages?The text was updated successfully, but these errors were encountered: