encoding/jsonschema: fix issue 3176
https://cuelang.org/issue/3176 describes a situation where a higher
level constraint omitted a necessary term from its disjunction because
of a `oneOf`. On inspection, the current logic for `usedTypes` and
`allowedTypes` seems flaky.
Notably, `usedTypes` does not seem to fit its purported purpose, as
described in this comment [1] by Marcel:
> Used means that the type [is] implied somewhere (e.g. by a constraint
> or in the "all" bucket). "types" means that this type should be
> represented (and if it hasn't yet up till now, it needs an explicit
> type).
- various constraint types that adjust `usedTypes` (e.g. `minLength`) do
_not_ imply a particular type, as they only apply if the object is that
particular type.
- the `state.value` logic also sets `usedTypes` but that's also
incorrect because it sets it for nested values and also inappropriately
when the value is part of an enum (when it's in an enum, we know the
union of the types in the enum, not their intersection).
We fix this by making the invariants simpler (and renaming `usedTypes`
to `knownTypes` to hopefully make its meaning clearer). Namely,
`allowedTypes` holds the full set of types that the result is allowed to
be; `knownTypes` holds the full set of types that the non-type-specific
constraints are known to imply.
For example:
{"enum": [1, null]}
would result in knownTypes={number,null}, allowedTypes={number,null}
but:
{"types": ["number", "null"]}
would result in: knownTypes=allTypes, allowedTypes={number,null} because
the latter adds no elements to state.all that imply the types where the
former does.
None of this logic is entirely ideal: it would be considerably nicer if
we could emit much more naive CUE and let the evaluator simplify it for
us, but we're not there yet.
Note: this does improve the output in some of the existing test cases.
Fixes #3176.
[1] https://cue-review.googlesource.com/c/cue/+/6302/10..14/encoding/jsonschema/decode.go#b433
Signed-off-by: Roger Peppe <rogpeppe@gmail.com>
Change-Id: I8fc29b3de035d1ecad62b5c1bf6a8ef136660dc9
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/1199309
Unity-Result: CUE porcuepine <cue.porcuepine@gmail.com>
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>