File: variables_helper.go

package info (click to toggle)
golang-github-hashicorp-hil 0.0~git20160711.1e86c6b-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 352 kB
  • sloc: yacc: 161; makefile: 2
file content (45 lines) | stat: -rw-r--r-- 1,324 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package ast

import "fmt"

func VariableListElementTypesAreHomogenous(variableName string, list []Variable) (Type, error) {
	listTypes := make(map[Type]struct{})
	for _, v := range list {
		if _, ok := listTypes[v.Type]; ok {
			continue
		}
		listTypes[v.Type] = struct{}{}
	}

	if len(listTypes) != 1 && len(list) != 0 {
		return TypeInvalid, fmt.Errorf("list %q does not have homogenous types. found %s", variableName, reportTypes(listTypes))
	}

	if len(list) > 0 {
		return list[0].Type, nil
	}

	return TypeInvalid, fmt.Errorf("list %q does not have any elements so cannot determine type.", variableName)
}

func VariableMapValueTypesAreHomogenous(variableName string, vmap map[string]Variable) (Type, error) {
	valueTypes := make(map[Type]struct{})
	for _, v := range vmap {
		if _, ok := valueTypes[v.Type]; ok {
			continue
		}
		valueTypes[v.Type] = struct{}{}
	}

	if len(valueTypes) != 1 && len(vmap) != 0 {
		return TypeInvalid, fmt.Errorf("map %q does not have homogenous value types. found %s", variableName, reportTypes(valueTypes))
	}

	// For loop here is an easy way to get a single key, we return immediately.
	for _, v := range vmap {
		return v.Type, nil
	}

	// This means the map is empty
	return TypeInvalid, fmt.Errorf("map %q does not have any elements so cannot determine type.", variableName)
}