Skip to content
Myr

Move jq-coded builtins to non-C file (fix #424)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Tolnay · committed by David Tolnay · parent b80d58e · Browse files · 4 files+302 added−296 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+302 added−296 removed

  • other:+302 added−296 removed

4 files+302 added−296 removed

modified:src/builtin.c+9 added-296 removed
1362 unmodified lines
13631364 return block_bind_referenced(builtins, b, OP_IS_CALL_PSEUDO);1365}13661367#define LIBM_DD(name) "def " #name ": _" #name ";",1368#define LIBM_DDD(name) "def " #name "(a;b): _" #name "(a;b);",1369#define LIBM_DD_NO(name) "def " #name ": \"Error: " #name "() not found at build time\"|error;",1370#define LIBM_DDD_NO(name) "def " #name "(a;b): \"Error: " #name "() not found at build time\"|error;",1367#define LIBM_DD(name) "def " #name ": _" #name ";"1368#define LIBM_DDD(name) "def " #name "(a;b): _" #name "(a;b);"1369#define LIBM_DD_NO(name) "def " #name ": \"Error: " #name "() not found at build time\"|error;"1370#define LIBM_DDD_NO(name) "def " #name "(a;b): \"Error: " #name "() not found at build time\"|error;"13711372static const char* const jq_builtins[] = {1373 "def error: error(.);",1374 "def map(f): [.[] | f];",1375 "def select(f): if f then . else empty end;",1376 "def sort_by(f): _sort_by_impl(map([f]));",1377 "def group_by(f): _group_by_impl(map([f]));",1378 "def unique: group_by(.) | map(.[0]);",1379 "def unique_by(f): group_by(f) | map(.[0]);",1380 "def max_by(f): _max_by_impl(map([f]));",1381 "def min_by(f): _min_by_impl(map([f]));",1372static const char* const jq_builtins =1373#include "libm.h"1383 "def add: reduce .[] as $x (null; . + $x);",1384 "def del(f): delpaths([path(f)]);",1385 "def _assign(paths; value): value as $v | reduce path(paths) as $p (.; setpath($p; $v));",1386 "def _modify(paths; update): reduce path(paths) as $p (.; setpath($p; getpath($p) | update));",1387 "def map_values(f): .[] |= f;",1374#include "builtin.inc"1375;13761389 // recurse1390 "def recurse(f): def r: ., (f | select(. != null) | r); r;",1391 "def recurse(f; cond): def r: ., (f | select(cond) | r); r;",1392 "def recurse: recurse(.[]?);",1393 "def recurse_down: recurse;",13941395 "def to_entries: [keys_unsorted[] as $k | {key: $k, value: .[$k]}];",1396 "def from_entries: map({(.key // .Key // .name // .Name): (if has(\"value\") then .value else .Value end)}) | add | .//={};",1397 "def with_entries(f): to_entries | map(f) | from_entries;",1398 "def reverse: [.[length - 1 - range(0;length)]];",1399 "def indices($i): if type == \"array\" and ($i|type) == \"array\" then .[$i]"1400 " elif type == \"array\" then .[[$i]]"1401 " elif type == \"string\" and ($i|type) == \"string\" then _strindices($i)"1402 " else .[$i] end;",1403 "def index($i): indices($i) | .[0];", // TODO: optimize1404 "def rindex($i): indices($i) | .[-1:][0];", // TODO: optimize1405 "def paths: path(recurse(if (type|. == \"array\" or . == \"object\") then .[] else empty end))|select(length > 0);",1406 "def paths(node_filter): . as $dot|paths|select(. as $p|$dot|getpath($p)|node_filter);",1407 "def any(generator; condition):"1408 " [label $out | foreach generator as $i"1409 " (false;"1410 " if . then break $out elif $i | condition then true else . end;"1411 " if . then . else empty end)] | length == 1;",1412 "def any(condition): any(.[]; condition);",1413 "def any: any(.);",1414 "def all(generator; condition): "1415 " [label $out | foreach generator as $i"1416 " (true;"1417 " if .|not then break $out elif $i | condition then . else false end;"1418 " if .|not then . else empty end)] | length == 0;",1419 "def all(condition): all(.[]; condition);",1420 "def all: all(.);",1421 "def isfinite: type == \"number\" and (isinfinite | not);",1422 "def arrays: select(type == \"array\");",1423 "def objects: select(type == \"object\");",1424 "def iterables: arrays, objects;",1425 "def booleans: select(type == \"boolean\");",1426 "def numbers: select(type == \"number\");",1427 "def normals: select(isnormal);",1428 "def finites: select(isfinite);",1429 "def strings: select(type == \"string\");",1430 "def nulls: select(type == \"null\");",1431 "def values: select(. != null);",1432 "def scalars: select(. == null or . == true or . == false or type == \"number\" or type == \"string\");",1433 "def scalars_or_empty: select(. == null or . == true or . == false or type == \"number\" or type == \"string\" or ((type==\"array\" or type==\"object\") and length==0));",1434 "def leaf_paths: paths(scalars);",1435 "def join($x): reduce .[] as $i (null; (.//\"\") + (if . == null then $i else $x + $i end))//\"\";",1436 "def _flatten($x): reduce .[] as $i ([]; if $i | type == \"array\" and $x != 0 then . + ($i | _flatten($x-1)) else . + [$i] end);",1437 "def flatten($x): if $x < 0 then error(\"flatten depth must not be negative\") else _flatten($x) end;",1438 "def flatten: _flatten(-1);",1439 "def range($x): range(0;$x);",1440 "def fromdateiso8601: strptime(\"%Y-%m-%dT%H:%M:%SZ\")|mktime;",1441 "def todateiso8601: strftime(\"%Y-%m-%dT%H:%M:%SZ\");",1442 "def fromdate: fromdateiso8601;",1443 "def todate: todateiso8601;",1444 "def match(re; mode): _match_impl(re; mode; false)|.[];",1445 "def match($val): ($val|type) as $vt | if $vt == \"string\" then match($val; null)"1446 " elif $vt == \"array\" and ($val | length) > 1 then match($val[0]; $val[1])"1447 " elif $vt == \"array\" and ($val | length) > 0 then match($val[0]; null)"1448 " else error( $vt + \" not a string or array\") end;",1449 "def test(re; mode): _match_impl(re; mode; true);",1450 "def test($val): ($val|type) as $vt | if $vt == \"string\" then test($val; null)"1451 " elif $vt == \"array\" and ($val | length) > 1 then test($val[0]; $val[1])"1452 " elif $vt == \"array\" and ($val | length) > 0 then test($val[0]; null)"1453 " else error( $vt + \" not a string or array\") end;",1454 "def capture(re; mods): match(re; mods) | reduce ( .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair ({}; . + $pair);",1455 "def capture($val): ($val|type) as $vt | if $vt == \"string\" then capture($val; null)"1456 " elif $vt == \"array\" and ($val | length) > 1 then capture($val[0]; $val[1])"1457 " elif $vt == \"array\" and ($val | length) > 0 then capture($val[0]; null)"1458 " else error( $vt + \" not a string or array\") end;",1459 "def scan(re):"1460 " match(re; \"g\")"1461 " | if (.captures|length > 0)"1462 " then [ .captures | .[] | .string ]"1463 " else .string"1464 " end ;",1465 //1466 // If input is an array, then emit a stream of successive subarrays of length n (or less),1467 // and similarly for strings.1468 "def _nwise(a; $n): if a|length <= $n then a else a[0:$n] , _nwise(a[$n:]; $n) end;",1469 "def _nwise($n): _nwise(.; $n);",1470 //1471 // splits/1 produces a stream; split/1 is retained for backward compatibility.1472 "def splits($re; flags): . as $s"1473 // # multiple occurrences of "g" are acceptable1474 " | [ match($re; \"g\" + flags) | (.offset, .offset + .length) ]"1475 " | [0] + . +[$s|length]"1476 " | _nwise(2)"1477 " | $s[.[0]:.[1] ] ;",1478 "def splits($re): splits($re; null);",1479 //1480 // split emits an array for backward compatibility1481 "def split($re; flags): [ splits($re; flags) ];",1482 //1483 // If s contains capture variables, then create a capture object and pipe it to s1484 "def sub($re; s):"1485 " . as $in"1486 " | [match($re)]"1487 " | if length == 0 then $in"1488 " else .[0]"1489 " | . as $r"1490 // # create the \"capture\" object:1491 " | reduce ( $r | .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair"1492 " ({}; . + $pair)"1493 " | $in[0:$r.offset] + s + $in[$r.offset+$r.length:]"1494 " end ;",1495 //1496 // If s contains capture variables, then create a capture object and pipe it to s1497 "def sub($re; s; flags):"1498 " def subg: explode | select(. != 103) | implode;"1499 // # "fla" should be flags with all occurrences of g removed; gs should be non-nil if flags has a g1500 " def sub1(fla; gs):"1501 " def mysub:"1502 " . as $in"1503 " | [match($re; fla)]"1504 " | if length == 0 then $in"1505 " else .[0] as $edit"1506 " | ($edit | .offset + .length) as $len"1507 // # create the "capture" object:1508 " | reduce ( $edit | .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair"1509 " ({}; . + $pair)"1510 " | $in[0:$edit.offset]"1511 " + s"1512 " + ($in[$len:] | if gs then mysub else . end)"1513 " end ;"1514 " mysub ;"1515 " (flags | index(\"g\")) as $gs"1516 " | (flags | if $gs then subg else . end) as $fla"1517 " | sub1($fla; $gs);",1518 //1519 "def sub($re; s): sub($re; s; \"\");",1520 // repeated substitution of re (which may contain named captures)1521 "def gsub($re; s; flags): sub($re; s; flags + \"g\");",1522 "def gsub($re; s): sub($re; s; \"g\");",15231524 //#######################################################################1525 // range/3, with a `by` expression argument1526 "def range($init; $upto; $by): "1527 " def _range: "1528 " if ($by > 0 and . < $upto) or ($by < 0 and . > $upto) then ., ((.+$by)|_range) else . end; "1529 " if $by == 0 then $init else $init|_range end | select(($by > 0 and . < $upto) or ($by < 0 and . > $upto));",1530 // generic iterator/generator1531 "def while(cond; update): "1532 " def _while: "1533 " if cond then ., (update | _while) else empty end; "1534 " _while;",1535 "def until(cond; next): "1536 " def _until: "1537 " if cond then . else (next|_until) end;"1538 " _until;",1539 "def limit($n; exp): if $n < 0 then exp else label $out | foreach exp as $item ([$n, null]; if .[0] < 1 then break $out else [.[0] -1, $item] end; .[1]) end;",1540 "def first(g): label $out | foreach g as $item ([false, null]; if .[0]==true then break $out else [true, $item] end; .[1]);",1541 "def last(g): reduce g as $item (null; $item);",1542 "def nth($n; g): if $n < 0 then error(\"nth doesn't support negative indices\") else last(limit($n + 1; g)) end;",1543 "def first: .[0];",1544 "def last: .[-1];",1545 "def nth($n): .[$n];",1546 "def combinations:"1547 " if length == 0 then [] else"1548 " .[0][] as $x"1549 " | (.[1:] | combinations) as $y"1550 " | [$x] + $y"1551 " end;",1552 "def combinations(n):"1553 " . as $dot"1554 " | [range(n) | $dot]"1555 " | combinations;",1556 // # transpose a possibly jagged matrix, quickly;1557 // # rows are padded with nulls so the result is always rectangular.1558 "def transpose:"1559 " if . == [] then []"1560 " else . as $in"1561 " | (map(length) | max) as $max"1562 " | length as $length"1563 " | reduce range(0; $max) as $j"1564 " ([]; . + [reduce range(0;$length) as $i ([]; . + [ $in[$i][$j] ] )] )"1565 " end;",1566 "def in(xs): . as $x | xs | has($x);",1567 "def inside(xs): . as $x | xs | contains($x);",1568 "def input: _input;",1569 "def repeat(exp): "1570 " def _repeat: "1571 " exp, _repeat;"1572 " _repeat;",1573 "def inputs: try repeat(_input) catch if .==\"break\" then empty else .|error end;",1574 // # like ruby's downcase - only characters A to Z are affected1575 "def ascii_downcase:"1576 " explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;",1577 // # like ruby's upcase - only characters a to z are affected1578 "def ascii_upcase:"1579 " explode | map( if 97 <= . and . <= 122 then . - 32 else . end) | implode;",15801581 // Streaming utilities1582 "def truncate_stream(stream):"1583 " . as $n | null | stream | . as $input | if (.[0]|length) > $n then setpath([0];$input[0][1:]) else empty end;",1584 "def fromstream(i):"1585 " foreach i as $item ("1586 " [null,false,null,false];"1587 " if ($item[0]|length) == 0 then [null,false,.[2],.[3]]"1588 " elif ($item|length) == 1 and ($item[0]|length) < 2 then [null,false,.[0],.[1]]"1589 " else . end |"1590 " . as $state |"1591 " if ($item|length) > 1 and ($item[0]|length) > 0 then"1592 " [.[0]|setpath(($item|.[0]); ($item|.[1])), "1593 " true, "1594 " $state[2], "1595 " $state[3]] "1596 " else ."1597 " end;"1598 " if ($item[0]|length) == 1 and ($item|length == 1) and .[3] then .[2] else empty end,"1599 " if ($item[0]|length) == 0 then $item[1] else empty end"1600 " );",1601 "def tostream:\n"1602 " {string:true,number:true,boolean:true,null:true} as $leaf_types |\n"1603 " . as $dot |\n"1604 " if $leaf_types[$dot|type] or length==0 then [[],$dot]\n"1605 " else\n"1606 " # We really need a _streaming_ form of `keys`.\n"1607 " # We can use `range` for arrays, but not for objects.\n"1608 " keys as $keys |\n"1609 " $keys[-1] as $last|\n"1610 " ((# for each key\n"1611 " $keys[] | . as $key |\n"1612 " $dot[$key] | . as $dot |\n"1613 " # recurse on each key/value\n"1614 " tostream|.[0]|=[$key]+.),\n"1615 " # then add the closing marker\n"1616 " [[$last]])\n"1617 " end;",161816191620 // # Assuming the input array is sorted, bsearch/1 returns1621 // # the index of the target if the target is in the input array; and otherwise1622 // # (-1 - ix), where ix is the insertion point that would leave the array sorted.1623 // # If the input is not sorted, bsearch will terminate but with irrelevant results.1624 "def bsearch(target):"1625 " if length == 0 then -1"1626 " elif length == 1 then"1627 " if target == .[0] then 0 elif target < .[0] then -1 else -2 end"1628 " else . as $in"1629 "" // # state variable: [start, end, answer]1630 "" // # where start and end are the upper and lower offsets to use.1631 " | [0, length-1, null]"1632 " | until( .[0] > .[1] ;"1633 " if .[2] != null then (.[1] = -1)" // # i.e. break1634 " else"1635 " ( ( (.[1] + .[0]) / 2 ) | floor ) as $mid"1636 " | $in[$mid] as $monkey"1637 " | if $monkey == target then (.[2] = $mid)" // # success1638 " elif .[0] == .[1] then (.[1] = -1)" // # failure1639 " elif $monkey < target then (.[0] = ($mid + 1))"1640 " else (.[1] = ($mid - 1))"1641 " end"1642 " end )"1643 " | if .[2] == null then" // # compute the insertion point1644 " if $in[ .[0] ] < target then (-2 -.[0])"1645 " else (-1 -.[0])"1646 " end"1647 " else .[2]"1648 " end"1649 " end;",16501651 // # Apply f to composite entities recursively, and to atoms1652 "def walk(f):"1653 " . as $in"1654 " | if type == \"object\" then"1655 " reduce keys[] as $key"1656 " ( {}; . + { ($key): ($in[$key] | walk(f)) } ) | f"1657 " elif type == \"array\" then map( walk(f) ) | f"1658 " else f"1659 " end;",1660};16611377#undef LIBM_DDD_NO1378#undef LIBM_DD_NO1379#undef LIBM_DDD1380#undef LIBM_DD
31 unmodified lines
1412 if (nerrors) {1413 block_free(*bb);1414 return nerrors;1415 }1701 for (int i=(int)(sizeof(jq_builtins)/sizeof(jq_builtins[0]))-1; i>=0; i--) {1702 nerrors = builtins_bind_one(jq, bb, jq_builtins[i]);1703 assert(!nerrors);1416 nerrors = builtins_bind_one(jq, bb, jq_builtins);1417 assert(!nerrors);1704 }1418 *bb = bind_bytecoded_builtins(*bb);1419 *bb = gen_cbinding(function_list, sizeof(function_list)/sizeof(function_list[0]), *bb);1420 return nerrors;1421}
added:src/builtin.jq+286 added
1def error: error(.);2def map(f): [.[] | f];3def select(f): if f then . else empty end;4def sort_by(f): _sort_by_impl(map([f]));5def group_by(f): _group_by_impl(map([f]));6def unique: group_by(.) | map(.[0]);7def unique_by(f): group_by(f) | map(.[0]);8def max_by(f): _max_by_impl(map([f]));9def min_by(f): _min_by_impl(map([f]));10def add: reduce .[] as $x (null; . + $x);11def del(f): delpaths([path(f)]);12def _assign(paths; value): value as $v | reduce path(paths) as $p (.; setpath($p; $v));13def _modify(paths; update): reduce path(paths) as $p (.; setpath($p; getpath($p) | update));14def map_values(f): .[] |= f;1516# recurse17def recurse(f): def r: ., (f | select(. != null) | r); r;18def recurse(f; cond): def r: ., (f | select(cond) | r); r;19def recurse: recurse(.[]?);20def recurse_down: recurse;2122def to_entries: [keys_unsorted[] as $k | {key: $k, value: .[$k]}];23def from_entries: map({(.key // .Key // .name // .Name): (if has("value") then .value else .Value end)}) | add | .//={};24def with_entries(f): to_entries | map(f) | from_entries;25def reverse: [.[length - 1 - range(0;length)]];26def indices($i): if type == "array" and ($i|type) == "array" then .[$i]27 elif type == "array" then .[[$i]]28 elif type == "string" and ($i|type) == "string" then _strindices($i)29 else .[$i] end;30def index($i): indices($i) | .[0]; # TODO: optimize31def rindex($i): indices($i) | .[-1:][0]; # TODO: optimize32def paths: path(recurse(if (type|. == "array" or . == "object") then .[] else empty end))|select(length > 0);33def paths(node_filter): . as $dot|paths|select(. as $p|$dot|getpath($p)|node_filter);34def any(generator; condition):35 [label $out | foreach generator as $i36 (false;37 if . then break $out elif $i | condition then true else . end;38 if . then . else empty end)] | length == 1;39def any(condition): any(.[]; condition);40def any: any(.);41def all(generator; condition):42 [label $out | foreach generator as $i43 (true;44 if .|not then break $out elif $i | condition then . else false end;45 if .|not then . else empty end)] | length == 0;46def all(condition): all(.[]; condition);47def all: all(.);48def isfinite: type == "number" and (isinfinite | not);49def arrays: select(type == "array");50def objects: select(type == "object");51def iterables: arrays, objects;52def booleans: select(type == "boolean");53def numbers: select(type == "number");54def normals: select(isnormal);55def finites: select(isfinite);56def strings: select(type == "string");57def nulls: select(type == "null");58def values: select(. != null);59def scalars: select(. == null or . == true or . == false or type == "number" or type == "string");60def scalars_or_empty: select(. == null or . == true or . == false or type == "number" or type == "string" or ((type=="array" or type=="object") and length==0));61def leaf_paths: paths(scalars);62def join($x): reduce .[] as $i (null; (.//"") + (if . == null then $i else $x + $i end))//"";63def _flatten($x): reduce .[] as $i ([]; if $i | type == "array" and $x != 0 then . + ($i | _flatten($x-1)) else . + [$i] end);64def flatten($x): if $x < 0 then error("flatten depth must not be negative") else _flatten($x) end;65def flatten: _flatten(-1);66def range($x): range(0;$x);67def fromdateiso8601: strptime("%Y-%m-%dT%H:%M:%SZ")|mktime;68def todateiso8601: strftime("%Y-%m-%dT%H:%M:%SZ");69def fromdate: fromdateiso8601;70def todate: todateiso8601;71def match(re; mode): _match_impl(re; mode; false)|.[];72def match($val): ($val|type) as $vt | if $vt == "string" then match($val; null)73 elif $vt == "array" and ($val | length) > 1 then match($val[0]; $val[1])74 elif $vt == "array" and ($val | length) > 0 then match($val[0]; null)75 else error( $vt + " not a string or array") end;76def test(re; mode): _match_impl(re; mode; true);77def test($val): ($val|type) as $vt | if $vt == "string" then test($val; null)78 elif $vt == "array" and ($val | length) > 1 then test($val[0]; $val[1])79 elif $vt == "array" and ($val | length) > 0 then test($val[0]; null)80 else error( $vt + " not a string or array") end;81def capture(re; mods): match(re; mods) | reduce ( .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair ({}; . + $pair);82def capture($val): ($val|type) as $vt | if $vt == "string" then capture($val; null)83 elif $vt == "array" and ($val | length) > 1 then capture($val[0]; $val[1])84 elif $vt == "array" and ($val | length) > 0 then capture($val[0]; null)85 else error( $vt + " not a string or array") end;86def scan(re):87 match(re; "g")88 | if (.captures|length > 0)89 then [ .captures | .[] | .string ]90 else .string91 end ;92#93# If input is an array, then emit a stream of successive subarrays of length n (or less),94# and similarly for strings.95def _nwise(a; $n): if a|length <= $n then a else a[0:$n] , _nwise(a[$n:]; $n) end;96def _nwise($n): _nwise(.; $n);97#98# splits/1 produces a stream; split/1 is retained for backward compatibility.99def splits($re; flags): . as $s100# # multiple occurrences of "g" are acceptable101 | [ match($re; "g" + flags) | (.offset, .offset + .length) ]102 | [0] + . +[$s|length]103 | _nwise(2)104 | $s[.[0]:.[1] ] ;105def splits($re): splits($re; null);106#107# split emits an array for backward compatibility108def split($re; flags): [ splits($re; flags) ];109#110# If s contains capture variables, then create a capture object and pipe it to s111def sub($re; s):112 . as $in113 | [match($re)]114 | if length == 0 then $in115 else .[0]116 | . as $r117# # create the "capture" object:118 | reduce ( $r | .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair119 ({}; . + $pair)120 | $in[0:$r.offset] + s + $in[$r.offset+$r.length:]121 end ;122#123# If s contains capture variables, then create a capture object and pipe it to s124def sub($re; s; flags):125 def subg: explode | select(. != 103) | implode;126# "fla" should be flags with all occurrences of g removed; gs should be non-nil if flags has a g127 def sub1(fla; gs):128 def mysub:129 . as $in130 | [match($re; fla)]131 | if length == 0 then $in132 else .[0] as $edit133 | ($edit | .offset + .length) as $len134# # create the "capture" object:135 | reduce ( $edit | .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair136 ({}; . + $pair)137 | $in[0:$edit.offset]138 + s139 + ($in[$len:] | if gs then mysub else . end)140 end ;141 mysub ;142 (flags | index("g")) as $gs143 | (flags | if $gs then subg else . end) as $fla144 | sub1($fla; $gs);145#146def sub($re; s): sub($re; s; "");147# repeated substitution of re (which may contain named captures)148def gsub($re; s; flags): sub($re; s; flags + "g");149def gsub($re; s): sub($re; s; "g");150151########################################################################152# range/3, with a `by` expression argument153def range($init; $upto; $by):154 def _range:155 if ($by > 0 and . < $upto) or ($by < 0 and . > $upto) then ., ((.+$by)|_range) else . end;156 if $by == 0 then $init else $init|_range end | select(($by > 0 and . < $upto) or ($by < 0 and . > $upto));157# generic iterator/generator158def while(cond; update):159 def _while:160 if cond then ., (update | _while) else empty end;161 _while;162def until(cond; next):163 def _until:164 if cond then . else (next|_until) end;165 _until;166def limit($n; exp): if $n < 0 then exp else label $out | foreach exp as $item ([$n, null]; if .[0] < 1 then break $out else [.[0] -1, $item] end; .[1]) end;167def first(g): label $out | foreach g as $item ([false, null]; if .[0]==true then break $out else [true, $item] end; .[1]);168def last(g): reduce g as $item (null; $item);169def nth($n; g): if $n < 0 then error("nth doesn't support negative indices") else last(limit($n + 1; g)) end;170def first: .[0];171def last: .[-1];172def nth($n): .[$n];173def combinations:174 if length == 0 then [] else175 .[0][] as $x176 | (.[1:] | combinations) as $y177 | [$x] + $y178 end;179def combinations(n):180 . as $dot181 | [range(n) | $dot]182 | combinations;183# transpose a possibly jagged matrix, quickly;184# rows are padded with nulls so the result is always rectangular.185def transpose:186 if . == [] then []187 else . as $in188 | (map(length) | max) as $max189 | length as $length190 | reduce range(0; $max) as $j191 ([]; . + [reduce range(0;$length) as $i ([]; . + [ $in[$i][$j] ] )] )192 end;193def in(xs): . as $x | xs | has($x);194def inside(xs): . as $x | xs | contains($x);195def input: _input;196def repeat(exp):197 def _repeat:198 exp, _repeat;199 _repeat;200def inputs: try repeat(_input) catch if .=="break" then empty else .|error end;201# like ruby's downcase - only characters A to Z are affected202def ascii_downcase:203 explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;204# like ruby's upcase - only characters a to z are affected205def ascii_upcase:206 explode | map( if 97 <= . and . <= 122 then . - 32 else . end) | implode;207208# Streaming utilities209def truncate_stream(stream):210 . as $n | null | stream | . as $input | if (.[0]|length) > $n then setpath([0];$input[0][1:]) else empty end;211def fromstream(i):212 foreach i as $item (213 [null,false,null,false];214 if ($item[0]|length) == 0 then [null,false,.[2],.[3]]215 elif ($item|length) == 1 and ($item[0]|length) < 2 then [null,false,.[0],.[1]]216 else . end |217 . as $state |218 if ($item|length) > 1 and ($item[0]|length) > 0 then219 [.[0]|setpath(($item|.[0]); ($item|.[1])),220 true,221 $state[2],222 $state[3]]223 else .224 end;225 if ($item[0]|length) == 1 and ($item|length == 1) and .[3] then .[2] else empty end,226 if ($item[0]|length) == 0 then $item[1] else empty end227 );228def tostream:229 {string:true,number:true,boolean:true,null:true} as $leaf_types |230 . as $dot |231 if $leaf_types[$dot|type] or length==0 then [[],$dot]232 else233 # We really need a _streaming_ form of `keys`.234 # We can use `range` for arrays, but not for objects.235 keys as $keys |236 $keys[-1] as $last|237 ((# for each key238 $keys[] | . as $key |239 $dot[$key] | . as $dot |240 # recurse on each key/value241 tostream|.[0]|=[$key]+.),242 # then add the closing marker243 [[$last]])244 end;245246247# Assuming the input array is sorted, bsearch/1 returns248# the index of the target if the target is in the input array; and otherwise249# (-1 - ix), where ix is the insertion point that would leave the array sorted.250# If the input is not sorted, bsearch will terminate but with irrelevant results.251def bsearch(target):252 if length == 0 then -1253 elif length == 1 then254 if target == .[0] then 0 elif target < .[0] then -1 else -2 end255 else . as $in256 # state variable: [start, end, answer]257 # where start and end are the upper and lower offsets to use.258 | [0, length-1, null]259 | until( .[0] > .[1] ;260 if .[2] != null then (.[1] = -1) # i.e. break261 else262 ( ( (.[1] + .[0]) / 2 ) | floor ) as $mid263 | $in[$mid] as $monkey264 | if $monkey == target then (.[2] = $mid) # success265 elif .[0] == .[1] then (.[1] = -1) # failure266 elif $monkey < target then (.[0] = ($mid + 1))267 else (.[1] = ($mid - 1))268 end269 end )270 | if .[2] == null then # compute the insertion point271 if $in[ .[0] ] < target then (-2 -.[0])272 else (-1 -.[0])273 end274 else .[2]275 end276 end;277278# Apply f to composite entities recursively, and to atoms279def walk(f):280 . as $in281 | if type == "object" then282 reduce keys[] as $key283 ( {}; . + { ($key): ($in[$key] | walk(f)) } ) | f284 elif type == "array" then map( walk(f) ) | f285 else f286 end;
modified:.gitignore+3 added
14 unmodified lines
15jq16!tests/modules/lib/jq/17jq.11819# Generated source20src/builtin.inc2122# Autotools junk23.libs24.deps25.dirstamp
26 unmodified lines
modified:Makefile.am+4 added
84 unmodified lines
85src/version.h: .remake-version-h86 $(AM_V_GEN) $(generate_ver); echo "$$ver" > $@87src/main.c: src/version.h8889src/builtin.inc: src/builtin.jq90 $(AM_V_GEN) sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' -e 's/$$/\\n"/' $^ > $@91src/main.c: src/builtin.inc9293bin_PROGRAMS = jq94jq_SOURCES = src/main.c src/version.h95jq_LDFLAGS = -static-libtool-libs96jq_LDADD = libjq.la -lm
84 unmodified lines