Module mz_sql_parser::ast::visit_mut
source · Expand description
Traversal of a mutable AST.
This module provides a VisitMut
trait that is like the Visit
trait
but operates on a mutable borrow, rather than an immutable borrow, of the
syntax tree.
Each method of the VisitMut
trait is a hook that can be overridden to
customize the behavior when visiting the corresponding type of node. By
default, every method recursively visits the substructure of the input by
invoking the right visitor method of each of its fields.
pub trait VisitMut<'ast, T: AstInfo> {
/* ... */
fn visit_function_mut(&mut self, node: &'ast mut Function<T>) {
visit_function_mut(self, node);
}
/* ... */
}
pub fn visit_function_mut<'ast, V, T: AstInfo>(visitor: &mut V, node: &'ast mut Function<T>)
where
V: VisitMut<'ast, T> + ?Sized,
{
visitor.visit_item_name_mut(&mut node.name);
visitor.visit_function_args_mut(&mut node.args);
if let Some(filter) = &mut node.filter {
visitor.visit_expr_mut(&mut *filter);
}
if let Some(over) = &mut node.over {
visitor.visit_window_spec_mut(over);
}
}
§Examples
This visitor removes parentheses from expressions.
use std::error::Error;
use mz_sql_parser::ast::{AstInfo, Expr};
use mz_sql_parser::ast::visit_mut::{self, VisitMut};
struct RemoveParens;
impl<'a, T: AstInfo> VisitMut<'a, T> for RemoveParens {
fn visit_expr_mut(&mut self, expr: &'a mut Expr<T>) {
visit_mut::visit_expr_mut(self, expr);
if let Expr::Nested(e) = expr {
*expr = (**e).clone();
}
}
}
fn main() -> Result<(), Box<dyn Error>> {
let sql = "(a + ((b))) + c";
let mut expr = mz_sql_parser::parser::parse_expr(sql.into())?;
RemoveParens.visit_expr_mut(&mut expr);
let expected = mz_sql_parser::parser::parse_expr("a + b + c".into())?;
assert_eq!(expr, expected);
Ok(())
}
The VisitMutNode
trait is implemented for every node in the AST and can
be used to write generic functions that apply a VisitMut
implementation to
any node in the AST.
§Implementation notes
This module is automatically generated by the crate’s build script. Changes to the AST will be automatically propagated to the visitor.
This approach to AST visitors is inspired by the syn
crate. These module
docs are directly derived from the syn::visit_mut
module docs.