blob: 9e2efa869e014326c4fb9cd5bdcf0869d3e014fd [file] [log] [blame] [view]
Marcel van Lohuizen6f0faec2018-12-16 10:42:42 +01001<!--
2 Copyright 2018 The CUE Authors
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15-->
16
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +010017# The CUE Language Specification
18
19## Introduction
20
Marcel van Lohuizen5953c662019-01-26 13:26:04 +010021This is a reference manual for the CUE data constraint language.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +010022CUE, pronounced cue or Q, is a general-purpose and strongly typed
Marcel van Lohuizen5953c662019-01-26 13:26:04 +010023constraint-based language.
24It can be used for data templating, data validation, code generation, scripting,
25and many other applications involving structured data.
26The CUE tooling, layered on top of CUE, provides
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +010027a general purpose scripting language for creating scripts as well as
Marcel van Lohuizen5953c662019-01-26 13:26:04 +010028simple servers, also expressed in CUE.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +010029
30CUE was designed with cloud configuration, and related systems, in mind,
31but is not limited to this domain.
32It derives its formalism from relational programming languages.
33This formalism allows for managing and reasoning over large amounts of
Marcel van Lohuizen5953c662019-01-26 13:26:04 +010034data in a straightforward manner.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +010035
36The grammar is compact and regular, allowing for easy analysis by automatic
37tools such as integrated development environments.
38
39This document is maintained by mpvl@golang.org.
40CUE has a lot of similarities with the Go language. This document draws heavily
Marcel van Lohuizen73f14eb2019-01-30 17:11:17 +010041from the Go specification as a result.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +010042
43CUE draws its influence from many languages.
44Its main influences were BCL/ GCL (internal to Google),
45LKB (LinGO), Go, and JSON.
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +020046Others are Swift, Typescript, Javascript, Prolog, NCL (internal to Google),
Marcel van Lohuizen62658a82019-06-16 12:18:47 +020047Jsonnet, HCL, Flabbergast, Nix, JSONPath, Haskell, Objective-C, and Python.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +010048
49
50## Notation
51
52The syntax is specified using Extended Backus-Naur Form (EBNF):
53
54```
55Production = production_name "=" [ Expression ] "." .
56Expression = Alternative { "|" Alternative } .
57Alternative = Term { Term } .
58Term = production_name | token [ "…" token ] | Group | Option | Repetition .
59Group = "(" Expression ")" .
60Option = "[" Expression "]" .
61Repetition = "{" Expression "}" .
62```
63
64Productions are expressions constructed from terms and the following operators,
65in increasing precedence:
66
67```
68| alternation
69() grouping
70[] option (0 or 1 times)
71{} repetition (0 to n times)
72```
73
74Lower-case production names are used to identify lexical tokens. Non-terminals
75are in CamelCase. Lexical tokens are enclosed in double quotes "" or back quotes
76``.
77
78The form a … b represents the set of characters from a through b as
79alternatives. The horizontal ellipsis … is also used elsewhere in the spec to
80informally denote various enumerations or code snippets that are not further
81specified. The character … (as opposed to the three characters ...) is not a
Roger Peppeded0e1d2019-09-24 16:39:36 +010082token of the CUE language.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +010083
84
85## Source code representation
86
87Source code is Unicode text encoded in UTF-8.
88Unless otherwise noted, the text is not canonicalized, so a single
89accented code point is distinct from the same character constructed from
90combining an accent and a letter; those are treated as two code points.
91For simplicity, this document will use the unqualified term character to refer
92to a Unicode code point in the source text.
93
94Each code point is distinct; for instance, upper and lower case letters are
95different characters.
96
97Implementation restriction: For compatibility with other tools, a compiler may
98disallow the NUL character (U+0000) in the source text.
99
100Implementation restriction: For compatibility with other tools, a compiler may
101ignore a UTF-8-encoded byte order mark (U+FEFF) if it is the first Unicode code
102point in the source text. A byte order mark may be disallowed anywhere else in
103the source.
104
105
106### Characters
107
108The following terms are used to denote specific Unicode character classes:
109
110```
111newline = /* the Unicode code point U+000A */ .
112unicode_char = /* an arbitrary Unicode code point except newline */ .
113unicode_letter = /* a Unicode code point classified as "Letter" */ .
114unicode_digit = /* a Unicode code point classified as "Number, decimal digit" */ .
115```
116
117In The Unicode Standard 8.0, Section 4.5 "General Category" defines a set of
118character categories.
119CUE treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo
120as Unicode letters, and those in the Number category Nd as Unicode digits.
121
122
123### Letters and digits
124
125The underscore character _ (U+005F) is considered a letter.
126
127```
128letter = unicode_letter | "_" .
129decimal_digit = "0" … "9" .
130octal_digit = "0" … "7" .
131hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
132```
133
134
135## Lexical elements
136
137### Comments
Marcel van Lohuizen7fc421b2019-09-11 09:24:03 +0200138Comments serve as program documentation.
139CUE supports line comments that start with the character sequence //
140and stop at the end of the line.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100141
Marcel van Lohuizen7fc421b2019-09-11 09:24:03 +0200142A comment cannot start inside a string literal or inside a comment.
143A comment acts like a newline.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100144
145
146### Tokens
147
148Tokens form the vocabulary of the CUE language. There are four classes:
149identifiers, keywords, operators and punctuation, and literals. White space,
150formed from spaces (U+0020), horizontal tabs (U+0009), carriage returns
151(U+000D), and newlines (U+000A), is ignored except as it separates tokens that
152would otherwise combine into a single token. Also, a newline or end of file may
153trigger the insertion of a comma. While breaking the input into tokens, the
154next token is the longest sequence of characters that form a valid token.
155
156
157### Commas
158
159The formal grammar uses commas "," as terminators in a number of productions.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500160CUE programs may omit most of these commas using the following two rules:
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100161
162When the input is broken into tokens, a comma is automatically inserted into
163the token stream immediately after a line's final token if that token is
164
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500165- an identifier
166- null, true, false, bottom, or an integer, floating-point, or string literal
167- one of the characters ), ], or }
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100168
169
170Although commas are automatically inserted, the parser will require
171explicit commas between two list elements.
172
173To reflect idiomatic use, examples in this document elide commas using
174these rules.
175
176
177### Identifiers
178
179Identifiers name entities such as fields and aliases.
Marcel van Lohuizen8a2df962019-11-10 00:14:24 +0100180An identifier is a sequence of one or more letters (which includes `_` and `$`)
Marcel van Lohuizenb7083ff2020-05-12 11:38:19 +0200181and digits, optionally preceded by `#` or `_#`.
Marcel van Lohuizendbf1c002020-05-16 14:19:34 +0200182It may not be `_` or `$`.
183The first character in an identifier, or after an `#` if it contains one,
184must be a letter.
Marcel van Lohuizenb7083ff2020-05-12 11:38:19 +0200185Identifiers starting with a `#` or `_` are reserved for definitions and hidden
186fields.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100187
188<!--
189TODO: allow identifiers as defined in Unicode UAX #31
190(https://unicode.org/reports/tr31/).
191
192Identifiers are normalized using the NFC normal form.
193-->
194
195```
Marcel van Lohuizenb7083ff2020-05-12 11:38:19 +0200196identifier = [ "#" | "_#" ] letter { letter | unicode_digit } .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100197```
198
199```
200a
201_x9
202fieldName
203αβ
204```
205
206<!-- TODO: Allow Unicode identifiers TR 32 http://unicode.org/reports/tr31/ -->
207
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500208Some identifiers are [predeclared](#predeclared-identifiers).
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100209
210
211### Keywords
212
213CUE has a limited set of keywords.
Marcel van Lohuizen40178752019-08-25 19:17:56 +0200214In addition, CUE reserves all identifiers starting with `__`(double underscores)
215as keywords.
216These are typically targets of pre-declared identifiers.
217
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100218All keywords may be used as labels (field names).
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +0200219Unless noted otherwise, they can also be used as identifiers to refer to
220the same name.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100221
222
223#### Values
224
225The following keywords are values.
226
227```
228null true false
229```
230
231These can never be used to refer to a field of the same name.
232This restriction is to ensure compatibility with JSON configuration files.
233
234
235#### Preamble
236
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100237The following keywords are used at the preamble of a CUE file.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100238After the preamble, they may be used as identifiers to refer to namesake fields.
239
240```
241package import
242```
243
244
245#### Comprehension clauses
246
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100247The following keywords are used in comprehensions.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100248
249```
250for in if let
251```
252
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100253<!--
254TODO:
255 reduce [to]
256 order [by]
257-->
258
259
260#### Arithmetic
261
262The following pseudo keywords can be used as operators in expressions.
263
264```
265div mod quo rem
266```
267
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100268### Operators and punctuation
269
270The following character sequences represent operators and punctuation:
271
272```
Marcel van Lohuizen40178752019-08-25 19:17:56 +0200273+ div && == < = ( )
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +0100274- mod || != > : { }
275* quo & =~ <= ? [ ] ,
276/ rem | !~ >= ! _|_ ... .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100277```
Marcel van Lohuizen40178752019-08-25 19:17:56 +0200278<!--
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +0100279Free tokens: ; ~ ^
Marcel van Lohuizen40178752019-08-25 19:17:56 +0200280// To be used:
281 @ at: associative lists.
282
283// Idea: use # instead of @ for attributes and allow then at declaration level.
284// This will open up the possibility of defining #! at the start of a file
285// without requiring special syntax. Although probably not quite.
286 -->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100287
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +0100288
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100289### Integer literals
290
291An integer literal is a sequence of digits representing an integer value.
Marcel van Lohuizenb2703c62019-09-29 18:20:01 +0200292An optional prefix sets a non-decimal base: 0o for octal,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002930x or 0X for hexadecimal, and 0b for binary.
294In hexadecimal literals, letters a-f and A-F represent values 10 through 15.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500295All integers allow interstitial underscores "_";
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100296these have no meaning and are solely for readability.
297
298Decimal integers may have a SI or IEC multiplier.
299Multipliers can be used with fractional numbers.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500300When multiplying a fraction by a multiplier, the result is truncated
301towards zero if it is not an integer.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100302
303```
Marcel van Lohuizenafb4db62019-05-31 00:23:24 +0200304int_lit = decimal_lit | si_lit | octal_lit | binary_lit | hex_lit .
305decimal_lit = ( "1" … "9" ) { [ "_" ] decimal_digit } .
306decimals = decimal_digit { [ "_" ] decimal_digit } .
307si_it = decimals [ "." decimals ] multiplier |
308 "." decimals multiplier .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100309binary_lit = "0b" binary_digit { binary_digit } .
310hex_lit = "0" ( "x" | "X" ) hex_digit { [ "_" ] hex_digit } .
Marcel van Lohuizenb2703c62019-09-29 18:20:01 +0200311octal_lit = "0o" octal_digit { [ "_" ] octal_digit } .
Marcel van Lohuizen6eefcd02019-10-04 13:32:06 +0200312multiplier = ( "K" | "M" | "G" | "T" | "P" ) [ "i" ]
Marcel van Lohuizenafb4db62019-05-31 00:23:24 +0200313
314float_lit = decimals "." [ decimals ] [ exponent ] |
315 decimals exponent |
316 "." decimals [ exponent ].
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +0200317exponent = ( "e" | "E" ) [ "+" | "-" ] decimals .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100318```
Marcel van Lohuizen6eefcd02019-10-04 13:32:06 +0200319<!--
320TODO: consider allowing Exo (and up), if not followed by a sign
321or number. Alternatively one could only allow Ei, Yi, and Zi.
322-->
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +0100323
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100324```
32542
3261.5Gi
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100327170_141_183_460_469_231_731_687_303_715_884_105_727
Marcel van Lohuizenfc6303c2019-02-07 17:49:04 +01003280xBad_Face
3290o755
3300b0101_0001
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100331```
332
333### Decimal floating-point literals
334
335A decimal floating-point literal is a representation of
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500336a decimal floating-point value (a _float_).
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100337It has an integer part, a decimal point, a fractional part, and an
338exponent part.
339The integer and fractional part comprise decimal digits; the
340exponent part is an `e` or `E` followed by an optionally signed decimal exponent.
341One of the integer part or the fractional part may be elided; one of the decimal
342point or the exponent may be elided.
343
344```
345decimal_lit = decimals "." [ decimals ] [ exponent ] |
346 decimals exponent |
347 "." decimals [ exponent ] .
348exponent = ( "e" | "E" ) [ "+" | "-" ] decimals .
349```
350
351```
3520.
35372.40
354072.40 // == 72.40
3552.71828
3561.e+0
3576.67428e-11
3581E6
359.25
360.12345E+5
361```
362
363
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100364### String and byte sequence literals
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100365
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100366A string literal represents a string constant obtained from concatenating a
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100367sequence of characters.
368Byte sequences are a sequence of bytes.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100369
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100370String and byte sequence literals are character sequences between,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100371respectively, double and single quotes, as in `"bar"` and `'bar'`.
372Within the quotes, any character may appear except newline and,
373respectively, unescaped double or single quote.
374String literals may only be valid UTF-8.
375Byte sequences may contain any sequence of bytes.
376
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400377Several escape sequences allow arbitrary values to be encoded as ASCII text.
378An escape sequence starts with an _escape delimiter_, which is `\` by default.
379The escape delimiter may be altered to be `\` plus a fixed number of
380hash symbols `#`
381by padding the start and end of a string or byte sequence literal
382with this number of hash symbols.
383
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100384There are four ways to represent the integer value as a numeric constant: `\x`
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400385followed by exactly two hexadecimal digits; `\u` followed by exactly four
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100386hexadecimal digits; `\U` followed by exactly eight hexadecimal digits, and a
387plain backslash `\` followed by exactly three octal digits.
388In each case the value of the literal is the value represented by the
389digits in the corresponding base.
390Hexadecimal and octal escapes are only allowed within byte sequences
391(single quotes).
392
393Although these representations all result in an integer, they have different
394valid ranges.
395Octal escapes must represent a value between 0 and 255 inclusive.
396Hexadecimal escapes satisfy this condition by construction.
397The escapes `\u` and `\U` represent Unicode code points so within them
398some values are illegal, in particular those above `0x10FFFF`.
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400399Surrogate halves are allowed,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100400but are translated into their non-surrogate equivalent internally.
401
402The three-digit octal (`\nnn`) and two-digit hexadecimal (`\xnn`) escapes
403represent individual bytes of the resulting string; all other escapes represent
404the (possibly multi-byte) UTF-8 encoding of individual characters.
405Thus inside a string literal `\377` and `\xFF` represent a single byte of
406value `0xFF=255`, while `ÿ`, `\u00FF`, `\U000000FF` and `\xc3\xbf` represent
407the two bytes `0xc3 0xbf` of the UTF-8
408encoding of character `U+00FF`.
409
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100410```
411\a U+0007 alert or bell
412\b U+0008 backspace
413\f U+000C form feed
414\n U+000A line feed or newline
415\r U+000D carriage return
416\t U+0009 horizontal tab
417\v U+000b vertical tab
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100418\/ U+002f slash (solidus)
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100419\\ U+005c backslash
420\' U+0027 single quote (valid escape only within single quoted literals)
421\" U+0022 double quote (valid escape only within double quoted literals)
422```
423
424The escape `\(` is used as an escape for string interpolation.
425A `\(` must be followed by a valid CUE Expression, followed by a `)`.
426
427All other sequences starting with a backslash are illegal inside literals.
428
429```
Marcel van Lohuizen39df6c92019-10-25 20:16:26 +0200430escaped_char = `\` { `#` } ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | "/" | `\` | "'" | `"` ) .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100431byte_value = octal_byte_value | hex_byte_value .
432octal_byte_value = `\` octal_digit octal_digit octal_digit .
433hex_byte_value = `\` "x" hex_digit hex_digit .
434little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .
435big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit
436 hex_digit hex_digit hex_digit hex_digit .
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400437unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
438interpolation = "\(" Expression ")" .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100439
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400440string_lit = simple_string_lit |
441 multiline_string_lit |
442 simple_bytes_lit |
443 multiline_bytes_lit |
444 `#` string_lit `#` .
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100445
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400446simple_string_lit = `"` { unicode_value | interpolation } `"` .
Marcel van Lohuizenc6e5d172019-11-22 12:09:25 -0800447simple_bytes_lit = `'` { unicode_value | interpolation | byte_value } `'` .
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400448multiline_string_lit = `"""` newline
449 { unicode_value | interpolation | newline }
450 newline `"""` .
451multiline_bytes_lit = "'''" newline
452 { unicode_value | interpolation | byte_value | newline }
453 newline "'''" .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100454```
455
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400456Carriage return characters (`\r`) inside string literals are discarded from
Marcel van Lohuizendb9d25a2019-02-21 23:54:43 +0100457the string value.
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400458
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100459```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100460'a\000\xab'
461'\007'
462'\377'
463'\xa' // illegal: too few hexadecimal digits
464"\n"
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +0100465"\""
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100466'Hello, world!\n'
467"Hello, \( name )!"
468"日本語"
469"\u65e5本\U00008a9e"
470"\xff\u00FF"
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +0100471"\uD800" // illegal: surrogate half (TODO: probably should allow)
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100472"\U00110000" // illegal: invalid Unicode code point
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400473
474#"This is not an \(interpolation)"#
475#"This is an \#(interpolation)"#
476#"The sequence "\U0001F604" renders as \#U0001F604."#
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100477```
478
479These examples all represent the same string:
480
481```
482"日本語" // UTF-8 input text
483'日本語' // UTF-8 input text as byte sequence
484`日本語` // UTF-8 input text as a raw literal
485"\u65e5\u672c\u8a9e" // the explicit Unicode code points
486"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points
487"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
488```
489
490If the source code represents a character as two code points, such as a
491combining form involving an accent and a letter, the result will appear as two
492code points if placed in a string literal.
493
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400494Strings and byte sequences have a multiline equivalent.
495Multiline strings are like their single-line equivalent,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100496but allow newline characters.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100497
Marcel van Lohuizen369e4232019-02-15 10:59:29 +0400498Multiline strings and byte sequences respectively start with
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100499a triple double quote (`"""`) or triple single quote (`'''`),
500immediately followed by a newline, which is discarded from the string contents.
501The string is closed by a matching triple quote, which must be by itself
502on a newline, preceded by optional whitespace.
Marcel van Lohuizenc8d6c392019-12-02 13:30:47 +0100503The newline preceding the closing quote is discarded from the string contents.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100504The whitespace before a closing triple quote must appear before any non-empty
505line after the opening quote and will be removed from each of these
506lines in the string literal.
507A closing triple quote may not appear in the string.
508To include it is suffices to escape one of the quotes.
509
510```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100511"""
512 lily:
513 out of the water
514 out of itself
515
516 bass
517 picking bugs
518 off the moon
519 — Nick Virgilio, Selected Haiku, 1988
520 """
521```
522
523This represents the same string as:
524
525```
526"lily:\nout of the water\nout of itself\n\n" +
527"bass\npicking bugs\noff the moon\n" +
528" — Nick Virgilio, Selected Haiku, 1988"
529```
530
531<!-- TODO: other values
532
533Support for other values:
534- Duration literals
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +0100535- regular expessions: `re("[a-z]")`
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100536-->
537
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500538
539## Values
540
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100541In addition to simple values like `"hello"` and `42.0`, CUE has _structs_.
542A struct is a map from labels to values, like `{a: 42.0, b: "hello"}`.
543Structs are CUE's only way of building up complex values;
544lists, which we will see later,
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500545are defined in terms of structs.
546
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100547All possible values are ordered in a lattice,
548a partial order where every two elements have a single greatest lower bound.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500549A value `a` is an _instance_ of a value `b`,
550denoted `a ⊑ b`, if `b == a` or `b` is more general than `a`,
551that is if `a` orders before `b` in the partial order
552(`⊑` is _not_ a CUE operator).
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100553We also say that `b` _subsumes_ `a` in this case.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500554In graphical terms, `b` is "above" `a` in the lattice.
555
556At the top of the lattice is the single ancestor of all values, called
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100557_top_, denoted `_` in CUE.
558Every value is an instance of top.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500559
560At the bottom of the lattice is the value called _bottom_, denoted `_|_`.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100561A bottom value usually indicates an error.
562Bottom is an instance of every value.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500563
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100564An _atom_ is any value whose only instances are itself and bottom.
565Examples of atoms are `42.0`, `"hello"`, `true`, `null`.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500566
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100567A value is _concrete_ if it is either an atom, or a struct all of whose
568field values are themselves concrete, recursively.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500569
570CUE's values also include what we normally think of as types, like `string` and
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100571`float`.
572But CUE does not distinguish between types and values; only the
573relationship of values in the lattice is important.
574Each CUE "type" subsumes the concrete values that one would normally think
575of as part of that type.
576For example, "hello" is an instance of `string`, and `42.0` is an instance of
577`float`.
578In addition to `string` and `float`, CUE has `null`, `int`, `bool` and `bytes`.
579We informally call these CUE's "basic types".
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100580
581
582```
583false ⊑ bool
584true ⊑ bool
585true ⊑ true
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01005865.0 ⊑ float
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100587bool ⊑ _
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100588_|_ ⊑ _
589_|_ ⊑ _|_
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100590
Marcel van Lohuizen6f0faec2018-12-16 10:42:42 +0100591_ ⋢ _|_
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100592_ ⋢ bool
593int ⋢ bool
594bool ⋢ int
595false ⋢ true
596true ⋢ false
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100597float ⋢ 5.0
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01005985 ⋢ 6
599```
600
601
602### Unification
603
Jonathan Amsterdama8d8a3c2019-02-03 07:53:55 -0500604The _unification_ of values `a` and `b`
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100605is defined as the greatest lower bound of `a` and `b`. (That is, the
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500606value `u` such that `u ⊑ a` and `u ⊑ b`,
607and for any other value `v` for which `v ⊑ a` and `v ⊑ b`
608it holds that `v ⊑ u`.)
Jonathan Amsterdama8d8a3c2019-02-03 07:53:55 -0500609Since CUE values form a lattice, the unification of two CUE values is
Jonathan Amsterdam061bde12019-09-03 08:28:10 -0400610always unique.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100611
Jonathan Amsterdama8d8a3c2019-02-03 07:53:55 -0500612These all follow from the definition of unification:
613- The unification of `a` with itself is always `a`.
614- The unification of values `a` and `b` where `a ⊑ b` is always `a`.
615- The unification of a value with bottom is always bottom.
616
617Unification in CUE is a [binary expression](#Operands), written `a & b`.
618It is commutative and associative.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100619As a consequence, order of evaluation is irrelevant, a property that is key
620to many of the constructs in the CUE language as well as the tooling layered
621on top of it.
622
Jonathan Amsterdama8d8a3c2019-02-03 07:53:55 -0500623
624
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100625<!-- TODO: explicitly mention that disjunction is not a binary operation
626but a definition of a single value?-->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100627
Marcel van Lohuizen69139d62019-01-24 13:46:51 +0100628
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100629### Disjunction
630
Jonathan Amsterdama8d8a3c2019-02-03 07:53:55 -0500631The _disjunction_ of values `a` and `b`
632is defined as the least upper bound of `a` and `b`.
633(That is, the value `d` such that `a ⊑ d` and `b ⊑ d`,
634and for any other value `e` for which `a ⊑ e` and `b ⊑ e`,
635it holds that `d ⊑ e`.)
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100636This style of disjunctions is sometimes also referred to as sum types.
Jonathan Amsterdama8d8a3c2019-02-03 07:53:55 -0500637Since CUE values form a lattice, the disjunction of two CUE values is always unique.
638
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100639
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500640These all follow from the definition of disjunction:
641- The disjunction of `a` with itself is always `a`.
642- The disjunction of a value `a` and `b` where `a ⊑ b` is always `b`.
643- The disjunction of a value `a` with bottom is always `a`.
644- The disjunction of two bottom values is bottom.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100645
Jonathan Amsterdama8d8a3c2019-02-03 07:53:55 -0500646Disjunction in CUE is a [binary expression](#Operands), written `a | b`.
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100647It is commutative, associative, and idempotent.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100648
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100649The unification of a disjunction with another value is equal to the disjunction
650composed of the unification of this value with all of the original elements
651of the disjunction.
652In other words, unification distributes over disjunction.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100653
654```
Marcel van Lohuizen69139d62019-01-24 13:46:51 +0100655(a_0 | ... |a_n) & b ==> a_0&b | ... | a_n&b.
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100656```
657
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100658```
659Expression Result
660({a:1} | {b:2}) & {c:3} {a:1, c:3} | {b:2, c:3}
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100661(int | string) & "foo" "foo"
662("a" | "b") & "c" _|_
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100663```
664
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100665A disjunction is _normalized_ if there is no element
666`a` for which there is an element `b` such that `a ⊑ b`.
667
668<!--
669Normalization is important, as we need to account for spurious elements
670For instance "tcp" | "tcp" should resolve to "tcp".
671
672Also consider
673
674 ({a:1} | {b:1}) & ({a:1} | {b:2}) -> {a:1} | {a:1,b:1} | {a:1,b:2},
675
676in this case, elements {a:1,b:1} and {a:1,b:2} are subsumed by {a:1} and thus
677this expression is logically equivalent to {a:1} and should therefore be
678considered to be unambiguous and resolve to {a:1} if a concrete value is needed.
679
680For instance, in
681
682 x: ({a:1} | {b:1}) & ({a:1} | {b:2}) // -> {a:1} | {a:1,b:1} | {a:1,b:2}
683 y: x.a // 1
684
685y should resolve to 1, and not an error.
686
687For comparison, in
688
689 x: ({a:1, b:1} | {b:2}) & {a:1} // -> {a:1,b:1} | {a:1,b:2}
690 y: x.a // _|_
691
692y should be an error as x is still ambiguous before the selector is applied,
693even though `a` resolves to 1 in all cases.
694-->
695
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500696
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100697#### Default values
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500698
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100699Any element of a disjunction can be marked as a default
Axel Wagner8529d772019-09-24 18:27:12 +0000700by prefixing it with an asterisk `*`.
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100701Intuitively, when an expression needs to be resolved for an operation other
702than unification or disjunctions,
703non-starred elements are dropped in favor of starred ones if the starred ones
704do not resolve to bottom.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500705
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100706More precisely, any value `v` may be associated with a default value `d`,
707denoted `(v, d)` (not CUE syntax),
708where `d` must be in instance of `v` (`d ⊑ v`).
709The rules for unifying and disjoining such values are as follows:
710
711```
712U1: (v1, d1) & v2 => (v1&v2, d1&v2)
713U2: (v1, d1) & (v2, d2) => (v1&v2, d1&d2)
714
715D1: (v1, d1) | v2 => (v1|v2, d1)
716D2: (v1, d1) | (v2, d2) => (v1|v2, d1|d2)
717```
718
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100719Default values may be introduced within disjunctions
720by _marking_ terms of a disjunction with an asterisk `*`
721([a unary expression](#Operators)).
722The default value of a disjunction with marked terms is the disjunction
723of those marked terms, applying the following rules for marks:
724
725```
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +0200726M1: *v => (v, v)
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100727M2: *(v1, d1) => (v1, d1)
728```
729
Jonathan Amsterdam061bde12019-09-03 08:28:10 -0400730In general, any operation `f` in CUE involving default values proceeds along the
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +0200731following lines
732```
Jonathan Amsterdam061bde12019-09-03 08:28:10 -0400733O1: f((v1, d1), ..., (vn, dn)) => (f(v1, ..., vn), f(d1, ..., dn))
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +0200734```
735where, with the exception of disjunction, a value `v` without a default
736value is promoted to `(v, v)`.
737
738
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100739```
740Expression Value-default pair Rules applied
741*"tcp" | "udp" ("tcp"|"udp", "tcp") M1, D1
742string | *"foo" (string, "foo") M1, D1
743
744*1 | 2 | 3 (1|2|3, 1) M1, D1
745
746(*1|2|3) | (1|*2|3) (1|2|3, 1|2) M1, D1, D2
747(*1|2|3) | *(1|*2|3) (1|2|3, 1|2) M1, D1, M2, D2
748(*1|2|3) | (1|*2|3)&2 (1|2|3, 1|2) M1, D1, U1, D2
749
750(*1|2) & (1|*2) (1|2, _|_) M1, D1, U2
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +0200751
752(*1|2) + (1|*2) ((1|2)+(1|2), 3) M1, D1, O1
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100753```
754
755The rules of subsumption for defaults can be derived from the above definitions
756and are as follows.
757
758```
759(v2, d2) ⊑ (v1, d1) if v2 ⊑ v1 and d2 ⊑ d1
760(v1, d1) ⊑ v if v1 ⊑ v
761v ⊑ (v1, d1) if v ⊑ d1
762```
763
764<!--
765For the second rule, note that by definition d1 ⊑ v1, so d1 ⊑ v1 ⊑ v.
766
767The last one is so restrictive as v could still be made more specific by
768associating it with a default that is not subsumed by d1.
769
770Proof:
771 by definition for any d ⊑ v, it holds that (v, d) ⊑ v,
772 where the most general value is (v, v).
773 Given the subsumption rule for (v2, d2) ⊑ (v1, d1),
774 from (v, v) ⊑ v ⊑ (v1, d1) it follows that v ⊑ d1
775 exactly defines the boundary of this subsumption.
776-->
Marcel van Lohuizen69139d62019-01-24 13:46:51 +0100777
778<!--
779(non-normalized entries could also be implicitly marked, allowing writing
780int | 1, instead of int | *1, but that can be done in a backwards
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100781compatible way later if really desirable, as long as we require that
782disjunction literals be normalized).
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500783-->
784
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100785
786```
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100787Expression Resolves to
788"tcp" | "udp" "tcp" | "udp"
Marcel van Lohuizen69139d62019-01-24 13:46:51 +0100789*"tcp" | "udp" "tcp"
790float | *1 1
791*string | 1.0 string
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100792
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100793(*1|2|3) | (1|*2|3) 1|2
794(*1|2|3) & (1|*2|3) 1|2|3 // default is _|_
795
796(* >=5 | int) & (* <=5 | int) 5
797
Marcel van Lohuizen69139d62019-01-24 13:46:51 +0100798(*"tcp"|"udp") & ("udp"|*"tcp") "tcp"
799(*"tcp"|"udp") & ("udp"|"tcp") "tcp"
800(*"tcp"|"udp") & "tcp" "tcp"
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100801(*"tcp"|"udp") & (*"udp"|"tcp") "tcp" | "udp" // default is _|_
Marcel van Lohuizen69139d62019-01-24 13:46:51 +0100802
803(*true | false) & bool true
804(*true | false) & (true | false) true
805
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100806{a: 1} | {b: 1} {a: 1} | {b: 1}
Marcel van Lohuizen69139d62019-01-24 13:46:51 +0100807{a: 1} | *{b: 1} {b:1}
Marcel van Lohuizen6e5d9932019-03-14 15:52:48 +0100808*{a: 1} | *{b: 1} {a: 1} | {b: 1}
809({a: 1} | {b: 1}) & {a:1} {a:1} // after eliminating {a:1,b:1} by normalization
810({a:1}|*{b:1}) & ({a:1}|*{b:1}) {b:1} // after eliminating {a:1,b:1} by normalization
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100811```
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500812
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100813
814### Bottom and errors
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100815
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100816Any evaluation error in CUE results in a bottom value, respresented by
Axel Wagner8529d772019-09-24 18:27:12 +0000817the token `_|_`.
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100818Bottom is an instance of every other value.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100819Any evaluation error is represented as bottom.
820
821Implementations may associate error strings with different instances of bottom;
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500822logically they all remain the same value.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100823
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100824
825### Top
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100826
Axel Wagner8529d772019-09-24 18:27:12 +0000827Top is represented by the underscore character `_`, lexically an identifier.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100828Unifying any value `v` with top results `v` itself.
829
830```
831Expr Result
832_ & 5 5
833_ & _ _
834_ & _|_ _|_
835_ | _|_ _
836```
837
838
839### Null
840
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100841The _null value_ is represented with the keyword `null`.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100842It has only one parent, top, and one child, bottom.
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100843It is unordered with respect to any other value.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100844
845```
846null_lit = "null"
847```
848
849```
Marcel van Lohuizen6f0faec2018-12-16 10:42:42 +0100850null & 8 _|_
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100851null & _ null
852null & _|_ _|_
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100853```
854
855
856### Boolean values
857
858A _boolean type_ represents the set of Boolean truth values denoted by
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100859the keywords `true` and `false`.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100860The predeclared boolean type is `bool`; it is a defined type and a separate
861element in the lattice.
862
863```
864boolean_lit = "true" | "false"
865```
866
867```
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100868bool & true true
869true & true true
870true & false _|_
871bool & (false|true) false | true
872bool & (true|false) true | false
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100873```
874
875
876### Numeric values
877
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500878The _integer type_ represents the set of all integral numbers.
879The _decimal floating-point type_ represents the set of all decimal floating-point
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100880numbers.
881They are two distinct types.
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +0200882Both are instances instances of a generic `number` type.
883
884<!--
885 number
886 / \
887 int float
888-->
889
890The predeclared number, integer, decimal floating-point types are
891`number`, `int` and `float`; they are defined types.
892<!--
893TODO: should we drop float? It is somewhat preciser and probably a good idea
894to have it in the programmatic API, but it may be confusing to have to deal
895with it in the language.
896-->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100897
898A decimal floating-point literal always has type `float`;
899it is not an instance of `int` even if it is an integral number.
900
Jonathan Amsterdam061bde12019-09-03 08:28:10 -0400901Integer literals are always of type `int` and don't match type `float`.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100902
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100903Numeric literals are exact values of arbitrary precision.
904If the operation permits it, numbers should be kept in arbitrary precision.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100905
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100906Implementation restriction: although numeric values have arbitrary precision
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100907in the language, implementations may implement them using an internal
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100908representation with limited precision.
909That said, every implementation must:
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100910
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500911- Represent integer values with at least 256 bits.
912- Represent floating-point values, with a mantissa of at least 256 bits and
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100913a signed binary exponent of at least 16 bits.
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500914- Give an error if unable to represent an integer value precisely.
915- Give an error if unable to represent a floating-point value due to overflow.
916- Round to the nearest representable value if unable to represent
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100917a floating-point value due to limits on precision.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100918These requirements apply to the result of any expression except for builtin
919functions for which an unusual loss of precision must be explicitly documented.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100920
921
922### Strings
923
Marcel van Lohuizen4108f802019-08-13 18:30:25 +0200924The _string type_ represents the set of UTF-8 strings,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100925not allowing surrogates.
926The predeclared string type is `string`; it is a defined type.
927
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100928The length of a string `s` (its size in bytes) can be discovered using
Jonathan Amsterdam061bde12019-09-03 08:28:10 -0400929the built-in function `len`.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100930
Marcel van Lohuizen4108f802019-08-13 18:30:25 +0200931
932### Bytes
933
934The _bytes type_ represents the set of byte sequences.
935A byte sequence value is a (possibly empty) sequence of bytes.
936The number of bytes is called the length of the byte sequence
937and is never negative.
938The predeclared byte sequence type is `bytes`; it is a defined type.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100939
940
Marcel van Lohuizen7da140a2019-02-01 09:35:00 +0100941### Bounds
942
Jonathan Amsterdam061bde12019-09-03 08:28:10 -0400943A _bound_, syntactically a [unary expression](#Operands), defines
Marcel van Lohuizen62b87272019-02-01 10:07:49 +0100944an infinite disjunction of concrete values than can be represented
Marcel van Lohuizen7da140a2019-02-01 09:35:00 +0100945as a single comparison.
946
947For any [comparison operator](#Comparison-operators) `op` except `==`,
948`op a` is the disjunction of every `x` such that `x op a`.
949
950```
9512 & >=2 & <=5 // 2, where 2 is either an int or float.
9522.5 & >=1 & <=5 // 2.5
9532 & >=1.0 & <3.0 // 2.0
Marcel van Lohuizen62b87272019-02-01 10:07:49 +01009542 & >1 & <3.0 // 2.0
Marcel van Lohuizen7da140a2019-02-01 09:35:00 +01009552.5 & int & >1 & <5 // _|_
9562.5 & float & >1 & <5 // 2.5
957int & 2 & >1.0 & <3.0 // _|_
9582.5 & >=(int & 1) & <5 // _|_
959>=0 & <=7 & >=3 & <=10 // >=3 & <=7
960!=null & 1 // 1
961>=5 & <=5 // 5
962```
963
964
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100965### Structs
966
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500967A _struct_ is a set of elements called _fields_, each of
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100968which has a name, called a _label_, and value.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100969
970We say a label is defined for a struct if the struct has a field with the
971corresponding label.
Marcel van Lohuizen62658a82019-06-16 12:18:47 +0200972The value for a label `f` of struct `a` is denoted `a.f`.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100973A struct `a` is an instance of `b`, or `a ⊑ b`, if for any label `f`
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100974defined for `b`, label `f` is also defined for `a` and `a.f ⊑ b.f`.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +0100975Note that if `a` is an instance of `b` it may have fields with labels that
976are not defined for `b`.
977
Jonathan Amsterdame4790382019-01-20 10:29:29 -0500978The (unique) struct with no fields, written `{}`, has every struct as an
979instance. It can be considered the type of all structs.
980
Jonathan Amsterdam061bde12019-09-03 08:28:10 -0400981```
982{a: 1} ⊑ {}
983{a: 1, b: 1} ⊑ {a: 1}
984{a: 1} ⊑ {a: int}
985{a: 1, b: 1} ⊑ {a: int, b: float}
986
987{} ⋢ {a: 1}
988{a: 2} ⋢ {a: 1}
989{a: 1} ⋢ {b: 1}
990```
991
Marcel van Lohuizen62658a82019-06-16 12:18:47 +0200992A field may be required or optional.
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +0100993The successful unification of structs `a` and `b` is a new struct `c` which
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100994has all fields of both `a` and `b`, where
995the value of a field `f` in `c` is `a.f & b.f` if `f` is in both `a` and `b`,
996or just `a.f` or `b.f` if `f` is in just `a` or `b`, respectively.
Marcel van Lohuizen62658a82019-06-16 12:18:47 +0200997If a field `f` is in both `a` and `b`, `c.f` is optional only if both
998`a.f` and `b.f` are optional.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +0100999Any [references](#References) to `a` or `b`
1000in their respective field values need to be replaced with references to `c`.
Marcel van Lohuizen3022ae92019-10-15 13:35:58 +02001001The result of a unification is bottom (`_|_`) if any of its non-optional
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001002fields evaluates to bottom, recursively.
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02001003
Marcel van Lohuizen5134dee2019-07-21 14:41:44 +02001004<!--NOTE: About bottom values for optional fields being okay.
1005
1006The proposition ¬P is a close cousin of P → ⊥ and is often used
1007as an approximation to avoid the issues of using not.
1008Bottom (⊥) is also frequently used to mean undefined. This makes sense.
1009Consider `{a?: 2} & {a?: 3}`.
1010Both structs say `a` is optional; in other words, it may be omitted.
1011So we can still get a valid result by omitting `a`, even in
1012case of a conflict.
1013
1014Granted, this definition may lead to confusing results, especially in
1015definitions, when tightening an optional field leads to unintentionally
1016discarding it.
1017It could be a role of vet checkers to identify such cases (and suggest users
1018to explicitly use `_|_` to discard a field, for instance).
1019-->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001020
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001021Syntactically, a struct literal may contain multiple fields with
1022the same label, the result of which is a single field with the same properties
1023as defined as the unification of two fields resulting from unifying two structs.
1024
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001025These examples illustrate required fields only.
1026Examples with optional fields follow below.
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001027
1028```
1029Expression Result (without optional fields)
1030{a: int, a: 1} {a: 1}
1031{a: int} & {a: 1} {a: 1}
1032{a: >=1 & <=7} & {a: >=5 & <=9} {a: >=5 & <=7}
1033{a: >=1 & <=7, a: >=5 & <=9} {a: >=5 & <=7}
1034
1035{a: 1} & {b: 2} {a: 1, b: 2}
1036{a: 1, b: int} & {b: 2} {a: 1, b: 2}
1037
1038{a: 1} & {a: 2} _|_
1039```
1040
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001041Optional labels are defined in sets with an expression to select all
1042labels to which to apply a given constraint.
1043Syntactically, the label of an optional field set is an expression in square
1044brackets indicating the matching labels.
1045The value `string` matches all fields, while a concrete string matches a
1046single field.
1047As the latter case is common, a concrete label followed by
1048a question mark `?` may be used as a shorthand.
Marcel van Lohuizen0cb140e2020-02-10 09:09:43 +01001049So
1050```
1051foo?: bar
1052```
1053is a shorthand for
1054```
1055["foo"]: bar
1056```
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001057The question mark is not part of the field name.
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001058The token `...` may be used as the last declaration in a struct
Marcel van Lohuizen0cb140e2020-02-10 09:09:43 +01001059and is a shorthand for
1060```
1061[_]: _
1062```
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001063
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001064Concrete field labels may be an identifier or string, the latter of which may be
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001065interpolated.
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001066Fields with identifier labels can be referred to within the scope they are
1067defined, string labels cannot.
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001068References within such interpolated strings are resolved within
1069the scope of the struct in which the label sequence is
1070defined and can reference concrete labels lexically preceding
1071the label within a label sequence.
1072<!-- We allow this so that rewriting a CUE file to collapse or expand
1073field sequences has no impact on semantics.
1074-->
1075
1076<!--TODO: first implementation round will not yet have expression labels
1077
1078An ExpressionLabel sets a collection of optional fields to a field value.
1079By default it defines this value for all possible string labels.
1080An optional expression limits this to the set of optional fields which
1081labels match the expression.
1082-->
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001083
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001084
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001085<!-- NOTE: if we allow ...Expr, as in list, it would mean something different. -->
Jonathan Amsterdame4790382019-01-20 10:29:29 -05001086
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001087
1088<!-- NOTE:
1089A DefinitionDecl does not allow repeated labels. This is to avoid
1090any ambiguity or confusion about whether earlier path components
1091are to be interpreted as declarations or normal fields (they should
1092always be normal fields.)
1093-->
1094
1095<!--NOTE:
1096The syntax has been deliberately restricted to allow for the following
1097future extensions and relaxations:
1098 - Allow omitting a "?" in an expression label to indicate a concrete
1099 string value (but maybe we want to use () for that).
1100 - Make the "?" in expression label optional if expression labels
1101 are always optional.
1102 - Or allow eliding the "?" if the expression has no references and
1103 is obviously not concrete (such as `[string]`).
1104 - The expression of an expression label may also indicate a struct with
1105 integer or even number labels
1106 (beware of imprecise computation in the latter).
1107 e.g. `{ [int]: string }` is a map of integers to strings.
1108 - Allow for associative lists (`foo [@.field]: {field: string}`)
1109 - The `...` notation can be extended analogously to that of a ListList,
1110 by allowing it to follow with an expression for the remaining properties.
1111 In that case it is no longer a shorthand for `[string]: _`, but rather
1112 would define the value for any other value for which there is no field
1113 defined.
1114 Like the definition with List, this is somewhat odd, but it allows the
1115 encoding of JSON schema's and (non-structural) OpenAPI's
1116 additionalProperties and additionalItems.
1117-->
1118
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001119```
Marcel van Lohuizen1f5a9032019-09-09 23:53:42 +02001120StructLit = "{" { Declaration "," } [ "..." ] "}" .
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001121Declaration = Field | Embedding | LetClause | attribute .
1122Embedding = Comprehension | AliasExpr .
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001123Field = Label ":" { Label ":" } Expression { attribute } .
Marcel van Lohuizen86e1a642020-05-19 21:42:01 +02001124Label = [ identifier "=" ] LabelExpr .
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001125LabelExpr = LabelName [ "?" ] | "[" AliasExpr "]" .
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001126LabelName = identifier | simple_string_lit .
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +01001127
Marcel van Lohuizen4d29dde2019-12-02 23:11:30 +01001128attribute = "@" identifier "(" attr_tokens ")" .
1129attr_tokens = { attr_token |
1130 "(" attr_tokens ")" |
1131 "[" attr_tokens "]" |
1132 "{" attr_tokens "}" } .
1133attr_token = /* any token except '(', ')', '[', ']', '{', or '}' */
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001134```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001135
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001136```
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001137Expression Result (without optional fields)
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001138a: { foo?: string } {}
1139b: { foo: "bar" } { foo: "bar" }
1140c: { foo?: *"bar" | string } {}
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001141
1142d: a & b { foo: "bar" }
1143e: b & c { foo: "bar" }
1144f: a & c {}
1145g: a & { foo?: number } {}
1146h: b & { foo?: number } _|_
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001147i: c & { foo: string } { foo: "bar" }
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001148
1149intMap: [string]: int
1150intMap: {
1151 t1: 43
1152 t2: 2.4 // error: 2.4 is not an integer
1153}
1154
1155nameMap: [string]: {
1156 firstName: string
1157 nickName: *firstName | string
1158}
1159
1160nameMap: hank: { firstName: "Hank" }
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001161```
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001162The optional field set defined by `nameMap` matches every field,
1163in this case just `hank`, and unifies the associated constraint
1164with the matched field, resulting in:
1165```
1166nameMap: hank: {
1167 firstName: "Hank"
1168 nickName: "Hank"
1169}
1170```
1171
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001172
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001173#### Closed structs
1174
1175By default, structs are open to adding fields.
Marcel van Lohuizen5134dee2019-07-21 14:41:44 +02001176Instances of an open struct `p` may contain fields not defined in `p`.
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001177This is makes it easy to add fields, but can lead to bugs:
1178
1179```
1180S: {
1181 field1: string
1182}
1183
1184S1: S & { field2: "foo" }
1185
1186// S1 is { field1: string, field2: "foo" }
1187
1188
1189A: {
1190 field1: string
1191 field2: string
1192}
1193
1194A1: A & {
1195 feild1: "foo" // "field1" was accidentally misspelled
1196}
1197
1198// A1 is
1199// { field1: string, field2: string, feild1: "foo" }
1200// not the intended
1201// { field1: "foo", field2: string }
1202```
1203
Marcel van Lohuizen18637db2019-09-03 11:48:25 +02001204A _closed struct_ `c` is a struct whose instances may not have regular fields
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001205not defined in `c`.
Marcel van Lohuizen4245fb42019-09-09 11:22:12 +02001206Closing a struct is equivalent to adding an optional field with value `_|_`
Marcel van Lohuizen5134dee2019-07-21 14:41:44 +02001207for all undefined fields.
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001208
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001209Syntactically, closed structs can be explicitly created with the `close` builtin
1210or implicitly by [definitions](#Definitions).
1211
1212
1213```
1214A: close({
1215 field1: string
1216 field2: string
1217})
1218
1219A1: A & {
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001220 feild1: string
1221} // _|_ feild1 not defined for A
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001222
1223A2: A & {
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001224 for k,v in { feild1: string } {
1225 k: v
1226 }
1227} // _|_ feild1 not defined for A
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001228
1229C: close({
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001230 [_]: _
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001231})
1232
1233C2: C & {
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001234 for k,v in { thisIsFine: string } {
1235 "\(k)": v
1236 }
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001237}
1238
1239D: close({
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001240 // Values generated by comprehensions are treated as embeddings.
1241 for k,v in { x: string } {
1242 "\(k)": v
1243 }
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001244})
1245```
1246
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001247<!-- (jba) Somewhere it should be said that optional fields are only
1248 interesting inside closed structs. -->
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001249
1250#### Embedding
1251
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001252A struct may contain an _embedded value_, an operand used
Marcel van Lohuizen5134dee2019-07-21 14:41:44 +02001253as a declaration, which must evaluate to a struct.
1254An embedded value of type struct is unified with the struct in which it is
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001255embedded, but disregarding the restrictions imposed by closed structs.
1256A struct resulting from such a unification is closed if either of the involved
1257structs were closed.
1258
Marcel van Lohuizena3c7bef2019-10-10 21:50:58 +02001259At the top level, an embedded value may be any type.
1260In this case, a CUE program will evaluate to the embedded value
1261and the CUE program may not have top-level regular or optional
1262fields (definitions and aliases are allowed).
1263
Marcel van Lohuizene53305e2019-09-13 10:10:31 +02001264Syntactically, embeddings may be any expression, except that `<`
1265is eagerly interpreted as a bind label.
Marcel van Lohuizen1f5a9032019-09-09 23:53:42 +02001266
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001267```
1268S1: {
1269 a: 1
1270 b: 2
1271 {
1272 c: 3
1273 }
1274}
1275// S1 is { a: 1, b: 2, c: 3 }
1276
1277S2: close({
1278 a: 1
1279 b: 2
1280 {
1281 c: 3
1282 }
1283})
1284// same as close(S1)
1285
1286S3: {
1287 a: 1
1288 b: 2
1289 close({
1290 c: 3
1291 })
1292}
1293// same as S2
1294```
1295
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001296
Marcel van Lohuizenb7083ff2020-05-12 11:38:19 +02001297#### Definitions and hidden fields
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001298
Marcel van Lohuizenb7083ff2020-05-12 11:38:19 +02001299A field is a _definition_ if its identifier starts with `#` or `_#`.
1300A field is _hidden_ if its starts with a `_`.
1301Definitions and hidden fields are not emitted when converting a CUE program
1302to data and are never required to be concrete.
1303For definitions
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001304literal structs that are part of a definition's value are implicitly closed,
Marcel van Lohuizenfa7e3ce2019-10-10 15:43:34 +02001305but may unify unrestricted with other structs within the field's declaration.
Marcel van Lohuizen5e8c3912019-09-03 15:46:26 +02001306This excludes literals structs in embeddings and aliases.
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02001307
Marcel van Lohuizenfa7e3ce2019-10-10 15:43:34 +02001308<!--
1309This may be a more intuitive definition:
1310 Literal structs that are part of a definition's value are implicitly closed.
1311 Implicitly closed literal structs that are unified within
1312 a single field declaration are considered to be a single literal struct.
1313However, this would make unification non-commutative, unless one imposes an
1314ordering where literal structs are unified before unifying them with others.
1315Imposing such an ordering is complex and error prone.
1316-->
Marcel van Lohuizen5134dee2019-07-21 14:41:44 +02001317An ellipsis `...` in such literal structs keeps them open,
1318as it defines `_` for all labels.
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02001319
Marcel van Lohuizen5e8c3912019-09-03 15:46:26 +02001320<!--
1321Excluding embeddings from recursive closing allows comprehensions to be
1322interpreted as embeddings without some exception. For instance,
1323 if x > 2 {
1324 foo: string
1325 }
1326should not cause any failure. It is also consistent with embeddings being
1327opened when included in a closed struct.
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001328
Marcel van Lohuizen5e8c3912019-09-03 15:46:26 +02001329Finally, excluding embeddings from recursive closing allows for
1330a mechanism to not recursively close, without needing an additional language
1331construct, such as a triple colon or something else:
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001332#foo: {
Marcel van Lohuizen5e8c3912019-09-03 15:46:26 +02001333 {
1334 // not recursively closed
1335 }
1336 ... // include this to not close outer struct
1337}
1338
1339Including aliases from this exclusion, which are more a separate definition
1340than embedding seems sensible, and allows for an easy mechanism to avoid
1341closing, aside from embedding.
1342-->
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001343
1344```
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001345#MyStruct: {
1346 sub: field: string
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001347}
1348
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001349#MyStruct: {
1350 sub: enabled?: bool
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001351}
1352
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001353myValue: #MyStruct & {
1354 sub: feild: 2 // error, feild not defined in #MyStruct
1355 sub: enabled: true // okay
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001356}
1357
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001358#D: {
1359 #OneOf
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001360
1361 c: int // adds this field.
1362}
1363
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001364#OneOf: { a: int } | { b: int }
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001365
1366
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001367D1: #D & { a: 12, c: 22 } // { a: 12, c: 22 }
1368D2: #D & { a: 12, b: 33 } // _|_ // cannot define both `a` and `b`
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001369```
1370
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001371
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001372<!---
1373JSON fields are usual camelCase. Clashes can be avoided by adopting the
1374convention that definitions be TitleCase. Unexported definitions are still
1375subject to clashes, but those are likely easier to resolve because they are
1376package internal.
1377--->
1378
1379
Marcel van Lohuizen4dd96302020-01-13 09:38:00 +01001380#### Attributes
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001381
Marcel van Lohuizen4dd96302020-01-13 09:38:00 +01001382Attributes allow associating meta information with values.
1383Their primary purpose is to define mappings between CUE and
1384other representations.
1385Attributes do not influence the evaluation of CUE.
1386
1387An attribute associates an identifier with a value, a balanced token sequence,
1388which is a sequence of CUE tokens with balanced brackets (`()`, `[]`, and `{}`).
1389The sequence may not contain interpolations.
1390
1391Fields, structs and packages can be associated with a set of attributes.
1392Attributes accumulate during unification, but implementations may remove
1393duplicates that have the same source string representation.
1394The interpretation of an attribute, including the handling of multiple
1395attributes for a given identifier, is up to the consumer of the attribute.
1396
1397Field attributes define additional information about a field,
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001398such as a mapping to a protocol buffer <!-- TODO: add link --> tag or alternative
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +01001399name of the field when mapping to a different language.
1400
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +01001401
1402```
Marcel van Lohuizen4dd96302020-01-13 09:38:00 +01001403// Package attribute
1404@protobuf(proto3)
1405
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001406myStruct1: {
Marcel van Lohuizen4dd96302020-01-13 09:38:00 +01001407 // Struct attribute:
1408 @jsonschema(id="https://example.org/mystruct1.json")
1409
1410 // Field attributes
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +01001411 field: string @go(Field)
1412 attr: int @xml(,attr) @go(Attr)
1413}
1414
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001415myStruct2: {
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +01001416 field: string @go(Field)
1417 attr: int @xml(a1,attr) @go(Attr)
1418}
1419
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001420Combined: myStruct1 & myStruct2
Marcel van Lohuizenb9b62d32019-03-14 23:50:15 +01001421// field: string @go(Field)
1422// attr: int @xml(,attr) @xml(a1,attr) @go(Attr)
1423```
1424
Marcel van Lohuizenfa7e3ce2019-10-10 15:43:34 +02001425
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001426#### Aliases
1427
Marcel van Lohuizen62b87272019-02-01 10:07:49 +01001428Aliases name values that can be referred to
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001429within the [scope](#declarations-and-scopes) in which they are declared.
1430The name of an alias must be unique within its scope.
1431
1432```
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001433AliasExpr = Expression | identifier "=" Expression .
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001434```
1435
1436Aliases can appear in several positions:
1437
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001438<!--- TODO: consider allowing this. It should be considered whether
1439having field aliases isn't already sufficient.
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001440
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001441As a declaration in a struct (`X=value`):
1442
1443- binds identifier `X` to a value embedded within the struct.
1444--->
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001445
1446In front of a Label (`X=label: value`):
1447
1448- binds the identifier to the same value as `label` would be bound
1449 to if it were a valid identifier.
1450- for optional fields (`foo?: bar` and `[foo]: bar`),
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001451 the bound identifier is only visible within the field value (`bar`).
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001452
1453Inside a bracketed label (`[X=expr]: value`):
1454
1455- binds the identifier to the the concrete label that matches `expr`
1456 within the instances of the field value (`value`).
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001457
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001458Before a list element (`[ X=value, X+1 ]`) (Not yet implemented)
1459
1460- binds the identifier to the list element it precedes within the scope of the
1461 list expression.
1462
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001463<!-- TODO: explain the difference between aliases and definitions.
1464 Now that you have definitions, are aliases really necessary?
1465 Consider removing.
1466-->
1467
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001468```
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001469// An alias declaration
1470Alias = 3
1471a: Alias // 3
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001472
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001473// A field alias
1474foo: X // 4
1475X="not an identifier": 4
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001476
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001477// A label alias
1478[Y=string]: { name: Y }
1479foo: { value: 1 } // outputs: foo: { name: "foo", value: 1 }
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001480```
1481
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001482<!-- TODO: also allow aliases as lists -->
1483
1484
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001485#### Let declarations
1486
1487_Let declarations_ bind an identifier to an expression.
1488The identifier is visible within the [scope](#declarations-and-scopes)
1489in which it is declared.
1490The identifier must be unique within its scope.
1491
1492```
1493let x = expr
1494
1495a: x + 1
1496b: x + 2
1497```
1498
Jonathan Amsterdam061bde12019-09-03 08:28:10 -04001499#### Shorthand notation for nested structs
1500
Jonathan Amsterdame4790382019-01-20 10:29:29 -05001501A field whose value is a struct with a single field may be written as
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001502a colon-separated sequence of the two field names,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001503followed by a colon and the value of that single field.
1504
1505```
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001506job: myTask: replicas: 2
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001507```
Jonathan Amsterdame4790382019-01-20 10:29:29 -05001508expands to
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001509```
Jonathan Amsterdame4790382019-01-20 10:29:29 -05001510job: {
1511 myTask: {
1512 replicas: 2
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001513 }
1514}
1515```
1516
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001517<!-- OPTIONAL FIELDS:
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001518
Marcel van Lohuizen08a0ef22019-03-28 09:12:19 +01001519The optional marker solves the issue of having to print large amounts of
1520boilerplate when dealing with large types with many optional or default
1521values (such as Kubernetes).
1522Writing such optional values in terms of *null | value is tedious,
1523unpleasant to read, and as it is not well defined what can be dropped or not,
1524all null values have to be emitted from the output, even if the user
1525doesn't override them.
1526Part of the issue is how null is defined. We could adopt a Typescript-like
1527approach of introducing "void" or "undefined" to mean "not defined and not
1528part of the output". But having all of null, undefined, and void can be
1529confusing. If these ever are introduced anyway, the ? operator could be
1530expressed along the lines of
1531 foo?: bar
1532being a shorthand for
1533 foo: void | bar
1534where void is the default if no other default is given.
1535
1536The current mechanical definition of "?" is straightforward, though, and
1537probably avoids the need for void, while solving a big issue.
1538
1539Caveats:
1540[1] this definition requires explicitly defined fields to be emitted, even
1541if they could be elided (for instance if the explicit value is the default
1542value defined an optional field). This is probably a good thing.
1543
1544[2] a default value may still need to be included in an output if it is not
1545the zero value for that field and it is not known if any outside system is
1546aware of defaults. For instance, which defaults are specified by the user
1547and which by the schema understood by the receiving system.
1548The use of "?" together with defaults should therefore be used carefully
1549in non-schema definitions.
1550Problematic cases should be easy to detect by a vet-like check, though.
1551
1552[3] It should be considered how this affects the trim command.
1553Should values implied by optional fields be allowed to be removed?
1554Probably not. This restriction is unlikely to limit the usefulness of trim,
1555though.
1556
1557[4] There should be an option to emit all concrete optional values.
1558```
1559-->
1560
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001561### Lists
1562
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01001563A list literal defines a new value of type list.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001564A list may be open or closed.
1565An open list is indicated with a `...` at the end of an element list,
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01001566optionally followed by a value for the remaining elements.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001567
1568The length of a closed list is the number of elements it contains.
1569The length of an open list is the its number of elements as a lower bound
1570and an unlimited number of elements as its upper bound.
1571
1572```
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001573ListLit = "[" [ ElementList [ "," [ "..." [ Expression ] ] ] [ "," ] "]" .
1574ElementList = Embedding { "," Embedding } .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001575```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001576
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001577Lists can be thought of as structs:
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001578
1579```
Marcel van Lohuizen08466f82019-02-01 09:09:09 +01001580List: *null | {
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001581 Elem: _
1582 Tail: List
1583}
1584```
1585
1586For closed lists, `Tail` is `null` for the last element, for open lists it is
Marcel van Lohuizen08466f82019-02-01 09:09:09 +01001587`*null | List`, defaulting to the shortest variant.
Jonathan Amsterdame4790382019-01-20 10:29:29 -05001588For instance, the open list [ 1, 2, ... ] can be represented as:
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001589```
1590open: List & { Elem: 1, Tail: { Elem: 2 } }
1591```
1592and the closed version of this list, [ 1, 2 ], as
1593```
1594closed: List & { Elem: 1, Tail: { Elem: 2, Tail: null } }
1595```
1596
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001597Using this representation, the subsumption rule for lists can
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001598be derived from those of structs.
1599Implementations are not required to implement lists as structs.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001600The `Elem` and `Tail` fields are not special and `len` will not work as
1601expected in these cases.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001602
1603
1604## Declarations and Scopes
1605
1606
1607### Blocks
1608
1609A _block_ is a possibly empty sequence of declarations.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001610The braces of a struct literal `{ ... }` form a block, but there are
Jonathan Amsterdame4790382019-01-20 10:29:29 -05001611others as well:
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001612
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +01001613- The _universe block_ encompasses all CUE source text.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001614- Each [package](#modules-instances-and-packages) has a _package block_
1615 containing all CUE source text in that package.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001616- Each file has a _file block_ containing all CUE source text in that file.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001617- Each `for` and `let` clause in a [comprehension](#comprehensions)
1618 is considered to be its own implicit block.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001619
1620Blocks nest and influence [scoping].
1621
1622
1623### Declarations and scope
1624
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001625A _declaration_ may bind an identifier to a field, alias, or package.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001626Every identifier in a program must be declared.
1627Other than for fields,
1628no identifier may be declared twice within the same block.
1629For fields an identifier may be declared more than once within the same block,
1630resulting in a field with a value that is the result of unifying the values
1631of all fields with the same identifier.
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001632String labels do not bind an identifier to the respective field.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001633
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001634The _scope_ of a declared identifier is the extent of source text in which the
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001635identifier denotes the specified field, alias, or package.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001636
1637CUE is lexically scoped using blocks:
1638
Jonathan Amsterdame4790382019-01-20 10:29:29 -050016391. The scope of a [predeclared identifier](#predeclared-identifiers) is the universe block.
Marcel van Lohuizen21f6c442019-09-26 14:55:23 +020016401. The scope of an identifier denoting a field
1641 declared at top level (outside any struct literal) is the package block.
16421. The scope of an identifier denoting an alias
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001643 declared at top level (outside any struct literal) is the file block.
16441. The scope of the package name of an imported package is the file block of the
1645 file containing the import declaration.
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +020016461. The scope of a field, alias or let identifier declared inside a struct
1647 literal is the innermost containing block.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001648
1649An identifier declared in a block may be redeclared in an inner block.
1650While the identifier of the inner declaration is in scope, it denotes the entity
1651declared by the inner declaration.
1652
1653The package clause is not a declaration;
Jonathan Amsterdame4790382019-01-20 10:29:29 -05001654the package name does not appear in any scope.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001655Its purpose is to identify the files belonging to the same package
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +01001656and to specify the default name for import declarations.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001657
1658
1659### Predeclared identifiers
1660
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001661CUE predefines a set of types and builtin functions.
1662For each of these there is a corresponding keyword which is the name
1663of the predefined identifier, prefixed with `__`.
1664
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001665```
1666Functions
1667len required close open
1668
1669Types
1670null The null type and value
1671bool All boolean values
1672int All integral numbers
1673float All decimal floating-point numbers
1674string Any valid UTF-8 sequence
Marcel van Lohuizen4108f802019-08-13 18:30:25 +02001675bytes Any valid byte sequence
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001676
1677Derived Value
1678number int | float
Marcel van Lohuizen62b87272019-02-01 10:07:49 +01001679uint >=0
1680uint8 >=0 & <=255
1681int8 >=-128 & <=127
1682uint16 >=0 & <=65536
1683int16 >=-32_768 & <=32_767
1684rune >=0 & <=0x10FFFF
1685uint32 >=0 & <=4_294_967_296
1686int32 >=-2_147_483_648 & <=2_147_483_647
1687uint64 >=0 & <=18_446_744_073_709_551_615
1688int64 >=-9_223_372_036_854_775_808 & <=9_223_372_036_854_775_807
1689uint128 >=0 & <=340_282_366_920_938_463_463_374_607_431_768_211_455
1690int128 >=-170_141_183_460_469_231_731_687_303_715_884_105_728 &
1691 <=170_141_183_460_469_231_731_687_303_715_884_105_727
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02001692float32 >=-3.40282346638528859811704183484516925440e+38 &
1693 <=3.40282346638528859811704183484516925440e+38
1694float64 >=-1.797693134862315708145274237317043567981e+308 &
1695 <=1.797693134862315708145274237317043567981e+308
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001696```
1697
1698
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001699### Exported identifiers
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001700
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001701<!-- move to a more logical spot -->
1702
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001703An identifier of a package may be exported to permit access to it
1704from another package.
Marcel van Lohuizenb7083ff2020-05-12 11:38:19 +02001705All identifiers not starting with `_` (so all regular fields and definitions
1706starting with `#`) are exported.
1707Any identifier starting with `_` is not visible outside the package and resides
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001708in a separate namespace than namesake identifiers of other packages.
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001709
1710```
1711package mypackage
1712
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001713foo: string // visible outside mypackage
1714"bar": string // visible outside mypackage
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001715
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001716#Foo: { // visible outside mypackage
1717 a: 1 // visible outside mypackage
1718 _b: 2 // not visible outside mypackage
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001719
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01001720 #C: { // visible outside mypackage
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001721 d: 4 // visible outside mypackage
1722 }
Marcel van Lohuizenb7083ff2020-05-12 11:38:19 +02001723 _#E: foo // not visible outside mypackage
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001724}
1725```
1726
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001727
1728### Uniqueness of identifiers
1729
1730Given a set of identifiers, an identifier is called unique if it is different
1731from every other in the set, after applying normalization following
1732Unicode Annex #31.
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001733Two identifiers are different if they are spelled differently
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001734or if they appear in different packages and are not exported.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001735Otherwise, they are the same.
1736
1737
1738### Field declarations
1739
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001740A field associates the value of an expression to a label within a struct.
1741If this label is an identifier, it binds the field to that identifier,
1742so the field's value can be referenced by writing the identifier.
1743String labels are not bound to fields.
1744```
1745a: {
1746 b: 2
1747 "s": 3
1748
1749 c: b // 2
1750 d: s // _|_ unresolved identifier "s"
1751 e: a.s // 3
1752}
1753```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001754
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001755If an expression may result in a value associated with a default value
1756as described in [default values](#default-values), the field binds to this
1757value-default pair.
1758
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001759
Marcel van Lohuizenbcf832f2019-04-03 22:50:44 +02001760<!-- TODO: disallow creating identifiers starting with __
1761...and reserve them for builtin values.
1762
1763The issue is with code generation. As no guarantee can be given that
1764a predeclared identifier is not overridden in one of the enclosing scopes,
1765code will have to handle detecting such cases and renaming them.
1766An alternative is to have the predeclared identifiers be aliases for namesake
1767equivalents starting with a double underscore (e.g. string -> __string),
1768allowing generated code (normal code would keep using `string`) to refer
1769to these directly.
1770-->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001771
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001772
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001773### Let declarations
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001774
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001775Within a struct, a let clause binds an identifier to the given expression.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001776
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001777Within the scope of the identifier, the identifier refers to the
1778_locally declared_ expression.
Marcel van Lohuizen40178752019-08-25 19:17:56 +02001779The expression is evaluated in the scope it was declared.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001780
1781
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001782## Expressions
1783
1784An expression specifies the computation of a value by applying operators and
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001785built-in functions to operands.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001786
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001787Expressions that require concrete values are called _incomplete_ if any of
1788their operands are not concrete, but define a value that would be legal for
1789that expression.
1790Incomplete expressions may be left unevaluated until a concrete value is
1791requested at the application level.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001792
1793### Operands
1794
1795Operands denote the elementary values in an expression.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01001796An operand may be a literal, a (possibly qualified) identifier denoting
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001797field, alias, or let declaration, or a parenthesized expression.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001798
1799```
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02001800Operand = Literal | OperandName | "(" Expression ")" .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001801Literal = BasicLit | ListLit | StructLit .
1802BasicLit = int_lit | float_lit | string_lit |
1803 null_lit | bool_lit | bottom_lit | top_lit .
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001804OperandName = identifier | QualifiedIdent .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001805```
1806
1807### Qualified identifiers
1808
1809A qualified identifier is an identifier qualified with a package name prefix.
1810
1811```
1812QualifiedIdent = PackageName "." identifier .
1813```
1814
1815A qualified identifier accesses an identifier in a different package,
1816which must be [imported].
1817The identifier must be declared in the [package block] of that package.
1818
1819```
1820math.Sin // denotes the Sin function in package math
1821```
1822
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001823### References
1824
1825An identifier operand refers to a field and is called a reference.
1826The value of a reference is a copy of the expression associated with the field
1827that it is bound to,
1828with any references within that expression bound to the respective copies of
1829the fields they were originally bound to.
1830Implementations may use a different mechanism to evaluate as long as
1831these semantics are maintained.
1832
1833```
1834a: {
1835 place: string
1836 greeting: "Hello, \(place)!"
1837}
1838
1839b: a & { place: "world" }
1840c: a & { place: "you" }
1841
1842d: b.greeting // "Hello, world!"
1843e: c.greeting // "Hello, you!"
1844```
1845
1846
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001847
1848### Primary expressions
1849
1850Primary expressions are the operands for unary and binary expressions.
1851
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001852
1853```
1854
1855Slice: indices must be complete
1856([0, 1, 2, 3] | [2, 3])[0:2] => [0, 1] | [2, 3]
1857
1858([0, 1, 2, 3] | *[2, 3])[0:2] => [0, 1] | [2, 3]
1859([0,1,2,3]|[2,3], [2,3])[0:2] => ([0,1]|[2,3], [2,3])
1860
1861Index
1862a: (1|2, 1)
1863b: ([0,1,2,3]|[2,3], [2,3])[a] => ([0,1,2,3]|[2,3][a], 3)
1864
1865Binary operation
1866A binary is only evaluated if its operands are complete.
1867
1868Input Maximum allowed evaluation
1869a: string string
1870b: 2 2
1871c: a * b a * 2
1872
1873An error in a struct is if the evaluation of any expression results in
1874bottom, where an incomplete expression is not considered bottom.
1875```
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +01001876<!-- TODO(mpvl)
1877 Conversion |
1878-->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001879```
1880PrimaryExpr =
1881 Operand |
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001882 PrimaryExpr Selector |
1883 PrimaryExpr Index |
1884 PrimaryExpr Slice |
1885 PrimaryExpr Arguments .
1886
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +02001887Selector = "." (identifier | simple_string_lit) .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001888Index = "[" Expression "]" .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001889Argument = Expression .
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02001890Arguments = "(" [ ( Argument { "," Argument } ) [ "," ] ] ")" .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001891```
1892<!---
Marcel van Lohuizen9ffcbbc2019-10-23 18:05:05 +02001893TODO:
1894 PrimaryExpr Query |
1895Query = "." Filters .
1896Filters = Filter { Filter } .
1897Filter = "[" [ "?" ] AliasExpr "]" .
1898
1899TODO: maybe reintroduce slices, as they are useful in queries, probably this
1900time with Python semantics.
1901Slice = "[" [ Expression ] ":" [ Expression ] [ ":" [Expression] ] "]" .
1902
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001903Argument = Expression | ( identifer ":" Expression ).
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +02001904
1905// & expression type
1906// string_lit: same as label. Arguments is current node.
1907// If selector is applied to list, it performs the operation for each
1908// element.
1909
1910TODO: considering allowing decimal_lit for selectors.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001911--->
1912
1913```
1914x
19152
1916(s + ".txt")
1917f(3.1415, true)
1918m["foo"]
1919s[i : j + 1]
1920obj.color
1921f.p[i].x
1922```
1923
1924
1925### Selectors
1926
Roger Peppeded0e1d2019-09-24 16:39:36 +01001927For a [primary expression](#primary-expressions) `x` that is not a [package name](#package-clause),
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001928the selector expression
1929
1930```
1931x.f
1932```
1933
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +02001934denotes the element of a <!--list or -->struct `x` identified by `f`.
1935<!--For structs, -->`f` must be an identifier or a string literal identifying
1936any definition or regular non-optional field.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001937The identifier `f` is called the field selector.
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +02001938
1939<!--
1940Allowing strings to be used as field selectors obviates the need for
1941backquoted identifiers. Note that some standards use names for structs that
1942are not standard identifiers (such "Fn::Foo"). Note that indexing does not
1943allow access to identifiers.
1944-->
1945
1946<!--
1947For lists, `f` must be an integer and follows the same lookup rules as
1948for the index operation.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001949The type of the selector expression is the type of `f`.
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +02001950-->
1951
Roger Peppeded0e1d2019-09-24 16:39:36 +01001952If `x` is a package name, see the section on [qualified identifiers](#qualified-identifiers).
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001953
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001954<!--
1955TODO: consider allowing this and also for selectors. It needs to be considered
1956how defaults are corried forward in cases like:
1957
1958 x: { a: string | *"foo" } | *{ a: int | *4 }
1959 y: x.a & string
1960
1961What is y in this case?
1962 (x.a & string, _|_)
1963 (string|"foo", _|_)
1964 (string|"foo", "foo)
1965If the latter, then why?
1966
1967For a disjunction of the form `x1 | ... | xn`,
1968the selector is applied to each element `x1.f | ... | xn.f`.
1969-->
1970
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +02001971Otherwise, if `x` is not a <!--list or -->struct,
1972or if `f` does not exist in `x`,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001973the result of the expression is bottom (an error).
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001974In the latter case the expression is incomplete.
1975The operand of a selector may be associated with a default.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001976
1977```
1978T: {
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +02001979 x: int
1980 y: 3
1981 "x-y": 4
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001982}
1983
Marcel van Lohuizenc7791ac2019-10-07 11:29:28 +02001984a: T.x // int
1985b: T.y // 3
1986c: T.z // _|_ // field 'z' not found in T
1987d: T."x-y" // 4
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001988
1989e: {a: 1|*2} | *{a: 3|*4}
1990f: e.a // 4 (default value)
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01001991```
1992
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02001993<!--
1994```
1995(v, d).f => (v.f, d.f)
1996
1997e: {a: 1|*2} | *{a: 3|*4}
1998f: e.a // 4 after selecting default from (({a: 1|*2} | {a: 3|*4}).a, 4)
1999
2000```
2001-->
2002
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002003
2004### Index expressions
2005
2006A primary expression of the form
2007
2008```
2009a[x]
2010```
2011
Marcel van Lohuizen4108f802019-08-13 18:30:25 +02002012denotes the element of a list or struct `a` indexed by `x`.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002013The value `x` is called the index or field name, respectively.
2014The following rules apply:
2015
2016If `a` is not a struct:
2017
Marcel van Lohuizen4108f802019-08-13 18:30:25 +02002018- `a` is a list (which need not be complete)
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02002019- the index `x` unified with `int` must be concrete.
2020- the index `x` is in range if `0 <= x < len(a)`, where only the
2021 explicitly defined values of an open-ended list are considered,
2022 otherwise it is out of range
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002023
2024The result of `a[x]` is
2025
Marcel van Lohuizen4108f802019-08-13 18:30:25 +02002026for `a` of list type:
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002027
Marcel van Lohuizen4108f802019-08-13 18:30:25 +02002028- the list element at index `x`, if `x` is within range
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002029- bottom (an error), otherwise
2030
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002031
2032for `a` of struct type:
2033
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02002034- the index `x` unified with `string` must be concrete.
Marcel van Lohuizend2825532019-09-23 12:44:01 +01002035- the value of the regular and non-optional field named `x` of struct `a`,
2036 if this field exists
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002037- bottom (an error), otherwise
2038
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02002039
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002040```
2041[ 1, 2 ][1] // 2
Marcel van Lohuizen6f0faec2018-12-16 10:42:42 +01002042[ 1, 2 ][2] // _|_
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01002043[ 1, 2, ...][2] // _|_
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002044```
2045
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02002046Both the operand and index value may be a value-default pair.
2047```
2048va[vi] => va[vi]
2049va[(vi, di)] => (va[vi], va[di])
2050(va, da)[vi] => (va[vi], da[vi])
2051(va, da)[(vi, di)] => (va[vi], da[di])
2052```
2053
2054```
2055Fields Result
2056x: [1, 2] | *[3, 4] ([1,2]|[3,4], [3,4])
2057i: int | *1 (int, 1)
2058
2059v: x[i] (x[i], 4)
2060```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002061
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002062### Operators
2063
2064Operators combine operands into expressions.
2065
2066```
2067Expression = UnaryExpr | Expression binary_op Expression .
2068UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
2069
Marcel van Lohuizen62b87272019-02-01 10:07:49 +01002070binary_op = "|" | "&" | "||" | "&&" | "==" | rel_op | add_op | mul_op .
Marcel van Lohuizen2b0e7cd2019-03-25 08:28:41 +01002071rel_op = "!=" | "<" | "<=" | ">" | ">=" | "=~" | "!~" .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002072add_op = "+" | "-" .
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002073mul_op = "*" | "/" | "div" | "mod" | "quo" | "rem" .
Marcel van Lohuizen7da140a2019-02-01 09:35:00 +01002074unary_op = "+" | "-" | "!" | "*" | rel_op .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002075```
2076
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01002077Comparisons are discussed [elsewhere](#Comparison-operators).
Marcel van Lohuizen7da140a2019-02-01 09:35:00 +01002078For any binary operators, the operand types must unify.
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02002079
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01002080<!-- TODO: durations
2081 unless the operation involves durations.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002082
2083Except for duration operations, if one operand is an untyped [literal] and the
2084other operand is not, the constant is [converted] to the type of the other
2085operand.
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01002086-->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002087
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02002088Operands of unary and binary expressions may be associated with a default using
2089the following
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02002090
Marcel van Lohuizenfe4abac2019-04-06 17:19:03 +02002091<!--
2092```
2093O1: op (v1, d1) => (op v1, op d1)
2094
2095O2: (v1, d1) op (v2, d2) => (v1 op v2, d1 op d2)
2096and because v => (v, v)
2097O3: v1 op (v2, d2) => (v1 op v2, v1 op d2)
2098O4: (v1, d1) op v2 => (v1 op v2, d1 op v2)
2099```
2100-->
2101
2102```
2103Field Resulting Value-Default pair
2104a: *1|2 (1|2, 1)
2105b: -a (-a, -1)
2106
2107c: a + 2 (a+2, 3)
2108d: a + a (a+a, 2)
2109```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002110
2111#### Operator precedence
2112
2113Unary operators have the highest precedence.
2114
2115There are eight precedence levels for binary operators.
Marcel van Lohuizen62b87272019-02-01 10:07:49 +01002116Multiplication operators binds strongest, followed by
2117addition operators, comparison operators,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002118`&&` (logical AND), `||` (logical OR), `&` (unification),
2119and finally `|` (disjunction):
2120
2121```
2122Precedence Operator
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002123 7 * / div mod quo rem
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002124 6 + -
Marcel van Lohuizen2b0e7cd2019-03-25 08:28:41 +01002125 5 == != < <= > >= =~ !~
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002126 4 &&
2127 3 ||
2128 2 &
2129 1 |
2130```
2131
2132Binary operators of the same precedence associate from left to right.
2133For instance, `x / y * z` is the same as `(x / y) * z`.
2134
2135```
2136+x
213723 + 3*x[i]
2138x <= f()
2139f() || g()
2140x == y+1 && y == z-1
21412 | int
2142{ a: 1 } & { b: 2 }
2143```
2144
2145#### Arithmetic operators
2146
2147Arithmetic operators apply to numeric values and yield a result of the same type
2148as the first operand. The three of the four standard arithmetic operators
2149`(+, -, *)` apply to integer and decimal floating-point types;
Marcel van Lohuizen1e0fe9c2018-12-21 00:17:06 +01002150`+` and `*` also apply to lists and strings.
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002151`/` only applies to decimal floating-point types and
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002152`div`, `mod`, `quo`, and `rem` only apply to integer types.
2153
2154```
Marcel van Lohuizen08466f82019-02-01 09:09:09 +01002155+ sum integers, floats, lists, strings, bytes
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002156- difference integers, floats
Marcel van Lohuizen08466f82019-02-01 09:09:09 +01002157* product integers, floats, lists, strings, bytes
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002158/ quotient floats
2159div division integers
2160mod modulo integers
2161quo quotient integers
2162rem remainder integers
2163```
2164
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002165For any operator that accepts operands of type `float`, any operand may be
2166of type `int` or `float`, in which case the result will be `float` if any
2167of the operands is `float` or `int` otherwise.
2168For `/` the result is always `float`.
2169
2170
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002171#### Integer operators
2172
2173For two integer values `x` and `y`,
2174the integer quotient `q = x div y` and remainder `r = x mod y `
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +01002175implement Euclidean division and
2176satisfy the following relationship:
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002177
2178```
2179r = x - y*q with 0 <= r < |y|
2180```
2181where `|y|` denotes the absolute value of `y`.
2182
2183```
2184 x y x div y x mod y
2185 5 3 1 2
2186-5 3 -2 1
2187 5 -3 -1 2
2188-5 -3 2 1
2189```
2190
2191For two integer values `x` and `y`,
2192the integer quotient `q = x quo y` and remainder `r = x rem y `
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +01002193implement truncated division and
2194satisfy the following relationship:
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002195
2196```
2197x = q*y + r and |r| < |y|
2198```
2199
2200with `x quo y` truncated towards zero.
2201
2202```
2203 x y x quo y x rem y
2204 5 3 1 2
2205-5 3 -1 -2
2206 5 -3 -1 2
2207-5 -3 1 -2
2208```
2209
2210A zero divisor in either case results in bottom (an error).
2211
2212For integer operands, the unary operators `+` and `-` are defined as follows:
2213
2214```
2215+x is 0 + x
2216-x negation is 0 - x
2217```
2218
2219
2220#### Decimal floating-point operators
2221
2222For decimal floating-point numbers, `+x` is the same as `x`,
2223while -x is the negation of x.
2224The result of a floating-point division by zero is bottom (an error).
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02002225
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01002226<!-- TODO: consider making it +/- Inf -->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002227
2228An implementation may combine multiple floating-point operations into a single
2229fused operation, possibly across statements, and produce a result that differs
2230from the value obtained by executing and rounding the instructions individually.
2231
2232
2233#### List operators
2234
2235Lists can be concatenated using the `+` operator.
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002236Opens list are closed to their default value beforehand.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002237
2238```
2239[ 1, 2 ] + [ 3, 4 ] // [ 1, 2, 3, 4 ]
2240[ 1, 2, ... ] + [ 3, 4 ] // [ 1, 2, 3, 4 ]
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002241[ 1, 2 ] + [ 3, 4, ... ] // [ 1, 2, 3, 4 ]
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002242```
2243
Jonathan Amsterdam0500c312019-02-16 18:04:09 -05002244Lists can be multiplied with a non-negative`int` using the `*` operator
Marcel van Lohuizen13e36bd2019-02-01 09:59:18 +01002245to create a repeated the list by the indicated number.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002246```
22473*[1,2] // [1, 2, 1, 2, 1, 2]
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +020022483*[1, 2, ...] // [1, 2, 1, 2, 1 ,2]
Marcel van Lohuizen13e36bd2019-02-01 09:59:18 +01002249[byte]*4 // [byte, byte, byte, byte]
Jonathan Amsterdam0500c312019-02-16 18:04:09 -050022500*[1,2] // []
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002251```
Marcel van Lohuizen08466f82019-02-01 09:09:09 +01002252
2253<!-- TODO(mpvl): should we allow multiplication with a range?
2254If so, how does one specify a list with a range of possible lengths?
2255
2256Suggestion from jba:
2257Multiplication should distribute over disjunction,
2258so int(1)..int(3) * [x] = [x] | [x, x] | [x, x, x].
Marcel van Lohuizen62b87272019-02-01 10:07:49 +01002259The hard part is figuring out what (>=1 & <=3) * [x] means,
2260since >=1 & <=3 includes many floats.
Marcel van Lohuizen08466f82019-02-01 09:09:09 +01002261(mpvl: could constrain arguments to parameter types, but needs to be
2262done consistently.)
2263-->
2264
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002265
2266#### String operators
2267
2268Strings can be concatenated using the `+` operator:
2269```
Daniel Martí107863a2020-02-11 15:00:50 +00002270s: "hi " + name + " and good bye"
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002271```
2272String addition creates a new string by concatenating the operands.
2273
2274A string can be repeated by multiplying it:
2275
2276```
2277s: "etc. "*3 // "etc. etc. etc. "
2278```
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02002279
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002280<!-- jba: Do these work for byte sequences? If not, why not? -->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002281
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002282
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002283##### Comparison operators
2284
2285Comparison operators compare two operands and yield an untyped boolean value.
2286
2287```
2288== equal
2289!= not equal
2290< less
2291<= less or equal
2292> greater
2293>= greater or equal
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +01002294=~ matches regular expression
2295!~ does not match regular expression
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002296```
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02002297
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +01002298<!-- regular expression operator inspired by Bash, Perl, and Ruby. -->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002299
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +01002300In any comparison, the types of the two operands must unify or one of the
2301operands must be null.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002302
2303The equality operators `==` and `!=` apply to operands that are comparable.
2304The ordering operators `<`, `<=`, `>`, and `>=` apply to operands that are ordered.
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +01002305The matching operators `=~` and `!~` apply to a string and regular
2306expression operand.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002307These terms and the result of the comparisons are defined as follows:
2308
Marcel van Lohuizen855243e2019-02-07 18:00:55 +01002309- Null is comparable with itself and any other type.
2310 Two null values are always equal, null is unequal with anything else.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002311- Boolean values are comparable.
2312 Two boolean values are equal if they are either both true or both false.
2313- Integer values are comparable and ordered, in the usual way.
2314- Floating-point values are comparable and ordered, as per the definitions
2315 for binary coded decimals in the IEEE-754-2008 standard.
Marcel van Lohuizen4a360992019-05-11 18:18:31 +02002316- Floating point numbers may be compared with integers.
Marcel van Lohuizen4108f802019-08-13 18:30:25 +02002317- String and bytes values are comparable and ordered lexically byte-wise.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01002318- Struct are not comparable.
Marcel van Lohuizen855243e2019-02-07 18:00:55 +01002319- Lists are not comparable.
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +01002320- The regular expression syntax is the one accepted by RE2,
2321 described in https://github.com/google/re2/wiki/Syntax,
2322 except for `\C`.
2323- `s =~ r` is true if `s` matches the regular expression `r`.
2324- `s !~ r` is true if `s` does not match regular expression `r`.
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02002325
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02002326<!--- TODO: consider the following
2327- For regular expression, named capture groups are interpreted as CUE references
2328 that must unify with the strings matching this capture group.
2329--->
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +01002330<!-- TODO: Implementations should adopt an algorithm that runs in linear time? -->
Marcel van Lohuizen88a8a5f2019-02-20 01:26:22 +01002331<!-- Consider implementing Level 2 of Unicode regular expression. -->
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +01002332
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002333```
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +010023343 < 4 // true
Marcel van Lohuizen4a360992019-05-11 18:18:31 +020023353 < 4.0 // true
Marcel van Lohuizen0a0a3ac2019-02-10 16:48:53 +01002336null == 2 // false
2337null != {} // true
2338{} == {} // _|_: structs are not comparable against structs
2339
2340"Wild cats" =~ "cat" // true
2341"Wild cats" !~ "dog" // true
2342
2343"foo" =~ "^[a-z]{3}$" // true
2344"foo" =~ "^[a-z]{4}$" // false
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002345```
2346
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002347<!-- jba
2348I think I know what `3 < a` should mean if
2349
Marcel van Lohuizen62b87272019-02-01 10:07:49 +01002350 a: >=1 & <=5
2351
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002352It should be a constraint on `a` that can be evaluated once `a`'s value is known more precisely.
2353
Marcel van Lohuizen62b87272019-02-01 10:07:49 +01002354But what does `3 < (>=1 & <=5)` mean? We'll never get more information, so it must have a definite value.
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002355-->
2356
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002357#### Logical operators
2358
2359Logical operators apply to boolean values and yield a result of the same type
2360as the operands. The right operand is evaluated conditionally.
2361
2362```
2363&& conditional AND p && q is "if p then q else false"
2364|| conditional OR p || q is "if p then true else q"
2365! NOT !p is "not p"
2366```
2367
2368
2369<!--
2370### TODO TODO TODO
2371
23723.14 / 0.0 // illegal: division by zero
2373Illegal conversions always apply to CUE.
2374
2375Implementation 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.
2376-->
2377
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +01002378<!--- TODO(mpvl): conversions
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002379### Conversions
2380Conversions are expressions of the form `T(x)` where `T` and `x` are
2381expressions.
2382The result is always an instance of `T`.
2383
2384```
2385Conversion = Expression "(" Expression [ "," ] ")" .
2386```
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +01002387--->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002388<!---
2389
2390A literal value `x` can be converted to type T if `x` is representable by a
2391value of `T`.
2392
2393As a special case, an integer literal `x` can be converted to a string type
2394using the same rule as for non-constant x.
2395
2396Converting a literal yields a typed value as result.
2397
2398```
2399uint(iota) // iota value of type uint
2400float32(2.718281828) // 2.718281828 of type float32
2401complex128(1) // 1.0 + 0.0i of type complex128
2402float32(0.49999999) // 0.5 of type float32
2403float64(-1e-1000) // 0.0 of type float64
2404string('x') // "x" of type string
2405string(0x266c) // "♬" of type string
2406MyString("foo" + "bar") // "foobar" of type MyString
2407string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant
2408(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
2409int(1.2) // illegal: 1.2 cannot be represented as an int
2410string(65.0) // illegal: 65.0 is not an integer constant
2411```
2412--->
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +01002413<!---
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002414
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002415A conversion is always allowed if `x` is an instance of `T`.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002416
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002417If `T` and `x` of different underlying type, a conversion is allowed if
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002418`x` can be converted to a value `x'` of `T`'s type, and
2419`x'` is an instance of `T`.
2420A value `x` can be converted to the type of `T` in any of these cases:
2421
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01002422- `x` is a struct and is subsumed by `T`.
2423- `x` and `T` are both integer or floating points.
2424- `x` is an integer or a byte sequence and `T` is a string.
2425- `x` is a string and `T` is a byte sequence.
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002426
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002427Specific rules apply to conversions between numeric types, structs,
2428or to and from a string type. These conversions may change the representation
2429of `x`.
2430All other conversions only change the type but not the representation of x.
2431
2432
2433#### Conversions between numeric ranges
2434For the conversion of numeric values, the following rules apply:
2435
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +010024361. Any integer value can be converted into any other integer value
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002437 provided that it is within range.
24382. When converting a decimal floating-point number to an integer, the fraction
2439 is discarded (truncation towards zero). TODO: or disallow truncating?
2440
2441```
2442a: uint16(int(1000)) // uint16(1000)
Marcel van Lohuizen6f0faec2018-12-16 10:42:42 +01002443b: uint8(1000) // _|_ // overflow
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002444c: int(2.5) // 2 TODO: TBD
2445```
2446
2447
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002448#### Conversions to and from a string type
2449
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002450Converting a list of bytes to a string type yields a string whose successive
2451bytes are the elements of the slice.
2452Invalid UTF-8 is converted to `"\uFFFD"`.
2453
2454```
2455string('hell\xc3\xb8') // "hellø"
2456string(bytes([0x20])) // " "
2457```
2458
2459As string value is always convertible to a list of bytes.
2460
2461```
2462bytes("hellø") // 'hell\xc3\xb8'
2463bytes("") // ''
2464```
2465
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002466#### Conversions between list types
2467
2468Conversions between list types are possible only if `T` strictly subsumes `x`
2469and the result will be the unification of `T` and `x`.
2470
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002471If we introduce named types this would be different from IP & [10, ...]
2472
2473Consider removing this until it has a different meaning.
2474
2475```
2476IP: 4*[byte]
2477Private10: IP([10, ...]) // [10, byte, byte, byte]
2478```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002479
Marcel van Lohuizen75cb0032019-01-11 12:10:48 +01002480#### Conversions between struct types
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002481
2482A conversion from `x` to `T`
2483is applied using the following rules:
2484
24851. `x` must be an instance of `T`,
24862. all fields defined for `x` that are not defined for `T` are removed from
2487 the result of the conversion, recursively.
2488
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002489<!-- jba: I don't think you say anywhere that the matching fields are unified.
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +01002490mpvl: they are not, x must be an instance of T, in which case x == T&x,
2491so unification would be unnecessary.
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002492-->
Marcel van Lohuizena3f00972019-02-01 11:10:39 +01002493<!--
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002494```
2495T: {
2496 a: { b: 1..10 }
2497}
2498
2499x1: {
2500 a: { b: 8, c: 10 }
2501 d: 9
2502}
2503
2504c1: T(x1) // { a: { b: 8 } }
Marcel van Lohuizen6f0faec2018-12-16 10:42:42 +01002505c2: T({}) // _|_ // missing field 'a' in '{}'
2506c3: T({ a: {b: 0} }) // _|_ // field a.b does not unify (0 & 1..10)
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002507```
Marcel van Lohuizend340e8d2019-01-30 16:57:39 +01002508-->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002509
2510### Calls
2511
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01002512Calls can be made to core library functions, called builtins.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002513Given an expression `f` of function type F,
2514```
2515f(a1, a2, … an)
2516```
2517calls `f` with arguments a1, a2, … an. Arguments must be expressions
2518of which the values are an instance of the parameter types of `F`
2519and are evaluated before the function is called.
2520
2521```
2522a: math.Atan2(x, y)
2523```
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002524
2525In a function call, the function value and arguments are evaluated in the usual
Marcel van Lohuizen1e0fe9c2018-12-21 00:17:06 +01002526order.
2527After they are evaluated, the parameters of the call are passed by value
2528to the function and the called function begins execution.
2529The return parameters
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002530of the function are passed by value back to the calling function when the
2531function returns.
2532
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002533
2534### Comprehensions
2535
Marcel van Lohuizen66db9202018-12-17 19:02:08 +01002536Lists and fields can be constructed using comprehensions.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002537
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02002538Comprehensions define a clause sequence that consists of a sequence of
2539`for`, `if`, and `let` clauses, nesting from left to right.
2540The sequence must start with a `for` or `if` clause.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002541The `for` and `let` clauses each define a new scope in which new values are
2542bound to be available for the next clause.
2543
2544The `for` clause binds the defined identifiers, on each iteration, to the next
2545value of some iterable value in a new scope.
2546A `for` clause may bind one or two identifiers.
Marcel van Lohuizen4245fb42019-09-09 11:22:12 +02002547If there is one identifier, it binds it to the value of
2548a list element or struct field value.
Marcel van Lohuizen5fee32f2019-01-21 22:18:48 +01002549If there are two identifiers, the first value will be the key or index,
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002550if available, and the second will be the value.
2551
Marcel van Lohuizen4245fb42019-09-09 11:22:12 +02002552For lists, `for` iterates over all elements in the list after closing it.
2553For structs, `for` iterates over all non-optional regular fields.
2554
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002555An `if` clause, or guard, specifies an expression that terminates the current
2556iteration if it evaluates to false.
2557
2558The `let` clause binds the result of an expression to the defined identifier
2559in a new scope.
2560
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002561A current iteration is said to complete if the innermost block of the clause
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002562sequence is reached.
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02002563Syntactically, the comprehension value is a struct.
2564A comprehension can generate non-struct values by embedding such values within
2565this struct.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002566
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02002567Within lists, the values yielded by a comprehension are inserted in the list
2568at the position of the comprehension.
2569Within structs, the values yielded by a comprehension are embedded within the
2570struct.
2571Both structs and lists may contain multiple comprehensions.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002572
2573```
Marcel van Lohuizen1f5a9032019-09-09 23:53:42 +02002574Comprehension = Clauses StructLit .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002575
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02002576Clauses = StartClause { [ "," ] Clause } .
2577StartClause = ForClause | GuardClause .
2578Clause = StartClause | LetClause .
2579ForClause = "for" identifier [ "," identifier ] "in" Expression .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002580GuardClause = "if" Expression .
2581LetClause = "let" identifier "=" Expression .
2582```
2583
2584```
2585a: [1, 2, 3, 4]
Marcel van Lohuizende0c53d2020-04-05 15:36:29 +02002586b: [ for x in a if x > 1 { x+1 } ] // [3, 4, 5]
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002587
Marcel van Lohuizen40178752019-08-25 19:17:56 +02002588c: {
2589 for x in a
2590 if x < 4
2591 let y = 1 {
2592 "\(x)": x + y
2593 }
2594}
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002595d: { "1": 2, "2": 3, "3": 4 }
2596```
2597
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002598
2599### String interpolation
2600
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002601String interpolation allows constructing strings by replacing placeholder
2602expressions with their string representation.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002603String interpolation may be used in single- and double-quoted strings, as well
2604as their multiline equivalent.
2605
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002606A placeholder consists of "\(" followed by an expression and a ")". The
2607expression is evaluated within the scope within which the string is defined.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002608
2609```
2610a: "World"
2611b: "Hello \( a )!" // Hello World!
2612```
2613
2614
2615## Builtin Functions
2616
2617Built-in functions are predeclared. They are called like any other function.
2618
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002619
2620### `len`
2621
2622The built-in function `len` takes arguments of various types and return
2623a result of type int.
2624
2625```
2626Argument type Result
2627
2628string string length in bytes
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01002629bytes length of byte sequence
2630list list length, smallest length for an open list
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002631struct number of distinct data fields, including optional
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002632```
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002633<!-- TODO: consider not supporting len, but instead rely on more
2634precisely named builtin functions:
2635 - strings.RuneLen(x)
2636 - bytes.Len(x) // x may be a string
2637 - struct.NumFooFields(x)
2638 - list.Len(x)
2639-->
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01002640
2641```
2642Expression Result
2643len("Hellø") 6
2644len([1, 2, 3]) 3
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002645len([1, 2, ...]) >=2
Marcel van Lohuizen45163fa2019-01-22 15:53:32 +01002646```
2647
Marcel van Lohuizen62658a82019-06-16 12:18:47 +02002648
2649### `close`
2650
2651The builtin function `close` converts a partially defined, or open, struct
2652to a fully defined, or closed, struct.
2653
2654
Marcel van Lohuizena460fe82019-04-26 10:20:51 +02002655### `and`
2656
2657The built-in function `and` takes a list and returns the result of applying
2658the `&` operator to all elements in the list.
2659It returns top for the empty list.
2660
Adieu5b4fa8b2019-12-03 19:20:58 +01002661```
Marcel van Lohuizena460fe82019-04-26 10:20:51 +02002662Expression: Result
2663and([a, b]) a & b
2664and([a]) a
2665and([]) _
Adieu5b4fa8b2019-12-03 19:20:58 +01002666```
Marcel van Lohuizena460fe82019-04-26 10:20:51 +02002667
2668### `or`
2669
2670The built-in function `or` takes a list and returns the result of applying
2671the `|` operator to all elements in the list.
2672It returns bottom for the empty list.
2673
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002674```
Marcel van Lohuizena460fe82019-04-26 10:20:51 +02002675Expression: Result
Adieu5b4fa8b2019-12-03 19:20:58 +01002676or([a, b]) a | b
2677or([a]) a
2678or([]) _|_
Marcel van Lohuizen6c35af62019-05-06 10:50:57 +02002679```
Marcel van Lohuizena460fe82019-04-26 10:20:51 +02002680
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002681
Marcel van Lohuizen6713ae22019-01-26 14:42:25 +01002682## Cycles
2683
2684Implementations are required to interpret or reject cycles encountered
2685during evaluation according to the rules in this section.
2686
2687
2688### Reference cycles
2689
2690A _reference cycle_ occurs if a field references itself, either directly or
2691indirectly.
2692
2693```
2694// x references itself
2695x: x
2696
2697// indirect cycles
2698b: c
2699c: d
2700d: b
2701```
2702
2703Implementations should report these as an error except in the following cases:
2704
2705
2706#### Expressions that unify an atom with an expression
2707
2708An expression of the form `a & e`, where `a` is an atom
2709and `e` is an expression, always evaluates to `a` or bottom.
2710As it does not matter how we fail, we can assume the result to be `a`
2711and validate after the field in which the expression occurs has been evaluated
2712that `a == e`.
2713
2714```
Marcel van Lohuizeneac8f9a2019-08-03 13:53:56 +02002715// Config Evaluates to (requiring concrete values)
Marcel van Lohuizen6713ae22019-01-26 14:42:25 +01002716x: { x: {
2717 a: b + 100 a: _|_ // cycle detected
2718 b: a - 100 b: _|_ // cycle detected
2719} }
2720
2721y: x & { y: {
2722 a: 200 a: 200 // asserted that 200 == b + 100
2723 b: 100
2724} }
2725```
2726
2727
2728#### Field values
2729
2730A field value of the form `r & v`,
2731where `r` evaluates to a reference cycle and `v` is a value,
2732evaluates to `v`.
2733Unification is idempotent and unifying a value with itself ad infinitum,
2734which is what the cycle represents, results in this value.
2735Implementations should detect cycles of this kind, ignore `r`,
2736and take `v` as the result of unification.
Marcel van Lohuizen0d0b9ad2019-10-10 18:19:28 +02002737
Marcel van Lohuizen6713ae22019-01-26 14:42:25 +01002738<!-- Tomabechi's graph unification algorithm
2739can detect such cycles at near-zero cost. -->
2740
2741```
2742Configuration Evaluated
2743// c Cycles in nodes of type struct evaluate
2744// ↙︎ ↖ to the fixed point of unifying their
2745// a → b values ad infinitum.
2746
2747a: b & { x: 1 } // a: { x: 1, y: 2, z: 3 }
2748b: c & { y: 2 } // b: { x: 1, y: 2, z: 3 }
2749c: a & { z: 3 } // c: { x: 1, y: 2, z: 3 }
2750
2751// resolve a b & {x:1}
2752// substitute b c & {y:2} & {x:1}
2753// substitute c a & {z:3} & {y:2} & {x:1}
2754// eliminate a (cycle) {z:3} & {y:2} & {x:1}
2755// simplify {x:1,y:2,z:3}
2756```
2757
2758This rule also applies to field values that are disjunctions of unification
2759operations of the above form.
2760
2761```
2762a: b&{x:1} | {y:1} // {x:1,y:3,z:2} | {y:1}
2763b: {x:2} | c&{z:2} // {x:2} | {x:1,y:3,z:2}
2764c: a&{y:3} | {z:3} // {x:1,y:3,z:2} | {z:3}
2765
2766
2767// resolving a b&{x:1} | {y:1}
2768// substitute b ({x:2} | c&{z:2})&{x:1} | {y:1}
2769// simplify c&{z:2}&{x:1} | {y:1}
2770// substitute c (a&{y:3} | {z:3})&{z:2}&{x:1} | {y:1}
2771// simplify a&{y:3}&{z:2}&{x:1} | {y:1}
2772// eliminate a (cycle) {y:3}&{z:2}&{x:1} | {y:1}
2773// expand {x:1,y:3,z:2} | {y:1}
2774```
2775
2776Note that all nodes that form a reference cycle to form a struct will evaluate
2777to the same value.
2778If a field value is a disjunction, any element that is part of a cycle will
2779evaluate to this value.
2780
2781
2782### Structural cycles
2783
2784CUE disallows infinite structures.
2785Implementations must report an error when encountering such declarations.
2786
2787<!-- for instance using an occurs check -->
2788
2789```
2790// Disallowed: a list of infinite length with all elements being 1.
2791list: {
2792 head: 1
2793 tail: list
2794}
2795
2796// Disallowed: another infinite structure (a:{b:{d:{b:{d:{...}}}}}, ...).
2797a: {
2798 b: c
2799}
2800c: {
2801 d: a
2802}
2803```
2804
2805It is allowed for a value to define an infinite set of possibilities
2806without evaluating to an infinite structure itself.
2807
2808```
2809// List defines a list of arbitrary length (default null).
2810List: *null | {
2811 head: _
2812 tail: List
2813}
2814```
2815
2816<!--
Marcel van Lohuizen7f48df72019-02-01 17:24:59 +01002817Consider banning any construct that makes CUE not having a linear
2818running time expressed in the number of nodes in the output.
2819
2820This would require restricting constructs like:
2821
2822(fib&{n:2}).out
2823
2824fib: {
2825 n: int
2826
2827 out: (fib&{n:n-2}).out + (fib&{n:n-1}).out if n >= 2
2828 out: fib({n:n-2}).out + fib({n:n-1}).out if n >= 2
2829 out: n if n < 2
2830}
2831
2832-->
2833<!--
Marcel van Lohuizen6713ae22019-01-26 14:42:25 +01002834### Unused fields
2835
2836TODO: rules for detection of unused fields
2837
28381. Any alias value must be used
2839-->
2840
2841
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002842## Modules, instances, and packages
2843
2844CUE configurations are constructed combining _instances_.
2845An instance, in turn, is constructed from one or more source files belonging
2846to the same _package_ that together declare the data representation.
2847Elements of this data representation may be exported and used
2848in other instances.
2849
2850### Source file organization
2851
2852Each source file consists of an optional package clause defining collection
2853of files to which it belongs,
2854followed by a possibly empty set of import declarations that declare
2855packages whose contents it wishes to use, followed by a possibly empty set of
2856declarations.
2857
Marcel van Lohuizen1f5a9032019-09-09 23:53:42 +02002858Like with a struct, a source file may contain embeddings.
2859Unlike with a struct, the embedded expressions may be any value.
2860If the result of the unification of all embedded values is not a struct,
2861it will be output instead of its enclosing file when exporting CUE
2862to a data format
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002863
Marcel van Lohuizenc174a082020-05-06 18:37:53 +02002864<!-- TODO: allow ... anywhere in SourceFile and struct. -->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002865```
Marcel van Lohuizenc174a082020-05-06 18:37:53 +02002866SourceFile = [ PackageClause "," ] { ImportDecl "," } { Declaration "," } [ "..." ] .
Marcel van Lohuizen1f5a9032019-09-09 23:53:42 +02002867```
2868
2869```
2870"Hello \(place)!"
2871
2872place: "world"
2873
2874// Outputs "Hello world!"
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002875```
2876
2877### Package clause
2878
2879A package clause is an optional clause that defines the package to which
2880a source file the file belongs.
2881
2882```
2883PackageClause = "package" PackageName .
2884PackageName = identifier .
2885```
2886
Marcel van Lohuizencb8f4f52020-03-08 17:39:39 +01002887The PackageName must not be the blank identifier or a definition identifier.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002888
2889```
2890package math
2891```
2892
2893### Modules and instances
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002894A _module_ defines a tree of directories, rooted at the _module root_.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002895
2896All source files within a module with the same package belong to the same
2897package.
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002898<!-- jba: I can't make sense of the above sentence. -->
2899A module may define multiple packages.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002900
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002901An _instance_ of a package is any subset of files belonging
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002902to the same package.
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002903<!-- jba: Are you saying that -->
2904<!-- if I have a package with files a, b and c, then there are 8 instances of -->
2905<!-- that package, some of which are {a, b}, {c}, {b, c}, and so on? What's the -->
2906<!-- purpose of that definition? -->
2907It is interpreted as the concatenation of these files.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002908
2909An implementation may impose conventions on the layout of package files
2910to determine which files of a package belongs to an instance.
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002911For example, an instance may be defined as the subset of package files
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002912belonging to a directory and all its ancestors.
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002913<!-- jba: OK, that helps a little, but I still don't see what the purpose is. -->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002914
Marcel van Lohuizen7414fae2019-08-13 17:26:35 +02002915
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002916### Import declarations
2917
2918An import declaration states that the source file containing the declaration
2919depends on definitions of the _imported_ package (§Program initialization and
2920execution) and enables access to exported identifiers of that package.
2921The import names an identifier (PackageName) to be used for access and an
2922ImportPath that specifies the package to be imported.
2923
2924```
Marcel van Lohuizen40178752019-08-25 19:17:56 +02002925ImportDecl = "import" ( ImportSpec | "(" { ImportSpec "," } ")" ) .
Marcel van Lohuizenfbab65d2019-08-13 16:51:15 +02002926ImportSpec = [ PackageName ] ImportPath .
Marcel van Lohuizen7414fae2019-08-13 17:26:35 +02002927ImportLocation = { unicode_value } .
2928ImportPath = `"` ImportLocation [ ":" identifier ] `"` .
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002929```
2930
Marcel van Lohuizen7414fae2019-08-13 17:26:35 +02002931The PackageName is used in qualified identifiers to access
2932exported identifiers of the package within the importing source file.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002933It is declared in the file block.
Marcel van Lohuizen7414fae2019-08-13 17:26:35 +02002934It defaults to the identifier specified in the package clause of the imported
2935package, which must match either the last path component of ImportLocation
2936or the identifier following it.
2937
2938<!--
2939Note: this deviates from the Go spec where there is no such restriction.
2940This restriction has the benefit of being to determine the identifiers
2941for packages from within the file itself. But for CUE it is has another benefit:
2942when using package hiearchies, one is more likely to want to include multiple
2943packages within the same directory structure. This mechanism allows
2944disambiguation in these cases.
2945-->
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002946
2947The interpretation of the ImportPath is implementation-dependent but it is
2948typically either the path of a builtin package or a fully qualifying location
Marcel van Lohuizen7414fae2019-08-13 17:26:35 +02002949of a package within a source code repository.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002950
Marcel van Lohuizen7414fae2019-08-13 17:26:35 +02002951An ImportLocation must be a non-empty strings using only characters belonging
2952Unicode's L, M, N, P, and S general categories
2953(the Graphic characters without spaces)
2954and may not include the characters !"#$%&'()*,:;<=>?[\]^`{|}
2955or the Unicode replacement character U+FFFD.
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002956
Jonathan Amsterdame4790382019-01-20 10:29:29 -05002957Assume we have package containing the package clause "package math",
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002958which exports function Sin at the path identified by "lib/math".
2959This table illustrates how Sin is accessed in files
2960that import the package after the various types of import declaration.
2961
2962```
2963Import declaration Local name of Sin
2964
2965import "lib/math" math.Sin
Marcel van Lohuizen7414fae2019-08-13 17:26:35 +02002966import "lib/math:math" math.Sin
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002967import m "lib/math" m.Sin
Marcel van Lohuizendd5e5892018-11-22 23:29:16 +01002968```
2969
2970An import declaration declares a dependency relation between the importing and
2971imported package. It is illegal for a package to import itself, directly or
2972indirectly, or to directly import a package without referring to any of its
2973exported identifiers.
2974
2975
2976### An example package
2977
2978TODO