Module 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§

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

Functions§

visit_array
visit_attr
visit_binary_op
visit_block
visit_block_label
visit_body
visit_conditional
visit_directive
visit_element
visit_else_template_expr
visit_expr
visit_for_cond
visit_for_directive
visit_for_expr
visit_for_intro
visit_for_template_expr
visit_func_args
visit_func_call
visit_func_name
visit_heredoc_template
visit_if_directive
visit_if_template_expr
visit_interpolation
visit_object
visit_object_item
visit_object_key
visit_object_value
visit_parenthesis
visit_string_template
visit_structure
visit_template
visit_traversal
visit_traversal_operator
visit_unary_op