Module: Rjq::Builtins
- Defined in:
- lib/rjq/builtins.rb
Constant Summary collapse
- ZERO_ARITY_BUILTINS =
%w[ empty length utf8bytelength type keys keys_unsorted values arrays objects iterables scalars booleans nulls numbers strings not error halt halt_error input inputs debug stderr input_filename input_line_number null true false infinite nan isinfinite isnan isnormal add any all flatten floor ceil round sqrt log log2 log10 exp exp2 exp10 pow10 atan abs cos sin tan acos asin cosh sinh tanh acosh asinh atanh cbrt significand logb gamma tgamma lgamma lgamma_r frexp modf fabs nearbyint trunc rint j0 j1 y0 y1 erf erfc expm1 log1p isfinite finites normals get_jq_origin get_prog_origin get_search_list to_entries from_entries to_number tonumber tostring tojson fromjson ascii explode implode ascii_downcase ascii_upcase recurse recurse_down paths leaf_paths tostream min max sort unique reverse combinations transpose first last env now gmtime localtime mktime fromdate todate fromdateiso8601 todateiso8601 date builtins modulemeta ].freeze
- ONE_ARITY_BUILTINS =
%w[ has in IN INDEX error halt_error debug flatten range any all with_entries select map map_values split join ltrimstr rtrimstr startswith endswith index rindex indices recurse recurse_down path paths leaf_paths getpath delpaths del pick walk fromstream truncate_stream min_by max_by sort_by group_by GROUP_BY unique_by UNIQUE_BY contains inside combinations bsearch first last nth repeat isempty strftime strflocaltime strptime dateadd datesub test match capture scan splits format ].freeze
- TWO_ARITY_BUILTINS =
%w[ IN INDEX JOIN any all range recurse recurse_down pow atan2 ldexp scalb scalbln drem setpath nth limit until while split test match scan splits sub gsub capture copysign fdim fmax fmin fmod hypot jn nextafter nexttoward remainder yn ].freeze
- THREE_ARITY_BUILTINS =
%w[JOIN range fma sub gsub].freeze
- FOUR_ARITY_BUILTINS =
%w[JOIN].freeze
- BUILTIN_ARITIES =
[ [0, ZERO_ARITY_BUILTINS], [1, ONE_ARITY_BUILTINS], [2, TWO_ARITY_BUILTINS], [3, THREE_ARITY_BUILTINS], [4, FOUR_ARITY_BUILTINS] ].each_with_object({}) do |(arity, names), registry| names.each { |name| (registry[name] ||= []) << arity } end.transform_values(&:freeze).freeze
- BUILTIN_NAMES =
BUILTIN_ARITIES.keys.freeze
- EXTENSION_NAMES =
%w[ GROUP_BY UNIQUE_BY ascii date dateadd datesub false leaf_paths null recurse_down to_number true ].freeze
- JQ_BUILTIN_NAMES =
(BUILTIN_NAMES - EXTENSION_NAMES).freeze
- EXTENSION_ARITIES =
EXTENSION_NAMES.to_h { |name| [name, BUILTIN_ARITIES.fetch(name)] }.freeze
- FORMAT_NAMES =
%w[@text @json @html @uri @csv @tsv @sh @base64 @base64d @base32 @base32d].freeze
- REGISTRY =
BUILTIN_NAMES.to_h { |name| [name, true] }.freeze
- FILTER_ARGUMENT_POSITIONS =
{ 'IN' => [0, 1], 'INDEX' => [0, 1], 'JOIN' => [1, 2, 3], 'any' => [0, 1], 'all' => [0, 1], 'with_entries' => [0], 'select' => [0], 'map' => [0], 'map_values' => [0], 'recurse' => [0, 1], 'recurse_down' => [0, 1], 'path' => [0], 'paths' => [0], 'leaf_paths' => [0], 'del' => [0], 'pick' => [0], 'walk' => [0], 'fromstream' => [0], 'truncate_stream' => [0], 'min_by' => [0], 'max_by' => [0], 'sort_by' => [0], 'group_by' => [0], 'GROUP_BY' => [0], 'unique_by' => [0], 'UNIQUE_BY' => [0], 'first' => [0], 'last' => [0], 'nth' => [0, 1], 'limit' => [1], 'until' => [0, 1], 'while' => [0, 1], 'repeat' => [0], 'isempty' => [0], 'split' => [1], 'splits' => [1], 'sub' => [1], 'gsub' => [1] }.transform_values(&:freeze).freeze
- LEFT_OUTER_ARGUMENT_BUILTINS =
%w[gsub range scan split splits sub].freeze
- FLATTEN_UNBOUNDED =
Object.new.freeze
Class Method Summary collapse
- .absolute(value) ⇒ Object
- .add(value) ⇒ Object
- .all?(input, context, args) ⇒ Boolean
- .any?(input, context, args) ⇒ Boolean
- .array_slice_equal?(input, needle, index) ⇒ Boolean
- .assert_array(value) ⇒ Object
- .assert_string(value) ⇒ Object
- .base32_decode(input) ⇒ Object
- .base32_encode(input) ⇒ Object
- .bsearch(input, context, args) ⇒ Object
- .builtin_arities(name) ⇒ Object
- .call(name, input, context, args) ⇒ Object
- .call_stream(name, input, context, args) ⇒ Object
- .capture_builtin(input, context, args) ⇒ Object
- .capture_name(match, index) ⇒ Object
- .capture_values(match) ⇒ Object
- .cartesian(sets) ⇒ Object
- .collect_filter(filter, input, context) ⇒ Object
- .collect_paths(filter, input, context) ⇒ Object
- .combination_array(value) ⇒ Object
- .combinations(input, context, args) ⇒ Object
- .consume_regexp_character_class(chars, index) ⇒ Object
- .container_for_path(path) ⇒ Object
- .contains?(container, contained) ⇒ Boolean
- .copy_sign(magnitude, sign) ⇒ Object
- .csv_field(item) ⇒ Object
- .current_input_record(context) ⇒ Object
- .decode_base64(input) ⇒ Object
- .decorated_sort(input, context, filter) ⇒ Object
- .delete_paths(input, context, args) ⇒ Object
- .delpaths(input, paths) ⇒ Object
- .dispatch(name, input, context, args) ⇒ Object
- .each_resolved_argument_set(name, args, input, context, &block) ⇒ Object
- .emit_diagnostic(name, input, context, args) ⇒ Object
- .eval_arg(args, index, input, context) ⇒ Object
- .extreme(input, mode) ⇒ Object
- .extreme_by(input, context, filter, mode) ⇒ Object
- .filter_key(value, context, filter) ⇒ Object
- .filter_stream(filter, input, context) ⇒ Object
- .first_builtin(input, context, args) ⇒ Object
- .flatten(value, depth = FLATTEN_UNBOUNDED) ⇒ Object
- .flatten_items(items, depth) ⇒ Object
- .float_extreme(left, right, mode) ⇒ Object
- .format_builtin(input, context, args) ⇒ Object
- .format_csv(input) ⇒ Object
- .format_sh(input) ⇒ Object
- .format_tsv(input) ⇒ Object
- .from_entries(entries) ⇒ Object
- .from_stream(stream) ⇒ Object
- .group_by_filter(input, context, filter) ⇒ Object
- .gsub_with_filter(string, regex, replacement_filter, context) ⇒ Object
- .has?(container, key) ⇒ Boolean
- .html_escape(input) ⇒ Object
- .ieee_remainder(left, right) ⇒ Object
- .implode(input) ⇒ Object
- .in_sql?(input, context, args) ⇒ Boolean
- .index_of(input, needle) ⇒ Object
- .index_sql(input, context, args) ⇒ Object
- .indices_of(input, needle) ⇒ Object
- .input_builtin(context) ⇒ Object
- .input_values(input, context, filter) ⇒ Object
- .inputs_builtin(context) ⇒ Object
- .iterable_values(input) ⇒ Object
- .join(input, separator) ⇒ Object
- .join_sql(input, context, args) ⇒ Object
- .jq_regexp_pattern(pattern, dot_matches_newline:) ⇒ Object
- .keys(value, sorted:) ⇒ Object
- .last_builtin(input, context, args) ⇒ Object
- .length(value) ⇒ Object
- .limit(input, context, args) ⇒ Object
- .map_entries(input, context, filter) ⇒ Object
- .map_filter(value, context, filter) ⇒ Object
- .map_values(value, context, filter) ⇒ Object
- .match_builtin(input, context, args) ⇒ Object
- .match_object(match) ⇒ Object
- .matches_for_regexp(input, context, args, string) ⇒ Object
- .math_nary(name, input, context, args) ⇒ Object
- .math_unary(name, input) ⇒ Object
- .mktime(input) ⇒ Object
- .modulemeta(input, context) ⇒ Object
- .next_float_toward(value, target) ⇒ Object
- .normal_number?(value) ⇒ Boolean
- .nth(input, context, args) ⇒ Object
- .nth_filter_index(value) ⇒ Object
- .nth_index_value(input, raw_index) ⇒ Object
- .numeric(value) ⇒ Object
- .option_state(current, enabled, disabled, option) ⇒ Object
- .ordered_delete_paths(paths) ⇒ Object
- .paths_builtin(input, context, args, leaves_only:) ⇒ Object
- .pick(input, context, args) ⇒ Object
- .range(input, context, args) ⇒ Object
- .range_values(from, to, step) ⇒ Object
- .recurse(input, context, args) ⇒ Object
- .regexp(input, context, args) ⇒ Object
- .regexp_matches(input, context, args, string) ⇒ Object
- .regexp_parts(input, context, args) ⇒ Object
- .repeat_filter(input, context, args) ⇒ Object
- .replacement_filters(node) ⇒ Object
- .replacements_for(replacement_filter, match, context) ⇒ Object
- .resolve_argument_indices(name, args, indices, input, context, resolved, &block) ⇒ Object
- .rindex_of(input, needle) ⇒ Object
- .round_to_even(value) ⇒ Object
- .ruby_regexp_group(enabled, disabled, parent_dotall, child_dotall, body) ⇒ Object
- .scan_builtin(input, context, args) ⇒ Object
- .scoped_regexp_options(chars, index) ⇒ Object
- .search_list(context) ⇒ Object
- .select(input, context, filter) ⇒ Object
- .sh_quote(input) ⇒ Object
- .short_dump(value) ⇒ Object
- .sort_by_filter(input, context, filter) ⇒ Object
- .source_all?(node, input, context) ⇒ Boolean
- .source_any?(node, input, context) ⇒ Boolean
- .split(input, context, args) ⇒ Object
- .split_at_matches(string, matches) ⇒ Object
- .splits_builtin(input, context, args) ⇒ Object
- .strftime_builtin(input, context, args, local: false) ⇒ Object
- .strptime(input, context, args) ⇒ Object
- .sub_with_filter(string, regex, replacement_filter, context) ⇒ Object
- .substitute(input, context, args, global:) ⇒ Object
- .subtract_flatten_depth(depth) ⇒ Object
- .time_array(time) ⇒ Object
- .to_entries(value) ⇒ Object
- .to_number(value) ⇒ Object
- .to_stream(value) ⇒ Object
- .to_string(value) ⇒ Object
- .transform_regexp_segment(chars, index, line_anchors:, dot_matches_newline:, stop_at_group_end: false) ⇒ Object
- .transpose(input) ⇒ Object
- .truncate_boundary(depth, length) ⇒ Object
- .truncate_path(path, depth) ⇒ Object
- .truncate_stream(input, context, args) ⇒ Object
- .unique_by_filter(input, context, filter) ⇒ Object
- .unique_values(array) ⇒ Object
- .unsupported_search_result(input, needle) ⇒ Object
- .until_filter(input, context, args) ⇒ Object
- .uri_escape(input) ⇒ Object
- .utf8_byte_length(value) ⇒ Object
- .valid_arity?(name, arity) ⇒ Boolean
- .validate_pick_path(path) ⇒ Object
- .validate_string_search_needle(input, needle) ⇒ Object
- .walk(input, context, filter) ⇒ Object
- .while_filter(input, context, args) ⇒ Object
Class Method Details
.absolute(value) ⇒ Object
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 |
# File 'lib/rjq/builtins.rb', line 630 def absolute(value) if value.nil? || value == true || value == false raise TypeError, "#{Value.type_of(value)} (#{JSON::Dumper.dump(value, indent: nil)}) cannot be negated" end return value unless value.is_a?(Numeric) if value.is_a?(Number) return value unless value.literal.start_with?('-') return value if value.literal.match?(/\A-0+(?:\.0+)?(?:[eE][+-]?\d+)?\z/) return value.to_f.abs end return value if value.zero? || !value.negative? value.abs end |
.add(value) ⇒ Object
482 483 484 485 486 |
# File 'lib/rjq/builtins.rb', line 482 def add(value) assert_array(value).reduce(nil) do |sum, item| sum.nil? ? item : AST::BinaryOp.new(AST::Literal.new(sum), '+', AST::Literal.new(item)).eval(nil, AST::Context.new).first end end |
.all?(input, context, args) ⇒ Boolean
499 500 501 502 503 504 505 506 507 508 |
# File 'lib/rjq/builtins.rb', line 499 def all?(input, context, args) if args.length == 2 return source_all?(args[0], input, context) do |value| source_all?(args[1], value, context) { |result| Value.truthy?(result) } end end values = args.empty? ? iterable_values(input) : input_values(input, context, args.first) values.all? { |value| Value.truthy?(value) } end |
.any?(input, context, args) ⇒ Boolean
488 489 490 491 492 493 494 495 496 497 |
# File 'lib/rjq/builtins.rb', line 488 def any?(input, context, args) if args.length == 2 return source_any?(args[0], input, context) do |value| source_any?(args[1], value, context) { |result| Value.truthy?(result) } end end values = args.empty? ? iterable_values(input) : input_values(input, context, args.first) values.any? { |value| Value.truthy?(value) } end |
.array_slice_equal?(input, needle, index) ⇒ Boolean
1305 1306 1307 |
# File 'lib/rjq/builtins.rb', line 1305 def array_slice_equal?(input, needle, index) needle.each_with_index.all? { |item, offset| Value.equal?(input[index + offset], item) } end |
.assert_array(value) ⇒ Object
2085 2086 2087 2088 2089 |
# File 'lib/rjq/builtins.rb', line 2085 def assert_array(value) raise TypeError, "expected array, got #{Value.type_of(value)}" unless value.is_a?(Array) value end |
.assert_string(value) ⇒ Object
2091 2092 2093 2094 2095 |
# File 'lib/rjq/builtins.rb', line 2091 def assert_string(value) raise TypeError, "expected string, got #{Value.type_of(value)}" unless value.is_a?(String) value end |
.base32_decode(input) ⇒ Object
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 |
# File 'lib/rjq/builtins.rb', line 1945 def base32_decode(input) alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' clean = input.upcase.delete('=') output = +''.b buffer = 0 bits = 0 clean.each_char do |char| index = alphabet.index(char) raise RuntimeError, "invalid base32 character #{char.inspect}" unless index buffer = (buffer << 5) | index bits += 5 if bits >= 8 bits -= 8 output << ((buffer >> bits) & 0xFF) buffer &= (1 << bits) - 1 end end output end |
.base32_encode(input) ⇒ Object
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 |
# File 'lib/rjq/builtins.rb', line 1920 def base32_encode(input) alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' encoded = +'' buffer = 0 bits = 0 input.each_byte do |byte| buffer = (buffer << 8) | byte bits += 8 while bits >= 5 bits -= 5 encoded << alphabet[(buffer >> bits) & 31] end buffer &= (1 << bits) - 1 end encoded << alphabet[(buffer << (5 - bits)) & 31] if bits.positive? encoded + ('=' * ((8 - (encoded.length % 8)) % 8)) end |
.bsearch(input, context, args) ⇒ Object
1341 1342 1343 1344 1345 1346 1347 1348 1349 |
# File 'lib/rjq/builtins.rb', line 1341 def bsearch(input, context, args) array = assert_array(input) args.flat_map do |arg| arg.eval(input, context).map do |needle| found = array.bsearch_index { |item| Value.compare(item, needle) >= 0 } found && Value.equal?(array[found], needle) ? found : -((found || array.length) + 1) end end end |
.builtin_arities(name) ⇒ Object
2070 2071 2072 |
# File 'lib/rjq/builtins.rb', line 2070 def builtin_arities(name) BUILTIN_ARITIES.fetch(name, []).map { |arity| "#{name}/#{arity}" } end |
.call(name, input, context, args) ⇒ Object
67 68 69 |
# File 'lib/rjq/builtins.rb', line 67 def call(name, input, context, args) call_stream(name, input, context, args).to_a end |
.call_stream(name, input, context, args) ⇒ Object
71 72 73 74 75 76 77 |
# File 'lib/rjq/builtins.rb', line 71 def call_stream(name, input, context, args) Enumerator.new do |yielder| each_resolved_argument_set(name, args, input, context) do |resolved_args| dispatch(name, input, context, resolved_args).each { |value| yielder << value } end end end |
.capture_builtin(input, context, args) ⇒ Object
1788 1789 1790 1791 1792 1793 1794 |
# File 'lib/rjq/builtins.rb', line 1788 def capture_builtin(input, context, args) regex, = regexp(input, context, args) match = regex.match(assert_string(input)) return [] unless match [match.names.to_h { |name| [name, match[name]] }] end |
.capture_name(match, index) ⇒ Object
1784 1785 1786 |
# File 'lib/rjq/builtins.rb', line 1784 def capture_name(match, index) match.names.find { |name| match.regexp.named_captures.fetch(name).include?(index) } end |
.capture_values(match) ⇒ Object
1858 1859 1860 |
# File 'lib/rjq/builtins.rb', line 1858 def capture_values(match) match.names.to_h { |name| [name, match[name]] } end |
.cartesian(sets) ⇒ Object
569 570 571 572 573 574 575 |
# File 'lib/rjq/builtins.rb', line 569 def cartesian(sets) return [[]] if sets.empty? sets.reduce([[]]) do |acc, values| acc.flat_map { |prefix| values.map { |value| prefix + [value] } } end end |
.collect_filter(filter, input, context) ⇒ Object
2048 2049 2050 2051 2052 2053 |
# File 'lib/rjq/builtins.rb', line 2048 def collect_filter(filter, input, context) filter_stream(filter, input, context).to_a rescue Rjq::RuntimeError => e e.take_outputs raise end |
.collect_paths(filter, input, context) ⇒ Object
2016 2017 2018 2019 2020 2021 |
# File 'lib/rjq/builtins.rb', line 2016 def collect_paths(filter, input, context) filter.paths(input, context) rescue Rjq::RuntimeError => e e.take_outputs raise end |
.combination_array(value) ⇒ Object
1334 1335 1336 1337 1338 1339 |
# File 'lib/rjq/builtins.rb', line 1334 def combination_array(value) return value if value.is_a?(Array) raise TypeError, "Cannot iterate over #{Value.type_of(value)} (#{JSON::Dumper.dump(value, indent: nil)})" end |
.combinations(input, context, args) ⇒ Object
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 |
# File 'lib/rjq/builtins.rb', line 1309 def combinations(input, context, args) if args.length == 1 raw_count = eval_arg(args, 0, input, context) raise RuntimeError, 'Range bounds must be numeric' unless raw_count.is_a?(Numeric) count = raw_count.ceil return [[]] if count.negative? arrays = Array.new(count) { combination_array(input) } else source = args.empty? ? assert_array(input) : eval_arg(args, 0, input, context) arrays = assert_array(source) end arrays.reduce([[]]) do |acc, array| assert_array(array) acc.flat_map { |prefix| array.map { |item| prefix + [item] } } end end |
.consume_regexp_character_class(chars, index) ⇒ Object
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 |
# File 'lib/rjq/builtins.rb', line 1636 def consume_regexp_character_class(chars, index) output = +'[' index += 1 if chars[index] == '^' output << '^' index += 1 end if chars[index] == ']' output << '\\]' index += 1 end while index < chars.length char = chars[index] if char == '\\' output << char index += 1 output << chars[index] if index < chars.length elsif char == '[' && %w[: . =].include?(chars[index + 1]) marker = chars[index + 1] closing = "#{marker}]" while index < chars.length output << chars[index] index += 1 next unless output.end_with?(closing) break end next elsif char == ']' output << char return [output, index + 1] else output << char end index += 1 end [output, index] end |
.container_for_path(path) ⇒ Object
924 925 926 |
# File 'lib/rjq/builtins.rb', line 924 def container_for_path(path) path.first.is_a?(Numeric) ? [] : {} end |
.contains?(container, contained) ⇒ Boolean
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 |
# File 'lib/rjq/builtins.rb', line 1151 def contains?(container, contained) tasks = [[:evaluate, container, contained]] results = [] until tasks.empty? action, *values = tasks.pop case action when :evaluate candidate, needle = values if candidate.is_a?(Hash) && needle.is_a?(Hash) entries = needle.to_a unless entries.all? { |key, _value| candidate.key?(key) } results << false next end tasks << [:hash_all, candidate, entries, 0] elsif candidate.is_a?(Array) && needle.is_a?(Array) tasks << [:array_all, candidate, needle, 0] elsif candidate.is_a?(String) && needle.is_a?(String) results << candidate.include?(needle) else results << Value.equal?(candidate, needle) end when :hash_all candidate, entries, index = values if index >= entries.length results << true else key, needle = entries[index] tasks << [:hash_after, candidate, entries, index] tasks << [:evaluate, candidate.fetch(key), needle] end when :hash_after candidate, entries, index = values if results.pop tasks << [:hash_all, candidate, entries, index + 1] else results << false end when :array_all candidate, needles, needle_index = values if needle_index >= needles.length results << true elsif candidate.empty? results << false else tasks << [:array_all_after, candidate, needles, needle_index] tasks << [:array_any, candidate, needles.fetch(needle_index), 0] end when :array_all_after candidate, needles, needle_index = values if results.pop tasks << [:array_all, candidate, needles, needle_index + 1] else results << false end when :array_any candidate, needle, candidate_index = values if candidate_index >= candidate.length results << false else tasks << [:array_any_after, candidate, needle, candidate_index] tasks << [:evaluate, candidate.fetch(candidate_index), needle] end when :array_any_after candidate, needle, candidate_index = values if results.pop results << true else tasks << [:array_any, candidate, needle, candidate_index + 1] end end end results.fetch(0) end |
.copy_sign(magnitude, sign) ⇒ Object
682 683 684 685 |
# File 'lib/rjq/builtins.rb', line 682 def copy_sign(magnitude, sign) negative = sign.to_f.negative? || (sign.to_f.zero? && (1.0 / sign.to_f).negative?) negative ? -magnitude.to_f.abs : magnitude.to_f.abs end |
.csv_field(item) ⇒ Object
1875 1876 1877 1878 1879 1880 1881 1882 1883 |
# File 'lib/rjq/builtins.rb', line 1875 def csv_field(item) return '' if item.nil? return to_string(item) if item.is_a?(Numeric) || item == true || item == false unless item.is_a?(String) raise TypeError, "#{Value.type_of(item)} (#{short_dump(item)}) is not valid in a csv row" end "\"#{item.gsub('"', '""')}\"" end |
.current_input_record(context) ⇒ Object
467 468 469 |
# File 'lib/rjq/builtins.rb', line 467 def current_input_record(context) context.[:input_queue]&.current_record end |
.decode_base64(input) ⇒ Object
1938 1939 1940 1941 1942 1943 |
# File 'lib/rjq/builtins.rb', line 1938 def decode_base64(input) string = assert_string(input) string.unpack1('m0').force_encoding(Encoding::UTF_8) rescue ArgumentError raise RuntimeError, "string (#{JSON::Dumper.dump(input, indent: nil)}) is not valid base64 data" end |
.decorated_sort(input, context, filter) ⇒ Object
1103 1104 1105 1106 1107 1108 1109 1110 |
# File 'lib/rjq/builtins.rb', line 1103 def decorated_sort(input, context, filter) assert_array(input).each_with_index.map do |item, index| [item, filter_key(item, context, filter), index] end.sort do |left, right| comparison = Value.compare(left[1], right[1]) comparison.zero? ? left[2] <=> right[2] : comparison end end |
.delete_paths(input, context, args) ⇒ Object
896 897 898 899 900 901 902 903 |
# File 'lib/rjq/builtins.rb', line 896 def delete_paths(input, context, args) copy = Value.deep_copy(input) paths = args.flat_map { |arg| collect_paths(arg, input, context) } return nil if paths.any?(&:empty?) ordered_delete_paths(paths).each { |path| Path.delete(copy, path) } copy end |
.delpaths(input, paths) ⇒ Object
886 887 888 889 890 891 892 893 894 |
# File 'lib/rjq/builtins.rb', line 886 def delpaths(input, paths) raise TypeError, 'Paths must be specified as an array' unless paths.is_a?(Array) copy = Value.deep_copy(input) return nil if paths.any?(&:empty?) ordered_delete_paths(paths).each { |path| Path.delete(copy, path) } copy end |
.dispatch(name, input, context, args) ⇒ Object
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
# File 'lib/rjq/builtins.rb', line 79 def dispatch(name, input, context, args) return call(name, args.fetch(0).eval(input, context).first, context, []) if name.start_with?('@') && !args.empty? case name when 'empty' [] when 'length' [length(input)] when 'utf8bytelength' [utf8_byte_length(input)] when 'type' [Value.type_of(input)] when 'keys' [keys(input, sorted: true)] when 'keys_unsorted' [keys(input, sorted: false)] when 'values' input.nil? ? [] : [input] when 'arrays' input.is_a?(Array) ? [input] : [] when 'objects' input.is_a?(Hash) ? [input] : [] when 'iterables' input.is_a?(Array) || input.is_a?(Hash) ? [input] : [] when 'scalars' input.is_a?(Array) || input.is_a?(Hash) ? [] : [input] when 'booleans' [true, false].include?(input) ? [input] : [] when 'nulls' input.nil? ? [input] : [] when 'numbers' input.is_a?(Numeric) ? [input] : [] when 'strings' input.is_a?(String) ? [input] : [] when 'has' [has?(input, eval_arg(args, 0, input, context))] when 'in' [has?(eval_arg(args, 0, input, context), input)] when 'IN' [in_sql?(input, context, args)] when 'INDEX' [index_sql(input, context, args)] when 'JOIN' [join_sql(input, context, args)] when 'not' [!Value.truthy?(input)] when 'error' raise ErrorValue, args.empty? ? input : eval_arg(args, 0, input, context) when 'halt' raise HaltError, nil when 'halt_error' raise HaltError.new(input, args.empty? ? 5 : eval_arg(args, 0, input, context).to_i) when 'input' input_builtin(context) when 'inputs' inputs_builtin(context) when 'input_filename' filename = current_input_record(context)&.filename || context..fetch(:current_filename, '<stdin>') [filename || '<stdin>'] when 'input_line_number' [current_input_record(context)&.line || context..fetch(:current_line, 1)] when 'debug', 'stderr' emit_diagnostic(name, input, context, args) when 'null' [nil] when 'true' [true] when 'false' [false] when 'infinite' [Float::INFINITY] when 'nan' [Float::NAN] when 'isinfinite' [input.is_a?(Float) && input.infinite? ? true : false] when 'isnan' [input.is_a?(Float) && input.nan?] when 'isnormal' [normal_number?(input)] when 'isfinite' [input.is_a?(Numeric) && input.to_f.finite?] when 'finites' input.is_a?(Numeric) && input.to_f.finite? ? [input] : [] when 'normals' normal_number?(input) ? [input] : [] when 'add' [add(input)] when 'abs' [absolute(input)] when 'any' [any?(input, context, args)] when 'all' [all?(input, context, args)] when 'flatten' args.empty? ? [flatten(input)] : args.fetch(0).eval(input, context).map { |depth| flatten(input, depth) } when 'range' range(input, context, args) when 'floor', 'ceil', 'round', 'sqrt', 'log', 'log2', 'log10', 'exp', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh', 'cbrt', 'trunc', 'fabs', 'gamma', 'tgamma', 'lgamma', 'significand', 'logb', 'nearbyint', 'rint', 'frexp', 'modf', 'lgamma_r', 'j0', 'j1', 'y0', 'y1', 'erf', 'erfc', 'expm1', 'log1p' [math_unary(name, input)] when 'pow', 'atan2', 'ldexp', 'scalb', 'scalbln', 'fma', 'drem', 'copysign', 'fdim', 'fmax', 'fmin', 'fmod', 'hypot', 'jn', 'nextafter', 'nexttoward', 'remainder', 'yn' [math_nary(name, input, context, args)] when 'exp2' [2**numeric(input)] when 'exp10', 'pow10' [10**numeric(input)] when 'to_entries' [to_entries(input)] when 'from_entries' [from_entries(assert_array(input))] when 'with_entries' [from_entries(map_entries(input, context, args.fetch(0)))] when 'select' select(input, context, args.fetch(0)) when 'map' [map_filter(input, context, args.fetch(0))] when 'map_values' [map_values(input, context, args.fetch(0))] when 'to_number', 'tonumber' [to_number(input)] when 'tostring' [to_string(input)] when 'tojson', '@json' [JSON::Dumper.dump(input, indent: nil)] when 'fromjson' [JSON::Parser.parse_one(assert_string(input))] when 'ascii' [JSON::Dumper.dump(to_string(input), indent: nil, ascii: true)[1...-1]] when 'explode' [assert_string(input).each_codepoint.to_a] when 'implode' [implode(input)] when 'split' [split(input, context, args)] when 'join' args.empty? ? [join(input, '')] : args.fetch(0).eval(input, context).map { |separator| join(input, separator) } when 'ltrimstr' [assert_string(input).delete_prefix(assert_string(eval_arg(args, 0, input, context)))] when 'rtrimstr' [assert_string(input).delete_suffix(assert_string(eval_arg(args, 0, input, context)))] when 'ascii_downcase' [assert_string(input).tr('A-Z', 'a-z')] when 'ascii_upcase' [assert_string(input).tr('a-z', 'A-Z')] when 'startswith' [assert_string(input).start_with?(assert_string(eval_arg(args, 0, input, context)))] when 'endswith' [assert_string(input).end_with?(assert_string(eval_arg(args, 0, input, context)))] when 'index' args.fetch(0).eval(input, context).map { |needle| index_of(input, needle) } when 'rindex' args.fetch(0).eval(input, context).map { |needle| rindex_of(input, needle) } when 'indices' args.fetch(0).eval(input, context).map { |needle| indices_of(input, needle) } when 'recurse', 'recurse_down' recurse(input, context, args) when 'path' args.fetch(0).paths(input, context) when 'paths' paths_builtin(input, context, args, leaves_only: false) when 'leaf_paths' paths_builtin(input, context, args, leaves_only: true) when 'getpath' [Path.get(input, eval_arg(args, 0, input, context))] when 'setpath' [Path.set(Value.deep_copy(input), eval_arg(args, 0, input, context), eval_arg(args, 1, input, context))] when 'delpaths' [delpaths(input, eval_arg(args, 0, input, context))] when 'del' [delete_paths(input, context, args)] when 'pick' [pick(input, context, args)] when 'walk' walk(input, context, args.fetch(0)) when 'tostream' to_stream(input) when 'fromstream' from_stream(filter_stream(args.fetch(0), input, context)) when 'truncate_stream' truncate_stream(input, context, args) when 'min' [extreme(input, :min)] when 'max' [extreme(input, :max)] when 'min_by' [extreme_by(input, context, args.fetch(0), :min)] when 'max_by' [extreme_by(input, context, args.fetch(0), :max)] when 'sort' [assert_array(input).sort { |a, b| Value.compare(a, b) }] when 'sort_by' [sort_by_filter(input, context, args.fetch(0))] when 'group_by', 'GROUP_BY' [group_by_filter(input, context, args.fetch(0))] when 'unique' [unique_values(assert_array(input))] when 'unique_by', 'UNIQUE_BY' [unique_by_filter(input, context, args.fetch(0))] when 'reverse' [assert_array(input).reverse] when 'contains' [contains?(input, eval_arg(args, 0, input, context))] when 'inside' [contains?(eval_arg(args, 0, input, context), input)] when 'combinations' combinations(input, context, args) when 'transpose' [transpose(input)] when 'bsearch' bsearch(input, context, args) when 'first' first_builtin(input, context, args) when 'last' last_builtin(input, context, args) when 'nth' nth(input, context, args) when 'limit' limit(input, context, args) when 'until' until_filter(input, context, args) when 'while' while_filter(input, context, args) when 'repeat' repeat_filter(input, context, args) when 'isempty' [args.fetch(0).take(input, context, 1).empty?] when 'builtins' [JQ_BUILTIN_NAMES.flat_map { |builtin| builtin_arities(builtin) }.sort] when 'modulemeta' [(input, context)] when 'env' [ENV.to_h] when 'now' [Time.now.to_f] when 'gmtime' [time_array(Time.at(numeric(input)).utc)] when 'localtime' [time_array(Time.at(numeric(input)).localtime)] when 'mktime' [mktime(input)] when 'strftime' [strftime_builtin(input, context, args)] when 'strflocaltime' [strftime_builtin(input, context, args, local: true)] when 'strptime' [strptime(input, context, args)] when 'fromdate', 'fromdateiso8601' [Time.iso8601(assert_string(input)).to_f] when 'todate', 'todateiso8601' [Time.at(numeric(input)).utc.iso8601] when 'date' [Time.now.utc.iso8601] when 'dateadd' [Time.at(numeric(input) + numeric(eval_arg(args, 0, input, context))).to_f] when 'datesub' [Time.at(numeric(input) - numeric(eval_arg(args, 0, input, context))).to_f] when 'test' regex, flags = regexp(input, context, args) match = regex.match(assert_string(input)) [match ? !(flags.include?('n') && match[0].empty?) : false] when 'match' match_builtin(input, context, args) when 'capture' capture_builtin(input, context, args) when 'format' format_builtin(input, context, args) when 'scan' scan_builtin(input, context, args) when 'splits' splits_builtin(input, context, args) when 'sub' substitute(input, context, args, global: false) when 'gsub' substitute(input, context, args, global: true) when '@text' [to_string(input)] when '@html' [html_escape(to_string(input))] when '@uri' [uri_escape(to_string(input))] when '@base64' [[to_string(input)].pack('m0')] when '@base64d' [decode_base64(input)] when '@base32' [base32_encode(to_string(input))] when '@base32d' [base32_decode(assert_string(input))] when '@csv' [format_csv(input)] when '@tsv' [format_tsv(input)] when '@sh' [format_sh(input)] when 'get_jq_origin' [context..fetch(:jq_origin, File.('../..', __dir__))] when 'get_prog_origin' source_path = context.[:source_path] [source_path ? File.dirname(File.(source_path)) : Dir.pwd] when 'get_search_list' [search_list(context)] else raise CompileError, "#{name}/#{args.length} is not defined" end rescue RegexpError => e raise unless defined?(Regexp::TimeoutError) && e.is_a?(Regexp::TimeoutError) raise Rjq::RuntimeError, 'regular expression match timeout' end |
.each_resolved_argument_set(name, args, input, context, &block) ⇒ Object
2023 2024 2025 2026 2027 |
# File 'lib/rjq/builtins.rb', line 2023 def each_resolved_argument_set(name, args, input, context, &block) indices = (0...args.length).to_a indices.reverse! unless LEFT_OUTER_ARGUMENT_BUILTINS.include?(name) resolve_argument_indices(name, args, indices, input, context, [], &block) end |
.emit_diagnostic(name, input, context, args) ⇒ Object
471 472 473 474 475 476 477 478 479 480 |
# File 'lib/rjq/builtins.rb', line 471 def emit_diagnostic(name, input, context, args) io = context.[:stderr] || $stderr diagnostic = args.empty? ? input : eval_arg(args, 0, input, context) if name == 'debug' io.puts(JSON::Dumper.dump(['DEBUG:', diagnostic], indent: nil)) else io.puts(to_string(diagnostic)) end [input] end |
.eval_arg(args, index, input, context) ⇒ Object
2004 2005 2006 2007 2008 |
# File 'lib/rjq/builtins.rb', line 2004 def eval_arg(args, index, input, context) raise RuntimeError, "missing argument #{index}" unless args[index] args[index].eval(input, context).first end |
.extreme(input, mode) ⇒ Object
1051 1052 1053 1054 1055 1056 |
# File 'lib/rjq/builtins.rb', line 1051 def extreme(input, mode) array = assert_array(input) return nil if array.empty? array.public_send(mode) { |a, b| Value.compare(a, b) } end |
.extreme_by(input, context, filter, mode) ⇒ Object
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 |
# File 'lib/rjq/builtins.rb', line 1058 def extreme_by(input, context, filter, mode) array = assert_array(input) return nil if array.empty? best = array.first best_key = filter_key(best, context, filter) array.drop(1).each do |item| key = filter_key(item, context, filter) comparison = Value.compare(key, best_key) if (mode == :min && comparison.negative?) || (mode == :max && comparison >= 0) best = item best_key = key end end best end |
.filter_key(value, context, filter) ⇒ Object
1146 1147 1148 1149 |
# File 'lib/rjq/builtins.rb', line 1146 def filter_key(value, context, filter) result = collect_filter(filter, value, context) result.length == 1 ? result.first : result end |
.filter_stream(filter, input, context) ⇒ Object
2010 2011 2012 2013 2014 |
# File 'lib/rjq/builtins.rb', line 2010 def filter_stream(filter, input, context) return filter.stream(input, context) if filter.respond_to?(:stream) filter.eval(input, context).each end |
.first_builtin(input, context, args) ⇒ Object
1351 1352 1353 1354 |
# File 'lib/rjq/builtins.rb', line 1351 def first_builtin(input, context, args) values = args.empty? ? assert_array(input) : args.fetch(0).take(input, context, 1) values.empty? ? [] : [values.first] end |
.flatten(value, depth = FLATTEN_UNBOUNDED) ⇒ Object
510 511 512 513 514 515 516 |
# File 'lib/rjq/builtins.rb', line 510 def flatten(value, depth = FLATTEN_UNBOUNDED) if !depth.equal?(FLATTEN_UNBOUNDED) && Value.compare(depth, 0).negative? raise RuntimeError, 'flatten depth must not be negative' end flatten_items(iterable_values(value), depth) end |
.flatten_items(items, depth) ⇒ Object
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 |
# File 'lib/rjq/builtins.rb', line 518 def flatten_items(items, depth) output = [] stack = items.to_a.reverse_each.map { |item| [item, depth] } until stack.empty? item, item_depth = stack.pop unbounded = item_depth.equal?(FLATTEN_UNBOUNDED) unless item.is_a?(Array) && (unbounded || !Value.equal?(item_depth, 0)) output << item next end next_depth = unbounded ? FLATTEN_UNBOUNDED : subtract_flatten_depth(item_depth) item.reverse_each { |child| stack << [child, next_depth] } end output end |
.float_extreme(left, right, mode) ⇒ Object
687 688 689 690 691 692 |
# File 'lib/rjq/builtins.rb', line 687 def float_extreme(left, right, mode) return right if left.to_f.nan? return left if right.to_f.nan? [left, right].public_send(mode) end |
.format_builtin(input, context, args) ⇒ Object
1714 1715 1716 1717 1718 1719 1720 |
# File 'lib/rjq/builtins.rb', line 1714 def format_builtin(input, context, args) format_name = assert_string(eval_arg(args, 0, input, context)) supported = %w[text json html uri csv tsv sh base64 base64d] raise RuntimeError, "format #{format_name.inspect} is not supported" unless supported.include?(format_name) dispatch("@#{format_name}", input, context, []) end |
.format_csv(input) ⇒ Object
1867 1868 1869 |
# File 'lib/rjq/builtins.rb', line 1867 def format_csv(input) assert_array(input).map { |item| csv_field(item) }.join(',') end |
.format_sh(input) ⇒ Object
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 |
# File 'lib/rjq/builtins.rb', line 1897 def format_sh(input) values = input.is_a?(Array) ? input : [input] values.map do |item| case item when String then sh_quote(item) when Numeric, TrueClass, FalseClass, NilClass then to_string(item) else raise TypeError, "#{Value.type_of(item)} (#{short_dump(item)}) can not be escaped for shell" end end.join(' ') end |
.format_tsv(input) ⇒ Object
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 |
# File 'lib/rjq/builtins.rb', line 1885 def format_tsv(input) assert_array(input).map do |item| next '' if item.nil? next to_string(item) if item.is_a?(Numeric) || item == true || item == false unless item.is_a?(String) raise TypeError, "#{Value.type_of(item)} (#{short_dump(item)}) is not valid in a tsv row" end item.gsub("\t", '\\t').gsub("\n", '\\n').gsub("\r", '\\r') end.join("\t") end |
.from_entries(entries) ⇒ Object
719 720 721 722 723 724 725 726 727 728 729 730 |
# File 'lib/rjq/builtins.rb', line 719 def from_entries(entries) entries.each_with_object({}) do |entry, object| key = %w[key Key name Name].lazy.map { |name| Path.read_index(entry, name) } .find { |candidate| Value.truthy?(candidate) } unless key.is_a?(String) raise TypeError, "Cannot use #{Value.type_of(key)} (#{JSON::Dumper.dump(key, indent: nil)}) as object key" end value = entry.key?('value') ? entry['value'] : entry['Value'] object[key] = value end end |
.from_stream(stream) ⇒ Object
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 |
# File 'lib/rjq/builtins.rb', line 988 def from_stream(stream) Enumerator.new do |yielder| root = nil stream.each do |event| event = assert_array(event) path = assert_array(event.first) if event.length == 1 if path.length == 1 && !root.nil? yielder << root root = nil end next end value = event[1] if path.empty? yielder << value root = nil else root ||= container_for_path(path) Path.set(root, path, value) end end yielder << root unless root.nil? end end |
.group_by_filter(input, context, filter) ⇒ Object
1079 1080 1081 1082 1083 1084 1085 1086 1087 |
# File 'lib/rjq/builtins.rb', line 1079 def group_by_filter(input, context, filter) decorated_sort(input, context, filter).each_with_object([]) do |(item, key), groups| if groups.empty? || !Value.equal?(groups.last.fetch(:key), key) groups << { key: key, values: [item] } else groups.last.fetch(:values) << item end end.map { |group| group.fetch(:values) } end |
.gsub_with_filter(string, regex, replacement_filter, context) ⇒ Object
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 |
# File 'lib/rjq/builtins.rb', line 1830 def gsub_with_filter(string, regex, replacement_filter, context) matches = string.to_enum(:scan, regex).map { Regexp.last_match } return [string] if matches.empty? first_replacements = replacements_for(replacement_filter, matches.first, context) first_replacements.each_index.filter_map do |branch| out = +'' offset = 0 complete = matches.each_with_index.all? do |match, index| replacements = index.zero? ? first_replacements : replacements_for(replacement_filter, match, context) replacement = replacements[branch] next false unless replacement out << string[offset...match.begin(0)].to_s out << replacement offset = match.end(0) true end next unless complete out << string[offset..].to_s end end |
.has?(container, key) ⇒ Boolean
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
# File 'lib/rjq/builtins.rb', line 425 def has?(container, key) case container when Array unless key.is_a?(Numeric) raise TypeError, "Cannot check whether array has a #{Value.type_of(key)} key" end return false unless key.finite? index = key.to_i index >= 0 && index < container.length when Hash unless key.is_a?(String) raise TypeError, "Cannot check whether object has a #{Value.type_of(key)} key" end container.key?(key) when NilClass false else raise TypeError, "Cannot check whether #{Value.type_of(container)} has a #{Value.type_of(key)} key" end end |
.html_escape(input) ⇒ Object
1871 1872 1873 |
# File 'lib/rjq/builtins.rb', line 1871 def html_escape(input) CGI.escapeHTML(input).gsub(''', ''') end |
.ieee_remainder(left, right) ⇒ Object
703 704 705 706 |
# File 'lib/rjq/builtins.rb', line 703 def ieee_remainder(left, right) quotient = (left.to_f / right.to_f).round(half: :even) left.to_f - (right.to_f * quotient) end |
.implode(input) ⇒ Object
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 |
# File 'lib/rjq/builtins.rb', line 810 def implode(input) raise TypeError, 'implode input must be an array' unless input.is_a?(Array) input.map do |item| unless item.is_a?(Numeric) && !item.to_f.nan? raise TypeError, "#{Value.type_of(item)} (#{JSON::Dumper.dump(item, indent: nil)}) can't be imploded, unicode codepoint needs to be numeric" end codepoint = item.to_f.finite? ? item.to_i : -1 codepoint = 0xFFFD if codepoint.negative? || codepoint > 0x10FFFF || codepoint.between?(0xD800, 0xDFFF) [codepoint].pack('U') end.join end |
.in_sql?(input, context, args) ⇒ Boolean
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 |
# File 'lib/rjq/builtins.rb', line 1134 def in_sql?(input, context, args) if args.length == 1 values = collect_filter(args.fetch(0), input, context) values = values.first if values.length == 1 && values.first.is_a?(Array) return values.any? { |item| Value.equal?(item, input) } end source_any?(args.fetch(0), input, context) do |item| source_any?(args.fetch(1), input, context) { |needle| Value.equal?(item, needle) } end end |
.index_of(input, needle) ⇒ Object
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 |
# File 'lib/rjq/builtins.rb', line 1227 def index_of(input, needle) if input.is_a?(String) validate_string_search_needle(input, needle) return nil if needle.empty? return input.index(needle) end return unsupported_search_result(input, needle) unless input.is_a?(Array) needle = [needle] unless needle.is_a?(Array) max = input.length - assert_array(needle).length return nil if needle.empty? (0..max).find { |index| array_slice_equal?(input, needle, index) } end |
.index_sql(input, context, args) ⇒ Object
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 |
# File 'lib/rjq/builtins.rb', line 1112 def index_sql(input, context, args) source = if args.length == 2 collect_filter(args[0], input, context) else assert_array(input) end filter = args.length == 2 ? args[1] : args.fetch(0) source.to_h do |item| [to_string(filter_key(item, context, filter)), item] end end |
.indices_of(input, needle) ⇒ Object
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 |
# File 'lib/rjq/builtins.rb', line 1261 def indices_of(input, needle) if input.is_a?(String) positions = [] offset = 0 validate_string_search_needle(input, needle) return [] if needle.empty? while (found = input.index(needle, offset)) positions << found offset = found + 1 end return positions end return unsupported_search_result(input, needle) unless input.is_a?(Array) needle = [needle] unless needle.is_a?(Array) return [] if needle.empty? max = input.length - needle.length (0..max).select { |index| array_slice_equal?(input, needle, index) } end |
.input_builtin(context) ⇒ Object
450 451 452 453 454 455 456 457 458 |
# File 'lib/rjq/builtins.rb', line 450 def input_builtin(context) queue = context.[:input_queue] return [queue.shift] if queue && !queue.empty? remaining = context..fetch(:remaining_inputs, []) raise RuntimeError, 'break' if remaining.empty? [remaining.first] end |
.input_values(input, context, filter) ⇒ Object
1966 1967 1968 1969 1970 1971 1972 |
# File 'lib/rjq/builtins.rb', line 1966 def input_values(input, context, filter) Enumerator.new do |yielder| iterable_values(input).each do |item| filter_stream(filter, item, context).each { |value| yielder << value } end end end |
.inputs_builtin(context) ⇒ Object
460 461 462 463 464 465 |
# File 'lib/rjq/builtins.rb', line 460 def inputs_builtin(context) queue = context.[:input_queue] return queue.each_remaining if queue context..fetch(:remaining_inputs, []) end |
.iterable_values(input) ⇒ Object
1974 1975 1976 1977 1978 1979 1980 |
# File 'lib/rjq/builtins.rb', line 1974 def iterable_values(input) return input.each if input.is_a?(Array) return input.each_value if input.is_a?(Hash) raise TypeError, "Cannot iterate over #{Value.type_of(input)} (#{JSON::Dumper.dump(input, indent: nil)})" end |
.join(input, separator) ⇒ Object
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 |
# File 'lib/rjq/builtins.rb', line 826 def join(input, separator) out = +'' assert_array(input).each_with_index do |item, index| out << separator.to_s if index.positive? case item when nil nil when String, Numeric, TrueClass, FalseClass out << to_string(item) else raise TypeError, "string (#{short_dump(out)}) and #{Value.type_of(item)} (#{short_dump(item)}) cannot be added" end end out end |
.join_sql(input, context, args) ⇒ Object
1125 1126 1127 1128 1129 1130 1131 1132 |
# File 'lib/rjq/builtins.rb', line 1125 def join_sql(input, context, args) index = eval_arg(args, 0, input, context) filter = args.fetch(1) assert_array(input).map do |item| key = to_string(filter_key(item, context, filter)) [item, index[key]] end end |
.jq_regexp_pattern(pattern, dot_matches_newline:) ⇒ Object
1579 1580 1581 1582 1583 1584 |
# File 'lib/rjq/builtins.rb', line 1579 def jq_regexp_pattern(pattern, dot_matches_newline:) chars = pattern.each_char.to_a transformed, = transform_regexp_segment(chars, 0, line_anchors: false, dot_matches_newline: dot_matches_newline) transformed end |
.keys(value, sorted:) ⇒ Object
414 415 416 417 418 419 420 421 422 423 |
# File 'lib/rjq/builtins.rb', line 414 def keys(value, sorted:) case value when Array (0...value.length).to_a when Hash sorted ? value.keys.sort : value.keys else raise TypeError, "cannot get keys of #{Value.type_of(value)}" end end |
.last_builtin(input, context, args) ⇒ Object
1356 1357 1358 1359 |
# File 'lib/rjq/builtins.rb', line 1356 def last_builtin(input, context, args) values = args.empty? ? assert_array(input) : collect_filter(args.fetch(0), input, context) values.empty? ? [] : [values.last] end |
.length(value) ⇒ Object
392 393 394 395 396 397 398 399 400 401 402 403 404 405 |
# File 'lib/rjq/builtins.rb', line 392 def length(value) case value when NilClass 0 when String value.each_char.count when Array, Hash value.length when Numeric value.abs else raise TypeError, "cannot get length of #{Value.type_of(value)}" end end |
.limit(input, context, args) ⇒ Object
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 |
# File 'lib/rjq/builtins.rb', line 1406 def limit(input, context, args) Enumerator.new do |yielder| filter_stream(args.fetch(0), input, context).each do |raw_count| count = numeric(raw_count).ceil next if count <= 0 emitted = 0 filter_stream(args.fetch(1), input, context).each do |value| yielder << value emitted += 1 break if emitted >= count end end end end |
.map_entries(input, context, filter) ⇒ Object
732 733 734 735 736 |
# File 'lib/rjq/builtins.rb', line 732 def map_entries(input, context, filter) to_entries(input).flat_map do |entry| collect_filter(filter, entry, context) end end |
.map_filter(value, context, filter) ⇒ Object
746 747 748 749 |
# File 'lib/rjq/builtins.rb', line 746 def map_filter(value, context, filter) items = value.is_a?(Hash) ? value.values : assert_array(value) items.flat_map { |item| collect_filter(filter, item, context) } end |
.map_values(value, context, filter) ⇒ Object
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 |
# File 'lib/rjq/builtins.rb', line 751 def map_values(value, context, filter) case value when Array value.each_with_object([]) do |item, out| outputs = filter_stream(filter, item, context).take(1) out << outputs.first unless outputs.empty? end when Hash value.each_with_object({}) do |(key, item), out| outputs = filter_stream(filter, item, context).take(1) out[key] = outputs.first unless outputs.empty? end else raise TypeError, "Cannot iterate over #{Value.type_of(value)} (#{JSON::Dumper.dump(value, indent: nil)})" end end |
.match_builtin(input, context, args) ⇒ Object
1756 1757 1758 1759 1760 1761 1762 1763 |
# File 'lib/rjq/builtins.rb', line 1756 def match_builtin(input, context, args) string = assert_string(input) regex, flags = regexp(input, context, args) global = flags.include?('g') matches = global ? string.to_enum(:scan, regex).map { Regexp.last_match } : [regex.match(string)].compact matches = matches.reject { |match| match[0].empty? } if flags.include?('n') matches.map { |match| match_object(match) } end |
.match_object(match) ⇒ Object
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 |
# File 'lib/rjq/builtins.rb', line 1765 def match_object(match) { 'offset' => match.begin(0), 'length' => match[0].length, 'string' => match[0], 'captures' => (1...match.length).map do |index| value = match[index] if value.nil? && match[0].empty? value = '' offset = match.begin(0) else offset = value ? match.begin(index) : -1 end { 'offset' => offset, 'length' => value ? value.length : 0, 'string' => value, 'name' => capture_name(match, index) } end } end |
.matches_for_regexp(input, context, args, string) ⇒ Object
1750 1751 1752 1753 1754 |
# File 'lib/rjq/builtins.rb', line 1750 def matches_for_regexp(input, context, args, string) regex, flags = regexp(input, context, args) matches = string.to_enum(:scan, regex).map { Regexp.last_match } matches.reject { |match| flags.include?('n') && match[0].empty? } end |
.math_nary(name, input, context, args) ⇒ Object
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 |
# File 'lib/rjq/builtins.rb', line 646 def math_nary(name, input, context, args) values = args.empty? ? [numeric(input)] : args.map { |arg| numeric(arg.eval(input, context).first) } case name when 'pow' then values[0]**values[1] when 'atan2' then Math.atan2(values[0], values[1]) when 'ldexp' then Math.ldexp(values[0], values[1].to_i) when 'scalb' then MathFunctions.scalb(values[0], values[1]) when 'scalbln' then MathFunctions.scalbln(values[0], values[1]) when 'fma' then MathFunctions.fma(values[0], values[1], values[2]) when 'drem' then MathFunctions.remainder(values[0], values[1]) when 'copysign' then copy_sign(values[0], values[1]) when 'fdim' then values.any? { |value| value.to_f.nan? } ? Float::NAN : [values[0] - values[1], 0].max when 'fmax' then float_extreme(values[0], values[1], :max) when 'fmin' then float_extreme(values[0], values[1], :min) when 'fmod' then values[0].remainder(values[1]) when 'hypot' then Math.hypot(values[0], values[1]) when 'jn', 'yn' then MathFunctions.bessel(name, values[0].to_i, values[1]) when 'nextafter', 'nexttoward' then next_float_toward(values[0], values[1]) when 'remainder' then MathFunctions.remainder(values[0], values[1]) end rescue Math::DomainError, FloatDomainError, ZeroDivisionError Float::NAN end |
.math_unary(name, input) ⇒ Object
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 |
# File 'lib/rjq/builtins.rb', line 577 def math_unary(name, input) value = numeric(input) case name when 'floor' then value.floor when 'ceil' then value.ceil when 'round' then value.round when 'sqrt' then Math.sqrt(value) when 'log' then Math.log(value) when 'log2' then Math.log2(value) when 'log10' then Math.log10(value) when 'exp' then Math.exp(value) when 'sin' then Math.sin(value) when 'cos' then Math.cos(value) when 'tan' then Math.tan(value) when 'asin' then Math.asin(value) when 'acos' then Math.acos(value) when 'atan' then Math.atan(value) when 'sinh' then Math.sinh(value) when 'cosh' then Math.cosh(value) when 'tanh' then Math.tanh(value) when 'asinh' then Math.asinh(value) when 'acosh' then Math.acosh(value) when 'atanh' then Math.atanh(value) when 'cbrt' then Math.cbrt(value) when 'trunc' then value.truncate when 'fabs' then value.abs when 'gamma', 'tgamma' then Math.gamma(value) when 'lgamma' then Math.lgamma(value).first when 'lgamma_r' then Math.lgamma(value) when 'frexp' then Math.frexp(value) when 'modf' integral = value.truncate [value - integral, integral] when 'significand' return 0 if value.zero? fraction, = Math.frexp(value) fraction * 2 when 'logb' return -Float::INFINITY if value.zero? Math.log2(value.abs).floor when 'nearbyint', 'rint' then round_to_even(value) when 'j0', 'j1', 'y0', 'y1' then MathFunctions.bessel(name, value) when 'erf' then Math.erf(value) when 'erfc' then Math.erfc(value) when 'expm1' then Math.expm1(value) when 'log1p' then Math.log1p(value) end rescue Math::DomainError Float::NAN end |
.mktime(input) ⇒ Object
1513 1514 1515 1516 1517 1518 1519 1520 |
# File 'lib/rjq/builtins.rb', line 1513 def mktime(input) values = assert_array(input) raise TypeError, 'mktime requires parsed datetime inputs' unless values.first(6).all?(Numeric) Time.utc(values[0], values[1] + 1, values[2], values[3], values[4], values[5]).to_f rescue ArgumentError raise TypeError, 'mktime requires parsed datetime inputs' end |
.modulemeta(input, context) ⇒ Object
2078 2079 2080 2081 2082 2083 |
# File 'lib/rjq/builtins.rb', line 2078 def (input, context) = context..fetch(:module_metadata, {}) raise RuntimeError, "module not found: #{input}" unless .key?(input) .fetch(input) end |
.next_float_toward(value, target) ⇒ Object
694 695 696 697 698 699 700 701 |
# File 'lib/rjq/builtins.rb', line 694 def next_float_toward(value, target) value = value.to_f target = target.to_f return target if value == target return Float::NAN if value.nan? || target.nan? value < target ? value.next_float : value.prev_float end |
.normal_number?(value) ⇒ Boolean
670 671 672 673 674 675 |
# File 'lib/rjq/builtins.rb', line 670 def normal_number?(value) return false unless value.is_a?(Numeric) float = value.to_f float.finite? && float.abs >= Float::MIN end |
.nth(input, context, args) ⇒ Object
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 |
# File 'lib/rjq/builtins.rb', line 1361 def nth(input, context, args) Enumerator.new do |yielder| filter_stream(args.fetch(0), input, context).each do |raw_index| if args.length == 1 yielder << nth_index_value(input, raw_index) next end index = nth_filter_index(raw_index) if index.respond_to?(:infinite?) && index.infinite? filter_stream(args[1], input, context).each { |_value| nil } next end values = args[1].take(input, context, index + 1) yielder << values[index] if index < values.length end end end |
.nth_filter_index(value) ⇒ Object
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 |
# File 'lib/rjq/builtins.rb', line 1390 def nth_filter_index(value) if value.is_a?(Numeric) raise RuntimeError, "nth doesn't support negative indices" if value.respond_to?(:nan?) && value.nan? raise RuntimeError, "nth doesn't support negative indices" if value < 0 return value if value.respond_to?(:infinite?) && value.infinite? return value.ceil end if value.nil? || value == true || value == false raise RuntimeError, "nth doesn't support negative indices" end raise TypeError, "#{Value.type_of(value)} (#{short_dump(value)}) and number (1) cannot be added" end |
.nth_index_value(input, raw_index) ⇒ Object
1381 1382 1383 1384 1385 1386 1387 1388 |
# File 'lib/rjq/builtins.rb', line 1381 def nth_index_value(input, raw_index) index = if raw_index.is_a?(Numeric) && (!raw_index.respond_to?(:finite?) || raw_index.finite?) raw_index.to_i else raw_index end Path.read_index(input, index) end |
.numeric(value) ⇒ Object
2097 2098 2099 2100 2101 |
# File 'lib/rjq/builtins.rb', line 2097 def numeric(value) raise TypeError, "expected number, got #{Value.type_of(value)}" unless value.is_a?(Numeric) value end |
.option_state(current, enabled, disabled, option) ⇒ Object
1697 1698 1699 1700 1701 1702 |
# File 'lib/rjq/builtins.rb', line 1697 def option_state(current, enabled, disabled, option) return true if enabled.include?(option) return false if disabled.include?(option) current end |
.ordered_delete_paths(paths) ⇒ Object
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 |
# File 'lib/rjq/builtins.rb', line 2055 def ordered_delete_paths(paths) paths.sort do |left, right| parent_cmp = Value.compare(left[0...-1], right[0...-1]) next parent_cmp unless parent_cmp.zero? left_key = left.last right_key = right.last if left_key.is_a?(Integer) && right_key.is_a?(Integer) right_key <=> left_key else Value.compare(right, left) end end end |
.paths_builtin(input, context, args, leaves_only:) ⇒ Object
928 929 930 931 932 933 934 935 936 937 938 939 940 |
# File 'lib/rjq/builtins.rb', line 928 def paths_builtin(input, context, args, leaves_only:) paths = Path.paths(input, leaves_only: leaves_only) return paths.reject(&:empty?) if args.empty? filter = args.fetch(0) Enumerator.new do |yielder| paths.each do |path| filter_stream(filter, Path.get(input, path), context).each do |value| yielder << path if !path.empty? && Value.truthy?(value) end end end end |
.pick(input, context, args) ⇒ Object
905 906 907 908 909 910 911 912 913 914 915 916 |
# File 'lib/rjq/builtins.rb', line 905 def pick(input, context, args) paths = args.flat_map { |arg| collect_paths(arg, input, context) } return Value.deep_copy(input) if paths.any?(&:empty?) paths.each { |path| validate_pick_path(path) } root = nil paths.each do |path| root ||= container_for_path(path) Path.set(root, path, Value.deep_copy(Path.get(input, path))) end root end |
.range(input, context, args) ⇒ Object
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 |
# File 'lib/rjq/builtins.rb', line 540 def range(input, context, args) numbers = args.map { |arg| numeric(arg.eval(input, context).first) } from, to, step = case numbers.length when 1 [0, numbers[0], 1] when 2 [numbers[0], numbers[1], 1] when 3 numbers else raise RuntimeError, 'range expects 1 to 3 arguments' end raise RuntimeError, 'range step cannot be zero' if step.zero? range_values(from, to, step) end |
.range_values(from, to, step) ⇒ Object
558 559 560 561 562 563 564 565 566 567 |
# File 'lib/rjq/builtins.rb', line 558 def range_values(from, to, step) Enumerator.new do |yielder| current = from comparison = step.positive? ? -> { current < to } : -> { current > to } while comparison.call yielder << current current += step end end end |
.recurse(input, context, args) ⇒ Object
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 |
# File 'lib/rjq/builtins.rb', line 850 def recurse(input, context, args) Enumerator.new do |yielder| stack = [[input].each] until stack.empty? begin value = stack.last.next rescue StopIteration stack.pop next end yielder << value children = if args.empty? case value when Array then value.each when Hash then value.each_value else [].each end else filter_stream(args.first, value, context) end if args.length > 1 condition = args[1] source_children = children children = Enumerator.new do |child_yielder| source_children.each do |child| filter_stream(condition, child, context).each do |result| child_yielder << child if Value.truthy?(result) end end end end stack << children.each end end end |
.regexp(input, context, args) ⇒ Object
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 |
# File 'lib/rjq/builtins.rb', line 1555 def regexp(input, context, args) pattern, flags = regexp_parts(input, context, args) unknown_flags = flags.each_char.uniq - %w[g i m n p s l x] raise RuntimeError, "unsupported regular expression flag: #{unknown_flags.first}" unless unknown_flags.empty? dot_matches_newline = flags.include?('m') || flags.include?('p') pattern = jq_regexp_pattern(pattern, dot_matches_newline: dot_matches_newline) = 0 |= Regexp::IGNORECASE if flags.include?('i') |= Regexp::MULTILINE if flags.include?('m') || flags.include?('p') |= Regexp::EXTENDED if flags.include?('x') timeout = context.[:regexp_timeout] regex = if timeout.nil? Regexp.new(pattern, ) elsif Regexp.respond_to?(:timeout) Regexp.new(pattern, , timeout: timeout) else raise RuntimeError, 'regular expression timeout is not supported by this Ruby' end [regex, flags] rescue RegexpError, ArgumentError => e raise RuntimeError, e..to_s end |
.regexp_matches(input, context, args, string) ⇒ Object
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 |
# File 'lib/rjq/builtins.rb', line 1739 def regexp_matches(input, context, args, string) return matches_for_regexp(input, context, args, string) unless args.length > 1 matches = [] filter_stream(args.fetch(1), input, context).each do |flags| flag_args = [args.fetch(0), AST::Literal.new(flags)] matches.concat(matches_for_regexp(input, context, flag_args, string)) end matches end |
.regexp_parts(input, context, args) ⇒ Object
1730 1731 1732 1733 1734 1735 1736 1737 |
# File 'lib/rjq/builtins.rb', line 1730 def regexp_parts(input, context, args) raw = eval_arg(args, 0, input, context) if raw.is_a?(Array) [assert_string(raw[0]), raw[1] ? assert_string(raw[1]) : ''] else [assert_string(raw), args.length > 1 ? assert_string(eval_arg(args, 1, input, context)) : ''] end end |
.repeat_filter(input, context, args) ⇒ Object
1501 1502 1503 1504 1505 1506 1507 |
# File 'lib/rjq/builtins.rb', line 1501 def repeat_filter(input, context, args) Enumerator.new do |yielder| loop do filter_stream(args.fetch(0), input, context).each { |value| yielder << value } end end end |
.replacement_filters(node) ⇒ Object
1814 1815 1816 1817 1818 1819 |
# File 'lib/rjq/builtins.rb', line 1814 def replacement_filters(node) return node.replacement_filters if node.respond_to?(:replacement_filters) return replacement_filters(node.left) + replacement_filters(node.right) if node.is_a?(AST::Comma) [node] end |
.replacements_for(replacement_filter, match, context) ⇒ Object
1854 1855 1856 |
# File 'lib/rjq/builtins.rb', line 1854 def replacements_for(replacement_filter, match, context) replacement_filter.eval(capture_values(match), context).map { |value| assert_string(value) } end |
.resolve_argument_indices(name, args, indices, input, context, resolved, &block) ⇒ Object
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 |
# File 'lib/rjq/builtins.rb', line 2029 def resolve_argument_indices(name, args, indices, input, context, resolved, &block) return yield(resolved) if indices.empty? index = indices.first remaining = indices.drop(1) argument = args.fetch(index) if FILTER_ARGUMENT_POSITIONS.fetch(name, []).include?(index) copy = resolved.dup copy[index] = argument return resolve_argument_indices(name, args, remaining, input, context, copy, &block) end filter_stream(argument, input, context).each do |value| copy = resolved.dup copy[index] = AST::Literal.new(value) resolve_argument_indices(name, args, remaining, input, context, copy, &block) end end |
.rindex_of(input, needle) ⇒ Object
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 |
# File 'lib/rjq/builtins.rb', line 1244 def rindex_of(input, needle) if input.is_a?(String) validate_string_search_needle(input, needle) return nil if needle.empty? return input.rindex(needle) end return unsupported_search_result(input, needle) unless input.is_a?(Array) needle = [needle] unless needle.is_a?(Array) max = input.length - assert_array(needle).length return nil if needle.empty? max.downto(0).find { |index| array_slice_equal?(input, needle, index) } end |
.round_to_even(value) ⇒ Object
677 678 679 680 |
# File 'lib/rjq/builtins.rb', line 677 def round_to_even(value) rounded = value.to_f.round(half: :even) rounded.zero? && value.to_f.negative? ? -0.0 : rounded end |
.ruby_regexp_group(enabled, disabled, parent_dotall, child_dotall, body) ⇒ Object
1704 1705 1706 1707 1708 1709 1710 1711 1712 |
# File 'lib/rjq/builtins.rb', line 1704 def ruby_regexp_group(enabled, disabled, parent_dotall, child_dotall, body) ruby_enabled = enabled.each_char.select { |option| %w[i x].include?(option) } ruby_disabled = disabled.each_char.select { |option| %w[i x].include?(option) } ruby_enabled << 'm' if child_dotall && !parent_dotall ruby_disabled << 'm' if parent_dotall && !child_dotall = ruby_enabled.join += "-#{ruby_disabled.join}" unless ruby_disabled.empty? .empty? ? "(?:#{body})" : "(?#{}:#{body})" end |
.scan_builtin(input, context, args) ⇒ Object
1796 1797 1798 1799 |
# File 'lib/rjq/builtins.rb', line 1796 def scan_builtin(input, context, args) regex, = regexp(input, context, args) assert_string(input).scan(regex).map { |item| item.is_a?(Array) && item.length == 1 ? item.first : item } end |
.scoped_regexp_options(chars, index) ⇒ Object
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 |
# File 'lib/rjq/builtins.rb', line 1675 def (chars, index) return unless chars[index, 2] == ['(', '?'] cursor = index + 2 enabled = +'' while cursor < chars.length && %w[i m s x].include?(chars[cursor]) enabled << chars[cursor] cursor += 1 end disabled = +'' if chars[cursor] == '-' cursor += 1 while cursor < chars.length && %w[i m s x].include?(chars[cursor]) disabled << chars[cursor] cursor += 1 end end return unless chars[cursor] == ':' && !(enabled.empty? && disabled.empty?) [enabled, disabled, cursor + 1] end |
.search_list(context) ⇒ Object
1722 1723 1724 1725 1726 1727 1728 |
# File 'lib/rjq/builtins.rb', line 1722 def search_list(context) configured = context..fetch(:library_path, []) return configured.map { |path| File.(path) } unless configured.empty? environment = ENV.fetch('JQ_LIBRARY_PATH', '').split(File::PATH_SEPARATOR).reject(&:empty?) (environment + [File.('~/.jq'), File.('~/.rjq')]).uniq end |
.select(input, context, filter) ⇒ Object
738 739 740 741 742 743 744 |
# File 'lib/rjq/builtins.rb', line 738 def select(input, context, filter) Enumerator.new do |yielder| filter_stream(filter, input, context).each do |value| yielder << input if Value.truthy?(value) end end end |
.sh_quote(input) ⇒ Object
1909 1910 1911 |
# File 'lib/rjq/builtins.rb', line 1909 def sh_quote(input) "'#{input.gsub("'", "'\\\\''")}'" end |
.short_dump(value) ⇒ Object
843 844 845 846 847 848 |
# File 'lib/rjq/builtins.rb', line 843 def short_dump(value) dumped = JSON::Dumper.dump(value, indent: nil) return "#{dumped[0, 11]}..." if value.is_a?(Hash) && dumped.length > 14 dumped.length > 18 ? "#{dumped[0, 15]}..." : dumped end |
.sort_by_filter(input, context, filter) ⇒ Object
1075 1076 1077 |
# File 'lib/rjq/builtins.rb', line 1075 def sort_by_filter(input, context, filter) decorated_sort(input, context, filter).map(&:first) end |
.source_all?(node, input, context) ⇒ Boolean
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 |
# File 'lib/rjq/builtins.rb', line 1993 def source_all?(node, input, context, &) return node.source_all?(input, context, &) if node.respond_to?(:source_all?) if node.is_a?(AST::Comma) return false unless source_all?(node.left, input, context, &) return source_all?(node.right, input, context, &) end node.eval(input, context).all?(&) end |
.source_any?(node, input, context) ⇒ Boolean
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 |
# File 'lib/rjq/builtins.rb', line 1982 def source_any?(node, input, context, &) return node.source_any?(input, context, &) if node.respond_to?(:source_any?) if node.is_a?(AST::Comma) return true if source_any?(node.left, input, context, &) return source_any?(node.right, input, context, &) end node.eval(input, context).any?(&) end |
.split(input, context, args) ⇒ Object
787 788 789 790 791 792 793 794 795 796 797 |
# File 'lib/rjq/builtins.rb', line 787 def split(input, context, args) string = assert_string(input) if args.length > 1 return split_at_matches(string, regexp_matches(input, context, args, string)) end separator = assert_string(eval_arg(args, 0, input, context)) return string.each_char.to_a if separator.empty? string.split(separator, -1) end |
.split_at_matches(string, matches) ⇒ Object
799 800 801 802 803 804 805 806 807 808 |
# File 'lib/rjq/builtins.rb', line 799 def split_at_matches(string, matches) return [string] if matches.empty? offset = 0 matches.map do |match| part = string[offset...match.begin(0)].to_s offset = match.end(0) part end << string[offset..].to_s end |
.splits_builtin(input, context, args) ⇒ Object
1862 1863 1864 1865 |
# File 'lib/rjq/builtins.rb', line 1862 def splits_builtin(input, context, args) string = assert_string(input) split_at_matches(string, regexp_matches(input, context, args, string)) end |
.strftime_builtin(input, context, args, local: false) ⇒ Object
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 |
# File 'lib/rjq/builtins.rb', line 1522 def strftime_builtin(input, context, args, local: false) format = assert_string(eval_arg(args, 0, input, context)) time = if input.is_a?(Array) values = input unless values.first(6).all?(Numeric) raise TypeError, "#{local ? 'strflocaltime' : 'strftime'}/1 requires parsed datetime inputs" end if local Time.local(values[0], values[1] + 1, values[2], values[3], values[4], values[5]) else Time.utc(values[0], values[1] + 1, values[2], values[3], values[4], values[5]) end else raise TypeError, 'strflocaltime/1 requires parsed datetime inputs' if local Time.at(numeric(input)).utc end time.strftime(format) rescue ArgumentError raise TypeError, "#{local ? 'strflocaltime' : 'strftime'}/1 requires parsed datetime inputs" end |
.strptime(input, context, args) ⇒ Object
1548 1549 1550 1551 1552 1553 |
# File 'lib/rjq/builtins.rb', line 1548 def strptime(input, context, args) parsed = DateTime.strptime(assert_string(input), assert_string(eval_arg(args, 0, input, context))) [parsed.year, parsed.month - 1, parsed.day, parsed.hour, parsed.min, parsed.sec, parsed.wday, parsed.yday - 1] rescue Date::Error raise RuntimeError, 'date does not match format' end |
.sub_with_filter(string, regex, replacement_filter, context) ⇒ Object
1821 1822 1823 1824 1825 1826 1827 1828 |
# File 'lib/rjq/builtins.rb', line 1821 def sub_with_filter(string, regex, replacement_filter, context) match = regex.match(string) return [string] unless match replacements_for(replacement_filter, match, context).map do |replacement| string[0...match.begin(0)] + replacement + string[match.end(0)..].to_s end end |
.substitute(input, context, args, global:) ⇒ Object
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 |
# File 'lib/rjq/builtins.rb', line 1801 def substitute(input, context, args, global:) string = assert_string(input) regex, = regexp(input, context, [args.fetch(0)] + args[2..].to_a) replacement_filters(args.fetch(1)).flat_map do |replacement_filter| if global gsub_with_filter(string, regex, replacement_filter, context) else sub_with_filter(string, regex, replacement_filter, context) end end end |
.subtract_flatten_depth(depth) ⇒ Object
535 536 537 538 |
# File 'lib/rjq/builtins.rb', line 535 def subtract_flatten_depth(depth) AST::BinaryOp.new(AST::Literal.new(depth), '-', AST::Literal.new(1)) .eval(nil, AST::Context.new).first end |
.time_array(time) ⇒ Object
1509 1510 1511 |
# File 'lib/rjq/builtins.rb', line 1509 def time_array(time) [time.year, time.month - 1, time.day, time.hour, time.min, time.sec, time.wday, time.yday - 1] end |
.to_entries(value) ⇒ Object
708 709 710 711 712 713 714 715 716 717 |
# File 'lib/rjq/builtins.rb', line 708 def to_entries(value) case value when Hash value.map { |key, item| { 'key' => key, 'value' => item } } when Array value.each_with_index.map { |item, index| { 'key' => index, 'value' => item } } else raise TypeError, "cannot convert #{Value.type_of(value)} to entries" end end |
.to_number(value) ⇒ Object
769 770 771 772 773 774 775 776 |
# File 'lib/rjq/builtins.rb', line 769 def to_number(value) return value if value.is_a?(Numeric) raise TypeError, "cannot convert #{Value.type_of(value)} to number" unless value.is_a?(String) value.match?(/[.eE]/) ? Float(value) : Integer(value, 10) rescue ArgumentError raise TypeError, 'invalid numeric string' end |
.to_stream(value) ⇒ Object
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 |
# File 'lib/rjq/builtins.rb', line 960 def to_stream(value) Enumerator.new do |yielder| stack = [[:visit, value, []]] until stack.empty? type, current, path = stack.pop if type == :emit yielder << current next end children = if current.is_a?(Array) current.each_with_index.map { |item, index| [item, path + [index]] } elsif current.is_a?(Hash) current.map { |key, item| [item, path + [key]] } end if children.nil? yielder << [path, current] elsif children.empty? yielder << [path, current.class.new] else last_component = current.is_a?(Array) ? current.length - 1 : current.keys.last stack << [:emit, [path + [last_component]], nil] children.reverse_each { |child, child_path| stack << [:visit, child, child_path] } end end end end |
.to_string(value) ⇒ Object
778 779 780 781 782 783 784 785 |
# File 'lib/rjq/builtins.rb', line 778 def to_string(value) case value when String value else JSON::Dumper.dump(value, indent: nil) end end |
.transform_regexp_segment(chars, index, line_anchors:, dot_matches_newline:, stop_at_group_end: false) ⇒ Object
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 |
# File 'lib/rjq/builtins.rb', line 1586 def transform_regexp_segment(chars, index, line_anchors:, dot_matches_newline:, stop_at_group_end: false) output = +'' while index < chars.length char = chars[index] if char == '\\' output << char index += 1 output << chars[index] if index < chars.length elsif char == '[' character_class, index = consume_regexp_character_class(chars, index) output << character_class next elsif char == '(' && (inline = (chars, index)) enabled, disabled, body_index = inline child_line_anchors = option_state(line_anchors, enabled, disabled, 'm') child_dot_matches_newline = option_state(dot_matches_newline, enabled, disabled, 's') body, next_index, closed = transform_regexp_segment( chars, body_index, line_anchors: child_line_anchors, dot_matches_newline: child_dot_matches_newline, stop_at_group_end: true ) output << if closed ruby_regexp_group(enabled, disabled, dot_matches_newline, child_dot_matches_newline, body) else chars[index...body_index].join + body end index = next_index next elsif char == '(' body, next_index, closed = transform_regexp_segment( chars, index + 1, line_anchors: line_anchors, dot_matches_newline: dot_matches_newline, stop_at_group_end: true ) output << "(#{body}" output << ')' if closed index = next_index next elsif char == ')' && stop_at_group_end return [output, index + 1, true] elsif char == '^' output << (line_anchors ? '^' : '\\A') elsif char == '$' output << (line_anchors ? '$' : '\\Z') else output << char end index += 1 end [output, index, !stop_at_group_end] end |
.transpose(input) ⇒ Object
1328 1329 1330 1331 1332 |
# File 'lib/rjq/builtins.rb', line 1328 def transpose(input) rows = assert_array(input).map { |row| assert_array(row) } max = rows.map(&:length).max || 0 (0...max).map { |index| rows.map { |row| row[index] } } end |
.truncate_boundary(depth, length) ⇒ Object
1041 1042 1043 1044 1045 1046 1047 1048 1049 |
# File 'lib/rjq/builtins.rb', line 1041 def truncate_boundary(depth, length) return 0 if depth.nil? || (depth.respond_to?(:nan?) && depth.nan?) raise TypeError, 'Array/string slice indices must be integers' unless depth.is_a?(Numeric) return depth.negative? ? 0 : length if depth.respond_to?(:infinite?) && depth.infinite? index = depth.floor index += length if index.negative? [[index, 0].max, length].min end |
.truncate_path(path, depth) ⇒ Object
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 |
# File 'lib/rjq/builtins.rb', line 1029 def truncate_path(path, depth) return nil if path.nil? unless path.is_a?(Array) || path.is_a?(String) raise TypeError, "Cannot index #{Value.type_of(path)} with object" end start = truncate_boundary(depth, path.is_a?(String) ? path.each_char.count : path.length) return path.each_char.drop(start).join if path.is_a?(String) path.drop(start) end |
.truncate_stream(input, context, args) ⇒ Object
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 |
# File 'lib/rjq/builtins.rb', line 1015 def truncate_stream(input, context, args) depth = input Enumerator.new do |yielder| filter_stream(args.fetch(0), nil, context).each do |event| path = Path.read_index(event, 0) next unless Value.compare(length(path), depth).positive? updated = event.nil? ? [] : event.dup updated[0] = truncate_path(path, depth) yielder << updated end end end |
.unique_by_filter(input, context, filter) ⇒ Object
1096 1097 1098 1099 1100 1101 |
# File 'lib/rjq/builtins.rb', line 1096 def unique_by_filter(input, context, filter) unique = decorated_sort(input, context, filter).each_with_object([]) do |(item, key), out| out << [item, key] if out.empty? || !Value.equal?(out.last.last, key) end unique.map(&:first) end |
.unique_values(array) ⇒ Object
1089 1090 1091 1092 1093 1094 |
# File 'lib/rjq/builtins.rb', line 1089 def unique_values(array) array = array.sort { |a, b| Value.compare(a, b) } array.each_with_object([]) do |item, out| out << item if out.empty? || !Value.equal?(out.last, item) end end |
.unsupported_search_result(input, needle) ⇒ Object
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 |
# File 'lib/rjq/builtins.rb', line 1290 def unsupported_search_result(input, needle) if input.is_a?(Hash) Path.read_index(input, needle) unless needle.is_a?(String) return nil end if input.nil? return nil if needle.is_a?(String) || needle.is_a?(Numeric) || needle.is_a?(Hash) Path.read_index(input, needle) end Path.read_index(input, needle) nil end |
.until_filter(input, context, args) ⇒ Object
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 |
# File 'lib/rjq/builtins.rb', line 1422 def until_filter(input, context, args) condition, update = args Enumerator.new do |yielder| tasks = [[:visit, input]] until tasks.empty? type, value, state = tasks.pop if type == :emit yielder << value next end if type == :visit tasks << [:condition, value, filter_stream(condition, value, context)] next end if type == :condition begin result = state.next tasks << [:condition, value, state] if Value.truthy?(result) tasks << [:emit, value] else tasks << [:updates, value, filter_stream(update, value, context)] end rescue StopIteration nil end elsif type == :updates begin next_value = state.next tasks << [:updates, value, state] tasks << [:visit, next_value] rescue StopIteration nil end end end end end |
.uri_escape(input) ⇒ Object
1913 1914 1915 1916 1917 1918 |
# File 'lib/rjq/builtins.rb', line 1913 def uri_escape(input) input.bytes.map do |byte| char = byte.chr char.match?(/[A-Za-z0-9_.~-]/) ? char : '%%%02X' % byte end.join end |
.utf8_byte_length(value) ⇒ Object
407 408 409 410 411 412 |
# File 'lib/rjq/builtins.rb', line 407 def utf8_byte_length(value) return value.bytesize if value.is_a?(String) raise TypeError, "#{Value.type_of(value)} (#{JSON::Dumper.dump(value, indent: nil)}) only strings have UTF-8 byte length" end |
.valid_arity?(name, arity) ⇒ Boolean
2074 2075 2076 |
# File 'lib/rjq/builtins.rb', line 2074 def valid_arity?(name, arity) BUILTIN_ARITIES.fetch(name, []).include?(arity) end |
.validate_pick_path(path) ⇒ Object
918 919 920 921 922 |
# File 'lib/rjq/builtins.rb', line 918 def validate_pick_path(path) return unless path.any? { |part| part.is_a?(Integer) && part.negative? } raise RuntimeError, 'Out of bounds negative array index' end |
.validate_string_search_needle(input, needle) ⇒ Object
1283 1284 1285 1286 1287 1288 |
# File 'lib/rjq/builtins.rb', line 1283 def validate_string_search_needle(input, needle) return if needle.is_a?(String) raise TypeError, 'Array/string slice indices must be integers' if needle.is_a?(Hash) Path.read_index(input, needle) end |
.walk(input, context, filter) ⇒ Object
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 |
# File 'lib/rjq/builtins.rb', line 942 def walk(input, context, filter) Enumerator.new do |yielder| transformed = case input when Array input.flat_map { |item| walk(item, context, filter).to_a } when Hash input.each_with_object({}) do |(key, value), out| values = walk(value, context, filter).take(1) out[key] = values.first unless values.empty? end else input end filter_stream(filter, transformed, context).each { |value| yielder << value } end end |
.while_filter(input, context, args) ⇒ Object
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 |
# File 'lib/rjq/builtins.rb', line 1462 def while_filter(input, context, args) condition, update = args Enumerator.new do |yielder| tasks = [[:visit, input]] until tasks.empty? type, value, state = tasks.pop if type == :emit yielder << value next end if type == :visit tasks << [:condition, value, filter_stream(condition, value, context)] next end if type == :condition begin result = state.next tasks << [:condition, value, state] if Value.truthy?(result) tasks << [:updates, value, filter_stream(update, value, context)] tasks << [:emit, value] end rescue StopIteration nil end elsif type == :updates begin next_value = state.next tasks << [:updates, value, state] tasks << [:visit, next_value] rescue StopIteration nil end end end end end |