···1313aimed at improving the overall experience of putting
1414configurations to good use.
15151616-Features highlights:
1616+Some highlights:
17171818- JSON superset: get started quickly
1919- convert existing YAML and JSON
2020+- arbitrary-precision arithmetic
2021- reformatter
2122- automatically simplify configurations
2223- powerful scripting
+487
doc/cmd/cue.md
···11+# `cue` command reference
22+33+This documentation is a formatted from of the builtin documentation of the
44+cue help command.
55+66+## General usage
77+88+```
99+cue [command]
1010+```
1111+1212+The commands are:
1313+1414+```
1515+ cmd run a user-defined shell command
1616+ eval evaluate a configuration file
1717+ export outputs an evaluated configuration in a standard format
1818+ extract
1919+ fmt formats Cue configuration files.
2020+ help Help about any command
2121+ import convert other data formats to CUE files
2222+ list list packages or modules
2323+ serve starts a builtin or user-defined service
2424+2525+Flags:
2626+ --config string config file (default is $HOME/.cue)
2727+ --debug give detailed error info
2828+ -h, --help help for cue
2929+ --pkg string CUE package to evaluate
3030+ --root load a Cue package from its root
3131+```
3232+3333+## Start a bug report
3434+3535+TODO
3636+3737+## Evaluate a CUE file
3838+3939+```
4040+Flags:
4141+ --pkg string Cue package to evaluate
4242+```
4343+4444+## Formatting CUE files
4545+4646+`fmt` formats the given files or the files for the given packages in place.
4747+4848+Usage:
4949+```
5050+ cue fmt [-s] [packages] [flags]
5151+```
5252+Flags:
5353+```
5454+ --config string config file (default is $HOME/.cue)
5555+ --debug give detailed error info
5656+ -n, --dryrun only run simulation
5757+ -p, --package string Cue package to evaluate
5858+ -s, --simplify simplify output
5959+```
6060+6161+## Exporting results
6262+6363+`export` evaluates the configuration found in the current directory
6464+and prints the emit value to stdout.
6565+6666+Examples:
6767+Evaluated and emit
6868+6969+```
7070+ # a single file
7171+ cue export config.cue
7272+7373+ # multiple files: these are combined at the top-level.
7474+ # Order doesn't matter.
7575+ cue export file1.cue foo/file2.cue
7676+7777+ # all files within the "mypkg" package: this includes all files
7878+ # in the current directory and its ancestor directories that are marked
7979+ # with the same package.
8080+ cue export -p cloud
8181+8282+ # the -p flag can be omitted if the directory only contains files for
8383+ # the "mypkg" package.
8484+ cue export
8585+```
8686+8787+### Emit value
8888+8989+For CUE files, the generated configuration is derived from the top-level single expression, the emit value. For example, the file
9090+9191+```
9292+ // config.cue
9393+ arg1: 1
9494+ arg2: "my string"
9595+9696+ {
9797+ a: arg1
9898+ b: arg2
9999+ }
100100+ ```
101101+yields the following JSON:
102102+```
103103+ {
104104+ "a": 1,
105105+ "b": "my string"
106106+ }
107107+```
108108+In absence of arguments, the current directory is loaded as a package instance.
109109+A package instance for a directory contains all files in the directory and its
110110+ancestor directories, up to the module root, belonging to the same package.
111111+112112+If the package is not explicitly defined by the '-p' flag, it must be uniquely
113113+defined by the files in the current directory.
114114+115115+## Import files in another format
116116+117117+`import` converts other data formats, like JSON and YAML to CUE files.
118118+The following file formats are currently supported:
119119+120120+```
121121+ Format Extensions
122122+ JSON .json .jsonl .ndjson
123123+ YAML .yaml .yml
124124+```
125125+126126+Files can either be specified explicitly, or inferred from the specified
127127+packages.
128128+In either case, the file extension is replaced with `.cue`.
129129+It will fail if the file already exists by default.
130130+The -f flag overrides this.
131131+132132+Examples:
133133+134134+```
135135+ # Convert individual files:
136136+ $ cue import foo.json bar.json # create foo.yaml and bar.yaml
137137+138138+ # Convert all json files in the indicated directories:
139139+ $ cue import ./... -type=json
140140+```
141141+142142+143143+### The `--path` flag
144144+145145+By default the parsed files are included as emit values.
146146+This default can be overridden by specifying a path, which has two forms:
147147+148148+```
149149+ -p ident*
150150+```
151151+152152+ and
153153+```
154154+ -p ident "->" expr*
155155+```
156156+157157+The first form specifies a fixed path.
158158+The empty path indicates including the value at the root.
159159+The second form allows expressing the path in terms of the imported value.
160160+An unbound identifier in the second form denotes a fixed name.
161161+Packages may be included with the -imports flag.
162162+Imports for top-level core packages are elided.
163163+164164+165165+### Handling multiple documents or streams
166166+167167+To handle Multi-document files, such as concatenated JSON objects or YAML files
168168+with document separators (---) the user must specify either the -path, -list, or
169169+-files flag.
170170+The -path flag assign each element to a path (identical paths are
171171+treated as usual); -list concatenates the entries, and -files causes each entry
172172+to be written to a different file.
173173+The -files flag may only be used if files are explicitly imported.
174174+The -list flag may be used in combination with the -path
175175+flag, concatenating each entry to the mapped location.
176176+177177+Examples:
178178+179179+```
180180+ $ cat <<EOF > foo.yaml
181181+ kind: Service
182182+ name: booster
183183+ EOF
184184+185185+ # include the parsed file as an emit value:
186186+ $ cue import foo.yaml
187187+ $ cat foo.cue
188188+ {
189189+ kind: Service
190190+ name: booster
191191+ }
192192+193193+ # include the parsed file at the root of the Cue file:
194194+ $ cue import -f -p "" foo.yaml
195195+ $ cat foo.cue
196196+ kind: Service
197197+ name: booster
198198+199199+ # include the import config at the mystuff path
200200+ $ cue import -f -p mystuff foo.yaml
201201+ $ cat foo.cue
202202+ myStuff: {
203203+ kind: Service
204204+ name: booster
205205+ }
206206+207207+ # append another object to the input file
208208+ $ cat <<EOF >> foo.yaml
209209+ ---
210210+ kind: Deployment
211211+ name: booster
212212+ replicas: 1
213213+214214+ # base the path values on th input
215215+ $ cue import -f -p "x -> strings.ToLower(x.kind) x.name" foo.yaml
216216+ $ cat foo.cue
217217+ service booster: {
218218+ kind: "Service"
219219+ name: "booster"
220220+ }
221221+222222+ deployment booster: {
223223+ kind: "Deployment"
224224+ name: "booster
225225+ replicas: 1
226226+ }
227227+228228+ # base the path values on th input
229229+ $ cue import -f -list -foo.yaml
230230+ $ cat foo.cue
231231+ [{
232232+ kind: "Service"
233233+ name: "booster"
234234+ }, {
235235+ kind: "Deployment"
236236+ name: "booster
237237+ replicas: 1
238238+ }]
239239+240240+ # base the path values on th input
241241+ $ cue import -f -list -p "x->strings.ToLower(x.kind)" foo.yaml
242242+ $ cat foo.cue
243243+ service: [{
244244+ kind: "Service"
245245+ name: "booster"
246246+ }
247247+ deployment: [{
248248+ kind: "Deployment"
249249+ name: "booster
250250+ replicas: 1
251251+ }]
252252+```
253253+254254+Usage:
255255+```
256256+ cue import [flags]
257257+```
258258+259259+Flags:
260260+```
261261+ --dryrun force overwriting existing files
262262+ --files force overwriting existing files
263263+ --fix string apply given fix
264264+ -f, --force force overwriting existing files
265265+ -h, --help help for import
266266+ --list concatenate multiple objects into a list
267267+ -n, --name string glob filter for file names
268268+ -o, --out string alternative output or - for stdout
269269+ -p, --path string path to include root
270270+ --type string only apply to files of this type
271271+```
272272+273273+## Extracting CUE files from source code
274274+275275+TODO: doc
276276+277277+## Running scripts with CUE
278278+279279+`cmd` executes user-defined named commands for each of the listed instances.
280280+281281+Commands define actions on instances.
282282+For instance, they may define how to upload a configuration to Kubernetes.
283283+Commands are defined in cue files ending with `_tool.cue` while otherwise using
284284+the same packaging rules: tool files must have a matching package clause and
285285+the same rules as for normal files define which will be included in which
286286+package.
287287+Tool files have access to the package scope, but none of the fields defined
288288+in a tool file influence the output of a package.
289289+Tool files are typically defined at the module root so that they apply
290290+to all instances.
291291+292292+293293+### Tasks
294294+295295+Each command consists of one or more tasks.
296296+A task may load or write a file, consult a user on the command line,
297297+or fetch a web page, and so on.
298298+Each task has inputs and outputs.
299299+Outputs are typically are typically filled out by the task implementation as
300300+the task completes.
301301+302302+Inputs of tasks my refer to outputs of other tasks.
303303+The cue tool does a static analysis of the configuration and only starts tasks
304304+that are fully specified.
305305+Upon completion of each task, cue rewrites the instance,
306306+filling in the completed task, and reevaluates which other tasks can now start,
307307+and so on until all tasks have completed.
308308+309309+310310+### Command definition
311311+312312+Commands are defined at the top-level of the configuration and all follow the
313313+following pattern:
314314+315315+```
316316+command <Name>: { // from "cue/tool".Command
317317+ // usage gives a short usage pattern of the command.
318318+ // Example:
319319+ // fmt [-n] [-x] [packages]
320320+ usage: Name | string
321321+322322+ // short gives a brief on-line description of the command.
323323+ // Example:
324324+ // reformat package sources
325325+ short: "" | string
326326+327327+ // long gives a detailed description of the command, including
328328+ // a description of flags usage and examples.
329329+ long: "" | string
330330+331331+ // A task defines a single action to be run as part of this command.
332332+ // Each task can have inputs and outputs, depending on the type
333333+ // task. The outputs are initially unspecified, but are filled out
334334+ // by the tooling
335335+ //
336336+ task <Name>: { // from "cue/tool".Task
337337+ // supported fields depend on type
338338+ }
339339+340340+ VarValue = string | bool | int | float | [...string|int|float]
341341+342342+ // var declares values that can be set by command line flags or
343343+ // environment variables.
344344+ //
345345+ // Example:
346346+ // // environment to run in
347347+ // var env: "test" | "prod"
348348+ // The tool would print documentation of this flag as:
349349+ // Flags:
350350+ // --env string environment to run in: test(default) or prod
351351+ var <Name>: VarValue
352352+353353+ // flag defines a command line flag.
354354+ //
355355+ // Example:
356356+ // var env: "test" | "prod"
357357+ //
358358+ // // augment the flag information for var
359359+ // flag env: {
360360+ // shortFlag: "e"
361361+ // description: "environment to run in"
362362+ // }
363363+ //
364364+ // The tool would print documentation of this flag as:
365365+ // Flags:
366366+ // -e, --env string environment to run in: test(default), staging, or prod
367367+ //
368368+ flag <Name>: { // from "cue/tool".Flag
369369+ // value defines the possible values for this flag.
370370+ // The default is string. Users can define default values by
371371+ // using disjunctions.
372372+ value: env[Name].value | VarValue
373373+374374+ // name, if set, allows var to be set with the command-line flag
375375+ // of the given name. null disables the command line flag.
376376+ name: Name | null | string
377377+378378+ // short defines an abbreviated version of the flag.
379379+ // Disabled by default.
380380+ short: null | string
381381+ }
382382+383383+ // populate flag with the default values for
384384+ flag: { "\(k)": { value: v } | null for k, v in var }
385385+386386+ // env defines environment variables. It is populated with values
387387+ // for var.
388388+ //
389389+ // To specify a var without an equivalent environment variable,
390390+ // either specify it as a flag directly or disable the equally
391391+ // named env entry explicitly:
392392+ //
393393+ // var foo: string
394394+ // env foo: null // don't use environment variables for foo
395395+ //
396396+ env <Name>: {
397397+ // name defines the environment variable that sets this flag.
398398+ name: "CUE_VAR_" + strings.Upper(Name) | string | null
399399+400400+ // The value retrieved from the environment variable or null
401401+ // if not set.
402402+ value: null | string | bytes
403403+ }
404404+ env: { "\(k)": { value: v } | null for k, v in var }
405405+ }
406406+```
407407+408408+Available tasks can be found in the package documentation at
409409+410410+```
411411+ cmd/cue/tool/tasks.
412412+ ```
413413+414414+More on tasks can be found in the tasks topic.
415415+416416+Examples
417417+A simple file using command line execution:
418418+419419+hello.cue:
420420+```
421421+ package foo
422422+423423+ import "cue/tool/tasks/exec"
424424+425425+ city: "Amsterdam"
426426+```
427427+428428+hello_tool.cue:
429429+```
430430+ package foo
431431+432432+ // Say hello!
433433+ command hello: {
434434+ // whom to say hello to
435435+ var who: "World" | string
436436+437437+ task print: exec.Run({
438438+ cmd: "echo Hello \(var.who)! Welcome to \(city)."
439439+ })
440440+ }
441441+ ```
442442+443443+Invoking the script on the command line:
444444+445445+```
446446+ $ cue cmd echo
447447+ Hello World! Welcome to Amsterdam.
448448+449449+ $ cue cmd echo -who you
450450+ Hello you! Welcome to Amsterdam.
451451+ ```
452452+An example with tasks depending on each other:
453453+454454+```
455455+package foo
456456+457457+import "cue/tool/tasks/exec"
458458+459459+city: "Amsterdam"
460460+461461+// Say hello!
462462+command hello: {
463463+ var file: "out.txt" | string // save transcript to this file
464464+465465+ task ask: cli.Ask({
466466+ prompt: "What is your name?"
467467+ response: string
468468+ })
469469+470470+ // starts after ask
471471+ task echo: exec.Run({
472472+ cmd: "echo Hello \(task.ask.response)!"]
473473+ stdout: string // capture stdout
474474+ })
475475+476476+ // starts after echo
477477+ task write: file.Append({
478478+ filename: var.file
479479+ contents: task.echo.stdout
480480+ })
481481+482482+ // also starts after echo
483483+ task print: cli.Print({
484484+ contents: task.echo.stdout
485485+ })
486486+}
487487+```
+6-6
doc/contribute.md
···256256257257<p>
258258Whether you already know what contribution to make, or you are searching for
259259-an idea, the <a href="https://github.com/cuelang/core/issues">issue tracker</a> is
259259+an idea, the <a href="https://github.com/cuelang/cue/issues">issue tracker</a> is
260260always the first place to go.
261261Issues are triaged to categorize them and manage the workflow.
262262</p>
···290290291291<ul>
292292 <li>
293293- Issues that need investigation: <a href="https://github.com/cuelang/core/issues?q=is%3Aissue+is%3Aopen+label%3ANeedsInvestigation"><code>is:issue is:open label:NeedsInvestigation</code></a>
293293+ Issues that need investigation: <a href="https://github.com/cuelang/cue/issues?q=is%3Aissue+is%3Aopen+label%3ANeedsInvestigation"><code>is:issue is:open label:NeedsInvestigation</code></a>
294294 </li>
295295 <li>
296296- Issues that need a fix: <a href="https://github.com/cuelang/core/issues?q=is%3Aissue+is%3Aopen+label%3ANeedsFix"><code>is:issue is:open label:NeedsFix</code></a>
296296+ Issues that need a fix: <a href="https://github.com/cuelang/cue/issues?q=is%3Aissue+is%3Aopen+label%3ANeedsFix"><code>is:issue is:open label:NeedsFix</code></a>
297297 </li>
298298 <li>
299299- Issues that need a fix and have a CL: <a href="https://github.com/cuelang/core/issues?q=is%3Aissue+is%3Aopen+label%3ANeedsFix+%22golang.org%2Fcl%22"><code>is:issue is:open label:NeedsFix "cuelang.org/cl"</code></a>
299299+ Issues that need a fix and have a CL: <a href="https://github.com/cuelang/cue/issues?q=is%3Aissue+is%3Aopen+label%3ANeedsFix+%22golang.org%2Fcl%22"><code>is:issue is:open label:NeedsFix "cuelang.org/cl"</code></a>
300300 </li>
301301 <li>
302302- Issues that need a fix and do not have a CL: <a href="https://github.com/cuelang/core/issues?q=is%3Aissue+is%3Aopen+label%3ANeedsFix+NOT+%22golang.org%2Fcl%22"><code>is:issue is:open label:NeedsFix NOT "cuelang.org/cl"</code></a>
302302+ Issues that need a fix and do not have a CL: <a href="https://github.com/cuelang/cue/issues?q=is%3Aissue+is%3Aopen+label%3ANeedsFix+NOT+%22golang.org%2Fcl%22"><code>is:issue is:open label:NeedsFix NOT "cuelang.org/cl"</code></a>
303303 </li>
304304</ul>
305305···882882Files in the CUE repository don't list author names, both to avoid clutter
883883and to avoid having to keep the lists up to date.
884884Instead, your name will appear in the
885885-<a href="https://cue.googlesource.com/core/+log">change log</a> and in the <a
885885+<a href="https://cue.googlesource.com/cue/+log">change log</a> and in the <a
886886href="/CONTRIBUTORS"><code>CONTRIBUTORS</code></a> file and perhaps the <a
887887href="/AUTHORS"><code>AUTHORS</code></a> file.
888888These files are automatically generated from the commit logs periodically.
+38
doc/install.md
···11+# Getting Started
22+33+Currently CUE can only be installed from source.
44+55+## Install CUE from source
66+77+### Prerequisites
88+99+Go 1.10 or higher (see below)
1010+1111+### Installing CUE
1212+1313+To download and install the `cue` command line tool run
1414+1515+```
1616+go get -u cuelang.org/go/cmd/cue
1717+```
1818+1919+And make sure the install directory is in your path.
2020+2121+To also download the API and documentation, run
2222+2323+```
2424+go get -u cuelang.org/go/cue
2525+```
2626+2727+2828+### Installing Go
2929+3030+#### Download Go
3131+3232+You can load the binary for Windows, MacOS X, and Linux at https://golang.org/dl/. If you use a different OS you can install Go from source.
3333+3434+#### Install Go
3535+3636+Follow the instructions at https://golang.org/doc/install#install.
3737+Make sure the go binary is in your path.
3838+CUE uses Go modules, so there is no need to set up a GOPATH.
+2516
doc/ref/spec.md
···11+# The CUE Language Specification
22+33+## Introduction
44+55+This is a reference manual for the CUE configuration language.
66+CUE, pronounced cue or Q, is a general-purpose and strongly typed
77+configuration language.
88+The CUE tooling, layered on top of CUE, converts this language to
99+a general purpose scripting language for creating scripts as well as
1010+simple servers.
1111+1212+CUE was designed with cloud configuration, and related systems, in mind,
1313+but is not limited to this domain.
1414+It derives its formalism from relational programming languages.
1515+This formalism allows for managing and reasoning over large amounts of
1616+configuration in a straightforward manner.
1717+1818+The grammar is compact and regular, allowing for easy analysis by automatic
1919+tools such as integrated development environments.
2020+2121+This document is maintained by mpvl@golang.org.
2222+CUE has a lot of similarities with the Go language. This document draws heavily
2323+from the Go specification as a result, Copyright 2009–2018, The Go Authors.
2424+2525+CUE draws its influence from many languages.
2626+Its main influences were BCL/ GCL (internal to Google),
2727+LKB (LinGO), Go, and JSON.
2828+Others are Swift, Javascript, Prolog, NCL (internal to Google), Jsonnet, HCL,
2929+Flabbergast, JSONPath, Haskell, Objective-C, and Python.
3030+3131+3232+## Notation
3333+3434+The syntax is specified using Extended Backus-Naur Form (EBNF):
3535+3636+```
3737+Production = production_name "=" [ Expression ] "." .
3838+Expression = Alternative { "|" Alternative } .
3939+Alternative = Term { Term } .
4040+Term = production_name | token [ "…" token ] | Group | Option | Repetition .
4141+Group = "(" Expression ")" .
4242+Option = "[" Expression "]" .
4343+Repetition = "{" Expression "}" .
4444+```
4545+4646+Productions are expressions constructed from terms and the following operators,
4747+in increasing precedence:
4848+4949+```
5050+| alternation
5151+() grouping
5252+[] option (0 or 1 times)
5353+{} repetition (0 to n times)
5454+```
5555+5656+Lower-case production names are used to identify lexical tokens. Non-terminals
5757+are in CamelCase. Lexical tokens are enclosed in double quotes "" or back quotes
5858+``.
5959+6060+The form a … b represents the set of characters from a through b as
6161+alternatives. The horizontal ellipsis … is also used elsewhere in the spec to
6262+informally denote various enumerations or code snippets that are not further
6363+specified. The character … (as opposed to the three characters ...) is not a
6464+token of the Go language.
6565+6666+6767+## Source code representation
6868+6969+Source code is Unicode text encoded in UTF-8.
7070+Unless otherwise noted, the text is not canonicalized, so a single
7171+accented code point is distinct from the same character constructed from
7272+combining an accent and a letter; those are treated as two code points.
7373+For simplicity, this document will use the unqualified term character to refer
7474+to a Unicode code point in the source text.
7575+7676+Each code point is distinct; for instance, upper and lower case letters are
7777+different characters.
7878+7979+Implementation restriction: For compatibility with other tools, a compiler may
8080+disallow the NUL character (U+0000) in the source text.
8181+8282+Implementation restriction: For compatibility with other tools, a compiler may
8383+ignore a UTF-8-encoded byte order mark (U+FEFF) if it is the first Unicode code
8484+point in the source text. A byte order mark may be disallowed anywhere else in
8585+the source.
8686+8787+8888+### Characters
8989+9090+The following terms are used to denote specific Unicode character classes:
9191+9292+```
9393+newline = /* the Unicode code point U+000A */ .
9494+unicode_char = /* an arbitrary Unicode code point except newline */ .
9595+unicode_letter = /* a Unicode code point classified as "Letter" */ .
9696+unicode_digit = /* a Unicode code point classified as "Number, decimal digit" */ .
9797+```
9898+9999+In The Unicode Standard 8.0, Section 4.5 "General Category" defines a set of
100100+character categories.
101101+CUE treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo
102102+as Unicode letters, and those in the Number category Nd as Unicode digits.
103103+104104+105105+### Letters and digits
106106+107107+The underscore character _ (U+005F) is considered a letter.
108108+109109+```
110110+letter = unicode_letter | "_" .
111111+decimal_digit = "0" … "9" .
112112+octal_digit = "0" … "7" .
113113+hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
114114+```
115115+116116+117117+## Lexical elements
118118+119119+### Comments
120120+Comments serve as program documentation. There are two forms:
121121+122122+1. Line comments start with the character sequence // and stop at the end of the line.
123123+2. General comments start with the character sequence /* and stop with the first subsequent character sequence */.
124124+125125+A comment cannot start inside string literal or inside a comment.
126126+A general comment containing no newlines acts like a space.
127127+Any other comment acts like a newline.
128128+129129+130130+### Tokens
131131+132132+Tokens form the vocabulary of the CUE language. There are four classes:
133133+identifiers, keywords, operators and punctuation, and literals. White space,
134134+formed from spaces (U+0020), horizontal tabs (U+0009), carriage returns
135135+(U+000D), and newlines (U+000A), is ignored except as it separates tokens that
136136+would otherwise combine into a single token. Also, a newline or end of file may
137137+trigger the insertion of a comma. While breaking the input into tokens, the
138138+next token is the longest sequence of characters that form a valid token.
139139+140140+141141+### Commas
142142+143143+The formal grammar uses commas "," as terminators in a number of productions.
144144+CUE programs may omit most of these commas using the following two rule:
145145+146146+When the input is broken into tokens, a comma is automatically inserted into
147147+the token stream immediately after a line's final token if that token is
148148+149149+ - an identifier
150150+ - null, true, false, bottom, an integer, a floating-point, or string literal
151151+ - one of the punctuation ), ], or }
152152+153153+154154+Although commas are automatically inserted, the parser will require
155155+explicit commas between two list elements.
156156+157157+To reflect idiomatic use, examples in this document elide commas using
158158+these rules.
159159+160160+161161+### Identifiers
162162+163163+Identifiers name entities such as fields and aliases.
164164+An identifier is a sequence of one or more letters and digits.
165165+It may not be `_`.
166166+The first character in an identifier must be a letter.
167167+168168+<!--
169169+TODO: allow identifiers as defined in Unicode UAX #31
170170+(https://unicode.org/reports/tr31/).
171171+172172+Identifiers are normalized using the NFC normal form.
173173+-->
174174+175175+```
176176+identifier = letter { letter | unicode_digit } .
177177+```
178178+179179+```
180180+a
181181+_x9
182182+fieldName
183183+αβ
184184+```
185185+186186+<!-- TODO: Allow Unicode identifiers TR 32 http://unicode.org/reports/tr31/ -->
187187+188188+Some identifiers are [predeclared].
189189+190190+191191+### Keywords
192192+193193+CUE has a limited set of keywords.
194194+All keywords may be used as labels (field names).
195195+They cannot, however, be used as identifiers to refer to the same name.
196196+197197+198198+#### Values
199199+200200+The following keywords are values.
201201+202202+```
203203+null true false
204204+```
205205+206206+These can never be used to refer to a field of the same name.
207207+This restriction is to ensure compatibility with JSON configuration files.
208208+209209+210210+#### Preamble
211211+212212+The following pseudo keywords are used at the preamble of a CUE file.
213213+After the preamble, they may be used as identifiers to refer to namesake fields.
214214+215215+```
216216+package import
217217+```
218218+219219+220220+#### Comprehension clauses
221221+222222+The following pseudo keywords are used in comprehensions.
223223+224224+```
225225+for in if let
226226+```
227227+228228+The pseudo keywords `for`, `if` and `let` cannot be used as identifiers to
229229+refer to fields. All others can.
230230+231231+<!--
232232+TODO:
233233+ reduce [to]
234234+ order [by]
235235+-->
236236+237237+238238+#### Arithmetic
239239+240240+The following pseudo keywords can be used as operators in expressions.
241241+242242+```
243243+div mod quo rem
244244+```
245245+246246+These may be used as identifiers to refer to fields in all other contexts.
247247+248248+249249+### Operators and punctuation
250250+251251+The following character sequences represent operators and punctuation:
252252+253253+```
254254++ & && == != ( )
255255+- | || < <= [ ]
256256+* : ! > >= { }
257257+/ :: ; = ... .. .
258258+div mod quo rem _|_ <- ,
259259+```
260260+Optional:
261261+```
262262+-> ⊥
263263+```
264264+265265+266266+### Integer literals
267267+268268+An integer literal is a sequence of digits representing an integer value.
269269+An optional prefix sets a non-decimal base: 0 for octal,
270270+0x or 0X for hexadecimal, and 0b for binary.
271271+In hexadecimal literals, letters a-f and A-F represent values 10 through 15.
272272+All integers allow intersticial underscores "_";
273273+these have no meaning and are solely for readability.
274274+275275+Decimal integers may have a SI or IEC multiplier.
276276+Multipliers can be used with fractional numbers.
277277+The result of multiplying the fraction with the multiplier is truncated
278278+towards zero if the result is not an integer.
279279+280280+```
281281+int_lit = decimal_lit | octal_lit | binary_lit | hex_lit .
282282+decimals = ( "0" … "9" ) { [ "_" ] decimal_digit } .
283283+decimal_lit = ( "1" … "9" ) { [ "_" ] decimal_digit } [ [ "." decimals ] multiplier ] |
284284+ "." decimals multiplier.
285285+octal_lit = "0" octal_digit { [ "_" ] octal_digit } .
286286+binary_lit = "0b" binary_digit { binary_digit } .
287287+hex_lit = "0" ( "x" | "X" ) hex_digit { [ "_" ] hex_digit } .
288288+multiplier = "k" | "Ki" | ( "M" | "G" | "T" | "P" | "E" | "Y" | "Z" ) [ "i" ]
289289+```
290290+<!--
291291+TODO: consider 0o766 notation for octal.
292292+--->
293293+294294+```
295295+42
296296+1.5Gi
297297+0600
298298+0xBad_Face
299299+170_141_183_460_469_231_731_687_303_715_884_105_727
300300+```
301301+302302+### Decimal floating-point literals
303303+304304+A decimal floating-point literal is a representation of
305305+a decimal floating-point value.
306306+We will refer to those as floats.
307307+It has an integer part, a decimal point, a fractional part, and an
308308+exponent part.
309309+The integer and fractional part comprise decimal digits; the
310310+exponent part is an `e` or `E` followed by an optionally signed decimal exponent.
311311+One of the integer part or the fractional part may be elided; one of the decimal
312312+point or the exponent may be elided.
313313+314314+```
315315+decimal_lit = decimals "." [ decimals ] [ exponent ] |
316316+ decimals exponent |
317317+ "." decimals [ exponent ] .
318318+exponent = ( "e" | "E" ) [ "+" | "-" ] decimals .
319319+```
320320+321321+```
322322+0.
323323+72.40
324324+072.40 // == 72.40
325325+2.71828
326326+1.e+0
327327+6.67428e-11
328328+1E6
329329+.25
330330+.12345E+5
331331+```
332332+333333+334334+### String literals
335335+A string literal represents a string constant obtained from concatenating a
336336+sequence of characters. There are three forms: raw string literals and
337337+interpreted strings and bytes sequences.
338338+339339+Raw string literals are character sequences between back quotes, as in
340340+```
341341+`foo`
342342+```
343343+Within the quotes, any character may appear except back quote. The value of a
344344+raw string literal is the string composed of the uninterpreted (implicitly
345345+UTF-8-encoded) characters between the quotes; in particular, backslashes have no
346346+special meaning and the string may contain newlines. Carriage return characters
347347+(`\r`) inside raw string literals are discarded from the raw string value.
348348+349349+Interpreted string and byte sequence literals are character sequences between,
350350+respectively, double and single quotes, as in `"bar"` and `'bar'`.
351351+Within the quotes, any character may appear except newline and,
352352+respectively, unescaped double or single quote.
353353+String literals may only be valid UTF-8.
354354+Byte sequences may contain any sequence of bytes.
355355+356356+Several backslash escapes allow arbitrary values to be encoded as ASCII text
357357+in interpreted strings.
358358+There are four ways to represent the integer value as a numeric constant: `\x`
359359+followed by exactly two hexadecimal digits; \u followed by exactly four
360360+hexadecimal digits; `\U` followed by exactly eight hexadecimal digits, and a
361361+plain backslash `\` followed by exactly three octal digits.
362362+In each case the value of the literal is the value represented by the
363363+digits in the corresponding base.
364364+Hexadecimal and octal escapes are only allowed within byte sequences
365365+(single quotes).
366366+367367+Although these representations all result in an integer, they have different
368368+valid ranges.
369369+Octal escapes must represent a value between 0 and 255 inclusive.
370370+Hexadecimal escapes satisfy this condition by construction.
371371+The escapes `\u` and `\U` represent Unicode code points so within them
372372+some values are illegal, in particular those above `0x10FFFF`.
373373+Surrogate halves are allowed to be compatible with JSON,
374374+but are translated into their non-surrogate equivalent internally.
375375+376376+The three-digit octal (`\nnn`) and two-digit hexadecimal (`\xnn`) escapes
377377+represent individual bytes of the resulting string; all other escapes represent
378378+the (possibly multi-byte) UTF-8 encoding of individual characters.
379379+Thus inside a string literal `\377` and `\xFF` represent a single byte of
380380+value `0xFF=255`, while `ÿ`, `\u00FF`, `\U000000FF` and `\xc3\xbf` represent
381381+the two bytes `0xc3 0xbf` of the UTF-8
382382+encoding of character `U+00FF`.
383383+384384+After a backslash, certain single-character escapes represent special values:
385385+386386+```
387387+\a U+0007 alert or bell
388388+\b U+0008 backspace
389389+\f U+000C form feed
390390+\n U+000A line feed or newline
391391+\r U+000D carriage return
392392+\t U+0009 horizontal tab
393393+\v U+000b vertical tab
394394+\\ U+005c backslash
395395+\' U+0027 single quote (valid escape only within single quoted literals)
396396+\" U+0022 double quote (valid escape only within double quoted literals)
397397+```
398398+399399+The escape `\(` is used as an escape for string interpolation.
400400+A `\(` must be followed by a valid CUE Expression, followed by a `)`.
401401+402402+All other sequences starting with a backslash are illegal inside literals.
403403+404404+```
405405+escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
406406+unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
407407+byte_value = octal_byte_value | hex_byte_value .
408408+octal_byte_value = `\` octal_digit octal_digit octal_digit .
409409+hex_byte_value = `\` "x" hex_digit hex_digit .
410410+little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .
411411+big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit
412412+ hex_digit hex_digit hex_digit hex_digit .
413413+414414+string_lit = raw_string_lit |
415415+ interpreted_string_lit |
416416+ interpreted_bytes_lit |
417417+ multiline_lit .
418418+interpolation = "\(" Expression ")" .
419419+raw_string_lit = "`" { unicode_char | newline } "`" .
420420+interpreted_string_lit = `"` { unicode_value | interpolation } `"` .
421421+interpreted_bytes_lit = `"` { unicode_value | interpolation | byte_value } `"` .
422422+```
423423+424424+```
425425+`abc` // same as "abc"
426426+`\n
427427+\n` // same as "\\n\n\\n"
428428+'a\000\xab'
429429+'\007'
430430+'\377'
431431+'\xa' // illegal: too few hexadecimal digits
432432+"\n"
433433+"\"" // same as `"`
434434+'Hello, world!\n'
435435+"Hello, \( name )!"
436436+"日本語"
437437+"\u65e5本\U00008a9e"
438438+"\xff\u00FF"
439439+"\uD800" // illegal: surrogate half
440440+"\U00110000" // illegal: invalid Unicode code point
441441+```
442442+443443+These examples all represent the same string:
444444+445445+```
446446+"日本語" // UTF-8 input text
447447+'日本語' // UTF-8 input text as byte sequence
448448+`日本語` // UTF-8 input text as a raw literal
449449+"\u65e5\u672c\u8a9e" // the explicit Unicode code points
450450+"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points
451451+"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
452452+```
453453+454454+If the source code represents a character as two code points, such as a
455455+combining form involving an accent and a letter, the result will appear as two
456456+code points if placed in a string literal.
457457+458458+Each of the interpreted string variants have a multiline equivalent.
459459+Multiline interpreted strings are like their single-line equivalent,
460460+but allow newline characters.
461461+Carriage return characters (`\r`) inside raw string literals are discarded from
462462+the raw string value.
463463+464464+Multiline interpreted strings and byte sequences respectively start with
465465+a triple double quote (`"""`) or triple single quote (`'''`),
466466+immediately followed by a newline, which is discarded from the string contents.
467467+The string is closed by a matching triple quote, which must be by itself
468468+on a newline, preceded by optional whitespace.
469469+The whitespace before a closing triple quote must appear before any non-empty
470470+line after the opening quote and will be removed from each of these
471471+lines in the string literal.
472472+A closing triple quote may not appear in the string.
473473+To include it is suffices to escape one of the quotes.
474474+475475+```
476476+multiline_lit = multiline_string_lit | multiline_bytes_lit .
477477+multiline_string_lit = `"""` newline
478478+ { unicode_char | interpolation | newline }
479479+ newline `"""` .
480480+multiline_bytes_lit = "'''" newline
481481+ { unicode_char | interpolation | newline | byte_value }
482482+ newline "'''" .
483483+```
484484+485485+```
486486+"""
487487+ lily:
488488+ out of the water
489489+ out of itself
490490+491491+ bass
492492+ picking bugs
493493+ off the moon
494494+ — Nick Virgilio, Selected Haiku, 1988
495495+ """
496496+```
497497+498498+This represents the same string as:
499499+500500+```
501501+"lily:\nout of the water\nout of itself\n\n" +
502502+"bass\npicking bugs\noff the moon\n" +
503503+" — Nick Virgilio, Selected Haiku, 1988"
504504+```
505505+506506+<!-- TODO: other values
507507+508508+Support for other values:
509509+- Duration literals
510510+- regualr expessions: `re("[a-z]")`
511511+-->
512512+513513+## Prototypes
514514+515515+CUE defines basic types and structs. The _basic types_ are null, bool,
516516+int, float, string, and bytes.
517517+A _struct_ is a map from a label to a value, where the value may be of any
518518+type.
519519+Lists, provided by CUE as a convenience, are special cases of structs and
520520+are not included in the definition of the type system.
521521+522522+In CUE, all possible types and values are partially ordered in a lattice.
523523+CUE does not distinguish between types and values, only between
524524+concrete and partially defined instances of a certain type.
525525+526526+For example `string` is the identifier used to set of all possible strings.
527527+The string `"hello"` is an instance of such a string and ordered below
528528+this string. The value `42` is not an instance of `string`.
529529+530530+531531+### Ordering and lattices
532532+533533+All possible prototypes are ordered in a lattice,
534534+a partial order where every two elements have a single greatest lower bound.
535535+A value `a` is said to be _greater_ than `b` if `a` orders before `b` in this
536536+partial order.
537537+At the top of this lattice is the single ancestor of all values, called
538538+_top_, denoted `_` in CUE.
539539+At the bottom of this lattice is the value called _bottom_, denoted `_|_`.
540540+A bottom value usually indicates an error.
541541+542542+We say that for any two prototypes `a` and `b` that `a` is an _instance_ of `b`,
543543+denoted `a ⊑ b`, if `b == a` or `b` is more general than `a`
544544+that is if `a` orders before `b` in the partial order
545545+(`⊑` is _not_ a CUE operator).
546546+We also say that `b` subsumes `a` in this case.
547547+548548+549549+An _atom_ is any value whose only instance is itself and bottom. Examples of
550550+atoms are `42`, `"hello"`, `true`, `null`.
551551+552552+A _type_ is any value which is only an instance of itself or top.
553553+This includes `null`: the null value, `bool`: all possible boolean values,
554554+`int`: all integral numbers, `float`, `string`, `bytes`, and `{}`.
555555+556556+A _concrete value_ is any atom or struct with fields of which the values
557557+are itself concrete values, recursively.
558558+A concrete value corresponds to a valid JSON value
559559+560560+A _prototype_ is any concrete value, type, or any instance of a type
561561+that is not a concrete value.
562562+We will informally refer to a prototype as _value_.
563563+564564+565565+```
566566+false ⊑ bool
567567+true ⊑ bool
568568+true ⊑ true
569569+5 ⊑ int
570570+bool ⊑ _
571571+⊥ ⊑ _
572572+⊥ ⊑ ⊥
573573+574574+_ ⋢ ⊥
575575+_ ⋢ bool
576576+int ⋢ bool
577577+bool ⋢ int
578578+false ⋢ true
579579+true ⋢ false
580580+int ⋢ 5
581581+5 ⋢ 6
582582+```
583583+584584+585585+### Unification
586586+587587+The _unification_ of values `a` and `b`, denoted as `a & b` in CUE,
588588+is defined as the value `u` such that `u ⊑ a` and `u ⊑ b`,
589589+while for any other value `u'` for which `u' ⊑ a` and `u' ⊑ b`
590590+it holds that `u' ⊑ u`.
591591+The value `u` is also called the _greatest lower bound_ of `a` and `b`.
592592+The greatest lower bound is, given the nature of lattices, always unique.
593593+The unification of `a` with itself is always `a`.
594594+The unification of a value `a` and `b` where `a ⊑ b` is always `a`.
595595+596596+Unification is commutative, transitive, and reflexive.
597597+As a consequence, order of evaluation is irrelevant, a property that is key
598598+to many of the constructs in the CUE language as well as the tooling layered
599599+on top of it.
600600+601601+Syntactically, unification is a [binary expression].
602602+603603+604604+### Disjunction
605605+606606+A _disjunction_ of two values `a` and `b`, denoted as `a | b` in CUE,
607607+is defined as the smallest value `d` such that `a ⊑ d` and `b ⊑ d`.
608608+The disjunction of `a` with itself is always `a`.
609609+The disjunction of a value `a` and `b` where `a ⊑ b` is always `b`.
610610+611611+Syntactically, disjunction is a [binary expression].
612612+613613+Implementations should report an error if for a disjunction `a | ... | b`,
614614+`b` is an instance of `a`, as `b` will be superfluous and can never
615615+be selected as a default.
616616+617617+A value that evaluates to bottom is removed from the disjunction.
618618+A disjunction evaluates to bottom if all of its values evaluate to bottom.
619619+620620+If a disjunction is used in any operation other than unification or another
621621+disjunction, the default value is chosen before operating on it.
622622+623623+```
624624+Expression Result (without picking default)
625625+(int | string) & "foo" "foo"
626626+("a" | "b") & "c" _|_
627627+628628+(3 | 5) + 2 5
629629+```
630630+631631+If the values of a disjunction are unambiguous, its first value may be taken
632632+as a default value.
633633+The default value for a disjunction is selected when:
634634+635635+1. passing it to an argument of a call or index value,
636636+1. using it in any unary or binary expression except for unification or disjunction,
637637+1. using it as the receiver of a call, index, slice, or selector expression, and
638638+1. a value is taken for a configuration.
639639+640640+A value is unambiguous if a disjunction has never been unified with another
641641+disjunction, or if the first element is the result of unifying two first
642642+values of a disjunction.
643643+644644+645645+```
646646+Expression Default
647647+("tcp"|"udp") & ("tcp"|"udp") "tcp" // default chosen
648648+("tcp"|"udp") & ("udp"|"tcp") _|_ // no unique default
649649+650650+("a"|"b") & ("b"|"a") & "a" "a" // single value after evaluation
651651+```
652652+653653+654654+### Bottom and errors
655655+Any evaluation error in CUE results in a bottom value, respresented by
656656+the identifier '⊥' or token '_|_', the latter mostly used for user input.
657657+Bottom is an instance of every other prototype.
658658+Any evaluation error is represented as bottom.
659659+660660+Implementations may associate error strings with different instances of bottom;
661661+logically they remain all the same value.
662662+663663+```
664664+Expr Result
665665+ 1 & 2 _|_
666666+int & bool _|_
667667+_|_ | 1 1
668668+_|_ & 2 _|_
669669+_|_ & _|_ _|_
670670+```
671671+672672+673673+### Top
674674+Top is represented by the underscore character '_', lexically an identifier.
675675+Unifying any value `v` with top results `v` itself.
676676+677677+```
678678+Expr Result
679679+_ & 5 5
680680+_ & _ _
681681+_ & _|_ _|_
682682+_ | _|_ _
683683+```
684684+685685+686686+### Null
687687+688688+The _null value_ is represented with the pseudo keyword `null`.
689689+It has only one parent, top, and one child, bottom.
690690+It is unordered with respect to any other prototype.
691691+692692+```
693693+null_lit = "null"
694694+```
695695+696696+```
697697+null & 8 ⊥
698698+```
699699+700700+701701+### Boolean values
702702+703703+A _boolean type_ represents the set of Boolean truth values denoted by
704704+the pseudo keywords `true` and `false`.
705705+The predeclared boolean type is `bool`; it is a defined type and a separate
706706+element in the lattice.
707707+708708+```
709709+boolean_lit = "true" | "false"
710710+```
711711+712712+```
713713+bool & true true
714714+bool | true true
715715+true | false true | false
716716+true & true true
717717+true & false ⊥
718718+```
719719+720720+721721+### Numeric values
722722+723723+An _integer type_ represents the set of all integral numbers.
724724+A _decimal floating-point type_ represents of all decimal floating-point
725725+numbers.
726726+They are two distinct types.
727727+The predeclared integer and decimal floating-point type are `int` and `float`;
728728+they are a defined type.
729729+730730+A decimal floating-point literal always has type `float`;
731731+it is not an instance of `int` even if it is an integral number.
732732+733733+An integer literal has both type `int` and `float`, with the integer variant
734734+being the default if no other constraints are applied.
735735+Expressed in terms of disjunction and [type conversion],
736736+the literal `1`, for instance, is defined as `int(1) | float(1)`.
737737+738738+Numeric values are exact values of arbitrary precision and do not overflow.
739739+Consequently, there are no constants denoting the IEEE-754 negative zero,
740740+infinity, and not-a-number values.
741741+742742+Implementation restriction: Although numeric values have arbitrary precision
743743+in the language, implementations may implement them using an internal
744744+representation with limited precision. That said, every implementation must:
745745+746746+Represent integer values with at least 256 bits.
747747+Represent floating-point values, with a mantissa of at least 256 bits and
748748+a signed binary exponent of at least 16 bits.
749749+Give an error if unable to represent an integer value precisely.
750750+Give an error if unable to represent a floating-point value due to overflow.
751751+Round to the nearest representable value if unable to represent
752752+a floating-point value due to limits on precision.
753753+These requirements apply to the result of any expression except builtin
754754+expressions where the loss of precision is remarked.
755755+756756+757757+### Strings
758758+759759+The _string type_ represents the set of all possible UTF-8 strings,
760760+not allowing surrogates.
761761+The predeclared string type is `string`; it is a defined type.
762762+763763+Strings are designed to be unicode-safe.
764764+Comparisson is done using canonical forms ("é" == "e\u0301").
765765+A string element is an extended grapheme cluster, which is an approximation
766766+of a human readable character.
767767+The length of a string is its number of extended grapheme clusters, and can
768768+be discovered using the built-in function `len`.
769769+770770+The length of a string `s` (its size in bytes) can be discovered using
771771+the built-in function len.
772772+A string's extended grapheme cluster can be accessed by integer index
773773+0 through len(s)-1 for any byte that is part of that grapheme cluster.
774774+To access the individual bytes of a string one should convert it to
775775+a sequence of bytes first.
776776+777777+778778+### Ranges
779779+780780+A _range type_, syntactically a [binary expression], defines
781781+a disjunction of concrete values that can be represented as a contiguous range.
782782+Ranges can be defined on numbers and strings.
783783+784784+The type of range `a..b` is the unification of the type of `a` and `b`.
785785+Note that this may be more than one type.
786786+787787+A range of numbers `a..b` defines an inclusive range for integers and
788788+floating-point numbers.
789789+790790+Remember that an integer literal represents both an `int` and `float`:
791791+```
792792+2 & 1..5 // 2, where 2 is either an int or float.
793793+2.5 & 1..5 // 2.5
794794+2.5 & int & 1..5 // ⊥
795795+2.5 & (int & 1)..5 // ⊥
796796+2.5 & float & 1..5 // 2.5
797797+0..7 & 3..10 // 3..7
798798+```
799799+800800+A range of strings `a..b` defines a set of strings that includes any `s`
801801+for which `NFC(a) <= NFC(s)` and `NFC(s) <= NFC(b)` in a byte-wise comparison,
802802+where `NFC` is the respective Unicode normal form.
803803+804804+805805+### Structs
806806+807807+A _struct_ is a set of named elements, called _fields_, each of
808808+which has a name, called a _label_, and value.
809809+Structs and fields respectively correspond to JSON objects and members.
810810+811811+We say a label is defined for a struct if the struct has a field with the
812812+corresponding label.
813813+We denote the value for a label `f` defined for `a` as `δ(f, a)`.
814814+815815+A struct `a` is an instance of `b`, or `a ⊑ b`, if for any label `f`
816816+defined for `b` label `f` is also defiend for `a` and `δ(f, a) ⊑ δ(f, b)`.
817817+Note that if `a` is an instance of `b` it may have fields with labels that
818818+are not defined for `b`.
819819+820820+The unification of structs `a` and `b` is defined as a new struct `c` which
821821+has all fields of `a` and `b` where the value is either the unification of the
822822+respective values where a field is contained in both or the original value
823823+for the respective fields of `a` or `b` otherwise.
824824+Any [references] to `a` or `b` in their respective field values need to be
825825+replaced with references to `c`.
826826+827827+Syntactically, a struct literal may contain multiple fields with
828828+the same label, the result of which is a single field with a value
829829+that is the result of unifying the values of those fields.
830830+831831+```
832832+StructLit = "{" [ { Declaration "," } Declaration ] "}" .
833833+Declaration = FieldDecl | AliasDecl .
834834+FieldDecl = Label { Label } ":" Expression .
835835+836836+AliasDecl = Label "=" Expression .
837837+Label = identifier | json_string | TemplateLabel | ExprLabel.
838838+TemplateLabel = "<" identifier ">" .
839839+ExprLabel = "[" Expression "]" .
840840+Tag = "#" identifier [ ":" json_string ] .
841841+json_string = `"` { unicode_value } `"`
842842+```
843843+844844+<!--
845845+TODO: consider using string interpolations for ExprLabel, instead of []
846846+So "\(k)" for [k]
847847+--->
848848+849849+850850+```
851851+{a: 1} ⊑ {}
852852+{a: 1, b: 1} ⊑ {a: 1}
853853+{a: 1} ⊑ {a: int}
854854+{a: 1, b: 1} ⊑ {a: int, b: float}
855855+856856+{} ⋢ {a: 1}
857857+{a: 2} ⋢ {a: 1}
858858+{a: 1} ⋢ {b: 1}
859859+```
860860+861861+```
862862+Expression Result
863863+{a: int, a: 1} {a: int(1)}
864864+{a: int} & {a: 1} {a: 1}
865865+{a: 1..7} & {a: 5..9} {a: 5..7}
866866+{a: 1..7, a: 5..9} {a: 5..7}
867867+868868+{a: 1} & {b: 2} {a: 1, b: 2}
869869+{a: 1, b: int} & {b: 2} {a: 1, b: 2}
870870+871871+{a: 1} & {a: 2} ⊥
872872+```
873873+874874+A struct literal may, besides fields, also define aliases.
875875+Aliases declare values that can be referred to within the [scope] of their
876876+definition, but are not part of the struct: aliases are irrelevant to
877877+the partial ordering of values and are not emitted as part of any
878878+generated data.
879879+The name of an alias must be unique within the struct literal.
880880+881881+```
882882+// An empty object.
883883+{}
884884+885885+// An object with 3 fields and 1 alias.
886886+{
887887+ alias = 3
888888+889889+ foo: 2
890890+ bar: "a string"
891891+892892+ "not an ident": 4
893893+}
894894+```
895895+896896+A field with as value a struct with a single field may be written as
897897+a sequence of the two field names,
898898+followed by a colon and the value of that single field.
899899+900900+```
901901+job myTask: {
902902+ replicas: 2
903903+}
904904+```
905905+expands to the following JSON:
906906+```
907907+"job": {
908908+ "myTask": {
909909+ "replicas": 2
910910+ }
911911+}
912912+```
913913+914914+915915+A field declaration may be followed by an optional field tag,
916916+which becomes a key value pair for all equivalent fields in structs with which
917917+it is unified.
918918+If two structs are unified which both define a field for a label and both
919919+fields have a tag for that field with the same key,
920920+implementations may require that their value match.
921921+The tags are made visible through CUE's API and are
922922+not visible within the language itself.
923923+924924+925925+### Lists
926926+927927+A list literal defines a new prototype of type list.
928928+A list may be open or closed.
929929+An open list is indicated with a `...` at the end of an element list,
930930+optionally followed by a prototype for the remaining elements.
931931+932932+The length of a closed list is the number of elements it contains.
933933+The length of an open list is the its number of elements as a lower bound
934934+and an unlimited number of elements as its upper bound.
935935+936936+```
937937+ListLit = "[" [ ElementList [ "," [ "..." [ Element ] ] ] "]" .
938938+ElementList = Element { "," Element } .
939939+Element = Expression | LiteralValue .
940940+```
941941+<!---
942942+KeyedElement = Element .
943943+--->
944944+945945+A list can be represented as a struct:
946946+947947+```
948948+List: null | {
949949+ Elem: _
950950+ Tail: List
951951+}
952952+```
953953+954954+For closed lists, `Tail` is `null` for the last element, for open lists it is
955955+`null | List`.
956956+For instance, the closed list [ 1, 2, ... ] can be represented as:
957957+```
958958+open: List & { Elem: 1, Tail: { Elem: 2 } }
959959+```
960960+and the closed version of this list, [ 1, 2 ], as
961961+```
962962+closed: List & { Elem: 1, Tail: { Elem: 2, Tail: null } }
963963+```
964964+965965+Using this definition, the subsumption and unification rules for lists can
966966+be derived from those of structs.
967967+Implementations are not required to implement lists as structs.
968968+969969+970970+## Declarations and Scopes
971971+972972+973973+### Blocks
974974+975975+A _block_ is a possibly empty sequence of declarations.
976976+A block is mostly corresponds with the brace brackets of a struct literal
977977+`{ ... }`, but also includes the following,
978978+979979+- The _universe block_ encompases all CUE source text.
980980+- Each package has a _package block_ containing all CUE source text in that package.
981981+- Each file has a _file block_ containing all CUE source text in that file.
982982+- Each `for` and `let` clause in a comprehension is considered to be
983983+ its own implicit block.
984984+- Each function value is considered to be its own implicit block.
985985+986986+Blocks nest and influence [scoping].
987987+988988+989989+### Declarations and scope
990990+991991+A _declaration_ binds an identifier to a field, alias, or package.
992992+Every identifier in a program must be declared.
993993+Other than for fields,
994994+no identifier may be declared twice within the same block.
995995+For fields an identifier may be declared more than once within the same block,
996996+resulting in a field with a value that is the result of unifying the values
997997+of all fields with the same identifier.
998998+999999+```
10001000+TopLevelDecl = Declaration | Emit .
10011001+Emit = Operand .
10021002+```
10031003+10041004+The _scope_ of a declared identifier is the extent of source text in which the
10051005+identifier denotes the specified field, alias, function, or package.
10061006+10071007+CUE is lexically scoped using blocks:
10081008+10091009+1. The scope of a [predeclared identifier] is the universe block.
10101010+1. The scope of an identifier denoting a field or alias
10111011+ declared at top level (outside any struct literal) is the file block.
10121012+1. The scope of the package name of an imported package is the file block of the
10131013+ file containing the import declaration.
10141014+1. The scope of a field or alias identifier declared inside a struct literal
10151015+ is the innermost containing block.
10161016+10171017+An identifier declared in a block may be redeclared in an inner block.
10181018+While the identifier of the inner declaration is in scope, it denotes the entity
10191019+declared by the inner declaration.
10201020+10211021+The package clause is not a declaration;
10221022+the package name do not appear in any scope.
10231023+Its purpose is to identify the files belonging to the same package
10241024+and tospecify the default name for import declarations.
10251025+10261026+10271027+### Predeclared identifiers
10281028+10291029+```
10301030+Functions
10311031+len required close open
10321032+10331033+Types
10341034+null The null type and value
10351035+bool All boolean values
10361036+int All integral numbers
10371037+float All decimal floating-point numbers
10381038+string Any valid UTF-8 sequence
10391039+bytes A blob of bytes representing arbitrary data
10401040+10411041+Derived Value
10421042+number int | float
10431043+uint 0..int
10441044+uint8 0..255
10451045+byte uint8
10461046+int8 -128..127
10471047+uint16 0..65536
10481048+int16 -32_768...32_767
10491049+rune 0..0x10FFFF
10501050+uint32 0..4_294_967_296
10511051+int32 -2_147_483_648..2_147_483_647
10521052+uint64 0..18_446_744_073_709_551_615
10531053+int64 -9_223_372_036_854_775_808..9_223_372_036_854_775_807
10541054+uint128 340_282_366_920_938_463_463_374_607_431_768_211_455
10551055+10561056+ "int128": mkIntRange(
10571057+ "-170141183460469231731687303715884105728",
10581058+ "170141183460469231731687303715884105727"),
10591059+10601060+ // Do not include an alias for "byte", as it would be too easily confused
10611061+ // with the builtin "bytes".
10621062+ "uint8": mkIntRange("0", "255"),
10631063+ "uint16": mkIntRange("0", "65535"),
10641064+ "uint32": mkIntRange("0", "4294967295"),
10651065+ "uint64": mkIntRange("0", "18446744073709551615"),
10661066+}
10671067+```
10681068+10691069+10701070+### Exported and manifested identifiers
10711071+10721072+An identifier of a package may be exported to permit access to it
10731073+from another package.
10741074+An identifier is exported if both:
10751075+the first character of the identifier's name is not a Unicode lower case letter
10761076+(Unicode class "Ll") or the underscore "_"; and
10771077+the identifier is declared in the file block.
10781078+All other identifiers are not exported.
10791079+10801080+An identifier that starts with the underscore "_" is not
10811081+emitted in any data output.
10821082+Quoted labels that start with an underscore are emitted nonetheless.
10831083+10841084+### Uniqueness of identifiers
10851085+10861086+Given a set of identifiers, an identifier is called unique if it is different
10871087+from every other in the set, after applying normalization following
10881088+Unicode Annex #31.
10891089+Two identifiers are different if they are spelled differently.
10901090+<!--
10911091+or if they appear in different packages and are not exported.
10921092+--->
10931093+Otherwise, they are the same.
10941094+10951095+10961096+### Field declarations
10971097+10981098+A field declaration binds a label (the names of the field) to an expression.
10991099+The name for a quoted string used as label is the string it represents.
11001100+Tne name for an identifier used as a label is the identifier itself.
11011101+Quoted strings and identifiers can be used used interchangeably, with the
11021102+exception of identifiers starting with an underscore '_'.
11031103+The latter represent hidden fields and are treated in a different namespace.
11041104+11051105+11061106+### Alias declarations
11071107+11081108+An alias declaration binds an identifier to the given expression.
11091109+11101110+Within the scope of the identifier, it serves as an _alias_ for that
11111111+expression.
11121112+The expression is evaluated in the scope as it was declared.
11131113+11141114+11151115+### Function declarations
11161116+11171117+NOTE: this is an internal construction.
11181118+11191119+A function declaration binds an identifier, the function name, to a function.
11201120+11211121+```
11221122+FunctionDecl = FunctionName Parameters "->" FunctionValue .
11231123+FunctionName = identifier .
11241124+FunctionValue = Expression .
11251125+Result = Parameters .
11261126+Parameters = "(" [ ParameterList [ "," ] ] ")" .
11271127+ParameterList = ParameterDecl { "," ParameterDecl } .
11281128+ParameterDecl = identifier [ ":" Type ] .
11291129+```
11301130+11311131+11321132+## Expressions
11331133+11341134+An expression specifies the computation of a value by applying operators and
11351135+functions to operands.
11361136+11371137+11381138+### Operands
11391139+11401140+Operands denote the elementary values in an expression.
11411141+An operand may be a literal, a (possibly [qualified]) identifier denoting
11421142+field, alias, function, or a parenthesized expression.
11431143+11441144+```
11451145+Operand = Literal | OperandName | ListComprehension | "(" Expression ")" .
11461146+Literal = BasicLit | ListLit | StructLit .
11471147+BasicLit = int_lit | float_lit | string_lit |
11481148+ null_lit | bool_lit | bottom_lit | top_lit .
11491149+OperandName = identifier | QualifiedIdent.
11501150+```
11511151+11521152+### Qualified identifiers
11531153+11541154+A qualified identifier is an identifier qualified with a package name prefix.
11551155+11561156+```
11571157+QualifiedIdent = PackageName "." identifier .
11581158+```
11591159+11601160+A qualified identifier accesses an identifier in a different package,
11611161+which must be [imported].
11621162+The identifier must be declared in the [package block] of that package.
11631163+11641164+```
11651165+math.Sin // denotes the Sin function in package math
11661166+```
11671167+11681168+11691169+### Primary expressions
11701170+11711171+Primary expressions are the operands for unary and binary expressions.
11721172+11731173+```
11741174+PrimaryExpr =
11751175+ Operand |
11761176+ Conversion |
11771177+ PrimaryExpr Selector |
11781178+ PrimaryExpr Index |
11791179+ PrimaryExpr Slice |
11801180+ PrimaryExpr Arguments .
11811181+11821182+Selector = "." identifier .
11831183+Index = "[" Expression "]" .
11841184+Slice = "[" [ Expression ] ":" [ Expression ] "]"
11851185+Argument = Expression .
11861186+Arguments = "(" [ ( Argument { "," Argument } ) [ "..." ] [ "," ] ] ")" .
11871187+```
11881188+<!---
11891189+Argument = Expression | ( identifer ":" Expression ).
11901190+--->
11911191+11921192+```
11931193+x
11941194+2
11951195+(s + ".txt")
11961196+f(3.1415, true)
11971197+m["foo"]
11981198+s[i : j + 1]
11991199+obj.color
12001200+f.p[i].x
12011201+```
12021202+12031203+12041204+### Selectors
12051205+12061206+For a [primary expression] `x` that is not a [package name],
12071207+the selector expression
12081208+12091209+```
12101210+x.f
12111211+```
12121212+12131213+denotes the field `f` of the value `x`.
12141214+The identifier `f` is called the field selector.
12151215+The type of the selector expression is the type of `f`.
12161216+If `x` is a package name, see the section on [qualified identifiers].
12171217+12181218+Otherwise, if `x` is not a struct, or if `f` does not exist in `x`,
12191219+the result of the expression is bottom (an error).
12201220+12211221+```
12221222+T: {
12231223+ x: int
12241224+ y: 3
12251225+}
12261226+12271227+a: T.x // int
12281228+b: T.y // 3
12291229+c: T.z // ⊥ // field 'z' not found in T
12301230+```
12311231+12321232+12331233+### Index expressions
12341234+12351235+A primary expression of the form
12361236+12371237+```
12381238+a[x]
12391239+```
12401240+12411241+denotes the element of the list, string, or struct `a` indexed by `x`.
12421242+The value `x` is called the index or field name, respectively.
12431243+The following rules apply:
12441244+12451245+If `a` is not a struct:
12461246+12471247+- the index `x` must be of integer type
12481248+- the index `x` is in range if `0 <= x < len(a)`, otherwise it is out of range
12491249+12501250+The result of `a[x]` is
12511251+12521252+for `a` of list type (including single quoted strings, which are lists of bytes):
12531253+12541254+- the list element at index `x`, if `x` is within range
12551255+- bottom (an error), otherwise
12561256+12571257+for `a` of string type:
12581258+12591259+- the grapheme cluster at the `x`th byte (type string), if `x` is within range
12601260+- bottom (an error), otherwise
12611261+12621262+for `a` of struct type:
12631263+12641264+- the value of the field named `x` of struct `a`, if this field exists
12651265+- bottom (an error), otherwise
12661266+12671267+```
12681268+[ 1, 2 ][1] // 2
12691269+[ 1, 2 ][2] // ⊥
12701270+"He\u0300?"[0] // "H"
12711271+"He\u0300?"[1] // "e\u0300"
12721272+"He\u0300?"[2] // "e\u0300"
12731273+"He\u0300?"[3] // "e\u0300"
12741274+"He\u0300?"[4] // "?"
12751275+"He\u0300?"[5] // ⊥
12761276+```
12771277+12781278+12791279+### Slice expressions
12801280+12811281+Slice expressions construct a substring or slice from a string or list.
12821282+12831283+For strings or lists, the primary expression
12841284+```
12851285+a[low : high]
12861286+```
12871287+constructs a substring or slice. The indices `low` and `high` select
12881288+which elements of operand a appear in the result. The result has indices
12891289+starting at 0 and length equal to `high` - `low`.
12901290+After slicing the list `a`
12911291+12921292+```
12931293+a := [1, 2, 3, 4, 5]
12941294+s := a[1:4]
12951295+```
12961296+the list s has length 3 and elements
12971297+```
12981298+s[0] == 2
12991299+s[1] == 3
13001300+s[2] == 4
13011301+```
13021302+For convenience, any of the indices may be omitted.
13031303+A missing `low` index defaults to zero; a missing `high` index defaults
13041304+to the length of the sliced operand:
13051305+```
13061306+a[2:] // same as a[2 : len(a)]
13071307+a[:3] // same as a[0 : 3]
13081308+a[:] // same as a[0 : len(a)]
13091309+```
13101310+13111311+Indices are in range if `0 <= low <= high <= len(a)`,
13121312+otherwise they are out of range.
13131313+For strings, the indices selects the start of the extended grapheme cluster
13141314+at byte position indicated by the index.
13151315+If any of the slice values is out of range or if `low > high`, the result of
13161316+a slice is bottom (error).
13171317+13181318+```
13191319+"He\u0300?"[:2] // "He\u0300"
13201320+"He\u0300?"[1:2] // "e\u0300"
13211321+"He\u0300?"[4:5] // "e\u0300?"
13221322+```
13231323+13241324+13251325+The result of a successful slice operation is a value of the same type
13261326+as the operand.
13271327+13281328+13291329+### Operators
13301330+13311331+Operators combine operands into expressions.
13321332+13331333+```
13341334+Expression = UnaryExpr | Expression binary_op Expression .
13351335+UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
13361336+13371337+binary_op = "|" | "&" | "||" | "&&" | rel_op | add_op | mul_op | ".." .
13381338+rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" .
13391339+add_op = "+" | "-" .
13401340+mul_op = "*" | "/" | "div" | "mod" | "quo" | "rem" .
13411341+13421342+unary_op = "+" | "-" | "!" .
13431343+```
13441344+13451345+Comparisons are discussed [elsewhere]. For other binary operators, the operand
13461346+types must be [identical] unless the operation involves untyped [constants]
13471347+or durations. For operations involving constants only, see the section on
13481348+[constant expressions].
13491349+13501350+Except for duration operations, if one operand is an untyped [literal] and the
13511351+other operand is not, the constant is [converted] to the type of the other
13521352+operand.
13531353+13541354+13551355+#### Operator precedence
13561356+13571357+Unary operators have the highest precedence.
13581358+13591359+There are eight precedence levels for binary operators.
13601360+The `..` operator (range) binds strongest, followed by
13611361+multiplication operators, addition operators, comparison operators,
13621362+`&&` (logical AND), `||` (logical OR), `&` (unification),
13631363+and finally `|` (disjunction):
13641364+13651365+```
13661366+Precedence Operator
13671367+ 8 ..
13681368+ 7 * / div mod quo rem
13691369+ 6 + -
13701370+ 5 == != < <= > >=
13711371+ 4 &&
13721372+ 3 ||
13731373+ 2 &
13741374+ 1 |
13751375+```
13761376+13771377+Binary operators of the same precedence associate from left to right.
13781378+For instance, `x / y * z` is the same as `(x / y) * z`.
13791379+13801380+```
13811381++x
13821382+23 + 3*x[i]
13831383+x <= f()
13841384+f() || g()
13851385+x == y+1 && y == z-1
13861386+2 | int
13871387+{ a: 1 } & { b: 2 }
13881388+```
13891389+13901390+#### Arithmetic operators
13911391+13921392+Arithmetic operators apply to numeric values and yield a result of the same type
13931393+as the first operand. The three of the four standard arithmetic operators
13941394+`(+, -, *)` apply to integer and decimal floating-point types;
13951395+`+` and `*` also applies to lists and strings.
13961396+`/` only applies to decimal floating-point types and
13971397+`div`, `mod`, `quo`, and `rem` only apply to integer types.
13981398+13991399+```
14001400++ sum integers, floats, lists, strings
14011401+- difference integers, floats
14021402+* product integers, floats, lists, strings
14031403+/ quotient floats
14041404+div division integers
14051405+mod modulo integers
14061406+quo quotient integers
14071407+rem remainder integers
14081408+```
14091409+14101410+#### Integer operators
14111411+14121412+For two integer values `x` and `y`,
14131413+the integer quotient `q = x div y` and remainder `r = x mod y `
14141414+satisfy the following relationships:
14151415+14161416+```
14171417+r = x - y*q with 0 <= r < |y|
14181418+```
14191419+where `|y|` denotes the absolute value of `y`.
14201420+14211421+```
14221422+ x y x div y x mod y
14231423+ 5 3 1 2
14241424+-5 3 -2 1
14251425+ 5 -3 -1 2
14261426+-5 -3 2 1
14271427+```
14281428+14291429+For two integer values `x` and `y`,
14301430+the integer quotient `q = x quo y` and remainder `r = x rem y `
14311431+satisfy the following relationships:
14321432+14331433+```
14341434+x = q*y + r and |r| < |y|
14351435+```
14361436+14371437+with `x quo y` truncated towards zero.
14381438+14391439+```
14401440+ x y x quo y x rem y
14411441+ 5 3 1 2
14421442+-5 3 -1 -2
14431443+ 5 -3 -1 2
14441444+-5 -3 1 -2
14451445+```
14461446+14471447+A zero divisor in either case results in bottom (an error).
14481448+14491449+For integer operands, the unary operators `+` and `-` are defined as follows:
14501450+14511451+```
14521452++x is 0 + x
14531453+-x negation is 0 - x
14541454+```
14551455+14561456+14571457+#### Decimal floating-point operators
14581458+14591459+For decimal floating-point numbers, `+x` is the same as `x`,
14601460+while -x is the negation of x.
14611461+The result of a floating-point division by zero is bottom (an error).
14621462+14631463+An implementation may combine multiple floating-point operations into a single
14641464+fused operation, possibly across statements, and produce a result that differs
14651465+from the value obtained by executing and rounding the instructions individually.
14661466+14671467+14681468+#### List operators
14691469+14701470+Lists can be concatenated using the `+` operator.
14711471+For, list `a` and `b`
14721472+```
14731473+a + b
14741474+```
14751475+will produce an open list if `b` is open.
14761476+If list `a` is open, only the existing elements will be involved in the
14771477+concatenation.
14781478+14791479+```
14801480+[ 1, 2 ] + [ 3, 4 ] // [ 1, 2, 3, 4 ]
14811481+[ 1, 2, ... ] + [ 3, 4 ] // [ 1, 2, 3, 4 ]
14821482+[ 1, 2 ] + [ 3, 4, ... ] // [ 1, 2, 3, 4, ... ]
14831483+```
14841484+14851485+Lists can be multiplied using the `*` operator.
14861486+```
14871487+3*[1,2] // [1, 2, 1, 2, 1, 2]
14881488+14891489+[1, 2, ...int] // open list of two elements with element type int
14901490+4*[byte] // [byte, byte, byte, byte]
14911491+[...byte] // byte list or arbitrary length
14921492+(0..5)*[byte] // byte list of size 0 through 5
14931493+14941494+// list with alternating elements of type string and int
14951495+uint*[string, int]
14961496+```
14971497+14981498+The following illustrate how typed lists can be encoded as structs:
14991499+```
15001500+ip: 4*[byte]
15011501+ipT: {
15021502+ Elem: byte
15031503+ Tail: {
15041504+ Elem: byte
15051505+ Tail: {
15061506+ Elem: byte
15071507+ Tail: {
15081508+ Elem: byte
15091509+ Tail: null
15101510+ }
15111511+ }
15121512+ }
15131513+}
15141514+15151515+rangeList: (1..2)*[int]
15161516+rangeListT: null | {
15171517+ Elem: int
15181518+ Tail: {
15191519+ Elem: int
15201520+ Tail: null | {
15211521+ Elem: int
15221522+ Tail: null
15231523+ }
15241524+ }
15251525+}
15261526+15271527+strIntList: uint*[string, int]
15281528+strIntListT: null | {
15291529+ Elem: string
15301530+ Tail: {
15311531+ Elem: int
15321532+ Tail: strIntListT
15331533+ }
15341534+}
15351535+```
15361536+15371537+#### String operators
15381538+15391539+Strings can be concatenated using the `+` operator:
15401540+```
15411541+s := "hi " + name + " and good bye"
15421542+```
15431543+String addition creates a new string by concatenating the operands.
15441544+15451545+A string can be repeated by multiplying it:
15461546+15471547+```
15481548+s: "etc. "*3 // "etc. etc. etc. "
15491549+```
15501550+15511551+##### Comparison operators
15521552+15531553+Comparison operators compare two operands and yield an untyped boolean value.
15541554+15551555+```
15561556+== equal
15571557+!= not equal
15581558+< less
15591559+<= less or equal
15601560+> greater
15611561+>= greater or equal
15621562+```
15631563+15641564+In any comparison, the types of the two operands must unify.
15651565+15661566+The equality operators `==` and `!=` apply to operands that are comparable.
15671567+The ordering operators `<`, `<=`, `>`, and `>=` apply to operands that are ordered.
15681568+These terms and the result of the comparisons are defined as follows:
15691569+15701570+- Boolean values are comparable.
15711571+ Two boolean values are equal if they are either both true or both false.
15721572+- Integer values are comparable and ordered, in the usual way.
15731573+- Floating-point values are comparable and ordered, as per the definitions
15741574+ for binary coded decimals in the IEEE-754-2008 standard.
15751575+- String values are comparable and ordered, lexically byte-wise.
15761576+- Struct are not comparable.
15771577+ Two struct values are equal if their corresponding non-blank fields are equal.
15781578+- List are not comparable.
15791579+ Two array values are equal if their corresponding elements are equal.
15801580+```
15811581+c: 3 < 4
15821582+15831583+x: int
15841584+y: int
15851585+15861586+b3: x == y // b3 has type bool
15871587+```
15881588+15891589+#### Logical operators
15901590+15911591+Logical operators apply to boolean values and yield a result of the same type
15921592+as the operands. The right operand is evaluated conditionally.
15931593+15941594+```
15951595+&& conditional AND p && q is "if p then q else false"
15961596+|| conditional OR p || q is "if p then true else q"
15971597+! NOT !p is "not p"
15981598+```
15991599+16001600+16011601+<!--
16021602+### TODO TODO TODO
16031603+16041604+3.14 / 0.0 // illegal: division by zero
16051605+Illegal conversions always apply to CUE.
16061606+16071607+Implementation restriction: A compiler may use rounding while computing untyped floating-point or complex constant expressions; see the implementation restriction in the section on constants. This rounding may cause a floating-point constant expression to be invalid in an integer context, even if it would be integral when calculated using infinite precision, and vice versa.
16081608+-->
16091609+16101610+### Conversions
16111611+Conversions are expressions of the form `T(x)` where `T` and `x` are
16121612+expressions.
16131613+The result is always an instance of `T`.
16141614+16151615+```
16161616+Conversion = Expression "(" Expression [ "," ] ")" .
16171617+```
16181618+16191619+<!---
16201620+16211621+A literal value `x` can be converted to type T if `x` is representable by a
16221622+value of `T`.
16231623+16241624+As a special case, an integer literal `x` can be converted to a string type
16251625+using the same rule as for non-constant x.
16261626+16271627+Converting a literal yields a typed value as result.
16281628+16291629+```
16301630+uint(iota) // iota value of type uint
16311631+float32(2.718281828) // 2.718281828 of type float32
16321632+complex128(1) // 1.0 + 0.0i of type complex128
16331633+float32(0.49999999) // 0.5 of type float32
16341634+float64(-1e-1000) // 0.0 of type float64
16351635+string('x') // "x" of type string
16361636+string(0x266c) // "♬" of type string
16371637+MyString("foo" + "bar") // "foobar" of type MyString
16381638+string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant
16391639+(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
16401640+int(1.2) // illegal: 1.2 cannot be represented as an int
16411641+string(65.0) // illegal: 65.0 is not an integer constant
16421642+```
16431643+--->
16441644+16451645+A conversion is always allowed if `x` is of the same type as `T` and `x`
16461646+is an instance of `T`.
16471647+16481648+If `T` and `x` of different underlying type, a conversion if
16491649+`x` can be converted to a value `x'` of `T`'s type, and
16501650+`x'` is an instance of `T`.
16511651+A value `x` can be converted to the type of `T` in any of these cases:
16521652+16531653+- `x` is of type struct and is subsumed by `T` ignoring struct tags.
16541654+- `x` and `T` are both integer or floating point types.
16551655+- `x` is an integer or a list of bytes or runes and `T` is a string type.
16561656+- `x` is a string and `T` is a list of bytes or runes.
16571657+16581658+16591659+[Field tags] are ignored when comparing struct types for identity
16601660+for the purpose of conversion:
16611661+16621662+```
16631663+person: {
16641664+ name: string #xml:"Name"
16651665+ address: null | {
16661666+ street: string #xml:"Street"
16671667+ city: string #xml:"City"
16681668+ } #xml:"Address"
16691669+}
16701670+16711671+person2: {
16721672+ name: string
16731673+ address: null | {
16741674+ street: string
16751675+ city: string
16761676+ }
16771677+}
16781678+16791679+p2 = person(person2) // ignoring tags, the underlying types are identical
16801680+```
16811681+16821682+Specific rules apply to conversions between numeric types, structs,
16831683+or to and from a string type. These conversions may change the representation
16841684+of `x`.
16851685+All other conversions only change the type but not the representation of x.
16861686+16871687+16881688+#### Conversions between numeric ranges
16891689+For the conversion of numeric values, the following rules apply:
16901690+16911691+1. Any integer prototype can be converted into any other integer prototype
16921692+ provided that it is within range.
16931693+2. When converting a decimal floating-point number to an integer, the fraction
16941694+ is discarded (truncation towards zero). TODO: or disallow truncating?
16951695+16961696+```
16971697+a: uint16(int(1000)) // uint16(1000)
16981698+b: uint8(1000) // ⊥ // overflow
16991699+c: int(2.5) // 2 TODO: TBD
17001700+```
17011701+17021702+17031703+17041704+#### Conversions to and from a string type
17051705+17061706+Converting a signed or unsigned integer value to a string type yields a string
17071707+containing the UTF-8 representation of the integer. Values outside the range of
17081708+valid Unicode code points are converted to `"\uFFFD"`.
17091709+17101710+```
17111711+string('a') // "a"
17121712+string(-1) // "\ufffd" == "\xef\xbf\xbd"
17131713+string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8"
17141714+17151715+MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5"
17161716+```
17171717+17181718+Converting a list of bytes to a string type yields a string whose successive
17191719+bytes are the elements of the slice.
17201720+Invalid UTF-8 is converted to `"\uFFFD"`.
17211721+17221722+```
17231723+string('hell\xc3\xb8') // "hellø"
17241724+string(bytes([0x20])) // " "
17251725+```
17261726+17271727+As string value is always convertible to a list of bytes.
17281728+17291729+```
17301730+bytes("hellø") // 'hell\xc3\xb8'
17311731+bytes("") // ''
17321732+```
17331733+17341734+<!---
17351735+#### Conversions between list types
17361736+17371737+Conversions between list types are possible only if `T` strictly subsumes `x`
17381738+and the result will be the unification of `T` and `x`.
17391739+17401740+<!---
17411741+If we introduce named types this would be different from IP & [10, ...]
17421742+17431743+Consider removing this until it has a different meaning.
17441744+17451745+```
17461746+IP: 4*[byte]
17471747+Private10: IP([10, ...]) // [10, byte, byte, byte]
17481748+```
17491749+--->
17501750+17511751+#### Convesions between struct types
17521752+17531753+A conversion from `x` to `T`
17541754+is applied using the following rules:
17551755+17561756+1. `x` must be an instance of `T`,
17571757+2. all fields defined for `x` that are not defined for `T` are removed from
17581758+ the result of the conversion, recursively.
17591759+17601760+```
17611761+T: {
17621762+ a: { b: 1..10 }
17631763+}
17641764+17651765+x1: {
17661766+ a: { b: 8, c: 10 }
17671767+ d: 9
17681768+}
17691769+17701770+c1: T(x1) // { a: { b: 8 } }
17711771+c2: T({}) // ⊥ // missing field 'a' in '{}'
17721772+c3: T({ a: {b: 0} }) // ⊥ // field a.b does not unify (0 & 1..10)
17731773+```
17741774+17751775+17761776+### Calls
17771777+17781778+Given an expression `f` of function type F,
17791779+```
17801780+f(a1, a2, … an)
17811781+```
17821782+calls `f` with arguments a1, a2, … an. Arguments must be expressions
17831783+of which the values are an instance of the parameter types of `F`
17841784+and are evaluated before the function is called.
17851785+17861786+```
17871787+a: math.Atan2(x, y)
17881788+```
17891789+<!---
17901790+17911791+// FUNCTIONS ARE DISABLED:
17921792+Point: {
17931793+ Scale(a: float) -> Point({ Value: Point.Value * a })
17941794+ Value: float
17951795+}
17961796+pt: Point
17971797+pt: { Value: a }
17981798+17991799+ptp: pt.Scale(3.5)
18001800+--->
18011801+18021802+18031803+In a function call, the function value and arguments are evaluated in the usual
18041804+order. After they are evaluated, the parameters of the call are passed by value
18051805+to the function and the called function begins execution. The return parameters
18061806+of the function are passed by value back to the calling function when the
18071807+function returns.
18081808+18091809+<!---
18101810+TODO:
18111811+18121812+Passing arguments to ... parameters
18131813+If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value passed to p is nil. Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.
18141814+18151815+Given the function and calls
18161816+18171817+func Greeting(prefix string, who ...string)
18181818+Greeting("nobody")
18191819+Greeting("hello:", "Joe", "Anna", "Eileen")
18201820+within Greeting, who will have the value nil in the first call, and []string{"Joe", "Anna", "Eileen"} in the second.
18211821+18221822+If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.
18231823+18241824+Given the slice s and call
18251825+18261826+s := []string{"James", "Jasmine"}
18271827+Greeting("goodbye:", s...)
18281828+within Greeting, who will have the same value as s with the same underlying array.
18291829+--->
18301830+18311831+18321832+### Comprehensions
18331833+18341834+Lists and structs can be constructed using comprehensions.
18351835+18361836+Each define a clause sequence that consists of a sequence of `for`, `if`, and
18371837+`let` clauses, nesting from left to right.
18381838+The `for` and `let` clauses each define a new scope in which new values are
18391839+bound to be available for the next clause.
18401840+18411841+The `for` clause binds the defined identifiers, on each iteration, to the next
18421842+value of some iterable value in a new scope.
18431843+A `for` clause may bind one or two identifiers.
18441844+If there is one identifier, it binds it to the value, for instance
18451845+a list element, a struct field value or a range element.
18461846+If there are more two identifies, the first value will be the key or index,
18471847+if available, and the second will be the value.
18481848+18491849+An `if` clause, or guard, specifies an expression that terminates the current
18501850+iteration if it evaluates to false.
18511851+18521852+The `let` clause binds the result of an expression to the defined identifier
18531853+in a new scope.
18541854+18551855+A current iteration is said to complete if the inner-most block of the clause
18561856+sequence is reached.
18571857+18581858+List comprehensions specify a single expression that is evaluated and included
18591859+in the list for each completed iteration.
18601860+18611861+Struct comprehensions specify two expressions, one for the label and one for
18621862+the value, that each get evaluated and included as a field in the struct
18631863+for each completed iteration.
18641864+18651865+```
18661866+ComprehensionDecl = Field [ "<-" ] Clauses .
18671867+ListComprehension = "[" Expression "<-" Clauses "]" .
18681868+18691869+Clauses = Clause { Clause } .
18701870+Clause = ForClause | GuardClause | LetClause .
18711871+ForClause = "for" identifier [ ", " identifier] "in" Expression .
18721872+GuardClause = "if" Expression .
18731873+LetClause = "let" identifier "=" Expression .
18741874+```
18751875+18761876+```
18771877+a: [1, 2, 3, 4]
18781878+b: [ x+1 for x in a if x > 1] // [3, 4, 5]
18791879+18801880+c: { ("\(x)"): x + y for x in a if x < 4 let y = 1 }
18811881+d: { "1": 2, "2": 3, "3": 4 }
18821882+```
18831883+18841884+<!---
18851885+The above examples could be expressed as struct unification as follows:
18861886+18871887+```
18881888+b: [ ]
18891889+bc: {
18901890+ x1: _
18911891+ next: {
18921892+ x2: true & x1 > 1
18931893+ next: {
18941894+ x3: x1+1
18951895+ }
18961896+ }
18971897+ result: next.next.x3 | []
18981898+}
18991899+```
19001900+19011901+Struct comprehensions cannot be expressed as such as there is not equivalent
19021902+in the language to have computed field labels.
19031903+--->
19041904+19051905+19061906+### String interpolation
19071907+19081908+Strings interpolation allows constructing strings by replacing placeholder
19091909+expressions included in strings to be replaced with their string representation.
19101910+String interpolation may be used in single- and double-quoted strings, as well
19111911+as their multiline equivalent.
19121912+19131913+A placeholder is demarked by a enclosing parentheses prefixed with
19141914+a backslash `\`.
19151915+Within the parentheses may be any expression to be
19161916+evaluated within the scope within which the string is defined.
19171917+19181918+```
19191919+a: "World"
19201920+b: "Hello \( a )!" // Hello World!
19211921+```
19221922+19231923+19241924+## Builtin Functions
19251925+19261926+Built-in functions are predeclared. They are called like any other function.
19271927+19281928+The built-in functions cannot be used as function values.
19291929+19301930+### `len`
19311931+19321932+The built-in function `len` takes arguments of various types and return
19331933+a result of type int.
19341934+19351935+```
19361936+Argument type Result
19371937+19381938+string string length in bytes
19391939+list list length
19401940+struct number of distinct fields
19411941+```
19421942+19431943+19441944+### `required`
19451945+19461946+The built-in function `required` discards the default mechanism of
19471947+a disjunction.
19481948+19491949+```
19501950+"tcp" | "udp" // default is "tcp"
19511951+required("tcp" | "udp") // no default, user must specify either "tcp" or "udp"
19521952+```
19531953+19541954+19551955+## Modules, instances, and packages
19561956+19571957+CUE configurations are constructed combining _instances_.
19581958+An instance, in turn, is constructed from one or more source files belonging
19591959+to the same _package_ that together declare the data representation.
19601960+Elements of this data representation may be exported and used
19611961+in other instances.
19621962+19631963+### Source file organization
19641964+19651965+Each source file consists of an optional package clause defining collection
19661966+of files to which it belongs,
19671967+followed by a possibly empty set of import declarations that declare
19681968+packages whose contents it wishes to use, followed by a possibly empty set of
19691969+declarations.
19701970+19711971+19721972+```
19731973+SourceFile = [ PackageClause "," ] { ImportDecl "," } { TopLevelDecl "," } .
19741974+```
19751975+19761976+### Package clause
19771977+19781978+A package clause is an optional clause that defines the package to which
19791979+a source file the file belongs.
19801980+19811981+```
19821982+PackageClause = "package" PackageName .
19831983+PackageName = identifier .
19841984+```
19851985+19861986+The PackageName must not be the blank identifier.
19871987+19881988+```
19891989+package math
19901990+```
19911991+19921992+### Modules and instances
19931993+A _module_ defines a tree directories, rooted at the _module root_.
19941994+19951995+All source files within a module with the same package belong to the same
19961996+package.
19971997+A module may define multiple package.
19981998+19991999+An _instance_ of a package is any subset of files within a module belonging
20002000+to the same package.
20012001+It is interpreted as the concatanation of these files.
20022002+20032003+An implementation may impose conventions on the layout of package files
20042004+to determine which files of a package belongs to an instance.
20052005+For instance, an instance may be defined as the subset of package files
20062006+belonging to a directory and all its ancestors.
20072007+20082008+20092009+### Import declarations
20102010+20112011+An import declaration states that the source file containing the declaration
20122012+depends on definitions of the _imported_ package (§Program initialization and
20132013+execution) and enables access to exported identifiers of that package.
20142014+The import names an identifier (PackageName) to be used for access and an
20152015+ImportPath that specifies the package to be imported.
20162016+20172017+```
20182018+ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
20192019+ImportSpec = [ "." | PackageName ] ImportPath .
20202020+ImportPath = `"` { unicode_value } `"` .
20212021+```
20222022+20232023+The PackageName is used in qualified identifiers to access exported identifiers
20242024+of the package within the importing source file.
20252025+It is declared in the file block.
20262026+If the PackageName is omitted, it defaults to the identifier specified in the
20272027+package clause of the imported instance.
20282028+If an explicit period (.) appears instead of a name, all the instances's
20292029+exported identifiers declared in that instances's package block will be declared
20302030+in the importing source file's file block
20312031+and must be accessed without a qualifier.
20322032+20332033+The interpretation of the ImportPath is implementation-dependent but it is
20342034+typically either the path of a builtin package or a fully qualifying location
20352035+of an instance within a source code repository.
20362036+20372037+Implementation restriction: An interpreter may restrict ImportPaths to non-empty
20382038+strings using only characters belonging to Unicode's L, M, N, P, and S general
20392039+categories (the Graphic characters without spaces) and may also exclude the
20402040+characters !"#$%&'()*,:;<=>?[\]^`{|} and the Unicode replacement character
20412041+U+FFFD.
20422042+20432043+Assume we have package containing the package clause package math,
20442044+which exports function Sin at the path identified by "lib/math".
20452045+This table illustrates how Sin is accessed in files
20462046+that import the package after the various types of import declaration.
20472047+20482048+```
20492049+Import declaration Local name of Sin
20502050+20512051+import "lib/math" math.Sin
20522052+import m "lib/math" m.Sin
20532053+import . "lib/math" Sin
20542054+```
20552055+20562056+An import declaration declares a dependency relation between the importing and
20572057+imported package. It is illegal for a package to import itself, directly or
20582058+indirectly, or to directly import a package without referring to any of its
20592059+exported identifiers.
20602060+20612061+20622062+### An example package
20632063+20642064+TODO
20652065+20662066+## Interpretation
20672067+20682068+CUE was inspired by a formalism known as
20692069+typed attribute structures [Carpenter 1992] or
20702070+typed feature structures [Copestake 2002],
20712071+which are used in linguistics to encode grammars and
20722072+lexicons. Being able to effectively encode large amounts of data in a rigorous
20732073+manner, this formalism seemed like a great fit for large-scale configuration.
20742074+20752075+Although CUE configurations are specified as trees, not graphs, implementations
20762076+can benefit from considering them as graphs when dealing with cycles,
20772077+and effectively turning them into graphs when applying techniques like
20782078+structure sharing.
20792079+Dealing with cycles is well understood for typed attribute structures
20802080+and as CUE configurations are formally closely related to them,
20812081+we can benefit from this knowledge without reinventing the wheel.
20822082+20832083+20842084+### Formal definition
20852085+20862086+<!--
20872087+The previous section is equivalent to the below text with the main difference
20882088+that it is only defined for trees. Technically, structs are more akin dags,
20892089+but that is hard to explain at this point and also unnecessarily pedantic.
20902090+ We keep the definition closer to trees and will layer treatment
20912091+of cycles on top of these definitions to achieve the same result (possibly
20922092+without the benefits of structure sharing of a dag).
20932093+20942094+A _field_ is a field name, or _label_ and a protype.
20952095+A _struct_ is a set of _fields_ with unique labels for each field.
20962096+-->
20972097+20982098+A CUE configuration can be defined in terms of constraints, which are
20992099+analogous to typed attribute structures referred to above.
21002100+21012101+#### Definition of basic prototypes
21022102+21032103+> A _basic prototype_ is any CUE prototype that is not a struct (or, by
21042104+> extension, a list).
21052105+> All basic prototypes are paritally ordered in a lattice, such that for any
21062106+> basic prototype `a` and `b` there is a unique greatest lower bound
21072107+> defined for the subsumption relation `a ⊑ b`.
21082108+21092109+```
21102110+Basic prototypes
21112111+null
21122112+true
21132113+bool
21142114+3.14
21152115+string
21162116+"Hello"
21172117+0..10
21182118+<8
21192119+re("Hello .*!")
21202120+```
21212121+21222122+The basic prototypes correspond to their respective types defined earlier.
21232123+21242124+Struct (and by extension lists), are represented by the abstract notion of
21252125+a constraint structure.
21262126+Each node in a configuration, including the root node,
21272127+is associated with a constraint.
21282128+21292129+21302130+#### Definition of a typed feature structures and substructures
21312131+21322132+> A typed feature structure_ defined for a finite set of labels `Label`
21332133+> is directed acyclic graph with labeled
21342134+> arcs and values, represented by a tuple `C = <Q, q0, υ, δ>`, where
21352135+>
21362136+> 1. `Q` is the finite set of nodes,
21372137+> 1. `q0 ∈ Q`, is the root node,
21382138+> 1. `υ: Q → T` is the total node typing function,
21392139+> for a finite set of possible terms `T`.
21402140+> 1. `δ: Label × Q → Q` is the partial feature function,
21412141+>
21422142+> subject to the following conditions:
21432143+>
21442144+> 1. there is no node `q` or label `l` such that `δ(q, l) = q0` (root)
21452145+> 2. for every node `q` in `Q` there is a path `π` (i.e. a sequence of
21462146+> members of Label) such that `δ(q0, π) = q` (unique root, correctness)
21472147+> 3. there is no node `q` or path `π` such that `δ(q, π) = q` (no cycles)
21482148+>
21492149+> where `δ` is extended to be defined on paths as follows:
21502150+>
21512151+> 1. `δ(q, ϵ) = q`, where `ϵ` is the empty path
21522152+> 2. `δ(q, l∙π) = δ(δ(l, q), π)`
21532153+>
21542154+> The _substructures_ of a typed feature structure are the
21552155+> typed feature structures rooted at each node in the structure.
21562156+>
21572157+> The set of all possible typed feature structures for a given label
21582158+> set is denoted as `𝒞`<sub>`Label`</sub>.
21592159+>
21602160+> The set of _terms_ for label set `Label` is recursively defined as
21612161+>
21622162+> 1. every basic prototype: `P ⊆ T`
21632163+> 2. every constraint in `𝒞`<sub>`Label`</sub> is a term: `𝒞`<sub>`Label`</sub>` ⊆ T`
21642164+> 3. for every `n` prototypes `t₁, ..., tₙ`, and every `n`-ary function symbol
21652165+> `f ∈ F_n`, the prototye `f(t₁,...,tₙ) ∈ T`.
21662166+>
21672167+21682168+21692169+This definition has been taken and modified from [Carpenter, 1992]
21702170+and [Copestake, 2002].
21712171+21722172+Without loss of generality, we will henceforth assume that the given set
21732173+of labels is constant and denote `𝒞`<sub>`Label`</sub> as `𝒞`.
21742174+21752175+In CUE configurations, the abstract constraints implicated by `υ`
21762176+are CUE exressions.
21772177+Literal structs can be treated as part of the original typed feature structure
21782178+and do not need evaluation.
21792179+Any other expression is evaluated and unified with existing values of that node.
21802180+21812181+References in expressions refer to other nodes within the `C` and represent
21822182+a copy of such a `C`.
21832183+The functions defined by `F` correspond to the binary and unary operators
21842184+and interpolation construct of CUE, as well as builtin functions.
21852185+21862186+CUE allows duplicate labels within a struct, while the definition of
21872187+typed feature structures does not.
21882188+A duplicate label `l` with respective values `a` and `b` is represented in
21892189+a constraint as a single label with term `&(a, b)`,
21902190+the unification of `a` and `b`.
21912191+Multiple labels may be recursively combined in any order.
21922192+21932193+<!-- unnecessary, probably.
21942194+#### Definition of evaluated prototype
21952195+21962196+> A fully evaluated prototype, `T_evaluated ⊆ T` is a subset of `T` consisting
21972197+> only of atoms, typed attribute structures and constraint functions.
21982198+>
21992199+> A prototype is called _ground_ if it is an atom or typed attribute structure.
22002200+22012201+#### Unification of evaluated prototypes
22022202+22032203+> A fully evaluated prototype, `T_evaluated ⊆ T` is a subset of `T` consisting
22042204+> only of atoms, typed attribute structures and constraint functions.
22052205+>
22062206+> A prototype is called _ground_ if it is an atom or typed attribute structure.
22072207+-->
22082208+22092209+#### Definition of subsumption and unification on typed attribute structure
22102210+22112211+> For a given collection of constraints `𝒞`,
22122212+> we define `π ≡`<sub>`C`</sub> `π'` to mean that constraint structure `C ∈ 𝒞`
22132213+> contains path equivalence between the paths `π` and `π'`
22142214+> (i.e. `δ(q0, π) = δ(q0, π')`, where `q0` is the root node of `C`);
22152215+> and `𝒫`<sub>`C`</sub>`(π) = c` to mean that
22162216+> the constraint structure at the path `π` in `C`
22172217+> is `c` (i.e. `𝒫`<sub>`C`</sub>`(π) = c` if and only if `υ(δ(q0, π)) == c`,
22182218+> where `q0` is the root node of `C`).
22192219+> Subsumption is then defined as follows:
22202220+> `C ∈ 𝒞` subsumes `C' ∈ 𝒞`, written `C' ⊑ C`, if and only if:
22212221+>
22222222+> - `π ≡`<sub>`C`</sub> `π'` implies `π ≡`<sub>`C'`</sub> `π'`
22232223+> - `𝒫`<sub>`C`</sub>`(π) = c` implies`𝒫`<sub>`C'`</sub>`(π) = c` and `c' ⊑ c`
22242224+>
22252225+> The unification of `C` and `C'`, denoted `C ⊓ C'`,
22262226+> is the greatest lower bound of `C` and `C'` in `𝒞` ordered by subsumption.
22272227+22282228+Like with the subsumption relation for basic prototypes,
22292229+the subsumption relation for constraints determines the mutual placement
22302230+of constraints within the partial order of all values.
22312231+22322232+22332233+#### Evaluation function
22342234+22352235+> The evaluation function is given by `E: T -> 𝒞`.
22362236+> The unification of two constraint structures is evaluated as defined above.
22372237+> All other functions are evaluated according to the definitions found earlier
22382238+> in this spec.
22392239+> An error is indicated by `⊥`.
22402240+22412241+#### Definition of well-formedness
22422242+22432243+> We say that a given constraint structure `C = <Q, q0, υ, δ> ∈ 𝒞` is
22442244+> a _well-formed_ constraint structure if and only if for all nodes `q ∈ Q`,
22452245+> the substructure `C'` rooted at `q`,
22462246+> is such that `E(υ(q)) ∈ 𝒞` and `C' = <Q', q, δ', υ'> ⊑ E(υ(q))`.
22472247+22482248+<!-- Also, like Copestake, define appropriate features?
22492249+Appropriate features are useful for detecting unused variables.
22502250+22512251+Appropriate features could be introduced by distinguishing between:
22522252+22532253+a: MyStruct // appropriate features are MyStruct
22542254+a: {a : 1}
22552255+22562256+and
22572257+22582258+a: MyStruct & { a: 1 } // appropriate features are those of MyStruct + 'a'
22592259+22602260+This is way to suttle, though.
22612261+22622262+Alternatively: use Haskell's approach:
22632263+22642264+a :: MyStruct // define a to be MyStruct any other features are allowed but
22652265+ // discarded from the model. Unused features are an error.
22662266+22672267+Let's first try to see if we can get away with static usage analysis.
22682268+A variant would be to define appropriate features unconditionally, but enforce
22692269+them only for unused variables, with some looser definition of unused.
22702270+-->
22712271+22722272+The _evaluation_ of a CUE configuration represented by `C`
22732273+is defined as the process of making `C` well-formed.
22742274+22752275+<!--
22762276+ore abstractly, we can define this structure as the tuple
22772277+`<≡, 𝒫>`, where
22782278+22792279+- `≡ ⊆ Path × Path` where `π ≡ π'` if and only if `Δ(π, q0) = Δ(π', q0)` (path equivalence)
22802280+- `P: Path → ℙ` is `υ(Δ(π, q))` (path value).
22812281+22822282+A struct `a = <≡, 𝒫>` subsumes a struct `b = <≡', 𝒫'>`, or `a ⊑ b`,
22832283+if and only if
22842284+22852285+- `π ≡ π'` implied `π ≡' π'`, and
22862286+- `𝒫(π) = v` implies `𝒫'(π) = v'` and `v' ⊑ v`
22872287+-->
22882288+22892289+#### References
22902290+Theory:
22912291+- [1992] Bob Carpenter, "The logic of typed feature structures.";
22922292+ Cambridge University Press, ISBN:0-521-41932-8
22932293+- [2002] Ann Copestake, "Implementing Typed Feature Structure Grammars.";
22942294+ CSLI Publications, ISBN 1-57586-261-1
22952295+22962296+Some graph unification algorithms:
22972297+22982298+- [1985] Fernando C. N. Pereira, "A structure-sharing representation for
22992299+ unification-based grammar formalisms."; In Proc. of the 23rd Annual Meeting of
23002300+ the Association for Computational Linguistics. Chicago, IL
23012301+- [1991] H. Tomabechi, "Quasi-destructive graph unifications.."; In Proceedings
23022302+ of the 29th Annual Meeting of the ACL. Berkeley, CA
23032303+- [1992] Hideto Tomabechi, "Quasi-destructive graph ynifications with structure-
23042304+ sharing."; In Proceedings of the 15th International Conference on
23052305+ Computational Linguistics (COLING-92), Nantes, France.
23062306+- [2001] Marcel van Lohuizen, "Memory-efficient and thread-safe
23072307+ quasi-destructive graph unification."; In Proceedings of the 38th Meeting of
23082308+ the Association for Computational Linguistics. Hong Kong, China.
23092309+23102310+23112311+### Evaluation
23122312+23132313+The _evaluation_ of a CUE configuration `C` is defined as the process of
23142314+making `C` well-formed.
23152315+23162316+This document does not define any operational semantics.
23172317+As the unification operation is communitive, transitive, and reflexive,
23182318+implementations have a considerable amount of leeway in
23192319+chosing an evaluation strategy.
23202320+Although most algorithms for the unification of typed attribute structure
23212321+that have been proposed are `O(n)`, there can be considerable performance
23222322+benefits of chosing one of the many proposed evaluation strategies over the
23232323+other.
23242324+Implementations will need to be verified against the above formal definition.
23252325+23262326+23272327+23282328+#### Constraint functions
23292329+23302330+A _constraint function_ is a unary function `f` which for any input `a` only
23312331+returns values that are an instance of `a`. For instance, the constraint
23322332+function `f` for `string` returns `"foo"` for `f("foo")` and `_|_` for `f(1)`.
23332333+Constraint functions may take other constraint functions as arguments to
23342334+produce a more restricting constraint function.
23352335+For instance, the constraint function `f` for `0..8` returns `5` for `f(5)`,
23362336+`5..8` for `f(5..10)`, and `_|_` for `f("foo")`.
23372337+23382338+23392339+Constraint functions play a special role in unification.
23402340+The unification function `&(a, b)` is defined as
23412341+23422342+- `a & b` if `a` and `b` are two atoms
23432343+- `a & b` if `a` and `b` are two nodes, respresenting struct
23442344+- `a(b)` or `b(a)` if either `a` or `b` is a constraint function, respectively.
23452345+23462346+Implementations are free to pick which constraint function is applied if
23472347+both `a` and `b` are constraint functions, as the properties of unification
23482348+will ensure this produces identical results.
23492349+23502350+#### Manifestation
23512351+23522352+TODO: a prototype which is a function invocation that cannot be evaluated
23532353+or for which the result is not an atom or a struct is called _incomplete_.
23542354+23552355+23562356+23572357+### Validation
23582358+23592359+TODO: when to proactively do recursive validation
23602360+23612361+#### References
23622362+23632363+A distinguising feature of CUE's unification algorithm is the use of references.
23642364+In conventional graph unification for typed feature structures, the structures
23652365+that are unified into the existing graph are independent and pre-evaluated.
23662366+In CUE, the constraint structures indicated by references may still need to
23672367+be evaluated.
23682368+Some conventional evaluation strategy may not cope well with references that
23692369+refer to each other.
23702370+The simple solution is to deploy a bread-first evaluation strategy, rather than
23712371+the more traditional depth-first approach.
23722372+Other approaches are possible, however, and implementations are free to choose
23732373+which approach is deployed.
23742374+23752375+### Cycles
23762376+23772377+TODO: describe precisely which cycles must be resolved by implementations.
23782378+23792379+Rules:
23802380+23812381+- Unification of atom value `a` with non-concrete atom `b` for node `q`:
23822382+ - set `q` to `a` and schedule the evalution `a == b` at the end of
23832383+ evaluating `q`: `C` is only correct under the assumption that `q` is `a`
23842384+ so evaluate later.
23852385+23862386+A direct cyclic reference between nodes defines a shared node for the paths
23872387+of the original nodes.
23882388+23892389+- Unification of cycle of references of struct,
23902390+ for instance: `{ a: b, b: c, c: a }`
23912391+ - ignore the cycle and continue evaluating not including the last unification:
23922392+ a unification of a value with itself is itself. As `a` was already included,
23932393+ ignoring the cycle will produce the same result.
23942394+23952395+```
23962396+Configuration Evaluated
23972397+// c Cycles in nodes of type struct evaluate
23982398+// ↙︎ ↖ to the fixed point of unifying their.
23992399+// a → b values
24002400+24012401+a: b // a: { x: 1, y: 3 }
24022402+b: c // b: { x: 1, y: 3 }
24032403+c: a // c: { x: 1, y: 3 }
24042404+24052405+a: { x: 1 }
24062406+b: { y: 3 }
24072407+```
24082408+24092409+24102410+1. Cycle breaking
24112411+1. Cycle detection
24122412+1. Assertion checks
24132413+1. Validation
24142414+24152415+The preparation step loads all the relevant CUE sources and merges duplicate
24162416+by creating unification expressions until each field is unique within its scope.
24172417+24182418+24192419+For fields of type struct any cycle that does not result in an infinite
24202420+structure is allowed.
24212421+An expresion of type struct only allows unification and disjunction operations.
24222422+24232423+Unification of structs is done by unifying a copy of each of the input structs.
24242424+A copy of a referenced input struct may itself contain references which are
24252425+handled with the following rules:
24262426+- a reference bound to a field that it is being copied is replaced
24272427+ with a new reference pointing to the respective copy,
24282428+- a reference bound to a field that is not being copied refers to the
24292429+ original field.
24302430+24312431+24322432+#### Self-referential cycles
24332433+24342434+A graph unification algorithm like Tomabechi [] or Van Lohuizen [] can be used
24352435+to handle the reference replacement rules and minimize the cost of
24362436+copying and cycle detection.
24372437+24382438+Unification of lists, which are expressible as structs, follow along the same
24392439+lines.
24402440+24412441+For an expression `a & b` of any scalar type where exactly one of `a` or `b` is
24422442+a concrete value, the result may be replaced by this concrete value while
24432443+adding the expression `a == b` to the list of assertions.
24442444+24452445+```
24462446+// Config Evaluates to
24472447+x: { x: {
24482448+ a: b + 100 a: ⊥ // cycle detected
24492449+ b: a - 100 b: ⊥ // cycle detected
24502450+} }
24512451+24522452+y: x & { y: {
24532453+ a: 200 a: 200 // asserted that 200 == b + 100
24542454+ b: 100
24552455+} }
24562456+```
24572457+24582458+During the evaluation of a field which expression is being evaluated is marked as such.
24592459+24602460+A field `f` with unification expression `e` where `e` contains reference that in turn
24612461+point to `a` can be handled as follows:
24622462+24632463+#### Evaluation cycles
24642464+24652465+For structs, cycles are disallowed
24662466+24672467+Disallowed cycles:
24682468+24692469+A field `a` is _reachable_ from field `b` if there is a selector sequence
24702470+from `a` to `b`.
24712471+24722472+A reference used in field `a` may not refer to a value that recursively
24732473+refers to a value that is reachable from `a`.
24742474+24752475+```
24762476+a: b & { c: 3 }
24772477+24782478+b: a.c // illegal reference
24792479+24802480+```
24812481+24822482+#### Structural cycles
24832483+24842484+A reference to `Δ(π, q0)` may not recursively refer to `Δ(π', q)`,
24852485+where `π` is a prefix to `π'`.
24862486+24872487+24882488+a: b & { b: _ }
24892489+24902490+24912491+### Validation
24922492+24932493+Implementations are allowed to postpone recursive unification of structures
24942494+except for in the following cases:
24952495+24962496+- Unification within disjunctions:
24972497+24982498+24992499+<!--
25002500+### Inference
25012501+25022502+There is currently no logical inference for values of references prescribed.
25032503+It mostly relies on users defining the value of all variables.
25042504+The main reason for this is to keep control over run time complexity.
25052505+However, implementations may be free to do so.
25062506+Also, later versions of the language may strengthen requirements for resolution.
25072507+25082508+TODO: examples of situations where variables could be resolved but are not.
25092509+-->
25102510+25112511+### Unused values
25122512+25132513+TODO: rules for detection of unused variables
25142514+25152515+1. Any alias value must be used
25162516+