Debian Codegraph @

doc/ref/language.html.md

raw
1 ---
2 layout: markdown
3 title: Language Reference
4 ---
5
6 # Language Reference
7
8 This page explains Jsonnet in detail. We assume basic familiarity with the language, so if you are just starting out, please go through [the tutorial](/learning/tutorial.html) first. On the other hand, we do not try to cover 100% of the language here. If you need a more complete and precise description, please refer to [the specification](/ref/spec.html) and [the standard library documentation](/ref/stdlib.html).
9
10 ## The Scope of the Jsonnet Project
11
12 Jsonnet is designed primarily for configuring complex systems. The standard use case is integrating multiple services which do not know about each other. Writing the configuration for each independently would result in massive duplication and most likely would be difficult to maintain. Jsonnet allows you to specify the configuration on your terms and programmatically set up all individual services.
13
14 If you are an application author, Jsonnet may free you from having to design your custom configuration format. The applications can simply consume JSON or other structured format and the users can specify their configuration in Jsonnet – a generic configuration language.
15
16 Jsonnet is a full programming language, so it can be used to implement arbitrary logic. However, it does not allow unrestricted IO (see [Independence from the Environment](#independence-from-the-environment-hermeticity)), so it is practical for cases where precise control over input and output is a good thing. There are a couple of potential applications, other than configuration:
17 * Static site generation
18 * Embedded expression language
19 * Ad hoc JSON transformations – it makes sense to use Jsonnet for that if you already know it. Otherwise [jq](https://stedolan.github.io/jq/) is arguably a better option (Jsonnet prioritizes clarity over terseness and convenience, which can be a disadvantage for one-off usage).
20 * Teaching – due to simplicity and principled approach.
21
22 ## What It Is, Not What It Does
23
24 Jsonnet is a purely functional language (with OO features). Programmers accustomed to mostly imperative languages such as Python, C++, Java or Go will need to change their mindset a bit.
25
26 One important difference is that you define things in terms of *what they are* rather than *what they do*. Consider a simple implementation of a `map` function:
27 ```
28 local map(func, arr) =
29 if std.length(arr) == 0 then
30 []
31 else
32 [func(arr[0])] + map(func, arr[1:])
33 ;
34 // Example usage:
35 map(function(i) i * 2, [1, 2, 3, 4, 5])
36 ```
37
38 If you try to read it out loud, you get something like:
39
40 > The result of mapping function `func` over array `arr` is either
41 > 1. an empty array, if array `arr` is empty
42 > 2. the result of applying function `func` to the first element of `arr` followed by the mapping of the remaining elements, if `arr` is not empty.
43
44 Compare it to a traditional, imperative implementation which would read more like:
45 > In order to map a function `func` over array `arr`:
46 > 1. Create a copy of an array `arr`, called `newArr`.
47 > 2. For each index `i` in array `newArr`
48 > * Replace `newArr[i]` with `func` applied to `newArr[i]`.
49 > 3. Return `newArr` as the result.
50
51 Jsonnet definitions are similar to definitions in mathematics. A great advantage of such style is that it frees you from constantly thinking about the state and the order of operations.
52
53 ## Expressions
54
55 Jsonnet programs are composed entirely out of [expressions](https://en.wikipedia.org/wiki/Expression_(computer_science)). There are no statements or special top-level declarations present in most other languages. For instance, imports, conditionals, functions, objects, and locals are all expressions.
56
57 Any kind of expression can be a Jsonnet program, it is not necessary to have a top-level object. For example `2+2`, `"foo"` or `local bar = 21; bar * 2` are all valid Jsonnet programs.
58
59 Expressions can be *evaluated* to produce a *value*. The evaluation does not have any side effects.
60
61 The value to which an expression evaluates depends on its *environment* – values of variables, to which the expression refers. For example expression `x * x` depends on the value of `x`. Such expression is only valid in contexts where variable `x` is available, e.g. `local x = 2; x * x` or `function(x); x * x`.
62
63 Jsonnet variables follow the rules of *lexical scoping*. The environment and consequently the meaning of variables in a given expression is statically determined:
64
65 ```
66 local a = local x = 'a'; x;
67 local foo = local x = 'b'; a;
68 foo
69 ```
70
71 A special case of that is creating [closures](https://en.wikipedia.org/wiki/Closure_(computer_programming)), such as the following:
72 ```
73 local addNumber(number) = function(x) number + x;
74 local add2 = addNumber(2);
75 local add3 = addNumber(3);
76 [
77 add2(2),
78 add3(5)
79 ]
80 ```
81
82 ## Values
83
84 Jsonnet has only seven types of values:
85 * `null` – only one value, namely `null`.
86 * `boolean` – two values, `true` and `false`.
87 * `string` – Unicode strings (sequences of Unicode codepoints).
88 * `number` – IEEE754 64-bit floating point number.
89 * `function`, pure functions which take values as arguments and return a value.
90 * `array`, a finite-length array of values.
91 * `object`, a superset of JSON objects with support for inheritance.
92
93 All Jsonnet values are immutable. It is not possible to change a value of a field of an object or an element of an array – you can only create a new one with the desired change applied.
94
95 You can check the type of any value using `std.type`.
96
97 ### Equivalence and Equality
98
99 We say that values `a` and `b` are equal if `a == b` evaluates to `true` and that they are unequal if `a == b` evaluates to `false`. Some pairs of values are neither equal or unequal, because functions cannot be checked for equality (and consequently some arrays and objects containing functions).
100
101 Values of different types are never considered equal – there is no implicit casting (unlike, for example, in JavaScript).
102
103 We say that values `a` and `b` are *the same value*, or *equivalent* if it is impossible to tell these values apart in any way in Jsonnet. More formally `a` and `b` are equivalent if there does not exist a Jsonnet function `f` such that exactly one of `f(a)` and `f(b)` results in an error.
104
105 In general, equivalent values may have different representations, and that may have performance implications, but does not affect the result.
106
107 Equivalent values of course cannot be unequal, but equal values may not be equivalent (e.g. `{ a: 1, b: 1}` and `{a: 1, b: self.a}`).
108
109 ### Null
110
111 Null is the simplest type in Jsonnet. It has only one value – `null`.
112
113 There is no special handling of `null`, it is a value like any other.
114 In particular arrays can have null elements and objects can have null fields. The null value is equal only to the null value.
115
116 ### Boolean
117
118 Boolean has two values: `true` and `false`. They are the only values which can be used in `if` conditions.
119
120 ### String
121
122 Strings in Jsonnet are sequences of Unicode [codepoints](https://en.wikipedia.org/wiki/Code_point).
123
124 In most contexts a string can be treated as an array of one codepoint strings (e.g. `std.length` and the `[]` operator work like that). Comparisons (`<`, `<=`, `>`, `>=`) and equality checks (`==`, `!=`) also follow this pattern – in both cases codepoints will be compared lexicographically.
125
126 While similar, strings are **not** actually equivalent to arrays of codepoints. For example `std.type("foo") != std.type(["f", "o", "o"])` and `"foo" != ["f", "o", "o"]`).
127
128 Unlike arrays, strings are strict, meaning that evaluating a string requires calculating all its contents.
129
130 Strings can be constructed as literals, slices of existing strings, concatenations of existing strings or converted from an array of Unicode codepoint numbers.
131
132 ### Number
133
134 Jsonnet numbers are 64-bit floating point numbers as defined in IEEE754 excluding `nan` and `inf` values. Operations resulting in infinity or not a number are errors.
135
136 Integers can be safely represented as a Jsonnet number in the range [-2^53 + 1,2^53 - 1]. This is [a direct consequence of IEEE754 spec](https://en.wikipedia.org/wiki/Double-precision_floating-point_format), with the requirements that a safe integer is representable exactly, and cannot be produced by rounding any other integer to fit the IEEE-754 representation. See also, the JavaScript [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER), [`Number.MIN_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER), and [`Number.isSafeInteger`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger) definitions.
137
138 Currently, the C++ and Go Jsonnet implementations restrict the arguments (inputs) to binary bitwise operations (the operators `<<`, `>>`, `&`, `|`, and `^`) to the safe integer range.
139
140 ### Function
141
142 Functions in Jsonnet are functions in the mathematical sense. Each function has parameters and a body expression. The result of calling a function is equivalent to the result of evaluating its body with arguments introduced to the environment.
143
144 You can define a function with a *function literal*:
145 ```
146 local func = function(x) x * 2;
147 func(21)
148 ```
149
150 Jsonnet has syntax sugar which allows a shorter, equivalent variant:
151 ```
152 local func(x) = x * 2;
153 func(21)
154 ```
155
156 The arguments are **not** evaluated when a function is called. They are passed lazily and evaluated only when used. This allows expressing things which in other languages require built-in functionality or macros, such as short-circuit boolean operations:
157 ```
158 local and3(a, b, c) = a && b && c;
159 and3(true, false, error "this one is never evaluated")
160 ```
161 The expression `error "message"` raises an error with the provided message string. Thus, in this example, the values for `a` and `b` are evaluated because they are required to compute `a && b`. However, since `a && b` is `false` - there is no need to evaluate the value for `c` and the error is never thrown.
162
163
164 Functions in Jsonnet are [referentially transparent](https://en.wikipedia.org/wiki/Referential_transparency), meaning that any function call can be replaced with its definition, without changing the meaning of the program. For example consider the following snippet:
165
166 ```
167 local pow2(n) = if n == 0 then 1 else 2 * pow2(n - 1);
168 pow2(17)
169 ```
170
171 The call to function pow2 can be replaced with its definition as follows:
172
173 ```
174 local pow2(n) = if n == 0 then 1 else 2 * pow2(n - 1);
175 local n = 17;
176 if n == 0 then 1 else 2 * pow2(n - 1)
177 ```
178
179 #### Function Parameters
180
181 The parameters can be either required or optional. In the definition, required and optional parameters can be mixed in any order. Optional parameters require specifying the default argument.
182
183 When calling a function, each argument can be passed either as named or as positional, but all positional arguments need to go before the named arguments.
184
185 For example the following program is valid:
186
187 ```
188 local foo(x, y=1) = x + y;
189 [
190 foo(1),
191 foo(1, 1),
192 foo(x=1, y=1),
193 foo(y=1, x=1),
194 foo(x=1),
195 ]
196 ```
197
198 It is recommended to always pass optional arguments as named (for readability). We also recommend to pass arguments as positional **when all parameters are required**, because the function author probably did not consider the parameter names as part of the stable interface.
199
200 (Sidenote: We are looking for a way to have explicit named-only or positional-only parameters in function signatures, without breaking backwards compatibility.)
201
202 ### Array
203
204 Arrays in Jsonnet are finite-length sequences of arbitrary values.
205 Values of different types can be mixed in an array. Individual array elements are lazy, meaning that evaluating an array does not cause evaluation of all arguments.
206
207 ```
208 local arr = [error "a", 2+2, error "b"];
209 arr[1]
210 ```
211
212 In the example above `2+2` is evaluated, but the expressions for the other array elements are not. See: [Rationale for Lazy Semantics](/articles/design.html#lazy).
213
214 There is no separate tuple type in Jsonnet. Arrays are used in contexts where tuples would be natural in other languages, for example for returning multiple values from a function.
215
216 The simplest way of creating an array is *an array literal*. It is simply a comma separated list of elements, such as `[1, 2, "foo", 2 + 2]`.
217
218 The most flexible way of creating an array is `std.makeArray(sz, func)`. It takes the size of the array to construct and a function which takes an index `i` and returns the `i`-th element. It is possible to build all other array functionality using this function. In practice, using more specialized functions is usually (but not always) more handy and results in a more efficient program.
219
220 Arrays can be concatenated using the operator `+`.
221
222 Arrays `a` and `b` are equal if they have equal length and for all indexes `i`, `a[i] == b[i]`.
223
224 The comparison of arrays is lexicographic, so array `a` is smaller than `b` if `a[i] < b[i]` for some `i` and for all `j < i`, `a[j] == b[j]` or if `a` is a (shorter) prefix of `b`.
225
226 #### Array Comprehensions
227
228 Jsonnet offers *array comprehensions* which provide an elegant and easy to use syntax for mapping, filtering and taking Cartesian products of arrays.
229
230 In the simplest case a comprehension generates one element for each element of the source array. This is similar to using `std.map`.
231
232 ```
233 [x * x for x in std.range(1, 10)]
234 ```
235
236 It is possible to add a filtering condition – an `if` component. Array elements are generated only when the condition is met.
237
238 ```
239 [x for x in std.range(1, 10) if x % 3 == 0]
240 ```
241
242 If you add more than one `for`, an element will be generated for each combination of values from each loop. This corresponds to taking a Cartesian product of source arrays.
243
244 The first `for` is the outermost one and the last is the innermost one. In the following example for each value of `x`, all values of `y` are generated before proceeding to the next value of `x`.
245
246 ```
247 [
248 [x, y]
249 for x in std.range(1, 3)
250 for y in std.range(1, 3)
251 ]
252 ```
253
254 The domains for the subsequent `for` components can depend on the earlier ones:
255
256 ```
257 [
258 [x, y]
259 for x in std.range(1, 3)
260 for y in std.range(x, 3)
261 ]
262 ```
263
264 The variables introduced in the subsequent `for` components may shadow variables introduced in the earlier ones.
265 ```
266 [
267 x
268 for x in std.range(1, 3)
269 for x in std.range(1, 3)
270 ]
271 ```
272
273 The `if` and `for` components can be freely mixed. It almost always makes sense to put conditions as early as possible – this way unnecessary iterations of subsequent `for` components will be avoided.
274
275 ```
276 [
277 [x, y]
278 for x in std.range(1, 10)
279 if x % 3 == 0
280 for y in std.range(1, 10)
281 if y % 2 == 0
282 ]
283 ```
284
285 There is nothing "magical" about array comprehensions. They provide a more convenient syntax for what can be achieved using regular functions. In particular, they can always be "mechanically" translated to a series of `std.flatMap` calls and simple conditionals. For example, the following programs are equivalent:
286
287 ```
288 [
289 [x * 2, y]
290 for x in [1, 2, 3, 4, 5]
291 for y in [1, 2, 3]
292 if x % 2 == 0
293 ]
294 ```
295
296 ```
297 std.flatMap(
298 function(x) std.flatMap(
299 function(y) if x % 2 == 0 then [[x * 2, y]] else [],
300 [1, 2, 3]
301 ),
302 [1, 2, 3, 4, 5]
303 )
304 ```
305
306
307 ### Object
308
309 In the simplest case a Jsonnet object is a mapping from string keys to arbitrary values.
310
311 ```
312 {
313 "foo": 1,
314 "bar": {
315 "arr": [1, 2, 3],
316 "number": 10 + 7,
317 }
318 }
319 ```
320
321 Jsonnet objects can be indexed either using `.` with an identifier or `[]` with an arbitrary expression.
322
323 ```
324 local obj = {
325 "foo": 1,
326 "bar": {
327 "arr": [1, 2, 3],
328 "number": 10 + 7,
329 }
330 };
331 [
332 obj.foo,
333 obj["foo"],
334 obj["f" + "oo"]
335 ]
336 ```
337
338 #### Inheritance
339
340 Jsonnet objects allow inheritance in the OOP sense, even though there are no classes or declarations. The inheritance is realized as an operation `+` which can be applied to any two objects. This might be surprising, because in mainstream languages the inheritance hierarchy is static.
341
342 For objects which are simple key-value mappings, inheritance is the same as replacing the respective fields from the first object with fields from the second object.
343
344 ```
345 {
346 a: 1,
347 b: 2,
348 }
349 +
350 {
351 a: 3
352 }
353 ```
354
355 It is possible for one field to refer to other fields of the same object using `self`. When combining objects, it is possible to refer to the inherited fields using `super`.
356
357 ```
358 local obj = {
359 name: "Alice",
360 greeting: "Hello, " + self.name,
361 };
362 [
363 obj,
364 obj + { name: "Bob" },
365 obj + { greeting: super.greeting + "!"},
366 obj + { name: "Bob", greeting: super.greeting + "!"},
367 ]
368 ```
369
370 In general, it is useful to think about a Jsonnet object as a stack of *layers*. A layer consists of fields. An object literal or an object comprehension is a single-layer object. Object inheritance `A` + `B` creates a new object with `B` layers on top of `A` layers.
371
372 Reference to a field through `self` corresponds to looking for the field starting from the top of the stack and going towards the bottom until the field is found. Reference through `super` searches for the field starting from the layer below the current one.
373
374 Because the layers can be added to other objects using inheritance, each field can be a part of multiple objects and have a different value in each of them. Therefore, fields can only be evaluated in the context of the "current object". This context is determined when an object is indexed from outside – then a field *from a specific object* is requested and all its transitive `self` and `super` references can be resolved in this particular stack of layers.
375
376 #### Emulating Functions
377
378 It is easy to emulate functions using objects. While it is bad style, it illustrates the power of dynamic inheritance.
379
380 ```
381 local add = {
382 params: {
383 a: error "please provide argument a",
384 b: error "please provide argument b",
385 },
386 result: self.params.a + self.params.b
387 };
388 (add + { params: { a: 1, b: 2} }).result
389 ```
390
391 #### Properties
392
393 Let `D`, `E`, `F` range over arbitrary objects. Let ≡ mean equivalence.
394
395 * **Associativity** always holds:
396 ```
397 (D + E) + F ≡ D + (E + F)
398 ```
399 * **Identity** always holds:
400 ```
401 D + { } ≡ D
402 { } + D ≡ D
403 ```
404 * **Idempotence** holds when `D` does not contain `super`:
405 ```
406 D + D ≡ D
407 ```
408 * **Commutativity** holds when `D` and `E` do not contain super and have no common fields:
409 ```
410 D + E ≡ E + D
411 ```
412
413 #### Self-Referencing Objects
414
415 Objects can be self-referencing even without OOP features, simply because variable definitions can be recursive:
416
417 ```
418 local obj = {
419 name: "Alice",
420 greeting: "Hello, " + obj.name,
421 }; obj
422 ```
423
424 Referencing `obj` like that is **different** from using `self`. Here `obj` is a specific object with a fixed set of fields and their values, and consequently `obj.name` is a fixed value. On the other hand, `self` is not a value, but a reference to the "current" object and `self.name` can be overridden.
425
426
427 ```
428 [
429 local obj = {
430 name: "Alice",
431 greeting: "Hello, " + obj.name + "!",
432 }; obj + {name: "Bob"},
433 {
434 name: "Alice",
435 greeting: "Hello, " + self.name + "!",
436 } + {name: "Bob"},
437 ]
438 ```
439
440 Going back to the [stack of layers analogy](#inheritance), `self` does not know the stack – it will perform the lookup in the "current object". On the other hand `obj` is a specific stack of layers – a reference from outside.
441
442 Both kinds of behavior are useful. You need to make a decision whether to refer to the fields of the objects as they are currently defined or to allow overriding.
443
444 #### Visibilities
445
446 Jsonnet objects have a concept of visibility which affects manifestation (printing out objects) and equality checks. This concept has nothing to do with the notion of private/public fields from other languages.
447
448 There are three kinds of visibility that an object field may have:
449 * `:` – Default, visible unless parent's field with the same name is hidden.
450 * `::` – Hidden.
451 * `:::` – Forced Visible.
452
453 Example:
454 ```
455 {
456 default: "foo",
457 default_then_hidden: "foo",
458 hidden:: "foo",
459 hidden_then_default:: "foo",
460 hidden_then_visible:: "foo",
461 visible::: "foo",
462 visible_then_hidden::: "foo",
463 }
464 +
465 {
466 default_then_hidden:: "foo",
467 hidden_then_default: "foo",
468 hidden_then_visible::: "foo",
469 visible_then_hidden:: "foo",
470 }
471 ```
472
473 The value of a field is irrelevant for determining its visibility.
474
475 It is possible to check field's visibility using `std.objectHas` and `std.objectHasAll` standard library functions. The first checks if an object has a visible field with a specified name and the second checks if an object has a field regardless of its visibility.
476
477 #### Nested Field Inheritance
478
479 By default nested objects are completely replaced when overriden. For example:
480 ```
481 {
482 nested_object: {
483 field_of_the_nested_object: "will disappear"
484 },
485 not_touched: "still there",
486 }
487 +
488 {
489 nested_object: {
490 new_field: "will be there"
491 }
492 }
493 ```
494 results in:
495 ```
496 {
497 "nested_object": {
498 "new_field": "will be there"
499 },
500 "not_touched": "still there"
501 }
502 ```
503
504 It is possible to explicitly make the new field inherit from the old field instead by using `+:`, `+::` or `+:::` as the field separator in the right-hand side object.
505
506 Example:
507 ```
508 {
509 a: ['a'],
510 b: ['c'],
511 c: { a: 'a', c: 'c' },
512 } +
513 {
514 a: ['a2'],
515 b+: ['c2'],
516 c+: { a: 'a2', b: 'b2' },
517 d+: { d: 'd' },
518 }
519 ```
520 resulting in:
521 ```
522 {
523 "a": [
524 "a2"
525 ],
526 "b": [
527 "c",
528 "c2"
529 ],
530 "c": {
531 "a": "a2",
532 "b": "b2",
533 "c": "c"
534 },
535 "d": {
536 "d": "d"
537 }
538 }
539 ```
540
541 The field separators `+:`, `+::`, `+:::` are relevant for nested objects (which will be inherited) and arrays (which will be concatenated). The number of colons determines the visibility of the field.
542
543 It is not an error to have `+:` without a matching field on the left hand side. In such cases the right hand side field is used directly. E.g. both `{ foo +: { bar: "baz" } }` and `{} + { foo +: { bar: "baz" } }` evaluate to `{ foo: { bar: "baz" } }`.
544
545 In all cases, these field separators are just syntax sugar and the same results can be achieved with `super`. More precisely `{ a +: b }` is equivalent to `{ a: if "a" in super then super.a + b else b }` (and similarly `+::` and `+:::`).
546
547
548 #### Object Equality
549
550 Two objects are equal when their respective *visible* fields are equal. Hidden fields are ignored, which allows ignoring the "helper" parts of the object when evaluating equality.
551
552 Checking equality of some objects is not allowed when the objects contain visible fields that cannot be checked for equality. For example:
553
554 ```
555 {
556 a: function() 42
557 } == {
558 a: function() 42
559 }
560 ```
561
562 Usually, fields which cannot be checked for equality (e.g. functions) should be hidden, because they cannot be manifested, unless a custom manifestation method is used.
563
564 #### Object Locals
565
566 It is possible to declare a `local` inside an object, which will be available to all fields.
567
568 ```
569 {
570 local foo = 1,
571 aaa: foo,
572 bbb: foo,
573 }
574 ```
575
576 Object locals end with a comma, instead of semicolon (like fields). They are not independent expressions, but parts of an object literal expression. Formally, they are equivalent to declaring the locals in each field separately, but interpreters are likely to implement this more efficiently.
577
578 Object locals can access `self` and `super` – they are "inside the object". As a consequence of this, **object locals are not available in Field Name Expressions**, because (in general) they depend on the object being already created, which requires the field names to be already known.
579
580 #### Object Assertions
581
582 Objects may contain assertions, which are boolean expressions that are checked when any of the object's fields are evaluated.
583
584 ```
585 local base = {
586 assert self.a > 0 : "a must be positive",
587 a: self.x * self.y,
588 };
589
590 base + { x: 5, y: -5 }
591 ```
592
593 When this expression is manifested, the assertion will be checked, and in this case fail (since `a` evaluates to `-25`), producing an error with the provided message.
594
595 Note that object assertions are only checked if one or more of an object's fields are evaluated. Since Jsonnet is a lazy language (see [Rationale for Lazy Semantics](/articles/design.html#lazy)), an object might be defined but never evaluated if none of its fields are needed to produce the final output, and in this case the object's assertions are not checked. Listing an object's field names (for example, using the `std.objectFields` or `std.objectFieldsAll` standard library functions) does not evaluate the field values.
596
597 #### Field Name Expressions
598
599 Field names of Jsonnet objects can be arbitrary strings and can be calculated dynamically *when the object is created*.
600
601 ```
602 {
603 a: 1,
604 "a a": 2,
605 "ąę": 3,
606 ["aaa" + "bbb"]: 4,
607 }
608 ```
609
610 When an object is evaluated, all the field names are evaluated. This means they cannot refer to object locals, `self`, or `super`. In other words, their scope is "outside of the object".
611
612 #### Conditional Fields
613
614 If a field name evaluates to null, that field value is discarded and not included in the resulting object. The following code will evaluate to the empty object:
615
616 ```
617 {
618 [if 1 == 2 then "foo"]: "bar",
619 }
620 ```
621
622 ## Independence from the Environment (Hermeticity)
623
624 Jsonnet programs are *pure computations*, which have no side-effects and which depend only on the values which were explicitly passed.
625 In particular, the behavior is independent from the setup of the system on which it runs (operating system, environment variables, filesystem, ...).
626 The semantics are [defined almost entirely in mathematical terms](/ref/spec.html), with a few exceptions, where Jsonnet depends on well-established portable standards (such as [IEEE754](https://en.wikipedia.org/wiki/IEEE_754) and [Unicode](https://en.wikipedia.org/wiki/Unicode)).
627
628 It is possible to pass data from the environment, but only explicitly, by using abstractions provided by Jsonnet. This has multiple benefits:
629 * Fewer surprises – The behavior will not change when you change something about your system. In other languages any part of the program can depend on anything. In Jsonnet you need to worry only about what is explicitly passed.
630 * Easier to run on other machines (e.g. development or CI) – You can pass any values to the program, which allows generating any configuration on any system.
631 * Longevity – Jsonnet programs don't need to change as other technologies go out of date.
632 * Portability – it is reasonably easy to create an implementation of Jsonnet for any platform.
633
634 ## Passing Data to Jsonnet
635
636 ### Consider Self-Contained Programs
637
638 Before using any of the methods described below, it is worth considering if a fully self-contained setup is viable.
639
640 In this style, the configuration is a set of `.jsonnet` and `.libsonnet` files. Every output file corresponds to a `.jsonnet` file and all shared setup is in `.libsonnet` files. Any raw data can be placed in additional files and imported using `importstr` or `importbin`. Usually, all code and data is committed to a repository.
641 Sometimes the generated configuration is also checked in, which makes it easy to spot unintended changes.
642
643 Sometimes it is not practical, though. For example if the produced configuration needs to contain secrets, which you do not want to commit alongside code, it is necessary to pass them from outside.
644
645 ### Top-Level Arguments (TLAs)
646
647 The preferred way of passing data to Jsonnet is through Top-level Arguments. This mechanism allows calling a Jsonnet program like a function.
648
649 Consider the following simple program `add.jsonnet`:
650 ```
651 function(a, b) a + b
652 ```
653
654 It can be called `jsonnet add.jsonnet --tla-code a=1 --tla-code b=2`. The result of the evaluation will be `3`.
655
656 Any program evaluating to a function can be called with TLAs.
657
658 ```
659 jsonnet -e 'std.map' --tla-code 'func=function(x) x * x' --tla-code arr='[1, 2, 3]'
660 ```
661
662 Functions are the canonical way of parameterizing values, so this method of passing values to programs fits well with the rest of the language. For example, the programs intended for use with TLAs can also be imported from other Jsonnet files and called as normal functions:
663
664 ```
665 local add = import 'add.jsonnet';
666 add(1, 2)
667 ```
668
669 ### External Variables (ExtVars)
670
671 Alternatively, you can use ExtVars. ExtVars are available globally in the program, including in any imported library. **Contrary to their name, they are not variables in the same sense as variables introduced by `local`**. They have a separate namespace and can be accessed through `std.extVar` function.
672
673 Consider the following program `foo.jsonnet`:
674 ```
675 std.extVar("foo")
676 ```
677 It can be called with `jsonnet foo.jsonnet --ext-str foo=bar`.
678
679 Referring to an undeclared External Variable is an error. There is no way to check if an ExtVar exists dynamically. There is no way to set External Variables from within a Jsonnet program – they need to be set before execution.
680
681 Since ExtVars are global, they create composability problems. It is easy to imagine two libraries depending on the same ExtVar, but with a different meaning. **For this reason we strongly discourage authors of generic libraries from using ExtVars**. If a global configuration for a library is desired, you can make your library a function which has parameter for any necessary configuration. This is less of a problem in "final" setups – in individual configuration or in opinionated frameworks, which enforce the structure anyway.
682
683 <!--
684 TODO: Some parts of this page are still incomplete:
685 * JsonPath heritage of $ (?)
686 * Scoping rules of local
687 * numbers, floating point rounding error, int64, bitwise on float
688 * different types of string literals, escapes, strings that span lines |||, line endings
689 * Precise meaning of $
690 * scope of self within an object, including locals, asserts and comprehensions
691 * general form of comprehensions
692 * general form of slices (!)
693 * precise semantics of default argument expressions
694 * tailstrict
695 * Recursion in all its forms - functions, objects, modules, locals
696 * "Looping in Jsonnet" – recursion and higher-order functions
697 * More object orientation: mixins, diamond problem, definition of +: (!)
698 * laziness in depth (!!)
699 * Imports in depth: relative paths, jpaths, etc. (!!)
700 * Libraries in Jsonnet (e.g. libraries are usually objects, parametrized libraries (!!)
701 * Native callbacks and import callbacks
702 * operator precedence
703 * Testing
704 * Debugging techniques
705 * Explaining syntax sugar for methods
706 * "Plain objects" (equivalent to the mapping).
707 * Thunks
708 * Producing non-JSON output (custom manifestation, string output)
709
710 TODO: technical issues
711 * Include example output (!!!)
712 * Make examples interactive (but keep them visually compact)
713 * Table of Contents
714 * Easier links to headers – make headers themselves links? (!!)
715 -->>