[][src]Module glsl::visitor

AST visitors (i.e. on-the-fly mutation at different places in the AST).

Visitors are mutable objects that can mutate parts of an AST while traversing it. You can see them as flexible mutations taking place on patterns representing your AST – they get called everytime an interesting node gets visited. Because of their mutable nature, you can accumulate a state as you traverse the AST and implement exotic filtering.

Visitors must implement the Visitor trait in order to be usable.

In order to visit any part of an AST (from its very top root or from any part of it), you must use the Host interface, that provides the Host::visit function.

For instance, we can imagine visiting an AST to count how many variables are declared:

use glsl::syntax::{CompoundStatement, Expr, SingleDeclaration, Statement, TypeSpecifierNonArray};
use glsl::visitor::{Host, Visit, Visitor};
use std::iter::FromIterator;

let decl0 = Statement::declare_var(
  TypeSpecifierNonArray::Float,
  "x",
  None,
  Some(Expr::from(3.14).into())
);

let decl1 = Statement::declare_var(
  TypeSpecifierNonArray::Int,
  "y",
  None,
  None
);

let decl2 = Statement::declare_var(
  TypeSpecifierNonArray::Vec4,
  "z",
  None,
  None
);

let mut compound = CompoundStatement::from_iter(vec![decl0, decl1, decl2]);

// our visitor that will count the number of variables it saw
struct Counter {
  var_nb: usize
}

impl Visitor for Counter {
  // we are only interested in single declaration with a name
  fn visit_single_declaration(&mut self, declaration: &mut SingleDeclaration) -> Visit {
    if declaration.name.is_some() {
      self.var_nb += 1;
    }

    // do not go deeper
    Visit::Parent
  }
}

let mut counter = Counter { var_nb: 0 };
compound.visit(&mut counter);
assert_eq!(counter.var_nb, 3);

Enums

Visit

Visit strategy after having visited an AST node.

Traits

Host

Part of the AST that can be visited.

Visitor

Visitor object, visiting AST nodes.