Testing presence, validity, and concreteness

CUE configurations have long tested values by comparing them with bottom: x != _|_ and x == _|_. That one comparison is asked to answer three different questions — is the field there, is the value free of errors, is it a finished value — and it answers each of them only some of the time.

The predicate builtins ask each question on its own. This guide shows which predicate answers which question, how to use them together with the reflect package, and how to move existing code over.

The predicate builtins are the predicates experiment, in preview from CUE v0.19.0. A file opts in with @experiment(predicates). The functions reflect.Allows and reflect.Field are part of the standard library from the same version and need no opt-in. See the predicates experiment and the reflect package for the reference. Short-circuit evaluation is stable from v0.19.0, so no @experiment(shortcircuit) attribute is needed at this version.

Which predicate answers which question

QuestionUseAnswers false whenReports an error when
Is this field present?exists(x.f)the field is absent but could still be addedthe field can never exist
Is this value free of errors?isValid(expr)the value is an error, or no instance of it can be validnever: it is the one predicate that catches errors
Is this value finished, as an export needs it?isConcrete(expr)the value is a type, a constraint, or absentthe value is an error
May this label ever appear?reflect.Allows(s, "f")the struct or list is closed to the labels is not a struct or list
What is this field constrained to?reflect.Field(s, "f")— it returns the valuethe field can never exist
How many of these fields are present?existsN(n, x.a, x.b)— it is a validatorthe count cannot meet n
How many of these conditions hold?countN(n, [c1, c2])— it is a validatorthe count cannot meet n

The examples in this guide start from the same file:

cue
@experiment(predicates)

package example

import "reflect"

s: {name: "web", port?: int, replicas: int}

t: {a?: 1, b?: int}

#Closed: {a: 1, b?: 2}

exists: is the field present?

exists takes a reference to a field, a selector, or an index, and reports whether that member is present. It does not look at the member’s value: a present field whose value is an error still exists.

ExpressionResult
exists(s.name)true
exists(s.port)falsedeclared optional, not set
exists(s.other)falses is open, so other could be added
exists(#Closed.zzz)error#Closed is closed, so zzz can never exist

false always means “not now, but a legal configuration could add it”. A member that can never exist is an error instead, so a misspelled field name on a closed struct or definition is caught and not silently reported as absent.

isValid: is the value free of errors?

isValid reports whether an expression denotes a value that could still be made concrete. It is the only predicate that turns an error into false, and so the only one to use for catching an error.

ExpressionResult
isValid(s.replicas)trueint can still be given a value
isValid(s.replicas & "x")falseconflicting values
isValid(s.port)falsea reference to an absent field is an error
isValid({a?: 1 & 2})truean instance may leave a out
isValid({a!: 1 & 2})falseno instance can supply a

A value that is merely unfinished — a type, an unresolved disjunction — is valid.

isConcrete: is the value finished?

isConcrete reports whether an expression is a fully concrete value: a single piece of data, as cue export requires. For a struct or list, every regular field and element must be concrete and no required field may be unset; optional fields and pattern constraints do not count.

ExpressionResult
isConcrete(s.name)true
isConcrete(s.replicas)falseint is a type
isConcrete({a?: int})trueoptional constraints do not count
isConcrete({a!: int})falsean unset required field blocks an export
isConcrete(1 & 2)errorerrors are passed through, not caught

Selecting a field that is not there

When the argument selects a field, the answer depends on whether the field could exist:

ExpressionResult
isConcrete(s.port)falseabsent, but could still be supplied
isConcrete(t.a)falseabsent, even though its constraint is 1
isConcrete(#Closed.zzz)errorzzz can never exist

isConcrete asks about the member, not about its constraint. An absent field is not a finished value however specific its constraint is, so with t: {a?: 1, b?: int} both isConcrete(t.a) and isConcrete(t.b) are false. To ask about the constraint, read it with reflect.Field:

ExpressionResult
reflect.Field(t, "a")1
isConcrete(reflect.Field(t, "a"))true
isConcrete(reflect.Field(t, "b"))false

reflect.Field(s, "f") is the value that f has, or would have, in s. It cannot tell an absent field from a present one whose value is _; use exists for that.

Selecting through an optional struct

When an intermediate struct is itself optional and unset, such as u: {b?: {c: 1}}, each operation follows its own calling model:

ExpressionResultWhy
exists(u.b.c)incomplete erroronly the final field may be absent; check exists(u.b) && exists(u.b.c) instead
isValid(u.b.c)falseu.b.c evaluates to bottom at finalization, which isValid catches
isConcrete(u.b.c)falseu.b.c evaluates to an incomplete bottom (u & {b: {c: 1}} could still supply it), which isConcrete maps to false
reflect.Allows(u.b, "c")incomplete errorordinary function argument u.b is incomplete
reflect.Field(u.b, "c")incomplete errorordinary function argument u.b is incomplete; use reflect.Field(reflect.Field(u, "b"), "c") (1) to inspect the nested constraint

Asking about a field that may be impossible

exists is strict: asking about a field that a closed struct does not declare is an error. That is what you want for a field name you wrote yourself, and not what you want when the name is computed, or when the struct is one of several definitions.

reflect.Allows reports whether a label may ever appear, and answers false where exists reports an error. Ask it first:

cue
reflect.Allows(s, "k") && exists(s.k)
ExpressionResult
reflect.Allows(#Closed, "zzz") && exists(#Closed.zzz)falsenever allowed
reflect.Allows(#Closed, "b") && exists(#Closed.b)falseallowed, not present
reflect.Allows(#Closed, "a") && exists(#Closed.a)truepresent

This relies on && not evaluating its right operand when the left one is false. That behavior is part of the language from v0.19.0, so the example needs only @experiment(predicates). Files at v0.17.0 or v0.18.0 could opt in with @experiment(shortcircuit), but the predicate builtins are available only from v0.19.0. See the shortcircuit experiment for the compatibility details.

In a comprehension, two guards express the same check:

cue
if reflect.Allows(s, "k") if exists(s.k) {
	// ...
}

A fallback disjunction, *exists(s.k) | false, also yields false for an impossible field, though it is best reserved for migration since it swallows any error in s as well.

existsN and countN: how many?

existsN is a validator: embed it in a struct to constrain how many of the referenced fields are present. With a bound of 1 it is the “exactly one of” pattern:

cue
#Source: {
	existsN(1, git, oci, path)
	git?:  string
	oci?:  string
	path?: string
}

ok:   #Source & {git: "https://example.com/repo.git"}
both: #Source & {git: "a", oci: "b"} // error: 2 matched, expected 1
none: #Source                        // incomplete: a field may still be added

The bound can be any numeric constraint, such as <=1 or >=2. Too many present fields is an error at once; too few stays incomplete, since a field may still be added, and is reported when a complete value is required, as by cue vet -c or cue export.

countN is the general form. It counts the true values in a list of conditions, so it combines with any predicate: existsN(1, a, b) is countN(1, [exists(a), exists(b)]).

cue
#Limits: {
	countN(>=1, [isConcrete(cpu), isConcrete(memory)])
	cpu:    number | string
	memory: string
}

Moving from _|_ comparisons

cue fix rewrites comparisons with bottom to isValid and adds the @experiment(predicates) attribute to each file it changes:

sh
cue fix --exp=predicates ./...
BeforeAfter
x != _|_isValid(x)
x == _|_!isValid(x)

The module’s language version must be v0.19.0 or later. The rewrite is applied only when predicates is named: --exp=all leaves it out, because it can change what a configuration means in one case.

The case to check by hand

The comparison x != _|_ is false for a field that is declared but not yet concrete. isValid(x) is true for it, since a type can still be satisfied. A guard on such a field therefore flips:

cue
#Service: {
	name:     string
	replicas: int
}

svc: #Service & {name: "web"}

out: {
	if svc.replicas != _|_ {
		scaled: true
	}
}

Before the fix out is {}. After it the guard reads if isValid(svc.replicas) and out is {scaled: true}.

cue fix cannot tell which question the comparison was asking: it sees the expression, not that its value is a type. Where the comparison was testing “has this been given a value?”, replace isValid with isConcrete after running the fix:

cue
if isConcrete(svc.replicas) {
	scaled: true
}

As a rule of thumb for the comparisons you find:

  • “Is the optional field set?” becomes exists(x.f).
  • “Did this expression produce an error?” becomes isValid(expr), which is what the fix writes.
  • “Has this been filled in with data?” becomes isConcrete(x.f).

Guards on absent optional fields, the most common use of the comparison, keep their meaning under the rewrite: isValid(svc.port) is false while port is not set.

Reference

Install CUE