Debian Codegraph @

ast/literal.go

raw symbols SCIP
1 // Copyright (c) HashiCorp, Inc.
2 // SPDX-License-Identifier: MPL-2.0
3
4 package ast
5
6 import (
7 "fmt"
8 "reflect"
9 )
10
11 // LiteralNode represents a single literal value, such as "foo" or
12 // 42 or 3.14159. Based on the Type, the Value can be safely cast.
13 type LiteralNode struct {
14 Value interface{}
15 Typex Type
16 Posx Pos
17 }
18
19 // NewLiteralNode returns a new literal node representing the given
20 // literal Go value, which must correspond to one of the primitive types
21 // supported by HIL. Lists and maps cannot currently be constructed via
22 // this function.
23 //
24 // If an inappropriately-typed value is provided, this function will
25 // return an error. The main intended use of this function is to produce
26 // "synthetic" literals from constants in code, where the value type is
27 // well known at compile time. To easily store these in global variables,
28 // see also MustNewLiteralNode.
29 func NewLiteralNode(value interface{}, pos Pos) (*LiteralNode, error) {
30 goType := reflect.TypeOf(value)
31 var hilType Type
32
33 switch goType.Kind() {
34 case reflect.Bool:
35 hilType = TypeBool
36 case reflect.Int:
37 hilType = TypeInt
38 case reflect.Float64:
39 hilType = TypeFloat
40 case reflect.String:
41 hilType = TypeString
42 default:
43 return nil, fmt.Errorf("unsupported literal node type: %T", value)
44 }
45
46 return &LiteralNode{
47 Value: value,
48 Typex: hilType,
49 Posx: pos,
50 }, nil
51 }
52
53 // MustNewLiteralNode wraps NewLiteralNode and panics if an error is
54 // returned, thus allowing valid literal nodes to be easily assigned to
55 // global variables.
56 func MustNewLiteralNode(value interface{}, pos Pos) *LiteralNode {
57 node, err := NewLiteralNode(value, pos)
58 if err != nil {
59 panic(err)
60 }
61 return node
62 }
63
64 func (n *LiteralNode) Accept(v Visitor) Node {
65 return v(n)
66 }
67
68 func (n *LiteralNode) Pos() Pos {
69 return n.Posx
70 }
71
72 func (n *LiteralNode) GoString() string {
73 return fmt.Sprintf("*%#v", *n)
74 }
75
76 func (n *LiteralNode) String() string {
77 return fmt.Sprintf("Literal(%s, %v)", n.Typex, n.Value)
78 }
79
80 func (n *LiteralNode) Type(Scope) (Type, error) {
81 return n.Typex, nil
82 }
83
84 // IsUnknown returns true either if the node's value is itself unknown
85 // of if it is a collection containing any unknown elements, deeply.
86 func (n *LiteralNode) IsUnknown() bool {
87 return IsUnknown(Variable{
88 Type: n.Typex,
89 Value: n.Value,
90 })
91 }