Home

gen @main - refs - log -
-
https://git.jolheiser.com/gen.git
Generate Go flags and Nix module
gen / constraints.go
- raw -
  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
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main

import (
	"errors"
	"fmt"
	"math"
	"strconv"
	"strings"

	"cuelang.org/go/cue"
)

// bound is a numeric lower or upper limit on a scalar
type bound struct {
	// value is the limit as written in the schema, e.g. 0.5
	value string
	// inclusive is set for >= and <=
	inclusive bool
}

func (b *bound) float() float64 {
	f, _ := strconv.ParseFloat(b.value, 64)
	return f
}

// tighterMin returns whichever lower bound allows less
func (b *bound) tighterMin(next *bound) *bound {
	if b == nil {
		return next
	}
	if b.float() == next.float() {
		return b.tighterInclusive(next)
	}
	if next.float() > b.float() {
		return next
	}
	return b
}

// tighterMax returns whichever upper bound allows less
func (b *bound) tighterMax(next *bound) *bound {
	if b == nil {
		return next
	}
	if b.float() == next.float() {
		return b.tighterInclusive(next)
	}
	if next.float() < b.float() {
		return next
	}
	return b
}

// tighterInclusive picks between two bounds with the same limit, where exclusive is tighter
func (b *bound) tighterInclusive(next *bound) *bound {
	if !next.inclusive {
		return next
	}
	return b
}

// regex is a =~ constraint
type regex struct {
	pattern string
	// definition is the label of the definition the regex is written in, without the #, or empty if it's on the field itself
	definition string
}

// constraints are collected from a scalar's CUE expression
type constraints struct {
	// definitions are the definitions referenced along the way (e.g. #Port), nearest first
	definitions []cue.Value
	min         *bound
	max         *bound
	regexes     []regex
	notEmpty    bool
	enum        []cue.Value
}

const maxConstraintDepth = 10

// collect walks v's expression, recording each constraint it finds.
// definition is the label of the definition v is part of, if any.
// Any constraint gen can't generate code for is an error.
func (c *constraints) collect(v cue.Value, definition string, depth int) error {
	if depth > maxConstraintDepth {
		return errors.New("constraint is too deeply nested")
	}

	// Follow references, keeping track of any definitions
	if root, path := v.ReferencePath(); len(path.Selectors()) > 0 {
		target := root.LookupPath(path)
		selectors := path.Selectors()
		if last := selectors[len(selectors)-1]; last.IsDefinition() {
			c.definitions = append(c.definitions, target)
			definition = strings.TrimLeft(last.String(), "_#")
		}
		return c.collect(target, definition, depth+1)
	}

	op, args := v.Expr()
	switch op {
	case cue.NoOp:
		// A plain type or literal has no constraints, but it may wrap an expression or reference
		if len(args) == 1 && isExprOrReference(args[0]) {
			return c.collect(args[0], definition, depth+1)
		}
		return nil
	case cue.AndOp:
		for _, arg := range args {
			if err := c.collect(arg, definition, depth+1); err != nil {
				return err
			}
		}
		return nil
	case cue.OrOp:
		return c.collectDisjunction(v, args, definition, depth)
	case cue.GreaterThanOp, cue.GreaterThanEqualOp, cue.LessThanOp, cue.LessThanEqualOp:
		return c.collectBound(op, args[0])
	case cue.NotEqualOp:
		// Only != "" is supported
		if str, err := args[0].String(); err == nil && str == "" {
			c.notEmpty = true
			return nil
		}
	case cue.RegexMatchOp:
		pattern, err := args[0].String()
		if err != nil {
			return err
		}
		c.regexes = append(c.regexes, regex{pattern: pattern, definition: definition})
		return nil
	}
	return fmt.Errorf("unsupported constraint %v", v)
}

// isExprOrReference reports whether v is an expression or a reference, rather than a plain type or literal
func isExprOrReference(v cue.Value) bool {
	op, _ := v.Expr()
	_, path := v.ReferencePath()
	return op != cue.NoOp || len(path.Selectors()) > 0
}

// collectDisjunction handles v, a disjunction of args.
//
// Two forms are supported:
//   - only literals, which is an enum, e.g. "low" | "mid" | "high"
//   - one constraint, with literals it allows as defaults, e.g. int & >0 | *1
func (c *constraints) collectDisjunction(v cue.Value, args []cue.Value, definition string, depth int) error {
	var types, literals []cue.Value
	for _, arg := range args {
		if arg.IsConcrete() {
			literals = append(literals, arg)
		} else {
			types = append(types, arg)
		}
	}

	switch len(types) {
	case 0:
		c.enum = append(c.enum, literals...)
		return nil
	case 1:
		for _, literal := range literals {
			if types[0].Subsume(literal) != nil {
				return fmt.Errorf("unsupported disjunction %v: %v is not allowed by %v", v, literal, types[0])
			}
		}
		return c.collect(types[0], definition, depth+1)
	default:
		return fmt.Errorf("unsupported disjunction %v: only enums of literal values, or one constraint plus a default, are supported", v)
	}
}

// collectBound records a >, >=, <, or <= constraint, keeping the tightest bound seen so far
func (c *constraints) collectBound(op cue.Op, limit cue.Value) error {
	value, err := limit.MarshalJSON()
	if err != nil {
		return err
	}

	b := &bound{
		value:     string(value),
		inclusive: op == cue.GreaterThanEqualOp || op == cue.LessThanEqualOp,
	}
	if op == cue.GreaterThanOp || op == cue.GreaterThanEqualOp {
		c.min = c.min.tighterMin(b)
	} else {
		c.max = c.max.tighterMax(b)
	}
	return nil
}

// intBounds converts the scalar's bounds to inclusive integers, e.g. >0 becomes 1 and <=9.5 becomes 9.
// Either is nil if there is no such bound.
func intBounds(s scalar) (lower, upper *int64) {
	if s.min != nil {
		limit := s.min.float()
		n := int64(math.Ceil(limit))
		if !s.min.inclusive && float64(n) == limit {
			n++
		}
		lower = &n
	}
	if s.max != nil {
		limit := s.max.float()
		n := int64(math.Floor(limit))
		if !s.max.inclusive && float64(n) == limit {
			n--
		}
		upper = &n
	}
	return lower, upper
}