| 27 | } |
| 28 | |
| 29 | func decodeUserFunctions(body hcl.Body, blockType string, contextFunc ContextFunc) (funcs map[string]function.Function, remain hcl.Body, diags hcl.Diagnostics) { |
| 30 | schema := &hcl.BodySchema{ |
| 31 | Blocks: []hcl.BlockHeaderSchema{ |
| 32 | { |
| 33 | Type: blockType, |
| 34 | LabelNames: []string{"name"}, |
| 35 | }, |
| 36 | }, |
| 37 | } |
| 38 | |
| 39 | content, remain, diags := body.PartialContent(schema) |
| 40 | if diags.HasErrors() { |
| 41 | return nil, remain, diags |
| 42 | } |
| 43 | |
| 44 | // first call to getBaseCtx will populate context, and then the same |
| 45 | // context will be used for all subsequent calls. It's assumed that |
| 46 | // all functions in a given body should see an identical context. |
| 47 | var baseCtx *hcl.EvalContext |
| 48 | getBaseCtx := func() *hcl.EvalContext { |
| 49 | if baseCtx == nil { |
| 50 | if contextFunc != nil { |
| 51 | baseCtx = contextFunc() |
| 52 | } |
| 53 | } |
| 54 | // baseCtx might still be nil here, and that's okay |
| 55 | return baseCtx |
| 56 | } |
| 57 | |
| 58 | funcs = make(map[string]function.Function) |
| 59 | Blocks: |
| 60 | for _, block := range content.Blocks { |
| 61 | name := block.Labels[0] |
| 62 | funcContent, funcDiags := block.Body.Content(funcBodySchema) |
| 63 | diags = append(diags, funcDiags...) |
| 64 | if funcDiags.HasErrors() { |
| 65 | continue |
| 66 | } |
| 67 | |
| 68 | paramsExpr := funcContent.Attributes["params"].Expr |
| 69 | resultExpr := funcContent.Attributes["result"].Expr |
| 70 | var varParamExpr hcl.Expression |
| 71 | if funcContent.Attributes["variadic_param"] != nil { |
| 72 | varParamExpr = funcContent.Attributes["variadic_param"].Expr |
| 73 | } |
| 74 | |
| 75 | var params []string |
| 76 | var varParam string |
| 77 | |
| 78 | paramExprs, paramsDiags := hcl.ExprList(paramsExpr) |
| 79 | diags = append(diags, paramsDiags...) |
| 80 | if paramsDiags.HasErrors() { |
| 81 | continue |
| 82 | } |
| 83 | for _, paramExpr := range paramExprs { |
| 84 | param := hcl.ExprAsKeyword(paramExpr) |
| 85 | if param == "" { |
| 86 | diags = append(diags, &hcl.Diagnostic{ |