github.com/hashicorp/hcl/v2@v2.20.0/hclsyntax/walk.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package hclsyntax
     5  
     6  import (
     7  	"github.com/hashicorp/hcl/v2"
     8  )
     9  
    10  // VisitFunc is the callback signature for VisitAll.
    11  type VisitFunc func(node Node) hcl.Diagnostics
    12  
    13  // VisitAll is a basic way to traverse the AST beginning with a particular
    14  // node. The given function will be called once for each AST node in
    15  // depth-first order, but no context is provided about the shape of the tree.
    16  //
    17  // The VisitFunc may return diagnostics, in which case they will be accumulated
    18  // and returned as a single set.
    19  func VisitAll(node Node, f VisitFunc) hcl.Diagnostics {
    20  	diags := f(node)
    21  	node.walkChildNodes(func(node Node) {
    22  		diags = append(diags, VisitAll(node, f)...)
    23  	})
    24  	return diags
    25  }
    26  
    27  // Walker is an interface used with Walk.
    28  type Walker interface {
    29  	Enter(node Node) hcl.Diagnostics
    30  	Exit(node Node) hcl.Diagnostics
    31  }
    32  
    33  // Walk is a more complex way to traverse the AST starting with a particular
    34  // node, which provides information about the tree structure via separate
    35  // Enter and Exit functions.
    36  func Walk(node Node, w Walker) hcl.Diagnostics {
    37  	diags := w.Enter(node)
    38  	node.walkChildNodes(func(node Node) {
    39  		diags = append(diags, Walk(node, w)...)
    40  	})
    41  	moreDiags := w.Exit(node)
    42  	diags = append(diags, moreDiags...)
    43  	return diags
    44  }