Module hcl_edit::visit

source ·
Expand description

HCL language item traversal.

Each method of the Visit trait is a hook that can be overridden to customize the behavior when visiting the corresponding type of language item. By default, every method recursively visits the substructure of the AST by invoking the right visitor method of each of its fields.

The API is modeled after syn::visit. For a mutable alternative, see hcl_edit::visit_mut.

§Examples

Collect all referenced variables from a HCL document:

use hcl_edit::expr::Expression;
use hcl_edit::structure::Body;
use hcl_edit::visit::{visit_expr, Visit};
use std::collections::HashSet;
use std::str::FromStr;

#[derive(Default)]
struct VariableNameVisitor {
    variable_names: HashSet<String>,
}

impl Visit for VariableNameVisitor {
    fn visit_expr(&mut self, expr: &Expression) {
        if let Expression::Variable(var) = expr {
            self.variable_names.insert(var.to_string());
        } else {
            // Recurse further down the AST.
            visit_expr(self, expr);
        }
    }
}

let input = r#"
    // A service definition.
    service {
        fullname        = "${namespace}/${name}"
        health_endpoint = "${base_url}/health"
    }
"#;

let body = input.parse::<Body>()?;

let mut visitor = VariableNameVisitor::default();

visitor.visit_body(&body);

let expected = HashSet::from(["namespace".into(), "name".into(), "base_url".into()]);

assert_eq!(visitor.variable_names, expected);

Traits§

  • Traversal to walk a shared borrow of an HCL language item.

Functions§