git.delta.rocks / jrsonnet / refs/commits / df9bc99da41f

difftreelog

feat std.parseYaml intrinsic

Yaroslav Bolyukin2021-11-27parent: #7c0b097.patch.diff
in: master

6 files changed

modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -7,11 +7,9 @@
 edition = "2018"
 
 [features]
-default = ["serialized-stdlib", "explaining-traces", "serde-json"]
+default = ["serialized-stdlib", "explaining-traces"]
 # Serializes standard library AST instead of parsing them every run
-serialized-stdlib = ["serde", "bincode", "jrsonnet-parser/deserialize"]
-# Allow to convert Val into serde_json::Value and backwards
-serde-json = ["serde", "serde_json"]
+serialized-stdlib = ["bincode", "jrsonnet-parser/deserialize"]
 # Rustc-like trace visualization
 explaining-traces = ["annotate-snippets"]
 # Allows library authors to throw custom errors
@@ -34,21 +32,17 @@
 thiserror = "1.0"
 gcmodule = { git = "https://github.com/CertainLach/gcmodule", branch = "jrsonnet" }
 
+serde = "1.0"
+serde_json = "1.0"
+serde_yaml = { git = "https://github.com/CertainLach/serde-yaml", branch = "feature/old-octals-quirk" }
+
 [dependencies.anyhow]
 version = "1.0"
 optional = true
 
 # Serialized stdlib
-[dependencies.serde]
-version = "1.0"
-optional = true
 [dependencies.bincode]
 version = "1.3.1"
-optional = true
-
-# Serde json
-[dependencies.serde_json]
-version = "1.0"
 optional = true
 
 # Explaining traces
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -3,15 +3,17 @@
 	equals,
 	error::{Error::*, Result},
 	operator::evaluate_mod_op,
-	parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context,
-	EvaluationState, FuncVal, IndexableVal, LazyVal, Val,
+	parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,
+	IndexableVal, LazyVal, Val,
 };
 use format::{format_arr, format_obj};
 use gcmodule::Cc;
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{ArgsDesc, ExprLocation};
 use jrsonnet_types::ty;
-use std::{collections::HashMap, path::PathBuf, rc::Rc};
+use serde::Deserialize;
+use serde_yaml::DeserializingQuirks;
+use std::{collections::HashMap, convert::TryFrom, path::PathBuf, rc::Rc};
 
 pub mod stdlib;
 pub use stdlib::*;
@@ -128,6 +130,7 @@
 			("strReplace".into(), builtin_str_replace),
 			("splitLimit".into(), builtin_splitlimit),
 			("parseJson".into(), builtin_parse_json),
+			("parseYaml".into(), builtin_parse_yaml),
 			("asciiUpper".into(), builtin_ascii_upper),
 			("asciiLower".into(), builtin_ascii_lower),
 			("member".into(), builtin_member),
@@ -210,9 +213,30 @@
 	parse_args!(context, "parseJson", args, 1, [
 		0, s: ty!(string) => Val::Str;
 	], {
-		let state = EvaluationState::default();
-		let path = PathBuf::from("std.parseJson").into();
-		state.evaluate_snippet_raw(path ,s)
+		let value: serde_json::Value = serde_json::from_str(&s).map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
+		Ok(Val::try_from(&value)?)
+	})
+}
+
+fn builtin_parse_yaml(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
+	parse_args!(context, "parseYaml", args, 1, [
+		0, s: ty!(string) => Val::Str;
+	], {
+		let value = serde_yaml::Deserializer::from_str_with_quirks(&s, DeserializingQuirks { old_octals: true });
+		let mut out = vec![];
+		for item in value {
+			let value = serde_json::Value::deserialize(item)
+				.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
+			let val = Val::try_from(&value)?;
+			out.push(val);
+		}
+		if out.is_empty() {
+			Ok(Val::Null)
+		} else if out.len() == 1 {
+			Ok(out.into_iter().next().unwrap())
+		} else {
+			Ok(Val::Arr(out.into()))
+		}
 	})
 }
 
modifiedcrates/jrsonnet-evaluator/src/integrations/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/mod.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/mod.rs
@@ -1,2 +1 @@
-#[cfg(feature = "serde-json")]
 pub mod serde;
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -15,7 +15,7 @@
 			Val::Num(n) => Self::Number(if n.fract() <= f64::EPSILON {
 				(*n as i64).into()
 			} else {
-				Number::from_f64(*n).expect("to json number")
+				Number::from_f64(*n).expect("jsonnet numbers can't be infinite or NaN")
 			}),
 			Val::Arr(a) => {
 				let mut out = Vec::with_capacity(a.len());
@@ -29,7 +29,9 @@
 				for key in o.fields() {
 					out.insert(
 						(&key as &str).into(),
-						(&o.get(key)?.expect("field exists")).try_into()?,
+						(&o.get(key)?
+							.expect("key is present in fields, so value should exist"))
+							.try_into()?,
 					);
 				}
 				Self::Object(out)
@@ -39,27 +41,30 @@
 	}
 }
 
-impl From<&Value> for Val {
-	fn from(v: &Value) -> Self {
-		match v {
+impl TryFrom<&Value> for Val {
+	type Error = LocError;
+	fn try_from(v: &Value) -> Result<Self> {
+		Ok(match v {
 			Value::Null => Self::Null,
 			Value::Bool(v) => Self::Bool(*v),
-			Value::Number(n) => Self::Num(n.as_f64().expect("as f64")),
+			Value::Number(n) => Self::Num(n.as_f64().ok_or_else(|| {
+				RuntimeError(format!("json number can't be represented as jsonnet: {}", n).into())
+			})?),
 			Value::String(s) => Self::Str((s as &str).into()),
 			Value::Array(a) => {
 				let mut out: Vec<Self> = Vec::with_capacity(a.len());
 				for v in a {
-					out.push(v.into());
+					out.push(v.try_into()?);
 				}
 				Self::Arr(out.into())
 			}
 			Value::Object(o) => {
 				let mut builder = ObjValueBuilder::with_capacity(o.len());
 				for (k, v) in o {
-					builder.member((k as &str).into()).value(v.into());
+					builder.member((k as &str).into()).value(v.try_into()?);
 				}
 				Self::Obj(builder.build())
 			}
-		}
+		})
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -98,7 +98,7 @@
 			let mut n = self.resolver.resolve(path);
 			let mut offset = error.location.offset;
 			let is_eof = if offset >= source_code.len() {
-				offset = source_code.len() - 1;
+				offset = source_code.len().saturating_sub(1);
 				true
 			} else {
 				false
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/std.jsonnet
1{2  local std = self,3  local id = std.id,45  # Those functions aren't normally located in stdlib6  length:: $intrinsic(length),7  type:: $intrinsic(type),8  makeArray:: $intrinsic(makeArray),9  codepoint:: $intrinsic(codepoint),10  objectFieldsEx:: $intrinsic(objectFieldsEx),11  objectHasEx:: $intrinsic(objectHasEx),12  primitiveEquals:: $intrinsic(primitiveEquals),13  modulo:: $intrinsic(modulo),14  floor:: $intrinsic(floor),15  ceil:: $intrinsic(ceil),16  extVar:: $intrinsic(extVar),17  native:: $intrinsic(native),18  filter:: $intrinsic(filter),19  char:: $intrinsic(char),20  encodeUTF8:: $intrinsic(encodeUTF8),21  decodeUTF8:: $intrinsic(decodeUTF8),22  md5:: $intrinsic(md5),23  trace:: $intrinsic(trace),24  id:: $intrinsic(id),25  parseJson:: $intrinsic(parseJson),2627  log:: $intrinsic(log),28  pow:: $intrinsic(pow),29  sqrt:: $intrinsic(sqrt),3031  sin:: $intrinsic(sin),32  cos:: $intrinsic(cos),33  tan:: $intrinsic(tan),34  asin:: $intrinsic(asin),35  acos:: $intrinsic(acos),36  atan:: $intrinsic(atan),3738  exp:: $intrinsic(exp),39  mantissa:: $intrinsic(mantissa),40  exponent:: $intrinsic(exponent),4142  isString(v):: std.type(v) == 'string',43  isNumber(v):: std.type(v) == 'number',44  isBoolean(v):: std.type(v) == 'boolean',45  isObject(v):: std.type(v) == 'object',46  isArray(v):: std.type(v) == 'array',47  isFunction(v):: std.type(v) == 'function',4849  toString(a)::50    if std.type(a) == 'string' then a else '' + a,5152  substr:: $intrinsic(substr),5354  startsWith(a, b)::55    if std.length(a) < std.length(b) then56      false57    else58      std.substr(a, 0, std.length(b)) == b,5960  endsWith(a, b)::61    if std.length(a) < std.length(b) then62      false63    else64      std.substr(a, std.length(a) - std.length(b), std.length(b)) == b,6566  lstripChars(str, chars)::67    if std.length(str) > 0 && std.member(chars, str[0]) then68      std.lstripChars(str[1:], chars)69    else70      str,7172  rstripChars(str, chars)::73    local len = std.length(str);74    if len > 0 && std.member(chars, str[len - 1]) then75      std.rstripChars(str[:len - 1], chars)76    else77      str,7879  stripChars(str, chars)::80    std.lstripChars(std.rstripChars(str, chars), chars),8182  stringChars(str)::83    std.makeArray(std.length(str), function(i) str[i]),8485  local parse_nat(str, base) =86    assert base > 0 && base <= 16 : 'integer base %d invalid' % base;87    // These codepoints are in ascending order:88    local zero_code = std.codepoint('0');89    local upper_a_code = std.codepoint('A');90    local lower_a_code = std.codepoint('a');91    local addDigit(aggregate, char) =92      local code = std.codepoint(char);93      local digit = if code >= lower_a_code then94        code - lower_a_code + 1095      else if code >= upper_a_code then96        code - upper_a_code + 1097      else98        code - zero_code;99      assert digit >= 0 && digit < base : '%s is not a base %d integer' % [str, base];100      base * aggregate + digit;101    std.foldl(addDigit, std.stringChars(str), 0),102103  parseInt(str)::104    assert std.isString(str) : 'Expected string, got ' + std.type(str);105    assert std.length(str) > 0 && str != '-' : 'Not an integer: "%s"' % [str];106    if str[0] == '-' then107      -parse_nat(str[1:], 10)108    else109      parse_nat(str, 10),110111  parseOctal(str)::112    assert std.isString(str) : 'Expected string, got ' + std.type(str);113    assert std.length(str) > 0 : 'Not an octal number: ""';114    parse_nat(str, 8),115116  parseHex(str)::117    assert std.isString(str) : 'Expected string, got ' + std.type(str);118    assert std.length(str) > 0 : 'Not hexadecimal: ""';119    parse_nat(str, 16),120121  split(str, c)::122    assert std.isString(str) : 'std.split first parameter should be a string, got ' + std.type(str);123    assert std.isString(c) : 'std.split second parameter should be a string, got ' + std.type(c);124    assert std.length(c) == 1 : 'std.split second parameter should have length 1, got ' + std.length(c);125    std.splitLimit(str, c, -1),126127  splitLimit:: $intrinsic(splitLimit),128129  strReplace:: $intrinsic(strReplace),130131  asciiUpper:: $intrinsic(asciiUpper),132133  asciiLower:: $intrinsic(asciiLower),134135  range:: $intrinsic(range),136137  repeat(what, count)::138    local joiner =139      if std.isString(what) then ''140      else if std.isArray(what) then []141      else error 'std.repeat first argument must be an array or a string';142    std.join(joiner, std.makeArray(count, function(i) what)),143144  slice:: $intrinsic(slice),145146  member:: $intrinsic(member),147148  count:: $intrinsic(count),149150  mod:: $intrinsic(mod),151152  map:: $intrinsic(map),153154  mapWithIndex(func, arr)::155    if !std.isFunction(func) then156      error ('std.mapWithIndex first param must be function, got ' + std.type(func))157    else if !std.isArray(arr) && !std.isString(arr) then158      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))159    else160      std.makeArray(std.length(arr), function(i) func(i, arr[i])),161162  mapWithKey(func, obj)::163    if !std.isFunction(func) then164      error ('std.mapWithKey first param must be function, got ' + std.type(func))165    else if !std.isObject(obj) then166      error ('std.mapWithKey second param must be object, got ' + std.type(obj))167    else168      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },169170  flatMap:: $intrinsic(flatMap),171172  join:: $intrinsic(join),173174  lines(arr)::175    std.join('\n', arr + ['']),176177  deepJoin(arr)::178    if std.isString(arr) then179      arr180    else if std.isArray(arr) then181      std.join('', [std.deepJoin(x) for x in arr])182    else183      error 'Expected string or array, got %s' % std.type(arr),184185186  format:: $intrinsic(format),187188  foldr:: $intrinsic(foldr),189190  foldl:: $intrinsic(foldl),191192  filterMap(filter_func, map_func, arr)::193    if !std.isFunction(filter_func) then194      error ('std.filterMap first param must be function, got ' + std.type(filter_func))195    else if !std.isFunction(map_func) then196      error ('std.filterMap second param must be function, got ' + std.type(map_func))197    else if !std.isArray(arr) then198      error ('std.filterMap third param must be array, got ' + std.type(arr))199    else200      std.map(map_func, std.filter(filter_func, arr)),201202  assertEqual(a, b)::203    if a == b then204      true205    else206      error 'Assertion failed. ' + a + ' != ' + b,207208  abs(n)::209    if !std.isNumber(n) then210      error 'std.abs expected number, got ' + std.type(n)211    else212      if n > 0 then n else -n,213214  sign(n)::215    if !std.isNumber(n) then216      error 'std.sign expected number, got ' + std.type(n)217    else218      if n > 0 then219        1220      else if n < 0 then221        -1222      else 0,223224  max(a, b)::225    if !std.isNumber(a) then226      error 'std.max first param expected number, got ' + std.type(a)227    else if !std.isNumber(b) then228      error 'std.max second param expected number, got ' + std.type(b)229    else230      if a > b then a else b,231232  min(a, b)::233    if !std.isNumber(a) then234      error 'std.min first param expected number, got ' + std.type(a)235    else if !std.isNumber(b) then236      error 'std.min second param expected number, got ' + std.type(b)237    else238      if a < b then a else b,239240  clamp(x, minVal, maxVal)::241    if x < minVal then minVal242    else if x > maxVal then maxVal243    else x,244245  flattenArrays(arrs)::246    std.foldl(function(a, b) a + b, arrs, []),247248  manifestIni(ini)::249    local body_lines(body) =250      std.join([], [251        local value_or_values = body[k];252        if std.isArray(value_or_values) then253          ['%s = %s' % [k, value] for value in value_or_values]254        else255          ['%s = %s' % [k, value_or_values]]256257        for k in std.objectFields(body)258      ]);259260    local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),261          main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],262          all_sections = [263      section_lines(k, ini.sections[k])264      for k in std.objectFields(ini.sections)265    ];266    std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),267268  manifestToml(value):: std.manifestTomlEx(value, '  '),269270  manifestTomlEx(value, indent)::271    local272      escapeStringToml = std.escapeStringJson,273      escapeKeyToml(key) =274        local bare_allowed = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'));275        if std.setUnion(std.set(std.stringChars(key)), bare_allowed) == bare_allowed then key else escapeStringToml(key),276      isTableArray(v) = std.isArray(v) && std.length(v) > 0 && std.foldl(function(a, b) a && std.isObject(b), v, true),277      isSection(v) = std.isObject(v) || isTableArray(v),278      renderValue(v, indexedPath, inline, cindent) =279        if v == true then280          'true'281        else if v == false then282          'false'283        else if v == null then284          error 'Tried to manifest "null" at ' + indexedPath285        else if std.isNumber(v) then286          '' + v287        else if std.isString(v) then288          escapeStringToml(v)289        else if std.isFunction(v) then290          error 'Tried to manifest function at ' + indexedPath291        else if std.isArray(v) then292          if std.length(v) == 0 then293            '[]'294          else295            local range = std.range(0, std.length(v) - 1);296            local new_indent = if inline then '' else cindent + indent;297            local separator = if inline then ' ' else '\n';298            local lines = ['[' + separator]299                          + std.join([',' + separator],300                                     [301                                       [new_indent + renderValue(v[i], indexedPath + [i], true, '')]302                                       for i in range303                                     ])304                          + [separator + (if inline then '' else cindent) + ']'];305            std.join('', lines)306        else if std.isObject(v) then307          local lines = ['{ ']308                        + std.join([', '],309                                   [310                                     [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]311                                     for k in std.objectFields(v)312                                   ])313                        + [' }'];314          std.join('', lines),315      renderTableInternal(v, path, indexedPath, cindent) =316        local kvp = std.flattenArrays([317          [cindent + escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], false, cindent)]318          for k in std.objectFields(v)319          if !isSection(v[k])320        ]);321        local sections = [std.join('\n', kvp)] + [322          (323            if std.isObject(v[k]) then324              renderTable(v[k], path + [k], indexedPath + [k], cindent)325            else326              renderTableArray(v[k], path + [k], indexedPath + [k], cindent)327          )328          for k in std.objectFields(v)329          if isSection(v[k])330        ];331        std.join('\n\n', sections),332      renderTable(v, path, indexedPath, cindent) =333        cindent + '[' + std.join('.', std.map(escapeKeyToml, path)) + ']'334        + (if v == {} then '' else '\n')335        + renderTableInternal(v, path, indexedPath, cindent + indent),336      renderTableArray(v, path, indexedPath, cindent) =337        local range = std.range(0, std.length(v) - 1);338        local sections = [339          (cindent + '[[' + std.join('.', std.map(escapeKeyToml, path)) + ']]'340           + (if v[i] == {} then '' else '\n')341           + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))342          for i in range343        ];344        std.join('\n\n', sections);345    if std.isObject(value) then346      renderTableInternal(value, [], [], '')347    else348      error 'TOML body must be an object. Got ' + std.type(value),349350  escapeStringJson:: $intrinsic(escapeStringJson),351352  escapeStringPython(str)::353    std.escapeStringJson(str),354355  escapeStringBash(str_)::356    local str = std.toString(str_);357    local trans(ch) =358      if ch == "'" then359        "'\"'\"'"360      else361        ch;362    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),363364  escapeStringDollars(str_)::365    local str = std.toString(str_);366    local trans(ch) =367      if ch == '$' then368        '$$'369      else370        ch;371    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),372373  manifestJson(value):: std.manifestJsonEx(value, '    ') tailstrict,374375  manifestJsonEx:: $intrinsic(manifestJsonEx),376377  manifestYamlDocImpl:: $intrinsic(manifestYamlDocImpl),378379  manifestYamlDoc(value, indent_array_in_object=false):: std.manifestYamlDocImpl(value, indent_array_in_object),380381  manifestYamlStream(value, indent_array_in_object=false, c_document_end=true)::382    if !std.isArray(value) then383      error 'manifestYamlStream only takes arrays, got ' + std.type(value)384    else385      '---\n' + std.join(386        '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object) for e in value]387      ) + if c_document_end then '\n...\n' else '\n',388389390  manifestPython(v)::391    if std.isObject(v) then392      local fields = [393        '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]394        for k in std.objectFields(v)395      ];396      '{%s}' % [std.join(', ', fields)]397    else if std.isArray(v) then398      '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]399    else if std.isString(v) then400      '%s' % [std.escapeStringPython(v)]401    else if std.isFunction(v) then402      error 'cannot manifest function'403    else if std.isNumber(v) then404      std.toString(v)405    else if v == true then406      'True'407    else if v == false then408      'False'409    else if v == null then410      'None',411412  manifestPythonVars(conf)::413    local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];414    std.join('\n', vars + ['']),415416  manifestXmlJsonml(value)::417    if !std.isArray(value) then418      error 'Expected a JSONML value (an array), got %s' % std.type(value)419    else420      local aux(v) =421        if std.isString(v) then422          v423        else424          local tag = v[0];425          local has_attrs = std.length(v) > 1 && std.isObject(v[1]);426          local attrs = if has_attrs then v[1] else {};427          local children = if has_attrs then v[2:] else v[1:];428          local attrs_str =429            std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);430          std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);431432      aux(value),433434  local base64_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',435  local base64_inv = { [base64_table[i]]: i for i in std.range(0, 63) },436437  base64:: $intrinsic(base64),438439  base64DecodeBytes:: $intrinsic(base64DecodeBytes),440441  base64Decode:: $intrinsic(base64Decode),442443  reverse:: $intrinsic(reverse),444445  sortImpl:: $intrinsic(sortImpl),446447  sort(arr, keyF=id)::448    std.sortImpl(arr, keyF),449450  uniq(arr, keyF=id)::451    local f(a, b) =452      if std.length(a) == 0 then453        [b]454      else if keyF(a[std.length(a) - 1]) == keyF(b) then455        a456      else457        a + [b];458    std.foldl(f, arr, []),459460  set(arr, keyF=id)::461    std.uniq(std.sort(arr, keyF), keyF),462463  setMember(x, arr, keyF=id)::464    // TODO(dcunnin): Binary chop for O(log n) complexity465    std.length(std.setInter([x], arr, keyF)) > 0,466467  setUnion(a, b, keyF=id)::468    // NOTE: order matters, values in `a` win469    local aux(a, b, i, j, acc) =470      if i >= std.length(a) then471        acc + b[j:]472      else if j >= std.length(b) then473        acc + a[i:]474      else475        local ak = keyF(a[i]);476        local bk = keyF(b[j]);477        if ak == bk then478          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict479        else if ak < bk then480          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict481        else482          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;483    aux(a, b, 0, 0, []),484485  setInter(a, b, keyF=id)::486    local aux(a, b, i, j, acc) =487      if i >= std.length(a) || j >= std.length(b) then488        acc489      else490        if keyF(a[i]) == keyF(b[j]) then491          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict492        else if keyF(a[i]) < keyF(b[j]) then493          aux(a, b, i + 1, j, acc) tailstrict494        else495          aux(a, b, i, j + 1, acc) tailstrict;496    aux(a, b, 0, 0, []) tailstrict,497498  setDiff(a, b, keyF=id)::499    local aux(a, b, i, j, acc) =500      if i >= std.length(a) then501        acc502      else if j >= std.length(b) then503        acc + a[i:]504      else505        if keyF(a[i]) == keyF(b[j]) then506          aux(a, b, i + 1, j + 1, acc) tailstrict507        else if keyF(a[i]) < keyF(b[j]) then508          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict509        else510          aux(a, b, i, j + 1, acc) tailstrict;511    aux(a, b, 0, 0, []) tailstrict,512513  mergePatch(target, patch)::514    if std.isObject(patch) then515      local target_object =516        if std.isObject(target) then target else {};517518      local target_fields =519        if std.isObject(target_object) then std.objectFields(target_object) else [];520521      local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];522      local both_fields = std.setUnion(target_fields, std.objectFields(patch));523524      {525        [k]:526          if !std.objectHas(patch, k) then527            target_object[k]528          else if !std.objectHas(target_object, k) then529            std.mergePatch(null, patch[k]) tailstrict530          else531            std.mergePatch(target_object[k], patch[k]) tailstrict532        for k in std.setDiff(both_fields, null_fields)533      }534    else535      patch,536537  objectFields(o)::538    std.objectFieldsEx(o, false),539540  objectFieldsAll(o)::541    std.objectFieldsEx(o, true),542543  objectHas(o, f)::544    std.objectHasEx(o, f, false),545546  objectHasAll(o, f)::547    std.objectHasEx(o, f, true),548549  objectValues(o)::550    [o[k] for k in std.objectFields(o)],551552  objectValuesAll(o)::553    [o[k] for k in std.objectFieldsAll(o)],554555  equals:: $intrinsic(equals),556557  resolvePath(f, r)::558    local arr = std.split(f, '/');559    std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),560561  prune(a)::562    local isContent(b) =563      if b == null then564        false565      else if std.isArray(b) then566        std.length(b) > 0567      else if std.isObject(b) then568        std.length(b) > 0569      else570        true;571    if std.isArray(a) then572      [std.prune(x) for x in a if isContent($.prune(x))]573    else if std.isObject(a) then {574      [x]: $.prune(a[x])575      for x in std.objectFields(a)576      if isContent(std.prune(a[x]))577    } else578      a,579580  findSubstr(pat, str)::581    if !std.isString(pat) then582      error 'findSubstr first parameter should be a string, got ' + std.type(pat)583    else if !std.isString(str) then584      error 'findSubstr second parameter should be a string, got ' + std.type(str)585    else586      local pat_len = std.length(pat);587      local str_len = std.length(str);588      if pat_len == 0 || str_len == 0 || pat_len > str_len then589        []590      else591        std.filter(function(i) str[i:i + pat_len] == pat, std.range(0, str_len - pat_len)),592593  find(value, arr)::594    if !std.isArray(arr) then595      error 'find second parameter should be an array, got ' + std.type(arr)596    else597      std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),598}
after · crates/jrsonnet-stdlib/src/std.jsonnet
1{2  local std = self,3  local id = std.id,45  # Those functions aren't normally located in stdlib6  length:: $intrinsic(length),7  type:: $intrinsic(type),8  makeArray:: $intrinsic(makeArray),9  codepoint:: $intrinsic(codepoint),10  objectFieldsEx:: $intrinsic(objectFieldsEx),11  objectHasEx:: $intrinsic(objectHasEx),12  primitiveEquals:: $intrinsic(primitiveEquals),13  modulo:: $intrinsic(modulo),14  floor:: $intrinsic(floor),15  ceil:: $intrinsic(ceil),16  extVar:: $intrinsic(extVar),17  native:: $intrinsic(native),18  filter:: $intrinsic(filter),19  char:: $intrinsic(char),20  encodeUTF8:: $intrinsic(encodeUTF8),21  decodeUTF8:: $intrinsic(decodeUTF8),22  md5:: $intrinsic(md5),23  trace:: $intrinsic(trace),24  id:: $intrinsic(id),25  parseJson:: $intrinsic(parseJson),26  parseYaml:: $intrinsic(parseYaml),2728  log:: $intrinsic(log),29  pow:: $intrinsic(pow),30  sqrt:: $intrinsic(sqrt),3132  sin:: $intrinsic(sin),33  cos:: $intrinsic(cos),34  tan:: $intrinsic(tan),35  asin:: $intrinsic(asin),36  acos:: $intrinsic(acos),37  atan:: $intrinsic(atan),3839  exp:: $intrinsic(exp),40  mantissa:: $intrinsic(mantissa),41  exponent:: $intrinsic(exponent),4243  isString(v):: std.type(v) == 'string',44  isNumber(v):: std.type(v) == 'number',45  isBoolean(v):: std.type(v) == 'boolean',46  isObject(v):: std.type(v) == 'object',47  isArray(v):: std.type(v) == 'array',48  isFunction(v):: std.type(v) == 'function',4950  toString(a)::51    if std.type(a) == 'string' then a else '' + a,5253  substr:: $intrinsic(substr),5455  startsWith(a, b)::56    if std.length(a) < std.length(b) then57      false58    else59      std.substr(a, 0, std.length(b)) == b,6061  endsWith(a, b)::62    if std.length(a) < std.length(b) then63      false64    else65      std.substr(a, std.length(a) - std.length(b), std.length(b)) == b,6667  lstripChars(str, chars)::68    if std.length(str) > 0 && std.member(chars, str[0]) then69      std.lstripChars(str[1:], chars)70    else71      str,7273  rstripChars(str, chars)::74    local len = std.length(str);75    if len > 0 && std.member(chars, str[len - 1]) then76      std.rstripChars(str[:len - 1], chars)77    else78      str,7980  stripChars(str, chars)::81    std.lstripChars(std.rstripChars(str, chars), chars),8283  stringChars(str)::84    std.makeArray(std.length(str), function(i) str[i]),8586  local parse_nat(str, base) =87    assert base > 0 && base <= 16 : 'integer base %d invalid' % base;88    // These codepoints are in ascending order:89    local zero_code = std.codepoint('0');90    local upper_a_code = std.codepoint('A');91    local lower_a_code = std.codepoint('a');92    local addDigit(aggregate, char) =93      local code = std.codepoint(char);94      local digit = if code >= lower_a_code then95        code - lower_a_code + 1096      else if code >= upper_a_code then97        code - upper_a_code + 1098      else99        code - zero_code;100      assert digit >= 0 && digit < base : '%s is not a base %d integer' % [str, base];101      base * aggregate + digit;102    std.foldl(addDigit, std.stringChars(str), 0),103104  parseInt(str)::105    assert std.isString(str) : 'Expected string, got ' + std.type(str);106    assert std.length(str) > 0 && str != '-' : 'Not an integer: "%s"' % [str];107    if str[0] == '-' then108      -parse_nat(str[1:], 10)109    else110      parse_nat(str, 10),111112  parseOctal(str)::113    assert std.isString(str) : 'Expected string, got ' + std.type(str);114    assert std.length(str) > 0 : 'Not an octal number: ""';115    parse_nat(str, 8),116117  parseHex(str)::118    assert std.isString(str) : 'Expected string, got ' + std.type(str);119    assert std.length(str) > 0 : 'Not hexadecimal: ""';120    parse_nat(str, 16),121122  split(str, c)::123    assert std.isString(str) : 'std.split first parameter should be a string, got ' + std.type(str);124    assert std.isString(c) : 'std.split second parameter should be a string, got ' + std.type(c);125    assert std.length(c) == 1 : 'std.split second parameter should have length 1, got ' + std.length(c);126    std.splitLimit(str, c, -1),127128  splitLimit:: $intrinsic(splitLimit),129130  strReplace:: $intrinsic(strReplace),131132  asciiUpper:: $intrinsic(asciiUpper),133134  asciiLower:: $intrinsic(asciiLower),135136  range:: $intrinsic(range),137138  repeat(what, count)::139    local joiner =140      if std.isString(what) then ''141      else if std.isArray(what) then []142      else error 'std.repeat first argument must be an array or a string';143    std.join(joiner, std.makeArray(count, function(i) what)),144145  slice:: $intrinsic(slice),146147  member:: $intrinsic(member),148149  count:: $intrinsic(count),150151  mod:: $intrinsic(mod),152153  map:: $intrinsic(map),154155  mapWithIndex(func, arr)::156    if !std.isFunction(func) then157      error ('std.mapWithIndex first param must be function, got ' + std.type(func))158    else if !std.isArray(arr) && !std.isString(arr) then159      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))160    else161      std.makeArray(std.length(arr), function(i) func(i, arr[i])),162163  mapWithKey(func, obj)::164    if !std.isFunction(func) then165      error ('std.mapWithKey first param must be function, got ' + std.type(func))166    else if !std.isObject(obj) then167      error ('std.mapWithKey second param must be object, got ' + std.type(obj))168    else169      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },170171  flatMap:: $intrinsic(flatMap),172173  join:: $intrinsic(join),174175  lines(arr)::176    std.join('\n', arr + ['']),177178  deepJoin(arr)::179    if std.isString(arr) then180      arr181    else if std.isArray(arr) then182      std.join('', [std.deepJoin(x) for x in arr])183    else184      error 'Expected string or array, got %s' % std.type(arr),185186187  format:: $intrinsic(format),188189  foldr:: $intrinsic(foldr),190191  foldl:: $intrinsic(foldl),192193  filterMap(filter_func, map_func, arr)::194    if !std.isFunction(filter_func) then195      error ('std.filterMap first param must be function, got ' + std.type(filter_func))196    else if !std.isFunction(map_func) then197      error ('std.filterMap second param must be function, got ' + std.type(map_func))198    else if !std.isArray(arr) then199      error ('std.filterMap third param must be array, got ' + std.type(arr))200    else201      std.map(map_func, std.filter(filter_func, arr)),202203  assertEqual(a, b)::204    if a == b then205      true206    else207      error 'Assertion failed. ' + a + ' != ' + b,208209  abs(n)::210    if !std.isNumber(n) then211      error 'std.abs expected number, got ' + std.type(n)212    else213      if n > 0 then n else -n,214215  sign(n)::216    if !std.isNumber(n) then217      error 'std.sign expected number, got ' + std.type(n)218    else219      if n > 0 then220        1221      else if n < 0 then222        -1223      else 0,224225  max(a, b)::226    if !std.isNumber(a) then227      error 'std.max first param expected number, got ' + std.type(a)228    else if !std.isNumber(b) then229      error 'std.max second param expected number, got ' + std.type(b)230    else231      if a > b then a else b,232233  min(a, b)::234    if !std.isNumber(a) then235      error 'std.min first param expected number, got ' + std.type(a)236    else if !std.isNumber(b) then237      error 'std.min second param expected number, got ' + std.type(b)238    else239      if a < b then a else b,240241  clamp(x, minVal, maxVal)::242    if x < minVal then minVal243    else if x > maxVal then maxVal244    else x,245246  flattenArrays(arrs)::247    std.foldl(function(a, b) a + b, arrs, []),248249  manifestIni(ini)::250    local body_lines(body) =251      std.join([], [252        local value_or_values = body[k];253        if std.isArray(value_or_values) then254          ['%s = %s' % [k, value] for value in value_or_values]255        else256          ['%s = %s' % [k, value_or_values]]257258        for k in std.objectFields(body)259      ]);260261    local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),262          main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],263          all_sections = [264      section_lines(k, ini.sections[k])265      for k in std.objectFields(ini.sections)266    ];267    std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),268269  manifestToml(value):: std.manifestTomlEx(value, '  '),270271  manifestTomlEx(value, indent)::272    local273      escapeStringToml = std.escapeStringJson,274      escapeKeyToml(key) =275        local bare_allowed = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'));276        if std.setUnion(std.set(std.stringChars(key)), bare_allowed) == bare_allowed then key else escapeStringToml(key),277      isTableArray(v) = std.isArray(v) && std.length(v) > 0 && std.foldl(function(a, b) a && std.isObject(b), v, true),278      isSection(v) = std.isObject(v) || isTableArray(v),279      renderValue(v, indexedPath, inline, cindent) =280        if v == true then281          'true'282        else if v == false then283          'false'284        else if v == null then285          error 'Tried to manifest "null" at ' + indexedPath286        else if std.isNumber(v) then287          '' + v288        else if std.isString(v) then289          escapeStringToml(v)290        else if std.isFunction(v) then291          error 'Tried to manifest function at ' + indexedPath292        else if std.isArray(v) then293          if std.length(v) == 0 then294            '[]'295          else296            local range = std.range(0, std.length(v) - 1);297            local new_indent = if inline then '' else cindent + indent;298            local separator = if inline then ' ' else '\n';299            local lines = ['[' + separator]300                          + std.join([',' + separator],301                                     [302                                       [new_indent + renderValue(v[i], indexedPath + [i], true, '')]303                                       for i in range304                                     ])305                          + [separator + (if inline then '' else cindent) + ']'];306            std.join('', lines)307        else if std.isObject(v) then308          local lines = ['{ ']309                        + std.join([', '],310                                   [311                                     [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]312                                     for k in std.objectFields(v)313                                   ])314                        + [' }'];315          std.join('', lines),316      renderTableInternal(v, path, indexedPath, cindent) =317        local kvp = std.flattenArrays([318          [cindent + escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], false, cindent)]319          for k in std.objectFields(v)320          if !isSection(v[k])321        ]);322        local sections = [std.join('\n', kvp)] + [323          (324            if std.isObject(v[k]) then325              renderTable(v[k], path + [k], indexedPath + [k], cindent)326            else327              renderTableArray(v[k], path + [k], indexedPath + [k], cindent)328          )329          for k in std.objectFields(v)330          if isSection(v[k])331        ];332        std.join('\n\n', sections),333      renderTable(v, path, indexedPath, cindent) =334        cindent + '[' + std.join('.', std.map(escapeKeyToml, path)) + ']'335        + (if v == {} then '' else '\n')336        + renderTableInternal(v, path, indexedPath, cindent + indent),337      renderTableArray(v, path, indexedPath, cindent) =338        local range = std.range(0, std.length(v) - 1);339        local sections = [340          (cindent + '[[' + std.join('.', std.map(escapeKeyToml, path)) + ']]'341           + (if v[i] == {} then '' else '\n')342           + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))343          for i in range344        ];345        std.join('\n\n', sections);346    if std.isObject(value) then347      renderTableInternal(value, [], [], '')348    else349      error 'TOML body must be an object. Got ' + std.type(value),350351  escapeStringJson:: $intrinsic(escapeStringJson),352353  escapeStringPython(str)::354    std.escapeStringJson(str),355356  escapeStringBash(str_)::357    local str = std.toString(str_);358    local trans(ch) =359      if ch == "'" then360        "'\"'\"'"361      else362        ch;363    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),364365  escapeStringDollars(str_)::366    local str = std.toString(str_);367    local trans(ch) =368      if ch == '$' then369        '$$'370      else371        ch;372    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),373374  manifestJson(value):: std.manifestJsonEx(value, '    ') tailstrict,375376  manifestJsonEx:: $intrinsic(manifestJsonEx),377378  manifestYamlDocImpl:: $intrinsic(manifestYamlDocImpl),379380  manifestYamlDoc(value, indent_array_in_object=false):: std.manifestYamlDocImpl(value, indent_array_in_object),381382  manifestYamlStream(value, indent_array_in_object=false, c_document_end=true)::383    if !std.isArray(value) then384      error 'manifestYamlStream only takes arrays, got ' + std.type(value)385    else386      '---\n' + std.join(387        '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object) for e in value]388      ) + if c_document_end then '\n...\n' else '\n',389390391  manifestPython(v)::392    if std.isObject(v) then393      local fields = [394        '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]395        for k in std.objectFields(v)396      ];397      '{%s}' % [std.join(', ', fields)]398    else if std.isArray(v) then399      '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]400    else if std.isString(v) then401      '%s' % [std.escapeStringPython(v)]402    else if std.isFunction(v) then403      error 'cannot manifest function'404    else if std.isNumber(v) then405      std.toString(v)406    else if v == true then407      'True'408    else if v == false then409      'False'410    else if v == null then411      'None',412413  manifestPythonVars(conf)::414    local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];415    std.join('\n', vars + ['']),416417  manifestXmlJsonml(value)::418    if !std.isArray(value) then419      error 'Expected a JSONML value (an array), got %s' % std.type(value)420    else421      local aux(v) =422        if std.isString(v) then423          v424        else425          local tag = v[0];426          local has_attrs = std.length(v) > 1 && std.isObject(v[1]);427          local attrs = if has_attrs then v[1] else {};428          local children = if has_attrs then v[2:] else v[1:];429          local attrs_str =430            std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);431          std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);432433      aux(value),434435  local base64_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',436  local base64_inv = { [base64_table[i]]: i for i in std.range(0, 63) },437438  base64:: $intrinsic(base64),439440  base64DecodeBytes:: $intrinsic(base64DecodeBytes),441442  base64Decode:: $intrinsic(base64Decode),443444  reverse:: $intrinsic(reverse),445446  sortImpl:: $intrinsic(sortImpl),447448  sort(arr, keyF=id)::449    std.sortImpl(arr, keyF),450451  uniq(arr, keyF=id)::452    local f(a, b) =453      if std.length(a) == 0 then454        [b]455      else if keyF(a[std.length(a) - 1]) == keyF(b) then456        a457      else458        a + [b];459    std.foldl(f, arr, []),460461  set(arr, keyF=id)::462    std.uniq(std.sort(arr, keyF), keyF),463464  setMember(x, arr, keyF=id)::465    // TODO(dcunnin): Binary chop for O(log n) complexity466    std.length(std.setInter([x], arr, keyF)) > 0,467468  setUnion(a, b, keyF=id)::469    // NOTE: order matters, values in `a` win470    local aux(a, b, i, j, acc) =471      if i >= std.length(a) then472        acc + b[j:]473      else if j >= std.length(b) then474        acc + a[i:]475      else476        local ak = keyF(a[i]);477        local bk = keyF(b[j]);478        if ak == bk then479          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict480        else if ak < bk then481          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict482        else483          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;484    aux(a, b, 0, 0, []),485486  setInter(a, b, keyF=id)::487    local aux(a, b, i, j, acc) =488      if i >= std.length(a) || j >= std.length(b) then489        acc490      else491        if keyF(a[i]) == keyF(b[j]) then492          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict493        else if keyF(a[i]) < keyF(b[j]) then494          aux(a, b, i + 1, j, acc) tailstrict495        else496          aux(a, b, i, j + 1, acc) tailstrict;497    aux(a, b, 0, 0, []) tailstrict,498499  setDiff(a, b, keyF=id)::500    local aux(a, b, i, j, acc) =501      if i >= std.length(a) then502        acc503      else if j >= std.length(b) then504        acc + a[i:]505      else506        if keyF(a[i]) == keyF(b[j]) then507          aux(a, b, i + 1, j + 1, acc) tailstrict508        else if keyF(a[i]) < keyF(b[j]) then509          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict510        else511          aux(a, b, i, j + 1, acc) tailstrict;512    aux(a, b, 0, 0, []) tailstrict,513514  mergePatch(target, patch)::515    if std.isObject(patch) then516      local target_object =517        if std.isObject(target) then target else {};518519      local target_fields =520        if std.isObject(target_object) then std.objectFields(target_object) else [];521522      local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];523      local both_fields = std.setUnion(target_fields, std.objectFields(patch));524525      {526        [k]:527          if !std.objectHas(patch, k) then528            target_object[k]529          else if !std.objectHas(target_object, k) then530            std.mergePatch(null, patch[k]) tailstrict531          else532            std.mergePatch(target_object[k], patch[k]) tailstrict533        for k in std.setDiff(both_fields, null_fields)534      }535    else536      patch,537538  objectFields(o)::539    std.objectFieldsEx(o, false),540541  objectFieldsAll(o)::542    std.objectFieldsEx(o, true),543544  objectHas(o, f)::545    std.objectHasEx(o, f, false),546547  objectHasAll(o, f)::548    std.objectHasEx(o, f, true),549550  objectValues(o)::551    [o[k] for k in std.objectFields(o)],552553  objectValuesAll(o)::554    [o[k] for k in std.objectFieldsAll(o)],555556  equals:: $intrinsic(equals),557558  resolvePath(f, r)::559    local arr = std.split(f, '/');560    std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),561562  prune(a)::563    local isContent(b) =564      if b == null then565        false566      else if std.isArray(b) then567        std.length(b) > 0568      else if std.isObject(b) then569        std.length(b) > 0570      else571        true;572    if std.isArray(a) then573      [std.prune(x) for x in a if isContent($.prune(x))]574    else if std.isObject(a) then {575      [x]: $.prune(a[x])576      for x in std.objectFields(a)577      if isContent(std.prune(a[x]))578    } else579      a,580581  findSubstr(pat, str)::582    if !std.isString(pat) then583      error 'findSubstr first parameter should be a string, got ' + std.type(pat)584    else if !std.isString(str) then585      error 'findSubstr second parameter should be a string, got ' + std.type(str)586    else587      local pat_len = std.length(pat);588      local str_len = std.length(str);589      if pat_len == 0 || str_len == 0 || pat_len > str_len then590        []591      else592        std.filter(function(i) str[i:i + pat_len] == pat, std.range(0, str_len - pat_len)),593594  find(value, arr)::595    if !std.isArray(arr) then596      error 'find second parameter should be an array, got ' + std.type(arr)597    else598      std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),599}