github.com/myhau/pulumi/pkg/v3@v3.70.2-0.20221116134521-f2775972e587/codegen/hcl2/model/utilities.go (about) 1 // Copyright 2016-2020, Pulumi Corporation. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package model 16 17 import ( 18 "sort" 19 20 "github.com/hashicorp/hcl/v2" 21 "github.com/hashicorp/hcl/v2/hclsyntax" 22 23 "github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax" 24 "github.com/pulumi/pulumi/sdk/v3/go/common/util/contract" 25 ) 26 27 func syntaxOrNone(node hclsyntax.Node) hclsyntax.Node { 28 if node == nil { 29 return syntax.None 30 } 31 return node 32 } 33 34 // SourceOrderLess returns true if the first range precedes the second when ordered by source position. Positions are 35 // ordered first by filename, then by byte offset. 36 func SourceOrderLess(a, b hcl.Range) bool { 37 return a.Filename < b.Filename || a.Start.Byte < b.Start.Byte 38 } 39 40 // SourceOrderBody sorts the contents of an HCL2 body in source order. 41 func SourceOrderBody(body *hclsyntax.Body) []hclsyntax.Node { 42 items := make([]hclsyntax.Node, 0, len(body.Attributes)+len(body.Blocks)) 43 for _, attr := range body.Attributes { 44 items = append(items, attr) 45 } 46 for _, block := range body.Blocks { 47 items = append(items, block) 48 } 49 sort.Slice(items, func(i, j int) bool { 50 return SourceOrderLess(items[i].Range(), items[j].Range()) 51 }) 52 return items 53 } 54 55 func VariableReference(v *Variable) *ScopeTraversalExpression { 56 x := &ScopeTraversalExpression{ 57 RootName: v.Name, 58 Traversal: hcl.Traversal{hcl.TraverseRoot{Name: v.Name}}, 59 Parts: []Traversable{v}, 60 } 61 diags := x.Typecheck(false) 62 contract.Assert(len(diags) == 0) 63 return x 64 } 65 66 func ConstantReference(c *Constant) *ScopeTraversalExpression { 67 x := &ScopeTraversalExpression{ 68 RootName: c.Name, 69 Traversal: hcl.Traversal{hcl.TraverseRoot{Name: c.Name}}, 70 Parts: []Traversable{c}, 71 } 72 diags := x.Typecheck(false) 73 contract.Assert(len(diags) == 0) 74 return x 75 }