Debian Codegraph @

stdlib/std.jsonnet

raw
1 /*
2 Copyright 2015 Google Inc. All rights reserved.
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
17 /* This is the Jsonnet standard library, at least the parts of it that are written in Jsonnet.
18 *
19 * There are some native methods as well, which are defined in the interpreter and added to this
20 * file. It is never necessary to import std.jsonnet, it is embedded into the interpreter at
21 * compile-time and automatically imported into all other Jsonnet programs.
22 */
23 {
24
25 local std = self,
26 local id = function(x) x,
27
28 local go_only_function = error 'This function is only supported in go version of jsonnet. See https://github.com/google/go-jsonnet',
29
30 isString(v):: std.type(v) == 'string',
31 isNumber(v):: std.type(v) == 'number',
32 isBoolean(v):: std.type(v) == 'boolean',
33 isObject(v):: std.type(v) == 'object',
34 isArray(v):: std.type(v) == 'array',
35 isFunction(v):: std.type(v) == 'function',
36 isNull(v):: v == null,
37
38 toString(a)::
39 if std.type(a) == 'string' then a else '' + a,
40
41 substr(str, from, len)::
42 assert std.isString(str) : 'substr first parameter should be a string, got ' + std.type(str);
43 assert std.isNumber(from) : 'substr second parameter should be a string, got ' + std.type(from);
44 assert std.isNumber(len) : 'substr third parameter should be a string, got ' + std.type(len);
45 assert len >= 0 : 'substr third parameter should be greater than zero, got ' + len;
46 std.join('', std.makeArray(std.max(0, std.min(len, std.length(str) - from)), function(i) str[i + from])),
47
48 startsWith(a, b)::
49 if std.length(a) < std.length(b) then
50 false
51 else
52 std.substr(a, 0, std.length(b)) == b,
53
54 endsWith(a, b)::
55 if std.length(a) < std.length(b) then
56 false
57 else
58 std.substr(a, std.length(a) - std.length(b), std.length(b)) == b,
59
60 lstripChars(str, chars)::
61 if std.length(str) > 0 && std.member(chars, str[0]) then
62 std.lstripChars(str[1:], chars) tailstrict
63 else
64 str,
65
66 rstripChars(str, chars)::
67 local len = std.length(str);
68 if len > 0 && std.member(chars, str[len - 1]) then
69 std.rstripChars(str[:len - 1], chars) tailstrict
70 else
71 str,
72
73 stripChars(str, chars)::
74 std.lstripChars(std.rstripChars(str, chars), chars),
75
76 stringChars(str)::
77 std.makeArray(std.length(str), function(i) str[i]),
78
79 local parse_nat(str, base) =
80 assert base > 0 && base <= 16 : 'integer base %d invalid' % base;
81 // These codepoints are in ascending order:
82 local zero_code = std.codepoint('0');
83 local upper_a_code = std.codepoint('A');
84 local lower_a_code = std.codepoint('a');
85 local addDigit(aggregate, char) =
86 local code = std.codepoint(char);
87 local digit = if code >= lower_a_code then
88 code - lower_a_code + 10
89 else if code >= upper_a_code then
90 code - upper_a_code + 10
91 else
92 code - zero_code;
93 assert digit >= 0 && digit < base : '%s is not a base %d integer' % [str, base];
94 base * aggregate + digit;
95 std.foldl(addDigit, std.stringChars(str), 0),
96
97 parseInt(str)::
98 assert std.isString(str) : 'Expected string, got ' + std.type(str);
99 assert std.length(str) > 0 && str != '-' : 'Not an integer: "%s"' % [str];
100 if str[0] == '-' then
101 -parse_nat(str[1:], 10)
102 else
103 parse_nat(str, 10),
104
105 parseOctal(str)::
106 assert std.isString(str) : 'Expected string, got ' + std.type(str);
107 assert std.length(str) > 0 : 'Not an octal number: ""';
108 parse_nat(str, 8),
109
110 parseHex(str)::
111 assert std.isString(str) : 'Expected string, got ' + std.type(str);
112 assert std.length(str) > 0 : 'Not hexadecimal: ""';
113 parse_nat(str, 16),
114
115 split(str, c)::
116 assert std.isString(str) : 'std.split first parameter must be a String, got ' + std.type(str);
117 assert std.isString(c) : 'std.split second parameter must be a String, got ' + std.type(c);
118 assert std.length(c) >= 1 : 'std.split second parameter must have length 1 or greater, got ' + std.length(c);
119 std.splitLimit(str, c, -1),
120
121 splitLimit(str, c, maxsplits)::
122 assert std.isString(str) : 'str.splitLimit first parameter must be a String, got ' + std.type(str);
123 assert std.isString(c) : 'str.splitLimit second parameter must be a String, got ' + std.type(c);
124 assert std.length(c) >= 1 : 'std.splitLimit second parameter must have length 1 or greater, got ' + std.length(c);
125 assert std.isNumber(maxsplits) : 'str.splitLimit third parameter must be a Number, got ' + std.type(maxsplits);
126 local strLen = std.length(str);
127 local cLen = std.length(c);
128 local aux(idx, ret, val) =
129 if idx >= strLen then
130 ret + [val]
131 else if str[idx:idx + cLen:1] == c &&
132 (maxsplits == -1 || std.length(ret) < maxsplits) then
133 aux(idx + cLen, ret + [val], '')
134 else
135 aux(idx + 1, ret, val + str[idx]);
136 aux(0, [], ''),
137
138 splitLimitR(str, c, maxsplits)::
139 assert std.isString(str) : 'str.splitLimitR first parameter must be a String, got ' + std.type(str);
140 assert std.isString(c) : 'str.splitLimitR second parameter must be a String, got ' + std.type(c);
141 assert std.length(c) >= 1 : 'std.splitLimitR second parameter must have length 1 or greater, got ' + std.length(c);
142 assert std.isNumber(maxsplits) : 'str.splitLimitR third parameter must be a Number, got ' + std.type(maxsplits);
143 if maxsplits == -1 then
144 std.splitLimit(str, c, -1)
145 else
146 local revStr(str) = std.join('', std.reverse(std.stringChars(str)));
147 std.map(function(e) revStr(e), std.reverse(std.splitLimit(revStr(str), revStr(c), maxsplits))),
148
149 strReplace(str, from, to)::
150 assert std.isString(str);
151 assert std.isString(from);
152 assert std.isString(to);
153 assert from != '' : "'from' string must not be zero length.";
154
155 // Cache for performance.
156 local str_len = std.length(str);
157 local from_len = std.length(from);
158
159 // True if from is at str[i].
160 local found_at(i) = str[i:i + from_len] == from;
161
162 // Return the remainder of 'str' starting with 'start_index' where
163 // all occurrences of 'from' after 'curr_index' are replaced with 'to'.
164 local replace_after(start_index, curr_index, acc) =
165 if curr_index > str_len then
166 acc + str[start_index:curr_index]
167 else if found_at(curr_index) then
168 local new_index = curr_index + std.length(from);
169 replace_after(new_index, new_index, acc + str[start_index:curr_index] + to) tailstrict
170 else
171 replace_after(start_index, curr_index + 1, acc) tailstrict;
172
173 // if from_len==1, then we replace by splitting and rejoining the
174 // string which is much faster than recursing on replace_after
175 if from_len == 1 then
176 std.join(to, std.split(str, from))
177 else
178 replace_after(0, 0, ''),
179
180 asciiUpper(str)::
181 local cp = std.codepoint;
182 local up_letter(c) = if cp(c) >= 97 && cp(c) < 123 then
183 std.char(cp(c) - 32)
184 else
185 c;
186 std.join('', std.map(up_letter, std.stringChars(str))),
187
188 asciiLower(str)::
189 local cp = std.codepoint;
190 local down_letter(c) = if cp(c) >= 65 && cp(c) < 91 then
191 std.char(cp(c) + 32)
192 else
193 c;
194 std.join('', std.map(down_letter, std.stringChars(str))),
195
196 range(from, to)::
197 std.makeArray(to - from + 1, function(i) i + from),
198
199 repeat(what, count)::
200 local joiner =
201 if std.isString(what) then ''
202 else if std.isArray(what) then []
203 else error 'std.repeat first argument must be an array or a string';
204 std.join(joiner, std.makeArray(count, function(i) what)),
205
206 slice(indexable, index, end, step)::
207 local invar =
208 // loop invariant with defaults applied
209 {
210 length: std.length(indexable),
211 indexable: indexable,
212 index:
213 if index == null
214 then 0
215 else
216 if index < 0
217 then std.max(0, self.length + index)
218 else index,
219 end:
220 if end == null
221 then self.length
222 else
223 if end < 0
224 then self.length + end
225 else end,
226 step:
227 if step == null
228 then 1
229 else step,
230 type: std.type(indexable)
231 };
232 assert invar.step >= 0 : 'got [%s:%s:%s] but negative steps are not supported' % [invar.index, invar.end, invar.step];
233 assert step != 0 : 'got %s but step must be greater than 0' % step;
234 assert std.isString(indexable) || std.isArray(indexable) : 'std.slice accepts a string or an array, but got: %s' % std.type(indexable);
235 local build(slice, cur) =
236 if cur >= invar.end || cur >= invar.length then
237 slice
238 else
239 build(
240 if invar.type == 'string' then
241 slice + invar.indexable[cur]
242 else
243 slice + [invar.indexable[cur]],
244 cur + invar.step
245 ) tailstrict;
246 build(if invar.type == 'string' then '' else [], invar.index),
247
248 member(arr, x)::
249 if std.isArray(arr) then
250 std.count(arr, x) > 0
251 else if std.isString(arr) then
252 std.length(std.findSubstr(x, arr)) > 0
253 else error 'std.member first argument must be an array or a string',
254
255 count(arr, x):: std.length(std.filter(function(v) v == x, arr)),
256
257 mod(a, b)::
258 if std.isNumber(a) && std.isNumber(b) then
259 std.modulo(a, b)
260 else if std.isString(a) then
261 std.format(a, b)
262 else
263 error 'Operator % cannot be used on types ' + std.type(a) + ' and ' + std.type(b) + '.',
264
265 // this is the most precision that will fit in a f64
266 pi:: 3.14159265358979311600,
267
268 deg2rad(x):: x * std.pi / 180,
269 rad2deg(x):: x * 180 / std.pi,
270
271 log2(x):: std.log(x) / std.log(2),
272 log10(x):: std.log(x) / std.log(10),
273
274 map(func, arr)::
275 if !std.isFunction(func) then
276 error ('std.map first param must be function, got ' + std.type(func))
277 else if !std.isArray(arr) && !std.isString(arr) then
278 error ('std.map second param must be array / string, got ' + std.type(arr))
279 else
280 std.makeArray(std.length(arr), function(i) func(arr[i])),
281
282 mapWithIndex(func, arr)::
283 if !std.isFunction(func) then
284 error ('std.mapWithIndex first param must be function, got ' + std.type(func))
285 else if !std.isArray(arr) && !std.isString(arr) then
286 error ('std.mapWithIndex second param must be array, got ' + std.type(arr))
287 else
288 std.makeArray(std.length(arr), function(i) func(i, arr[i])),
289
290 mapWithKey(func, obj)::
291 if !std.isFunction(func) then
292 error ('std.mapWithKey first param must be function, got ' + std.type(func))
293 else if !std.isObject(obj) then
294 error ('std.mapWithKey second param must be object, got ' + std.type(obj))
295 else
296 { [k]: func(k, obj[k]) for k in std.objectFields(obj) },
297
298 flatMap(func, arr)::
299 if !std.isFunction(func) then
300 error ('std.flatMap first param must be function, got ' + std.type(func))
301 else if std.isArray(arr) then
302 std.flattenArrays(std.makeArray(
303 std.length(arr), function(i)
304 local o = func(arr[i]);
305 if std.isArray(o) then o else
306 error ('std.flatMap on arrays, provided function must return an array, got ' + std.type(o))
307 ))
308 else if std.isString(arr) then
309 std.join('', std.makeArray(
310 std.length(arr), function(i)
311 local o = func(arr[i]);
312 if std.isString(o) then o else
313 error ('std.flatMap on strings, provided function must return a string, got ' + std.type(o))
314 ))
315 else error ('std.flatMap second param must be array / string, got ' + std.type(arr)),
316
317 join(sep, arr)::
318 local aux(arr, i, first, running) =
319 if i >= std.length(arr) then
320 running
321 else if arr[i] == null then
322 aux(arr, i + 1, first, running) tailstrict
323 else if std.type(arr[i]) != std.type(sep) then
324 error 'expected %s but arr[%d] was %s ' % [std.type(sep), i, std.type(arr[i])]
325 else if first then
326 aux(arr, i + 1, false, running + arr[i]) tailstrict
327 else
328 aux(arr, i + 1, false, running + sep + arr[i]) tailstrict;
329 if !std.isArray(arr) then
330 error 'join second parameter should be array, got ' + std.type(arr)
331 else if std.isString(sep) then
332 aux(arr, 0, true, '')
333 else if std.isArray(sep) then
334 aux(arr, 0, true, [])
335 else
336 error 'join first parameter should be string or array, got ' + std.type(sep),
337
338 lines(arr)::
339 std.join('\n', arr + ['']),
340
341 deepJoin(arr)::
342 if std.isString(arr) then
343 arr
344 else if std.isArray(arr) then
345 std.join('', [std.deepJoin(x) for x in arr])
346 else
347 error 'Expected string or array, got %s' % std.type(arr),
348
349
350 format(str, vals)::
351
352 /////////////////////////////
353 // Parse the mini-language //
354 /////////////////////////////
355
356 local try_parse_mapping_key(str, i) =
357 assert i < std.length(str) : 'Truncated format code.';
358 local c = str[i];
359 if c == '(' then
360 local consume(str, j, v) =
361 if j >= std.length(str) then
362 error 'Truncated format code.'
363 else
364 local c = str[j];
365 if c != ')' then
366 consume(str, j + 1, v + c)
367 else
368 { i: j + 1, v: v };
369 consume(str, i + 1, '')
370 else
371 { i: i, v: null };
372
373 local try_parse_cflags(str, i) =
374 local consume(str, j, v) =
375 assert j < std.length(str) : 'Truncated format code.';
376 local c = str[j];
377 if c == '#' then
378 consume(str, j + 1, v { alt: true })
379 else if c == '0' then
380 consume(str, j + 1, v { zero: true })
381 else if c == '-' then
382 consume(str, j + 1, v { left: true })
383 else if c == ' ' then
384 consume(str, j + 1, v { blank: true })
385 else if c == '+' then
386 consume(str, j + 1, v { plus: true })
387 else
388 { i: j, v: v };
389 consume(str, i, { alt: false, zero: false, left: false, blank: false, plus: false });
390
391 local try_parse_field_width(str, i) =
392 if i < std.length(str) && str[i] == '*' then
393 { i: i + 1, v: '*' }
394 else
395 local consume(str, j, v) =
396 assert j < std.length(str) : 'Truncated format code.';
397 local c = str[j];
398 if c == '0' then
399 consume(str, j + 1, v * 10 + 0)
400 else if c == '1' then
401 consume(str, j + 1, v * 10 + 1)
402 else if c == '2' then
403 consume(str, j + 1, v * 10 + 2)
404 else if c == '3' then
405 consume(str, j + 1, v * 10 + 3)
406 else if c == '4' then
407 consume(str, j + 1, v * 10 + 4)
408 else if c == '5' then
409 consume(str, j + 1, v * 10 + 5)
410 else if c == '6' then
411 consume(str, j + 1, v * 10 + 6)
412 else if c == '7' then
413 consume(str, j + 1, v * 10 + 7)
414 else if c == '8' then
415 consume(str, j + 1, v * 10 + 8)
416 else if c == '9' then
417 consume(str, j + 1, v * 10 + 9)
418 else
419 { i: j, v: v };
420 consume(str, i, 0);
421
422 local try_parse_precision(str, i) =
423 assert i < std.length(str) : 'Truncated format code.';
424 local c = str[i];
425 if c == '.' then
426 try_parse_field_width(str, i + 1)
427 else
428 { i: i, v: null };
429
430 // Ignored, if it exists.
431 local try_parse_length_modifier(str, i) =
432 assert i < std.length(str) : 'Truncated format code.';
433 local c = str[i];
434 if c == 'h' || c == 'l' || c == 'L' then
435 i + 1
436 else
437 i;
438
439 local parse_conv_type(str, i) =
440 assert i < std.length(str) : 'Truncated format code.';
441 local c = str[i];
442 if c == 'd' || c == 'i' || c == 'u' then
443 { i: i + 1, v: 'd', caps: false }
444 else if c == 'o' then
445 { i: i + 1, v: 'o', caps: false }
446 else if c == 'x' then
447 { i: i + 1, v: 'x', caps: false }
448 else if c == 'X' then
449 { i: i + 1, v: 'x', caps: true }
450 else if c == 'e' then
451 { i: i + 1, v: 'e', caps: false }
452 else if c == 'E' then
453 { i: i + 1, v: 'e', caps: true }
454 else if c == 'f' then
455 { i: i + 1, v: 'f', caps: false }
456 else if c == 'F' then
457 { i: i + 1, v: 'f', caps: true }
458 else if c == 'g' then
459 { i: i + 1, v: 'g', caps: false }
460 else if c == 'G' then
461 { i: i + 1, v: 'g', caps: true }
462 else if c == 'c' then
463 { i: i + 1, v: 'c', caps: false }
464 else if c == 's' then
465 { i: i + 1, v: 's', caps: false }
466 else if c == '%' then
467 { i: i + 1, v: '%', caps: false }
468 else
469 error 'Unrecognised conversion type: ' + c;
470
471
472 // Parsed initial %, now the rest.
473 local parse_code(str, i) =
474 assert i < std.length(str) : 'Truncated format code.';
475 local mkey = try_parse_mapping_key(str, i);
476 local cflags = try_parse_cflags(str, mkey.i);
477 local fw = try_parse_field_width(str, cflags.i);
478 local prec = try_parse_precision(str, fw.i);
479 local len_mod = try_parse_length_modifier(str, prec.i);
480 local ctype = parse_conv_type(str, len_mod);
481 {
482 i: ctype.i,
483 code: {
484 mkey: mkey.v,
485 cflags: cflags.v,
486 fw: fw.v,
487 prec: prec.v,
488 ctype: ctype.v,
489 caps: ctype.caps,
490 },
491 };
492
493 // Parse a format string (containing none or more % format tags).
494 local parse_codes(str, i, out, cur) =
495 if i >= std.length(str) then
496 out + [cur]
497 else
498 local c = str[i];
499 if c == '%' then
500 local r = parse_code(str, i + 1);
501 parse_codes(str, r.i, out + [cur, r.code], '') tailstrict
502 else
503 parse_codes(str, i + 1, out, cur + c) tailstrict;
504
505 local codes = parse_codes(str, 0, [], '');
506
507
508 ///////////////////////
509 // Format the values //
510 ///////////////////////
511
512 // Useful utilities
513 local padding(w, s) =
514 local aux(w, v) =
515 if w <= 0 then
516 v
517 else
518 aux(w - 1, v + s);
519 aux(w, '');
520
521 // Add s to the left of str so that its length is at least w.
522 local pad_left(str, w, s) =
523 padding(w - std.length(str), s) + str;
524
525 // Add s to the right of str so that its length is at least w.
526 local pad_right(str, w, s) =
527 str + padding(w - std.length(str), s);
528
529 // Render a sign & magnitude integer (radix ranges from decimal to binary).
530 // neg should be a boolean, and when true indicates that we should render a negative number.
531 // mag must always be a whole number >= 0, it's the magnitude of the integer to render
532 // min_chars must be a whole number >= 0
533 // It is the field width, i.e. std.length() of the result should be >= min_chars
534 // min_digits must be a whole number >= 0. It's the number of zeroes to pad with.
535 // blank must be a boolean, if true adds an additional ' ' in front of a positive number, so
536 // that it is aligned with negative numbers with the same number of digits.
537 // plus must be a boolean, if true adds a '+' in front of a positive number, so that it is
538 // aligned with negative numbers with the same number of digits. This takes precedence over
539 // blank, if both are true.
540 // radix must be a whole number >1 and <= 10. It is the base of the system of numerals.
541 // zero_prefix is a string prefixed before the sign to all numbers that are not 0.
542 local render_int(neg, mag, min_chars, min_digits, blank, plus, radix, zero_prefix) =
543 // dec is the minimal string needed to represent the number as text.
544 local dec =
545 if mag == 0 then
546 '0'
547 else
548 local aux(n) =
549 if n == 0 then
550 zero_prefix
551 else
552 aux(std.floor(n / radix)) + (n % radix);
553 aux(mag);
554 local zp = min_chars - (if neg || blank || plus then 1 else 0);
555 local zp2 = std.max(zp, min_digits);
556 local dec2 = pad_left(dec, zp2, '0');
557 (if neg then '-' else if plus then '+' else if blank then ' ' else '') + dec2;
558
559 // Render an integer in hexadecimal.
560 local render_hex(n__, min_chars, min_digits, blank, plus, add_zerox, capitals) =
561 local numerals = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
562 + if capitals then ['A', 'B', 'C', 'D', 'E', 'F']
563 else ['a', 'b', 'c', 'd', 'e', 'f'];
564 local n_ = std.abs(n__);
565 local aux(n) =
566 if n == 0 then
567 ''
568 else
569 aux(std.floor(n / 16)) + numerals[n % 16];
570 local hex = if std.floor(n_) == 0 then '0' else aux(std.floor(n_));
571 local neg = n__ < 0;
572 local zp = min_chars - (if neg || blank || plus then 1 else 0)
573 - (if add_zerox then 2 else 0);
574 local zp2 = std.max(zp, min_digits);
575 local hex2 = (if add_zerox then (if capitals then '0X' else '0x') else '')
576 + pad_left(hex, zp2, '0');
577 (if neg then '-' else if plus then '+' else if blank then ' ' else '') + hex2;
578
579 local strip_trailing_zero(str) =
580 local aux(str, i) =
581 if i < 0 then
582 ''
583 else
584 if str[i] == '0' then
585 aux(str, i - 1)
586 else
587 std.substr(str, 0, i + 1);
588 aux(str, std.length(str) - 1);
589
590 // Render floating point in decimal form
591 local render_float_dec(n__, zero_pad, blank, plus, ensure_pt, trailing, prec) =
592 local n_ = std.abs(n__);
593 local whole = std.floor(n_);
594 // Represent the rounded number as an integer * 1/10**prec.
595 // Note that it can also be equal to 10**prec and we'll need to carry
596 // over to the wholes. We operate on the absolute numbers, so that we
597 // don't have trouble with the rounding direction.
598 local denominator = std.pow(10, prec);
599 local numerator = std.abs(n_) * denominator + 0.5;
600 local whole = std.sign(n_) * std.floor(numerator / denominator);
601 local frac = std.floor(numerator) % denominator;
602 local dot_size = if prec == 0 && !ensure_pt then 0 else 1;
603 local zp = zero_pad - prec - dot_size;
604 local str = render_int(n__ < 0, whole, zp, 0, blank, plus, 10, '');
605 if prec == 0 then
606 str + if ensure_pt then '.' else ''
607 else
608 if trailing || frac > 0 then
609 local frac_str = render_int(false, frac, prec, 0, false, false, 10, '');
610 str + '.' + if !trailing then strip_trailing_zero(frac_str) else frac_str
611 else
612 str;
613
614 // Render floating point in scientific form
615 local render_float_sci(n__, zero_pad, blank, plus, ensure_pt, trailing, caps, prec) =
616 local exponent = if n__ == 0 then 0 else std.floor(std.log(std.abs(n__)) / std.log(10));
617 local suff = (if caps then 'E' else 'e')
618 + render_int(exponent < 0, std.abs(exponent), 3, 0, false, true, 10, '');
619 local mantissa = if exponent == -324 then
620 // Avoid a rounding error where std.pow(10, -324) is 0
621 // -324 is the smallest exponent possible.
622 n__ * 10 / std.pow(10, exponent + 1)
623 else
624 n__ / std.pow(10, exponent);
625 local zp2 = zero_pad - std.length(suff);
626 render_float_dec(mantissa, zp2, blank, plus, ensure_pt, trailing, prec) + suff;
627
628 // Render a value with an arbitrary format code.
629 local format_code(val, code, fw, prec_or_null, i) =
630 local cflags = code.cflags;
631 local fpprec = if prec_or_null != null then prec_or_null else 6;
632 local iprec = if prec_or_null != null then prec_or_null else 0;
633 local zp = if cflags.zero && !cflags.left then fw else 0;
634 if code.ctype == 's' then
635 std.toString(val)
636 else if code.ctype == 'd' then
637 if std.type(val) != 'number' then
638 error 'Format required number at '
639 + i + ', got ' + std.type(val)
640 else
641 render_int(val <= -1, std.floor(std.abs(val)), zp, iprec, cflags.blank, cflags.plus, 10, '')
642 else if code.ctype == 'o' then
643 if std.type(val) != 'number' then
644 error 'Format required number at '
645 + i + ', got ' + std.type(val)
646 else
647 local zero_prefix = if cflags.alt then '0' else '';
648 render_int(val <= -1, std.floor(std.abs(val)), zp, iprec, cflags.blank, cflags.plus, 8, zero_prefix)
649 else if code.ctype == 'x' then
650 if std.type(val) != 'number' then
651 error 'Format required number at '
652 + i + ', got ' + std.type(val)
653 else
654 render_hex(std.floor(val),
655 zp,
656 iprec,
657 cflags.blank,
658 cflags.plus,
659 cflags.alt,
660 code.caps)
661 else if code.ctype == 'f' then
662 if std.type(val) != 'number' then
663 error 'Format required number at '
664 + i + ', got ' + std.type(val)
665 else
666 render_float_dec(val,
667 zp,
668 cflags.blank,
669 cflags.plus,
670 cflags.alt,
671 true,
672 fpprec)
673 else if code.ctype == 'e' then
674 if std.type(val) != 'number' then
675 error 'Format required number at '
676 + i + ', got ' + std.type(val)
677 else
678 render_float_sci(val,
679 zp,
680 cflags.blank,
681 cflags.plus,
682 cflags.alt,
683 true,
684 code.caps,
685 fpprec)
686 else if code.ctype == 'g' then
687 if std.type(val) != 'number' then
688 error 'Format required number at '
689 + i + ', got ' + std.type(val)
690 else
691 local exponent = if val != 0 then std.floor(std.log(std.abs(val)) / std.log(10)) else 0;
692 if exponent < -4 || exponent >= fpprec then
693 render_float_sci(val,
694 zp,
695 cflags.blank,
696 cflags.plus,
697 cflags.alt,
698 cflags.alt,
699 code.caps,
700 fpprec - 1)
701 else
702 local digits_before_pt = std.max(1, exponent + 1);
703 render_float_dec(val,
704 zp,
705 cflags.blank,
706 cflags.plus,
707 cflags.alt,
708 cflags.alt,
709 fpprec - digits_before_pt)
710 else if code.ctype == 'c' then
711 if std.type(val) == 'number' then
712 std.char(val)
713 else if std.type(val) == 'string' then
714 if std.length(val) == 1 then
715 val
716 else
717 error '%c expected 1-sized string got: ' + std.length(val)
718 else
719 error '%c expected number / string, got: ' + std.type(val)
720 else
721 error 'Unknown code: ' + code.ctype;
722
723 // Render a parsed format string with an array of values.
724 local format_codes_arr(codes, arr, i, j, v) =
725 if i >= std.length(codes) then
726 if j < std.length(arr) then
727 error ('Too many values to format: ' + std.length(arr) + ', expected ' + j)
728 else
729 v
730 else
731 local code = codes[i];
732 if std.type(code) == 'string' then
733 format_codes_arr(codes, arr, i + 1, j, v + code) tailstrict
734 else
735 local tmp = if code.fw == '*' then {
736 j: j + 1,
737 fw: if j >= std.length(arr) then
738 error ('Not enough values to format: ' + std.length(arr) + ', expected at least ' + j)
739 else
740 arr[j],
741 } else {
742 j: j,
743 fw: code.fw,
744 };
745 local tmp2 = if code.prec == '*' then {
746 j: tmp.j + 1,
747 prec: if tmp.j >= std.length(arr) then
748 error ('Not enough values to format: ' + std.length(arr) + ', expected at least ' + tmp.j)
749 else
750 arr[tmp.j],
751 } else {
752 j: tmp.j,
753 prec: code.prec,
754 };
755 local j2 = tmp2.j;
756 local val =
757 if j2 < std.length(arr) then
758 arr[j2]
759 else
760 error ('Not enough values to format: ' + std.length(arr) + ', expected more than ' + j2);
761 local s =
762 if code.ctype == '%' then
763 '%'
764 else
765 format_code(val, code, tmp.fw, tmp2.prec, j2);
766 local s_padded =
767 if code.cflags.left then
768 pad_right(s, tmp.fw, ' ')
769 else
770 pad_left(s, tmp.fw, ' ');
771 local j3 =
772 if code.ctype == '%' then
773 j2
774 else
775 j2 + 1;
776 format_codes_arr(codes, arr, i + 1, j3, v + s_padded) tailstrict;
777
778 // Render a parsed format string with an object of values.
779 local format_codes_obj(codes, obj, i, v) =
780 if i >= std.length(codes) then
781 v
782 else
783 local code = codes[i];
784 if std.type(code) == 'string' then
785 format_codes_obj(codes, obj, i + 1, v + code) tailstrict
786 else
787 local f =
788 if code.mkey == null then
789 error 'Mapping keys required.'
790 else
791 code.mkey;
792 local fw =
793 if code.fw == '*' then
794 error 'Cannot use * field width with object.'
795 else
796 code.fw;
797 local prec =
798 if code.prec == '*' then
799 error 'Cannot use * precision with object.'
800 else
801 code.prec;
802 local val =
803 if std.objectHasAll(obj, f) then
804 obj[f]
805 else
806 error 'No such field: ' + f;
807 local s =
808 if code.ctype == '%' then
809 '%'
810 else
811 format_code(val, code, fw, prec, f);
812 local s_padded =
813 if code.cflags.left then
814 pad_right(s, fw, ' ')
815 else
816 pad_left(s, fw, ' ');
817 format_codes_obj(codes, obj, i + 1, v + s_padded) tailstrict;
818
819 if std.isArray(vals) then
820 format_codes_arr(codes, vals, 0, 0, '')
821 else if std.isObject(vals) then
822 format_codes_obj(codes, vals, 0, '')
823 else
824 format_codes_arr(codes, [vals], 0, 0, ''),
825
826 foldr(func, arr, init)::
827 local aux(func, arr, running, idx) =
828 if idx < 0 then
829 running
830 else
831 aux(func, arr, func(arr[idx], running), idx - 1) tailstrict;
832 aux(func, arr, init, std.length(arr) - 1),
833
834 foldl(func, arr, init)::
835 local aux(func, arr, running, idx) =
836 if idx >= std.length(arr) then
837 running
838 else
839 aux(func, arr, func(running, arr[idx]), idx + 1) tailstrict;
840 aux(func, arr, init, 0),
841
842
843 filterMap(filter_func, map_func, arr)::
844 if !std.isFunction(filter_func) then
845 error ('std.filterMap first param must be function, got ' + std.type(filter_func))
846 else if !std.isFunction(map_func) then
847 error ('std.filterMap second param must be function, got ' + std.type(map_func))
848 else if !std.isArray(arr) then
849 error ('std.filterMap third param must be array, got ' + std.type(arr))
850 else
851 std.map(map_func, std.filter(filter_func, arr)),
852
853 assertEqual(a, b)::
854 // If the values are strings, escape them for printing.
855 // If not, they'll be JSON-stringified anyway by the later string concatenation.
856 local astr = if std.type(a) == 'string' then std.escapeStringJson(a) else a;
857 local bstr = if std.type(b) == 'string' then std.escapeStringJson(b) else b;
858 if a == b then
859 true
860 else
861 error 'Assertion failed. ' + astr + ' != ' + bstr,
862
863 abs(n)::
864 if !std.isNumber(n) then
865 error 'std.abs expected number, got ' + std.type(n)
866 else
867 if n > 0 then n else -n,
868
869 sign(n)::
870 if !std.isNumber(n) then
871 error 'std.sign expected number, got ' + std.type(n)
872 else
873 if n > 0 then
874 1
875 else if n < 0 then
876 -1
877 else 0,
878
879 max(a, b)::
880 if !std.isNumber(a) then
881 error 'std.max first param expected number, got ' + std.type(a)
882 else if !std.isNumber(b) then
883 error 'std.max second param expected number, got ' + std.type(b)
884 else
885 if a > b then a else b,
886
887 min(a, b)::
888 if !std.isNumber(a) then
889 error 'std.min first param expected number, got ' + std.type(a)
890 else if !std.isNumber(b) then
891 error 'std.min second param expected number, got ' + std.type(b)
892 else
893 if a < b then a else b,
894
895 clamp(x, minVal, maxVal)::
896 if x < minVal then minVal
897 else if x > maxVal then maxVal
898 else x,
899
900 flattenArrays(arrs)::
901 std.foldl(function(a, b) a + b, arrs, []),
902
903 flattenDeepArray(value)::
904 if std.isArray(value) then
905 [y for x in value for y in std.flattenDeepArray(x)]
906 else
907 [value],
908
909 manifestIni(ini)::
910 local body_lines(body) =
911 std.join([], [
912 local value_or_values = body[k];
913 if std.isArray(value_or_values) then
914 ['%s = %s' % [k, value] for value in value_or_values]
915 else
916 ['%s = %s' % [k, value_or_values]]
917
918 for k in std.objectFields(body)
919 ]);
920
921 local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),
922 main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],
923 all_sections = [
924 section_lines(k, ini.sections[k])
925 for k in std.objectFields(ini.sections)
926 ];
927 std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),
928
929 manifestToml(value):: std.manifestTomlEx(value, ' '),
930
931 manifestTomlEx(value, indent)::
932 local
933 escapeStringToml = std.escapeStringJson,
934 escapeKeyToml(key) =
935 local bare_allowed = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'));
936 if std.setUnion(std.set(std.stringChars(key)), bare_allowed) == bare_allowed then key else escapeStringToml(key),
937 isTableArray(v) = std.isArray(v) && std.length(v) > 0 && std.all(std.map(std.isObject, v)),
938 isSection(v) = std.isObject(v) || isTableArray(v),
939 renderValue(v, indexedPath, inline, cindent) =
940 if v == true then
941 'true'
942 else if v == false then
943 'false'
944 else if v == null then
945 error 'Tried to manifest "null" at ' + indexedPath
946 else if std.isNumber(v) then
947 '' + v
948 else if std.isString(v) then
949 escapeStringToml(v)
950 else if std.isFunction(v) then
951 error 'Tried to manifest function at ' + indexedPath
952 else if std.isArray(v) then
953 if std.length(v) == 0 then
954 '[]'
955 else
956 local range = std.range(0, std.length(v) - 1);
957 local new_indent = if inline then '' else cindent + indent;
958 local separator = if inline then ' ' else '\n';
959 local lines = ['[' + separator]
960 + std.join([',' + separator],
961 [
962 [new_indent + renderValue(v[i], indexedPath + [i], true, '')]
963 for i in range
964 ])
965 + [separator + (if inline then '' else cindent) + ']'];
966 std.join('', lines)
967 else if std.isObject(v) then
968 local lines = ['{ ']
969 + std.join([', '],
970 [
971 [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]
972 for k in std.objectFields(v)
973 ])
974 + [' }'];
975 std.join('', lines),
976 renderTableInternal(v, path, indexedPath, cindent) =
977 local kvp = std.flattenArrays([
978 [cindent + escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], false, cindent)]
979 for k in std.objectFields(v)
980 if !isSection(v[k])
981 ]);
982 local sections = [std.join('\n', kvp)] + [
983 (
984 if std.isObject(v[k]) then
985 renderTable(v[k], path + [k], indexedPath + [k], cindent)
986 else
987 renderTableArray(v[k], path + [k], indexedPath + [k], cindent)
988 )
989 for k in std.objectFields(v)
990 if isSection(v[k])
991 ];
992 std.join('\n\n', sections),
993 renderTable(v, path, indexedPath, cindent) =
994 cindent + '[' + std.join('.', std.map(escapeKeyToml, path)) + ']'
995 + (if v == {} then '' else '\n')
996 + renderTableInternal(v, path, indexedPath, cindent + indent),
997 renderTableArray(v, path, indexedPath, cindent) =
998 local range = std.range(0, std.length(v) - 1);
999 local sections = [
1000 (cindent + '[[' + std.join('.', std.map(escapeKeyToml, path)) + ']]'
1001 + (if v[i] == {} then '' else '\n')
1002 + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))
1003 for i in range
1004 ];
1005 std.join('\n\n', sections);
1006 if std.isObject(value) then
1007 renderTableInternal(value, [], [], '')
1008 else
1009 error 'TOML body must be an object. Got ' + std.type(value),
1010
1011 escapeStringJson(str_)::
1012 local str = std.toString(str_);
1013 local trans(ch) =
1014 if ch == '"' then
1015 '\\"'
1016 else if ch == '\\' then
1017 '\\\\'
1018 else if ch == '\b' then
1019 '\\b'
1020 else if ch == '\f' then
1021 '\\f'
1022 else if ch == '\n' then
1023 '\\n'
1024 else if ch == '\r' then
1025 '\\r'
1026 else if ch == '\t' then
1027 '\\t'
1028 else
1029 local cp = std.codepoint(ch);
1030 if cp < 32 || (cp >= 127 && cp <= 159) then
1031 '\\u%04x' % [cp]
1032 else
1033 ch;
1034 '"%s"' % std.join('', [trans(ch) for ch in std.stringChars(str)]),
1035
1036 escapeStringPython(str)::
1037 std.escapeStringJson(str),
1038
1039 escapeStringBash(str_)::
1040 local str = std.toString(str_);
1041 "'%s'" % std.strReplace(str, "'", "'\"'\"'"),
1042
1043 escapeStringDollars(str_)::
1044 local str = std.toString(str_);
1045 std.strReplace(str, '$', '$$'),
1046
1047 local xml_escapes = {
1048 '<': '&lt;',
1049 '>': '&gt;',
1050 '&': '&amp;',
1051 '"': '&quot;',
1052 "'": '&apos;',
1053 },
1054
1055 escapeStringXML(str_)::
1056 local str = std.toString(str_);
1057 std.join('', [std.get(xml_escapes, ch, ch) for ch in std.stringChars(str)]),
1058
1059 manifestJson(value):: std.manifestJsonEx(value, ' '),
1060
1061 manifestJsonMinified(value):: std.manifestJsonEx(value, '', '', ':'),
1062
1063 manifestJsonEx(value, indent, newline='\n', key_val_sep=': ')::
1064 local aux(v, path, cindent) =
1065 if v == true then
1066 'true'
1067 else if v == false then
1068 'false'
1069 else if v == null then
1070 'null'
1071 else if std.isNumber(v) then
1072 '' + v
1073 else if std.isString(v) then
1074 std.escapeStringJson(v)
1075 else if std.isFunction(v) then
1076 error 'Tried to manifest function at ' + path
1077 else if std.isArray(v) then
1078 local range = std.range(0, std.length(v) - 1);
1079 local new_indent = cindent + indent;
1080 local lines = ['[' + newline]
1081 + std.join([',' + newline],
1082 [
1083 [new_indent + aux(v[i], path + [i], new_indent)]
1084 for i in range
1085 ])
1086 + [newline + cindent + ']'];
1087 std.join('', lines)
1088 else if std.isObject(v) then
1089 local lines = ['{' + newline]
1090 + std.join([',' + newline],
1091 [
1092 [cindent + indent + std.escapeStringJson(k) + key_val_sep
1093 + aux(v[k], path + [k], cindent + indent)]
1094 for k in std.objectFields(v)
1095 ])
1096 + [newline + cindent + '}'];
1097 std.join('', lines);
1098 aux(value, [], ''),
1099
1100 manifestYamlDoc(value, indent_array_in_object=false, quote_keys=true)::
1101 local onlyChars(charSet, strSet) =
1102 if std.length(std.setInter(charSet, strSet)) == std.length(strSet) then
1103 true
1104 else false;
1105 local isReserved(key) =
1106 // NOTE: These values are checked for case insensitively.
1107 // While this approach results in some false positives, it eliminates
1108 // the risk of missing a permutation.
1109 local reserved = [
1110 // Boolean types taken from https://yaml.org/type/bool.html
1111 'true',
1112 'false',
1113 'yes',
1114 'no',
1115 'on',
1116 'off',
1117 'y',
1118 'n',
1119 // Numerical words taken from https://yaml.org/type/float.html
1120 '.nan',
1121 '-.inf',
1122 '+.inf',
1123 '.inf',
1124 'null',
1125 // Invalid keys that contain no invalid characters
1126 '-',
1127 '---',
1128 '',
1129 ];
1130 local bad = [word for word in reserved if word == std.asciiLower(key)];
1131 if std.length(bad) > 0 then
1132 true
1133 else false;
1134 local typeMatch(m_key, type) =
1135 // Look for positive or negative numerical types (ex: 0x)
1136 if std.substr(m_key, 0, 2) == type || std.substr(m_key, 0, 3) == '-' + type then
1137 true
1138 else false;
1139 local bareSafe(key) =
1140 /*
1141 For a key to be considered safe to emit without quotes, the following must be true
1142 - All characters must match [a-zA-Z0-9_/\-]
1143 - Not match the integer format defined in https://yaml.org/type/int.html
1144 - Not match the float format defined in https://yaml.org/type/float.html
1145 - Not match the timestamp format defined in https://yaml.org/type/timestamp.html
1146 - Not match the boolean format defined in https://yaml.org/type/bool.html
1147 - Not match the null format defined in https://yaml.org/type/null.html
1148 - Not match (ignoring case) any reserved words which pass the above tests.
1149 Reserved words are defined in isReserved() above.
1150
1151 Since the remaining YAML types require characters outside the set chosen as valid
1152 for the elimination of quotes from the YAML output, the remaining types listed at
1153 https://yaml.org/type/ are by default always quoted.
1154 */
1155 local letters = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-/'));
1156 local digits = std.set(std.stringChars('0123456789'));
1157 local intChars = std.set(digits + std.stringChars('_-'));
1158 local binChars = std.set(intChars + std.stringChars('b'));
1159 local hexChars = std.set(digits + std.stringChars('abcdefx_-'));
1160 local floatChars = std.set(digits + std.stringChars('e._-'));
1161 local dateChars = std.set(digits + std.stringChars('-'));
1162 local safeChars = std.set(letters + floatChars);
1163 local keyLc = std.asciiLower(key);
1164 local keyChars = std.stringChars(key);
1165 local keySet = std.set(keyChars);
1166 local keySetLc = std.set(std.stringChars(keyLc));
1167 // Check for unsafe characters
1168 if !onlyChars(safeChars, keySet) then
1169 false
1170 // Check for reserved words
1171 else if isReserved(key) then
1172 false
1173 /* Check for timestamp values. Since spaces and colons are already forbidden,
1174 all that could potentially pass is the standard date format (ex MM-DD-YYYY, YYYY-DD-MM, etc).
1175 This check is even more conservative: Keys that meet all of the following:
1176 - all characters match [0-9\-]
1177 - has exactly 2 dashes
1178 are considered dates.
1179 */
1180 else if onlyChars(dateChars, keySet)
1181 && std.length(std.findSubstr('-', key)) == 2 then
1182 false
1183 /* Check for integers. Keys that meet all of the following:
1184 - all characters match [0-9_\-]
1185 - has at most 1 dash
1186 are considered integers.
1187 */
1188 else if onlyChars(intChars, keySetLc)
1189 && std.length(std.findSubstr('-', key)) < 2 then
1190 false
1191 /* Check for binary integers. Keys that meet all of the following:
1192 - all characters match [0-9b_\-]
1193 - has at least 3 characters
1194 - starts with (-)0b
1195 are considered binary integers.
1196 */
1197 else if onlyChars(binChars, keySetLc)
1198 && std.length(key) > 2
1199 && typeMatch(key, '0b') then
1200 false
1201 /* Check for floats. Keys that meet all of the following:
1202 - all characters match [0-9e._\-]
1203 - has at most a single period
1204 - has at most two dashes
1205 - has at most 1 'e'
1206 are considered floats.
1207 */
1208 else if onlyChars(floatChars, keySetLc)
1209 && std.length(std.findSubstr('.', key)) == 1
1210 && std.length(std.findSubstr('-', key)) < 3
1211 && std.length(std.findSubstr('e', keyLc)) < 2 then
1212 false
1213 /* Check for hexadecimals. Keys that meet all of the following:
1214 - all characters match [0-9a-fx_\-]
1215 - has at most 1 dash
1216 - has at least 3 characters
1217 - starts with (-)0x
1218 are considered hexadecimals.
1219 */
1220 else if onlyChars(hexChars, keySetLc)
1221 && std.length(std.findSubstr('-', key)) < 2
1222 && std.length(keyChars) > 2
1223 && typeMatch(key, '0x') then
1224 false
1225 // All checks pass. Key is safe for emission without quotes.
1226 else true;
1227 local escapeKeyYaml(key) =
1228 if bareSafe(key) then key else std.escapeStringJson(key);
1229 local aux(v, path, cindent) =
1230 if v == true then
1231 'true'
1232 else if v == false then
1233 'false'
1234 else if v == null then
1235 'null'
1236 else if std.isNumber(v) then
1237 '' + v
1238 else if std.isString(v) then
1239 local len = std.length(v);
1240 if len == 0 then
1241 '""'
1242 else if v[len - 1] == '\n' then
1243 local split = std.split(v, '\n');
1244 std.join('\n' + cindent + ' ', ['|'] + split[0:std.length(split) - 1])
1245 else
1246 std.escapeStringJson(v)
1247 else if std.isFunction(v) then
1248 error 'Tried to manifest function at ' + path
1249 else if std.isArray(v) then
1250 if std.length(v) == 0 then
1251 '[]'
1252 else
1253 local params(value) =
1254 if std.isArray(value) && std.length(value) > 0 then {
1255 // While we could avoid the new line, it yields YAML that is
1256 // hard to read, e.g.:
1257 // - - - 1
1258 // - 2
1259 // - - 3
1260 // - 4
1261 new_indent: cindent + ' ',
1262 space: '\n' + self.new_indent,
1263 } else if std.isObject(value) && std.length(value) > 0 then {
1264 new_indent: cindent + ' ',
1265 // In this case we can start on the same line as the - because the indentation
1266 // matches up then. The converse is not true, because fields are not always
1267 // 1 character long.
1268 space: ' ',
1269 } else {
1270 // In this case, new_indent is only used in the case of multi-line strings.
1271 new_indent: cindent,
1272 space: ' ',
1273 };
1274 local range = std.range(0, std.length(v) - 1);
1275 local parts = [
1276 '-' + param.space + aux(v[i], path + [i], param.new_indent)
1277 for i in range
1278 for param in [params(v[i])]
1279 ];
1280 std.join('\n' + cindent, parts)
1281 else if std.isObject(v) then
1282 if std.length(v) == 0 then
1283 '{}'
1284 else
1285 local params(value) =
1286 if std.isArray(value) && std.length(value) > 0 then {
1287 // Not indenting allows e.g.
1288 // ports:
1289 // - 80
1290 // instead of
1291 // ports:
1292 // - 80
1293 new_indent: if indent_array_in_object then cindent + ' ' else cindent,
1294 space: '\n' + self.new_indent,
1295 } else if std.isObject(value) && std.length(value) > 0 then {
1296 new_indent: cindent + ' ',
1297 space: '\n' + self.new_indent,
1298 } else {
1299 // In this case, new_indent is only used in the case of multi-line strings.
1300 new_indent: cindent,
1301 space: ' ',
1302 };
1303 local lines = [
1304 (if quote_keys then std.escapeStringJson(k) else escapeKeyYaml(k)) + ':' + param.space + aux(v[k], path + [k], param.new_indent)
1305 for k in std.objectFields(v)
1306 for param in [params(v[k])]
1307 ];
1308 std.join('\n' + cindent, lines);
1309 aux(value, [], ''),
1310
1311 manifestYamlStream(value, indent_array_in_object=false, c_document_end=true, quote_keys=true)::
1312 if !std.isArray(value) then
1313 error 'manifestYamlStream only takes arrays, got ' + std.type(value)
1314 else
1315 '---\n' + std.join(
1316 '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object, quote_keys) for e in value]
1317 ) + if c_document_end then '\n...\n' else '\n',
1318
1319
1320 manifestPython(v)::
1321 if std.isObject(v) then
1322 local fields = [
1323 '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]
1324 for k in std.objectFields(v)
1325 ];
1326 '{%s}' % [std.join(', ', fields)]
1327 else if std.isArray(v) then
1328 '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]
1329 else if std.isString(v) then
1330 '%s' % [std.escapeStringPython(v)]
1331 else if std.isFunction(v) then
1332 error 'cannot manifest function'
1333 else if std.isNumber(v) then
1334 std.toString(v)
1335 else if v == true then
1336 'True'
1337 else if v == false then
1338 'False'
1339 else if v == null then
1340 'None',
1341
1342 manifestPythonVars(conf)::
1343 local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];
1344 std.join('\n', vars + ['']),
1345
1346 manifestXmlJsonml(value)::
1347 if !std.isArray(value) then
1348 error 'Expected a JSONML value (an array), got %s' % std.type(value)
1349 else
1350 local aux(v) =
1351 if std.isString(v) then
1352 v
1353 else
1354 local tag = v[0];
1355 local has_attrs = std.length(v) > 1 && std.isObject(v[1]);
1356 local attrs = if has_attrs then v[1] else {};
1357 local children = if has_attrs then v[2:] else v[1:];
1358 local attrs_str =
1359 std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);
1360 std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);
1361
1362 aux(value),
1363
1364 local base64_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
1365 local base64_inv = { [base64_table[i]]: i for i in std.range(0, 63) },
1366
1367 base64(input)::
1368 local bytes =
1369 if std.isString(input) then
1370 std.map(std.codepoint, input)
1371 else
1372 input;
1373
1374 local aux(arr, i, r) =
1375 if i >= std.length(arr) then
1376 r
1377 else if i + 1 >= std.length(arr) then
1378 local str =
1379 // 6 MSB of i
1380 base64_table[(arr[i] & 252) >> 2] +
1381 // 2 LSB of i
1382 base64_table[(arr[i] & 3) << 4] +
1383 '==';
1384 aux(arr, i + 3, r + str) tailstrict
1385 else if i + 2 >= std.length(arr) then
1386 local str =
1387 // 6 MSB of i
1388 base64_table[(arr[i] & 252) >> 2] +
1389 // 2 LSB of i, 4 MSB of i+1
1390 base64_table[(arr[i] & 3) << 4 | (arr[i + 1] & 240) >> 4] +
1391 // 4 LSB of i+1
1392 base64_table[(arr[i + 1] & 15) << 2] +
1393 '=';
1394 aux(arr, i + 3, r + str) tailstrict
1395 else
1396 local str =
1397 // 6 MSB of i
1398 base64_table[(arr[i] & 252) >> 2] +
1399 // 2 LSB of i, 4 MSB of i+1
1400 base64_table[(arr[i] & 3) << 4 | (arr[i + 1] & 240) >> 4] +
1401 // 4 LSB of i+1, 2 MSB of i+2
1402 base64_table[(arr[i + 1] & 15) << 2 | (arr[i + 2] & 192) >> 6] +
1403 // 6 LSB of i+2
1404 base64_table[(arr[i + 2] & 63)];
1405 aux(arr, i + 3, r + str) tailstrict;
1406
1407 local sanity = std.all([a < 256 for a in bytes]);
1408 if !sanity then
1409 error 'Can only base64 encode strings / arrays of single bytes.'
1410 else
1411 aux(bytes, 0, ''),
1412
1413
1414 base64DecodeBytes(str)::
1415 if std.length(str) % 4 != 0 then
1416 error 'Not a base64 encoded string "%s"' % str
1417 else
1418 local aux(str, i, r) =
1419 if i >= std.length(str) then
1420 r
1421 else
1422 // all 6 bits of i, 2 MSB of i+1
1423 local n1 = [base64_inv[str[i]] << 2 | (base64_inv[str[i + 1]] >> 4)];
1424 // 4 LSB of i+1, 4MSB of i+2
1425 local n2 =
1426 if str[i + 2] == '=' then []
1427 else [(base64_inv[str[i + 1]] & 15) << 4 | (base64_inv[str[i + 2]] >> 2)];
1428 // 2 LSB of i+2, all 6 bits of i+3
1429 local n3 =
1430 if str[i + 3] == '=' then []
1431 else [(base64_inv[str[i + 2]] & 3) << 6 | base64_inv[str[i + 3]]];
1432 aux(str, i + 4, r + n1 + n2 + n3) tailstrict;
1433 aux(str, 0, []),
1434
1435 base64Decode(str)::
1436 local bytes = std.base64DecodeBytes(str);
1437 std.join('', std.map(std.char, bytes)),
1438
1439 reverse(arr)::
1440 local l = std.length(arr);
1441 std.makeArray(l, function(i) arr[l - i - 1]),
1442
1443 // Merge-sort for long arrays and naive quicksort for shorter ones
1444 sort(arr, keyF=id)::
1445 local quickSort(arr, keyF=id) =
1446 local l = std.length(arr);
1447 if std.length(arr) <= 1 then
1448 arr
1449 else
1450 local pos = 0;
1451 local pivot = keyF(arr[pos]);
1452 local rest = std.makeArray(l - 1, function(i) if i < pos then arr[i] else arr[i + 1]);
1453 local left = std.filter(function(x) keyF(x) < pivot, rest);
1454 local right = std.filter(function(x) keyF(x) >= pivot, rest);
1455 quickSort(left, keyF) + [arr[pos]] + quickSort(right, keyF);
1456
1457 local merge(a, b) =
1458 local la = std.length(a), lb = std.length(b);
1459 local aux(i, j, prefix) =
1460 if i == la then
1461 prefix + b[j:]
1462 else if j == lb then
1463 prefix + a[i:]
1464 else
1465 if keyF(a[i]) <= keyF(b[j]) then
1466 aux(i + 1, j, prefix + [a[i]]) tailstrict
1467 else
1468 aux(i, j + 1, prefix + [b[j]]) tailstrict;
1469 aux(0, 0, []);
1470
1471 local l = std.length(arr);
1472 if std.length(arr) <= 30 then
1473 quickSort(arr, keyF=keyF)
1474 else
1475 local mid = std.floor(l / 2);
1476 local left = arr[:mid], right = arr[mid:];
1477 merge(std.sort(left, keyF=keyF), std.sort(right, keyF=keyF)),
1478
1479 uniq(arr, keyF=id)::
1480 local f(a, b) =
1481 if std.length(a) == 0 then
1482 [b]
1483 else if keyF(a[std.length(a) - 1]) == keyF(b) then
1484 a
1485 else
1486 a + [b];
1487 std.foldl(f, arr, []),
1488
1489 set(arr, keyF=id)::
1490 std.uniq(std.sort(arr, keyF), keyF),
1491
1492 setMember(x, arr, keyF=id)::
1493 // TODO(dcunnin): Binary chop for O(log n) complexity
1494 std.length(std.setInter([x], arr, keyF)) > 0,
1495
1496 setUnion(a, b, keyF=id)::
1497 // NOTE: order matters, values in `a` win
1498 local aux(a, b, i, j, acc) =
1499 if i >= std.length(a) then
1500 acc + b[j:]
1501 else if j >= std.length(b) then
1502 acc + a[i:]
1503 else
1504 local ak = keyF(a[i]);
1505 local bk = keyF(b[j]);
1506 if ak == bk then
1507 aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict
1508 else if ak < bk then
1509 aux(a, b, i + 1, j, acc + [a[i]]) tailstrict
1510 else
1511 aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;
1512 aux(a, b, 0, 0, []),
1513
1514 setInter(a, b, keyF=id)::
1515 local aux(a, b, i, j, acc) =
1516 if i >= std.length(a) || j >= std.length(b) then
1517 acc
1518 else
1519 if keyF(a[i]) == keyF(b[j]) then
1520 aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict
1521 else if keyF(a[i]) < keyF(b[j]) then
1522 aux(a, b, i + 1, j, acc) tailstrict
1523 else
1524 aux(a, b, i, j + 1, acc) tailstrict;
1525 aux(a, b, 0, 0, []) tailstrict,
1526
1527 setDiff(a, b, keyF=id)::
1528 local aux(a, b, i, j, acc) =
1529 if i >= std.length(a) then
1530 acc
1531 else if j >= std.length(b) then
1532 acc + a[i:]
1533 else
1534 if keyF(a[i]) == keyF(b[j]) then
1535 aux(a, b, i + 1, j + 1, acc) tailstrict
1536 else if keyF(a[i]) < keyF(b[j]) then
1537 aux(a, b, i + 1, j, acc + [a[i]]) tailstrict
1538 else
1539 aux(a, b, i, j + 1, acc) tailstrict;
1540 aux(a, b, 0, 0, []) tailstrict,
1541
1542 mergePatch(target, patch)::
1543 if std.isObject(patch) then
1544 local target_object =
1545 if std.isObject(target) then target else {};
1546
1547 local target_fields =
1548 if std.isObject(target_object) then std.objectFields(target_object) else [];
1549
1550 local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];
1551 local both_fields = std.setUnion(target_fields, std.objectFields(patch));
1552
1553 {
1554 [k]:
1555 if !std.objectHas(patch, k) then
1556 target_object[k]
1557 else if !std.objectHas(target_object, k) then
1558 std.mergePatch(null, patch[k]) tailstrict
1559 else
1560 std.mergePatch(target_object[k], patch[k]) tailstrict
1561 for k in std.setDiff(both_fields, null_fields)
1562 }
1563 else
1564 patch,
1565
1566 get(o, f, default=null, inc_hidden=true)::
1567 if std.objectHasEx(o, f, inc_hidden) then o[f] else default,
1568
1569 objectFields(o)::
1570 std.objectFieldsEx(o, false),
1571
1572 objectFieldsAll(o)::
1573 std.objectFieldsEx(o, true),
1574
1575 objectHas(o, f)::
1576 std.objectHasEx(o, f, false),
1577
1578 objectHasAll(o, f)::
1579 std.objectHasEx(o, f, true),
1580
1581 objectValues(o)::
1582 [o[k] for k in std.objectFields(o)],
1583
1584 objectValuesAll(o)::
1585 [o[k] for k in std.objectFieldsAll(o)],
1586
1587 objectKeysValues(o)::
1588 [{ key: k, value: o[k] } for k in std.objectFields(o)],
1589
1590 objectKeysValuesAll(o)::
1591 [{ key: k, value: o[k] } for k in std.objectFieldsAll(o)],
1592
1593 equals(a, b)::
1594 local ta = std.type(a);
1595 local tb = std.type(b);
1596 if !std.primitiveEquals(ta, tb) then
1597 false
1598 else
1599 if std.primitiveEquals(ta, 'array') then
1600 local la = std.length(a);
1601 if !std.primitiveEquals(la, std.length(b)) then
1602 false
1603 else
1604 local aux(a, b, i) =
1605 if i >= la then
1606 true
1607 else if a[i] != b[i] then
1608 false
1609 else
1610 aux(a, b, i + 1) tailstrict;
1611 aux(a, b, 0)
1612 else if std.primitiveEquals(ta, 'object') then
1613 local fields = std.objectFields(a);
1614 local lfields = std.length(fields);
1615 if fields != std.objectFields(b) then
1616 false
1617 else
1618 local aux(a, b, i) =
1619 if i >= lfields then
1620 true
1621 else if local f = fields[i]; a[f] != b[f] then
1622 false
1623 else
1624 aux(a, b, i + 1) tailstrict;
1625 aux(a, b, 0)
1626 else
1627 std.primitiveEquals(a, b),
1628
1629
1630 resolvePath(f, r)::
1631 local arr = std.split(f, '/');
1632 std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),
1633
1634 prune(a)::
1635 local isContent(b) =
1636 if b == null then
1637 false
1638 else if std.isArray(b) then
1639 std.length(b) > 0
1640 else if std.isObject(b) then
1641 std.length(b) > 0
1642 else
1643 true;
1644 if std.isArray(a) then
1645 [std.prune(x) for x in a if isContent($.prune(x))]
1646 else if std.isObject(a) then {
1647 [x]: $.prune(a[x])
1648 for x in std.objectFields(a)
1649 if isContent(std.prune(a[x]))
1650 } else
1651 a,
1652
1653 findSubstr(pat, str)::
1654 if !std.isString(pat) then
1655 error 'findSubstr first parameter should be a string, got ' + std.type(pat)
1656 else if !std.isString(str) then
1657 error 'findSubstr second parameter should be a string, got ' + std.type(str)
1658 else
1659 local pat_len = std.length(pat);
1660 local str_len = std.length(str);
1661 if pat_len == 0 || str_len == 0 || pat_len > str_len then
1662 []
1663 else
1664 std.filter(function(i) str[i:i + pat_len] == pat, std.range(0, str_len - pat_len)),
1665
1666 find(value, arr)::
1667 if !std.isArray(arr) then
1668 error 'find second parameter should be an array, got ' + std.type(arr)
1669 else
1670 std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),
1671
1672 all(arr)::
1673 assert std.isArray(arr) : 'all() parameter should be an array, got ' + std.type(arr);
1674 local arrLen = std.length(arr);
1675 local aux(idx) =
1676 if idx >= arrLen then
1677 true
1678 else
1679 local e = arr[idx];
1680 assert std.isBoolean(e) : 'element "%s" of type %s is not a boolean' % [e, std.type(e)];
1681 if !e then
1682 false
1683 else
1684 aux(idx + 1) tailstrict;
1685 aux(0),
1686
1687 any(arr)::
1688 assert std.isArray(arr) : 'any() parameter should be an array, got ' + std.type(arr);
1689 local arrLen = std.length(arr);
1690 local aux(idx) =
1691 if idx >= arrLen then
1692 false
1693 else
1694 local e = arr[idx];
1695 assert std.isBoolean(e) : 'element "%s" of type %s is not a boolean' % [e, std.type(e)];
1696 if e then
1697 true
1698 else
1699 aux(idx + 1) tailstrict;
1700 aux(0),
1701
1702 // Three way comparison.
1703 // TODO(sbarzowski): consider exposing and documenting it properly
1704 __compare(v1, v2)::
1705 local t1 = std.type(v1), t2 = std.type(v2);
1706 if t1 != t2 then
1707 error 'Comparison requires matching types. Got ' + t1 + ' and ' + t2
1708 else if t1 == 'array' then
1709 std.__compare_array(v1, v2)
1710 else if t1 == 'function' || t1 == 'object' || t1 == 'boolean' then
1711 error 'Values of type ' + t1 + ' are not comparable.'
1712 else if v1 < v2 then -1
1713 else if v1 > v2 then 1
1714 else 0,
1715
1716 __compare_array(arr1, arr2)::
1717 local len1 = std.length(arr1), len2 = std.length(arr2);
1718 local minLen = std.min(len1, len2);
1719 local aux(i) =
1720 if i < minLen then
1721 local cmpRes = std.__compare(arr1[i], arr2[i]);
1722 if cmpRes != 0 then
1723 cmpRes
1724 else
1725 aux(i + 1) tailstrict
1726 else
1727 std.__compare(len1, len2);
1728 aux(0),
1729
1730 __array_less(arr1, arr2):: std.__compare_array(arr1, arr2) == -1,
1731 __array_greater(arr1, arr2):: std.__compare_array(arr1, arr2) == 1,
1732 __array_less_or_equal(arr1, arr2):: std.__compare_array(arr1, arr2) <= 0,
1733 __array_greater_or_equal(arr1, arr2):: std.__compare_array(arr1, arr2) >= 0,
1734
1735 sum(arr):: std.foldl(function(a, b) a + b, arr, 0),
1736
1737 avg(arr)::
1738 if std.length(arr) == 0 then
1739 error 'Cannot calculate average of an empty array.'
1740 else
1741 std.sum(arr)/std.length(arr),
1742
1743 minArray(arr, keyF=id, onEmpty=error 'Expected at least one element in array. Got none')::
1744 if std.length(arr) == 0 then
1745 onEmpty
1746 else
1747 local minVal = arr[0];
1748 local minFn(a, b) =
1749 if std.__compare(keyF(a), keyF(b)) > 0 then
1750 b
1751 else
1752 a;
1753 std.foldl(minFn, arr, minVal),
1754
1755 maxArray(arr, keyF=id, onEmpty=error 'Expected at least one element in array. Got none')::
1756 if std.length(arr) == 0 then
1757 onEmpty
1758 else
1759 local maxVal = arr[0];
1760 local maxFn(a, b) =
1761 if std.__compare(keyF(a), keyF(b)) < 0 then
1762 b
1763 else
1764 a;
1765 std.foldl(maxFn, arr, maxVal),
1766
1767 xor(x, y):: x != y,
1768
1769 xnor(x, y):: x == y,
1770
1771 round(x):: std.floor(x + 0.5),
1772
1773 isEmpty(str):: std.length(str) == 0,
1774
1775 contains(arr, elem):: std.any([e == elem for e in arr]),
1776
1777 equalsIgnoreCase(str1, str2):: std.asciiLower(str1) == std.asciiLower(str2),
1778
1779 isEven(x):: std.round(x) % 2 == 0,
1780 isOdd(x):: std.round(x) % 2 != 0,
1781 isInteger(x):: std.round(x) == x,
1782 isDecimal(x):: std.round(x) != x,
1783
1784 removeAt(arr, at):: [
1785 arr[i],
1786 for i in std.range(0, std.length(arr) - 1)
1787 if i != at
1788 ],
1789
1790 remove(arr, elem)::
1791 local indexes = std.find(elem, arr);
1792 if std.length(indexes) == 0
1793 then
1794 arr
1795 else
1796 std.removeAt(arr, indexes[0])
1797 ,
1798
1799 sha1(str):: go_only_function,
1800 sha256(str):: go_only_function,
1801 sha512(str):: go_only_function,
1802 sha3(str):: go_only_function,
1803
1804 trim(str):: std.stripChars(str, ' \t\n\f\r\u0085\u00A0'),
1805 }