git.delta.rocks / jrsonnet / refs/commits / 7c9753954b3b

difftreelog

source

crates/jsonnet-stdlib/src/std.jsonnet45.1 KiBsourcehistory
1{23  local std = self,4  local id = function(x) x,56  isString(v):: std.type(v) == 'string',7  isNumber(v):: std.type(v) == 'number',8  isBoolean(v):: std.type(v) == 'boolean',9  isObject(v):: std.type(v) == 'object',10  isArray(v):: std.type(v) == 'array',11  isFunction(v):: std.type(v) == 'function',1213  toString(a)::14    if std.type(a) == 'string' then a else '' + a,1516  substr(str, from, len)::17    assert std.isString(str) : 'substr first parameter should be a string, got ' + std.type(str);18    assert std.isNumber(from) : 'substr second parameter should be a string, got ' + std.type(from);19    assert std.isNumber(len) : 'substr third parameter should be a string, got ' + std.type(len);20    assert len >= 0 : 'substr third parameter should be greater than zero, got ' + len;21    std.join('', std.makeArray(std.max(0, std.min(len, std.length(str) - from)), function(i) str[i + from])),2223  startsWith(a, b)::24    if std.length(a) < std.length(b) then25      false26    else27      std.substr(a, 0, std.length(b)) == b,2829  endsWith(a, b)::30    if std.length(a) < std.length(b) then31      false32    else33      std.substr(a, std.length(a) - std.length(b), std.length(b)) == b,3435  lstripChars(str, chars)::36    if std.length(str) > 0 && std.member(chars, str[0]) then37      std.lstripChars(str[1:], chars)38    else39      str,4041  rstripChars(str, chars)::42    local len = std.length(str);43    if len > 0 && std.member(chars, str[len - 1]) then44      std.rstripChars(str[:len - 1], chars)45    else46      str,4748  stripChars(str, chars)::49    std.lstripChars(std.rstripChars(str, chars), chars),5051  stringChars(str)::52    std.makeArray(std.length(str), function(i) str[i]),5354  local parse_nat(str, base) =55    assert base > 0 && base <= 16 : 'integer base %d invalid' % base;56    // These codepoints are in ascending order:57    local zero_code = std.codepoint('0');58    local upper_a_code = std.codepoint('A');59    local lower_a_code = std.codepoint('a');60    local addDigit(aggregate, char) =61      local code = std.codepoint(char);62      local digit = if code >= lower_a_code then63        code - lower_a_code + 1064      else if code >= upper_a_code then65        code - upper_a_code + 1066      else67        code - zero_code;68      assert digit >= 0 && digit < base : '%s is not a base %d integer' % [str, base];69      base * aggregate + digit;70    std.foldl(addDigit, std.stringChars(str), 0),7172  parseInt(str)::73    assert std.isString(str) : 'Expected string, got ' + std.type(str);74    assert std.length(str) > 0 && str != '-' : 'Not an integer: "%s"' % [str];75    if str[0] == '-' then76      -parse_nat(str[1:], 10)77    else78      parse_nat(str, 10),7980  parseOctal(str)::81    assert std.isString(str) : 'Expected string, got ' + std.type(str);82    assert std.length(str) > 0 : 'Not an octal number: ""';83    parse_nat(str, 8),8485  parseHex(str)::86    assert std.isString(str) : 'Expected string, got ' + std.type(str);87    assert std.length(str) > 0 : 'Not hexadecimal: ""';88    parse_nat(str, 16),8990  split(str, c)::91    assert std.isString(str) : 'std.split first parameter should be a string, got ' + std.type(str);92    assert std.isString(c) : 'std.split second parameter should be a string, got ' + std.type(c);93    assert std.length(c) == 1 : 'std.split second parameter should have length 1, got ' + std.length(c);94    std.splitLimit(str, c, -1),9596  splitLimit(str, c, maxsplits)::97    assert std.isString(str) : 'std.splitLimit first parameter should be a string, got ' + std.type(str);98    assert std.isString(c) : 'std.splitLimit second parameter should be a string, got ' + std.type(c);99    assert std.length(c) == 1 : 'std.splitLimit second parameter should have length 1, got ' + std.length(c);100    assert std.isNumber(maxsplits) : 'std.splitLimit third parameter should be a number, got ' + std.type(maxsplits);101    local aux(str, delim, i, arr, v) =102      local c = str[i];103      local i2 = i + 1;104      if i >= std.length(str) then105        arr + [v]106      else if c == delim && (maxsplits == -1 || std.length(arr) < maxsplits) then107        aux(str, delim, i2, arr + [v], '') tailstrict108      else109        aux(str, delim, i2, arr, v + c) tailstrict;110    aux(str, c, 0, [], ''),111112  strReplace(str, from, to)::113    assert std.isString(str);114    assert std.isString(from);115    assert std.isString(to);116    assert from != '' : "'from' string must not be zero length.";117118    // Cache for performance.119    local str_len = std.length(str);120    local from_len = std.length(from);121122    // True if from is at str[i].123    local found_at(i) = str[i:i + from_len] == from;124125    // Return the remainder of 'str' starting with 'start_index' where126    // all occurrences of 'from' after 'curr_index' are replaced with 'to'.127    local replace_after(start_index, curr_index, acc) =128      if curr_index > str_len then129        acc + str[start_index:curr_index]130      else if found_at(curr_index) then131        local new_index = curr_index + std.length(from);132        replace_after(new_index, new_index, acc + str[start_index:curr_index] + to) tailstrict133      else134        replace_after(start_index, curr_index + 1, acc) tailstrict;135136    // if from_len==1, then we replace by splitting and rejoining the137    // string which is much faster than recursing on replace_after138    if from_len == 1 then139      std.join(to, std.split(str, from))140    else141      replace_after(0, 0, ''),142143  asciiUpper(str)::144    local cp = std.codepoint;145    local up_letter(c) = if cp(c) >= 97 && cp(c) < 123 then146      std.char(cp(c) - 32)147    else148      c;149    std.join('', std.map(up_letter, std.stringChars(str))),150151  asciiLower(str)::152    local cp = std.codepoint;153    local down_letter(c) = if cp(c) >= 65 && cp(c) < 91 then154      std.char(cp(c) + 32)155    else156      c;157    std.join('', std.map(down_letter, std.stringChars(str))),158159  range(from, to)::160    std.makeArray(to - from + 1, function(i) i + from),161162  repeat(what, count)::163    local joiner =164      if std.isString(what) then ''165      else if std.isArray(what) then []166      else error 'std.repeat first argument must be an array or a string';167    std.join(joiner, std.makeArray(count, function(i) what)),168169  slice(indexable, index, end, step)::170    local invar =171      // loop invariant with defaults applied172      {173        indexable: indexable,174        index:175          if index == null then 0176          else index,177        end:178          if end == null then std.length(indexable)179          else end,180        step:181          if step == null then 1182          else step,183        length: std.length(indexable),184        type: std.type(indexable),185      };186    assert invar.index >= 0 && invar.end >= 0 && invar.step >= 0 : 'got [%s:%s:%s] but negative index, end, and steps are not supported' % [invar.index, invar.end, invar.step];187    assert step != 0 : 'got %s but step must be greater than 0' % step;188    assert std.isString(indexable) || std.isArray(indexable) : 'std.slice accepts a string or an array, but got: %s' % std.type(indexable);189    local build(slice, cur) =190      if cur >= invar.end || cur >= invar.length then191        slice192      else193        build(194          if invar.type == 'string' then195            slice + invar.indexable[cur]196          else197            slice + [invar.indexable[cur]],198          cur + invar.step199        ) tailstrict;200    build(if invar.type == 'string' then '' else [], invar.index),201202  member(arr, x)::203    if std.isArray(arr) then204      std.count(arr, x) > 0205    else if std.isString(arr) then206      std.length(std.findSubstr(x, arr)) > 0207    else error 'std.member first argument must be an array or a string',208209  count(arr, x):: std.length(std.filter(function(v) v == x, arr)),210211  mod(a, b)::212    if std.isNumber(a) && std.isNumber(b) then213      std.modulo(a, b)214    else if std.isString(a) then215      std.format(a, b)216    else217      error 'Operator % cannot be used on types ' + std.type(a) + ' and ' + std.type(b) + '.',218219  map(func, arr)::220    if !std.isFunction(func) then221      error ('std.map first param must be function, got ' + std.type(func))222    else if !std.isArray(arr) && !std.isString(arr) then223      error ('std.map second param must be array / string, got ' + std.type(arr))224    else225      std.makeArray(std.length(arr), function(i) func(arr[i])),226227  mapWithIndex(func, arr)::228    if !std.isFunction(func) then229      error ('std.mapWithIndex first param must be function, got ' + std.type(func))230    else if !std.isArray(arr) && !std.isString(arr) then231      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))232    else233      std.makeArray(std.length(arr), function(i) func(i, arr[i])),234235  mapWithKey(func, obj)::236    if !std.isFunction(func) then237      error ('std.mapWithKey first param must be function, got ' + std.type(func))238    else if !std.isObject(obj) then239      error ('std.mapWithKey second param must be object, got ' + std.type(obj))240    else241      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },242243  flatMap(func, arr)::244    if !std.isFunction(func) then245      error ('std.flatMap first param must be function, got ' + std.type(func))246    else if std.isArray(arr) then247      std.flattenArrays(std.makeArray(std.length(arr), function(i) func(arr[i])))248    else if std.isString(arr) then249      std.join('', std.makeArray(std.length(arr), function(i) func(arr[i])))250    else error ('std.flatMap second param must be array / string, got ' + std.type(arr)),251252  join(sep, arr)::253    local aux(arr, i, first, running) =254      if i >= std.length(arr) then255        running256      else if arr[i] == null then257        aux(arr, i + 1, first, running) tailstrict258      else if std.type(arr[i]) != std.type(sep) then259        error 'expected %s but arr[%d] was %s ' % [std.type(sep), i, std.type(arr[i])]260      else if first then261        aux(arr, i + 1, false, running + arr[i]) tailstrict262      else263        aux(arr, i + 1, false, running + sep + arr[i]) tailstrict;264    if !std.isArray(arr) then265      error 'join second parameter should be array, got ' + std.type(arr)266    else if std.isString(sep) then267      aux(arr, 0, true, '')268    else if std.isArray(sep) then269      aux(arr, 0, true, [])270    else271      error 'join first parameter should be string or array, got ' + std.type(sep),272273  lines(arr)::274    std.join('\n', arr + ['']),275276  deepJoin(arr)::277    if std.isString(arr) then278      arr279    else if std.isArray(arr) then280      std.join('', [std.deepJoin(x) for x in arr])281    else282      error 'Expected string or array, got %s' % std.type(arr),283284285  format(str, vals)::286287    /////////////////////////////288    // Parse the mini-language //289    /////////////////////////////290291    local try_parse_mapping_key(str, i) =292      assert i < std.length(str) : 'Truncated format code.';293      local c = str[i];294      if c == '(' then295        local consume(str, j, v) =296          if j >= std.length(str) then297            error 'Truncated format code.'298          else299            local c = str[j];300            if c != ')' then301              consume(str, j + 1, v + c)302            else303              { i: j + 1, v: v };304        consume(str, i + 1, '')305      else306        { i: i, v: null };307308    local try_parse_cflags(str, i) =309      local consume(str, j, v) =310        assert j < std.length(str) : 'Truncated format code.';311        local c = str[j];312        if c == '#' then313          consume(str, j + 1, v { alt: true })314        else if c == '0' then315          consume(str, j + 1, v { zero: true })316        else if c == '-' then317          consume(str, j + 1, v { left: true })318        else if c == ' ' then319          consume(str, j + 1, v { blank: true })320        else if c == '+' then321          consume(str, j + 1, v { sign: true })322        else323          { i: j, v: v };324      consume(str, i, { alt: false, zero: false, left: false, blank: false, sign: false });325326    local try_parse_field_width(str, i) =327      if i < std.length(str) && str[i] == '*' then328        { i: i + 1, v: '*' }329      else330        local consume(str, j, v) =331          assert j < std.length(str) : 'Truncated format code.';332          local c = str[j];333          if c == '0' then334            consume(str, j + 1, v * 10 + 0)335          else if c == '1' then336            consume(str, j + 1, v * 10 + 1)337          else if c == '2' then338            consume(str, j + 1, v * 10 + 2)339          else if c == '3' then340            consume(str, j + 1, v * 10 + 3)341          else if c == '4' then342            consume(str, j + 1, v * 10 + 4)343          else if c == '5' then344            consume(str, j + 1, v * 10 + 5)345          else if c == '6' then346            consume(str, j + 1, v * 10 + 6)347          else if c == '7' then348            consume(str, j + 1, v * 10 + 7)349          else if c == '8' then350            consume(str, j + 1, v * 10 + 8)351          else if c == '9' then352            consume(str, j + 1, v * 10 + 9)353          else354            { i: j, v: v };355        consume(str, i, 0);356357    local try_parse_precision(str, i) =358      assert i < std.length(str) : 'Truncated format code.';359      local c = str[i];360      if c == '.' then361        try_parse_field_width(str, i + 1)362      else363        { i: i, v: null };364365    // Ignored, if it exists.366    local try_parse_length_modifier(str, i) =367      assert i < std.length(str) : 'Truncated format code.';368      local c = str[i];369      if c == 'h' || c == 'l' || c == 'L' then370        i + 1371      else372        i;373374    local parse_conv_type(str, i) =375      assert i < std.length(str) : 'Truncated format code.';376      local c = str[i];377      if c == 'd' || c == 'i' || c == 'u' then378        { i: i + 1, v: 'd', caps: false }379      else if c == 'o' then380        { i: i + 1, v: 'o', caps: false }381      else if c == 'x' then382        { i: i + 1, v: 'x', caps: false }383      else if c == 'X' then384        { i: i + 1, v: 'x', caps: true }385      else if c == 'e' then386        { i: i + 1, v: 'e', caps: false }387      else if c == 'E' then388        { i: i + 1, v: 'e', caps: true }389      else if c == 'f' then390        { i: i + 1, v: 'f', caps: false }391      else if c == 'F' then392        { i: i + 1, v: 'f', caps: true }393      else if c == 'g' then394        { i: i + 1, v: 'g', caps: false }395      else if c == 'G' then396        { i: i + 1, v: 'g', caps: true }397      else if c == 'c' then398        { i: i + 1, v: 'c', caps: false }399      else if c == 's' then400        { i: i + 1, v: 's', caps: false }401      else if c == '%' then402        { i: i + 1, v: '%', caps: false }403      else404        error 'Unrecognised conversion type: ' + c;405406407    // Parsed initial %, now the rest.408    local parse_code(str, i) =409      assert i < std.length(str) : 'Truncated format code.';410      local mkey = try_parse_mapping_key(str, i);411      local cflags = try_parse_cflags(str, mkey.i);412      local fw = try_parse_field_width(str, cflags.i);413      local prec = try_parse_precision(str, fw.i);414      local len_mod = try_parse_length_modifier(str, prec.i);415      local ctype = parse_conv_type(str, len_mod);416      {417        i: ctype.i,418        code: {419          mkey: mkey.v,420          cflags: cflags.v,421          fw: fw.v,422          prec: prec.v,423          ctype: ctype.v,424          caps: ctype.caps,425        },426      };427428    // Parse a format string (containing none or more % format tags).429    local parse_codes(str, i, out, cur) =430      if i >= std.length(str) then431        out + [cur]432      else433        local c = str[i];434        if c == '%' then435          local r = parse_code(str, i + 1);436          parse_codes(str, r.i, out + [cur, r.code], '') tailstrict437        else438          parse_codes(str, i + 1, out, cur + c) tailstrict;439440    local codes = parse_codes(str, 0, [], '');441442443    ///////////////////////444    // Format the values //445    ///////////////////////446447    // Useful utilities448    local padding(w, s) =449      local aux(w, v) =450        if w <= 0 then451          v452        else453          aux(w - 1, v + s);454      aux(w, '');455456    // Add s to the left of str so that its length is at least w.457    local pad_left(str, w, s) =458      padding(w - std.length(str), s) + str;459460    // Add s to the right of str so that its length is at least w.461    local pad_right(str, w, s) =462      str + padding(w - std.length(str), s);463464    // Render an integer (e.g., decimal or octal).465    local render_int(n__, min_chars, min_digits, blank, sign, radix, zero_prefix) =466      local n_ = std.abs(n__);467      local aux(n) =468        if n == 0 then469          zero_prefix470        else471          aux(std.floor(n / radix)) + (n % radix);472      local dec = if std.floor(n_) == 0 then '0' else aux(std.floor(n_));473      local neg = n__ < 0;474      local zp = min_chars - (if neg || blank || sign then 1 else 0);475      local zp2 = std.max(zp, min_digits);476      local dec2 = pad_left(dec, zp2, '0');477      (if neg then '-' else if sign then '+' else if blank then ' ' else '') + dec2;478479    // Render an integer in hexadecimal.480    local render_hex(n__, min_chars, min_digits, blank, sign, add_zerox, capitals) =481      local numerals = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]482                       + if capitals then ['A', 'B', 'C', 'D', 'E', 'F']483                       else ['a', 'b', 'c', 'd', 'e', 'f'];484      local n_ = std.abs(n__);485      local aux(n) =486        if n == 0 then487          ''488        else489          aux(std.floor(n / 16)) + numerals[n % 16];490      local hex = if std.floor(n_) == 0 then '0' else aux(std.floor(n_));491      local neg = n__ < 0;492      local zp = min_chars - (if neg || blank || sign then 1 else 0)493                 - (if add_zerox then 2 else 0);494      local zp2 = std.max(zp, min_digits);495      local hex2 = (if add_zerox then (if capitals then '0X' else '0x') else '')496                   + pad_left(hex, zp2, '0');497      (if neg then '-' else if sign then '+' else if blank then ' ' else '') + hex2;498499    local strip_trailing_zero(str) =500      local aux(str, i) =501        if i < 0 then502          ''503        else504          if str[i] == '0' then505            aux(str, i - 1)506          else507            std.substr(str, 0, i + 1);508      aux(str, std.length(str) - 1);509510    // Render floating point in decimal form511    local render_float_dec(n__, zero_pad, blank, sign, ensure_pt, trailing, prec) =512      local n_ = std.abs(n__);513      local whole = std.floor(n_);514      local dot_size = if prec == 0 && !ensure_pt then 0 else 1;515      local zp = zero_pad - prec - dot_size;516      local str = render_int(std.sign(n__) * whole, zp, 0, blank, sign, 10, '');517      if prec == 0 then518        str + if ensure_pt then '.' else ''519      else520        local frac = std.floor((n_ - whole) * std.pow(10, prec) + 0.5);521        if trailing || frac > 0 then522          local frac_str = render_int(frac, prec, 0, false, false, 10, '');523          str + '.' + if !trailing then strip_trailing_zero(frac_str) else frac_str524        else525          str;526527    // Render floating point in scientific form528    local render_float_sci(n__, zero_pad, blank, sign, ensure_pt, trailing, caps, prec) =529      local exponent = if n__ == 0 then 0 else std.floor(std.log(std.abs(n__)) / std.log(10));530      local suff = (if caps then 'E' else 'e')531                   + render_int(exponent, 3, 0, false, true, 10, '');532      local mantissa = if exponent == -324 then533        // Avoid a rounding error where std.pow(10, -324) is 0534        // -324 is the smallest exponent possible.535        n__ * 10 / std.pow(10, exponent + 1)536      else537        n__ / std.pow(10, exponent);538      local zp2 = zero_pad - std.length(suff);539      render_float_dec(mantissa, zp2, blank, sign, ensure_pt, trailing, prec) + suff;540541    // Render a value with an arbitrary format code.542    local format_code(val, code, fw, prec_or_null, i) =543      local cflags = code.cflags;544      local fpprec = if prec_or_null != null then prec_or_null else 6;545      local iprec = if prec_or_null != null then prec_or_null else 0;546      local zp = if cflags.zero && !cflags.left then fw else 0;547      if code.ctype == 's' then548        std.toString(val)549      else if code.ctype == 'd' then550        if std.type(val) != 'number' then551          error 'Format required number at '552                + i + ', got ' + std.type(val)553        else554          render_int(val, zp, iprec, cflags.blank, cflags.sign, 10, '')555      else if code.ctype == 'o' then556        if std.type(val) != 'number' then557          error 'Format required number at '558                + i + ', got ' + std.type(val)559        else560          local zero_prefix = if cflags.alt then '0' else '';561          render_int(val, zp, iprec, cflags.blank, cflags.sign, 8, zero_prefix)562      else if code.ctype == 'x' then563        if std.type(val) != 'number' then564          error 'Format required number at '565                + i + ', got ' + std.type(val)566        else567          render_hex(val,568                     zp,569                     iprec,570                     cflags.blank,571                     cflags.sign,572                     cflags.alt,573                     code.caps)574      else if code.ctype == 'f' then575        if std.type(val) != 'number' then576          error 'Format required number at '577                + i + ', got ' + std.type(val)578        else579          render_float_dec(val,580                           zp,581                           cflags.blank,582                           cflags.sign,583                           cflags.alt,584                           true,585                           fpprec)586      else if code.ctype == 'e' then587        if std.type(val) != 'number' then588          error 'Format required number at '589                + i + ', got ' + std.type(val)590        else591          render_float_sci(val,592                           zp,593                           cflags.blank,594                           cflags.sign,595                           cflags.alt,596                           true,597                           code.caps,598                           fpprec)599      else if code.ctype == 'g' then600        if std.type(val) != 'number' then601          error 'Format required number at '602                + i + ', got ' + std.type(val)603        else604          local exponent = std.floor(std.log(std.abs(val)) / std.log(10));605          if exponent < -4 || exponent >= fpprec then606            render_float_sci(val,607                             zp,608                             cflags.blank,609                             cflags.sign,610                             cflags.alt,611                             cflags.alt,612                             code.caps,613                             fpprec - 1)614          else615            local digits_before_pt = std.max(1, exponent + 1);616            render_float_dec(val,617                             zp,618                             cflags.blank,619                             cflags.sign,620                             cflags.alt,621                             cflags.alt,622                             fpprec - digits_before_pt)623      else if code.ctype == 'c' then624        if std.type(val) == 'number' then625          std.char(val)626        else if std.type(val) == 'string' then627          if std.length(val) == 1 then628            val629          else630            error '%c expected 1-sized string got: ' + std.length(val)631        else632          error '%c expected number / string, got: ' + std.type(val)633      else634        error 'Unknown code: ' + code.ctype;635636    // Render a parsed format string with an array of values.637    local format_codes_arr(codes, arr, i, j, v) =638      if i >= std.length(codes) then639        if j < std.length(arr) then640          error ('Too many values to format: ' + std.length(arr) + ', expected ' + j)641        else642          v643      else644        local code = codes[i];645        if std.type(code) == 'string' then646          format_codes_arr(codes, arr, i + 1, j, v + code) tailstrict647        else648          local tmp = if code.fw == '*' then {649            j: j + 1,650            fw: if j >= std.length(arr) then651              error ('Not enough values to format: ' + std.length(arr) + ', expected at least ' + j)652            else653              arr[j],654          } else {655            j: j,656            fw: code.fw,657          };658          local tmp2 = if code.prec == '*' then {659            j: tmp.j + 1,660            prec: if tmp.j >= std.length(arr) then661              error ('Not enough values to format: ' + std.length(arr) + ', expected at least ' + tmp.j)662            else663              arr[tmp.j],664          } else {665            j: tmp.j,666            prec: code.prec,667          };668          local j2 = tmp2.j;669          local val =670            if j2 < std.length(arr) then671              arr[j2]672            else673              error ('Not enough values to format: ' + std.length(arr) + ', expected more than ' + j2);674          local s =675            if code.ctype == '%' then676              '%'677            else678              format_code(val, code, tmp.fw, tmp2.prec, j2);679          local s_padded =680            if code.cflags.left then681              pad_right(s, tmp.fw, ' ')682            else683              pad_left(s, tmp.fw, ' ');684          local j3 =685            if code.ctype == '%' then686              j2687            else688              j2 + 1;689          format_codes_arr(codes, arr, i + 1, j3, v + s_padded) tailstrict;690691    // Render a parsed format string with an object of values.692    local format_codes_obj(codes, obj, i, v) =693      if i >= std.length(codes) then694        v695      else696        local code = codes[i];697        if std.type(code) == 'string' then698          format_codes_obj(codes, obj, i + 1, v + code) tailstrict699        else700          local f =701            if code.mkey == null then702              error 'Mapping keys required.'703            else704              code.mkey;705          local fw =706            if code.fw == '*' then707              error 'Cannot use * field width with object.'708            else709              code.fw;710          local prec =711            if code.prec == '*' then712              error 'Cannot use * precision with object.'713            else714              code.prec;715          local val =716            if std.objectHasAll(obj, f) then717              obj[f]718            else719              error 'No such field: ' + f;720          local s =721            if code.ctype == '%' then722              '%'723            else724              format_code(val, code, fw, prec, f);725          local s_padded =726            if code.cflags.left then727              pad_right(s, fw, ' ')728            else729              pad_left(s, fw, ' ');730          format_codes_obj(codes, obj, i + 1, v + s_padded) tailstrict;731732    if std.isArray(vals) then733      format_codes_arr(codes, vals, 0, 0, '')734    else if std.isObject(vals) then735      format_codes_obj(codes, vals, 0, '')736    else737      format_codes_arr(codes, [vals], 0, 0, ''),738739  foldr(func, arr, init)::740    local aux(func, arr, running, idx) =741      if idx < 0 then742        running743      else744        aux(func, arr, func(arr[idx], running), idx - 1) tailstrict;745    aux(func, arr, init, std.length(arr) - 1),746747  foldl(func, arr, init)::748    local aux(func, arr, running, idx) =749      if idx >= std.length(arr) then750        running751      else752        aux(func, arr, func(running, arr[idx]), idx + 1) tailstrict;753    aux(func, arr, init, 0),754755756  filterMap(filter_func, map_func, arr)::757    if !std.isFunction(filter_func) then758      error ('std.filterMap first param must be function, got ' + std.type(filter_func))759    else if !std.isFunction(map_func) then760      error ('std.filterMap second param must be function, got ' + std.type(map_func))761    else if !std.isArray(arr) then762      error ('std.filterMap third param must be array, got ' + std.type(arr))763    else764      std.map(map_func, std.filter(filter_func, arr)),765766  assertEqual(a, b)::767    if a == b then768      true769    else770      error 'Assertion failed. ' + a + ' != ' + b,771772  abs(n)::773    if !std.isNumber(n) then774      error 'std.abs expected number, got ' + std.type(n)775    else776      if n > 0 then n else -n,777778  sign(n)::779    if !std.isNumber(n) then780      error 'std.sign expected number, got ' + std.type(n)781    else782      if n > 0 then783        1784      else if n < 0 then785        -1786      else 0,787788  max(a, b)::789    if !std.isNumber(a) then790      error 'std.max first param expected number, got ' + std.type(a)791    else if !std.isNumber(b) then792      error 'std.max second param expected number, got ' + std.type(b)793    else794      if a > b then a else b,795796  min(a, b)::797    if !std.isNumber(a) then798      error 'std.max first param expected number, got ' + std.type(a)799    else if !std.isNumber(b) then800      error 'std.max second param expected number, got ' + std.type(b)801    else802      if a < b then a else b,803804  clamp(x, minVal, maxVal)::805    if x < minVal then minVal806    else if x > maxVal then maxVal807    else x,808809  flattenArrays(arrs)::810    std.foldl(function(a, b) a + b, arrs, []),811812  manifestIni(ini)::813    local body_lines(body) =814      std.join([], [815        local value_or_values = body[k];816        if std.isArray(value_or_values) then817          ['%s = %s' % [k, value] for value in value_or_values]818        else819          ['%s = %s' % [k, value_or_values]]820821        for k in std.objectFields(body)822      ]);823824    local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),825          main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],826          all_sections = [827      section_lines(k, ini.sections[k])828      for k in std.objectFields(ini.sections)829    ];830    std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),831832  escapeStringJson(str_)::833    local str = std.toString(str_);834    local trans(ch) =835      if ch == '"' then836        '\\"'837      else if ch == '\\' then838        '\\\\'839      else if ch == '\b' then840        '\\b'841      else if ch == '\f' then842        '\\f'843      else if ch == '\n' then844        '\\n'845      else if ch == '\r' then846        '\\r'847      else if ch == '\t' then848        '\\t'849      else850        local cp = std.codepoint(ch);851        if cp < 32 || (cp >= 127 && cp <= 159) then852          '\\u%04x' % [cp]853        else854          ch;855    '"%s"' % std.join('', [trans(ch) for ch in std.stringChars(str)]),856857  escapeStringPython(str)::858    std.escapeStringJson(str),859860  escapeStringBash(str_)::861    local str = std.toString(str_);862    local trans(ch) =863      if ch == "'" then864        "'\"'\"'"865      else866        ch;867    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),868869  escapeStringDollars(str_)::870    local str = std.toString(str_);871    local trans(ch) =872      if ch == '$' then873        '$$'874      else875        ch;876    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),877878  manifestJson(value):: std.manifestJsonEx(value, '    '),879880  manifestJsonEx(value, indent)::881    local aux(v, path, cindent) =882      if v == true then883        'true'884      else if v == false then885        'false'886      else if v == null then887        'null'888      else if std.isNumber(v) then889        '' + v890      else if std.isString(v) then891        std.escapeStringJson(v)892      else if std.isFunction(v) then893        error 'Tried to manifest function at ' + path894      else if std.isArray(v) then895        local range = std.range(0, std.length(v) - 1);896        local new_indent = cindent + indent;897        local lines = ['[\n']898                      + std.join([',\n'],899                                 [900                                   [new_indent + aux(v[i], path + [i], new_indent)]901                                   for i in range902                                 ])903                      + ['\n' + cindent + ']'];904        std.join('', lines)905      else if std.isObject(v) then906        local lines = ['{\n']907                      + std.join([',\n'],908                                 [909                                   [cindent + indent + std.escapeStringJson(k) + ': '910                                    + aux(v[k], path + [k], cindent + indent)]911                                   for k in std.objectFields(v)912                                 ])913                      + ['\n' + cindent + '}'];914        std.join('', lines);915    aux(value, [], ''),916917  manifestYamlDoc(value, indent_array_in_object=false)::918    local aux(v, path, cindent) =919      if v == true then920        'true'921      else if v == false then922        'false'923      else if v == null then924        'null'925      else if std.isNumber(v) then926        '' + v927      else if std.isString(v) then928        local len = std.length(v);929        if len == 0 then930          '""'931        else if v[len - 1] == '\n' then932          local split = std.split(v, '\n');933          std.join('\n' + cindent + '  ', ['|'] + split[0:std.length(split) - 1])934        else935          std.escapeStringJson(v)936      else if std.isFunction(v) then937        error 'Tried to manifest function at ' + path938      else if std.isArray(v) then939        if std.length(v) == 0 then940          '[]'941        else942          local params(value) =943            if std.isArray(value) && std.length(value) > 0 then {944              // While we could avoid the new line, it yields YAML that is945              // hard to read, e.g.:946              // - - - 1947              //     - 2948              //   - - 3949              //     - 4950              new_indent: cindent + '  ',951              space: '\n' + self.new_indent,952            } else if std.isObject(value) && std.length(value) > 0 then {953              new_indent: cindent + '  ',954              // In this case we can start on the same line as the - because the indentation955              // matches up then.  The converse is not true, because fields are not always956              // 1 character long.957              space: ' ',958            } else {959              // In this case, new_indent is only used in the case of multi-line strings.960              new_indent: cindent,961              space: ' ',962            };963          local range = std.range(0, std.length(v) - 1);964          local parts = [965            '-' + param.space + aux(v[i], path + [i], param.new_indent)966            for i in range967            for param in [params(v[i])]968          ];969          std.join('\n' + cindent, parts)970      else if std.isObject(v) then971        if std.length(v) == 0 then972          '{}'973        else974          local params(value) =975            if std.isArray(value) && std.length(value) > 0 then {976              // Not indenting allows e.g.977              // ports:978              // - 80979              // instead of980              // ports:981              //   - 80982              new_indent: if indent_array_in_object then cindent + '  ' else cindent,983              space: '\n' + self.new_indent,984            } else if std.isObject(value) && std.length(value) > 0 then {985              new_indent: cindent + '  ',986              space: '\n' + self.new_indent,987            } else {988              // In this case, new_indent is only used in the case of multi-line strings.989              new_indent: cindent,990              space: ' ',991            };992          local lines = [993            std.escapeStringJson(k) + ':' + param.space + aux(v[k], path + [k], param.new_indent)994            for k in std.objectFields(v)995            for param in [params(v[k])]996          ];997          std.join('\n' + cindent, lines);998    aux(value, [], ''),9991000  manifestYamlStream(value, indent_array_in_object=false, c_document_end=true)::1001    if !std.isArray(value) then1002      error 'manifestYamlStream only takes arrays, got ' + std.type(value)1003    else1004      '---\n' + std.join(1005        '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object) for e in value]1006      ) + if c_document_end then '\n...\n' else '\n',100710081009  manifestPython(v)::1010    if std.isObject(v) then1011      local fields = [1012        '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]1013        for k in std.objectFields(v)1014      ];1015      '{%s}' % [std.join(', ', fields)]1016    else if std.isArray(v) then1017      '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]1018    else if std.isString(v) then1019      '%s' % [std.escapeStringPython(v)]1020    else if std.isFunction(v) then1021      error 'cannot manifest function'1022    else if std.isNumber(v) then1023      std.toString(v)1024    else if v == true then1025      'True'1026    else if v == false then1027      'False'1028    else if v == null then1029      'None',10301031  manifestPythonVars(conf)::1032    local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];1033    std.join('\n', vars + ['']),10341035  manifestXmlJsonml(value)::1036    if !std.isArray(value) then1037      error 'Expected a JSONML value (an array), got %s' % std.type(value)1038    else1039      local aux(v) =1040        if std.isString(v) then1041          v1042        else1043          local tag = v[0];1044          local has_attrs = std.length(v) > 1 && std.isObject(v[1]);1045          local attrs = if has_attrs then v[1] else {};1046          local children = if has_attrs then v[2:] else v[1:];1047          local attrs_str =1048            std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);1049          std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);10501051      aux(value),10521053  local base64_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',1054  local base64_inv = { [base64_table[i]]: i for i in std.range(0, 63) },10551056  base64(input)::1057    local bytes =1058      if std.isString(input) then1059        std.map(function(c) std.codepoint(c), input)1060      else1061        input;10621063    local aux(arr, i, r) =1064      if i >= std.length(arr) then1065        r1066      else if i + 1 >= std.length(arr) then1067        local str =1068          // 6 MSB of i1069          base64_table[(arr[i] & 252) >> 2] +1070          // 2 LSB of i1071          base64_table[(arr[i] & 3) << 4] +1072          '==';1073        aux(arr, i + 3, r + str) tailstrict1074      else if i + 2 >= std.length(arr) then1075        local str =1076          // 6 MSB of i1077          base64_table[(arr[i] & 252) >> 2] +1078          // 2 LSB of i, 4 MSB of i+11079          base64_table[(arr[i] & 3) << 4 | (arr[i + 1] & 240) >> 4] +1080          // 4 LSB of i+11081          base64_table[(arr[i + 1] & 15) << 2] +1082          '=';1083        aux(arr, i + 3, r + str) tailstrict1084      else1085        local str =1086          // 6 MSB of i1087          base64_table[(arr[i] & 252) >> 2] +1088          // 2 LSB of i, 4 MSB of i+11089          base64_table[(arr[i] & 3) << 4 | (arr[i + 1] & 240) >> 4] +1090          // 4 LSB of i+1, 2 MSB of i+21091          base64_table[(arr[i + 1] & 15) << 2 | (arr[i + 2] & 192) >> 6] +1092          // 6 LSB of i+21093          base64_table[(arr[i + 2] & 63)];1094        aux(arr, i + 3, r + str) tailstrict;10951096    local sanity = std.foldl(function(r, a) r && (a < 256), bytes, true);1097    if !sanity then1098      error 'Can only base64 encode strings / arrays of single bytes.'1099    else1100      aux(bytes, 0, ''),110111021103  base64DecodeBytes(str)::1104    if std.length(str) % 4 != 0 then1105      error 'Not a base64 encoded string "%s"' % str1106    else1107      local aux(str, i, r) =1108        if i >= std.length(str) then1109          r1110        else1111          // all 6 bits of i, 2 MSB of i+11112          local n1 = [base64_inv[str[i]] << 2 | (base64_inv[str[i + 1]] >> 4)];1113          // 4 LSB of i+1, 4MSB of i+21114          local n2 =1115            if str[i + 2] == '=' then []1116            else [(base64_inv[str[i + 1]] & 15) << 4 | (base64_inv[str[i + 2]] >> 2)];1117          // 2 LSB of i+2, all 6 bits of i+31118          local n3 =1119            if str[i + 3] == '=' then []1120            else [(base64_inv[str[i + 2]] & 3) << 6 | base64_inv[str[i + 3]]];1121          aux(str, i + 4, r + n1 + n2 + n3) tailstrict;1122      aux(str, 0, []),11231124  base64Decode(str)::1125    local bytes = std.base64DecodeBytes(str);1126    std.join('', std.map(function(b) std.char(b), bytes)),11271128  reverse(arr)::1129    local l = std.length(arr);1130    std.makeArray(l, function(i) arr[l - i - 1]),11311132  // Merge-sort for long arrays and naive quicksort for shorter ones1133  sort(arr, keyF=id)::1134    local quickSort(arr, keyF=id) =1135      local l = std.length(arr);1136      if std.length(arr) <= 1 then1137        arr1138      else1139        local pos = 0;1140        local pivot = keyF(arr[pos]);1141        local rest = std.makeArray(l - 1, function(i) if i < pos then arr[i] else arr[i + 1]);1142        local left = std.filter(function(x) keyF(x) < pivot, rest);1143        local right = std.filter(function(x) keyF(x) >= pivot, rest);1144        quickSort(left, keyF) + [arr[pos]] + quickSort(right, keyF);11451146    local merge(a, b) =1147      local la = std.length(a), lb = std.length(b);1148      local aux(i, j, prefix) =1149        if i == la then1150          prefix + b[j:]1151        else if j == lb then1152          prefix + a[i:]1153        else1154          if keyF(a[i]) <= keyF(b[j]) then1155            aux(i + 1, j, prefix + [a[i]]) tailstrict1156          else1157            aux(i, j + 1, prefix + [b[j]]) tailstrict;1158      aux(0, 0, []);11591160    local l = std.length(arr);1161    if std.length(arr) <= 30 then1162      quickSort(arr, keyF=keyF)1163    else1164      local mid = std.floor(l / 2);1165      local left = arr[:mid], right = arr[mid:];1166      merge(std.sort(left, keyF=keyF), std.sort(right, keyF=keyF)),11671168  uniq(arr, keyF=id)::1169    local f(a, b) =1170      if std.length(a) == 0 then1171        [b]1172      else if keyF(a[std.length(a) - 1]) == keyF(b) then1173        a1174      else1175        a + [b];1176    std.foldl(f, arr, []),11771178  set(arr, keyF=id)::1179    std.uniq(std.sort(arr, keyF), keyF),11801181  setMember(x, arr, keyF=id)::1182    // TODO(dcunnin): Binary chop for O(log n) complexity1183    std.length(std.setInter([x], arr, keyF)) > 0,11841185  setUnion(a, b, keyF=id)::1186    // NOTE: order matters, values in `a` win1187    local aux(a, b, i, j, acc) =1188      if i >= std.length(a) then1189        acc + b[j:]1190      else if j >= std.length(b) then1191        acc + a[i:]1192      else1193        local ak = keyF(a[i]);1194        local bk = keyF(b[j]);1195        if ak == bk then1196          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict1197        else if ak < bk then1198          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict1199        else1200          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;1201    aux(a, b, 0, 0, []),12021203  setInter(a, b, keyF=id)::1204    local aux(a, b, i, j, acc) =1205      if i >= std.length(a) || j >= std.length(b) then1206        acc1207      else1208        if keyF(a[i]) == keyF(b[j]) then1209          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict1210        else if keyF(a[i]) < keyF(b[j]) then1211          aux(a, b, i + 1, j, acc) tailstrict1212        else1213          aux(a, b, i, j + 1, acc) tailstrict;1214    aux(a, b, 0, 0, []) tailstrict,12151216  setDiff(a, b, keyF=id)::1217    local aux(a, b, i, j, acc) =1218      if i >= std.length(a) then1219        acc1220      else if j >= std.length(b) then1221        acc + a[i:]1222      else1223        if keyF(a[i]) == keyF(b[j]) then1224          aux(a, b, i + 1, j + 1, acc) tailstrict1225        else if keyF(a[i]) < keyF(b[j]) then1226          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict1227        else1228          aux(a, b, i, j + 1, acc) tailstrict;1229    aux(a, b, 0, 0, []) tailstrict,12301231  mergePatch(target, patch)::1232    if std.isObject(patch) then1233      local target_object =1234        if std.isObject(target) then target else {};12351236      local target_fields =1237        if std.isObject(target_object) then std.objectFields(target_object) else [];12381239      local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];1240      local both_fields = std.setUnion(target_fields, std.objectFields(patch));12411242      {1243        [k]:1244          if !std.objectHas(patch, k) then1245            target_object[k]1246          else if !std.objectHas(target_object, k) then1247            std.mergePatch(null, patch[k]) tailstrict1248          else1249            std.mergePatch(target_object[k], patch[k]) tailstrict1250        for k in std.setDiff(both_fields, null_fields)1251      }1252    else1253      patch,12541255  objectFields(o)::1256    std.objectFieldsEx(o, false),12571258  objectFieldsAll(o)::1259    std.objectFieldsEx(o, true),12601261  objectHas(o, f)::1262    std.objectHasEx(o, f, false),12631264  objectHasAll(o, f)::1265    std.objectHasEx(o, f, true),12661267  equals(a, b)::1268    local ta = std.type(a);1269    local tb = std.type(b);1270    if !std.primitiveEquals(ta, tb) then1271      false1272    else1273      if std.primitiveEquals(ta, 'array') then1274        local la = std.length(a);1275        if !std.primitiveEquals(la, std.length(b)) then1276          false1277        else1278          local aux(a, b, i) =1279            if i >= la then1280              true1281            else if a[i] != b[i] then1282              false1283            else1284              aux(a, b, i + 1) tailstrict;1285          aux(a, b, 0)1286      else if std.primitiveEquals(ta, 'object') then1287        local fields = std.objectFields(a);1288        local lfields = std.length(fields);1289        if fields != std.objectFields(b) then1290          false1291        else1292          local aux(a, b, i) =1293            if i >= lfields then1294              true1295            else if local f = fields[i]; a[f] != b[f] then1296              false1297            else1298              aux(a, b, i + 1) tailstrict;1299          aux(a, b, 0)1300      else1301        std.primitiveEquals(a, b),130213031304  resolvePath(f, r)::1305    local arr = std.split(f, '/');1306    std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),13071308  prune(a)::1309    local isContent(b) =1310      if b == null then1311        false1312      else if std.isArray(b) then1313        std.length(b) > 01314      else if std.isObject(b) then1315        std.length(b) > 01316      else1317        true;1318    if std.isArray(a) then1319      [std.prune(x) for x in a if isContent($.prune(x))]1320    else if std.isObject(a) then {1321      [x]: $.prune(a[x])1322      for x in std.objectFields(a)1323      if isContent(std.prune(a[x]))1324    } else1325      a,13261327  findSubstr(pat, str)::1328    if !std.isString(pat) then1329      error 'findSubstr first parameter should be a string, got ' + std.type(pat)1330    else if !std.isString(str) then1331      error 'findSubstr second parameter should be a string, got ' + std.type(str)1332    else1333      local pat_len = std.length(pat);1334      local str_len = std.length(str);1335      if pat_len == 0 || str_len == 0 || pat_len > str_len then1336        []1337      else1338        std.filter(function(i) str[i:i + pat_len] == pat, std.range(0, str_len - pat_len)),13391340  find(value, arr)::1341    if !std.isArray(arr) then1342      error 'find second parameter should be an array, got ' + std.type(arr)1343    else1344      std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),1345}