Compare commits

..
Author SHA1 Message Date
William Langford 7099becbe8 Some syntax tweaks for AIX 2017-02-11 14:53:46 -05:00
William Langford 96815fe168 Define JV_*PRINTF_LIKE for non-__GNUC__ compilers 2017-02-09 13:16:09 -05:00
46 changed files with 2009 additions and 3772 deletions

No files matched your search

-29
View File
@@ -1,29 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
---
<!--
READ THIS FIRST!
If you have a usage question, please ask us on either Stack Overflow (https://stackoverflow.com/questions/tagged/jq) or in the #jq channel (http://irc.lc/freenode/%23jq/) on Freenode (https://webchat.freenode.net/).
-->
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Provide a minimal test case to reproduce the behavior.
If the input is large, either attach it as a file, or [create a gist](https://gist.github.com) and link to it here.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Environment (please complete the following information):**
- OS and Version: [e.g. macOS, Windows, Linux (please specify distro)]
- jq version [e.g. 1.5]
**Additional context**
Add any other context about the problem here.
-3
View File
@@ -1,3 +0,0 @@
[submodule "modules/oniguruma"]
path = modules/oniguruma
url = https://github.com/kkos/oniguruma.git
+58 -185
View File
@@ -1,201 +1,74 @@
os:
- linux
- osx
sudo: false
language: c
stages:
- name: test
compiler:
- gcc
- clang
- name: build
# Don't run build stage for pull requests to save time and resources.
if: type != pull_request
jobs:
matrix:
include:
# Build with gcc and run tests on Ubuntu.
- &test-ubuntu
stage: test
os: linux
compiler: gcc
- compiler: gcc
env: COVERAGE="--disable-valgrind --enable-gcov"
os: linux
addons:
apt:
packages:
- valgrind
- bison
- automake
addons:
apt:
packages:
- libonig-dev
- valgrind
- bison
before_install:
- uname -s
- rvm install ruby-1.9.3-p551
- rvm use 1.9.3
- rm src/{lexer,parser}.{c,h}
- sed -i.bak '/^AM_INIT_AUTOMAKE(\[-Wno-portability 1\.14\])$/s/14/11/' modules/oniguruma/configure.ac
before_install:
- echo "$TRAVIS_OS_NAME"
- uname -s
- brew update || true;
brew install flex || true;
brew install bison || true;
brew install oniguruma || true;
- rm src/{lexer,parser}.{c,h}
install:
- bundle install --gemfile=docs/Gemfile
- wget http://ftp.debian.org/debian/pool/main/b/bison/bison_3.0.2.dfsg-2_amd64.deb
- ar p bison_3.0.2.dfsg-2_amd64.deb data.tar.xz | tar xJ
- if [ -n "$COVERAGE" ]; then pip install --user cpp-coveralls; fi
install:
- bundle install --gemfile=docs/Gemfile
- wget http://ftp.debian.org/debian/pool/main/b/bison/bison_3.0.2.dfsg-2_amd64.deb
- ar p bison_3.0.2.dfsg-2_amd64.deb data.tar.xz | tar xJ
- if [ -n "$COVERAGE" ]; then pip install --user cpp-coveralls; fi
before_script:
# If this is OS X we'll get bison from brew, else we'll get bison
# from the .deb unpacked above in the install section.
- PATH=/usr/local/opt/bison/bin:$PWD/usr/bin:$PATH
- echo SHELL=$SHELL
- echo PATH=$PATH
- which bison
- bison --version
- autoreconf -if
- ./configure --with-oniguruma=builtin YACC="$(which bison) -y" $COVERAGE
before_script:
# If this is OS X we'll get bison from brew, else we'll get bison
# from the .deb unpacked above in the install section.
- PATH=/usr/local/opt/bison/bin:$PWD/usr/bin:$PATH
- echo SHELL=$SHELL
- echo PATH=$PATH
- which bison
- bison --version
- autoreconf -i
- ./configure YACC="$(which bison) -y" $COVERAGE
script:
# When using the bison from Debian we need to tell that bison where
# to find its data. Yay non-relocatable code. Not.
- echo PATH=$PATH
- which bison
- make BISON_PKGDATADIR=$PWD/usr/share/bison src/parser.c || make src/parser.c
# Make dist!
#
# Make it first to fail the build early, before we test with
# valgrind.
- make dist
# Build and test the dist (without valgrind)
- |
(
tar xvf jq-`scripts/version`.tar.gz &&
cd jq-`scripts/version` &&
pwd &&
./configure --disable-valgrind --with-oniguruma=builtin YACC="$(which bison) -y" $COVERAGE &&
make BISON_PKGDATADIR=$PWD/usr/share/bison src/parser.c || make src/parser.c &&
make -j4 &&
make check -j4 || true
)
# Build and test the HEAD
- make -j4
- make check -j4
script:
# When using the bison from Debian we need to tell that bison where
# to find its data. Yay non-relocatable code. Not.
- echo PATH=$PATH
- which bison
- make BISON_PKGDATADIR=$PWD/usr/share/bison src/parser.c || make src/parser.c
- make -j4
- make check -j4
after_failure:
- cat test-suite.log
- cat tests/*.log
# Build with clang and run tests on Ubuntu.
- <<: *test-ubuntu
compiler: clang
# Build with gcc and run tests with gcov on Ubuntu.
- <<: *test-ubuntu
env: COVERAGE="--disable-valgrind --enable-gcov"
after_script:
- rm -rf src/.libs # don't care about coverage for libjq
- coveralls --gcov-options '\-lp'
-e src/lexer.c -e src/parser.c -e src/jv_dtoa.c
# Build with gcc and run tests on macOS.
- &test-osx
<<: *test-ubuntu
os: osx
before_install:
- uname -s
- brew update
- brew install flex
- brew install bison
- rvm install ruby-1.9.3-p551
- rvm use 1.9.3
- rm src/{lexer,parser}.{c,h}
- sed -i.bak '/^AM_INIT_AUTOMAKE(\[-Wno-portability 1\.14\])$/s/14/11/' modules/oniguruma/configure.ac
install:
- bundle install --gemfile=docs/Gemfile
- if [ -n "$COVERAGE" ]; then pip install --user cpp-coveralls; fi
# Build with clang and run tests on macOS.
- <<: *test-osx
compiler: clang
# Build with gcc and run tests on Alpine Linux v3.7 (inside chroot).
# Note: Alpine uses musl libc.
- &test-alpine
stage: test
os: linux
language: minimal
compiler: gcc
sudo: true
before_install:
- "wget 'https://raw.githubusercontent.com/alpinelinux/alpine-chroot-install/v0.7.0/alpine-chroot-install' \
&& echo '090d323d887ef3a2fd4e752428553f22a52b87bb alpine-chroot-install' | sha1sum -c || travis_terminate 1"
- alpine() { /alpine/enter-chroot -u "$USER" "$@"; }
install:
- sudo sh alpine-chroot-install -b v3.7 -a "$ARCH"
-p 'build-base automake autoconf bison libtool oniguruma-dev'
before_script:
- autoreconf -if
script:
- alpine ./configure --disable-docs
- alpine make
- alpine make check
# Build release binary statically linked with musl libc on Alpine Linux
# (inside chroot). If building a tagged commit, then deploy release
# tarball to GitHub Releases.
- &build-alpine
<<: *test-alpine
stage: build
env: ARCH=x86_64
script:
- alpine ./configure --disable-docs --enable-all-static
CFLAGS='-Os -static -no-pie' CXXFLAGS='-Os -static -no-pie'
- alpine make
- alpine strip jq
- jq -V
- ls -lah jq
- file jq
# Ensure that the built executable is really statically linked.
- file jq | grep -Fw 'statically linked'
before_deploy:
- PKGNAME="jq-$TRAVIS_TAG-$ARCH-linux"
- mkdir $PKGNAME && mv jq $PKGNAME/
- tar -czf $PKGNAME.tar.gz $PKGNAME/
- sha256sum $PKGNAME.tar.gz > $PKGNAME.tar.gz.sha256
deploy:
provider: releases
api_key:
secure: # TODO: put encrypted GitHub token here!
file: jq-$TRAVIS_TAG-*.tar.gz*
file_glob: true
skip_cleanup: true
on:
tags: true
# Build binaries for other architectures using QEMU user-mode emulation.
- <<: *build-alpine
env: ARCH=x86
- <<: *build-alpine
env: ARCH=aarch64
- <<: *build-alpine
env: ARCH=armhf
- <<: *build-alpine
env: ARCH=ppc64le
after_script:
- |
if [ -n "$COVERAGE" ]; then
rm -rf src/.libs # don't care about coverage for libjq
coveralls --gcov-options '\-lp' \
-e src/lexer.c -e src/parser.c -e src/jv_dtoa.c
fi
after_failure:
- cat test-suite.log
- cat tests/*.log
notifications:
email: false
-3
View File
@@ -19,13 +19,11 @@ cdnbacon <mike@busbud.com>
Charles Merriam <charles.merriam@gmail.com>
Colin von Heuring <colin@janrain.com>
Damian Gryski <damian@gryski.com>
David Fetter <david@fetter.org> - added --rawfile
David Haguenauer <ml@kurokatta.org>
David R. MacIver <david@drmaciver.com> - bug fixes
David Tolnay <dtolnay@gmail.com> - destructuring, build improvements
Doug Luce <doug@github.con.com> - build
Eiichi Sato <sato.eiichi@gmail.com>
Eric Bréchemier <eric@egull.co> - bug fix
Filippo Giunchedi <fgiunchedi@gmail.com> - bug fixes
Filippo Valsorda <filippo.valsorda@gmail.com> - recursive object merge (`*`)
Hanfei Shen <qqshfox@gmail.com>
@@ -60,7 +58,6 @@ Ryoichi KATO <ryo1kato@gmail.com> - doc fixes
Rémy Léone <remy.leone@gmail.com> - add .travis.yml
Santiago Lapresta <santiago.lapresta@gmail.com> - join, arrays, all, any, other filters
Sebastian Freundt <freundt@ga-group.nl> - build
Shaun Guth <shaun.guth@gmail.com> - base64d
Shay Elkin <shay@everything.me>
Simon Elsbrock <simon@iodev.org> - Debian
Stefan Seemayer <stefan@seemayer.de>
+5 -23
View File
@@ -48,7 +48,7 @@ AM_YFLAGS = --warnings=all -d
lib_LTLIBRARIES = libjq.la
libjq_la_SOURCES = ${LIBJQ_SRC}
libjq_la_LIBADD = -lm
libjq_la_LDFLAGS = $(onig_LDFLAGS) -export-symbols-regex '^j[qv]_' -version-info 1:4:0
libjq_la_LDFLAGS = -export-symbols-regex '^j[qv]_' -version-info 1:4:0
if WIN32
libjq_la_LIBADD += -lshlwapi
@@ -109,17 +109,13 @@ jq_SOURCES = src/main.c src/version.h
jq_LDFLAGS = -static-libtool-libs
jq_LDADD = libjq.la -lm
if WIN32
jq_LDADD += -lshlwapi
endif
if ENABLE_ALL_STATIC
jq_LDFLAGS += -all-static
endif
### Tests (make check)
TESTS = tests/optionaltest tests/mantest tests/jqtest tests/onigtest tests/shtest tests/utf8test tests/base64test
TESTS = tests/optionaltest tests/mantest tests/jqtest tests/onigtest tests/shtest tests/utf8test
TESTS_ENVIRONMENT = NO_VALGRIND=$(NO_VALGRIND)
@@ -137,15 +133,6 @@ jq.1: $(srcdir)/jq.1.prebuilt
endif
### Build oniguruma
if BUILD_ONIGURUMA
libjq_la_LIBADD += modules/oniguruma/src/.libs/libonig.la
SUBDIRS = modules/oniguruma
endif
AM_CFLAGS += $(onig_CFLAGS)
### Packaging
docs/site.yml: configure.ac
@@ -157,11 +144,11 @@ install-binaries: $(BUILT_SOURCES)
DOC_FILES = docs/content docs/public docs/templates docs/site.yml \
docs/Gemfile docs/Gemfile.lock docs/Rakefile docs/README.md \
jq.1.prebuilt
docs/default_manpage.md jq.1.default
EXTRA_DIST = $(DOC_FILES) $(man_MANS) $(TESTS) $(TEST_LOG_COMPILER) \
jq.1.prebuilt jq.spec src/lexer.c src/lexer.h src/parser.c \
src/parser.h src/version.h src/builtin.jq \
src/parser.h src/version.h src/builtin.inc \
scripts/version tests/jq.test tests/modules/.jq \
tests/modules/a.jq tests/modules/b/b.jq tests/modules/c/c.jq \
tests/modules/c/d.jq tests/modules/data.json \
@@ -171,12 +158,7 @@ EXTRA_DIST = $(DOC_FILES) $(man_MANS) $(TESTS) $(TEST_LOG_COMPILER) \
tests/modules/test_bind_order0.jq \
tests/modules/test_bind_order1.jq \
tests/modules/test_bind_order2.jq tests/onig.supp \
tests/onig.test tests/setup tests/torture/input0.json \
tests/optional.test tests/optionaltest \
tests/utf8-truncate.jq tests/utf8test \
tests/base64.test tests/base64test \
tests/jq-f-test.sh tests/shtest
tests/onig.test tests/setup tests/torture/input0.json
# README.md is expected in Github projects, good stuff in it, so we'll
+6 -8
View File
@@ -23,21 +23,19 @@ Source tarball and built executable releases can be found on the
homepage and on the github release page, https://github.com/stedolan/jq/releases
If you're building directly from the latest git, you'll need flex,
bison (3.0 or newer), libtool, make, and autoconf installed.
To get regexp support you'll also need to install Oniguruma or clone it as a
git submodule as per the instructions below.
(note that jq's tests require regexp support to pass). To build, run:
bison (3.0 or newer), libtool, make, and autoconf installed. To get
regexp support you'll also need to install Oniguruma (note that jq's
tests require regexp support to pass). To build, run:
git submodule update --init # if building from git to get oniguruma
autoreconf -fi # if building from git
./configure --with-oniguruma=builtin
autoreconf -i # if building from git
./configure
make -j8
make check
To build without bison or flex, add `--disable-maintainer-mode` to the
./configure invocation:
./configure --with-oniguruma=builtin --disable-maintainer-mode
./configure --disable-maintainer-mode
(Developers must not use `--disable-maintainer-mode`, not when making
changes to the jq parser and/or lexer.)
+6 -10
View File
@@ -5,21 +5,18 @@ environment:
- MSYSTEM: MINGW32
PATH: C:\msys64\usr\bin;C:\msys64\mingw32\bin;C:\Windows\System32;C:\Windows;%PATH%
clone_script:
- bash -lc "git clone -q --branch=$APPVEYOR_REPO_BRANCH https://github.com/${APPVEYOR_REPO_NAME}.git $APPVEYOR_BUILD_FOLDER"
- bash -lc "cd $APPVEYOR_BUILD_FOLDER && git checkout -qf $APPVEYOR_REPO_BRANCH"
- bash -lc "cd $APPVEYOR_BUILD_FOLDER && git submodule update --init --recursive"
install:
# update mysy2
- C:\msys64\usr\bin\bash -lc "pacman --needed --noconfirm -Sy pacman-mirrors"
- C:\msys64\usr\bin\bash -lc "pacman --noconfirm -Sy"
- C:\msys64\usr\bin\bash -lc "pacman --noconfirm -S autoconf automake bison flex"
- C:\msys64\usr\bin\bash -lc "pacman --noconfirm -S git"
- C:\msys64\usr\bin\bash -lc "pacman --noconfirm -S mingw-w64-i686-oniguruma mingw-w64-x86_64-oniguruma"
build_script:
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && autoreconf -i"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && ./configure --with-oniguruma=builtin --disable-shared --enable-static --enable-all-static"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && ./configure --disable-shared --enable-static --enable-all-static"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && make -j8"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && cat jq.1 | groff -mandoc -Thtml > jq.html"
- 7z a jq-package.zip jq.1 jq.html jq.exe
@@ -29,9 +26,9 @@ build_script:
test_script:
# tests/optionaltest and tests/shtest fail on Windows; run them
# anyways but ignore their failures. Also, trace shtest.
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && make -j3 SUBDIRS= 'TESTS=tests/mantest tests/jqtest tests/onigtest tests/base64test' check"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && make SUBDIRS= TESTS=tests/optionaltest check || true"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && make SUBDIRS= TRACE_TESTS=1 TESTS=tests/shtest check || true"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && make -j3 'TESTS=tests/mantest tests/jqtest tests/onigtest' check"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && make TESTS=tests/optionaltest check || cat test-suite.log"
- bash -lc "exec 0</dev/null && cd $APPVEYOR_BUILD_FOLDER && make TRACE_TESTS=1 TESTS=tests/shtest check || cat test-suite.log"
artifacts:
- path: jq-package.zip
@@ -45,7 +42,6 @@ artifacts:
on_failure:
- cat config.log
- cat test-suite.log
- appveyor PushArtifact test-suite.log
# also push the jq.exe so that someone can download it anyways...
+4 -4
View File
@@ -10,10 +10,10 @@ NJOBS="-j`sysctl -n hw.ncpu || echo 1`"
# Get oniguruma
rm -rf $PWD/build/ios oniguruma-5.9.6
echo "Downloading oniguruma 5.9.6"
rm -rf $PWD/build/ios onig-5.9.5
echo "Downloading oniguruma 5.9.5"
curl -L https://github.com/kkos/oniguruma/archive/v5.9.6.tar.gz | tar xz
cd oniguruma-5.9.6
cd oniguruma-5.9.5
# So, we need to remake the configure scripts so that the arm64 architecture
# exists in config.sub. In order to keep autoreconf from failing, create
@@ -50,7 +50,7 @@ for arch in i386 x86_64 armv7 armv7s arm64; do
# Build oniguruma for this architecture
cd oniguruma-5.9.6
cd onig-5.9.5
CC=$CC CFLAGS=$CFLAGS LDFLAGS=$LDFLAGS ./configure --disable-shared --enable-static --host=$HOST --prefix=$ORIG_PWD/build/ios/$arch
STATUS=$?
if [ $STATUS -ne 0 ]
+36 -57
View File
@@ -1,7 +1,4 @@
m4_define([jq_version],
m4_esyscmd_s([(git rev-parse --verify -q jq-1.0 > /dev/null &&
(git describe --tags --dirty --match 'jq-*'|sed 's/^jq-//')) ||
echo `git rev-parse --abbrev-ref HEAD`-`git describe --always --dirty`])))
m4_define([jq_version], m4_esyscmd_s([git describe --tags --dirty --match 'jq-*'|sed 's/^jq-//']))
AC_INIT([jq], [jq_version], [https://github.com/stedolan/jq/issues],
[jq], [https://stedolan.github.io/jq])
@@ -41,9 +38,41 @@ if test "$USE_MAINTAINER_MODE" = yes; then
[AC_MSG_ERROR([You need bison version 3.0 or greater, or use --disable-maintainer-mode.])])
fi
AC_CHECK_PROGS(LEX, flex lex)
AC_PROG_LEX
if test "x$LEX" != xflex; then
LEX="$SHELL $missing_dir/missing flex"
fi
fi
##########################################################################
# check for ONIGURUMA library
##########################################################################
AC_ARG_WITH([oniguruma],
[AS_HELP_STRING([--with-oniguruma=prefix],
[try this for a non-standard install prefix of the oniguruma library])],
[],
[with_oniguruma=yes])
AS_IF([test "x$with_oniguruma" != xno], [
AS_IF([test "x$with_oniguruma" != xyes], [
CFLAGS="$CFLAGS -I${with_oniguruma}/include"
LDFLAGS="$LDFLAGS -L${with_oniguruma}/lib"
])
# check for ONIGURUMA library
have_oniguruma=0
AC_CHECK_HEADER("oniguruma.h",
AC_CHECK_LIB([onig],[onig_version],[LIBS="$LIBS -lonig"; have_oniguruma=1;]))
# handle check results
AS_IF([test $have_oniguruma = 1], [
AC_DEFINE([HAVE_ONIGURUMA], 1, [Define to 1 if Oniguruma is installed])
], [
AC_MSG_NOTICE([Oniguruma was not found.])
AC_MSG_NOTICE([Try setting the location using '--with-oniguruma=PREFIX'])
])
])
dnl Check for valgrind
AC_CHECK_PROGS(valgrind_cmd, valgrind)
if test "x$valgrind_cmd" = "x" ; then
@@ -127,8 +156,6 @@ AC_FIND_FUNC([strftime], [c], [#include <time.h>], [0, 0, 0, 0])
AC_FIND_FUNC([timegm], [c], [#include <time.h>], [0])
AC_FIND_FUNC([gmtime_r], [c], [#include <time.h>], [0, 0])
AC_FIND_FUNC([gmtime], [c], [#include <time.h>], [0])
AC_FIND_FUNC([localtime_r], [c], [#include <time.h>], [0, 0])
AC_FIND_FUNC([localtime], [c], [#include <time.h>], [0])
AC_FIND_FUNC([gettimeofday], [c], [#include <time.h>], [0, 0])
AC_CHECK_MEMBER([struct tm.tm_gmtoff], [AC_DEFINE([HAVE_TM_TM_GMT_OFF],1,[Define to 1 if the system has the tm_gmt_off field in struct tm])],
[], [[#include <time.h>]])
@@ -174,12 +201,11 @@ AC_CHECK_MATH_FUNC(fma,[.5,1.0,1.5])
AC_CHECK_MATH_FUNC(fmax,[.5,1.0])
AC_CHECK_MATH_FUNC(fmin,[.5,1.0])
AC_CHECK_MATH_FUNC(fmod,[.5,1.0])
AC_FIND_FUNC([frexp], [m c], [#include <math.h>], [0, 0])
AC_CHECK_MATH_FUNC(frexp,[.5,1.0])
AC_CHECK_MATH_FUNC(gamma,[.5])
AC_CHECK_MATH_FUNC(hypot, [.5,.5])
AC_CHECK_MATH_FUNC(j0, [.5])
AC_CHECK_MATH_FUNC(j1, [.5])
AC_CHECK_MATH_FUNC(jn, [1,.5])
AC_CHECK_MATH_FUNC(ldexp,[.5,2])
AC_CHECK_MATH_FUNC(lgamma,[.5])
AC_CHECK_MATH_FUNC(log10, [.5])
@@ -187,8 +213,7 @@ AC_CHECK_MATH_FUNC(log1p,[.5])
AC_CHECK_MATH_FUNC(log2, [.5])
AC_CHECK_MATH_FUNC(log, [.5])
AC_CHECK_MATH_FUNC(logb,[.5])
AC_CHECK_MATH_FUNC([modf], [m c], [#include <math.h>], [0, 0])
AC_CHECK_MATH_FUNC([lgamma_r], [m c], [#include <math.h>], [0, 0])
AC_CHECK_MATH_FUNC(modf,[.5,1.0])
AC_CHECK_MATH_FUNC(nearbyint,[.5])
AC_CHECK_MATH_FUNC(nextafter,[.5,1.0])
AC_CHECK_MATH_FUNC(nexttoward,[.5,1.0])
@@ -209,7 +234,6 @@ AC_CHECK_MATH_FUNC(tgamma, [.5])
AC_CHECK_MATH_FUNC(trunc,[.5])
AC_CHECK_MATH_FUNC(y0, [.5])
AC_CHECK_MATH_FUNC(y1, [.5])
AC_CHECK_MATH_FUNC(yn, [1,.5])
dnl Thread local storage
have___thread=no
@@ -230,51 +254,6 @@ AC_C_BIGENDIAN(
AC_MSG_ERROR(universial endianess not supported)
)
dnl Oniguruma
AC_ARG_WITH([oniguruma],
[AS_HELP_STRING([--with-oniguruma=prefix],
[try this for a non-standard install prefix of the oniguruma library])], ,
[with_oniguruma=yes])
onig_CFLAGS=
onig_LDFLAGS=
build_oniguruma=no
AS_IF([test "x$with_oniguruma" != xno], [
save_CFLAGS="$CFLAGS"
save_LDFLAGS="$LDFLAGS"
AS_IF([test "x$with_oniguruma" != xyes], [
AS_IF([test "x$with_oniguruma" = xbuiltin], [
build_oniguruma=yes
], [
onig_CFLAGS="-I${with_oniguruma}/include"
onig_LDFLAGS="-L${with_oniguruma}/lib"
])
])
AS_IF([test "x$build_oniguruma" = xno], [
# check for ONIGURUMA library, either in /usr or where requested
CFLAGS="$CFLAGS $onig_CFLAGS"
LDFLAGS="$LDFLAGS $onig_LDFLAGS"
AC_CHECK_HEADER("oniguruma.h",
AC_CHECK_LIB([onig],[onig_version]))
# handle check results
AS_IF([test "x$ac_cv_lib_onig_onig_version" != "xyes"], [
build_oniguruma=yes
AC_MSG_NOTICE([Oniguruma was not found. Will use the packaged oniguruma.])
])
])
AS_IF([test "x$build_oniguruma" = xyes -a -f "${srcdir}/modules/oniguruma/configure.ac" ], [
onig_CFLAGS="-I${srcdir}/modules/oniguruma/src"
onig_LDFLAGS="-L${srcdir}/modules/oniguruma/src -Wl,-rpath,${libdir}"
AC_CONFIG_SUBDIRS([modules/oniguruma])
AC_DEFINE([HAVE_LIBONIG],1,[Define to 1 if the system includes libonig])
])
CFLAGS="$save_CFLAGS"
LDFLAGS="$save_LDFLAGS"
])
AC_SUBST(onig_CFLAGS)
AC_SUBST(onig_LDFLAGS)
AM_CONDITIONAL([BUILD_ONIGURUMA], [test "x$build_oniguruma" = xyes])
AC_SUBST([BUNDLER], ["$bundle_cmd"])
AC_CONFIG_MACRO_DIR([config/m4])
-10
View File
@@ -30,16 +30,6 @@ end
Liquid::Template.register_filter(ExtraFilters)
begin
`java 2>&1`
rescue
class Bonsai::Exporter
def self.compress_assets
Bonsai.log "java not found! Not compressing javascript or stylesheets"
end
end
end
task :build do
Bonsai.root_dir = Dir.pwd
Bonsai::Exporter.publish!
+2 -6
View File
@@ -66,12 +66,8 @@ body:
### FreeBSD
* `pkg install jq` as root installs a pre-built
[binary package](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/pkgng-intro.html).
* `make -C /usr/ports/textproc/jq install clean` as root installs the
[jq](https://www.freshports.org/textproc/jq/)
[port](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/ports-using.html)
from source.
* Use [FreshPorts](https://www.freshports.org/textproc/jq/) to install
jq 1.4 with `pkg install jq`.
### Solaris
+181 -335
View File
@@ -160,9 +160,6 @@ sections:
terminal. You can force it to produce color even if writing to
a pipe or a file using `-C`, and disable color with `-M`.
Colors can be configured with the `JQ_COLORS` environment
variable (see below).
* `--ascii-output` / `-a`:
jq usually outputs non-ASCII Unicode codepoints as UTF-8, even
@@ -212,9 +209,6 @@ sections:
problem or system error, 3 if there was a jq program compile
error, or 0 if the jq program ran.
Another way to set the exit status is with the `halt_error`
builtin function.
* `--arg name value`:
This option passes a value to the jq program as a predefined
@@ -223,9 +217,6 @@ sections:
`value` will be treated as a string, so `--arg foo 123` will
bind `$foo` to `"123"`.
Named arguments are also available to the jq program as
`$ARGS.named`.
* `--argjson name JSON-text`:
This option passes a JSON-encoded value to the jq program as a
@@ -236,17 +227,10 @@ sections:
This option reads all the JSON texts in the named file and binds
an array of the parsed JSON values to the given global variable.
If you run jq with `--slurpfile foo bar`, then `$foo` is available
If you run jq with `--argfile foo bar`, then `$foo` is available
in the program and has an array whose elements correspond to the
texts in the file named `bar`.
* `--rawfile variable-name filename`:
This option reads in the named file and binds its contents to the given
global variable. If you run jq with `--rawfile foo bar`, then `$foo` is
available in the program and has a string whose contents are to the texs
in the file named `bar`.
* `--argfile variable-name filename`:
Do not use. Use `--slurpfile` instead.
@@ -255,16 +239,6 @@ sections:
one text, then that is used, else an array of texts is used as
in `--slurpfile`.)
* `--args`:
Remaining arguments are positional string arguments. These are
available to the jq program as `$ARGS.positional[]`.
* `--jsonargs`:
Remaining arguments are positional JSON text arguments. These
are available to the jq program as `$ARGS.positional[]`.
* `--run-tests [filename]`:
Runs the tests in the given file or standard input. This must
@@ -281,12 +255,12 @@ sections:
- title: Basic filters
entries:
- title: "Identity: `.`"
- title: "`.`"
body: |
The absolute simplest filter is `.` . This is a filter that
takes its input and produces it unchanged as output. That is,
this is the identity operator.
The absolute simplest (and least interesting) filter
is `.`. This is a filter that takes its input and
produces it unchanged as output.
Since jq by default pretty-prints all output, this trivial
program can be a useful way of formatting JSON output from,
@@ -297,24 +271,17 @@ sections:
input: '"Hello, world!"'
output: ['"Hello, world!"']
- title: "Object Identifier-Index: `.foo`, `.foo.bar`"
- title: "`.foo`, `.foo.bar`"
body: |
The simplest *useful* filter is `.foo`. When given a
JSON object (aka dictionary or hash) as input, it produces
the value at the key "foo", or null if there's none present.
A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.
This syntax only works for simple, identifier-like keys, that
is, keys that are all made of alphanumeric characters and
underscore, and which do not start with a digit.
If the key contains special characters, you need to surround
it with double quotes like this: `."foo$"`, or else `.["foo$"]`.
it with double quotes like this: `."foo$"`.
For example `.["foo::bar"]` and `.["foo.bar"]` work while
`.foo::bar` does not, and `.foo.bar` means `.["foo"].["bar"]`.
A filter of the form `.foo.bar` is equivalent to `.foo|.bar`.
examples:
- program: '.foo'
@@ -327,7 +294,7 @@ sections:
input: '{"foo": 42}'
output: [42]
- title: "Optional Object Identifier-Index: `.foo?`"
- title: "`.foo?`"
body: |
Just like `.foo`, but does not output even an error when `.`
@@ -347,22 +314,37 @@ sections:
input: '[1,2]'
output: ['[]']
- title: "Generic Object Index: `.[<string>]`"
- title: "`.[<string>]`, `.[2]`, `.[10:15]`"
body: |
You can also look up fields of an object using syntax like
`.["foo"]` (.foo above is a shorthand version of this, but
only for identifier-like strings).
`.["foo"]` (.foo above is a shorthand version of this). This
one works for arrays as well, if the key is an
integer. Arrays are zero-based (like javascript), so `.[2]`
returns the third element of the array.
- title: "Array Index: `.[2]`"
body: |
The `.[10:15]` syntax can be used to return a subarray of an
array or substring of a string. The array returned by
`.[10:15]` will be of length 5, containing the elements from
index 10 (inclusive) to index 15 (exclusive). Either index may
be negative (in which case it counts backwards from the end of
the array), or omitted (in which case it refers to the start
or end of the array).
When the index value is an integer, `.[<value>]` can index
arrays. Arrays are zero-based, so `.[2]` returns the third
element.
The `.[2]` syntax can be used to return the element at the
given index. Negative indices are allowed, with -1 referring
to the last element, -2 referring to the next to last element,
and so on.
Negative indices are allowed, with -1 referring to the last
element, -2 referring to the next to last element, and so on.
The `.foo` syntax only works for simply keys i.e. keys that
are all alphanumeric characters. `.[<string>]` works with
keys that contain special characters such as colons and dots.
For example `.["foo::bar"]` and `.["foo.bar"]` work while
`.foo::bar` and `.foo.bar` would not.
The `?` "operator" can also be used with the slice operator,
as in `.[10:15]?`, which outputs values where the inputs are
slice-able.
examples:
- program: '.[0]'
@@ -373,22 +355,6 @@ sections:
input: '[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]'
output: ['null']
- program: '.[-2]'
input: '[1,2,3]'
output: ['2']
- title: "Array/String Slice: `.[10:15]`"
body: |
The `.[10:15]` syntax can be used to return a subarray of an
array or substring of a string. The array returned by
`.[10:15]` will be of length 5, containing the elements from
index 10 (inclusive) to index 15 (exclusive). Either index may
be negative (in which case it counts backwards from the end of
the array), or omitted (in which case it refers to the start
or end of the array).
examples:
- program: '.[2:4]'
input: '["a","b","c","d","e"]'
output: ['["c", "d"]']
@@ -405,7 +371,11 @@ sections:
input: '["a","b","c","d","e"]'
output: ['["d", "e"]']
- title: "Array/Object Value Iterator: `.[]`"
- program: '.[-2]'
input: '[1,2,3]'
output: ['2']
- title: "`.[]`"
body: |
If you use the `.[index]` syntax, but omit the index
@@ -438,16 +408,15 @@ sections:
Like `.[]`, but no errors will be output if . is not an array
or object.
- title: "Comma: `,`"
- title: "`,`"
body: |
If two filters are separated by a comma, then the
same input will be fed into both and the two filters' output
value streams will be concatenated in order: first, all of the
outputs produced by the left expression, and then all of the
outputs produced by the right. For instance, filter `.foo,
.bar`, produces both the "foo" fields and "bar" fields as
separate outputs.
input will be fed into both and there will be multiple
outputs: first, all of the outputs produced by the left
expression, and then all of the outputs produced by the
right. For instance, filter `.foo, .bar`, produces
both the "foo" fields and "bar" fields as separate outputs.
examples:
- program: '.foo, .bar'
@@ -462,7 +431,7 @@ sections:
input: '["a","b","c","d","e"]'
output: ['"e"', '"c"']
- title: "Pipe: `|`"
- title: "`|`"
body: |
The | operator combines two filters by feeding the output(s) of
@@ -512,16 +481,16 @@ sections:
instead.
entries:
- title: "Array construction: `[]`"
- title: Array construction - `[]`
body: |
As in JSON, `[]` is used to construct arrays, as in
`[1,2,3]`. The elements of the arrays can be any jq
expression, including a pipeline. All of the results produced
by all of the expressions are collected into one big array.
You can use it to construct an array out of a known quantity
of values (as in `[.foo, .bar, .baz]`) or to "collect" all the
results of a filter into an array (as in `[.items[].name]`)
expression. All of the results produced by all of the
expressions are collected into one big array. You can use it
to construct an array out of a known quantity of values (as
in `[.foo, .bar, .baz]`) or to "collect" all the results of a
filter into an array (as in `[.items[].name]`)
Once you understand the "," operator, you can look at jq's array
syntax in a different light: the expression `[1,2,3]` is not using a
@@ -537,37 +506,30 @@ sections:
- program: "[.user, .projects[]]"
input: '{"user":"stedolan", "projects": ["jq", "wikiflow"]}'
output: ['["stedolan", "jq", "wikiflow"]']
- program: "[ .[] | . * 2]"
input: '[1, 2, 3]'
output: ['[2, 4, 6]']
- title: "Object Construction: `{}`"
- title: Objects - `{}`
body: |
Like JSON, `{}` is for constructing objects (aka
dictionaries or hashes), as in: `{"a": 42, "b": 17}`.
If the keys are "identifier-like", then the quotes can be left
off, as in `{a:42, b:17}`. Keys generated by expressions need
to be parenthesized, e.g., `{("a"+"b"):59}`.
The value can be any expression (although you may need to
wrap it in parentheses if it's a complicated one), which gets
applied to the {} expression's input (remember, all filters
have an input and an output).
If the keys are "sensible" (all alphabetic characters), then
the quotes can be left off. The value can be any expression
(although you may need to wrap it in parentheses if it's a
complicated one), which gets applied to the {} expression's
input (remember, all filters have an input and an
output).
{foo: .bar}
will produce the JSON object `{"foo": 42}` if given the JSON
object `{"bar":42, "baz":43}` as its input. You can use this
to select particular fields of an object: if the input is an
object with "user", "title", "id", and "content" fields and
you just want "user" and "title", you can write
object `{"bar":42, "baz":43}`. You can use this to select
particular fields of an object: if the input is an object
with "user", "title", "id", and "content" fields and you
just want "user" and "title", you can write
{user: .user, title: .title}
Because that is so common, there's a shortcut syntax for it:
`{user, title}`.
Because that's so common, there's a shortcut syntax: `{user, title}`.
If one of the expressions produces multiple results,
multiple dictionaries will be produced. If the input's
@@ -602,24 +564,6 @@ sections:
input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'
output: ['{"stedolan": ["JQ Primer", "More JQ"]}']
- title: "Recursive Descent: `..`"
body: |
Recursively descends `.`, producing every value. This is the
same as the zero-argument `recurse` builtin (see below). This
is intended to resemble the XPath `//` operator. Note that
`..a` does not work; use `..|.a` instead. In the example
below we use `..|.a?` to find all the values of object keys
"a" in any object found "below" `.`.
This is particularly useful in conjunction with `path(EXP)`
(also see below) and the `?` operator.
examples:
- program: '..|.a?'
input: '[[{"a":1}]]'
output: ['1']
- title: Builtin operators and functions
body: |
@@ -630,7 +574,7 @@ sections:
no result.
entries:
- title: "Addition: `+`"
- title: Addition - `+`
body: |
The operator `+` takes two filters, applies them both
@@ -669,7 +613,7 @@ sections:
input: 'null'
output: ['{"a": 42, "b": 2, "c": 3}']
- title: "Subtraction: `-`"
- title: Subtraction - `-`
body: |
As well as normal arithmetic subtraction on numbers, the `-`
@@ -684,7 +628,7 @@ sections:
input: '["xml", "yaml", "json"]'
output: ['["json"]']
- title: "Multiplication, division, modulo: `*`, `/`, and `%`"
- title: Multiplication, division, modulo - `*`, `/`, and `%`
body: |
These infix operators behave as expected when given two numbers.
@@ -999,25 +943,7 @@ sections:
Produces an error, just like `.a` applied to values other than
null and objects would, but with the given message as the
error's value. Errors can be caught with try/catch; see below.
- title: "`halt`"
body: |
Stops the jq program with no further outputs. jq will exit
with exit status `0`.
- title: "`halt_error`, `halt_error(exit_code)`"
body: |
Stops the jq program with no further outputs. The input will
be printed on `stderr` as raw output (i.e., strings will not
have double quotes) with no decoration, not even a newline.
The given `exit_code` (defaulting to `5`) will be jq's exit
status.
For example, `"Error: somthing went wrong\n"|halt_error(1)`.
error's value.
- title: "`$__loc__`"
body: |
@@ -1701,22 +1627,27 @@ sections:
output:
- '[{"a":{"b":2}}]'
- title: "`$ENV`, `env`"
- title: "`..`"
body: |
`$ENV` is an object representing the environment variables as
set when the jq program started.
`env` outputs an object representing jq's current environment.
At the moment there is no builtin for setting environment
variables.
Short-hand for `recurse` without arguments. This is intended
to resemble the XPath `//` operator. Note that `..a` does not
work; use `..|a` instead. In the example below we use
`..|.a?` to find all the values of object keys "a" in any
object found "below" `.`.
examples:
- program: '$ENV.PAGER'
input: 'null'
output: ['"less"']
- program: '..|.a?'
input: '[[{"a":1}]]'
output: ['1']
- title: "`env`"
body: |
Outputs an object representing jq's environment.
examples:
- program: 'env.PAGER'
input: 'null'
output: ['"less"']
@@ -1839,11 +1770,6 @@ sections:
The input is converted to base64 as specified by RFC 4648.
* `@base64d`:
The inverse of `@base64`, input is decoded as specified by RFC 4648.
Note\: If the decoded string is not UTF-8, the results are undefined.
This syntax can be combined with string interpolation in a
useful way. You can follow a `@foo` token with a string
literal. The contents of the string literal will *not* be
@@ -1873,14 +1799,6 @@ sections:
input: "\"O'Hara's Ale\""
output: ["\"echo 'O'\\\\''Hara'\\\\''s Ale'\""]
- program: '@base64'
input: '"This is a message"'
output: ['"VGhpcyBpcyBhIG1lc3NhZ2U="']
- program: '@base64d'
input: '"VGhpcyBpcyBhIG1lc3NhZ2U="'
output: ['"This is a message"']
- title: "Dates"
body: |
@@ -1904,25 +1822,19 @@ sections:
the Unix epoch.
Low-level jq interfaces to the C-library time functions are
also provided: `strptime`, `strftime`, `strflocaltime`,
`mktime`, `gmtime`, and `localtime`. Refer to your host
operating system's documentation for the format strings used
by `strptime` and `strftime`. Note: these are not necessarily
stable interfaces in jq, particularly as to their localization
functionality.
also provided: `strptime`, `strftime`, `mktime`, and `gmtime`.
Refer to your host operating system's documentation for the
format strings used by `strptime` and `strftime`. Note: these
are not necessarily stable interfaces in jq, particularly as
to their localization functionality.
The `gmtime` builtin consumes a number of seconds since the
Unix epoch and outputs a "broken down time" representation of
Greenwhich Meridian time as an array of numbers representing
(in this order): the year, the month (zero-based), the day of
the month (one-based), the hour of the day, the minute of the
hour, the second of the minute, the day of the week, and the
day of the year -- all one-based unless otherwise stated. The
day of the week number may be wrong on some systems for dates
before March 1st 1900, or after December 31 2099.
The `localtime` builtin works like the `gmtime` builtin, but
using the local timezone setting.
time as an array of numbers representing (in this order): the
year, the month (zero-based), the day of the month, the hour
of the day, the minute of the hour, the second of the minute,
the day of the week, and the day of the year -- all one-based
unless otherwise stated.
The `mktime` builtin consumes "broken down time"
representations of time output by `gmtime` and `strptime`.
@@ -1931,17 +1843,15 @@ sections:
`fmt` argument. The output is in the "broken down time"
representation consumed by `gmtime` and output by `mktime`.
The `strftime(fmt)` builtin formats a time (GMT) with the
given format. The `strflocaltime` does the same, but using
the local timezone setting.
The `strftime(fmt)` builtin formats a time with the given
format.
The format strings for `strptime` and `strftime` are described
in typical C library documentation. The format string for ISO
8601 datetime is `"%Y-%m-%dT%H:%M:%SZ"`.
jq may not support some or all of this date functionality on
some systems. In particular, the `%u` and `%j` specifiers for
`strptime(fmt)` are not supported on macOS.
some systems.
examples:
- program: 'fromdate'
@@ -1996,14 +1906,6 @@ sections:
This builtin outputs `true` if any value in the source stream
appears in the second stream, otherwise it outputs `false`.
- title: "`builtins`"
body: |
Returns a list of all builtin functions in the format `name/arity`.
Since functions with the same name but different arities are considered
separate functions, `all/0`, `all/1`, and `all/2` would all be present
in the list.
- title: Conditionals and Comparisons
entries:
- title: "`==`, `!=`"
@@ -2110,7 +2012,7 @@ sections:
input: 'null'
output: ['[false, true]']
- title: "Alternative operator: `//`"
- title: Alternative operator - `//`
body: |
A filter of the form `a // b` produces the same
@@ -2187,7 +2089,7 @@ sections:
because no label `$out` is visible.
- title: "Error Suppression / Optional Operator: `?`"
- title: "`?` operator"
body: |
The `?` operator, used as `EXP?`, is shorthand for `try EXP`.
@@ -2410,7 +2312,7 @@ sections:
Finally, there is a module/library system.
entries:
- title: "Variable / Symbolic Binding Operator: `... as $identifier | ...`"
- title: Variables
body: |
In jq, all filters have an input and an output, so manual
@@ -2603,20 +2505,18 @@ sections:
(2 as $item | . + $item) |
(1 as $item | . + $item)
If the reduction update expression outputs `empty` (that is,
no values), then the reduction state is left as-is. For
example, `reduce range(4) as $n ({}; if .==2 then empty else
.[$n|tostring] |= $n)` will produce `{"0":0,"1":1,"3":3}`.
examples:
- program: 'reduce .[] as $item (0; . + $item)'
input: '[10,2,5,3]'
output: ['20']
- title: "`isempty(exp)`"
body: |
Returns true if `exp` produces no outputs, false otherwise.
examples:
- program: 'isempty(empty)'
input: 'null'
output: ['true']
- program: 'reduce .[] as $n ([]; if $n%2==0 then empty else . + [$n] end)'
input: '[0,1,2,3,4,5]'
output: ['[1,3,5]']
- title: "`limit(n; exp)`"
body: |
@@ -2803,13 +2703,11 @@ sections:
jq itself. These two builtins, and jq's own reading actions, can
be interleaved with each other.
Two builtins provide minimal output capabilities, `debug`, and
`stderr`. (Recall that a jq program's output values are always
output as JSON texts on `stdout`.) The `debug` builtin can have
One builtin provides minimal output capabilities, `debug`.
(Recall that a jq program's output values are always output as
JSON texts on `stdout`.) The `debug` builtin can have
application-specific behavior, such as for executables that use
the libjq C API but aren't the jq executable itself. The `stderr`
builtin outputs its input in raw mode to stder with no additional
decoration, not even a newline.
the libjq C API but aren't the jq executable itself.
Most jq builtins are referentially transparent, and yield constant
and repeatable value streams when applied to constant inputs.
@@ -2837,12 +2735,6 @@ sections:
`["DEBUG:", <input-value>]` and prints that and a newline on
stderr, compactly. This may change in the future.
- title: "`stderr`"
body: |
Prints its input in raw and compact mode to stderr with no
additional decoration, not even a newline.
- title: "`input_filename`"
body: |
@@ -2914,6 +2806,7 @@ sections:
- title: Assignment
body: |
Assignment works a little differently in jq than in most
programming languages. jq doesn't distinguish between references
to and copies of something - two objects or arrays are either
@@ -2922,21 +2815,14 @@ sections:
If an object has two fields which are arrays, `.foo` and `.bar`,
and you append something to `.foo`, then `.bar` will not get
bigger, even if you've previously set `.bar = .foo`. If you're
used to programming in languages like Python, Java, Ruby,
Javascript, etc. then you can think of it as though jq does a full
deep copy of every object before it does the assignment (for
performance it doesn't actually do that, but that's the general
idea).
This means that it's impossible to build circular values in jq
(such as an array whose first element is itself). This is quite
intentional, and ensures that anything a jq program can produce
can be represented in JSON.
bigger. Even if you've just set `.bar = .foo`. If you're used to
programming in languages like Python, Java, Ruby, Javascript,
etc. then you can think of it as though jq does a full deep copy
of every object before it does the assignment (for performance,
it doesn't actually do that, but that's the general idea).
All the assignment operators in jq have path expressions on the
left-hand side (LHS). The right-hand side (RHS) provides values
to set to the paths named by the LHS path expressions.
left-hand side.
Values in jq are always immutable. Internally, assignment works
by using a reduction to compute new, replacement values for `.` that
@@ -2947,26 +2833,65 @@ sections:
sub-expression, `.`, sees the original value, not the modified
value.
Most users will want to use modification assignment operators,
such as `|=` or `+=`, rather than `=`.
Note that the LHS of assignment operators refers to a value in
`.`. Thus `$var.foo = 1` won't work as expected (`$var.foo` is
not a valid or useful path expression in `.`); use `$var | .foo =
1` instead.
Note too that `.a,.b=0` does not set `.a` and `.b`, but
`(.a,.b)=0` sets both.
entries:
- title: "Update-assignment: `|=`"
- title: "`=`"
body: |
This is the "update" operator '|='. It takes a filter on the
right-hand side and works out the new value for the property
of `.` being assigned to by running the old value through this
expression. For instance, (.foo, .bar) |= .+1 will build an
object with the "foo" field set to the input's "foo" plus 1,
and the "bar" field set to the input's "bar" plus 1.
The filter `.foo = 1` will take as input an object
and produce as output an object with the "foo" field set to
1. There is no notion of "modifying" or "changing" something
in jq - all jq values are immutable. For instance,
.foo = .bar | .foo.baz = 1
will not have the side-effect of setting .bar.baz to be set
to 1, as the similar-looking program in Javascript, Python,
Ruby or other languages would. Unlike these languages (but
like Haskell and some other functional languages), there is
no notion of two arrays or objects being "the same array" or
"the same object". They can be equal, or not equal, but if
we change one of them in no circumstances will the other
change behind our backs.
This means that it's impossible to build circular values in
jq (such as an array whose first element is itself). This is
quite intentional, and ensures that anything a jq program
can produce can be represented in JSON.
Note that the left-hand side of '=' refers to a value in `.`.
Thus `$var.foo = 1` won't work as expected (`$var.foo` is not
a valid or useful path expression in `.`); use `$var | .foo =
1` instead.
If the right-hand side of '=' produces multiple values, then
for each such value jq will set the paths on the left-hand
side to the value and then it will output the modified `.`.
For example, `(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then
`{"a":1,"b":1}`. The "update" assignment forms (see below) do
not do this.
Note too that `.a,.b=0` does not set `.a` and `.b`, but
`(.a,.b)=0` sets both.
- title: "`|=`"
body: |
As well as the assignment operator '=', jq provides the "update"
operator '|=', which takes a filter on the right-hand side and
works out the new value for the property of `.` being assigned
to by running the old value through this expression. For
instance, .foo |= .+1 will build an object with the "foo"
field set to the input's "foo" plus 1.
This example should show the difference between '=' and '|=':
Provide input '{"a": {"b": 10}, "b": 20}' to the programs:
.a = .b
.a |= .b
The former will set the "a" field of the input to the "b" field of the
input, and produce the output {"a": 20}. The latter will set the "a"
field of the input to the "a" field's "b" field, producing {"a": 10}.
The left-hand side can be any general path expression; see `path()`.
@@ -2979,66 +2904,26 @@ sections:
the left-hand side path will be deleted, as with `del(path)`.
If the right-hand side outputs multiple values, only the first
one will be used (COMPATIBILITY NOTE: in jq 1.5 and earlier
releases, it used to be that only the last one was used).
one will be used (NOTE: it used to be that only the last one was
used).
examples:
- program: '(..|select(type=="boolean")) |= if . then 1 else 0 end'
input: '[true,false,[5,true,[true,[false]],false]]'
output: ['[1,0,[5,1,[1,[0]],0]]']
- title: "Arithmetic update-assignment: `+=`, `-=`, `*=`, `/=`, `%=`, `//=`"
- title: "`+=`, `-=`, `*=`, `/=`, `%=`, `//=`"
body: |
jq has a few operators of the form `a op= b`, which are all
equivalent to `a |= . op b`. So, `+= 1` can be used to
increment values, being the same as `|= . + 1`.
equivalent to `a |= . op b`. So, `+= 1` can be used to increment values.
examples:
- program: .foo += 1
input: '{"foo": 42}'
output: ['{"foo": 43}']
- title: "Plain assignment: `=`"
body: |
This is the plain assignment operator. Unlike the others, the
input to the right-hand-side (RHS) is the same as the input to
the left-hand-side (LHS) rather than the value at the LHS
path, and all values output by the RHS will be used (as shown
below).
If the RHS of '=' produces multiple values, then for each such
value jq will set the paths on the left-hand side to the value
and then it will output the modified `.`. For example,
`(.a,.b)=range(2)` outputs `{"a":0,"b":0}`, then
`{"a":1,"b":1}`. The "update" assignment forms (see above) do
not do this.
This example should show the difference between '=' and '|=':
Provide input '{"a": {"b": 10}, "b": 20}' to the programs:
.a = .b
.a |= .b
The former will set the "a" field of the input to the "b"
field of the input, and produce the output {"a": 20, "b": 20}.
The latter will set the "a" field of the input to the "a"
field's "b" field, producing {"a": 10, "b": 20}.
Another example of the difference between '=' and '|=':
null|(.a,.b)=range(3)
outputs '{"a":0,"b":0}', '{"a":1,"b":1}', and '{"a":2,"b":2}',
while
null|(.a,.b)|=range(3)
outputs just '{"a":0,"b":0}'.
- title: Complex assignments
body: |
Lots more things are allowed on the left-hand side of a jq assignment
@@ -3200,42 +3085,3 @@ sections:
could then use to, for example, search for, download, and
install missing dependencies.
- title: Colors
body: |
To configure alternative colors just set the `JQ_COLORS`
environment variable to colon-delimited list of partial terminal
escape sequences like `"1;31"`, in this order:
- color for `null`
- color for `false`
- color for `true`
- color for numbers
- color for strings
- color for arrays
- color for objects
The default color scheme is the same as setting
`"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"`.
This is not a manual for VT100/ANSI escapes. However, each of
these color specifications should consist of two numbers separated
by a semi-colon, where the first number is one of these:
- 1 (bright)
- 2 (dim)
- 4 (underscore)
- 5 (blink)
- 7 (reverse)
- 8 (hidden)
and the second is one of these:
- 30 (black)
- 31 (red)
- 32 (green)
- 33 (yellow)
- 34 (blue)
- 35 (magenta)
- 36 (cyan)
- 37 (white)
+106 -289
View File
@@ -1,7 +1,7 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "JQ" "1" "December 2017" "" ""
.TH "JQ" "1" "February 2017" "" ""
.
.SH "NAME"
\fBjq\fR \- Command\-line JSON processor
@@ -105,9 +105,6 @@ Use the given number of spaces (no more than 8) for indentation\.
.IP
By default, jq outputs colored JSON if writing to a terminal\. You can force it to produce color even if writing to a pipe or a file using \fB\-C\fR, and disable color with \fB\-M\fR\.
.
.IP
Colors can be configured with the \fBJQ_COLORS\fR environment variable (see below)\.
.
.IP "\(bu" 4
\fB\-\-ascii\-output\fR / \fB\-a\fR:
.
@@ -156,18 +153,12 @@ Prepend \fBdirectory\fR to the search list for modules\. If this option is used
.IP
Sets the exit status of jq to 0 if the last output values was neither \fBfalse\fR nor \fBnull\fR, 1 if the last output value was either \fBfalse\fR or \fBnull\fR, or 4 if no valid result was ever produced\. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran\.
.
.IP
Another way to set the exit status is with the \fBhalt_error\fR builtin function\.
.
.IP "\(bu" 4
\fB\-\-arg name value\fR:
.
.IP
This option passes a value to the jq program as a predefined variable\. If you run jq with \fB\-\-arg foo bar\fR, then \fB$foo\fR is available in the program and has the value \fB"bar"\fR\. Note that \fBvalue\fR will be treated as a string, so \fB\-\-arg foo 123\fR will bind \fB$foo\fR to \fB"123"\fR\.
.
.IP
Named arguments are also available to the jq program as \fB$ARGS\.named\fR\.
.
.IP "\(bu" 4
\fB\-\-argjson name JSON\-text\fR:
.
@@ -190,18 +181,6 @@ Do not use\. Use \fB\-\-slurpfile\fR instead\.
(This option is like \fB\-\-slurpfile\fR, but when the file has just one text, then that is used, else an array of texts is used as in \fB\-\-slurpfile\fR\.)
.
.IP "\(bu" 4
\fB\-\-args\fR:
.
.IP
Remaining arguments are positional string arguments\. These are available to the jq program as \fB$ARGS\.positional[]\fR\.
.
.IP "\(bu" 4
\fB\-\-jsonargs\fR:
.
.IP
Remaining arguments are positional JSON text arguments\. These are available to the jq program as \fB$ARGS\.positional[]\fR\.
.
.IP "\(bu" 4
\fB\-\-run\-tests [filename]\fR:
.
.IP
@@ -214,8 +193,8 @@ Be warned that this option can change backwards\-incompatibly\.
.
.SH "BASIC FILTERS"
.
.SS "Identity: \."
The absolute simplest filter is \fB\.\fR \. This is a filter that takes its input and produces it unchanged as output\. That is, this is the identity operator\.
.SS "\."
The absolute simplest (and least interesting) filter is \fB\.\fR\. This is a filter that takes its input and produces it unchanged as output\.
.
.P
Since jq by default pretty\-prints all output, this trivial program can be a useful way of formatting JSON output from, say, \fBcurl\fR\.
@@ -232,21 +211,15 @@ jq \'\.\'
.
.IP "" 0
.
.SS "Object Identifier\-Index: \.foo, \.foo\.bar"
.SS "\.foo, \.foo\.bar"
The simplest \fIuseful\fR filter is \fB\.foo\fR\. When given a JSON object (aka dictionary or hash) as input, it produces the value at the key "foo", or null if there\'s none present\.
.
.P
If the key contains special characters, you need to surround it with double quotes like this: \fB\."foo$"\fR\.
.
.P
A filter of the form \fB\.foo\.bar\fR is equivalent to \fB\.foo|\.bar\fR\.
.
.P
This syntax only works for simple, identifier\-like keys, that is, keys that are all made of alphanumeric characters and underscore, and which do not start with a digit\.
.
.P
If the key contains special characters, you need to surround it with double quotes like this: \fB\."foo$"\fR, or else \fB\.["foo$"]\fR\.
.
.P
For example \fB\.["foo::bar"]\fR and \fB\.["foo\.bar"]\fR work while \fB\.foo::bar\fR does not, and \fB\.foo\.bar\fR means \fB\.["foo"]\.["bar"]\fR\.
.
.IP "" 4
.
.nf
@@ -267,7 +240,7 @@ jq \'\.["foo"]\'
.
.IP "" 0
.
.SS "Optional Object Identifier\-Index: \.foo?"
.SS "\.foo?"
Just like \fB\.foo\fR, but does not output even an error when \fB\.\fR is not an array or an object\.
.
.IP "" 4
@@ -294,14 +267,20 @@ jq \'[\.foo?]\'
.
.IP "" 0
.
.SS "Generic Object Index: \.[<string>]"
You can also look up fields of an object using syntax like \fB\.["foo"]\fR (\.foo above is a shorthand version of this, but only for identifier\-like strings)\.
.
.SS "Array Index: \.[2]"
When the index value is an integer, \fB\.[<value>]\fR can index arrays\. Arrays are zero\-based, so \fB\.[2]\fR returns the third element\.
.SS "\.[<string>], \.[2], \.[10:15]"
You can also look up fields of an object using syntax like \fB\.["foo"]\fR (\.foo above is a shorthand version of this)\. This one works for arrays as well, if the key is an integer\. Arrays are zero\-based (like javascript), so \fB\.[2]\fR returns the third element of the array\.
.
.P
Negative indices are allowed, with \-1 referring to the last element, \-2 referring to the next to last element, and so on\.
The \fB\.[10:15]\fR syntax can be used to return a subarray of an array or substring of a string\. The array returned by \fB\.[10:15]\fR will be of length 5, containing the elements from index 10 (inclusive) to index 15 (exclusive)\. Either index may be negative (in which case it counts backwards from the end of the array), or omitted (in which case it refers to the start or end of the array)\.
.
.P
The \fB\.[2]\fR syntax can be used to return the element at the given index\. Negative indices are allowed, with \-1 referring to the last element, \-2 referring to the next to last element, and so on\.
.
.P
The \fB\.foo\fR syntax only works for simply keys i\.e\. keys that are all alphanumeric characters\. \fB\.[<string>]\fR works with keys that contain special characters such as colons and dots\. For example \fB\.["foo::bar"]\fR and \fB\.["foo\.bar"]\fR work while \fB\.foo::bar\fR and \fB\.foo\.bar\fR would not\.
.
.P
The \fB?\fR "operator" can also be used with the slice operator, as in \fB\.[10:15]?\fR, which outputs values where the inputs are slice\-able\.
.
.IP "" 4
.
@@ -315,21 +294,6 @@ jq \'\.[2]\'
[{"name":"JSON", "good":true}, {"name":"XML", "good":false}]
=> null
jq \'\.[\-2]\'
[1,2,3]
=> 2
.
.fi
.
.IP "" 0
.
.SS "Array/String Slice: \.[10:15]"
The \fB\.[10:15]\fR syntax can be used to return a subarray of an array or substring of a string\. The array returned by \fB\.[10:15]\fR will be of length 5, containing the elements from index 10 (inclusive) to index 15 (exclusive)\. Either index may be negative (in which case it counts backwards from the end of the array), or omitted (in which case it refers to the start or end of the array)\.
.
.IP "" 4
.
.nf
jq \'\.[2:4]\'
["a","b","c","d","e"]
=> ["c", "d"]
@@ -345,12 +309,16 @@ jq \'\.[:3]\'
jq \'\.[\-2:]\'
["a","b","c","d","e"]
=> ["d", "e"]
jq \'\.[\-2]\'
[1,2,3]
=> 2
.
.fi
.
.IP "" 0
.
.SS "Array/Object Value Iterator: \.[]"
.SS "\.[]"
If you use the \fB\.[index]\fR syntax, but omit the index entirely, it will return \fIall\fR of the elements of an array\. Running \fB\.[]\fR with the input \fB[1,2,3]\fR will produce the numbers as three separate results, rather than as a single array\.
.
.P
@@ -379,8 +347,8 @@ jq \'\.[]\'
.SS "\.[]?"
Like \fB\.[]\fR, but no errors will be output if \. is not an array or object\.
.
.SS "Comma: ,"
If two filters are separated by a comma, then the same input will be fed into both and the two filters\' output value streams will be concatenated in order: first, all of the outputs produced by the left expression, and then all of the outputs produced by the right\. For instance, filter \fB\.foo, \.bar\fR, produces both the "foo" fields and "bar" fields as separate outputs\.
.SS ","
If two filters are separated by a comma, then the input will be fed into both and there will be multiple outputs: first, all of the outputs produced by the left expression, and then all of the outputs produced by the right\. For instance, filter \fB\.foo, \.bar\fR, produces both the "foo" fields and "bar" fields as separate outputs\.
.
.IP "" 4
.
@@ -402,7 +370,7 @@ jq \'\.[4,2]\'
.
.IP "" 0
.
.SS "Pipe: |"
.SS "|"
The | operator combines two filters by feeding the output(s) of the one on the left into the input of the one on the right\. It\'s pretty much the same as the Unix shell\'s pipe, if you\'re used to that\.
.
.P
@@ -447,8 +415,8 @@ jq supports the same set of datatypes as JSON \- numbers, strings, booleans, arr
.P
Booleans, null, strings and numbers are written the same way as in javascript\. Just like everything else in jq, these simple values take an input and produce an output \- \fB42\fR is a valid jq expression that takes an input, ignores it, and returns 42 instead\.
.
.SS "Array construction: []"
As in JSON, \fB[]\fR is used to construct arrays, as in \fB[1,2,3]\fR\. The elements of the arrays can be any jq expression, including a pipeline\. All of the results produced by all of the expressions are collected into one big array\. You can use it to construct an array out of a known quantity of values (as in \fB[\.foo, \.bar, \.baz]\fR) or to "collect" all the results of a filter into an array (as in \fB[\.items[]\.name]\fR)
.SS "Array construction \- []"
As in JSON, \fB[]\fR is used to construct arrays, as in \fB[1,2,3]\fR\. The elements of the arrays can be any jq expression\. All of the results produced by all of the expressions are collected into one big array\. You can use it to construct an array out of a known quantity of values (as in \fB[\.foo, \.bar, \.baz]\fR) or to "collect" all the results of a filter into an array (as in \fB[\.items[]\.name]\fR)
.
.P
Once you understand the "," operator, you can look at jq\'s array syntax in a different light: the expression \fB[1,2,3]\fR is not using a built\-in syntax for comma\-separated arrays, but is instead applying the \fB[]\fR operator (collect results) to the expression 1,2,3 (which produces three different results)\.
@@ -463,23 +431,16 @@ If you have a filter \fBX\fR that produces four results, then the expression \fB
jq \'[\.user, \.projects[]]\'
{"user":"stedolan", "projects": ["jq", "wikiflow"]}
=> ["stedolan", "jq", "wikiflow"]
jq \'[ \.[] | \. * 2]\'
[1, 2, 3]
=> [2, 4, 6]
.
.fi
.
.IP "" 0
.
.SS "Object Construction: {}"
.SS "Objects \- {}"
Like JSON, \fB{}\fR is for constructing objects (aka dictionaries or hashes), as in: \fB{"a": 42, "b": 17}\fR\.
.
.P
If the keys are "identifier\-like", then the quotes can be left off, as in \fB{a:42, b:17}\fR\. Keys generated by expressions need to be parenthesized, e\.g\., \fB{("a"+"b"):59}\fR\.
.
.P
The value can be any expression (although you may need to wrap it in parentheses if it\'s a complicated one), which gets applied to the {} expression\'s input (remember, all filters have an input and an output)\.
If the keys are "sensible" (all alphabetic characters), then the quotes can be left off\. The value can be any expression (although you may need to wrap it in parentheses if it\'s a complicated one), which gets applied to the {} expression\'s input (remember, all filters have an input and an output)\.
.
.IP "" 4
.
@@ -492,7 +453,7 @@ The value can be any expression (although you may need to wrap it in parentheses
.IP "" 0
.
.P
will produce the JSON object \fB{"foo": 42}\fR if given the JSON object \fB{"bar":42, "baz":43}\fR as its input\. You can use this to select particular fields of an object: if the input is an object with "user", "title", "id", and "content" fields and you just want "user" and "title", you can write
will produce the JSON object \fB{"foo": 42}\fR if given the JSON object \fB{"bar":42, "baz":43}\fR\. You can use this to select particular fields of an object: if the input is an object with "user", "title", "id", and "content" fields and you just want "user" and "title", you can write
.
.IP "" 4
.
@@ -505,7 +466,7 @@ will produce the JSON object \fB{"foo": 42}\fR if given the JSON object \fB{"bar
.IP "" 0
.
.P
Because that is so common, there\'s a shortcut syntax for it: \fB{user, title}\fR\.
Because that\'s so common, there\'s a shortcut syntax: \fB{user, title}\fR\.
.
.P
If one of the expressions produces multiple results, multiple dictionaries will be produced\. If the input\'s
@@ -581,28 +542,10 @@ jq \'{(\.user): \.titles}\'
.
.IP "" 0
.
.SS "Recursive Descent: \.\."
Recursively descends \fB\.\fR, producing every value\. This is the same as the zero\-argument \fBrecurse\fR builtin (see below)\. This is intended to resemble the XPath \fB//\fR operator\. Note that \fB\.\.a\fR does not work; use \fB\.\.|\.a\fR instead\. In the example below we use \fB\.\.|\.a?\fR to find all the values of object keys "a" in any object found "below" \fB\.\fR\.
.
.P
This is particularly useful in conjunction with \fBpath(EXP)\fR (also see below) and the \fB?\fR operator\.
.
.IP "" 4
.
.nf
jq \'\.\.|\.a?\'
[[{"a":1}]]
=> 1
.
.fi
.
.IP "" 0
.
.SH "BUILTIN OPERATORS AND FUNCTIONS"
Some jq operator (for instance, \fB+\fR) do different things depending on the type of their arguments (arrays, numbers, etc\.)\. However, jq never does implicit type conversions\. If you try to add a string to an object you\'ll get an error message and no result\.
.
.SS "Addition: +"
.SS "Addition \- +"
The operator \fB+\fR takes two filters, applies them both to the same input, and adds the results together\. What "adding" means depends on the types involved:
.
.IP "\(bu" 4
@@ -650,7 +593,7 @@ jq \'{a: 1} + {b: 2} + {c: 3} + {a: 42}\'
.
.IP "" 0
.
.SS "Subtraction: \-"
.SS "Subtraction \- \-"
As well as normal arithmetic subtraction on numbers, the \fB\-\fR operator can be used on arrays to remove all occurrences of the second array\'s elements from the first array\.
.
.IP "" 4
@@ -669,7 +612,7 @@ jq \'\. \- ["xml", "yaml"]\'
.
.IP "" 0
.
.SS "Multiplication, division, modulo: *, /, and %"
.SS "Multiplication, division, modulo \- *, /, and %"
These infix operators behave as expected when given two numbers\. Division by zero raises an error\. \fBx % y\fR computes x modulo y\.
.
.P
@@ -1027,19 +970,7 @@ jq \'[1,2,empty,3]\'
.IP "" 0
.
.SS "error(message)"
Produces an error, just like \fB\.a\fR applied to values other than null and objects would, but with the given message as the error\'s value\. Errors can be caught with try/catch; see below\.
.
.SS "halt"
Stops the jq program with no further outputs\. jq will exit with exit status \fB0\fR\.
.
.SS "halt_error, halt_error(exit_code)"
Stops the jq program with no further outputs\. The input will be printed on \fBstderr\fR as raw output (i\.e\., strings will not have double quotes) with no decoration, not even a newline\.
.
.P
The given \fBexit_code\fR (defaulting to \fB5\fR) will be jq\'s exit status\.
.
.P
For example, \fB"Error: somthing went wrong\en"|halt_error(1)\fR\.
Produces an error, just like \fB\.a\fR applied to values other than null and objects would, but with the given message as the error\'s value\.
.
.SS "$__loc__"
Produces an object with a "file" key and a "line" key, with the filename and line number where \fB$__loc__\fR occurs, as values\.
@@ -1852,22 +1783,27 @@ jq \'walk( if type == "object" then with_entries( \.key |= sub( "^_+"; "") ) els
.
.IP "" 0
.
.SS "$ENV, env"
\fB$ENV\fR is an object representing the environment variables as set when the jq program started\.
.
.P
\fBenv\fR outputs an object representing jq\'s current environment\.
.
.P
At the moment there is no builtin for setting environment variables\.
.SS "\.\."
Short\-hand for \fBrecurse\fR without arguments\. This is intended to resemble the XPath \fB//\fR operator\. Note that \fB\.\.a\fR does not work; use \fB\.\.|a\fR instead\. In the example below we use \fB\.\.|\.a?\fR to find all the values of object keys "a" in any object found "below" \fB\.\fR\.
.
.IP "" 4
.
.nf
jq \'$ENV\.PAGER\'
null
=> "less"
jq \'\.\.|\.a?\'
[[{"a":1}]]
=> 1
.
.fi
.
.IP "" 0
.
.SS "env"
Outputs an object representing jq\'s environment\.
.
.IP "" 4
.
.nf
jq \'env\.PAGER\'
null
@@ -2004,12 +1940,6 @@ The input is escaped suitable for use in a command\-line for a POSIX shell\. If
.IP
The input is converted to base64 as specified by RFC 4648\.
.
.TP
\fB@base64d\fR:
.
.IP
The inverse of \fB@base64\fR, input is decoded as specified by RFC 4648\. Note: If the decoded string is not UTF\-8, the results are undefined\.
.
.P
This syntax can be combined with string interpolation in a useful way\. You can follow a \fB@foo\fR token with a string literal\. The contents of the string literal will \fInot\fR be escaped\. However, all interpolations made inside that string literal will be escaped\. For instance,
.
@@ -2050,14 +1980,6 @@ jq \'@html\'
jq \'@sh "echo \e(\.)"\'
"O\'Hara\'s Ale"
=> "echo \'O\'\e\e\'\'Hara\'\e\e\'\'s Ale\'"
jq \'@base64\'
"This is a message"
=> "VGhpcyBpcyBhIG1lc3NhZ2U="
jq \'@base64d\'
"VGhpcyBpcyBhIG1lc3NhZ2U="
=> "This is a message"
.
.fi
.
@@ -2079,13 +2001,10 @@ The \fBtodate\fR builtin is an alias for \fBtodateiso8601\fR\.
The \fBnow\fR builtin outputs the current time, in seconds since the Unix epoch\.
.
.P
Low\-level jq interfaces to the C\-library time functions are also provided: \fBstrptime\fR, \fBstrftime\fR, \fBstrflocaltime\fR, \fBmktime\fR, \fBgmtime\fR, and \fBlocaltime\fR\. Refer to your host operating system\'s documentation for the format strings used by \fBstrptime\fR and \fBstrftime\fR\. Note: these are not necessarily stable interfaces in jq, particularly as to their localization functionality\.
Low\-level jq interfaces to the C\-library time functions are also provided: \fBstrptime\fR, \fBstrftime\fR, \fBmktime\fR, and \fBgmtime\fR\. Refer to your host operating system\'s documentation for the format strings used by \fBstrptime\fR and \fBstrftime\fR\. Note: these are not necessarily stable interfaces in jq, particularly as to their localization functionality\.
.
.P
The \fBgmtime\fR builtin consumes a number of seconds since the Unix epoch and outputs a "broken down time" representation of Greenwhich Meridian time as an array of numbers representing (in this order): the year, the month (zero\-based), the day of the month (one\-based), the hour of the day, the minute of the hour, the second of the minute, the day of the week, and the day of the year \-\- all one\-based unless otherwise stated\. The day of the week number may be wrong on some systems for dates before March 1st 1900, or after December 31 2099\.
.
.P
The \fBlocaltime\fR builtin works like the \fBgmtime\fR builtin, but using the local timezone setting\.
The \fBgmtime\fR builtin consumes a number of seconds since the Unix epoch and outputs a "broken down time" representation of time as an array of numbers representing (in this order): the year, the month (zero\-based), the day of the month, the hour of the day, the minute of the hour, the second of the minute, the day of the week, and the day of the year \-\- all one\-based unless otherwise stated\.
.
.P
The \fBmktime\fR builtin consumes "broken down time" representations of time output by \fBgmtime\fR and \fBstrptime\fR\.
@@ -2094,13 +2013,13 @@ The \fBmktime\fR builtin consumes "broken down time" representations of time out
The \fBstrptime(fmt)\fR builtin parses input strings matching the \fBfmt\fR argument\. The output is in the "broken down time" representation consumed by \fBgmtime\fR and output by \fBmktime\fR\.
.
.P
The \fBstrftime(fmt)\fR builtin formats a time (GMT) with the given format\. The \fBstrflocaltime\fR does the same, but using the local timezone setting\.
The \fBstrftime(fmt)\fR builtin formats a time with the given format\.
.
.P
The format strings for \fBstrptime\fR and \fBstrftime\fR are described in typical C library documentation\. The format string for ISO 8601 datetime is \fB"%Y\-%m\-%dT%H:%M:%SZ"\fR\.
.
.P
jq may not support some or all of this date functionality on some systems\. In particular, the \fB%u\fR and \fB%j\fR specifiers for \fBstrptime(fmt)\fR are not supported on macOS\.
jq may not support some or all of this date functionality on some systems\.
.
.IP "" 4
.
@@ -2161,9 +2080,6 @@ IN(source; s):
.IP
This builtin outputs \fBtrue\fR if any value in the source stream appears in the second stream, otherwise it outputs \fBfalse\fR\.
.
.SS "builtins"
Returns a list of all builtin functions in the format \fBname/arity\fR\. Since functions with the same name but different arities are considered separate functions, \fBall/0\fR, \fBall/1\fR, and \fBall/2\fR would all be present in the list\.
.
.SH "CONDITIONALS AND COMPARISONS"
.
.SS "==, !="
@@ -2263,7 +2179,7 @@ jq \'[true, false | not]\'
.
.IP "" 0
.
.SS "Alternative operator: //"
.SS "Alternative operator \- //"
A filter of the form \fBa // b\fR produces the same results as \fBa\fR, if \fBa\fR produces results other than \fBfalse\fR and \fBnull\fR\. Otherwise, \fBa // b\fR produces the same results as \fBb\fR\.
.
.P
@@ -2378,7 +2294,7 @@ break $out
.P
because no label \fB$out\fR is visible\.
.
.SS "Error Suppression / Optional Operator: ?"
.SS "? operator"
The \fB?\fR operator, used as \fBEXP?\fR, is shorthand for \fBtry EXP\fR\.
.
.IP "" 4
@@ -2598,7 +2514,7 @@ Some minimal I/O support (besides reading JSON from standard input, and writing
.P
Finally, there is a module/library system\.
.
.SS "Variable / Symbolic Binding Operator: \.\.\. as $identifier | \.\.\."
.SS "Variables"
In jq, all filters have an input and an output, so manual plumbing is not necessary to pass a value from one part of a program to the next\. Many expressions, for instance \fBa + b\fR, pass their input to two distinct subexpressions (here \fBa\fR and \fBb\fR are both passed the same input), so variables aren\'t usually necessary in order to use a value twice\.
.
.P
@@ -2861,25 +2777,25 @@ For each result that \fB\.[]\fR produces, \fB\. + $item\fR is run to accumulate
0 | (3 as $item | \. + $item) |
(2 as $item | \. + $item) |
(1 as $item | \. + $item)
jq \'reduce \.[] as $item (0; \. + $item)\'
[10,2,5,3]
=> 20
.
.fi
.
.IP "" 0
.
.SS "isempty(exp)"
Returns true if \fBexp\fR produces no outputs, false otherwise\.
.P
If the reduction update expression outputs \fBempty\fR (that is, no values), then the reduction state is left as\-is\. For example, \fBreduce range(4) as $n ({}; if \.==2 then empty else \.[$n|tostring] |= $n)\fR will produce \fB{"0":0,"1":1,"3":3}\fR\.
.
.IP "" 4
.
.nf
jq \'isempty(empty)\'
null
=> true
jq \'reduce \.[] as $item (0; \. + $item)\'
[10,2,5,3]
=> 20
jq \'reduce \.[] as $n ([]; if $n%2==0 then empty else \. + [$n] end)\'
[0,1,2,3,4,5]
=> [1,3,5]
.
.fi
.
@@ -3039,7 +2955,7 @@ See your system\'s manual for more information on each of these\.
At this time jq has minimal support for I/O, mostly in the form of control over when inputs are read\. Two builtins functions are provided for this, \fBinput\fR and \fBinputs\fR, that read from the same sources (e\.g\., \fBstdin\fR, files named on the command\-line) as jq itself\. These two builtins, and jq\'s own reading actions, can be interleaved with each other\.
.
.P
Two builtins provide minimal output capabilities, \fBdebug\fR, and \fBstderr\fR\. (Recall that a jq program\'s output values are always output as JSON texts on \fBstdout\fR\.) The \fBdebug\fR builtin can have application\-specific behavior, such as for executables that use the libjq C API but aren\'t the jq executable itself\. The \fBstderr\fR builtin outputs its input in raw mode to stder with no additional decoration, not even a newline\.
One builtin provides minimal output capabilities, \fBdebug\fR\. (Recall that a jq program\'s output values are always output as JSON texts on \fBstdout\fR\.) The \fBdebug\fR builtin can have application\-specific behavior, such as for executables that use the libjq C API but aren\'t the jq executable itself\.
.
.P
Most jq builtins are referentially transparent, and yield constant and repeatable value streams when applied to constant inputs\. This is not true of I/O builtins\.
@@ -3056,9 +2972,6 @@ This is primarily useful for reductions over a program\'s inputs\.
.SS "debug"
Causes a debug message based on the input value to be produced\. The jq executable wraps the input value with \fB["DEBUG:", <input\-value>]\fR and prints that and a newline on stderr, compactly\. This may change in the future\.
.
.SS "stderr"
Prints its input in raw and compact mode to stderr with no additional decoration, not even a newline\.
.
.SS "input_filename"
Returns the name of the file whose input is currently being filtered\. Note that this will not work well unless jq is running in a UTF\-8 locale\.
.
@@ -3129,28 +3042,49 @@ jq \'\. as $dot|fromstream($dot|tostream)|\.==$dot\'
Assignment works a little differently in jq than in most programming languages\. jq doesn\'t distinguish between references to and copies of something \- two objects or arrays are either equal or not equal, without any further notion of being "the same object" or "not the same object"\.
.
.P
If an object has two fields which are arrays, \fB\.foo\fR and \fB\.bar\fR, and you append something to \fB\.foo\fR, then \fB\.bar\fR will not get bigger, even if you\'ve previously set \fB\.bar = \.foo\fR\. If you\'re used to programming in languages like Python, Java, Ruby, Javascript, etc\. then you can think of it as though jq does a full deep copy of every object before it does the assignment (for performance it doesn\'t actually do that, but that\'s the general idea)\.
If an object has two fields which are arrays, \fB\.foo\fR and \fB\.bar\fR, and you append something to \fB\.foo\fR, then \fB\.bar\fR will not get bigger\. Even if you\'ve just set \fB\.bar = \.foo\fR\. If you\'re used to programming in languages like Python, Java, Ruby, Javascript, etc\. then you can think of it as though jq does a full deep copy of every object before it does the assignment (for performance, it doesn\'t actually do that, but that\'s the general idea)\.
.
.P
All the assignment operators in jq have path expressions on the left\-hand side\.
.
.P
Values in jq are always immutable\. Internally, assignment works by using a reduction to compute new, replacement values for \fB\.\fR that have had all the desired assignments applied to \fB\.\fR, then outputting the modified value\. This might be made clear by this example: \fB{a:{b:{c:1}}} | (\.a\.b|=3), \.\fR\. This will output \fB{"a":{"b":3}}\fR and \fB{"a":{"b":{"c":1}}}\fR because the last sub\-expression, \fB\.\fR, sees the original value, not the modified value\.
.
.SS "="
The filter \fB\.foo = 1\fR will take as input an object and produce as output an object with the "foo" field set to 1\. There is no notion of "modifying" or "changing" something in jq \- all jq values are immutable\. For instance,
.
.P
\&\.foo = \.bar | \.foo\.baz = 1
.
.P
will not have the side\-effect of setting \.bar\.baz to be set to 1, as the similar\-looking program in Javascript, Python, Ruby or other languages would\. Unlike these languages (but like Haskell and some other functional languages), there is no notion of two arrays or objects being "the same array" or "the same object"\. They can be equal, or not equal, but if we change one of them in no circumstances will the other change behind our backs\.
.
.P
This means that it\'s impossible to build circular values in jq (such as an array whose first element is itself)\. This is quite intentional, and ensures that anything a jq program can produce can be represented in JSON\.
.
.P
All the assignment operators in jq have path expressions on the left\-hand side (LHS)\. The right\-hand side (RHS) procides values to set to the paths named by the LHS path expressions\.
Note that the left\-hand side of \'=\' refers to a value in \fB\.\fR\. Thus \fB$var\.foo = 1\fR won\'t work as expected (\fB$var\.foo\fR is not a valid or useful path expression in \fB\.\fR); use \fB$var | \.foo = 1\fR instead\.
.
.P
Values in jq are always immutable\. Internally, assignment works by using a reduction to compute new, replacement values for \fB\.\fR that have had all the desired assignments applied to \fB\.\fR, then outputting the modified value\. This might be made clear by this example: \fB{a:{b:{c:1}}} | (\.a\.b|=3), \.\fR\. This will output \fB{"a":{"b":3}}\fR and \fB{"a":{"b":{"c":1}}}\fR because the last sub\-expression, \fB\.\fR, sees the original value, not the modified value\.
.
.P
Most users will want to use modification assignment operators, such as \fB|=\fR or \fB+=\fR, rather than \fB=\fR\.
.
.P
Note that the LHS of assignment operators refers to a value in \fB\.\fR\. Thus \fB$var\.foo = 1\fR won\'t work as expected (\fB$var\.foo\fR is not a valid or useful path expression in \fB\.\fR); use \fB$var | \.foo = 1\fR instead\.
If the right\-hand side of \'=\' produces multiple values, then for each such value jq will set the paths on the left\-hand side to the value and then it will output the modified \fB\.\fR\. For example, \fB(\.a,\.b)=range(2)\fR outputs \fB{"a":0,"b":0}\fR, then \fB{"a":1,"b":1}\fR\. The "update" assignment forms (see below) do not do this\.
.
.P
Note too that \fB\.a,\.b=0\fR does not set \fB\.a\fR and \fB\.b\fR, but \fB(\.a,\.b)=0\fR sets both\.
.
.SS "Update\-assignment: |="
This is the "update" operator \'|=\'\. It takes a filter on the right\-hand side and works out the new value for the property of \fB\.\fR being assigned to by running the old value through this expression\. For instance, (\.foo, \.bar) |= \.+1 will build an object with the "foo" field set to the input\'s "foo" plus 1, and the "bar" field set to the input\'s "bar" plus 1\.
.SS "|="
As well as the assignment operator \'=\', jq provides the "update" operator \'|=\', which takes a filter on the right\-hand side and works out the new value for the property of \fB\.\fR being assigned to by running the old value through this expression\. For instance, \.foo |= \.+1 will build an object with the "foo" field set to the input\'s "foo" plus 1\.
.
.P
This example should show the difference between \'=\' and \'|=\':
.
.P
Provide input \'{"a": {"b": 10}, "b": 20}\' to the programs:
.
.P
\&\.a = \.b \.a |= \.b
.
.P
The former will set the "a" field of the input to the "b" field of the input, and produce the output {"a": 20}\. The latter will set the "a" field of the input to the "a" field\'s "b" field, producing {"a": 10}\.
.
.P
The left\-hand side can be any general path expression; see \fBpath()\fR\.
@@ -3162,7 +3096,7 @@ Note that the left\-hand side of \'|=\' refers to a value in \fB\.\fR\. Thus \fB
If the right\-hand side outputs no values (i\.e\., \fBempty\fR), then the left\-hand side path will be deleted, as with \fBdel(path)\fR\.
.
.P
If the right\-hand side outputs multiple values, only the first one will be used (COMPATIBILITY NOTE: in jq 1\.5 and earlier releases, it used to be that only the last one was used)\.
If the right\-hand side outputs multiple values, only the first one will be used (NOTE: it used to be that only the last one was used)\.
.
.IP "" 4
.
@@ -3176,8 +3110,8 @@ jq \'(\.\.|select(type=="boolean")) |= if \. then 1 else 0 end\'
.
.IP "" 0
.
.SS "Arithmetic update\-assignment: +=, \-=, *=, /=, %=, //="
jq has a few operators of the form \fBa op= b\fR, which are all equivalent to \fBa |= \. op b\fR\. So, \fB+= 1\fR can be used to increment values, being the same as \fB|= \. + 1\fR\.
.SS "+=, \-=, *=, /=, %=, //="
jq has a few operators of the form \fBa op= b\fR, which are all equivalent to \fBa |= \. op b\fR\. So, \fB+= 1\fR can be used to increment values\.
.
.IP "" 4
.
@@ -3191,42 +3125,6 @@ jq \'\.foo += 1\'
.
.IP "" 0
.
.SS "Plain assignment: ="
This is the plain assignment operator\. Unlike the others, the input to the right\-hand\-side (RHS) is the same as the input to the left\-hand\-side (LHS) rather than the value at the LHS path, and all values output by the RHS will be used (as shown below)\.
.
.P
If the RHS of \'=\' produces multiple values, then for each such value jq will set the paths on the left\-hand side to the value and then it will output the modified \fB\.\fR\. For example, \fB(\.a,\.b)=range(2)\fR outputs \fB{"a":0,"b":0}\fR, then \fB{"a":1,"b":1}\fR\. The "update" assignment forms (see above) do not do this\.
.
.P
This example should show the difference between \'=\' and \'|=\':
.
.P
Provide input \'{"a": {"b": 10}, "b": 20}\' to the programs:
.
.P
\&\.a = \.b
.
.P
\&\.a |= \.b
.
.P
The former will set the "a" field of the input to the "b" field of the input, and produce the output {"a": 20, "b": 20}\. The latter will set the "a" field of the input to the "a" field\'s "b" field, producing {"a": 10, "b": 20}\.
.
.P
Another example of the difference between \'=\' and \'|=\':
.
.P
null|(\.a,\.b)=range(3)
.
.P
outputs \'{"a":0,"b":0}\', \'{"a":1,"b":1}\', and \'{"a":2,"b":2}\', while
.
.P
null|(\.a,\.b)|=range(3)
.
.P
outputs just \'{"a":0,"b":0}\'\.
.
.SS "Complex assignments"
Lots more things are allowed on the left\-hand side of a jq assignment than in most languages\. We\'ve already seen simple field accesses on the left hand side, and it\'s no surprise that array accesses work just as well:
.
@@ -3361,87 +3259,6 @@ Takes a module name as input and outputs the module\'s metadata as an object, wi
.P
Programs can use this to query a module\'s metadata, which they could then use to, for example, search for, download, and install missing dependencies\.
.
.SH "COLORS"
To configure alternative colors just set the \fBJQ_COLORS\fR environment variable to colon\-delimited list of partial terminal escape sequences like \fB"1;31"\fR, in this order:
.
.IP "\(bu" 4
color for \fBnull\fR
.
.IP "\(bu" 4
color for \fBfalse\fR
.
.IP "\(bu" 4
color for \fBtrue\fR
.
.IP "\(bu" 4
color for numbers
.
.IP "\(bu" 4
color for strings
.
.IP "\(bu" 4
color for arrays
.
.IP "\(bu" 4
color for objects
.
.IP "" 0
.
.P
The default color scheme is the same as setting \fB"JQ_COLORS=1;30:0;39:0;39:0;39:0;32:1;39:1;39"\fR\.
.
.P
This is not a manual for VT100/ANSI escapes\. However, each of these color specifications should consist of two numbers separated by a semi\-colon, where the first number is one of these:
.
.IP "\(bu" 4
1 (bright)
.
.IP "\(bu" 4
2 (dim)
.
.IP "\(bu" 4
4 (underscore)
.
.IP "\(bu" 4
5 (blink)
.
.IP "\(bu" 4
7 (reverse)
.
.IP "\(bu" 4
8 (hidden)
.
.IP "" 0
.
.P
and the second is one of these:
.
.IP "\(bu" 4
30 (black)
.
.IP "\(bu" 4
31 (red)
.
.IP "\(bu" 4
32 (green)
.
.IP "\(bu" 4
33 (yellow)
.
.IP "\(bu" 4
34 (blue)
.
.IP "\(bu" 4
35 (magenta)
.
.IP "\(bu" 4
36 (cyan)
.
.IP "\(bu" 4
37 (white)
.
.IP "" 0
.
.SH "BUGS"
Presumably\. Report them or discuss them at:
.
+2 -7
View File
@@ -1,10 +1,5 @@
#!/bin/sh
set -e
cd `dirname "$0"`
if git rev-parse --verify -q jq-1.0 > /dev/null 2>&1; then
git describe --tags --match 'jq-*' --dirty | sed 's/^jq-//'
else
b=`git rev-parse --abbrev-ref HEAD`
c=`git describe --always --dirty`
echo "${b}-${c}"
fi
git rev-parse --verify -q jq-1.0 > /dev/null 2>&1
git describe --tags --match 'jq-*' --dirty | sed 's/^jq-//'
+75 -392
View File
@@ -29,7 +29,7 @@ void *alloca (size_t);
#include <ctype.h>
#include <limits.h>
#include <math.h>
#ifdef HAVE_LIBONIG
#ifdef HAVE_ONIGURUMA
#include <oniguruma.h>
#endif
#include <string.h>
@@ -41,7 +41,6 @@ void *alloca (size_t);
#include "linker.h"
#include "locfile.h"
#include "jv_unicode.h"
#include "jv_alloc.h"
static jv type_error(jv bad, const char* msg) {
@@ -67,17 +66,6 @@ static jv type_error2(jv bad1, jv bad2, const char* msg) {
return err;
}
static inline jv ret_error(jv bad, jv msg) {
jv_free(bad);
return jv_invalid_with_msg(msg);
}
static inline jv ret_error2(jv bad1, jv bad2, jv msg) {
jv_free(bad1);
jv_free(bad2);
return jv_invalid_with_msg(msg);
}
static jv f_plus(jq_state *jq, jv input, jv a, jv b) {
jv_free(input);
if (jv_get_kind(a) == JV_KIND_NULL) {
@@ -113,15 +101,9 @@ static jv f_ ## name(jq_state *jq, jv input) { \
#define LIBM_DDD(name) \
static jv f_ ## name(jq_state *jq, jv input, jv a, jv b) { \
if (jv_get_kind(a) != JV_KIND_NUMBER || jv_get_kind(b) != JV_KIND_NUMBER) \
return type_error(input, "number required"); \
jv_free(input); \
if (jv_get_kind(a) != JV_KIND_NUMBER) { \
jv_free(b); \
return type_error(a, "number required"); \
} \
if (jv_get_kind(b) != JV_KIND_NUMBER) { \
jv_free(a); \
return type_error(b, "number required"); \
} \
jv ret = jv_number(name(jv_number_value(a), jv_number_value(b))); \
jv_free(a); \
jv_free(b); \
@@ -131,22 +113,9 @@ static jv f_ ## name(jq_state *jq, jv input, jv a, jv b) { \
#define LIBM_DDDD(name) \
static jv f_ ## name(jq_state *jq, jv input, jv a, jv b, jv c) { \
if (jv_get_kind(a) != JV_KIND_NUMBER || jv_get_kind(b) != JV_KIND_NUMBER) \
return type_error(input, "number required"); \
jv_free(input); \
if (jv_get_kind(a) != JV_KIND_NUMBER) { \
jv_free(b); \
jv_free(c); \
return type_error(a, "number required"); \
} \
if (jv_get_kind(b) != JV_KIND_NUMBER) { \
jv_free(a); \
jv_free(c); \
return type_error(b, "number required"); \
} \
if (jv_get_kind(c) != JV_KIND_NUMBER) { \
jv_free(a); \
jv_free(b); \
return type_error(c, "number required"); \
} \
jv ret = jv_number(name(jv_number_value(a), jv_number_value(b), jv_number_value(c))); \
jv_free(a); \
jv_free(b); \
@@ -162,41 +131,6 @@ static jv f_ ## name(jq_state *jq, jv input, jv a, jv b, jv c) { \
#undef LIBM_DDD
#undef LIBM_DD
#ifdef HAVE_FREXP
static jv f_frexp(jq_state *jq, jv input) {
if (jv_get_kind(input) != JV_KIND_NUMBER) {
return type_error(input, "number required");
}
int exp;
double d = frexp(jv_number_value(input), &exp);
jv ret = JV_ARRAY(jv_number(d), jv_number(exp));
jv_free(input);
return ret;
}
#endif
#ifdef HAVE_MODF
static jv f_modf(jq_state *jq, jv input) {
if (jv_get_kind(input) != JV_KIND_NUMBER) {
return type_error(input, "number required");
}
double i;
jv ret = JV_ARRAY(jv_number(modf(jv_number_value(input), &i)));
jv_free(input);
return jv_array_append(ret, jv_number(i));
}
#endif
#ifdef HAVE_LGAMMA_R
static jv f_lgamma_r(jq_state *jq, jv input) {
if (jv_get_kind(input) != JV_KIND_NUMBER) {
return type_error(input, "number required");
}
int sign;
jv ret = JV_ARRAY(jv_number(lgamma_r(jv_number_value(input), &sign)));
jv_free(input);
return jv_array_append(ret, jv_number(sign));
}
#endif
static jv f_negate(jq_state *jq, jv input) {
if (jv_get_kind(input) != JV_KIND_NUMBER) {
return type_error(input, "cannot be negated");
@@ -208,7 +142,7 @@ static jv f_negate(jq_state *jq, jv input) {
static jv f_startswith(jq_state *jq, jv a, jv b) {
if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)
return ret_error2(a, b, jv_string("startswith() requires string inputs"));
return jv_invalid_with_msg(jv_string("startswith() requires string inputs"));
int alen = jv_string_length_bytes(jv_copy(a));
int blen = jv_string_length_bytes(jv_copy(b));
jv ret;
@@ -224,7 +158,7 @@ static jv f_startswith(jq_state *jq, jv a, jv b) {
static jv f_endswith(jq_state *jq, jv a, jv b) {
if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)
return ret_error2(a, b, jv_string("endswith() requires string inputs"));
return jv_invalid_with_msg(jv_string("endswith() requires string inputs"));
const char *astr = jv_string_value(a);
const char *bstr = jv_string_value(b);
size_t alen = jv_string_length_bytes(jv_copy(a));
@@ -462,24 +396,6 @@ static jv f_utf8bytelength(jq_state *jq, jv input) {
#define CHARS_ALPHANUM "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
static const unsigned char BASE64_ENCODE_TABLE[64 + 1] = CHARS_ALPHANUM "+/";
static const unsigned char BASE64_INVALID_ENTRY = 0xFF;
static const unsigned char BASE64_DECODE_TABLE[255] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
62, // +
0xFF, 0xFF, 0xFF,
63, // /
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // 0-9
0xFF, 0xFF, 0xFF,
99, // =
0xFF, 0xFF, 0xFF,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // A-Z
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // a-z
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static jv escape_string(jv input, const char* escapings) {
assert(jv_get_kind(input) == JV_KIND_STRING);
@@ -632,6 +548,7 @@ static jv f_format(jq_state *jq, jv input, jv fmt) {
jv_free(fmt);
input = f_tostring(jq, input);
jv line = jv_string("");
const char b64[64 + 1] = CHARS_ALPHANUM "+/";
const unsigned char* data = (const unsigned char*)jv_string_value(input);
int len = jv_string_length_bytes(jv_copy(input));
for (int i=0; i<len; i+=3) {
@@ -643,7 +560,7 @@ static jv f_format(jq_state *jq, jv input, jv fmt) {
}
char buf[4];
for (int j=0; j<4; j++) {
buf[j] = BASE64_ENCODE_TABLE[(code >> (18 - j*6)) & 0x3f];
buf[j] = b64[(code >> (18 - j*6)) & 0x3f];
}
if (n < 3) buf[3] = '=';
if (n < 2) buf[2] = '=';
@@ -651,49 +568,6 @@ static jv f_format(jq_state *jq, jv input, jv fmt) {
}
jv_free(input);
return line;
} else if (!strcmp(fmt_s, "base64d")) {
jv_free(fmt);
input = f_tostring(jq, input);
const unsigned char* data = (const unsigned char*)jv_string_value(input);
int len = jv_string_length_bytes(jv_copy(input));
size_t decoded_len = (3 * len) / 4; // 3 usable bytes for every 4 bytes of input
char *result = jv_mem_calloc(decoded_len, sizeof(char));
memset(result, 0, decoded_len * sizeof(char));
uint32_t ri = 0;
int input_bytes_read=0;
uint32_t code = 0;
for (int i=0; i<len && data[i] != '='; i++) {
if (BASE64_DECODE_TABLE[data[i]] == BASE64_INVALID_ENTRY) {
free(result);
return type_error(input, "is not valid base64 data");
}
code <<= 6;
code |= BASE64_DECODE_TABLE[data[i]];
input_bytes_read++;
if (input_bytes_read == 4) {
result[ri++] = (code >> 16) & 0xFF;
result[ri++] = (code >> 8) & 0xFF;
result[ri++] = code & 0xFF;
input_bytes_read = 0;
code = 0;
}
}
if (input_bytes_read == 3) {
result[ri++] = (code >> 10) & 0xFF;
result[ri++] = (code >> 2) & 0xFF;
} else if (input_bytes_read == 2) {
result[ri++] = (code >> 4) & 0xFF;
} else if (input_bytes_read == 1) {
free(result);
return type_error(input, "trailing base64 byte found");
}
jv line = jv_string_sized(result, ri);
jv_free(input);
free(result);
return line;
} else {
jv_free(input);
return jv_invalid_with_msg(jv_string_concat(fmt, jv_string(" is not a valid format")));
@@ -744,7 +618,7 @@ static jv f_group_by_impl(jq_state *jq, jv input, jv keys) {
}
}
#ifdef HAVE_LIBONIG
#ifdef HAVE_ONIGURUMA
static int f_match_name_iter(const UChar* name, const UChar *name_end, int ngroups,
int *groups, regex_t *reg, void *arg) {
jv captures = *(jv*)arg;
@@ -948,11 +822,11 @@ static jv f_match(jq_state *jq, jv input, jv regex, jv modifiers, jv testmode) {
jv_free(regex);
return result;
}
#else /* !HAVE_LIBONIG */
#else /* ! HAVE_ONIGURUMA */
static jv f_match(jq_state *jq, jv input, jv regex, jv modifiers, jv testmode) {
return jv_invalid_with_msg(jv_string("jq was compiled without ONIGURUMA regex libary. match/test/sub and related functions are not available."));
}
#endif /* HAVE_LIBONIG */
#endif /* HAVE_ONIGURUMA */
static jv minmax_by(jv values, jv keys, int is_min) {
if (jv_get_kind(values) != JV_KIND_ARRAY)
@@ -1060,14 +934,14 @@ static jv f_error(jq_state *jq, jv input, jv msg) {
// FIXME Should autoconf check for this!
#ifndef WIN32
extern char **environ;
extern const char **environ;
#endif
static jv f_env(jq_state *jq, jv input) {
jv_free(input);
jv env = jv_object();
const char *var, *val;
for (char **e = environ; *e != NULL; e++) {
for (const char **e = environ; *e != NULL; e++) {
var = e[0];
val = strchr(e[0], '=');
if (val == NULL)
@@ -1078,21 +952,6 @@ static jv f_env(jq_state *jq, jv input) {
return env;
}
static jv f_halt(jq_state *jq, jv input) {
jv_free(input);
jq_halt(jq, jv_invalid(), jv_invalid());
return jv_true();
}
static jv f_halt_error(jq_state *jq, jv input, jv a) {
if (jv_get_kind(a) != JV_KIND_NUMBER) {
jv_free(a);
return type_error(input, "halt_error/1: number required");
}
jq_halt(jq, a, input);
return jv_true();
}
static jv f_get_search_list(jq_state *jq, jv input) {
jv_free(input);
return jq_get_lib_dirs(jq);
@@ -1110,14 +969,17 @@ static jv f_get_jq_origin(jq_state *jq, jv input) {
static jv f_string_split(jq_state *jq, jv a, jv b) {
if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING) {
return ret_error2(a, b, jv_string("split input and separator must be strings"));
jv_free(a);
jv_free(b);
return jv_invalid_with_msg(jv_string("split input and separator must be strings"));
}
return jv_string_split(a, b);
}
static jv f_string_explode(jq_state *jq, jv a) {
if (jv_get_kind(a) != JV_KIND_STRING) {
return ret_error(a, jv_string("explode input must be a string"));
jv_free(a);
return jv_invalid_with_msg(jv_string("explode input must be a string"));
}
return jv_string_explode(a);
}
@@ -1128,22 +990,21 @@ static jv f_string_indexes(jq_state *jq, jv a, jv b) {
static jv f_string_implode(jq_state *jq, jv a) {
if (jv_get_kind(a) != JV_KIND_ARRAY) {
return ret_error(a, jv_string("implode input must be an array"));
jv_free(a);
return jv_invalid_with_msg(jv_string("implode input must be an array"));
}
return jv_string_implode(a);
}
static jv f_setpath(jq_state *jq, jv a, jv b, jv c) { return jv_setpath(a, b, c); }
extern jv _jq_path_append(jq_state *, jv, jv, jv);
static jv f_getpath(jq_state *jq, jv a, jv b) {
return _jq_path_append(jq, a, b, jv_getpath(jv_copy(a), jv_copy(b)));
}
static jv f_getpath(jq_state *jq, jv a, jv b) { return jv_getpath(a, b); }
static jv f_delpaths(jq_state *jq, jv a, jv b) { return jv_delpaths(a, b); }
static jv f_has(jq_state *jq, jv a, jv b) { return jv_has(a, b); }
static jv f_modulemeta(jq_state *jq, jv a) {
if (jv_get_kind(a) != JV_KIND_STRING) {
return ret_error(a, jv_string("modulemeta input module name must be a string"));
jv_free(a);
return jv_invalid_with_msg(jv_string("modulemeta input module name must be a string"));
}
return load_module_meta(jq, a);
}
@@ -1172,6 +1033,7 @@ static jv f_debug(jq_state *jq, jv input) {
static jv f_stderr(jq_state *jq, jv input) {
jv_dumpf(jv_copy(input), stderr, 0);
fprintf(stderr, "\n");
return input;
}
@@ -1201,135 +1063,45 @@ static jv tm2jv(struct tm *tm) {
*
* Returns (time_t)-2 if mktime()'s side-effects cannot be corrected.
*/
static time_t my_timegm(struct tm *tm) {
static time_t my_mktime(struct tm *tm) {
#ifdef HAVE_TIMEGM
return timegm(tm);
#else /* HAVE_TIMEGM */
char *tz;
tz = (tz = getenv("TZ")) != NULL ? strdup(tz) : NULL;
if (tz != NULL)
setenv("TZ", "", 1);
time_t t = mktime(tm);
if (tz != NULL)
setenv("TZ", tz, 1);
return t;
#endif /* !HAVE_TIMEGM */
}
static time_t my_mktime(struct tm *tm) {
time_t t = mktime(tm);
if (t == (time_t)-1)
return t;
#ifdef HAVE_TM_TM_GMT_OFF
return t + tm->tm_gmtoff;
#elif HAVE_TM___TM_GMT_OFF
return t + tm->__tm_gmtoff;
return t + tm.tm_gmtoff;
#elif defined(HAVE_TM_TM_GMT_OFF)
return t + tm.__tm_gmtoff;
#else
return (time_t)-2; /* Not supported */
#endif
}
/* Compute and set tm_wday */
static void set_tm_wday(struct tm *tm) {
/*
* https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Gauss.27s_algorithm
* https://cs.uwaterloo.ca/~alopez-o/math-faq/node73.html
*
* Tested with dates from 1900-01-01 through 2100-01-01. This
* algorithm produces the wrong day-of-the-week number for dates in
* the range 1900-01-01..1900-02-28, and for 2100-01-01..2100-02-28.
* Since this is only needed on OS X and *BSD, we might just document
* this.
*/
int century = (1900 + tm->tm_year) / 100;
int year = (1900 + tm->tm_year) % 100;
if (tm->tm_mon < 2)
year--;
/*
* The month value in the wday computation below is shifted so that
* March is 1, April is 2, .., January is 11, and February is 12.
*/
int mon = tm->tm_mon - 1;
if (mon < 1)
mon += 12;
int wday =
(tm->tm_mday + (int)floor((2.6 * mon - 0.2)) + year + (int)floor(year / 4.0) + (int)floor(century / 4.0) - 2 * century) % 7;
if (wday < 0)
wday += 7;
#if 0
/* See commentary above */
assert(wday == tm->tm_wday || tm->tm_wday == 8);
#endif
tm->tm_wday = wday;
}
/*
* Compute and set tm_yday.
*
*/
static void set_tm_yday(struct tm *tm) {
static const int d[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
int mon = tm->tm_mon;
int year = 1900 + tm->tm_year;
int leap_day = 0;
if (tm->tm_mon > 1 &&
((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
leap_day = 1;
/* Bound check index into d[] */
if (mon < 0)
mon = -mon;
if (mon > 11)
mon %= 12;
int yday = d[mon] + leap_day + tm->tm_mday - 1;
assert(yday == tm->tm_yday || tm->tm_yday == 367);
tm->tm_yday = yday;
#endif /* !HAVE_TIMEGM */
}
#ifdef HAVE_STRPTIME
static jv f_strptime(jq_state *jq, jv a, jv b) {
if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING) {
return ret_error2(a, b, jv_string("strptime/1 requires string inputs and arguments"));
}
if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)
return jv_invalid_with_msg(jv_string("strptime/1 requires string inputs and arguments"));
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_wday = 8; // sentinel
tm.tm_yday = 367; // sentinel
const char *input = jv_string_value(a);
const char *fmt = jv_string_value(b);
const char *end = strptime(input, fmt, &tm);
if (end == NULL || (*end != '\0' && !isspace(*end))) {
return ret_error2(a, b, jv_string_fmt("date \"%s\" does not match format \"%s\"", input, fmt));
jv e = jv_invalid_with_msg(jv_string_fmt("date \"%s\" does not match format \"%s\"", input, fmt));
jv_free(a);
jv_free(b);
return e;
}
jv_free(b);
/*
* This is OS X or some *BSD whose strptime() is just not that
* helpful!
*
* We don't know that the format string did involve parsing a
* year, or a month (if tm->tm_mon == 0). But with our invalid
* day-of-week and day-of-year sentinel checks above, the worst
* this can do is produce garbage.
*/
#ifdef __APPLE__
/*
* Apple has made it worse, and different versions of the OS have different
* behaviors. Some versions just don't touch the fields, but others do, and
* sometimes provide wrong answers, at that! We can't tell at compile-time
* which behavior the target system will have, so instead we always use our
* functions to set these on OS X, and document that %u and %j are
* unsupported on OS X.
*/
set_tm_wday(&tm);
set_tm_yday(&tm);
#else
if (tm.tm_wday == 8 && tm.tm_mday != 0 && tm.tm_mon >= 0 && tm.tm_mon <= 11)
set_tm_wday(&tm);
if (tm.tm_yday == 367 && tm.tm_mday != 0 && tm.tm_mon >= 0 && tm.tm_mon <= 11)
set_tm_yday(&tm);
#endif
if (tm.tm_wday == 0 && tm.tm_yday == 0 && my_mktime(&tm) == (time_t)-2) {
jv_free(a);
return jv_invalid_with_msg(jv_string("strptime/1 not supported on this platform"));
}
jv r = tm2jv(&tm);
if (*end != '\0')
r = jv_array_append(r, jv_string(end));
@@ -1347,10 +1119,8 @@ static jv f_strptime(jq_state *jq, jv a, jv b) {
#define TO_TM_FIELD(t, j, i) \
do { \
jv n = jv_array_get(jv_copy(j), (i)); \
if (jv_get_kind(n) != (JV_KIND_NUMBER)) { \
jv_free(j); \
if (jv_get_kind(n) != (JV_KIND_NUMBER)) \
return 0; \
} \
t = jv_number_value(n); \
jv_free(n); \
} while (0)
@@ -1383,9 +1153,9 @@ static int jv2tm(jv a, struct tm *tm) {
static jv f_mktime(jq_state *jq, jv a) {
if (jv_get_kind(a) != JV_KIND_ARRAY)
return ret_error(a, jv_string("mktime requires array inputs"));
return jv_invalid_with_msg(jv_string("mktime requires array inputs"));
if (jv_array_length(jv_copy(a)) < 6)
return ret_error(a, jv_string("mktime requires parsed datetime inputs"));
return jv_invalid_with_msg(jv_string("mktime requires parsed datetime inputs"));
struct tm tm;
if (!jv2tm(a, &tm))
return jv_invalid_with_msg(jv_string("mktime requires parsed datetime inputs"));
@@ -1400,7 +1170,7 @@ static jv f_mktime(jq_state *jq, jv a) {
#ifdef HAVE_GMTIME_R
static jv f_gmtime(jq_state *jq, jv a) {
if (jv_get_kind(a) != JV_KIND_NUMBER)
return ret_error(a, jv_string("gmtime() requires numeric inputs"));
return jv_invalid_with_msg(jv_string("gmtime() requires numeric inputs"));
struct tm tm, *tmp;
memset(&tm, 0, sizeof(tm));
double fsecs = jv_number_value(a);
@@ -1415,7 +1185,7 @@ static jv f_gmtime(jq_state *jq, jv a) {
#elif defined HAVE_GMTIME
static jv f_gmtime(jq_state *jq, jv a) {
if (jv_get_kind(a) != JV_KIND_NUMBER)
return ret_error(a, jv_string("gmtime requires numeric inputs"));
return jv_invalid_with_msg(jv_string("gmtime requires numeric inputs"));
struct tm tm, *tmp;
memset(&tm, 0, sizeof(tm));
double fsecs = jv_number_value(a);
@@ -1434,56 +1204,16 @@ static jv f_gmtime(jq_state *jq, jv a) {
}
#endif
#ifdef HAVE_LOCALTIME_R
static jv f_localtime(jq_state *jq, jv a) {
if (jv_get_kind(a) != JV_KIND_NUMBER)
return ret_error(a, jv_string("localtime() requires numeric inputs"));
struct tm tm, *tmp;
memset(&tm, 0, sizeof(tm));
double fsecs = jv_number_value(a);
time_t secs = fsecs;
jv_free(a);
tmp = localtime_r(&secs, &tm);
if (tmp == NULL)
return jv_invalid_with_msg(jv_string("error converting number of seconds since epoch to datetime"));
a = tm2jv(tmp);
return jv_array_set(a, 5, jv_number(jv_number_value(jv_array_get(jv_copy(a), 5)) + (fsecs - floor(fsecs))));
}
#elif defined HAVE_GMTIME
static jv f_localtime(jq_state *jq, jv a) {
if (jv_get_kind(a) != JV_KIND_NUMBER)
return ret_error(a, jv_string("localtime requires numeric inputs"));
struct tm tm, *tmp;
memset(&tm, 0, sizeof(tm));
double fsecs = jv_number_value(a);
time_t secs = fsecs;
jv_free(a);
tmp = localtime(&secs);
if (tmp == NULL)
return jv_invalid_with_msg(jv_string("error converting number of seconds since epoch to datetime"));
a = tm2jv(tmp);
return jv_array_set(a, 5, jv_number(jv_number_value(jv_array_get(jv_copy(a), 5)) + (fsecs - floor(fsecs))));
}
#else
static jv f_localtime(jq_state *jq, jv a) {
jv_free(a);
return jv_invalid_with_msg(jv_string("localtime not implemented on this platform"));
}
#endif
#ifdef HAVE_STRFTIME
static jv f_strftime(jq_state *jq, jv a, jv b) {
if (jv_get_kind(a) == JV_KIND_NUMBER) {
a = f_gmtime(jq, a);
} else if (jv_get_kind(a) != JV_KIND_ARRAY) {
return ret_error2(a, b, jv_string("strftime/1 requires parsed datetime inputs"));
} else if (jv_get_kind(b) != JV_KIND_STRING) {
return ret_error2(a, b, jv_string("strftime/1 requires a string format"));
return jv_invalid_with_msg(jv_string("strftime/1 requires parsed datetime inputs"));
}
struct tm tm;
if (!jv2tm(a, &tm))
return ret_error(b, jv_string("strftime/1 requires parsed datetime inputs"));
return jv_invalid_with_msg(jv_string("strftime/1 requires parsed datetime inputs")); \
const char *fmt = jv_string_value(b);
size_t alloced = strlen(fmt) + 100;
char *buf = alloca(alloced);
@@ -1495,43 +1225,13 @@ static jv f_strftime(jq_state *jq, jv a, jv b) {
return jv_string(buf);
}
#else
static jv f_strftime(jq_state *jq, jv a, jv b) {
static jv f_strftime(jq_state *jq, jv a) {
jv_free(a);
jv_free(b);
return jv_invalid_with_msg(jv_string("strftime/1 not implemented on this platform"));
}
#endif
#ifdef HAVE_STRFTIME
static jv f_strflocaltime(jq_state *jq, jv a, jv b) {
if (jv_get_kind(a) == JV_KIND_NUMBER) {
a = f_localtime(jq, a);
} else if (jv_get_kind(a) != JV_KIND_ARRAY) {
return ret_error2(a, b, jv_string("strflocaltime/1 requires parsed datetime inputs"));
} else if (jv_get_kind(b) != JV_KIND_STRING) {
return ret_error2(a, b, jv_string("strflocaltime/1 requires a string format"));
}
struct tm tm;
if (!jv2tm(a, &tm))
return jv_invalid_with_msg(jv_string("strflocaltime/1 requires parsed datetime inputs"));
const char *fmt = jv_string_value(b);
size_t alloced = strlen(fmt) + 100;
char *buf = alloca(alloced);
size_t n = strftime(buf, alloced, fmt, &tm);
jv_free(b);
/* POSIX doesn't provide errno values for strftime() failures; weird */
if (n == 0 || n > alloced)
return jv_invalid_with_msg(jv_string("strflocaltime/1: unknown system failure"));
return jv_string(buf);
}
#else
static jv f_strflocaltime(jq_state *jq, jv a, jv b) {
jv_free(a);
jv_free(b);
return jv_invalid_with_msg(jv_string("strflocaltime/1 not implemented on this platform"));
}
#endif
#ifdef HAVE_GETTIMEOFDAY
static jv f_now(jq_state *jq, jv a) {
jv_free(a);
@@ -1562,28 +1262,19 @@ static jv f_current_line(jq_state *jq, jv a) {
}
#define LIBM_DD(name) \
{(cfunction_ptr)f_ ## name, #name, 1},
{(cfunction_ptr)f_ ## name, "_" #name, 1},
#define LIBM_DD_NO(name)
#define LIBM_DDD(name) \
{(cfunction_ptr)f_ ## name, #name, 3},
{(cfunction_ptr)f_ ## name, "_" #name, 3},
#define LIBM_DDD_NO(name)
#define LIBM_DDDD(name) \
{(cfunction_ptr)f_ ## name, #name, 4},
{(cfunction_ptr)f_ ## name, "_" #name, 4},
#define LIBM_DDDD_NO(name)
static const struct cfunction function_list[] = {
#include "libm.h"
#ifdef HAVE_FREXP
{(cfunction_ptr)f_frexp,"frexp", 1},
#endif
#ifdef HAVE_MODF
{(cfunction_ptr)f_modf,"modf", 1},
#endif
#ifdef HAVE_LGAMMA_R
{(cfunction_ptr)f_lgamma_r,"lgamma_r", 1},
#endif
{(cfunction_ptr)f_plus, "_plus", 3},
{(cfunction_ptr)f_negate, "_negate", 1},
{(cfunction_ptr)f_minus, "_minus", 3},
@@ -1633,8 +1324,6 @@ static const struct cfunction function_list[] = {
{(cfunction_ptr)f_error, "error", 2},
{(cfunction_ptr)f_format, "format", 2},
{(cfunction_ptr)f_env, "env", 1},
{(cfunction_ptr)f_halt, "halt", 1},
{(cfunction_ptr)f_halt_error, "halt_error", 2},
{(cfunction_ptr)f_get_search_list, "get_search_list", 1},
{(cfunction_ptr)f_get_prog_origin, "get_prog_origin", 1},
{(cfunction_ptr)f_get_jq_origin, "get_jq_origin", 1},
@@ -1645,10 +1334,8 @@ static const struct cfunction function_list[] = {
{(cfunction_ptr)f_stderr, "stderr", 1},
{(cfunction_ptr)f_strptime, "strptime", 2},
{(cfunction_ptr)f_strftime, "strftime", 2},
{(cfunction_ptr)f_strflocaltime, "strflocaltime", 2},
{(cfunction_ptr)f_mktime, "mktime", 1},
{(cfunction_ptr)f_gmtime, "gmtime", 1},
{(cfunction_ptr)f_localtime, "localtime", 1},
{(cfunction_ptr)f_now, "now", 1},
{(cfunction_ptr)f_current_filename, "input_filename", 1},
{(cfunction_ptr)f_current_line, "input_line_number", 1},
@@ -1703,32 +1390,37 @@ static block bind_bytecoded_builtins(block b) {
BLOCK(gen_param("start"), gen_param("end")),
range));
}
return block_bind(builtins, b, OP_IS_CALL_PSEUDO);
return block_bind_referenced(builtins, b, OP_IS_CALL_PSEUDO);
}
#define LIBM_DD(name) "def " #name ": _" #name ";"
#define LIBM_DDD(name) "def " #name "(a;b): _" #name "(a;b);"
#define LIBM_DDDD(name) "def " #name "(a;b;c): _" #name "(a;b;c);"
#define LIBM_DD_NO(name)
#define LIBM_DDD_NO(name)
#define LIBM_DDDD_NO(name)
static const char* const jq_builtins =
/* Include jq-coded builtins */
/* Include supported math functions first */
#include "libm.h"
/* Include jq-coded builtins next (some depend on math) */
#include "src/builtin.inc"
/* Include unsupported math functions next */
#undef LIBM_DDDD_NO
#undef LIBM_DDD_NO
#undef LIBM_DD_NO
#undef LIBM_DDDD
#undef LIBM_DDD
#undef LIBM_DD
#define LIBM_DD(name)
#define LIBM_DDD(name)
#define LIBM_DDDD(name)
#define LIBM_DD_NO(name) "def " #name ": \"Error: " #name "/0 not found at build time\"|error;"
#define LIBM_DDD_NO(name) "def " #name "(a;b): \"Error: " #name "/2 not found at build time\"|error;"
#define LIBM_DDDD_NO(name) "def " #name "(a;b;c): \"Error: " #name "/3 not found at build time\"|error;"
#define LIBM_DD_NO(name) "def " #name ": \"Error: " #name "() not found at build time\"|error;"
#define LIBM_DDD_NO(name) "def " #name "(a;b): \"Error: " #name "() not found at build time\"|error;"
#define LIBM_DDDD_NO(name) "def " #name "(a;b;c): \"Error: " #name "() not found at build time\"|error;"
#include "libm.h"
#ifndef HAVE_FREXP
"def frexp: \"Error: frexp/0 not found found at build time\"|error;"
#endif
#ifndef HAVE_MODF
"def modf: \"Error: modf/0 not found found at build time\"|error;"
#endif
#ifndef HAVE_LGAMMA_R
"def lgamma_r: \"Error: lgamma_r/0 not found found at build time\"|error;"
#endif
;
#undef LIBM_DDDD_NO
@@ -1739,18 +1431,13 @@ static const char* const jq_builtins =
#undef LIBM_DD
static block gen_builtin_list(block builtins) {
jv list = jv_array_append(block_list_funcs(builtins, 1), jv_string("builtins/0"));
return BLOCK(builtins, gen_function("builtins", gen_noop(), gen_const(list)));
}
static int builtins_bind_one(jq_state *jq, block* bb, const char* code) {
struct locfile* src;
src = locfile_init(jq, "<builtin>", code, strlen(code));
block funcs;
int nerrors = jq_parse_library(src, &funcs);
if (nerrors == 0) {
*bb = block_bind(funcs, *bb, OP_IS_CALL_PSEUDO);
*bb = block_bind_referenced(funcs, *bb, OP_IS_CALL_PSEUDO);
}
locfile_free(src);
return nerrors;
@@ -1772,18 +1459,14 @@ static int slurp_lib(jq_state *jq, block* bb) {
}
int builtins_bind(jq_state *jq, block* bb) {
block builtins = gen_noop();
int nerrors = slurp_lib(jq, bb);
if (nerrors) {
block_free(*bb);
return nerrors;
}
nerrors = builtins_bind_one(jq, &builtins, jq_builtins);
nerrors = builtins_bind_one(jq, bb, jq_builtins);
assert(!nerrors);
builtins = bind_bytecoded_builtins(builtins);
builtins = gen_cbinding(function_list, sizeof(function_list)/sizeof(function_list[0]), builtins);
builtins = gen_builtin_list(builtins);
*bb = block_bind(builtins, *bb, OP_IS_CALL_PSEUDO);
*bb = block_drop_unreferenced(*bb);
*bb = bind_bytecoded_builtins(*bb);
*bb = gen_cbinding(function_list, sizeof(function_list)/sizeof(function_list[0]), *bb);
return nerrors;
}
+3 -8
View File
@@ -1,4 +1,3 @@
def halt_error: halt_error(5);
def error: error(.);
def map(f): [.[] | f];
def select(f): if f then . else empty end;
@@ -167,11 +166,7 @@ def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
def limit($n; exp):
if $n < 0 then exp
else label $out | foreach exp as $item ($n; .-1; $item, if . <= 0 then break $out else empty end)
end;
def isempty(g): 0 == ((label $go | g | (1, break $go)) // 0);
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;
def first(g): label $out | g | ., break $out;
def last(g): reduce g as $item (null; $item);
def nth($n; g): if $n < 0 then error("nth doesn't support negative indices") else last(limit($n + 1; g)) end;
@@ -240,7 +235,7 @@ def tostream:
else
# We really need a _streaming_ form of `keys`.
# We can use `range` for arrays, but not for objects.
keys_unsorted as $keys |
keys as $keys |
$keys[-1] as $last|
((# for each key
$keys[] | . as $key |
@@ -287,7 +282,7 @@ def bsearch(target):
def walk(f):
. as $in
| if type == "object" then
reduce keys_unsorted[] as $key
reduce keys[] as $key
( {}; . + { ($key): ($in[$key] | walk(f)) } ) | f
elif type == "array" then map( walk(f) ) | f
else f
+45 -199
View File
@@ -5,7 +5,6 @@
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "compile.h"
#include "bytecode.h"
#include "locfile.h"
@@ -159,15 +158,8 @@ block gen_const_global(jv constant, const char *name) {
return inst_block(i);
}
block gen_op_pushk_under(jv constant) {
assert(opcode_describe(PUSHK_UNDER)->flags & OP_HAS_CONSTANT);
inst* i = inst_new(PUSHK_UNDER);
i->imm.constant = constant;
return inst_block(i);
}
int block_is_const(block b) {
return (block_is_single(b) && (b.first->op == LOADK || b.first->op == PUSHK_UNDER));
return (block_is_single(b) && b.first->op == LOADK);
}
int block_is_const_inf(block b) {
@@ -227,10 +219,6 @@ block gen_op_bound(opcode op, block binder) {
return b;
}
block gen_dictpair(block k, block v) {
return BLOCK(gen_subexp(k), gen_subexp(v), gen_op_simple(INSERT));
}
static void inst_join(inst* a, inst* b) {
assert(a && b);
@@ -492,18 +480,6 @@ jv block_take_imports(block* body) {
return imports;
}
jv block_list_funcs(block body, int omit_underscores) {
jv funcs = jv_object(); // Use the keys for set semantics.
for (inst *pos = body.first; pos != NULL; pos = pos->next) {
if (pos->op == CLOSURE_CREATE || pos->op == CLOSURE_CREATE_C) {
if (pos->symbol != NULL && (!omit_underscores || pos->symbol[0] != '_')) {
funcs = jv_object_set(funcs, jv_string_fmt("%s/%i", pos->symbol, pos->nformals), jv_null());
}
}
}
return jv_keys_unsorted(funcs);
}
block gen_module(block metadata) {
inst* i = inst_new(MODULEMETA);
i->imm.constant = block_const(metadata);
@@ -574,15 +550,9 @@ block gen_call(const char* name, block args) {
return b;
}
block gen_subexp(block a) {
if (block_is_noop(a)) {
return gen_op_simple(DUP);
}
if (block_is_single(a) && a.first->op == LOADK) {
jv c = block_const(a);
block_free(a);
return gen_op_pushk_under(c);
}
return BLOCK(gen_op_simple(SUBEXP_BEGIN), a, gen_op_simple(SUBEXP_END));
}
@@ -600,24 +570,17 @@ block gen_const_object(block expr) {
jv k = jv_null();
jv v = jv_null();
for (inst *i = expr.first; i; i = i->next) {
if (i->op == PUSHK_UNDER) {
k = jv_copy(i->imm.constant);
i = i->next;
} else if (i->op != SUBEXP_BEGIN ||
if (i->op != SUBEXP_BEGIN ||
i->next == NULL ||
i->next->op != LOADK ||
i->next->next == NULL ||
i->next->next->op != SUBEXP_END) {
is_const = 0;
break;
} else {
k = jv_copy(i->next->imm.constant);
i = i->next->next->next;
}
if (i != NULL && i->op == PUSHK_UNDER) {
v = jv_copy(i->imm.constant);
i = i->next;
} else if (i == NULL ||
k = jv_copy(i->next->imm.constant);
i = i->next->next->next;
if (i == NULL ||
i->op != SUBEXP_BEGIN ||
i->next == NULL ||
i->next->op != LOADK ||
@@ -625,10 +588,9 @@ block gen_const_object(block expr) {
i->next->next->op != SUBEXP_END) {
is_const = 0;
break;
} else {
v = jv_copy(i->next->imm.constant);
i = i->next->next->next;
}
v = jv_copy(i->next->imm.constant);
i = i->next->next->next;
if (i == NULL || i->op != INSERT) {
is_const = 0;
break;
@@ -734,94 +696,35 @@ static block bind_matcher(block matcher, block body) {
// block_has_only_binders(matcher), which is not true here as matchers
// may also contain code to extract the correct elements
for (inst* i = matcher.first; i; i = i->next) {
if ((i->op == STOREV || i->op == STOREVN) && !i->bound_by)
if (i->op == STOREV && !i->bound_by)
block_bind_subblock(inst_block(i), body, OP_HAS_VARIABLE, 0);
}
return BLOCK(matcher, body);
}
// Extract destructuring var names from the block
// *vars should be a jv_object (for set semantics)
static void block_get_unbound_vars(block b, jv *vars) {
assert(vars != NULL);
assert(jv_get_kind(*vars) == JV_KIND_OBJECT);
for (inst* i = b.first; i; i = i->next) {
if (i->subfn.first) {
block_get_unbound_vars(i->subfn, vars);
continue;
}
if ((i->op == STOREV || i->op == STOREVN) && i->bound_by == NULL) {
*vars = jv_object_set(*vars, jv_string(i->symbol), jv_true());
}
}
}
/* Build wrappers around destructuring matchers so that we can chain them
* when we have errors. The approach is as follows:
* DESTRUCTURE_ALT NEXT_MATCHER (unless last matcher)
* existing_matcher_block
* JUMP BODY
*/
static block bind_alternation_matchers(block matchers, block body) {
block preamble = {0};
block altmatchers = {0};
block mb = {0};
block final_matcher = matchers;
// Pass through the matchers to find all destructured names.
while (final_matcher.first && final_matcher.first->op == DESTRUCTURE_ALT) {
block_append(&altmatchers, inst_block(block_take(&final_matcher)));
}
// We don't have any alternations here, so we can use the simplest case.
if (altmatchers.first == NULL) {
return bind_matcher(final_matcher, body);
}
// Collect var names
jv all_vars = jv_object();
block_get_unbound_vars(altmatchers, &all_vars);
block_get_unbound_vars(final_matcher, &all_vars);
// We need a preamble of STOREVs to which to bind the matchers and the body.
jv_object_keys_foreach(all_vars, key) {
preamble = BLOCK(preamble,
gen_op_simple(DUP),
gen_const(jv_null()),
gen_op_unbound(STOREV, jv_string_value(key)));
jv_free(key);
}
jv_free(all_vars);
// Now we build each matcher in turn
for (inst *i = altmatchers.first; i; i = i->next) {
block submatcher = i->subfn;
// If we're successful, jump to the end of the matchers
submatcher = BLOCK(submatcher, gen_op_target(JUMP, final_matcher));
// DESTRUCTURE_ALT to the end of this submatcher so we can skip to the next one on error
mb = BLOCK(mb, gen_op_target(DESTRUCTURE_ALT, submatcher), submatcher);
// We're done with this inst and we don't want it anymore
// But we can't let it free the submatcher block.
i->subfn.first = i->subfn.last = NULL;
}
// We're done with these insts now.
block_free(altmatchers);
return bind_matcher(preamble, BLOCK(mb, final_matcher, body));
}
block gen_reduce(block source, block matcher, block init, block body) {
block res_var = gen_op_var_fresh(STOREV, "reduce");
block update_var = gen_op_bound(STOREV, res_var);
block jmp = gen_op_target(JUMP, body);
block loop = BLOCK(gen_op_simple(DUPN),
source,
bind_alternation_matchers(matcher,
bind_matcher(matcher,
BLOCK(gen_op_bound(LOADVN, res_var),
/*
* We fork to the body, jump to
* the STOREV. This means that
* if body produces no results
* (i.e., it just does empty)
* then we keep the current
* reduction state as-is.
*
* To break out of a
* reduction... use break.
*/
gen_op_target(FORK, jmp),
jmp,
body,
gen_op_bound(STOREV, res_var))),
update_var)),
gen_op_simple(BACKTRACK));
return BLOCK(gen_op_simple(DUP),
init,
@@ -839,7 +742,7 @@ block gen_foreach(block source, block matcher, block init, block update, block e
source,
// destructure the value into variable(s) for all the code
// in the body to see
bind_alternation_matchers(matcher,
bind_matcher(matcher,
// load the loop state variable
BLOCK(gen_op_bound(LOADVN, state_var),
// generate updated state
@@ -945,17 +848,6 @@ block gen_or(block a, block b) {
gen_const(jv_false())))));
}
block gen_destructure_alt(block matcher) {
for (inst *i = matcher.first; i; i = i->next) {
if (i->op == STOREV) {
i->op = STOREVN;
}
}
inst* i = inst_new(DESTRUCTURE_ALT);
i->subfn = matcher;
return inst_block(i);
}
block gen_var_binding(block var, const char* name, block body) {
return gen_destructure(var, gen_op_unbound(STOREV, name), body);
}
@@ -968,16 +860,9 @@ block gen_array_matcher(block left, block curr) {
// `left` was returned by this function, so the third inst is the
// constant containing the previously used index
assert(left.first->op == DUP);
assert(left.first->next != NULL);
inst *i = NULL;
if (left.first->next->op == PUSHK_UNDER) {
i = left.first->next;
} else {
assert(left.first->next->op == SUBEXP_BEGIN);
assert(left.first->next->next->op == LOADK);
i = left.first->next->next;
}
index = 1 + (int) jv_number_value(i->imm.constant);
assert(left.first->next->op == SUBEXP_BEGIN);
assert(left.first->next->next->op == LOADK);
index = 1 + (int) jv_number_value(left.first->next->next->imm.constant);
}
// `left` goes at the end so that the const index is in a predictable place
@@ -990,19 +875,13 @@ block gen_object_matcher(block name, block curr) {
curr);
}
block gen_destructure(block var, block matchers, block body) {
block gen_destructure(block var, block matcher, block body) {
// var bindings can be added after coding the program; leave the TOP first.
block top = gen_noop();
if (body.first && body.first->op == TOP)
top = inst_block(block_take(&body));
if (matchers.first && matchers.first->op == DESTRUCTURE_ALT) {
block_append(&var, gen_op_simple(DUP));
} else {
top = BLOCK(top, gen_op_simple(DUP));
}
return BLOCK(top, gen_subexp(var), gen_op_simple(POP), bind_alternation_matchers(matchers, body));
return BLOCK(top, gen_op_simple(DUP), var, bind_matcher(matcher, body));
}
// Like gen_var_binding(), but bind `break`'s wildcard unbound variable
@@ -1013,7 +892,7 @@ static block gen_wildvar_binding(block var, const char* name, block body) {
}
block gen_cond(block cond, block iftrue, block iffalse) {
return BLOCK(gen_op_simple(DUP), BLOCK(gen_subexp(cond), gen_op_simple(POP)),
return BLOCK(gen_op_simple(DUP), cond,
gen_condbranch(BLOCK(gen_op_simple(POP), iftrue),
BLOCK(gen_op_simple(POP), iffalse)));
}
@@ -1106,46 +985,16 @@ static int count_cfunctions(block b) {
return n;
}
#ifndef WIN32
extern char **environ;
#endif
static jv
make_env(jv env)
{
if (jv_is_valid(env))
return jv_copy(env);
jv r = jv_object();
if (environ == NULL)
return r;
for (size_t i = 0; environ[i] != NULL; i++) {
const char *eq;
if ((eq = strchr(environ[i], '=')) == NULL)
r = jv_object_delete(r, jv_string(environ[i]));
else
r = jv_object_set(r, jv_string_sized(environ[i], eq - environ[i]), jv_string(eq + 1));
}
return jv_copy(r);
}
// Expands call instructions into a calling sequence
static int expand_call_arglist(block* b, jv args, jv *env) {
static int expand_call_arglist(block* b) {
int errors = 0;
block ret = gen_noop();
for (inst* curr; (curr = block_take(b));) {
if (opcode_describe(curr->op)->flags & OP_HAS_BINDING) {
if (!curr->bound_by && curr->op == LOADV && strcmp(curr->symbol, "ENV") == 0) {
curr->op = LOADK;
*env = curr->imm.constant = make_env(*env);
} else if (!curr->bound_by && curr->op == LOADV && jv_object_has(jv_copy(args), jv_string(curr->symbol))) {
curr->op = LOADK;
curr->imm.constant = jv_object_get(jv_copy(args), jv_string(curr->symbol));
} else if (!curr->bound_by) {
if (!curr->bound_by) {
if (curr->symbol[0] == '*' && curr->symbol[1] >= '1' && curr->symbol[1] <= '3' && curr->symbol[2] == '\0')
locfile_locate(curr->locfile, curr->source, "jq: error: break used outside labeled control structure");
else if (curr->op == LOADV)
locfile_locate(curr->locfile, curr->source, "jq: error: $%s is not defined", curr->symbol);
else
locfile_locate(curr->locfile, curr->source, "jq: error: %s/%d is not defined", curr->symbol, block_count_actuals(curr->arglist));
errors++;
@@ -1198,7 +1047,7 @@ static int expand_call_arglist(block* b, jv args, jv *env) {
i->subfn = gen_noop();
inst_free(i);
// arguments should be pushed in reverse order, prepend them to prelude
errors += expand_call_arglist(&body, args, env);
errors += expand_call_arglist(&body);
prelude = BLOCK(gen_subexp(body), prelude);
actual_args++;
}
@@ -1220,12 +1069,12 @@ static int expand_call_arglist(block* b, jv args, jv *env) {
return errors;
}
static int compile(struct bytecode* bc, block b, struct locfile* lf, jv args, jv *env) {
static int compile(struct bytecode* bc, block b, struct locfile* lf) {
int errors = 0;
int pos = 0;
int var_frame_idx = 0;
bc->nsubfunctions = 0;
errors += expand_call_arglist(&b, args, env);
errors += expand_call_arglist(&b);
b = BLOCK(b, gen_op_simple(RET));
jv localnames = jv_array();
for (inst* curr = b.first; curr; curr = curr->next) {
@@ -1270,7 +1119,7 @@ static int compile(struct bytecode* bc, block b, struct locfile* lf, jv args, jv
bc->codelen = pos;
bc->debuginfo = jv_object_set(bc->debuginfo, jv_string("locals"), localnames);
if (bc->nsubfunctions) {
bc->subfunctions = jv_mem_calloc(sizeof(struct bytecode*), bc->nsubfunctions);
bc->subfunctions = jv_mem_alloc(sizeof(struct bytecode*) * bc->nsubfunctions);
for (inst* curr = b.first; curr; curr = curr->next) {
if (curr->op == CLOSURE_CREATE) {
struct bytecode* subfn = jv_mem_alloc(sizeof(struct bytecode));
@@ -1288,14 +1137,14 @@ static int compile(struct bytecode* bc, block b, struct locfile* lf, jv args, jv
params = jv_array_append(params, jv_string(param->symbol));
}
subfn->debuginfo = jv_object_set(subfn->debuginfo, jv_string("params"), params);
errors += compile(subfn, curr->subfn, lf, args, env);
errors += compile(subfn, curr->subfn, lf);
curr->subfn = gen_noop();
}
}
} else {
bc->subfunctions = 0;
}
uint16_t* code = jv_mem_calloc(sizeof(uint16_t), bc->codelen);
uint16_t* code = jv_mem_alloc(sizeof(uint16_t) * bc->codelen);
bc->code = code;
pos = 0;
jv constant_pool = jv_array();
@@ -1353,20 +1202,17 @@ static int compile(struct bytecode* bc, block b, struct locfile* lf, jv args, jv
return errors;
}
int block_compile(block b, struct bytecode** out, struct locfile* lf, jv args) {
int block_compile(block b, struct bytecode** out, struct locfile* lf) {
struct bytecode* bc = jv_mem_alloc(sizeof(struct bytecode));
bc->parent = 0;
bc->nclosures = 0;
bc->globals = jv_mem_alloc(sizeof(struct symbol_table));
int ncfunc = count_cfunctions(b);
bc->globals->ncfunctions = 0;
bc->globals->cfunctions = jv_mem_calloc(sizeof(struct cfunction), ncfunc);
bc->globals->cfunctions = jv_mem_alloc(sizeof(struct cfunction) * ncfunc);
bc->globals->cfunc_names = jv_array();
bc->debuginfo = jv_object_set(jv_object(), jv_string("name"), jv_null());
jv env = jv_invalid();
int nerrors = compile(bc, b, lf, args, &env);
jv_free(args);
jv_free(env);
int nerrors = compile(bc, b, lf);
assert(bc->globals->ncfunctions == ncfunc);
if (nerrors > 0) {
bytecode_free(bc);
+1 -5
View File
@@ -29,7 +29,6 @@ block gen_op_target(opcode op, block target);
block gen_op_unbound(opcode op, const char* name);
block gen_op_bound(opcode op, block binder);
block gen_op_var_fresh(opcode op, const char* name);
block gen_op_pushk_under(jv constant);
block gen_module(block metadata);
jv block_module_meta(block b);
@@ -50,13 +49,11 @@ block gen_definedor(block a, block b);
block gen_condbranch(block iftrue, block iffalse);
block gen_and(block a, block b);
block gen_or(block a, block b);
block gen_dictpair(block k, block v);
block gen_var_binding(block var, const char* name, block body);
block gen_array_matcher(block left, block curr);
block gen_object_matcher(block name, block curr);
block gen_destructure(block var, block matcher, block body);
block gen_destructure_alt(block matcher);
block gen_cond(block cond, block iftrue, block iffalse);
block gen_try_handler(block handler);
@@ -78,9 +75,8 @@ block block_bind_referenced(block binder, block body, int bindflags);
block block_drop_unreferenced(block body);
jv block_take_imports(block* body);
jv block_list_funcs(block body, int omit_underscores);
int block_compile(block, struct bytecode**, struct locfile*, jv);
int block_compile(block, struct bytecode**, struct locfile*);
void block_free(block);
+23 -124
View File
@@ -40,10 +40,6 @@ struct jq_state {
int initial_execution;
unsigned next_label;
int halted;
jv exit_code;
jv error_message;
jv attrs;
jq_input_cb input_cb;
void *input_cb_data;
@@ -246,28 +242,6 @@ static void path_append(jq_state* jq, jv component, jv value_at_path) {
}
}
/* For f_getpath() */
jv
_jq_path_append(jq_state *jq, jv v, jv p, jv value_at_path) {
if (jq->subexp_nest != 0 ||
jv_get_kind(jq->path) != JV_KIND_ARRAY ||
!jv_is_valid(value_at_path)) {
jv_free(v);
jv_free(p);
return value_at_path;
}
if (!jv_identical(v, jv_copy(jq->value_at_path))) {
jv_free(p);
return value_at_path;
}
if (jv_get_kind(p) == JV_KIND_ARRAY)
jq->path = jv_array_concat(jq->path, p);
else
jq->path = jv_array_append(jq->path, p);
jv_free(jq->value_at_path);
return jv_copy(jq->value_at_path = value_at_path);
}
uint16_t* stack_restore(jq_state *jq){
while (!stack_pop_will_free(&jq->stk, jq->fork_top)) {
if (stack_pop_will_free(&jq->stk, jq->stk_top)) {
@@ -311,9 +285,6 @@ static void jq_reset(jq_state *jq) {
jv_free(jq->error);
jq->error = jv_null();
jq->halted = 0;
jv_free(jq->exit_code);
jv_free(jq->error_message);
if (jv_get_kind(jq->path) != JV_KIND_INVALID)
jv_free(jq->path);
jq->path = jv_null();
@@ -349,11 +320,6 @@ jv jq_next(jq_state *jq) {
jq->initial_execution = 0;
assert(jv_get_kind(jq->error) == JV_KIND_NULL);
while (1) {
if (jq->halted) {
if (jq->debug_trace_enabled)
printf("\t<halted>\n");
return jv_invalid();
}
uint16_t opcode = *pc;
raising = 0;
@@ -365,9 +331,10 @@ jv jq_next(jq_state *jq) {
if (!backtracking) {
int stack_in = opdesc->stack_in;
if (stack_in == -1) stack_in = pc[1];
param = jq->stk_top;
for (int i=0; i<stack_in; i++) {
if (i != 0) {
if (i == 0) {
param = jq->stk_top;
} else {
printf(" | ");
param = *stack_block_next(&jq->stk, param);
}
@@ -377,12 +344,6 @@ jv jq_next(jq_state *jq) {
//printf(" -- ");
//jv_dump(jv_copy(jq->path), 0);
}
if (jq->debug_trace_enabled & JQ_DEBUG_TRACE_DETAIL) {
while ((param = *stack_block_next(&jq->stk, param))) {
printf(" || ");
jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);
}
}
} else {
printf("\t<backtracking>");
}
@@ -456,15 +417,6 @@ jv jq_next(jq_state *jq) {
break;
}
case PUSHK_UNDER: {
jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);
assert(jv_is_valid(v));
jv v2 = stack_pop(jq);
stack_push(jq, v);
stack_push(jq, v2);
break;
}
case POP: {
jv_free(stack_pop(jq));
break;
@@ -562,8 +514,6 @@ jv jq_next(jq_state *jq) {
break;
}
case STOREVN:
stack_save(jq, pc - 1, stack_get_pos(jq));
case STOREV: {
uint16_t level = *pc++;
uint16_t v = *pc++;
@@ -579,16 +529,6 @@ jv jq_next(jq_state *jq) {
break;
}
case ON_BACKTRACK(STOREVN): {
uint16_t level = *pc++;
uint16_t v = *pc++;
jv* var = frame_local_var(jq, v, level);
jv_free(*var);
*var = jv_null();
goto do_backtrack;
break;
}
case STORE_GLOBAL: {
// Get the constant
jv val = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);
@@ -799,27 +739,21 @@ jv jq_next(jq_state *jq) {
}
case FORK_OPT:
case DESTRUCTURE_ALT:
case FORK: {
stack_save(jq, pc - 1, stack_get_pos(jq));
pc++; // skip offset this time
break;
}
case ON_BACKTRACK(FORK_OPT):
case ON_BACKTRACK(DESTRUCTURE_ALT): {
case ON_BACKTRACK(FORK_OPT): {
if (jv_is_valid(jq->error)) {
// `try EXP ...` backtracked here (no value, `empty`), so we backtrack more
jv_free(stack_pop(jq));
goto do_backtrack;
}
// `try EXP ...` exception caught in EXP
// DESTRUCTURE_ALT doesn't want the error message on the stack,
// as we would just want to throw it away anyway.
if (opcode != ON_BACKTRACK(DESTRUCTURE_ALT)) {
jv_free(stack_pop(jq)); // free the input
stack_push(jq, jv_invalid_get_msg(jq->error)); // push the error's message
}
jv_free(stack_pop(jq)); // free the input
stack_push(jq, jv_invalid_get_msg(jq->error)); // push the error's message
jq->error = jv_null();
uint16_t offset = *pc++;
pc += offset;
@@ -998,10 +932,6 @@ jq_state *jq_init(void) {
jq->curr_frame = 0;
jq->error = jv_null();
jq->halted = 0;
jq->exit_code = jv_invalid();
jq->error_message = jv_invalid();
jq->err_cb = default_err_cb;
jq->err_cb_data = stderr;
@@ -1044,7 +974,11 @@ void jq_start(jq_state *jq, jv input, int flags) {
stack_push(jq, input);
stack_save(jq, jq->bc->code, stack_get_pos(jq));
jq->debug_trace_enabled = flags & JQ_DEBUG_TRACE_ALL;
if (flags & JQ_DEBUG_TRACE) {
jq->debug_trace_enabled = 1;
} else {
jq->debug_trace_enabled = 0;
}
jq->initial_execution = 1;
}
@@ -1132,26 +1066,9 @@ static struct bytecode *optimize(struct bytecode *bc) {
return optimize_code(bc);
}
static jv
args2obj(jv args)
{
if (jv_get_kind(args) == JV_KIND_OBJECT)
return args;
assert(jv_get_kind(args) == JV_KIND_ARRAY);
jv r = jv_object();
jv kk = jv_string("name");
jv vk = jv_string("value");
jv_array_foreach(args, i, v)
r = jv_object_set(r, jv_object_get(jv_copy(v), kk), jv_object_get(v, vk));
jv_free(args);
jv_free(kk);
jv_free(vk);
return r;
}
int jq_compile_args(jq_state *jq, const char* str, jv args) {
jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);
assert(jv_get_kind(args) == JV_KIND_ARRAY || jv_get_kind(args) == JV_KIND_OBJECT);
assert(jv_get_kind(args) == JV_KIND_ARRAY);
struct locfile* locations;
locations = locfile_init(jq, "<top-level>", str, strlen(str));
block program;
@@ -1162,22 +1079,29 @@ int jq_compile_args(jq_state *jq, const char* str, jv args) {
}
int nerrors = load_program(jq, locations, &program);
if (nerrors == 0) {
jv_array_foreach(args, i, arg) {
jv name = jv_object_get(jv_copy(arg), jv_string("name"));
jv value = jv_object_get(arg, jv_string("value"));
program = gen_var_binding(gen_const(value), jv_string_value(name), program);
jv_free(name);
}
nerrors = builtins_bind(jq, &program);
if (nerrors == 0) {
nerrors = block_compile(program, &jq->bc, locations, args = args2obj(args));
nerrors = block_compile(program, &jq->bc, locations);
}
} else
jv_free(args);
}
if (nerrors)
jq_report_error(jq, jv_string_fmt("jq: %d compile %s", nerrors, nerrors > 1 ? "errors" : "error"));
if (jq->bc)
jq->bc = optimize(jq->bc);
jv_free(args);
locfile_free(locations);
return jq->bc != NULL;
}
int jq_compile(jq_state *jq, const char* str) {
return jq_compile_args(jq, str, jv_object());
return jq_compile_args(jq, str, jv_array());
}
jv jq_get_jq_origin(jq_state *jq) {
@@ -1229,28 +1153,3 @@ void jq_get_debug_cb(jq_state *jq, jq_msg_cb *cb, void **data) {
*cb = jq->debug_cb;
*data = jq->debug_cb_data;
}
void
jq_halt(jq_state *jq, jv exit_code, jv error_message)
{
assert(!jq->halted);
jq->halted = 1;
jq->exit_code = exit_code;
jq->error_message = error_message;
}
int
jq_halted(jq_state *jq)
{
return jq->halted;
}
jv jq_get_exit_code(jq_state *jq)
{
return jv_copy(jq->exit_code);
}
jv jq_get_error_message(jq_state *jq)
{
return jv_copy(jq->error_message);
}
+1 -12
View File
@@ -4,11 +4,7 @@
#include <stdio.h>
#include "jv.h"
enum {
JQ_DEBUG_TRACE = 1,
JQ_DEBUG_TRACE_DETAIL = 2,
JQ_DEBUG_TRACE_ALL = JQ_DEBUG_TRACE | JQ_DEBUG_TRACE_DETAIL,
};
enum {JQ_DEBUG_TRACE = 1};
typedef struct jq_state jq_state;
typedef void (*jq_msg_cb)(void *, jv);
@@ -26,11 +22,6 @@ void jq_start(jq_state *, jv value, int);
jv jq_next(jq_state *);
void jq_teardown(jq_state **);
void jq_halt(jq_state *, jv, jv);
int jq_halted(jq_state *);
jv jq_get_exit_code(jq_state *);
jv jq_get_error_message(jq_state *);
typedef jv (*jq_input_cb)(jq_state *, void *);
void jq_set_input_cb(jq_state *, jq_input_cb, void *);
void jq_get_input_cb(jq_state *, jq_input_cb *, void **);
@@ -66,6 +57,4 @@ jv jq_util_input_get_position(jq_state*);
jv jq_util_input_get_current_filename(jq_state*);
jv jq_util_input_get_current_line(jq_state*);
int jq_set_colors(const char *);
#endif /* !JQ_H */
+4 -22
View File
@@ -296,18 +296,10 @@ static jv jvp_array_slice(jv a, int start, int end) {
jv_free(a);
return jv_array();
}
if (a.offset + start >= 1 << (sizeof(a.offset) * CHAR_BIT)) {
jv r = jv_array_sized(end - start);
for (int i = start; i < end; i++)
r = jv_array_append(r, jv_array_get(jv_copy(a), i));
jv_free(a);
return r;
} else {
a.offset += start;
a.size = end - start;
return a;
}
// FIXME FIXME FIXME large offsets
a.offset += start;
a.size = end - start;
return a;
}
/*
@@ -1114,16 +1106,6 @@ jv jv_object_get(jv object, jv key) {
return val;
}
int jv_object_has(jv object, jv key) {
assert(jv_get_kind(object) == JV_KIND_OBJECT);
assert(jv_get_kind(key) == JV_KIND_STRING);
jv* slot = jvp_object_read(object, key);
int res = slot ? 1 : 0;
jv_free(object);
jv_free(key);
return res;
}
jv jv_object_set(jv object, jv key, jv value) {
assert(jv_get_kind(object) == JV_KIND_OBJECT);
assert(jv_get_kind(key) == JV_KIND_STRING);
+7 -14
View File
@@ -99,6 +99,9 @@ jv jv_array_indexes(jv, jv);
__attribute__ ((__format__( __printf__, fmt_arg_num, args_num)))
#define JV_VPRINTF_LIKE(fmt_arg_num) \
__attribute__ ((__format__( __printf__, fmt_arg_num, 0)))
#else
#define JV_PRINTF_LIKE(fmt_arg_num, args_num)
#define JV_VPRINTF_LIKE(fmt_arg_num)
#endif
@@ -112,8 +115,8 @@ const char* jv_string_value(jv);
jv jv_string_indexes(jv j, jv k);
jv jv_string_slice(jv j, int start, int end);
jv jv_string_concat(jv, jv);
jv jv_string_vfmt(const char*, va_list) JV_VPRINTF_LIKE(1);
jv jv_string_fmt(const char*, ...) JV_PRINTF_LIKE(1, 2);
jv jv_string_vfmt(const char* fmt, va_list ap) JV_VPRINTF_LIKE(1);
jv jv_string_fmt(const char* fmt, ...) JV_PRINTF_LIKE(1, 2);
jv jv_string_append_codepoint(jv a, uint32_t c);
jv jv_string_append_buf(jv a, const char* buf, int len);
jv jv_string_append_str(jv a, const char* str);
@@ -123,7 +126,6 @@ jv jv_string_implode(jv j);
jv jv_object(void);
jv jv_object_get(jv object, jv key);
int jv_object_has(jv object, jv key);
jv jv_object_set(jv object, jv key, jv value);
jv jv_object_delete(jv object, jv key);
int jv_object_length(jv object);
@@ -145,15 +147,6 @@ jv jv_object_iter_value(jv, int);
: 0; \
jv_i__ = jv_object_iter_next(t, jv_i__)) \
#define jv_object_keys_foreach(t, k) \
for (int jv_i__ = jv_object_iter(t), jv_j__ = 1; jv_j__; jv_j__ = 0) \
for (jv k; \
jv_object_iter_valid((t), jv_i__) ? \
(k = jv_object_iter_key(t, jv_i__), \
1) \
: 0; \
jv_i__ = jv_object_iter_next(t, jv_i__))
#define JV_OBJECT_1(k1) (jv_object_set(jv_object(),(k1),jv_null()))
#define JV_OBJECT_2(k1,v1) (jv_object_set(jv_object(),(k1),(v1)))
#define JV_OBJECT_3(k1,v1,k2) (jv_object_set(JV_OBJECT_2((k1),(v1)),(k2),jv_null()))
@@ -195,10 +188,10 @@ jv jv_object_iter_value(jv, int);
int jv_get_refcnt(jv);
enum jv_print_flags {
enum {
JV_PRINT_PRETTY = 1,
JV_PRINT_ASCII = 2,
JV_PRINT_COLOR = 4, JV_PRINT_COLOUR = 4,
JV_PRINT_COLOR = 4,
JV_PRINT_SORTED = 8,
JV_PRINT_INVALID = 16,
JV_PRINT_REFCOUNT = 32,
+2 -2
View File
@@ -465,7 +465,7 @@ jv jv_keys_unsorted(jv x) {
jv jv_keys(jv x) {
if (jv_get_kind(x) == JV_KIND_OBJECT) {
int nkeys = jv_object_length(jv_copy(x));
jv* keys = jv_mem_calloc(sizeof(jv), nkeys);
jv* keys = jv_mem_alloc(sizeof(jv) * nkeys);
int kidx = 0;
jv_object_foreach(x, key, value) {
keys[kidx++] = key;
@@ -587,7 +587,7 @@ static struct sort_entry* sort_items(jv objects, jv keys) {
assert(jv_get_kind(keys) == JV_KIND_ARRAY);
assert(jv_array_length(jv_copy(objects)) == jv_array_length(jv_copy(keys)));
int n = jv_array_length(jv_copy(objects));
struct sort_entry* entries = jv_mem_calloc(sizeof(struct sort_entry), n);
struct sort_entry* entries = jv_mem_alloc(sizeof(struct sort_entry) * n);
for (int i=0; i<n; i++) {
entries[i].object = jv_array_get(jv_copy(objects), i);
entries[i].key = jv_array_get(jv_copy(keys), i);
+6 -25
View File
@@ -1,33 +1,16 @@
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "jv.h"
#include "jv_unicode.h"
jv jv_load_file(const char* filename, int raw) {
struct stat sb;
int fd = open(filename, O_RDONLY);
if (fd == -1) {
return jv_invalid_with_msg(jv_string_fmt("Could not open %s: %s",
filename,
strerror(errno)));
}
if (fstat(fd, &sb) == -1 || S_ISDIR(sb.st_mode)) {
close(fd);
return jv_invalid_with_msg(jv_string_fmt("Could not open %s: %s",
filename,
"It's a directory"));
}
FILE* file = fdopen(fd, "r");
struct jv_parser* parser = NULL;
FILE* file = fopen(filename, "r");
struct jv_parser* parser;
jv data;
if (!file) {
close(fd);
return jv_invalid_with_msg(jv_string_fmt("Could not open %s: %s",
filename,
strerror(errno)));
@@ -47,12 +30,10 @@ jv jv_load_file(const char* filename, int raw) {
while (!feof(file) && !ferror(file)) {
size_t n = fread(buf, 1, sizeof(buf)-max_utf8_len, file);
int len = 0;
if (n == 0)
continue;
if (jvp_utf8_backtrack(buf+(n-1), buf, &len) && len > 0 &&
!feof(file) && !ferror(file)) {
n += fread(buf+n, 1, len, file);
if (jvp_utf8_backtrack(buf+(n-1), buf, &len) && len > 0) {
if (!feof(file) && !ferror(file)) {
n += fread(buf+n, 1, len, file);
}
}
if (raw) {
+4 -51
View File
@@ -12,7 +12,6 @@
#include "jv.h"
#include "jv_dtoa.h"
#include "jv_unicode.h"
#include "jv_alloc.h"
#ifndef MAX_PRINT_DEPTH
#define MAX_PRINT_DEPTH (256)
@@ -27,66 +26,20 @@
static const jv_kind color_kinds[] =
{JV_KIND_NULL, JV_KIND_FALSE, JV_KIND_TRUE, JV_KIND_NUMBER,
JV_KIND_STRING, JV_KIND_ARRAY, JV_KIND_OBJECT};
static char color_bufs[sizeof(color_kinds)/sizeof(color_kinds[0])][16];
static const char *color_bufps[8];
static const char* def_colors[] =
static const char* const colors[] =
{COL("1;30"), COL("0;39"), COL("0;39"), COL("0;39"),
COL("0;32"), COL("1;39"), COL("1;39")};
#define FIELD_COLOR COL("34;1")
static const char **colors = def_colors;
int
jq_set_colors(const char *c)
{
const char *e;
size_t i;
if (c == NULL)
return 1;
colors = def_colors;
memset(color_bufs, 0, sizeof(color_bufs));
for (i = 0; i < sizeof(def_colors) / sizeof(def_colors[0]); i++)
color_bufps[i] = def_colors[i];
for (i = 0; i < sizeof(def_colors) / sizeof(def_colors[0]) && *c != '\0'; i++, c = e) {
if ((e = strchr(c, ':')) == NULL)
e = c + strlen(c);
if ((size_t)(e - c) > sizeof(color_bufs[i]) - 4 /* ESC [ m NUL */)
return 0;
color_bufs[i][0] = ESC[0];
color_bufs[i][1] = '[';
(void) strncpy(&color_bufs[i][2], c, e - c);
if (strspn(&color_bufs[i][2], "0123456789;") < strlen(&color_bufs[i][2]))
return 0;
color_bufs[i][2 + (e - c)] = 'm';
color_bufps[i] = color_bufs[i];
if (e[0] == ':')
e++;
}
colors = color_bufps;
return 1;
}
static void put_buf(const char *s, int len, FILE *fout, jv *strout, int is_tty) {
if (strout) {
*strout = jv_string_append_buf(*strout, s, len);
} else {
#ifdef WIN32
/* See util.h */
if (is_tty) {
wchar_t *ws;
size_t wl;
if (len == -1)
len = strlen(s);
wl = MultiByteToWideChar(CP_UTF8, 0, s, len, NULL, 0);
ws = jv_mem_calloc((wl + 1), sizeof(*ws));
if (!ws)
return;
wl = MultiByteToWideChar(CP_UTF8, 0, s, len, ws, wl + 1);
ws[wl] = 0;
WriteConsoleW((HANDLE)_get_osfhandle(fileno(fout)), ws, wl, NULL, NULL);
free(ws);
} else
if (is_tty)
WriteFile((HANDLE)_get_osfhandle(fileno(fout)), s, len, NULL, NULL);
else
fwrite(s, 1, len, fout);
#else
fwrite(s, 1, len, fout);
+1 -1
View File
@@ -9,7 +9,7 @@
// *missing_bytes. If there are no leading bytes or an invalid byte is
// encountered, NULL is returned and *missing_bytes is not altered.
const char* jvp_utf8_backtrack(const char* start, const char* min, int *missing_bytes) {
assert(min <= start);
assert(min < start);
if (min == start) {
return min;
}
+282 -307
View File
File diff suppressed because it is too large. Load diff
+12 -16
View File
@@ -2,9 +2,9 @@
#define jq_yyHEADER_H 1
#define jq_yyIN_HEADER 1
#line 6 "src/lexer.h"
#line 6 "lexer.h"
#line 8 "src/lexer.h"
#line 8 "lexer.h"
#define YY_INT_ALIGNED short int
@@ -12,8 +12,8 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
#define YY_FLEX_SUBMINOR_VERSION 0
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
@@ -214,7 +214,7 @@ void jq_yypop_buffer_state (yyscan_t yyscanner );
YY_BUFFER_STATE jq_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
YY_BUFFER_STATE jq_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
YY_BUFFER_STATE jq_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner );
YY_BUFFER_STATE jq_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
void *jq_yyalloc (yy_size_t ,yyscan_t yyscanner );
void *jq_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
@@ -222,7 +222,7 @@ void jq_yyfree (void * ,yyscan_t yyscanner );
/* Begin user sect3 */
#define jq_yywrap(yyscanner) (/*CONSTCOND*/1)
#define jq_yywrap(n) 1
#define YY_SKIP_YYWRAP
#define yytext_ptr yytext_r
@@ -266,23 +266,19 @@ void jq_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
FILE *jq_yyget_in (yyscan_t yyscanner );
void jq_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
void jq_yyset_in (FILE * in_str ,yyscan_t yyscanner );
FILE *jq_yyget_out (yyscan_t yyscanner );
void jq_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
void jq_yyset_out (FILE * out_str ,yyscan_t yyscanner );
yy_size_t jq_yyget_leng (yyscan_t yyscanner );
int jq_yyget_leng (yyscan_t yyscanner );
char *jq_yyget_text (yyscan_t yyscanner );
int jq_yyget_lineno (yyscan_t yyscanner );
void jq_yyset_lineno (int _line_number ,yyscan_t yyscanner );
int jq_yyget_column (yyscan_t yyscanner );
void jq_yyset_column (int _column_no ,yyscan_t yyscanner );
void jq_yyset_lineno (int line_number ,yyscan_t yyscanner );
YYSTYPE * jq_yyget_lval (yyscan_t yyscanner );
@@ -358,9 +354,9 @@ extern int jq_yylex \
#undef YY_DECL
#endif
#line 130 "src/lexer.l"
#line 129 "lexer.l"
#line 365 "src/lexer.h"
#line 361 "lexer.h"
#undef jq_yyIN_HEADER
#endif /* jq_yyHEADER_H */
-1
View File
@@ -71,7 +71,6 @@ struct lexer_param;
"<=" { return LESSEQ; }
">=" { return GREATEREQ; }
".." { return REC; }
"?//" { return ALTERNATION; }
"."|"?"|"="|";"|","|":"|"|"|"+"|"-"|"*"|"/"|"%"|"\$"|"<"|">" { return yytext[0];}
"["|"{"|"(" {
+16 -6
View File
@@ -144,10 +144,10 @@ LIBM_DD(y1)
LIBM_DD_NO(y1)
#endif
#ifdef HAVE_JN
LIBM_DDD(jn)
LIBM_DID(jn)
#endif
#ifdef HAVE_YN
LIBM_DDD(yn)
LIBM_DID(yn)
#endif
#ifdef HAVE_CEIL
LIBM_DD(ceil)
@@ -159,7 +159,7 @@ LIBM_DDD(copysign)
#else
LIBM_DDD_NO(copysign)
#endif
#if defined(HAVE_DREM) && !defined(WIN32)
#ifdef HAVE_DREM
LIBM_DDD(drem)
#else
LIBM_DDD_NO(drem)
@@ -174,7 +174,7 @@ LIBM_DD(erfc)
#else
LIBM_DD_NO(erfc)
#endif
#if defined(HAVE_EXP10) && !defined(WIN32)
#ifdef HAVE_EXP10
LIBM_DD(exp10)
#else
LIBM_DD_NO(exp10)
@@ -214,6 +214,11 @@ LIBM_DDD(fmod)
#else
LIBM_DDD_NO(fmod)
#endif
#ifdef HAVE_FREXP
LIBM_DDD(frexp)
#else
LIBM_DDD_NO(frexp)
#endif
#ifdef HAVE_GAMMA
LIBM_DD(gamma)
#else
@@ -234,6 +239,11 @@ LIBM_DD(logb)
#else
LIBM_DD_NO(logb)
#endif
#ifdef HAVE_MODF
LIBM_DDD(modf)
#else
LIBM_DDD_NO(modf)
#endif
#ifdef HAVE_NEARBYINT
LIBM_DD(nearbyint)
#else
@@ -249,7 +259,7 @@ LIBM_DDD(nexttoward)
#else
LIBM_DDD_NO(nexttoward)
#endif
#if defined(HAVE_POW10) && !defined(WIN32)
#ifdef HAVE_POW10
LIBM_DD(pow10)
#else
LIBM_DD_NO(pow10)
@@ -274,7 +284,7 @@ LIBM_DDD(scalbln)
#else
LIBM_DDD_NO(scalbln)
#endif
#if defined(HAVE_SIGNIFICAND) && !defined(WIN32)
#ifdef HAVE_SIGNIFICAND
LIBM_DD(significand)
#else
LIBM_DD_NO(significand)
+2 -5
View File
@@ -19,7 +19,6 @@
#include "parser.h"
#include "util.h"
#include "compile.h"
#include "jv_alloc.h"
struct lib_loading_state {
char **names;
@@ -279,8 +278,6 @@ static int process_dependencies(jq_state *jq, jv jq_origin, jv lib_origin, block
if (nerrors == 0) {
// Bind the library to the program
bk = block_bind_library(dep_def_block, bk, OP_IS_CALL_PSEUDO, as_str);
if (is_data)
bk = block_bind_library(dep_def_block, bk, OP_IS_CALL_PSEUDO, NULL);
}
}
jv_free(as);
@@ -327,8 +324,8 @@ static int load_library(jq_state *jq, jv lib_path, int is_data, int raw, const c
}
}
state_idx = lib_state->ct++;
lib_state->names = jv_mem_realloc(lib_state->names, lib_state->ct * sizeof(const char *));
lib_state->defs = jv_mem_realloc(lib_state->defs, lib_state->ct * sizeof(block));
lib_state->names = realloc(lib_state->names, lib_state->ct * sizeof(const char *));
lib_state->defs = realloc(lib_state->defs, lib_state->ct * sizeof(block));
lib_state->names[state_idx] = strdup(jv_string_value(lib_path));
lib_state->defs[state_idx] = program;
*out_block = program;
+1 -1
View File
@@ -21,7 +21,7 @@ struct locfile* locfile_init(jq_state *jq, const char *fname, const char* data,
for (int i=0; i<length; i++) {
if (data[i] == '\n') l->nlines++;
}
l->linemap = jv_mem_calloc(sizeof(int), (l->nlines + 1));
l->linemap = jv_mem_alloc(sizeof(int) * (l->nlines + 1));
l->linemap[0] = 0;
int line = 1;
for (int i=0; i<length; i++) {
+74 -154
View File
@@ -41,7 +41,7 @@ static const char* progname;
* For a longer help message we could use a better option parsing
* strategy, one that lets stack options.
*/
static void usage(int code, int keep_it_short) {
static void usage(int code) {
FILE *f = stderr;
if (code == 0)
@@ -49,9 +49,7 @@ static void usage(int code, int keep_it_short) {
int ret = fprintf(f,
"jq - commandline JSON processor [version %s]\n"
"\nUsage:\t%s [options] <jq filter> [file...]\n"
"\t%s [options] --args <jq filter> [strings...]\n"
"\t%s [options] --jsonargs <jq filter> [JSON_TEXTS...]\n\n"
"\nUsage:\n\n\t%s [options] <jq filter> [file...]\n\n"
"jq is a tool for processing JSON inputs, applying the given filter to\n"
"its JSON text inputs and producing the filter's results as JSON on\n"
"standard output.\n\n"
@@ -61,36 +59,22 @@ static void usage(int code, int keep_it_short) {
"For more advanced filters see the jq(1) manpage (\"man jq\")\n"
"and/or https://stedolan.github.io/jq\n\n"
"Example:\n\n\t$ echo '{\"foo\": 0}' | jq .\n"
"\t{\n\t\t\"foo\": 0\n\t}\n\n",
JQ_VERSION, progname, progname, progname);
if (keep_it_short) {
fprintf(f,
"For a listing of options, use %s --help.\n",
progname);
} else {
(void) fprintf(f,
"Some of the options include:\n"
" -c compact instead of pretty-printed output;\n"
" -n use `null` as the single input value;\n"
" -e set the exit status code based on the output;\n"
" -s read (slurp) all inputs into an array; apply filter to it;\n"
" -r output raw strings, not JSON texts;\n"
" -R read raw strings, not JSON texts;\n"
" -C colorize JSON;\n"
" -M monochrome (don't colorize JSON);\n"
" -S sort keys of objects on output;\n"
" --tab use tabs for indentation;\n"
" --arg a v set variable $a to value <v>;\n"
" --argjson a v set variable $a to JSON value <v>;\n"
" --slurpfile a f set variable $a to an array of JSON texts read from <f>;\n"
" --rawfile a f set variable $a to a string consisting of the contents of <f>;\n"
" --args remaining arguments are string arguments, not files;\n"
" --jsonargs remaining arguments are JSON arguments, not files;\n"
" -- terminates argument processing;\n\n"
"Named arguments are also available as $ARGS.named[], while\n"
"positional arguments are available as $ARGS.positional[].\n"
"\nSee the manpage for more options.\n");
}
"\t{\n\t\t\"foo\": 0\n\t}\n\n"
"Some of the options include:\n"
" -c compact instead of pretty-printed output;\n"
" -n use `null` as the single input value;\n"
" -e set the exit status code based on the output;\n"
" -s read (slurp) all inputs into an array; apply filter to it;\n"
" -r output raw strings, not JSON texts;\n"
" -R read raw strings, not JSON texts;\n"
" -C colorize JSON;\n"
" -M monochrome (don't colorize JSON);\n"
" -S sort keys of objects on output;\n"
" --tab use tabs for indentation;\n"
" --arg a v set variable $a to value <v>;\n"
" --argjson a v set variable $a to JSON value <v>;\n"
" --slurpfile a f set variable $a to an array of JSON texts read from <f>;\n"
"\nSee the manpage for more options.\n", JQ_VERSION, progname);
exit((ret < 0 && code == 0) ? 2 : code);
}
@@ -138,11 +122,10 @@ enum {
RAW_NO_LF = 1024,
UNBUFFERED_OUTPUT = 2048,
EXIT_STATUS = 4096,
EXIT_STATUS_EXACT = 8192,
SEQ = 16384,
RUN_TESTS = 32768,
SEQ = 8192,
RUN_TESTS = 16384,
/* debugging only */
DUMP_DISASM = 65536,
DUMP_DISASM = 32768,
};
static int options = 0;
@@ -167,11 +150,7 @@ static int process(jq_state *jq, jv value, int flags, int dumpopts) {
jv result;
while (jv_is_valid(result = jq_next(jq))) {
if ((options & RAW_OUTPUT) && jv_get_kind(result) == JV_KIND_STRING) {
if (options & ASCII_OUTPUT) {
jv_dumpf(result, stdout, JV_PRINT_ASCII);
} else {
fwrite(jv_string_value(result), 1, jv_string_length_bytes(jv_copy(result)), stdout);
}
fwrite(jv_string_value(result), 1, jv_string_length_bytes(jv_copy(result)), stdout);
ret = 0;
jv_free(result);
} else {
@@ -188,29 +167,7 @@ static int process(jq_state *jq, jv value, int flags, int dumpopts) {
if (options & UNBUFFERED_OUTPUT)
fflush(stdout);
}
if (jq_halted(jq)) {
// jq program invoked `halt` or `halt_error`
options |= EXIT_STATUS_EXACT;
jv exit_code = jq_get_exit_code(jq);
if (!jv_is_valid(exit_code))
ret = 0;
else if (jv_get_kind(exit_code) == JV_KIND_NUMBER)
ret = jv_number_value(exit_code);
else
ret = 5;
jv_free(exit_code);
jv error_message = jq_get_error_message(jq);
if (jv_get_kind(error_message) == JV_KIND_STRING) {
fprintf(stderr, "%s", jv_string_value(error_message));
} else if (jv_get_kind(error_message) == JV_KIND_NULL) {
// Halt with no output
} else if (jv_is_valid(error_message)) {
error_message = jv_dump_string(jv_copy(error_message), 0);
fprintf(stderr, "%s\n", jv_string_value(error_message));
} // else no message on stderr; use --debug-trace to see a message
fflush(stderr);
jv_free(error_message);
} else if (jv_invalid_has_msg(jv_copy(result))) {
if (jv_invalid_has_msg(jv_copy(result))) {
// Uncaught jq exception
jv msg = jv_invalid_get_msg(jv_copy(result));
jv input_pos = jq_util_input_get_position(jq);
@@ -243,10 +200,10 @@ int main(int argc, char* argv[]) {
int parser_flags = 0;
int nfiles = 0;
int badwrite;
jv ARGS = jv_array(); /* positional arguments */
jv program_arguments = jv_object(); /* named arguments */
jv program_arguments = jv_array();
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
fflush(stdout);
fflush(stderr);
_setmode(fileno(stdout), _O_TEXT | _O_U8TEXT);
@@ -278,35 +235,21 @@ int main(int argc, char* argv[]) {
jq_util_input_state *input_state = jq_util_input_init(NULL, NULL); // XXX add err_cb
int further_args_are_strings = 0;
int further_args_are_json = 0;
int args_done = 0;
int further_args_are_files = 0;
int jq_flags = 0;
size_t short_opts = 0;
jv lib_search_paths = jv_null();
for (int i=1; i<argc; i++, short_opts = 0) {
if (args_done) {
if (further_args_are_strings) {
ARGS = jv_array_append(ARGS, jv_string(argv[i]));
} else if (further_args_are_json) {
ARGS = jv_array_append(ARGS, jv_parse(argv[i]));
} else {
jq_util_input_add_input(input_state, argv[i]);
nfiles++;
}
if (further_args_are_files) {
jq_util_input_add_input(input_state, argv[i]);
nfiles++;
} else if (!strcmp(argv[i], "--")) {
if (!program) usage(2, 1);
args_done = 1;
if (!program) usage(2);
further_args_are_files = 1;
} else if (!isoptish(argv[i])) {
if (program) {
if (further_args_are_strings) {
ARGS = jv_array_append(ARGS, jv_string(argv[i]));
} else if (further_args_are_json) {
ARGS = jv_array_append(ARGS, jv_parse(argv[i]));
} else {
jq_util_input_add_input(input_state, argv[i]);
nfiles++;
}
jq_util_input_add_input(input_state, argv[i]);
nfiles++;
} else {
program = argv[i];
}
@@ -352,7 +295,7 @@ int main(int argc, char* argv[]) {
}
if (isoption(argv[i], 0, "unbuffered", &short_opts)) {
options |= UNBUFFERED_OUTPUT;
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 'S', "sort-keys", &short_opts)) {
options |= SORTED_OUTPUT;
@@ -377,7 +320,7 @@ int main(int argc, char* argv[]) {
if (isoption(argv[i], 0, "tab", &short_opts)) {
dumpopts &= ~JV_PRINT_INDENT_FLAGS(7);
dumpopts |= JV_PRINT_TAB | JV_PRINT_PRETTY;
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 0, "indent", &short_opts)) {
if (i >= argc - 1) {
@@ -392,108 +335,95 @@ int main(int argc, char* argv[]) {
}
dumpopts |= JV_PRINT_INDENT_FLAGS(indent);
i++;
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 0, "seq", &short_opts)) {
options |= SEQ;
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 0, "stream", &short_opts)) {
parser_flags |= JV_PARSE_STREAMING;
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 0, "stream-errors", &short_opts)) {
parser_flags |= JV_PARSE_STREAM_ERRORS;
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 'e', "exit-status", &short_opts)) {
options |= EXIT_STATUS;
if (!short_opts) continue;
}
// FIXME: For --arg* we should check that the varname is acceptable
if (isoption(argv[i], 0, "args", &short_opts)) {
further_args_are_strings = 1;
further_args_are_json = 0;
continue;
}
if (isoption(argv[i], 0, "jsonargs", &short_opts)) {
further_args_are_strings = 0;
further_args_are_json = 1;
continue;
}
if (isoption(argv[i], 0, "arg", &short_opts)) {
if (i >= argc - 2) {
fprintf(stderr, "%s: --arg takes two parameters (e.g. --arg varname value)\n", progname);
die();
}
if (!jv_object_has(jv_copy(program_arguments), jv_string(argv[i+1])))
program_arguments = jv_object_set(program_arguments, jv_string(argv[i+1]), jv_string(argv[i+2]));
jv arg = jv_object();
arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
arg = jv_object_set(arg, jv_string("value"), jv_string(argv[i+2]));
program_arguments = jv_array_append(program_arguments, arg);
i += 2; // skip the next two arguments
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 0, "argjson", &short_opts)) {
if (i >= argc - 2) {
fprintf(stderr, "%s: --argjson takes two parameters (e.g. --argjson varname text)\n", progname);
die();
}
if (!jv_object_has(jv_copy(program_arguments), jv_string(argv[i+1]))) {
jv v = jv_parse(argv[i+2]);
if (!jv_is_valid(v)) {
fprintf(stderr, "%s: invalid JSON text passed to --argjson\n", progname);
die();
}
program_arguments = jv_object_set(program_arguments, jv_string(argv[i+1]), v);
jv v = jv_parse(argv[i+2]);
if (!jv_is_valid(v)) {
fprintf(stderr, "%s: invalid JSON text passed to --argjson\n", progname);
die();
}
jv arg = jv_object();
arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
arg = jv_object_set(arg, jv_string("value"), v);
program_arguments = jv_array_append(program_arguments, arg);
i += 2; // skip the next two arguments
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 0, "argfile", &short_opts) ||
isoption(argv[i], 0, "rawfile", &short_opts) ||
isoption(argv[i], 0, "slurpfile", &short_opts)) {
int raw = isoption(argv[i], 0, "rawfile", &short_opts);
const char *which;
if (isoption(argv[i], 0, "argfile", &short_opts))
which = "argfile";
else if (raw)
which = "rawfile";
else
which = "slurpfile";
if (i >= argc - 2) {
fprintf(stderr, "%s: --%s takes two parameters (e.g. --%s varname filename)\n", progname, which, which);
die();
}
if (!jv_object_has(jv_copy(program_arguments), jv_string(argv[i+1]))) {
jv data = jv_load_file(argv[i+2], raw);
if (!jv_is_valid(data)) {
data = jv_invalid_get_msg(data);
fprintf(stderr, "%s: Bad JSON in --%s %s %s: %s\n", progname, which,
argv[i+1], argv[i+2], jv_string_value(data));
jv_free(data);
ret = 2;
goto out;
}
if (strcmp(which, "argfile") == 0 &&
jv_get_kind(data) == JV_KIND_ARRAY && jv_array_length(jv_copy(data)) == 1)
data = jv_array_get(data, 0);
program_arguments = jv_object_set(program_arguments, jv_string(argv[i+1]), data);
jv arg = jv_object();
arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1]));
jv data = jv_load_file(argv[i+2], 0);
if (!jv_is_valid(data)) {
data = jv_invalid_get_msg(data);
fprintf(stderr, "%s: Bad JSON in --%s %s %s: %s\n", progname, which,
argv[i+1], argv[i+2], jv_string_value(data));
jv_free(data);
jv_free(arg);
ret = 2;
goto out;
}
if (isoption(argv[i], 0, "argfile", &short_opts) &&
jv_get_kind(data) == JV_KIND_ARRAY && jv_array_length(jv_copy(data)) == 1)
data = jv_array_get(data, 0);
arg = jv_object_set(arg, jv_string("value"), data);
program_arguments = jv_array_append(program_arguments, arg);
i += 2; // skip the next two arguments
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 0, "debug-dump-disasm", &short_opts)) {
options |= DUMP_DISASM;
continue;
}
if (isoption(argv[i], 0, "debug-trace=all", &short_opts)) {
jq_flags |= JQ_DEBUG_TRACE_ALL;
if (!short_opts) continue;
}
if (isoption(argv[i], 0, "debug-trace", &short_opts)) {
jq_flags |= JQ_DEBUG_TRACE;
continue;
if (!short_opts) continue;
}
if (isoption(argv[i], 'h', "help", &short_opts)) {
usage(0, 0);
usage(0);
if (!short_opts) continue;
}
if (isoption(argv[i], 'V', "version", &short_opts)) {
@@ -534,9 +464,6 @@ int main(int argc, char* argv[]) {
if (options & COLOR_OUTPUT) dumpopts |= JV_PRINT_COLOR;
if (options & NO_COLOR_OUTPUT) dumpopts &= ~JV_PRINT_COLOR;
if (getenv("JQ_COLORS") != NULL && !jq_set_colors(getenv("JQ_COLORS")))
fprintf(stderr, "Failed to set $JQ_COLORS\n");
if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) {
// Default search path list
lib_search_paths = JV_ARRAY(jv_string("~/.jq"),
@@ -563,7 +490,7 @@ int main(int argc, char* argv[]) {
program = ".";
#endif
if (!program) usage(2, 1);
if (!program) usage(2);
if (options & FROM_FILE) {
char *program_origin = strdup(program);
@@ -581,17 +508,11 @@ int main(int argc, char* argv[]) {
goto out;
}
jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string(dirname(program_origin))));
ARGS = JV_OBJECT(jv_string("positional"), ARGS,
jv_string("named"), jv_copy(program_arguments));
program_arguments = jv_object_set(program_arguments, jv_string("ARGS"), jv_copy(ARGS));
compiled = jq_compile_args(jq, skip_shebang(jv_string_value(data)), jv_copy(program_arguments));
free(program_origin);
jv_free(data);
} else {
jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string("."))); // XXX is this good?
ARGS = JV_OBJECT(jv_string("positional"), ARGS,
jv_string("named"), jv_copy(program_arguments));
program_arguments = jv_object_set(program_arguments, jv_string("ARGS"), jv_copy(ARGS));
compiled = jq_compile_args(jq, program, jv_copy(program_arguments));
}
if (!compiled){
@@ -656,13 +577,12 @@ out:
ret = 2;
}
jv_free(ARGS);
jv_free(program_arguments);
jq_util_input_free(&input_state);
jq_teardown(&jq);
if (ret >= 10 && (options & EXIT_STATUS))
return ret - 10;
if (ret >= 10 && !(options & EXIT_STATUS_EXACT))
if (ret >= 10)
return 0;
return ret;
}
-4
View File
@@ -2,7 +2,6 @@ OP(LOADK, CONSTANT, 1, 1)
OP(DUP, NONE, 1, 2)
OP(DUPN, NONE, 1, 2)
OP(DUP2, NONE, 2, 3)
OP(PUSHK_UNDER, CONSTANT, 1, 2)
OP(POP, NONE, 1, 0)
OP(LOADV, VARIABLE, 1, 1)
OP(LOADVN, VARIABLE, 1, 1)
@@ -43,6 +42,3 @@ OP(CLOSURE_PARAM_REGULAR, DEFINITION, 0, 0)
OP(DEPS, CONSTANT, 0, 0)
OP(MODULEMETA, CONSTANT, 0, 0)
OP(GENLABEL, NONE, 0, 1)
OP(DESTRUCTURE_ALT, BRANCH, 0, 0)
OP(STOREVN, VARIABLE, 1, 0)
+979 -1058
View File
File diff suppressed because it is too large. Load diff
+18 -22
View File
@@ -1,8 +1,8 @@
/* A Bison parser, made by GNU Bison 3.0.4. */
/* A Bison parser, made by GNU Bison 3.0.2. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -101,14 +101,13 @@ struct lexer_param;
SETDEFINEDOR = 292,
LESSEQ = 293,
GREATEREQ = 294,
ALTERNATION = 295,
QQSTRING_START = 296,
QQSTRING_TEXT = 297,
QQSTRING_INTERP_START = 298,
QQSTRING_INTERP_END = 299,
QQSTRING_END = 300,
FUNCDEF = 301,
NONOPT = 302
QQSTRING_START = 295,
QQSTRING_TEXT = 296,
QQSTRING_INTERP_START = 297,
QQSTRING_INTERP_END = 298,
QQSTRING_END = 299,
FUNCDEF = 300,
NONOPT = 301
};
#endif
/* Tokens. */
@@ -149,18 +148,17 @@ struct lexer_param;
#define SETDEFINEDOR 292
#define LESSEQ 293
#define GREATEREQ 294
#define ALTERNATION 295
#define QQSTRING_START 296
#define QQSTRING_TEXT 297
#define QQSTRING_INTERP_START 298
#define QQSTRING_INTERP_END 299
#define QQSTRING_END 300
#define FUNCDEF 301
#define NONOPT 302
#define QQSTRING_START 295
#define QQSTRING_TEXT 296
#define QQSTRING_INTERP_START 297
#define QQSTRING_INTERP_END 298
#define QQSTRING_END 299
#define FUNCDEF 300
#define NONOPT 301
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE YYSTYPE;
union YYSTYPE
{
#line 31 "src/parser.y" /* yacc.c:1909 */
@@ -168,10 +166,8 @@ union YYSTYPE
jv literal;
block blk;
#line 172 "src/parser.h" /* yacc.c:1909 */
#line 170 "src/parser.h" /* yacc.c:1909 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
+10 -25
View File
@@ -83,7 +83,6 @@ struct lexer_param;
%token SETDEFINEDOR "//="
%token LESSEQ "<="
%token GREATEREQ ">="
%token ALTERNATION "?//"
%token QQSTRING_START
%token <literal> QQSTRING_TEXT
@@ -119,7 +118,7 @@ struct lexer_param;
%type <blk> FuncDef FuncDefs
%type <blk> Module Import Imports ImportWhat ImportFrom
%type <blk> Param Params Arg Args
%type <blk> Patterns RepPatterns Pattern ArrayPats ObjPats ObjPat
%type <blk> Pattern ArrayPats ObjPats ObjPat
%type <literal> Keyword
%{
#include "lexer.h"
@@ -177,6 +176,10 @@ static jv check_object_key(block k) {
return jv_invalid();
}
static block gen_dictpair(block k, block v) {
return BLOCK(gen_subexp(k), gen_subexp(v), gen_op_simple(INSERT));
}
static block gen_index(block obj, block key) {
return BLOCK(gen_subexp(key), obj, gen_op_simple(INDEX));
}
@@ -339,18 +342,19 @@ FuncDef Exp %prec FUNCDEF {
$$ = block_bind_referenced($1, $2, OP_IS_CALL_PSEUDO);
} |
Term "as" Patterns '|' Exp {
Term "as" Pattern '|' Exp {
$$ = gen_destructure($1, $3, $5);
} |
"reduce" Term "as" Patterns '(' Exp ';' Exp ')' {
"reduce" Term "as" Pattern '(' Exp ';' Exp ')' {
$$ = gen_reduce($2, $4, $6, $8);
} |
"foreach" Term "as" Patterns '(' Exp ';' Exp ';' Exp ')' {
"foreach" Term "as" Pattern '(' Exp ';' Exp ';' Exp ')' {
$$ = gen_foreach($2, $4, $6, $8, $10);
} |
"foreach" Term "as" Patterns '(' Exp ';' Exp ')' {
"foreach" Term "as" Pattern '(' Exp ';' Exp ')' {
$$ = gen_foreach($2, $4, $6, $8, gen_noop());
} |
@@ -774,22 +778,6 @@ Exp {
$$ = gen_lambda($1);
}
RepPatterns:
RepPatterns "?//" Pattern {
$$ = BLOCK($1, gen_destructure_alt($3));
} |
Pattern {
$$ = gen_destructure_alt($1);
}
Patterns:
RepPatterns "?//" Pattern {
$$ = BLOCK($1, $3);
} |
Pattern {
$$ = $1;
}
Pattern:
'$' IDENT {
$$ = gen_op_unbound(STOREV, jv_string_value($2));
@@ -822,9 +810,6 @@ ObjPat:
'$' IDENT {
$$ = gen_object_matcher(gen_const($2), gen_op_unbound(STOREV, jv_string_value($2)));
} |
'$' IDENT ':' Pattern {
$$ = gen_object_matcher(gen_const($2), BLOCK(gen_op_simple(DUP), gen_op_unbound(STOREV, jv_string_value($2)), $4));
} |
IDENT ':' Pattern {
$$ = gen_object_matcher(gen_const($1), $3);
} |
+3 -8
View File
@@ -52,7 +52,7 @@ FILE *fopen(const char *fname, const char *mode) {
MultiByteToWideChar(CP_UTF8, 0, fname, -1, wfname, sz);
sz = sizeof(wchar_t) * MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
wchar_t *wmode = alloca(sz + 2); // +2 is not needed, but just in case
wchar_t *wmode = alloca(sz); // +2 is not needed, but just in case
MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, sz);
return _wfopen(wfname, wmode);
}
@@ -139,7 +139,7 @@ jv jq_realpath(jv path) {
path_max = PATH_MAX;
#endif
if (path_max > 0) {
buf = jv_mem_alloc(path_max);
buf = malloc(sizeof(char) * path_max);
}
#ifdef WIN32
char *tmp = _fullpath(buf, jv_string_value(path), path_max);
@@ -410,7 +410,6 @@ jv jq_util_input_get_current_line(jq_state* jq) {
// When slurping, it returns just one value
jv jq_util_input_next_input(jq_util_input_state *state) {
int is_last = 0;
int has_more = 0;
jv value = jv_invalid(); // need more input
do {
if (state->parser == NULL) {
@@ -442,10 +441,6 @@ jv jq_util_input_next_input(jq_util_input_state *state) {
}
value = jv_parser_next(state->parser);
if (jv_is_valid(state->slurped)) {
// When slurping an input that doesn't have a trailing newline,
// we might have more than one value on the same line, so let's check
// to see if we have more data to parse.
has_more = jv_parser_remaining(state->parser);
if (jv_is_valid(value)) {
state->slurped = jv_array_append(state->slurped, value);
value = jv_invalid();
@@ -455,7 +450,7 @@ jv jq_util_input_next_input(jq_util_input_state *state) {
return value;
}
}
} while (!is_last || has_more);
} while (!is_last);
if (jv_is_valid(state->slurped)) {
value = state->slurped;
-35
View File
@@ -1,35 +0,0 @@
# Tests are groups of three lines: program, input, expected output
# Blank lines and lines starting with # are ignored
@base64
"<>&'\"\t"
"PD4mJyIJ"
# decoding encoded output results in same text
(@base64|@base64d)
"<>&'\"\t"
"<>&'\"\t"
# regression test for #436
@base64
"foóbar\n"
"Zm/Ds2Jhcgo="
@base64d
"Zm/Ds2Jhcgo="
"foóbar\n"
# optional trailing equals padding (With padding, this is cWl4YmF6Cg==)
@base64d
"cWl4YmF6Cg"
"qixbaz\n"
# invalid base64 characters (whitespace)
. | try @base64d catch .
"Not base64 data"
"string (\"Not base64...) is not valid base64 data"
# invalid base64 (too many bytes, QUJD = "ABCD"
. | try @base64d catch .
"QUJDa"
"string (\"QUJDa\") trailing base64 byte found"
-5
View File
@@ -1,5 +0,0 @@
#!/bin/sh
. "${0%/*}/setup" "$@"
$VALGRIND $Q $JQ -L "$mods" --run-tests $JQTESTDIR/base64.test
+5 -171
View File
@@ -61,7 +61,7 @@ null
null
"interpolation"
@text,@json,([1,.] | (@csv, @tsv)),@html,@uri,@sh,@base64,(@base64 | @base64d)
@text,@json,([1,.] | (@csv, @tsv)),@html,@uri,@sh,@base64
"<>&'\"\t"
"<>&'\"\t"
"\"<>&'\\\"\\t\""
@@ -71,17 +71,12 @@ null
"%3C%3E%26'%22%09"
"'<>&'\\''\"\t'"
"PD4mJyIJ"
"<>&'\"\t"
# regression test for #436
@base64
"foóbar\n"
"Zm/Ds2Jhcgo="
@base64d
"Zm/Ds2Jhcgo="
"foóbar\n"
@uri
"\u03bc"
"%CE%BC"
@@ -278,7 +273,7 @@ null
%%FAIL
. as $foo | break $foo
jq: error: $*label-foo is not defined at <top-level>, line 1:
jq: error: *label-foo/0 is not defined at <top-level>, line 1:
[.[]|[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]]
[1,2,3,4,5]
@@ -383,15 +378,6 @@ del(.[2:4],.[0],.[-2:])
[0,1,"a","b",4,5,6,7]
[0,1,"a","b","c",4,5,6,7]
# Slices at large offsets (issue #1108)
#
# This is written this way because [range(<large number>)] is
# significantly slower under valgrind than .[<large number>] = value.
#
# We range down rather than up so that we have just one realloc.
reduce range(65540;65536;-1) as $i ([]; .[$i] = $i)|.[65536:]
null
[null,65537,65538,65539,65540]
#
# Variables
@@ -705,127 +691,10 @@ reduce [[1,2,10], [3,4,10]][] as [$i,$j] (0; . + $i * $j)
null
14
# This, while useless, should still compile.
reduce . as $n (.; .)
# Test fix for #1313 (reduce should handle empty updates)
reduce range(5) as $n ([]; select($n%2 == 1) | . + [$n])
null
null
# Destructuring
. as {$a, b: [$c, {$d}]} | [$a, $c, $d]
{"a":1, "b":[2,{"d":3}]}
[1,2,3]
. as {$a, $b:[$c, $d]}| [$a, $b, $c, $d]
{"a":1, "b":[2,{"d":3}]}
[1,[2,{"d":3}],2,{"d":3}]
# Destructuring with alternation
.[] | . as {$a, b: [$c, {$d}]} ?// [$a, {$b}, $e] ?// $f | [$a, $b, $c, $d, $e, $f]
[{"a":1, "b":[2,{"d":3}]}, [4, {"b":5, "c":6}, 7, 8, 9], "foo"]
[1, null, 2, 3, null, null]
[4, 5, null, null, 7, null]
[null, null, null, null, null, "foo"]
# Destructuring DUP/POP issues
.[] | . as {a:$a} ?// {a:$a} ?// {a:$a} | $a
[[3],[4],[5],6]
# Runtime error: "jq: Cannot index array with string \"c\""
.[] as {a:$a} ?// {a:$a} ?// {a:$a} | $a
[[3],[4],[5],6]
# Runtime error: "jq: Cannot index array with string \"c\""
[[3],[4],[5],6][] | . as {a:$a} ?// {a:$a} ?// {a:$a} | $a
null
# Runtime error: "jq: Cannot index array with string \"c\""
[[3],[4],[5],6] | .[] as {a:$a} ?// {a:$a} ?// {a:$a} | $a
null
# Runtime error: "jq: Cannot index array with string \"c\""
.[] | . as {a:$a} ?// {a:$a} ?// $a | $a
[[3],[4],[5],6]
[3]
[4]
[5]
6
.[] as {a:$a} ?// {a:$a} ?// $a | $a
[[3],[4],[5],6]
[3]
[4]
[5]
6
[[3],[4],[5],6][] | . as {a:$a} ?// {a:$a} ?// $a | $a
null
[3]
[4]
[5]
6
[[3],[4],[5],6] | .[] as {a:$a} ?// {a:$a} ?// $a | $a
null
[3]
[4]
[5]
6
.[] | . as {a:$a} ?// $a ?// {a:$a} | $a
[[3],[4],[5],6]
[3]
[4]
[5]
6
.[] as {a:$a} ?// $a ?// {a:$a} | $a
[[3],[4],[5],6]
[3]
[4]
[5]
6
[[3],[4],[5],6][] | . as {a:$a} ?// $a ?// {a:$a} | $a
null
[3]
[4]
[5]
6
[[3],[4],[5],6] | .[] as {a:$a} ?// $a ?// {a:$a} | $a
null
[3]
[4]
[5]
6
.[] | . as $a ?// {a:$a} ?// {a:$a} | $a
[[3],[4],[5],6]
[3]
[4]
[5]
6
.[] as $a ?// {a:$a} ?// {a:$a} | $a
[[3],[4],[5],6]
[3]
[4]
[5]
6
[[3],[4],[5],6][] | . as $a ?// {a:$a} ?// {a:$a} | $a
null
[3]
[4]
[5]
6
[[3],[4],[5],6] | .[] as $a ?// {a:$a} ?// {a:$a} | $a
null
[3]
[4]
[5]
6
[1,3]
. as $dot|any($dot[];not)
[1,2,3,4,true,false,1,2,3,4,5]
@@ -968,18 +837,6 @@ def inc(x): x |= .+1; inc(.[].a)
[{"a":1,"b":2},{"a":2,"b":4},{"a":7,"b":8}]
[{"a":2,"b":2},{"a":3,"b":4},{"a":8,"b":8}]
# #1358, getpath/1 should work in path expressions
.[] | try (getpath(["a",0,"b"]) |= 5) catch .
[null,{"b":0},{"a":0},{"a":null},{"a":[0,1]},{"a":{"b":1}},{"a":[{}]},{"a":[{"c":3}]}]
{"a":[{"b":5}]}
{"b":0,"a":[{"b":5}]}
"Cannot index number with number"
{"a":[{"b":5}]}
"Cannot index number with string \"b\""
"Cannot index object with number"
{"a":[{"b":5}]}
{"a":[{"c":3,"b":5}]}
.[2][3] = 1
[4]
[4, null, [null, null, null, 1]]
@@ -1494,26 +1351,3 @@ IN(range(5;20); range(10))
null
true
# Regression test for #1347
(.a as $x | .b) = "b"
{"a":null,"b":null}
{"a":null,"b":"b"}
# Regression test for #1368
(.. | select(type == "object" and has("b") and (.b | type) == "array")|.b) |= .[0]
{"a": {"b": [1, {"b": 3}]}}
{"a": {"b": 1}}
isempty(empty)
null
true
isempty(range(3))
null
false
isempty(1,error("foo"))
null
false
-7
View File
@@ -5,13 +5,6 @@
"2015-03-05T23:51:47Z"
[[2015,2,5,23,51,47,4,63],1425599507]
# Check day-of-week and day of year computations
# (should trip an assert if this fails)
# This date range
last(range(365 * 67)|("1970-03-01T01:02:03Z"|strptime("%Y-%m-%dT%H:%M:%SZ")|mktime) + (86400 * .)|strftime("%Y-%m-%dT%H:%M:%SZ")|strptime("%Y-%m-%dT%H:%M:%SZ"))
null
[2037,1,11,1,2,3,3,41]
# %e is not available on mingw/WIN32
strftime("%A, %B %e, %Y")
1435677542.822351
+1 -3
View File
@@ -15,11 +15,9 @@ JQ=$JQBASEDIR/jq
if [ -z "${NO_VALGRIND-}" ] && which valgrind > /dev/null; then
VALGRIND="valgrind --error-exitcode=1 --leak-check=full \
--suppressions=$JQTESTDIR/onig.supp"
VG_EXIT0=--error-exitcode=0
Q=-q
else
VALGRIND=
VG_EXIT0=
Q=
fi
@@ -35,7 +33,7 @@ clean () {
fi
}
trap clean EXIT
d=$(mktemp -d -t jqXXXXXX || true)
d=`mktemp -d -t jqXXXXXX || true`
if [ -z "$d" ]; then
echo "Your OS does not support mktemp(1) -d" 1>&2
exit 1
+27 -118
View File
@@ -29,46 +29,50 @@ $VALGRIND $Q $JQ -Rne '[inputs] == ["a\u0000b", "c\u0000d", "e"]' $d/input
## move all of these into tests/all.test
# String constant folding (addition only)
nref=$($VALGRIND $Q $JQ -n --debug-dump-disasm '"foo"' | wc -l)
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '"foo"' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
# Numeric constant folding (not all ops yet)
n=$($VALGRIND $Q $JQ -n --debug-dump-disasm '1+1' | wc -l)
if [ $n -ne $nref ]; then
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '1+1' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
n=$($VALGRIND $Q $JQ -n --debug-dump-disasm '1-1' | wc -l)
if [ $n -ne $nref ]; then
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '1-1' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
n=$($VALGRIND $Q $JQ -n --debug-dump-disasm '2*3' | wc -l)
if [ $n -ne $nref ]; then
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '2*3' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
n=$($VALGRIND $Q $JQ -n --debug-dump-disasm '9/3' | wc -l)
if [ $n -ne $nref ]; then
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '9/3' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
n=$($VALGRIND $Q $JQ -n --debug-dump-disasm '9==3' | wc -l)
if [ $n -ne $nref ]; then
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '9==3' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
n=$($VALGRIND $Q $JQ -n --debug-dump-disasm '9!=3' | wc -l)
if [ $n -ne $nref ]; then
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '9!=3' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
n=$($VALGRIND $Q $JQ -n --debug-dump-disasm '9<=3' | wc -l)
if [ $n -ne $nref ]; then
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '9<=3' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
n=$($VALGRIND $Q $JQ -n --debug-dump-disasm '9>=3' | wc -l)
if [ $n -ne $nref ]; then
n=`$VALGRIND $Q $JQ -n --debug-dump-disasm '9>=3' | wc -l`
if [ $n -ne 5 ]; then
echo "Constant expression folding for strings didn't work"
exit 1
fi
@@ -122,14 +126,6 @@ if $VALGRIND $Q $JQ -e . $d/input; then
exit 2
fi
# Regression test for #1534
echo "[1,2,3,4]" > $d/expected
printf "[1,2][3,4]" | $JQ -cs add > $d/out 2>&1
cmp $d/out $d/expected
printf "[1,2][3,4]\n" | $JQ -cs add > $d/out 2>&1
cmp $d/out $d/expected
## Test streaming parser
## If we add an option to stream to the `import ... as $symbol;` directive
@@ -145,15 +141,15 @@ if which seq > /dev/null 2>&1; then
# test very, very slow when run with valgrind, and the whole point
# is to run it with valgrind.
#
#len=$(wc -c < "$JQTESTDIR/torture/input0.json")
#len=`wc -c < "$JQTESTDIR/torture/input0.json"`
if [ -z "$VALGRIND" ]; then
start=1
end=$(wc -c < "$JQTESTDIR/torture/input0.json")
end=`wc -c < "$JQTESTDIR/torture/input0.json"`
else
start=120
end=151
fi
for i in $(seq $start $end); do
for i in `seq $start $end`; do
dd "if=tests/torture/input0.json" bs=$i count=1 2>/dev/null |
$VALGRIND $JQ -c . > $d/out0 2>$d/err || true
if [ -n "$VALGRIND" ]; then
@@ -178,7 +174,7 @@ fi
## Fuzz parser
## XXX With a $(urandom) builtin we could move this test into tests/all.test
## XXX With a `urandom` builtin we could move this test into tests/all.test
clean=false
if dd if=/dev/urandom bs=16 count=1024 > $d/rand 2>/dev/null; then
# Have a /dev/urandom, good
@@ -197,12 +193,12 @@ clean=true
# Check handling of ~/.jq; these can't move into jq_test.c yet because
# they depend on $HOME
if [ "$(HOME="$mods" $VALGRIND $Q $JQ -nr fg)" != foobar ]; then
if [ "`HOME="$mods" $VALGRIND $Q $JQ -nr fg`" != foobar ]; then
echo "Bug #479 appears to be back" 1>&2
exit 1
fi
if [ $(HOME="$mods" $VALGRIND $Q $JQ --debug-dump-disasm -n fg | grep '^[a-z]' | wc -l) -gt 3 ]; then
if [ `HOME="$mods" $VALGRIND $Q $JQ --debug-dump-disasm -n fg | grep '^[a-z]' | wc -l` -gt 3 ]; then
echo "Binding too many defs into program" 1>&2
exit 1
fi
@@ -219,91 +215,4 @@ if ! $VALGRIND $Q $JQ -L tests/modules -ne 'import "test_bind_order" as check; c
exit 1
fi
## Halt
if ! $VALGRIND $Q $JQ -n halt; then
echo "jq halt didn't work as expected" 1>&2
exit 1
fi
if $VALGRIND $Q $VG_EXIT0 $JQ -n 'halt_error(1)'; then
echo "jq halt_error(1) didn't work as expected" 1>&2
exit 1
elif [ $? -ne 1 ]; then
echo "jq halt_error(1) had wrong error code" 1>&2
exit 1
fi
if $VALGRIND $Q $VG_EXIT0 $JQ -n 'halt_error(11)'; then
echo "jq halt_error(11) didn't work as expected" 1>&2
exit 1
elif [ $? -ne 11 ]; then
echo "jq halt_error(11) had wrong error code" 1>&2
exit 1
fi
if [ -n "$($VALGRIND $Q $JQ -n 'halt_error(1)' 2>&1)" ]; then
echo "jq halt_error(1) had unexpected output" 1>&2
exit 1
fi
if [ -n "$($VALGRIND $Q $JQ -n '"xyz\n"|halt_error(1)' 2>/dev/null)" ]; then
echo "jq halt_error(1) had unexpected output on stdout" 1>&2
exit 1
fi
if [ "$($VALGRIND $Q $JQ -n '"xyz\n"|halt_error(1)' 2>&1)" != xyz ]; then
echo "jq halt_error(1) had unexpected output" 1>&2
exit 1
fi
# Check $JQ_COLORS
$JQ -Ccn . > $d/color
printf '\033[1;30mnull\033[0m\n' > $d/expect
cmp $d/color $d/expect
JQ_COLORS='4;31' $JQ -Ccn . > $d/color
printf '\033[4;31mnull\033[0m\n' > $d/expect
cmp $d/color $d/expect
JQ_COLORS='1;30:0;31:0;32:0;33:0;34:1;35:1;36' \
$JQ -Ccn '[{"a":true,"b":false},123,null]' > $d/color
(
printf '\033[1;35m[\033[1;36m{'
printf '\033[0m\033[34;1m"a"\033['
printf '0m\033[1;36m:\033[0m\033['
printf '0;32mtrue\033[0m\033[1'
printf ';36m,\033[0m\033[34;1m'
printf '"b"\033[0m\033[1;36m:\033'
printf '[0m\033[0;31mfalse\033'
printf '[0m\033[1;36m\033[1;36'
printf 'm}\033[0m\033[1;35m,\033['
printf '0;33m123\033[0m\033[1;'
printf '35m,\033[1;30mnull\033'
printf '[0m\033[1;35m\033[1;35'
printf 'm]\033[0m\n'
) > $d/expect
cmp $d/color $d/expect
# Check garbage in JQ_COLORS. We write each color sequence into a 16
# char buffer that needs to hold ESC [ <color> m NUL, so each color
# sequence can be no more than 12 chars (bytes). These emit a warning
# on stderr.
set -vx
echo 'Failed to set $JQ_COLORS' > $d/expect_warning
$JQ -Ccn '[{"a":true,"b":false},123,null]' > $d/expect
JQ_COLORS='garbage;30:*;31:,;3^:0;$%:0;34:1;35:1;36' \
$JQ -Ccn '[{"a":true,"b":false},123,null]' > $d/color 2>$d/warning
cmp $d/color $d/expect
cmp $d/warning $d/expect_warning
JQ_COLORS='1234567890123456789;30:0;31:0;32:0;33:0;34:1;35:1;36' \
$JQ -Ccn '[{"a":true,"b":false},123,null]' > $d/color 2>$d/warning
cmp $d/color $d/expect
cmp $d/warning $d/expect_warning
JQ_COLORS='1;31234567890123456789:0;31:0;32:0;33:0;34:1;35:1;36' \
$JQ -Ccn '[{"a":true,"b":false},123,null]' > $d/color 2>$d/warning
cmp $d/color $d/expect
cmp $d/warning $d/expect_warning
JQ_COLORS='1234567890123456;1234567890123456:1234567890123456;1234567890123456:1234567890123456;1234567890123456:1234567890123456;1234567890123456:1234567890123456;1234567890123456:1234567890123456;1234567890123456:1234567890123456;1234567890123456' \
$JQ -Ccn '[{"a":true,"b":false},123,null]' > $d/color 2>$d/warning
cmp $d/color $d/expect
cmp $d/warning $d/expect_warning
JQ_COLORS="0123456789123:0123456789123:0123456789123:0123456789123:0123456789123:0123456789123:0123456789123:0123456789123:" \
$JQ -Ccn '[{"a":true,"b":false},123,null]' > $d/color 2>$d/warning
cmp $d/color $d/expect
cmp $d/warning $d/expect_warning
exit 0
+1 -1
View File
@@ -2,7 +2,7 @@
. "${0%/*}/setup" "$@"
if [ "$($VALGRIND $Q $JQ -nf $JQTESTDIR/utf8-truncate.jq)" != "true" ]; then
if [ "`$VALGRIND $Q $JQ -nf $JQTESTDIR/utf8-truncate.jq`" != "true" ]; then
echo "UTF-8 byte sequences that span the jv_load_file read buffer are mangled"
exit 1
fi