github.com/hashicorp/hcl/v2@v2.20.0/ext/userfunc/public.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package userfunc
     5  
     6  import (
     7  	"github.com/hashicorp/hcl/v2"
     8  	"github.com/zclconf/go-cty/cty/function"
     9  )
    10  
    11  // A ContextFunc is a callback used to produce the base EvalContext for
    12  // running a particular set of functions.
    13  //
    14  // This is a function rather than an EvalContext directly to allow functions
    15  // to be decoded before their context is complete. This will be true, for
    16  // example, for applications that wish to allow functions to refer to themselves.
    17  //
    18  // The simplest use of a ContextFunc is to give user functions access to the
    19  // same global variables and functions available elsewhere in an application's
    20  // configuration language, but more complex applications may use different
    21  // contexts to support lexical scoping depending on where in a configuration
    22  // structure a function declaration is found, etc.
    23  type ContextFunc func() *hcl.EvalContext
    24  
    25  // DecodeUserFunctions looks for blocks of the given type in the given body
    26  // and, for each one found, interprets it as a custom function definition.
    27  //
    28  // On success, the result is a mapping of function names to implementations,
    29  // along with a new body that represents the remaining content of the given
    30  // body which can be used for further processing.
    31  //
    32  // The result expression of each function is parsed during decoding but not
    33  // evaluated until the function is called.
    34  //
    35  // If the given ContextFunc is non-nil, it will be called to obtain the
    36  // context in which the function result expressions will be evaluated. If nil,
    37  // or if it returns nil, the result expression will have access only to
    38  // variables named after the declared parameters. A non-nil context turns
    39  // the returned functions into closures, bound to the given context.
    40  //
    41  // If the returned diagnostics set has errors then the function map and
    42  // remain body may be nil or incomplete.
    43  func DecodeUserFunctions(body hcl.Body, blockType string, context ContextFunc) (funcs map[string]function.Function, remain hcl.Body, diags hcl.Diagnostics) {
    44  	return decodeUserFunctions(body, blockType, context)
    45  }