v0.2.0

cue-lang/cue Released

A release of CUE OSS · its page on GitHub

This release makes several minor and bigger language changes. The changes are a result of analyzing CUE’s interoperability with other languages and what is needed for this. It is expected that these are the last major changes and that this fixes the look and feel of the language. In addition to the usual cue fmt-based rewrites, we now also provide a cue fix command to aid in the transition. Also, the old formats are still supported for now. Minor language changes and additions to the language are still planned on the path to stability.

The new language changes allow for a simpler JSON Schema mapping. This, in turn, allows for a more straightforward combination of schema and data on the command line.

New syntax for definitions

Before, definitions were indicated with a double colon ::. They lived in the same namespace as regular fields. This property complicated defining automated conversions of some other data formats to CUE. For instance, JSON Schema keeps separate sections for schema and definitions. As there is no enforced convention, as in Go, for naming the two kinds differently, one could not map these to the same struct. This forced schemas to be moved to another location, which turned out to be cumbersome and unnatural.

Another issue with the old syntax is that one could not determine from a reference a.b whether b would refer to a definition or regular field. Not a big problem per se, but it lacked clarity.

As of v0.2.0, definitions are denoted with special identifier starting with a #. As this was not a legal identifier before, such identifiers can safely be used exclusively for definitions. Effectively, definitions now have their own namespace. Other than that, definitions work as before. They still close a struct, they are not output during export, and you simply use their identifier to refer to them.

Before:

A :: b: int
b: c :: string

D: A
E: b.c

After

#A: b: int
b: #c: string
D: #A
E: b.#c

The #c notation is just an identifier: no special syntax is needed to handle them. As before, "#foo" still denotes a regular field with a name starting with #.

Using an initial # to distinguish between definitions and regular fields was inspired by Go’s use of initial casing to distinguish between exported and non-exported identifiers. Indeed because CUE is a JSON superset and interop focused, there is little control over casing. As we explain later in the Hidden Fields section, we also resurrect _ as a means of excluding fields and definitions from output.

The new notation may take a bit of getting used to, but the increased readability and the flexibility from the separate namespaces are big wins. So far the feedback has been overwhelmingly positive.

The Go, Protobuf, JSON Schema, and OpenAPI mappings, as well as the tutorials, have been ported to use #-style definitions. Please beware that if one has other templates based on this they need to be rewritten as well.

Limitations

The new definition syntax is more restricted than the old syntax. In general, it is no longer allowed to have dynamic definition names. For instance, the syntax disallows using interpolations for creating names. Also bulk optional fields only apply to regular fields. We think this actually benefits static analysis and is overall a good change. If need be, though, the old semantics can be simulated by containing a struct within a definition used as a map. In case this proves to be too limiting, we have a possible language change up our sleeves that would allow dynamic definitions again.

Old style definitions will keep being supported up to the next minor release. Use cue fix to rewrite current files (see below).

API changes

The current API assumed definitions and fields lived in the same namespace. The current API is therefore inherently broken. The Struct.FieldByName has been deliberately broken to force users to disambiguate. To evaluate a reference, it is recommended to use Dereference instead of passing the result of Reference to Lookup.

There are some good ideas to make the API considerably simpler and more powerful. This is contemplated to be built on top of the new adt package, which is developed as part of the evaluator rewrite, which is planned for the next minor release.

cue fix

To aid in the conversion to #-style definitions, the cue fix command is introduced. This command does a module-wide update of packages by default, but allows specifying individual files and packages.

This is no longer piggybacked on cue fmt. Unlike previous rewrites, the definition rewrite requires evaluation. In addition, not all current definitions are legal in the new syntax. The converter will not remap those. Also, unfortunately, due to API limitations, the converter can also not handle all legal cases. We hope that such cases will be rare, though.

Cases that cannot be handled are clearly marked with locations that may reference the definition included. Definitions with issues have are marked with a deliberately obscure @tmpNoExportNewDef attribute, indicating they need manual fixing

There is also a possibility there will be undetected breakage. This may happen if a selection is made in a disjunction where the field may be either a definition or regular field. The fact that this is even possible indicates that the old model was probably too flexible and possibly more bug prone. With new-style definitions such shenanigans are no longer possible.

Unfortunately, cue fix currently does not handle updating multiple packages within the same directory at once unless manually specified. We intend to allow this at some point.

Tool semantics changes

Previously, the cue tool handled schemas and data differently. In practice, the distinction is not all that clear, making this distinction somewhat “forced”. The cue tool now treats data and schemas as the same thing and always unifies them without distinction by default. This greatly simplifies its use and makes it a very powerful tool for operating directly on non-CUE schema.

There are two exceptions to the new “always unify all files” rules: 1) with cue vet multiple data files are still individually verified against a single schema. 2) the -d option still separates schema from data files. One could argue that the latter isn’t really necessary anymore, as we will see next.

JSON Schema mapping

The following command

cue export schema.json data.yaml

converts the schema.json (which has a proper value for $schema to detect the format) to a schema and data.yaml to data, and unifies the results. This will naturally fail if the contents of data doesn’t correspond to the schema. There is no special logic needed to detect these cases, other than knowing when to interpret a data file as JSON Schema.

Note that #-style definitions were key to make this possible. Without them, there would be no obvious way to map JSON Schema to the root of a config as merging fields and schema to the same namespace could result in conflicts.

OpenAPI merging

Another example of the new capabilities is that one can now merge schema as one would merge data. For instance, the following command merges two OpenAPI files and then outputs it again as OpenAPI:

cue def openapi: file1.json file2.json --out openapi

The user won’t even see the intermediate CUE.

Hidden fields

This release also officially resurrects hidden fields (identifiers written as, for example, _foo). They were removed from the spec as with the introduction of definitions they were believed to be an incongruent feature. They fit, however, quite nicely with the new-style definitions. They were still in use and proved to be more useful than expected. As they were never really removed from the implementation nothing changes. However, their comeback is now official.

For clarity, both hidden fields and definitions are not shown in exported output. They serve different functions, though.

A definition defines a new composite type, the most general specification of something. They are at the other end of the spectrum to concrete instances. As definitions are supposed to fully define a schema, CUE can use them to catch typos in field names by detecting fields that are not supposed to be there.

A hidden field can be any value and is not subjected to such scrutiny. They are used to define fields that are not converted to output without making them a definition.

Although this is not yet enforced, hidden fields are local to a package. To make the matrix complete identifiers starting with _# denote hidden definitions, or definitions local to a package. These can be used today, although this restriction is also not yet enforced.

Streamlined syntax for list comprehension

List comprehensions are now written as

[ for x in src { x + 1 } ]

This brings them in line with field comprehensions, where the value also comes after the comprehension clauses. Overall, this greatly increases readability.

This also harmonized the syntax. It simplifies both spec and implementation, and prepares for some of the constructs mentioned in the query proposal.

The one thing that may require some getting used to is the curly braces alluding to the value being a struct. If the curly braces contain a single scalar value, however, it is promoted to be the result of an iteration. CUE users may already be familiar with this construct at the top-level scope, where “embedded scalars” are the final result of evaluation. This construct was originally invented to allow omitting curly braces, while still being a superset of JSON (JSonnet uses the same trick). It turns out, however, that this trick can be quite useful when generalized to apply to any struct, not just the top-level one. We continue to investigate this possibility. Consider this the first application.

Using cue fmt will automatically update old list comprehensions to use the new format.

Added limitations on bulk optional fields

Previously, it was allowed to have a bulk optional field alongside regular fields within a struct

a: {
  [string]: T
  foo: S
}

Many people expected T to only apply to fields other than foo, but not foo itself. This is, in fact, how JSON Schema’s patternProperties and additionalProperties work. With hindsight, this approach turns out to have many benefits.

The plan is to transition to these new semantics. We will first disallow bulk optional fields alongside other fields altogether. This can easily be worked around by singling out such fields by wrapping them in curly braces:

a: {
  { [string]: T }
  foo: S
}

Bulk optional fields of this style

a: [string]: int

are effectively already singled out and can remain unchanged.

The resulting embedding means the same thing in CUE. After the original semantics of mixing these fields has been banned for some time, we can introduce the original syntax, but now with “fallback” semantics analogous to JSON Schema.

For this release cue fmt simply rewrites bulk optional fields to be singled out. Forcing the rewrite is planned for a next release, followed by dropping support, waiting and then changing the semantics.

API: astutil.Sanitize

A noteworthy addition to the API is astutil.Sanitize. This function aids automated rewrites of CUE ASTs. Adding fields to arbitrary CUE ASTs may inadvertently shadow references. Inserting references to imports may cause similar issues. Not handling these cases correctly was a common source of bugs. Sanitize shares code with the actual resolver and can therefore be expected to be more accurate than any parallel implementation.

The Sanitizer automatically detects and resolves shadowed fields and fixes the AST in place accordingly. It uses the following trick: like in Go, the CUE resolver uses an extra field in ast.Ident (a reference) to mark what an identifier points to. The Sanitizer runs resolution on an AST which already may have such fields filled out from previous resolutions. If the result is not consistent, it will modify the AST to make it so.

Users can manually set such resolutions as well. For instance, setting the resolution to an ast.ImportSpec will cause the spec to be inserted automatically or the node to resolve to a preexisting equivalent one.

More functionality can be added in the future. The key is that all converters can share the same logic. It has already been used to fix import inserting in JSON Schema and to fix import disambiguation in the protobuf converter.

CI improvements

CUE uses GitHub Actions for its CI. The configuration for that was YAML. The lack of validation causes some breakages here and there when these needed to be adjusted. The configuration is now written in CUE! We’ll let you know how it goes.

We also now have a TryBot for the Gerrit repo, which should also prevent breakages in the future.

Deprecations

Space-separated labels are now no longer supported and will give a compiler error complaining about a missing :.

Legacy (“back-style”) field comprehensions are now also no longer supported.

Some APIs have deliberately been broken to force handling the distinction between identifiers and strings.

All changes

66 changesby area

ci10

  • ciadd -f (fail) flag to curl calls in GitHub Actions trigger4c7d062
  • cidefine repository_dispatch build37b1de2
  • cifix bad testscript file name and update CI with module get check6bbacf9
  • cifix error in workflow generation task8fcefc8
  • cifix the GitHub actions repository_dispatch workflow8f1d260
  • cifix up Yaml error in specifying constraint on generate step99f4ce0
  • cifix up some build breakages063fa12
  • cire-run go generate against stable Go version as part of CI3527700
  • citidy up and refactor GitHub workflow specificationsa801188
  • ciuse CUE for GitHub Actions workflow specifications65163a0

cmd11

  • cmd/cue/cmdadd fix command for new-style definitionsa846fcc
  • cmd/cue/cmdbug fix: allow vet to combine schema and datad8d240d
  • cmd/cue/cmdfix build breakagec114dbb
  • cmd/cue/cmdfix typo 'filetype' -> 'filetypes'dc62e36
  • cmd/cue/cmdfix windows test breakage8f09dde
  • cmd/cue/cmdfmt rewrites alias to let clauses50bcd97
  • cmd/cue/cmdmerge data files by default5114891
  • cmd/cue/cmdprint full error messages in tools mode5163831
  • cmd/cue/cmdremove unused func mustParseFlags99117ba
  • cmd/cue/cmdupdate "get go" to use new-style definitions8be0ffe
  • cmdfix cli.Print usage in docstring7ed2fc1

cue24

  • cue/ast/astutiladd and use Santize functionb19b41a
  • cue/ast/astutilrefactor to prepare for Sanitize func00a8bb9
  • cue/astallow LetClause in NewStructafe86c1
  • cue/astprint StructLit in regular mode by defaultb70cc97
  • cue/buildfix typo reference to cue/load packagea5c0866
  • cue/cmd/cuedisallow quoted identifiers by default9954ecd
  • cue/formatdon't simplify when parent field has commentaeb0a8c
  • cue/formatfix formatting of generated ImportsDecl8938f35
  • cue/parserallow keywords in more places989e984
  • cue/parserremove support for legacy field comprehensions8040ce7
  • cue/parserremove support for space-separated labelsc1c4c63
  • cue/testdatareplace spaces in txtar file names7491622
  • cueallow # and disallow #0 as identifiersdbf1c00
  • cuedisallow bulk optional fields with other fields56c994d
  • cueimplement "front-style" list comprehensions1370f0a
  • cueintroduce let declaration724da18
  • cuemake test for Expr more precisefb7bdab
  • cuemerge attributes for top-level fieldsdd262ee
  • cueprevent crash in JSON conversion12927e8
  • cuesome API adjustments for new-style definitions0240d4e
  • cuesupport for #-style definitions9c9cdba
  • cuesupport new-style definitions in LookupDeff416ee8
  • cueuniform handling of definitions8837685
  • cueuse _# instead of #_ for hidden definitionb7083ff

doc4

  • doc/ref/spec.mdallow ... in an ast.Filec174a08
  • doc/ref/spec.mdfix doc bug in Label production86e1a64
  • doc/ref/specalternative syntax for definitionscb8f4f5
  • doc/ref/specharmonize list and struct comprehensionde0c53d

encoding10

  • encoding/jsonschemafix a few json schema bugsf395f12
  • encoding/jsonschemaimprove handling of $id and $refb5b7521
  • encoding/jsonschemaintroduce extra pass for metadatafaf1dfc
  • encoding/jsonschemause astutil.Sanitize to handle imports53e5561
  • encoding/jsonschemause new definition mapping435989a
  • encoding/openapimake title and version defaultsa85238c
  • encoding/openapiupdate to new-style definitions98aaff9
  • encoding/protobuffix typo in example0212bb9
  • encoding/protobufmove to new-style definitions2b118fb
  • encoding/yamluse idiomatic indentation (regression)3970555

Other7

  • Update broken link in tutorial docs README.mdf1c757f
  • allre-run go generate using Go 1.14.3238d821
  • depsput all tool deps in root go.mod filee027d80
  • internal/filetypesprint attributes for definitionsbe0649e
  • internalfactor out FileComment code4d8d154
  • testdataconvert old tests to txtar format0d4abd7
  • tools/trimfix package docbe60cd9

Downloads

Every file this release published on GitHub, with its SHA-256. Most people install CUE as Installing CUE describes, which also shows how to check a download.

Archives

PlatformFile and SHA-256
macOS, Intelcue_0.2.0_Darwin_x86_64.tar.gzf38412b855bf5c3b97d2c7358ebaaccc088b707158809bd0fce889bbe050ba61
Linux, Arm64cue_0.2.0_Linux_arm64.tar.gz8e66dc78c1cda1598c0f066d7f87ee0df4d74c0e1a74ea98ecca5bff28fa25e0
Linux, x86-64cue_0.2.0_Linux_x86_64.tar.gz36c454c8ab48e3fe1d0bb10a461b8b4e362566b50048a5e2808e221248f373d5
Windows, x86-64cue_0.2.0_Windows_x86_64.zip2d1d7f45c61808ba83692f1aefe804894e19d032aec06a91475cb5923bfa6bc4

SHA-256 checksums for all of these: checksums.txt

Install CUE