Module glsl_lang::visitor

source ·
Expand description

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_lang::ast::{CompoundStatement, CompoundStatementData, ExprData, SingleDeclaration, StatementData, TypeSpecifierNonArrayData, NodeContent};
use glsl_lang::visitor::{Host, Visit, Visitor};
use std::iter::FromIterator;

let decl0 = StatementData::declare_var(
  TypeSpecifierNonArrayData::Float,
  "x",
  None,
  Some(ExprData::from(3.14).into_node())
);

let decl1 = StatementData::declare_var(
  TypeSpecifierNonArrayData::Int,
  "y",
  None,
  None
);

let decl2 = StatementData::declare_var(
  TypeSpecifierNonArrayData::Vec4,
  "z",
  None,
  None
);

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

// 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: &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);

Macros§

Enums§

  • Visit strategy after having visited an AST node.

Traits§

  • Part of the AST that can be visited.
  • Part of the AST that can be visited.
  • Visitor object, visiting AST nodes.
  • Visitor object, visiting AST nodes.