Radish alpha
H
rad:z3QDZAW2FAfuLvihrhiyDC9fAD8G9
HardenedBSD Package Manager
Radicle
Git
Merge branch 'autosetup'
Baptiste Daroussin committed 7 years ago
commit b9c18cfe0fe5089ec9f1f44d36aee6b9f401214f
parent 9007a52
94 files changed +30876 -2241
modified .gitignore
@@ -1,6 +1,7 @@
*.o
*.so*
*.a
+
*.pico
*.po
*.Po
*.So
@@ -41,13 +42,16 @@ scripts/sbin/pkg2ng
# Generated files:

/Makefile
-
/config.guess
-
/config.status
-
/config.sub
/compat/Makefile
/docs/Makefile
/external/Makefile
-
external/blake2/Makefile
+
/external/blake2/Makefile
+
/external/picosat/Makefile
+
/external/expat/Makefile
+
/external/linenoise/Makefile
+
/external/libucl/Makefile
+
/external/sqlite/Makefile
+
/external/sqlite/config.h
/external/libelf/libelf_convert.c
/external/libelf/libelf_fsize.c
/external/libelf/libelf_msize.c
@@ -55,27 +59,10 @@ external/blake2/Makefile
/libpkg/Makefile
/libpkg/repo/Makefile
/libpkg/repo/binary/Makefile
-
/libtool
-
/ltmain.sh
/pkg_config.h
/pkg_config.h.in
-
/pkg_repos.h
/scripts/Makefile
/src/Makefile
-
/test-driver
/tests/Makefile
-

-
# http://www.gnu.org/software/automake
-

-
Makefile.in
-

-
# http://www.gnu.org/software/autoconf
-

-
/autom4te.cache
-
/aclocal.m4
-
/compile
-
/configure
-
/depcomp
-
/install-sh
-
/missing
-
/stamp-h1
+
/tests/frontend/test_environment.sh
+
/mk/defs.mk
modified .travis.yml
@@ -24,9 +24,6 @@ compiler:
before_install:
  - scripts/install_deps.sh

-
before_script:
-
  - autoreconf -i
-

script:
  - scripts/travis_build.sh

added Kyuafile
@@ -0,0 +1,4 @@
+
syntax(2)
+
test_suite("pkg")
+

+
include("tests/Kyuafile")
deleted Kyuafile.in
@@ -1,4 +0,0 @@
-
syntax(2)
-
test_suite("pkg")
-

-
include("tests/Kyuafile")
deleted Makefile.am
@@ -1,58 +0,0 @@
-
AUTOMAKE_OPTIONS=	subdir-objects
-
ACLOCAL_AMFLAGS=	-I m4
-

-
pkgconfigdir=	$(prefix)/libdata/pkgconfig
-
pkgconfig_DATA=	libpkg/pkg.pc
-

-
$(pkgconfig_DATA): config.status
-

-
DISTCLEANFILES=	pkg_repos.h
-
EXTRA_DIST=	docs Kyuafile
-
dist-hook:
-
	rm -rf `find $(distdir)/external -type d -name .deps`
-

-
check-local:
-
	if [ "$(HTML)" != "" ]; then \
-
		args="-r $(top_builddir)/res.db" ; \
-
	fi ; \
-
	kyua --config=none test $$args \
-
		--kyuafile='$(top_builddir)/Kyuafile' \
-
		--build-root='$(top_builddir)' || FAILED=1 ; \
-
	if [ "$(HTML)" != "" ]; then \
-
		kyua report-html --force $$args --output=$(HTML) ; \
-
		rm -f $(top_builddir)/res.db ; \
-
	fi ; \
-
	exit $${FAILED}
-

-
COCCI_ARGS=	-I ${top_srcdir} \
-
		-I /usr/include \
-
		-I /usr/local/include \
-
		-I ${top_srcdir}/compat \
-
		-I ${top_srcdir}/libpkg \
-
		-I ${top_srcdir}/src \
-
		-I ${top_srcdir}/external/expat/lib \
-
		-I ${top_srcdir}/external/libyaml/include \
-
		-I ${top_srcdir}/external/libucl/include \
-
		-I ${top_srcdir}/external/uthash \
-
		-I ${top_srcdir}/external/sqlite  \
-
		-I ${top_srcdir}/external/libelf
-

-
1cocci:
-
	spatch ${COCCI_ARGS} -in_place -sp_file $(top_srcdir)/tests/cocci/${COCCITEST} -dir ${top_srcdir}/libpkg ; \
-
	spatch ${COCCI_ARGS} -in_place -sp_file $(top_srcdir)/tests/cocci/${COCCITEST} -dir ${top_srcdir}/src ;
-

-
cocci:
-
	for c in ${top_srcdir}/tests/cocci/*.cocci ; do \
-
		echo "Passing $$c" ; \
-
		spatch ${COCCI_ARGS} -in_place -sp_file $$c -dir ${top_srcdir}/libpkg ; \
-
		spatch ${COCCI_ARGS} -in_place -sp_file $$c -dir ${top_srcdir}/src ; \
-
	done
-

-
STYLEPATTERN=	*.[c]
-

-
style-fix:
-
	find ${top_srcdir}/src ${top_srcdir}/libpkg -name "${STYLEPATTERN}" | xargs \
-
		uncrustify -c ${top_srcdir}/freebsd.cfg --no-backup
-

-

-
SUBDIRS = compat external libpkg src tests scripts docs
added Makefile.autosetup
@@ -0,0 +1,43 @@
+
include @builddir@/mk/defs.mk
+
DIRS=	external compat libpkg/repo libpkg src docs scripts @testsdir@
+

+
include $(MK)/dir.mk
+

+
check: all
+
@if testsdir == "tests"
+
	if [ "$(HTML)" != "" ]; then \
+
		args="-r $(top_builddir)/res.db" ; \
+
	fi ; \
+
	kyua --config=none test $$args \
+
		--kyuafile='$(top_builddir)/Kyuafile' \
+
		--build-root='$(top_builddir)' || FAILED=1 ; \
+
	if [ "$(HTML)" != "" ]; then \
+
		kyua report-html --force $$args --output=$(HTML) ; \
+
		rm -f $(top_builddir)/res.db ; \
+
	fi ; \
+
	exit $${FAILED}
+
@endif
+

+
COCCI_ARGS=	-I ${top_srcdir} \
+
		-I /usr/include \
+
		-I /usr/local/include \
+
		-I ${top_srcdir}/compat \
+
		-I ${top_srcdir}/libpkg \
+
		-I ${top_srcdir}/src \
+
		-I ${top_srcdir}/external/expat/lib \
+
		-I ${top_srcdir}/external/libyaml/include \
+
		-I ${top_srcdir}/external/libucl/include \
+
		-I ${top_srcdir}/external/uthash \
+
		-I ${top_srcdir}/external/sqlite  \
+
		-I ${top_srcdir}/external/libelf
+

+
1cocci:
+
	spatch ${COCCI_ARGS} -in_place -sp_file $(top_srcdir)/tests/cocci/${COCCITEST} -dir ${top_srcdir}/libpkg ; \
+
	spatch ${COCCI_ARGS} -in_place -sp_file $(top_srcdir)/tests/cocci/${COCCITEST} -dir ${top_srcdir}/src ;
+

+
cocci:
+
	for c in ${top_srcdir}/tests/cocci/*.cocci ; do \
+
		echo "Passing $$c" ; \
+
		spatch ${COCCI_ARGS} -in_place -sp_file $$c -dir ${top_srcdir}/libpkg ; \
+
		spatch ${COCCI_ARGS} -in_place -sp_file $$c -dir ${top_srcdir}/src ; \
+
	done
modified README.md
@@ -270,7 +270,6 @@ Just open your browser and download the release you want.
Once you have the pkg sources, installing it is fairly easy:

	% cd pkg
-
	% ./autogen.sh
	% ./configure
	% make
	# make install
added auto.def
@@ -0,0 +1,254 @@
+
# vim:se syn=tcl:
+
#
+

+
use cc cc-lib cc-shared pkg-config
+

+
set maj_ver 1
+
set med_ver 10
+
set min_ver 99
+
set dev_ver 8
+
define PKG_API [expr $maj_ver * 1000000 + $med_ver * 1000 + $min_ver]
+
define VERSION $maj_ver.$med_ver.$min_ver[expr {$dev_ver ? ".$dev_ver" : ""}]
+

+
# Add any user options here
+
options {
+
	pkgconfigdir:WHERE => "path to the directory where to install pc files"
+
	with-ldns => "add support for libldns"
+
	with-libarchive.pc => "build with libarchive getting flags via pc files"
+
}
+

+
if {[opt-str pkgconfigdir dir]} {
+
	define pkgconfigdir $dir
+
} else {
+
	if {[string match *-freebsd* [get-define host]]} {
+
		define pkgconfigdir [get-define prefix]/libdata/pkgconfig
+
	} else {
+
		define pkgconfigdir [get-define prefix]/lib/pkgconfig
+
	}
+
}
+

+
cc-check-tools ar ranlib strip
+

+
define EXTRA_LIBS ""
+
define LIBVERSION 4
+
define LIBSOEXT [format [get-define SH_SOEXTVER] [get-define LIBVERSION]]
+

+
define GITHASH ""
+
if {[cc-check-progs git] && [file exists .git]} {
+
	catch {exec git rev-parse --short HEAD} gitrev
+
	catch {exec git diff-index -m --name-only HEAD} gitdirty
+
	define GITHASH -$gitrev[expr {$gitdirty eq {} ? {} : {-dirty}}]
+
}
+

+
if {[string match *-linux* [get-define host]]} {
+
	cc-with { -libs { -lbsd }} {
+
		if {[cc-check-functions getprogname]} {
+
			define-append EXTRA_LIBS -lbsd
+
			define-feature libbsd
+
		} else {
+
			user-error "Unable to find libbsd"
+
		}
+
	}
+
}
+

+
if {![opt-bool with-libarchive.pc]} {
+
	cc-with { -libs { -larchive }} {
+
		if {![cc-check-functions archive_read_open]} {
+
			user-error "Unable to find libarchive"
+
		}
+
	}
+
}
+

+
cc-with { -libs { -lz }} {
+
	if {![cc-check-functions zlibVersion]} {
+
		user-error "Unable to find zlib"
+
	}
+
}
+

+
cc-with { -libs { -lbz2 }} {
+
	if {![cc-check-functions BZ2_bzReadOpen]} {
+
		user-error "Unable to find bzip2"
+
	}
+
}
+

+
cc-with { -libs { -llzma }} {
+
	if {![cc-check-functions lzma_version_string]} {
+
		user-error "Unable to find liblzma"
+
	}
+
}
+

+
# Atomics
+
msg-checking "Checking for atomic builtins... "
+
if {[cctest -code {
+
	volatile unsigned long val = 1;
+
	__sync_synchronize();
+
	__sync_val_compare_and_swap(&val, 1, 0);
+
	__sync_add_and_fetch(&val, 1);
+
	__sync_sub_and_fetch(&val, 1);
+
	return 0;
+
	}
+
]} {
+
	msg-result ok
+
	define-feature atomic_builtins
+
} else {
+
	msg-result no
+
	define-feature atomic_builtins 0
+
}
+

+
msg-checking "Checking for /proc/self/fd support... "
+
if {[file exists /proc/self/fd]} {
+
	msg-result ok
+
	define-feature proc-pid
+
} else {
+
	msg-result no
+
	define-feature proc-pid 0
+
}
+

+
lmap fct [list memmove usleep pread pwrite] {
+
	if {![cc-check-functions $fct]} {
+
		user-error "Cannot find $fct"
+
	}
+
}
+

+
cc-with { -includes fcntl.h } {
+
	cc-check-decls F_CLOSEM
+
}
+

+
cc-with { -includes sys/socket.h } {
+
	cc-check-decls SOCK_SEQPACKET
+
}
+

+
cc-with { -includes netinet/in.h } {
+
	cc-check-members "struct sockaddr_in.sin_len"
+
}
+

+
cc-with { -includes sys/stat.h } {
+
	cc-check-members "struct stat.st_mtim" "struct stat.st_flags"
+
}
+

+
# check for sqlite
+
cc-check-functions gmtime_r isnan localtime_r strchrnul strerror_r
+
cc-check-includes stdint.h inttypes.h
+

+
# check for pkg itself
+
cc-check-functions arc4random arc4random_stir basename_r chflagsat \
+
	closefrom dirfd eaccess fopencookie fstatfs funopen strnstr \
+
	strtofflags strtonum sysconf utimensat __res_setservers unlinkat \
+
	faccessat fstatat openat readlinkat fflagstostr
+

+
cc-with { -libs { -lutil }} {
+
	if {[cc-check-functions humanize_number]} {
+
		define-feature LIBUTIL
+
	}
+
}
+

+
cc-check-includes link.h machine/endian.h osreldate.h readpassphrase.h \
+
	sys/procctl.h sys/statfs.h sys/statvfs.h libutil.h
+

+
# for compat
+
cc-check-includes dirent.h
+

+
#endian stuff
+
lmap header [list endian.h sys/endian.h] {
+
	if {[cc-check-includes $header]} {
+
		cc-with [list -includes $header] {
+
			cc-check-decls be16dec be16enc be32dec be32enc be64dec be64enc \
+
				le16dec le16enc le32dec le32enc le64dec le64enc
+
		}
+
	}
+
}
+

+
if {[string match *-darwin* [get-define host]]} {
+
	define libabidir libmachista
+
} else {
+
# libelf
+
	cc-with { -includes { sys/types.h }} {
+
		cc-check-includes elf-hints.h sys/elf_common.h
+
	}
+

+
	if {[cc-check-includes gelf.h libelf.h]} {
+
		cc-with { -libs { -lelf } } {
+
			if {[cc-check-functions gelf_getehdr]} {
+
				define-feature libelf
+
				define-append EXTRA_LIBS -lelf
+
				define libabidir ""
+
			} else {
+
				define-feature libelf 0
+
				define libabidir "libelf"
+
			}
+
		}
+
	} else {
+
		define-feature libelf 0
+
		define libabidir "libelf"
+
	}
+
}
+

+
cc-with { -libs { -ljail} } {
+
	if {[cc-check-functions jail_getid]} {
+
		define-feature libjail
+
		define-append EXTRA_LIBS -ljail
+
	}
+
}
+

+
# libbsd
+
cc-check-includes bsd/err.h bsd/libutil.h bsd/readpassphrase.h \
+
	bsd/stdio.h bsd/strlib.h bsd/string.h bsd/sys/cdefs.h \
+
	bsd/unistd.h
+
 
+
# capsicum
+
if {[cc-check-functions cap_sandboxed]} {
+
	define-feature capsicum
+
	cc-check-includes sys/capsicum.h sys/capability.h
+
}
+

+
define testsdir ""
+
if {[pkg-config-init 0]} {
+
# atf
+
	if {[pkg-config atf-c] && [cc-check-progs kyua]} {
+
		define testsdir tests
+
		puts "test suite will be built"
+
	} else {
+
		puts "Skipping test suite"
+
	}
+
	if {[opt-bool with-ldns]} {
+
		if {![pkg-config libldns]} {
+
			user-error "Unable to find libldns"
+
		} else {
+
			define PKG_LIBDNS_LIBS_STATIC [exec pkg-config --static --libs-only-l libldns]
+
		}
+
	}
+
	if {[opt-bool with-libarchive.pc]} {
+
		if {![pkg-config libarchive]} {
+
			user-error "Unable to find libarchive"
+
		} else {
+
			define PKG_LIBARCHIVE_LIBS_STATIC [exec pkg-config --static --libs-only-l libarchive]
+
		}
+
	}
+
}
+

+
lmap repo [list binary] {
+
	define-append REPOS $repo
+
	define-append REPOS_LDFLAGS -L\$(top_builddir)/libpkg/repo/${repo} -lrepo-${repo}_pic
+
	define-append REPOS_STATIC_LIBS \$(top_builddir)/libpkg/repo/${repo}/librepo-${repo}.a
+
}
+

+
# ccache
+
if {[get-define CCACHE] ne {none}} {
+
  define CC "[get-define CCACHE] [get-define CC]"
+
}
+

+
make-config-header pkg_config.h
+
make-config-header external/sqlite/config.h
+
make-template mk/defs.mk.in
+
make-template libpkg/pkg.h.in
+
make-template libpkg/pkg.pc.in
+
make-template tests/frontend/test_environment.sh.in
+
make-template Makefile.autosetup Makefile
+

+
lmap dir [list external/expat external/blake2 external/picosat \
+
	external/linenoise external/libfetch external/sqlite \
+
	external compat libpkg libpkg/repo libpkg/repo/binary src \
+
	external/libucl external/libelf external/libmachista tests docs scripts] {
+
	make-template $dir/Makefile.autosetup $dir/Makefile
+
}
+

modified autogen.sh
@@ -1,2 +1,2 @@
#!/bin/sh
-
autoreconf -if
+
true
added autosetup/LICENSE
@@ -0,0 +1,35 @@
+
Unless explicitly stated, all files which form part of autosetup
+
are released under the following license:
+

+
---------------------------------------------------------------------
+
autosetup - A build environment "autoconfigurator"
+

+
Copyright (c) 2010-2011, WorkWare Systems <http://workware.net.au/>
+

+
Redistribution and use in source and binary forms, with or without
+
modification, are permitted provided that the following conditions
+
are met:
+

+
1. Redistributions of source code must retain the above copyright
+
   notice, this list of conditions and the following disclaimer.
+
2. Redistributions in binary form must reproduce the above
+
   copyright notice, this list of conditions and the following
+
   disclaimer in the documentation and/or other materials
+
   provided with the distribution.
+

+
THIS SOFTWARE IS PROVIDED BY THE WORKWARE SYSTEMS ``AS IS'' AND ANY
+
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WORKWARE
+
SYSTEMS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+

+
The views and conclusions contained in the software and documentation
+
are those of the authors and should not be interpreted as representing
+
official policies, either expressed or implied, of WorkWare Systems.
added autosetup/README.autosetup
@@ -0,0 +1,11 @@
+
README.autosetup created by autosetup v0.6.8
+

+
This is the autosetup directory for a local install of autosetup.
+
It contains autosetup, support files and loadable modules.
+

+
*.tcl files in this directory are optional modules which
+
can be loaded with the 'use' directive.
+

+
*.auto files in this directory are auto-loaded.
+

+
For more information, see http://msteveb.github.com/autosetup/
added autosetup/autosetup
@@ -0,0 +1,2431 @@
+
#!/bin/sh
+
# Copyright (c) 2006-2011 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+
# vim:se syntax=tcl:
+
# \
+
dir=`dirname "$0"`; exec "`$dir/autosetup-find-tclsh`" "$0" "$@"
+

+
set autosetup(version) 0.6.8
+

+
# Can be set to 1 to debug early-init problems
+
set autosetup(debug) [expr {"--debug" in $argv}]
+

+
##################################################################
+
#
+
# Main flow of control, option handling
+
#
+
proc main {argv} {
+
	global autosetup define
+

+
	# There are 3 potential directories involved:
+
	# 1. The directory containing autosetup (this script)
+
	# 2. The directory containing auto.def
+
	# 3. The current directory
+

+
	# From this we need to determine:
+
	# a. The path to this script (and related support files)
+
	# b. The path to auto.def
+
	# c. The build directory, where output files are created
+

+
	# This is also complicated by the fact that autosetup may
+
	# have been run via the configure wrapper ([getenv WRAPPER] is set)
+

+
	# Here are the rules.
+
	# a. This script is $::argv0
+
	#    => dir, prog, exe, libdir
+
	# b. auto.def is in the directory containing the configure wrapper,
+
	#    otherwise it is in the current directory.
+
	#    => srcdir, autodef
+
	# c. The build directory is the current directory
+
	#    => builddir, [pwd]
+

+
	# 'misc' is needed before we can do anything, so set a temporary libdir
+
	# in case this is the development version
+
	set autosetup(libdir) [file dirname $::argv0]/lib
+
	use misc
+

+
	# (a)
+
	set autosetup(dir) [realdir [file dirname [realpath $::argv0]]]
+
	set autosetup(prog) [file join $autosetup(dir) [file tail $::argv0]]
+
	set autosetup(exe) [getenv WRAPPER $autosetup(prog)]
+
	if {$autosetup(installed)} {
+
		set autosetup(libdir) $autosetup(dir)
+
	} else {
+
		set autosetup(libdir) [file join $autosetup(dir) lib]
+
	}
+
	autosetup_add_dep $autosetup(prog)
+

+
	# (b)
+
	if {[getenv WRAPPER ""] eq ""} {
+
		# Invoked directly
+
		set autosetup(srcdir) [pwd]
+
	} else {
+
		# Invoked via the configure wrapper
+
		set autosetup(srcdir) [file-normalize [file dirname $autosetup(exe)]]
+
	}
+
	set autosetup(autodef) [relative-path $autosetup(srcdir)/auto.def]
+

+
	# (c)
+
	set autosetup(builddir) [pwd]
+

+
	set autosetup(argv) $argv
+
	set autosetup(cmdline) {}
+
	# options is a list of known options
+
	set autosetup(options) {}
+
	# optset is a dictionary of option values set by the user based on getopt
+
	set autosetup(optset) {}
+
	# optdefault is a dictionary of default values
+
	set autosetup(optdefault) {}
+
	# options-defaults is a dictionary of overrides for default values for options
+
	set autosetup(options-defaults) {}
+
	set autosetup(optionhelp) {}
+
	set autosetup(showhelp) 0
+

+
	# Parse options
+
	use getopt
+

+
	# At the is point we don't know what is a valid option
+
	# We simply parse anything that looks like an option
+
	set autosetup(getopt) [getopt argv]
+

+
	#"=Core Options:"
+
	options-add {
+
		help:=local  => "display help and options. Optionally specify a module name, such as --help=system"
+
		licence license => "display the autosetup license"
+
		version      => "display the version of autosetup"
+
		ref:=text manual:=text
+
		reference:=text => "display the autosetup command reference. 'text', 'wiki', 'asciidoc' or 'markdown'"
+
		debug        => "display debugging output as autosetup runs"
+
		install:=.   => "install autosetup to the current or given directory"
+
	}
+
	if {$autosetup(installed)} {
+
		# hidden options so we can produce a nice error
+
		options-add {
+
			sysinstall:path
+
		}
+
	} else {
+
		options-add {
+
			sysinstall:path  => "install standalone autosetup to the given directory (e.g.: /usr/local)"
+
		}
+
	}
+
	options-add {
+
		force init:=help   => "create initial auto.def, etc.  Use --init=help for known types"
+
		# Undocumented options
+
		option-checking=1
+
		nopager
+
		quiet
+
		timing
+
		conf:
+
	}
+

+
	if {[opt-bool version]} {
+
		puts $autosetup(version)
+
		exit 0
+
	}
+

+
	# autosetup --conf=alternate-auto.def
+
	if {[opt-str conf o]} {
+
		set autosetup(autodef) $o
+
	}
+

+
	# Debugging output (set this early)
+
	incr autosetup(debug) [opt-bool debug]
+
	incr autosetup(force) [opt-bool force]
+
	incr autosetup(msg-quiet) [opt-bool quiet]
+
	incr autosetup(msg-timing) [opt-bool timing]
+

+
	# If the local module exists, source it now to allow for
+
	# project-local customisations
+
	if {[file exists $autosetup(libdir)/local.tcl]} {
+
		use local
+
	}
+

+
	# Now any auto-load modules
+
	autosetup_load_auto_modules
+

+
	if {[opt-str help o]} {
+
		incr autosetup(showhelp)
+
		use help
+
		autosetup_help $o
+
	}
+

+
	if {[opt-bool licence license]} {
+
		use help
+
		autosetup_show_license
+
		exit 0
+
	}
+

+
	if {[opt-str {manual ref reference} o]} {
+
		use help
+
		autosetup_reference $o
+
	}
+

+
	# Allow combining --install and --init
+
	set earlyexit 0
+
	if {[opt-str install o]} {
+
		use install
+
		autosetup_install $o
+
		incr earlyexit
+
	}
+

+
	if {[opt-str init o]} {
+
		use init
+
		autosetup_init $o
+
		incr earlyexit
+
	}
+

+
	if {$earlyexit} {
+
		exit 0
+
	}
+
	if {[opt-str sysinstall o]} {
+
		use install
+
		autosetup_install $o 1
+
		exit 0
+
	}
+

+
	if {![file exists $autosetup(autodef)]} {
+
		# Check for invalid option first
+
		options {}
+
		user-error "No auto.def found in \"$autosetup(srcdir)\" (use [file tail $::autosetup(exe)] --init to create one)"
+
	}
+

+
	# Parse extra arguments into autosetup(cmdline)
+
	foreach arg $argv {
+
		if {[regexp {([^=]*)=(.*)} $arg -> n v]} {
+
			dict set autosetup(cmdline) $n $v
+
			define $n $v
+
		} else {
+
			user-error "Unexpected parameter: $arg"
+
		}
+
	}
+

+
	autosetup_add_dep $autosetup(autodef)
+

+
	define CONFIGURE_OPTS ""
+
	foreach arg $autosetup(argv) {
+
		define-append CONFIGURE_OPTS [quote-if-needed $arg]
+
	}
+
	define AUTOREMAKE [file-normalize $autosetup(exe)]
+
	define-append AUTOREMAKE [get-define CONFIGURE_OPTS]
+

+

+
	# Log how we were invoked
+
	configlog "Invoked as: [getenv WRAPPER $::argv0] [quote-argv $autosetup(argv)]"
+

+
	# Note that auto.def is *not* loaded in the global scope
+
	source $autosetup(autodef)
+

+
	# Could warn here if options {} was not specified
+

+
	show-notices
+

+
	if {$autosetup(debug)} {
+
		msg-result "Writing all defines to config.log"
+
		configlog "================ defines ======================"
+
		foreach n [lsort [array names define]] {
+
			configlog "define $n $define($n)"
+
		}
+
	}
+

+
	exit 0
+
}
+

+
# @opt-bool ?-nodefault? option ...
+
#
+
# Check each of the named, boolean options and if any have been explicitly enabled
+
# or disabled by the user, return 1 or 0 accordingly.
+
#
+
# If the option was specified more than once, the last value wins.
+
# e.g. With '--enable-foo --disable-foo', '[opt-bool foo]' will return 0
+
#
+
# If no value was specified by the user, returns the default value for the
+
# first option. If '-nodefault' is given, this behaviour changes and
+
# -1 is returned instead.
+
#
+
proc opt-bool {args} {
+
	set nodefault 0
+
	if {[lindex $args 0] eq "-nodefault"} {
+
		set nodefault 1
+
		set args [lrange $args 1 end]
+
	}
+
	option-check-names {*}$args
+

+
	foreach opt $args {
+
		if {[dict exists $::autosetup(optset) $opt]} {
+
			return [dict get $::autosetup(optset) $opt]
+
		}
+
	}
+

+
	if {$nodefault} {
+
		return -1
+
	}
+
	# Default value is the default for the first option
+
	return [dict get $::autosetup(optdefault) [lindex $args 0]]
+
}
+

+
# @opt-val optionlist ?default=""?
+
#
+
# Returns a list containing all the values given for the non-boolean options in '$optionlist'.
+
# There will be one entry in the list for each option given by the user, including if the
+
# same option was used multiple times.
+
#
+
# If no options were set, '$default' is returned (exactly, not as a list).
+
#
+
# Note: For most use cases, 'opt-str' should be preferred.
+
#
+
proc opt-val {names {default ""}} {
+
	option-check-names {*}$names
+

+
	foreach opt $names {
+
		if {[dict exists $::autosetup(optset) $opt]} {
+
			lappend result {*}[dict get $::autosetup(optset) $opt]
+
		}
+
	}
+
	if {[info exists result]} {
+
		return $result
+
	}
+
	return $default
+
}
+

+
# @opt-str optionlist varname ?default?
+
#
+
# Sets '$varname' in the callers scope to the value for one of the given options.
+
#
+
# For the list of options given in '$optionlist', if any value is set for any option,
+
# the option value is taken to be the *last* value of the last option (in the order given).
+
#
+
# If no option was given, and a default was specified with 'options-defaults',
+
# that value is used.
+
#
+
# If no 'options-defaults' value was given and '$default' was given, it is used.
+
#
+
# If none of the above provided a value, no value is set.
+
#
+
# The return value depends on whether '$default' was specified.
+
# If it was, the option value is returned.
+
# If it was not, 1 is returns if a value was set, or 0 if not.
+
#
+
# Typical usage is as follows:
+
#
+
## if {[opt-str {myopt altname} o]} {
+
##     do something with $o
+
## }
+
#
+
# Or:
+
## define myname [opt-str {myopt altname} o "/usr/local"]
+
#
+
proc opt-str {names varname args} {
+
	global autosetup
+

+
	option-check-names {*}$names
+
	upvar $varname value
+

+
	if {[llength $args]} {
+
		# A default was given, so always return the string value of the option
+
		set default [lindex $args 0]
+
		set retopt 1
+
	} else {
+
		# No default, so return 0 or 1 to indicate if a value was found
+
		set retopt 0
+
	}
+

+
	foreach opt $names {
+
		if {[dict exists $::autosetup(optset) $opt]} {
+
			set result [lindex [dict get $::autosetup(optset) $opt] end]
+
		}
+
	}
+

+
	if {![info exists result]} {
+
		# No user-specified value. Has options-defaults been set?
+
		foreach opt $names {
+
			if {[dict exists $::autosetup(options-defaults) $opt]} {
+
				set result [dict get $autosetup(options-defaults) $opt]
+
			}
+
		}
+
	}
+

+
	if {[info exists result]} {
+
		set value $result
+
		if {$retopt} {
+
			return $value
+
		}
+
		return 1
+
	}
+

+
	if {$retopt} {
+
		set value $default
+
		return $value
+
	}
+

+
	return 0
+
}
+

+
proc option-check-names {args} {
+
	foreach o $args {
+
		if {$o ni $::autosetup(options)} {
+
			autosetup-error "Request for undeclared option --$o"
+
		}
+
	}
+
}
+

+
# Parse the option definition in $opts and update
+
# ::autosetup(setoptions) and ::autosetup(optionhelp) appropriately
+
#
+
proc options-add {opts {header ""}} {
+
	global autosetup
+

+
	# First weed out comment lines
+
	set realopts {}
+
	foreach line [split $opts \n] {
+
		if {![string match "#*" [string trimleft $line]]} {
+
			append realopts $line \n
+
		}
+
	}
+
	set opts $realopts
+

+
	for {set i 0} {$i < [llength $opts]} {incr i} {
+
		set opt [lindex $opts $i]
+
		if {[string match =* $opt]} {
+
			# This is a special heading
+
			lappend autosetup(optionhelp) $opt ""
+
			set header {}
+
			continue
+
		}
+
		unset -nocomplain defaultvalue equal value
+

+
		#puts "i=$i, opt=$opt"
+
		regexp {^([^:=]*)(:)?(=)?(.*)$} $opt -> name colon equal value
+
		if {$name in $autosetup(options)} {
+
			autosetup-error "Option $name already specified"
+
		}
+

+
		#puts "$opt => $name $colon $equal $value"
+

+
		# Find the corresponding value in the user options
+
		# and set the default if necessary
+
		if {[string match "-*" $opt]} {
+
			# This is a documentation-only option, like "-C <dir>"
+
			set opthelp $opt
+
		} elseif {$colon eq ""} {
+
			# Boolean option
+
			lappend autosetup(options) $name
+

+
			# Check for override
+
			if {[dict exists $autosetup(options-defaults) $name]} {
+
				# A default was specified with options-defaults, so use it
+
				set value [dict get $autosetup(options-defaults) $name]
+
			}
+

+
			if {$value eq "1"} {
+
				set opthelp "--disable-$name"
+
			} else {
+
				set opthelp "--$name"
+
			}
+

+
			# Set the default
+
			if {$value eq ""} {
+
				set value 0
+
			}
+
			set defaultvalue $value
+
			dict set autosetup(optdefault) $name $defaultvalue
+

+
			if {[dict exists $autosetup(getopt) $name]} {
+
				# The option was specified by the user. Look at the last value.
+
				lassign [lindex [dict get $autosetup(getopt) $name] end] type setvalue
+
				if {$type eq "str"} {
+
					# Can we convert the value to a boolean?
+
					if {$setvalue in {1 enabled yes}} {
+
						set setvalue 1
+
					} elseif {$setvalue in {0 disabled no}} {
+
						set setvalue 0
+
					} else {
+
						user-error "Boolean option $name given as --$name=$setvalue"
+
					}
+
				}
+
				dict set autosetup(optset) $name $setvalue
+
				#puts "Found boolean option --$name=$setvalue"
+
			}
+
		} else {
+
			# String option.
+
			lappend autosetup(options) $name
+

+
			if {$colon eq ":"} {
+
				# Was ":name=default" given?
+
				# If so, set $value to the display name and $defaultvalue to the default
+
				# (This is the preferred way to set a default value for a string option)
+
				if {[regexp {^([^=]+)=(.*)$} $value -> value defaultvalue]} {
+
					dict set autosetup(optdefault) $name $defaultvalue
+
				}
+
			}
+

+
			# Maybe override the default value
+
			if {[dict exists $autosetup(options-defaults) $name]} {
+
				# A default was specified with options-defaults, so use it
+
				set defaultvalue [dict get $autosetup(options-defaults) $name]
+
				dict set autosetup(optdefault) $name $defaultvalue
+
			} elseif {![info exists defaultvalue]} {
+
				# For backward compatiblity, if ":name" was given, use name as both
+
				# the display text and the default value, but only if the user
+
				# specified the option without the value
+
				set defaultvalue $value
+
			}
+

+
			if {$equal eq "="} {
+
				# String option with optional value
+
				set opthelp "--$name?=$value?"
+
			} else {
+
				# String option with required value
+
				set opthelp "--$name=$value"
+
			}
+

+
			# Get the values specified by the user
+
			if {[dict exists $autosetup(getopt) $name]} {
+
				set listvalue {}
+

+
				foreach pair [dict get $autosetup(getopt) $name] {
+
					lassign $pair type setvalue
+
					if {$type eq "bool" && $setvalue} {
+
						if {$equal ne "="} {
+
							user-error "Option --$name requires a value"
+
						}
+
						# If given as a boolean, use the default value
+
						set setvalue $defaultvalue
+
					}
+
					lappend listvalue $setvalue
+
				}
+

+
				#puts "Found string option --$name=$listvalue"
+
				dict set autosetup(optset) $name $listvalue
+
			}
+
		}
+

+
		# Now create the help for this option if appropriate
+
		if {[lindex $opts $i+1] eq "=>"} {
+
			set desc [lindex $opts $i+2]
+
			if {[info exists defaultvalue]} {
+
				set desc [string map [list @default@ $defaultvalue] $desc]
+
			}
+
			#string match \n* $desc
+
			if {$header ne ""} {
+
				lappend autosetup(optionhelp) $header ""
+
				set header ""
+
			}
+
			# A multi-line description
+
			lappend autosetup(optionhelp) $opthelp $desc
+
			incr i 2
+
		}
+
	}
+
}
+

+
# @module-options optionlist
+
#
+
# Like 'options', but used within a module.
+
proc module-options {opts} {
+
	set header ""
+
	if {$::autosetup(showhelp) > 1 && [llength $opts]} {
+
		set header "Module Options:"
+
	}
+
	options-add $opts $header
+

+
	if {$::autosetup(showhelp)} {
+
		# Ensure that the module isn't executed on --help
+
		# We are running under eval or source, so use break
+
		# to prevent further execution
+
		#return -code break -level 2
+
		return -code break
+
	}
+
}
+

+
proc max {a b} {
+
	expr {$a > $b ? $a : $b}
+
}
+

+
proc options-wrap-desc {text length firstprefix nextprefix initial} {
+
	set len $initial
+
	set space $firstprefix
+
	foreach word [split $text] {
+
		set word [string trim $word]
+
		if {$word == ""} {
+
			continue
+
		}
+
		if {$len && [string length $space$word] + $len >= $length} {
+
			puts ""
+
			set len 0
+
			set space $nextprefix
+
		}
+
		incr len [string length $space$word]
+
		puts -nonewline $space$word
+
		set space " "
+
	}
+
	if {$len} {
+
		puts ""
+
	}
+
}
+

+
proc options-show {} {
+
	# Determine the max option width
+
	set max 0
+
	foreach {opt desc} $::autosetup(optionhelp) {
+
		if {[string match =* $opt] || [string match \n* $desc]} {
+
			continue
+
		}
+
		set max [max $max [string length $opt]]
+
	}
+
	set indent [string repeat " " [expr $max+4]]
+
	set cols [getenv COLUMNS 80]
+
	catch {
+
		lassign [exec stty size] rows cols
+
	}
+
	incr cols -1
+
	# Now output
+
	foreach {opt desc} $::autosetup(optionhelp) {
+
		if {[string match =* $opt]} {
+
			puts [string range $opt 1 end]
+
			continue
+
		}
+
		puts -nonewline "  [format %-${max}s $opt]"
+
		if {[string match \n* $desc]} {
+
			puts $desc
+
		} else {
+
			options-wrap-desc [string trim $desc] $cols "  " $indent [expr $max + 2]
+
		}
+
	}
+
}
+

+
# @options optionspec
+
#
+
# Specifies configuration-time options which may be selected by the user
+
# and checked with 'opt-str' and 'opt-bool'. '$optionspec' contains a series
+
# of options specifications separated by newlines, as follows:
+
#
+
# A boolean option is of the form:
+
#
+
## name[=0|1]  => "Description of this boolean option"
+
#
+
# The default is 'name=0', meaning that the option is disabled by default.
+
# If 'name=1' is used to make the option enabled by default, the description should reflect
+
# that with text like "Disable support for ...".
+
#
+
# An argument option (one which takes a parameter) is of the form:
+
#
+
## name:[=]value  => "Description of this option"
+
#
+
# If the 'name:value' form is used, the value must be provided with the option (as '--name=myvalue').
+
# If the 'name:=value' form is used, the value is optional and the given value is used as the default
+
# if it is not provided.
+
#
+
# The description may contain '@default@', in which case it will be replaced with the default
+
# value for the option (taking into account defaults specified with 'options-defaults'.
+
#
+
# Undocumented options are also supported by omitting the '=> description'.
+
# These options are not displayed with '--help' and can be useful for internal options or as aliases.
+
#
+
# For example, '--disable-lfs' is an alias for '--disable=largefile':
+
#
+
## lfs=1 largefile=1 => "Disable large file support"
+
#
+
proc options {optlist} {
+
	# Allow options as a list or args
+
	options-add $optlist "Local Options:"
+

+
	if {$::autosetup(showhelp)} {
+
		options-show
+
		exit 0
+
	}
+

+
	# Check for invalid options
+
	if {[opt-bool option-checking]} {
+
		foreach o [dict keys $::autosetup(getopt)] {
+
			if {$o ni $::autosetup(options)} {
+
				user-error "Unknown option --$o"
+
			}
+
		}
+
	}
+
}
+

+
# @options-defaults dictionary
+
#
+
# Specifies a dictionary of options and a new default value for each of those options.
+
# Use before any 'use' statements in 'auto.def' to change the defaults for
+
# subsequently included modules.
+
proc options-defaults {dict} {
+
	foreach {n v} $dict {
+
		dict set ::autosetup(options-defaults) $n $v
+
	}
+
}
+

+
proc config_guess {} {
+
	if {[file-isexec $::autosetup(dir)/autosetup-config.guess]} {
+
		if {[catch {exec-with-stderr sh $::autosetup(dir)/autosetup-config.guess} alias]} {
+
			user-error $alias
+
		}
+
		return $alias
+
	} else {
+
		configlog "No autosetup-config.guess, so using uname"
+
		string tolower [exec uname -p]-unknown-[exec uname -s][exec uname -r]
+
	}
+
}
+

+
proc config_sub {alias} {
+
	if {[file-isexec $::autosetup(dir)/autosetup-config.sub]} {
+
		if {[catch {exec-with-stderr sh $::autosetup(dir)/autosetup-config.sub $alias} alias]} {
+
			user-error $alias
+
		}
+
	}
+
	return $alias
+
}
+

+
# @define name ?value=1?
+
#
+
# Defines the named variable to the given value.
+
# These (name, value) pairs represent the results of the configuration check
+
# and are available to be subsequently checked, modified and substituted.
+
#
+
proc define {name {value 1}} {
+
	set ::define($name) $value
+
	#dputs "$name <= $value"
+
}
+

+
# @undefine name
+
#
+
# Undefine the named variable.
+
#
+
proc undefine {name} {
+
	unset -nocomplain ::define($name)
+
	#dputs "$name <= <undef>"
+
}
+

+
# @define-append name value ...
+
#
+
# Appends the given value(s) to the given "defined" variable.
+
# If the variable is not defined or empty, it is set to '$value'.
+
# Otherwise the value is appended, separated by a space.
+
# Any extra values are similarly appended.
+
# If any value is already contained in the variable (as a substring) it is omitted.
+
#
+
proc define-append {name args} {
+
	if {[get-define $name ""] ne ""} {
+
		# Avoid duplicates
+
		foreach arg $args {
+
			set found 0
+
			foreach str [split $::define($name) " "] {
+
				if {$str eq $arg} {
+
					incr found
+
				}
+
			}
+
			if {!$found} {
+
				append ::define($name) " " $arg
+
			}
+
		}
+
	} else {
+
		set ::define($name) [join $args]
+
	}
+
	#dputs "$name += [join $args] => $::define($name)"
+
}
+

+
# @get-define name ?default=0?
+
#
+
# Returns the current value of the "defined" variable, or '$default'
+
# if not set.
+
#
+
proc get-define {name {default 0}} {
+
	if {[info exists ::define($name)]} {
+
		#dputs "$name => $::define($name)"
+
		return $::define($name)
+
	}
+
	#dputs "$name => $default"
+
	return $default
+
}
+

+
# @is-defined name
+
#
+
# Returns 1 if the given variable is defined.
+
#
+
proc is-defined {name} {
+
	info exists ::define($name)
+
}
+

+
# @all-defines
+
#
+
# Returns a dictionary (name, value list) of all defined variables.
+
#
+
# This is suitable for use with 'dict', 'array set' or 'foreach'
+
# and allows for arbitrary processing of the defined variables.
+
#
+
proc all-defines {} {
+
	array get ::define
+
}
+

+

+
# @get-env name default
+
#
+
# If '$name' was specified on the command line, return it.
+
# Otherwise if '$name' was set in the environment, return it.
+
# Otherwise return '$default'.
+
#
+
proc get-env {name default} {
+
	if {[dict exists $::autosetup(cmdline) $name]} {
+
		return [dict get $::autosetup(cmdline) $name]
+
	}
+
	getenv $name $default
+
}
+

+
# @env-is-set name
+
#
+
# Returns 1 if '$name' was specified on the command line or in the environment.
+
# Note that an empty environment variable is not considered to be set.
+
#
+
proc env-is-set {name} {
+
	if {[dict exists $::autosetup(cmdline) $name]} {
+
		return 1
+
	}
+
	if {[getenv $name ""] ne ""} {
+
		return 1
+
	}
+
	return 0
+
}
+

+
# @readfile filename ?default=""?
+
#
+
# Return the contents of the file, without the trailing newline.
+
# If the file doesn't exist or can't be read, returns '$default'.
+
#
+
proc readfile {filename {default_value ""}} {
+
	set result $default_value
+
	catch {
+
		set f [open $filename]
+
		set result [read -nonewline $f]
+
		close $f
+
	}
+
	return $result
+
}
+

+
# @writefile filename value
+
#
+
# Creates the given file containing '$value'.
+
# Does not add an extra newline.
+
#
+
proc writefile {filename value} {
+
	set f [open $filename w]
+
	puts -nonewline $f $value
+
	close $f
+
}
+

+
proc quote-if-needed {str} {
+
	if {[string match {*[\" ]*} $str]} {
+
		return \"[string map [list \" \\" \\ \\\\] $str]\"
+
	}
+
	return $str
+
}
+

+
proc quote-argv {argv} {
+
	set args {}
+
	foreach arg $argv {
+
		lappend args [quote-if-needed $arg]
+
	}
+
	join $args
+
}
+

+
# @list-non-empty list
+
#
+
# Returns a copy of the given list with empty elements removed
+
proc list-non-empty {list} {
+
	set result {}
+
	foreach p $list {
+
		if {$p ne ""} {
+
			lappend result $p
+
		}
+
	}
+
	return $result
+
}
+

+
# @find-executable-path name
+
#
+
# Searches the path for an executable with the given name.
+
# Note that the name may include some parameters, e.g. 'cc -mbig-endian',
+
# in which case the parameters are ignored.
+
# The full path to the executable if found, or "" if not found.
+
# Returns 1 if found, or 0 if not.
+
#
+
proc find-executable-path {name} {
+
	# Ignore any parameters
+
	set name [lindex $name 0]
+
	# The empty string is never a valid executable
+
	if {$name ne ""} {
+
		foreach p [split-path] {
+
			dputs "Looking for $name in $p"
+
			set exec [file join $p $name]
+
			if {[file-isexec $exec]} {
+
				dputs "Found $name -> $exec"
+
				return $exec
+
			}
+
		}
+
	}
+
	return {}
+
}
+

+
# @find-executable name
+
#
+
# Searches the path for an executable with the given name.
+
# Note that the name may include some parameters, e.g. 'cc -mbig-endian',
+
# in which case the parameters are ignored.
+
# Returns 1 if found, or 0 if not.
+
#
+
proc find-executable {name} {
+
	if {[find-executable-path $name] eq {}} {
+
		return 0
+
	}
+
	return 1
+
}
+

+
# @find-an-executable ?-required? name ...
+
#
+
# Given a list of possible executable names,
+
# searches for one of these on the path.
+
#
+
# Returns the name found, or "" if none found.
+
# If the first parameter is '-required', an error is generated
+
# if no executable is found.
+
#
+
proc find-an-executable {args} {
+
	set required 0
+
	if {[lindex $args 0] eq "-required"} {
+
		set args [lrange $args 1 end]
+
		incr required
+
	}
+
	foreach name $args {
+
		if {[find-executable $name]} {
+
			return $name
+
		}
+
	}
+
	if {$required} {
+
		if {[llength $args] == 1} {
+
			user-error "failed to find: [join $args]"
+
		} else {
+
			user-error "failed to find one of: [join $args]"
+
		}
+
	}
+
	return ""
+
}
+

+
# @configlog msg
+
#
+
# Writes the given message to the configuration log, 'config.log'.
+
#
+
proc configlog {msg} {
+
	if {![info exists ::autosetup(logfh)]} {
+
		set ::autosetup(logfh) [open config.log w]
+
	}
+
	puts $::autosetup(logfh) $msg
+
}
+

+
# @msg-checking msg
+
#
+
# Writes the message with no newline to stdout.
+
#
+
proc msg-checking {msg} {
+
	if {$::autosetup(msg-quiet) == 0} {
+
		maybe-show-timestamp
+
		puts -nonewline $msg
+
		set ::autosetup(msg-checking) 1
+
	}
+
}
+

+
# @msg-result msg
+
#
+
# Writes the message to stdout.
+
#
+
proc msg-result {msg} {
+
	if {$::autosetup(msg-quiet) == 0} {
+
		maybe-show-timestamp
+
		puts $msg
+
		set ::autosetup(msg-checking) 0
+
		show-notices
+
	}
+
}
+

+
# @msg-quiet command ...
+
#
+
# 'msg-quiet' evaluates it's arguments as a command with output
+
# from 'msg-checking' and 'msg-result' suppressed.
+
#
+
# This is useful if a check needs to run a subcheck which isn't
+
# of interest to the user.
+
proc msg-quiet {args} {
+
	incr ::autosetup(msg-quiet)
+
	set rc [uplevel 1 $args]
+
	incr ::autosetup(msg-quiet) -1
+
	return $rc
+
}
+

+
# Will be overridden by 'use misc'
+
proc error-stacktrace {msg} {
+
	return $msg
+
}
+

+
proc error-location {msg} {
+
	return $msg
+
}
+

+
##################################################################
+
#
+
# Debugging output
+
#
+
proc dputs {msg} {
+
	if {$::autosetup(debug)} {
+
		puts $msg
+
	}
+
}
+

+
##################################################################
+
#
+
# User and system warnings and errors
+
#
+
# Usage errors such as wrong command line options
+

+
# @user-error msg
+
#
+
# Indicate incorrect usage to the user, including if required components
+
# or features are not found.
+
# 'autosetup' exits with a non-zero return code.
+
#
+
proc user-error {msg} {
+
	show-notices
+
	puts stderr "Error: $msg"
+
	puts stderr "Try: '[file tail $::autosetup(exe)] --help' for options"
+
	exit 1
+
}
+

+
# @user-notice msg
+
#
+
# Output the given message to stderr.
+
#
+
proc user-notice {msg} {
+
	lappend ::autosetup(notices) $msg
+
}
+

+
# Incorrect usage in the auto.def file. Identify the location.
+
proc autosetup-error {msg} {
+
	autosetup-full-error [error-location $msg]
+
}
+

+
# Like autosetup-error, except $msg is the full error message.
+
proc autosetup-full-error {msg} {
+
	show-notices
+
	puts stderr $msg
+
	exit 1
+
}
+

+
proc show-notices {} {
+
	if {$::autosetup(msg-checking)} {
+
		puts ""
+
		set ::autosetup(msg-checking) 0
+
	}
+
	flush stdout
+
	if {[info exists ::autosetup(notices)]} {
+
		puts stderr [join $::autosetup(notices) \n]
+
		unset ::autosetup(notices)
+
	}
+
}
+

+
proc maybe-show-timestamp {} {
+
	if {$::autosetup(msg-timing) && $::autosetup(msg-checking) == 0} {
+
		puts -nonewline [format {[%6.2f] } [expr {([clock millis] - $::autosetup(start)) % 10000 / 1000.0}]]
+
	}
+
}
+

+
# @autosetup-require-version required
+
#
+
# Checks the current version of 'autosetup' against '$required'.
+
# A fatal error is generated if the current version is less than that required.
+
#
+
proc autosetup-require-version {required} {
+
	use util
+
	if {[compare-versions $::autosetup(version) $required] < 0} {
+
		user-error "autosetup version $required is required, but this is $::autosetup(version)"
+
	}
+
}
+

+
proc autosetup_version {} {
+
	return "autosetup v$::autosetup(version)"
+
}
+

+
##################################################################
+
#
+
# Directory/path handling
+
#
+

+
proc realdir {dir} {
+
	set oldpwd [pwd]
+
	cd $dir
+
	set pwd [pwd]
+
	cd $oldpwd
+
	return $pwd
+
}
+

+
# Follow symlinks until we get to something which is not a symlink
+
proc realpath {path} {
+
	while {1} {
+
		if {[catch {
+
			set path [file readlink $path]
+
		}]} {
+
			# Not a link
+
			break
+
		}
+
	}
+
	return $path
+
}
+

+
# Convert absolute path, $path into a path relative
+
# to the given directory (or the current dir, if not given).
+
#
+
proc relative-path {path {pwd {}}} {
+
	set diff 0
+
	set same 0
+
	set newf {}
+
	set prefix {}
+
	set path [file-normalize $path]
+
	if {$pwd eq ""} {
+
		set pwd [pwd]
+
	} else {
+
		set pwd [file-normalize $pwd]
+
	}
+

+
	if {$path eq $pwd} {
+
		return .
+
	}
+

+
	# Try to make the filename relative to the current dir
+
	foreach p [split $pwd /] f [split $path /] {
+
		if {$p ne $f} {
+
			incr diff
+
		} elseif {!$diff} {
+
			incr same
+
		}
+
		if {$diff} {
+
			if {$p ne ""} {
+
				# Add .. for sibling or parent dir
+
				lappend prefix ..
+
			}
+
			if {$f ne ""} {
+
				lappend newf $f
+
			}
+
		}
+
	}
+
	if {$same == 1 || [llength $prefix] > 3} {
+
		return $path
+
	}
+

+
	file join [join $prefix /] [join $newf /]
+
}
+

+
# Add filename as a dependency to rerun autosetup
+
# The name will be normalised (converted to a full path)
+
#
+
proc autosetup_add_dep {filename} {
+
	lappend ::autosetup(deps) [file-normalize $filename]
+
}
+

+
##################################################################
+
#
+
# Library module support
+
#
+

+
# @use module ...
+
#
+
# Load the given library modules.
+
# e.g. 'use cc cc-shared'
+
#
+
# Note that module 'X' is implemented in either 'autosetup/X.tcl'
+
# or 'autosetup/X/init.tcl'
+
#
+
# The latter form is useful for a complex module which requires additional
+
# support file. In this form, '$::usedir' is set to the module directory
+
# when it is loaded.
+
#
+
proc use {args} {
+
	global autosetup libmodule modsource
+

+
	set dirs [list $autosetup(libdir)]
+
	if {[info exists autosetup(srcdir)]} {
+
		lappend dirs $autosetup(srcdir)/autosetup
+
	}
+
	foreach m $args {
+
		if {[info exists libmodule($m)]} {
+
			continue
+
		}
+
		set libmodule($m) 1
+
		if {[info exists modsource(${m}.tcl)]} {
+
			automf_load eval $modsource(${m}.tcl)
+
		} else {
+
			set locs [list ${m}.tcl ${m}/init.tcl]
+
			set found 0
+
			foreach dir $dirs {
+
				foreach loc $locs {
+
					set source $dir/$loc
+
					if {[file exists $source]} {
+
						incr found
+
						break
+
					}
+
				}
+
				if {$found} {
+
					break
+
				}
+
			}
+
			if {$found} {
+
				# For the convenience of the "use" source, point to the directory
+
				# it is being loaded from
+
				set ::usedir [file dirname $source]
+
				automf_load source $source
+
				autosetup_add_dep $source
+
			} else {
+
				autosetup-error "use: No such module: $m"
+
			}
+
		}
+
	}
+
}
+

+
proc autosetup_load_auto_modules {} {
+
	global autosetup modsource
+
	# First load any embedded auto modules
+
	foreach mod [array names modsource *.auto] {
+
		automf_load eval $modsource($mod)
+
	}
+
	# Now any external auto modules
+
	foreach file [glob -nocomplain $autosetup(libdir)/*.auto $autosetup(libdir)/*/*.auto] {
+
		automf_load source $file
+
	}
+
}
+

+
# Load module source in the global scope by executing the given command
+
proc automf_load {args} {
+
	if {[catch [list uplevel #0 $args] msg opts] ni {0 2 3}} {
+
		autosetup-full-error [error-dump $msg $opts $::autosetup(debug)]
+
	}
+
}
+

+
# Initial settings
+
set autosetup(exe) $::argv0
+
set autosetup(istcl) 1
+
set autosetup(start) [clock millis]
+
set autosetup(installed) 0
+
set autosetup(sysinstall) 0
+
set autosetup(msg-checking) 0
+
set autosetup(msg-quiet) 0
+
set autosetup(inittypes) {}
+

+
# Embedded modules are inserted below here
+
set autosetup(installed) 1
+
set autosetup(sysinstall) 0
+
# ----- @module asciidoc-formatting.tcl -----
+

+
set modsource(asciidoc-formatting.tcl) {
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module which provides text formatting
+
# asciidoc format
+

+
use formatting
+

+
proc para {text} {
+
    regsub -all "\[ \t\n\]+" [string trim $text] " "
+
}
+
proc title {text} {
+
    underline [para $text] =
+
    nl
+
}
+
proc p {text} {
+
    puts [para $text]
+
    nl
+
}
+
proc code {text} {
+
    foreach line [parse_code_block $text] {
+
        puts "    $line"
+
    }
+
    nl
+
}
+
proc codelines {lines} {
+
    foreach line $lines {
+
        puts "    $line"
+
    }
+
    nl
+
}
+
proc nl {} {
+
    puts ""
+
}
+
proc underline {text char} {
+
    regexp "^(\[ \t\]*)(.*)" $text -> indent words
+
    puts $text
+
    puts $indent[string repeat $char [string length $words]]
+
}
+
proc section {text} {
+
    underline "[para $text]" -
+
    nl
+
}
+
proc subsection {text} {
+
    underline "$text" ~
+
    nl
+
}
+
proc bullet {text} {
+
    puts "* [para $text]"
+
}
+
proc indent {text} {
+
    puts " :: "
+
    puts [para $text]
+
}
+
proc defn {first args} {
+
    set sep ""
+
    if {$first ne ""} {
+
        puts "${first}::"
+
    } else {
+
        puts " :: "
+
    }
+
    set defn [string trim [join $args \n]]
+
    regsub -all "\n\n" $defn "\n ::\n" defn
+
    puts $defn
+
}
+
}
+

+
# ----- @module formatting.tcl -----
+

+
set modsource(formatting.tcl) {
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module which provides common text formatting
+

+
# This is designed for documenation which looks like:
+
# code {...}
+
# or
+
# code {
+
#    ...
+
#    ...
+
# }
+
# In the second case, we need to work out the indenting
+
# and strip it from all lines but preserve the remaining indenting.
+
# Note that all lines need to be indented with the same initial
+
# spaces/tabs.
+
#
+
# Returns a list of lines with the indenting removed.
+
#
+
proc parse_code_block {text} {
+
    # If the text begins with newline, take the following text,
+
    # otherwise just return the original
+
    if {![regexp "^\n(.*)" $text -> text]} {
+
        return [list [string trim $text]]
+
    }
+

+
    # And trip spaces off the end
+
    set text [string trimright $text]
+

+
    set min 100
+
    # Examine each line to determine the minimum indent
+
    foreach line [split $text \n] {
+
        if {$line eq ""} {
+
            # Ignore empty lines for the indent calculation
+
            continue
+
        }
+
        regexp "^(\[ \t\]*)" $line -> indent
+
        set len [string length $indent]
+
        if {$len < $min} {
+
            set min $len
+
        }
+
    }
+

+
    # Now make a list of lines with this indent removed
+
    set lines {}
+
    foreach line [split $text \n] {
+
        lappend lines [string range $line $min end]
+
    }
+

+
    # Return the result
+
    return $lines
+
}
+
}
+

+
# ----- @module getopt.tcl -----
+

+
set modsource(getopt.tcl) {
+
# Copyright (c) 2006 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Simple getopt module
+

+
# Parse everything out of the argv list which looks like an option
+
# Everything which doesn't look like an option, or is after --, is left unchanged
+
# Understands --enable-xxx as a synonym for --xxx to enable the boolean option xxx.
+
# Understands --disable-xxx to disable the boolean option xxx.
+
#
+
# The returned value is a dictionary keyed by option name
+
# Each value is a list of {type value} ... where type is "bool" or "str".
+
# The value for a boolean option is 0 or 1. The value of a string option is the value given.
+
proc getopt {argvname} {
+
	upvar $argvname argv
+
	set nargv {}
+

+
	set opts {}
+

+
	for {set i 0} {$i < [llength $argv]} {incr i} {
+
		set arg [lindex $argv $i]
+

+
		#dputs arg=$arg
+

+
		if {$arg eq "--"} {
+
			# End of options
+
			incr i
+
			lappend nargv {*}[lrange $argv $i end]
+
			break
+
		}
+

+
		if {[regexp {^--([^=][^=]+)=(.*)$} $arg -> name value]} {
+
			# --name=value
+
			dict lappend opts $name [list str $value]
+
		} elseif {[regexp {^--(enable-|disable-)?([^=]*)$} $arg -> prefix name]} {
+
			if {$prefix in {enable- ""}} {
+
				set value 1
+
			} else {
+
				set value 0
+
			}
+
			dict lappend opts $name [list bool $value]
+
		} else {
+
			lappend nargv $arg
+
		}
+
	}
+

+
	#puts "getopt: argv=[join $argv] => [join $nargv]"
+
	#array set getopt $opts
+
	#parray getopt
+

+
	set argv $nargv
+

+
	return $opts
+
}
+
}
+

+
# ----- @module help.tcl -----
+

+
set modsource(help.tcl) {
+
# Copyright (c) 2010 WorkWare Systems http://workware.net.au/
+
# All rights reserved
+

+
# Module which provides usage, help and the command reference
+

+
proc autosetup_help {what} {
+
    use_pager
+

+
    puts "Usage: [file tail $::autosetup(exe)] \[options\] \[settings\]\n"
+
    puts "This is [autosetup_version], a build environment \"autoconfigurator\""
+
    puts "See the documentation online at http://msteveb.github.com/autosetup/\n"
+

+
    if {$what eq "local"} {
+
        if {[file exists $::autosetup(autodef)]} {
+
            # This relies on auto.def having a call to 'options'
+
            # which will display options and quit
+
            source $::autosetup(autodef)
+
        } else {
+
            options-show
+
        }
+
    } else {
+
        incr ::autosetup(showhelp)
+
        if {[catch {use $what}]} {
+
            user-error "Unknown module: $what"
+
        } else {
+
            options-show
+
        }
+
    }
+
    exit 0
+
}
+

+
proc autosetup_show_license {} {
+
    global modsource autosetup
+
    use_pager
+

+
    if {[info exists modsource(LICENSE)]} {
+
        puts $modsource(LICENSE)
+
        return
+
    }
+
    foreach dir [list $autosetup(libdir) $autosetup(srcdir)] {
+
        set path [file join $dir LICENSE]
+
        if {[file exists $path]} {
+
            puts [readfile $path]
+
            return
+
        }
+
    }
+
    puts "LICENSE not found"
+
}
+

+
# If not already paged and stdout is a tty, pipe the output through the pager
+
# This is done by reinvoking autosetup with --nopager added
+
proc use_pager {} {
+
    if {![opt-bool nopager] && [getenv PAGER ""] ne "" && [isatty? stdin] && [isatty? stdout]} {
+
        if {[catch {
+
            exec [info nameofexecutable] $::argv0 --nopager {*}$::argv |& {*}[getenv PAGER] >@stdout <@stdin 2>@stderr
+
        } msg opts] == 1} {
+
            if {[dict get $opts -errorcode] eq "NONE"} {
+
                # an internal/exec error
+
                puts stderr $msg
+
                exit 1
+
            }
+
        }
+
        exit 0
+
    }
+
}
+

+
# Outputs the autosetup references in one of several formats
+
proc autosetup_reference {{type text}} {
+

+
    use_pager
+

+
    switch -glob -- $type {
+
        wiki {use wiki-formatting}
+
        ascii* {use asciidoc-formatting}
+
        md - markdown {use markdown-formatting}
+
        default {use text-formatting}
+
    }
+

+
    title "[autosetup_version] -- Command Reference"
+

+
    section {Introduction}
+

+
    p {
+
        See http://msteveb.github.com/autosetup/ for the online documentation for 'autosetup'
+
    }
+

+
    p {
+
        'autosetup' provides a number of built-in commands which
+
        are documented below. These may be used from 'auto.def' to test
+
        for features, define variables, create files from templates and
+
        other similar actions.
+
    }
+

+
    automf_command_reference
+

+
    exit 0
+
}
+

+
proc autosetup_output_block {type lines} {
+
    if {[llength $lines]} {
+
        switch $type {
+
            section {
+
                section $lines
+
            }
+
            subsection {
+
                subsection $lines
+
            }
+
            code {
+
                codelines $lines
+
            }
+
            p {
+
                p [join $lines]
+
            }
+
            list {
+
                foreach line $lines {
+
                    bullet $line
+
                }
+
                nl
+
            }
+
        }
+
    }
+
}
+

+
# Generate a command reference from inline documentation
+
proc automf_command_reference {} {
+
    lappend files $::autosetup(prog)
+
    lappend files {*}[lsort [glob -nocomplain $::autosetup(libdir)/*.tcl]]
+

+
    # We want to process all non-module files before module files
+
    # and then modules in alphabetical order.
+
    # So examine all files and extract docs into doc($modulename) and doc(_core_)
+
    #
+
    # Each entry is a list of {type data} where $type is one of: section, subsection, code, list, p
+
    # and $data is a string for section, subsection or a list of text lines for other types.
+

+
    # XXX: Should commands be in alphabetical order too? Currently they are in file order.
+

+
    set doc(_core_) {}
+
    lappend doc(_core_) [list section "Core Commands"]
+

+
    foreach file $files {
+
        set modulename [file rootname [file tail $file]]
+
        set current _core_
+
        set f [open $file]
+
        while {![eof $f]} {
+
            set line [gets $f]
+

+
            # Find embedded module names
+
            if {[regexp {^#.*@module ([^ ]*)} $line -> modulename]} {
+
                continue
+
            }
+

+
            # Find lines starting with "# @*" and continuing through the remaining comment lines
+
            if {![regexp {^# @(.*)} $line -> cmd]} {
+
                continue
+
            }
+

+
            # Synopsis or command?
+
            if {$cmd eq "synopsis:"} {
+
                set current $modulename
+
                lappend doc($current) [list section "Module: $modulename"]
+
            } else {
+
                lappend doc($current) [list subsection $cmd]
+
            }
+

+
            set lines {}
+
            set type p
+

+
            # Now the description
+
            while {![eof $f]} {
+
                set line [gets $f]
+

+
                if {![regexp {^#(#)? ?(.*)} $line -> hash cmd]} {
+
                    break
+
                }
+
                if {$hash eq "#"} {
+
                    set t code
+
                } elseif {[regexp {^- (.*)} $cmd -> cmd]} {
+
                    set t list
+
                } else {
+
                    set t p
+
                }
+

+
                #puts "hash=$hash, oldhash=$oldhash, lines=[llength $lines], cmd=$cmd"
+

+
                if {$t ne $type || $cmd eq ""} {
+
                    # Finish the current block
+
                    lappend doc($current) [list $type $lines]
+
                    set lines {}
+
                    set type $t
+
                }
+
                if {$cmd ne ""} {
+
                    lappend lines $cmd
+
                }
+
            }
+

+
            lappend doc($current) [list $type $lines]
+
        }
+
        close $f
+
    }
+

+
    # Now format and output the results
+

+
    # _core_ will sort first
+
    foreach module [lsort [array names doc]] {
+
        foreach item $doc($module) {
+
            autosetup_output_block {*}$item
+
        }
+
    }
+
}
+
}
+

+
# ----- @module init.tcl -----
+

+
set modsource(init.tcl) {
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module to help create auto.def and configure
+

+
proc autosetup_init {type} {
+
	set help 0
+
	if {$type in {? help}} {
+
		incr help
+
	} elseif {![dict exists $::autosetup(inittypes) $type]} {
+
		puts "Unknown type, --init=$type"
+
		incr help
+
	}
+
	if {$help} {
+
		puts "Use one of the following types (e.g. --init=make)\n"
+
		foreach type [lsort [dict keys $::autosetup(inittypes)]] {
+
			lassign [dict get $::autosetup(inittypes) $type] desc
+
			# XXX: Use the options-show code to wrap the description
+
			puts [format "%-10s %s" $type $desc]
+
		}
+
		return
+
	}
+
	lassign [dict get $::autosetup(inittypes) $type] desc script
+

+
	puts "Initialising $type: $desc\n"
+

+
	# All initialisations happens in the top level srcdir
+
	cd $::autosetup(srcdir)
+

+
	uplevel #0 $script
+
}
+

+
proc autosetup_add_init_type {type desc script} {
+
	dict set ::autosetup(inittypes) $type [list $desc $script]
+
}
+

+
# This is for in creating build-system init scripts
+
#
+
# If the file doesn't exist, create it containing $contents
+
# If the file does exist, only overwrite if --force is specified.
+
#
+
proc autosetup_check_create {filename contents} {
+
	if {[file exists $filename]} {
+
		if {!$::autosetup(force)} {
+
			puts "I see $filename already exists."
+
			return
+
		} else {
+
			puts "I will overwrite the existing $filename because you used --force."
+
		}
+
	} else {
+
		puts "I don't see $filename, so I will create it."
+
	}
+
	writefile $filename $contents
+
}
+
}
+

+
# ----- @module install.tcl -----
+

+
set modsource(install.tcl) {
+
# Copyright (c) 2006-2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module which can install autosetup
+

+
# autosetup(installed)=1 means that autosetup is not running from source
+
# autosetup(sysinstall)=1 means that autosetup is running from a sysinstall verion
+
# shared=1 means that we are trying to do a sysinstall. This is only possible from the development source.
+

+
proc autosetup_install {dir {shared 0}} {
+
	global autosetup
+
	if {$shared} {
+
		if {$autosetup(installed) || $autosetup(sysinstall)} {
+
			user-error "Can only --sysinstall from development sources"
+
		}
+
	} elseif {$autosetup(installed) && !$autosetup(sysinstall)} {
+
		user-error "Can't --install from project install"
+
	}
+

+
	if {$autosetup(sysinstall)} {
+
		# This is the sysinstall version, so install just uses references
+
		cd $dir
+

+
		puts "[autosetup_version] creating configure to use system-installed autosetup"
+
		autosetup_create_configure 1
+
		puts "Creating autosetup/README.autosetup"
+
		file mkdir autosetup
+
		autosetup_install_readme autosetup/README.autosetup 1
+
		return
+
	}
+

+
	if {[catch {
+
		if {$shared} {
+
			set target $dir/bin/autosetup
+
			set installedas $target
+
		} else {
+
			if {$dir eq "."} {
+
				set installedas autosetup
+
			} else {
+
				set installedas $dir/autosetup
+
			}
+
			cd $dir
+
			file mkdir autosetup
+
			set target autosetup/autosetup
+
		}
+
		set targetdir [file dirname $target]
+
		file mkdir $targetdir
+

+
		set f [open $target w]
+

+
		set publicmodules {}
+

+
		# First the main script, but only up until "CUT HERE"
+
		set in [open $autosetup(dir)/autosetup]
+
		while {[gets $in buf] >= 0} {
+
			if {$buf ne "##-- CUT HERE --##"} {
+
				puts $f $buf
+
				continue
+
			}
+

+
			# Insert the static modules here
+
			# i.e. those which don't contain @synopsis:
+
			# All modules are inserted if $shared is set
+
			puts $f "set autosetup(installed) 1"
+
			puts $f "set autosetup(sysinstall) $shared"
+
			foreach file [lsort [glob $autosetup(libdir)/*.{tcl,auto}]] {
+
				set modname [file tail $file]
+
				set ext [file ext $modname]
+
				set buf [readfile $file]
+
				if {!$shared} {
+
					if {$ext eq ".auto" || [string match "*\n# @synopsis:*" $buf]} {
+
						lappend publicmodules $file
+
						continue
+
					}
+
				}
+
				dputs "install: importing lib/[file tail $file]"
+
				puts $f "# ----- @module $modname -----"
+
				puts $f "\nset modsource($modname) \{"
+
				puts $f $buf
+
				puts $f "\}\n"
+
			}
+
			if {$shared} {
+
				foreach {srcname destname} [list $autosetup(libdir)/README.autosetup-lib README.autosetup \
+
						$autosetup(srcdir)/LICENSE LICENSE] {
+
					dputs "install: importing $srcname as $destname"
+
					puts $f "\nset modsource($destname) \\\n[list [readfile $srcname]\n]\n"
+
				}
+
			}
+
		}
+
		close $in
+
		close $f
+
		catch {exec chmod 755 $target}
+

+
		set installfiles {autosetup-config.guess autosetup-config.sub autosetup-test-tclsh}
+
		set removefiles {}
+

+
		if {!$shared} {
+
			autosetup_install_readme $targetdir/README.autosetup 0
+

+
			# Install public modules
+
			foreach file $publicmodules {
+
				set tail [file tail $file]
+
				autosetup_install_file $file $targetdir/$tail
+
			}
+
			lappend installfiles jimsh0.c autosetup-find-tclsh LICENSE
+
			lappend removefiles config.guess config.sub test-tclsh find-tclsh
+
		} else {
+
			lappend installfiles {sys-find-tclsh autosetup-find-tclsh}
+
		}
+

+
		# Install support files
+
		foreach fileinfo $installfiles {
+
			if {[llength $fileinfo] == 2} {
+
				lassign $fileinfo source dest
+
			} else {
+
				lassign $fileinfo source
+
				set dest $source
+
			}
+
			autosetup_install_file $autosetup(dir)/$source $targetdir/$dest
+
		}
+

+
		# Remove obsolete files
+
		foreach file $removefiles {
+
			if {[file exists $targetdir/$file]} {
+
				file delete $targetdir/$file
+
			}
+
		}
+
	} error]} {
+
		user-error "Failed to install autosetup: $error"
+
	}
+
	if {$shared} {
+
		set type "system"
+
	} else {
+
		set type "local"
+
	}
+
	puts "Installed $type [autosetup_version] to $installedas"
+

+
	if {!$shared} {
+
		# Now create 'configure' if necessary
+
		autosetup_create_configure 0
+
	}
+
}
+

+
proc autosetup_create_configure {shared} {
+
	if {[file exists configure]} {
+
		if {!$::autosetup(force)} {
+
			# Could this be an autosetup configure?
+
			if {![string match "*\nWRAPPER=*" [readfile configure]]} {
+
				puts "I see configure, but not created by autosetup, so I won't overwrite it."
+
				puts "Remove it or use --force to overwrite."
+
				return
+
			}
+
		} else {
+
			puts "I will overwrite the existing configure because you used --force."
+
		}
+
	} else {
+
		puts "I don't see configure, so I will create it."
+
	}
+
	if {$shared} {
+
		writefile configure \
+
{#!/bin/sh
+
WRAPPER="$0"; export WRAPPER; "autosetup" "$@"
+
}
+
	} else {
+
		writefile configure \
+
{#!/bin/sh
+
dir="`dirname "$0"`/autosetup"
+
WRAPPER="$0"; export WRAPPER; exec "`$dir/autosetup-find-tclsh`" "$dir/autosetup" "$@"
+
}
+
	}
+
	catch {exec chmod 755 configure}
+
}
+

+
# Append the contents of $file to filehandle $f
+
proc autosetup_install_append {f file} {
+
	dputs "install: include $file"
+
	set in [open $file]
+
	puts $f [read $in]
+
	close $in
+
}
+

+
proc autosetup_install_file {source target} {
+
	dputs "install: $source => $target"
+
	if {![file exists $source]} {
+
		error "Missing installation file '$source'"
+
	}
+
	writefile $target [readfile $source]\n
+
	# If possible, copy the file mode
+
	file stat $source stat
+
	set mode [format %o [expr {$stat(mode) & 0x1ff}]]
+
	catch {exec chmod $mode $target}
+
}
+

+
proc autosetup_install_readme {target sysinstall} {
+
	set readme "README.autosetup created by [autosetup_version]\n\n"
+
	if {$sysinstall} {
+
		append readme \
+
{This is the autosetup directory for a system install of autosetup.
+
Loadable modules can be added here.
+
}
+
	} else {
+
		append readme \
+
{This is the autosetup directory for a local install of autosetup.
+
It contains autosetup, support files and loadable modules.
+
}
+
}
+

+
	append readme {
+
*.tcl files in this directory are optional modules which
+
can be loaded with the 'use' directive.
+

+
*.auto files in this directory are auto-loaded.
+

+
For more information, see http://msteveb.github.com/autosetup/
+
}
+
	dputs "install: autosetup/README.autosetup"
+
	writefile $target $readme
+
}
+
}
+

+
# ----- @module markdown-formatting.tcl -----
+

+
set modsource(markdown-formatting.tcl) {
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module which provides text formatting
+
# markdown format (kramdown syntax)
+

+
use formatting
+

+
proc para {text} {
+
    regsub -all "\[ \t\n\]+" [string trim $text] " " text
+
    regsub -all {([^a-zA-Z])'([^']*)'} $text {\1**`\2`**} text
+
    regsub -all {^'([^']*)'} $text {**`\1`**} text
+
    regsub -all {(http[^ \t\n]*)} $text {[\1](\1)} text
+
    return $text
+
}
+
proc title {text} {
+
    underline [para $text] =
+
    nl
+
}
+
proc p {text} {
+
    puts [para $text]
+
    nl
+
}
+
proc codelines {lines} {
+
    puts "~~~~~~~~~~~~"
+
    foreach line $lines {
+
        puts $line
+
    }
+
    puts "~~~~~~~~~~~~"
+
    nl
+
}
+
proc code {text} {
+
    puts "~~~~~~~~~~~~"
+
    foreach line [parse_code_block $text] {
+
        puts $line
+
    }
+
    puts "~~~~~~~~~~~~"
+
    nl
+
}
+
proc nl {} {
+
    puts ""
+
}
+
proc underline {text char} {
+
    regexp "^(\[ \t\]*)(.*)" $text -> indent words
+
    puts $text
+
    puts $indent[string repeat $char [string length $words]]
+
}
+
proc section {text} {
+
    underline "[para $text]" -
+
    nl
+
}
+
proc subsection {text} {
+
    puts "### `$text`"
+
    nl
+
}
+
proc bullet {text} {
+
    puts "* [para $text]"
+
}
+
proc defn {first args} {
+
    puts "^"
+
    set defn [string trim [join $args \n]]
+
    if {$first ne ""} {
+
        puts "**${first}**"
+
        puts -nonewline ": "
+
        regsub -all "\n\n" $defn "\n: " defn
+
    }
+
    puts "$defn"
+
}
+
}
+

+
# ----- @module misc.tcl -----
+

+
set modsource(misc.tcl) {
+
# Copyright (c) 2007-2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module containing misc procs useful to modules
+
# Largely for platform compatibility
+

+
set autosetup(istcl) [info exists ::tcl_library]
+
set autosetup(iswin) [string equal windows $tcl_platform(platform)]
+

+
if {$autosetup(iswin)} {
+
	# mingw/windows separates $PATH with semicolons
+
	# and doesn't have an executable bit
+
	proc split-path {} {
+
		split [getenv PATH .] {;}
+
	}
+
	proc file-isexec {exec} {
+
		# Basic test for windows. We ignore .bat
+
		if {[file isfile $exec] || [file isfile $exec.exe]} {
+
			return 1
+
		}
+
		return 0
+
	}
+
} else {
+
	# unix separates $PATH with colons and has and executable bit
+
	proc split-path {} {
+
		split [getenv PATH .] :
+
	}
+
	proc file-isexec {exec} {
+
		file executable $exec
+
	}
+
}
+

+
# Assume that exec can return stdout and stderr
+
proc exec-with-stderr {args} {
+
	exec {*}$args 2>@1
+
}
+

+
if {$autosetup(istcl)} {
+
	# Tcl doesn't have the env command
+
	proc getenv {name args} {
+
		if {[info exists ::env($name)]} {
+
			return $::env($name)
+
		}
+
		if {[llength $args]} {
+
			return [lindex $args 0]
+
		}
+
		return -code error "environment variable \"$name\" does not exist"
+
	}
+
	proc isatty? {channel} {
+
		dict exists [fconfigure $channel] -xchar
+
	}
+
} else {
+
	if {$autosetup(iswin)} {
+
		# On Windows, backslash convert all environment variables
+
		# (Assume that Tcl does this for us)
+
		proc getenv {name args} {
+
			string map {\\ /} [env $name {*}$args]
+
		}
+
	} else {
+
		# Jim on unix is simple
+
		alias getenv env
+
	}
+
	proc isatty? {channel} {
+
		set tty 0
+
		catch {
+
			# isatty is a recent addition to Jim Tcl
+
			set tty [$channel isatty]
+
		}
+
		return $tty
+
	}
+
}
+

+
# In case 'file normalize' doesn't exist
+
#
+
proc file-normalize {path} {
+
	if {[catch {file normalize $path} result]} {
+
		if {$path eq ""} {
+
			return ""
+
		}
+
		set oldpwd [pwd]
+
		if {[file isdir $path]} {
+
			cd $path
+
			set result [pwd]
+
		} else {
+
			cd [file dirname $path]
+
			set result [file join [pwd] [file tail $path]]
+
		}
+
		cd $oldpwd
+
	}
+
	return $result
+
}
+

+
# If everything is working properly, the only errors which occur
+
# should be generated in user code (e.g. auto.def).
+
# By default, we only want to show the error location in user code.
+
# We use [info frame] to achieve this, but it works differently on Tcl and Jim.
+
#
+
# This is designed to be called for incorrect usage in auto.def, via autosetup-error
+
#
+
proc error-location {msg} {
+
	if {$::autosetup(debug)} {
+
		return -code error $msg
+
	}
+
	# Search back through the stack trace for the first error in a .def file
+
	for {set i 1} {$i < [info level]} {incr i} {
+
		if {$::autosetup(istcl)} {
+
			array set info [info frame -$i]
+
		} else {
+
			lassign [info frame -$i] info(caller) info(file) info(line)
+
		}
+
		if {[string match *.def $info(file)]} {
+
			return "[relative-path $info(file)]:$info(line): Error: $msg"
+
		}
+
		#puts "Skipping $info(file):$info(line)"
+
	}
+
	return $msg
+
}
+

+
# If everything is working properly, the only errors which occur
+
# should be generated in user code (e.g. auto.def).
+
# By default, we only want to show the error location in user code.
+
# We use [info frame] to achieve this, but it works differently on Tcl and Jim.
+
#
+
# This is designed to be called for incorrect usage in auto.def, via autosetup-error
+
#
+
proc error-stacktrace {msg} {
+
	if {$::autosetup(debug)} {
+
		return -code error $msg
+
	}
+
	# Search back through the stack trace for the first error in a .def file
+
	for {set i 1} {$i < [info level]} {incr i} {
+
		if {$::autosetup(istcl)} {
+
			array set info [info frame -$i]
+
		} else {
+
			lassign [info frame -$i] info(caller) info(file) info(line)
+
		}
+
		if {[string match *.def $info(file)]} {
+
			return "[relative-path $info(file)]:$info(line): Error: $msg"
+
		}
+
		#puts "Skipping $info(file):$info(line)"
+
	}
+
	return $msg
+
}
+

+
# Given the return from [catch {...} msg opts], returns an appropriate
+
# error message. A nice one for Jim and a less-nice one for Tcl.
+
# If 'fulltrace' is set, a full stack trace is provided.
+
# Otherwise a simple message is provided.
+
#
+
# This is designed for developer errors, e.g. in module code or auto.def code
+
#
+
#
+
proc error-dump {msg opts fulltrace} {
+
	if {$::autosetup(istcl)} {
+
		if {$fulltrace} {
+
			return "Error: [dict get $opts -errorinfo]"
+
		} else {
+
			return "Error: $msg"
+
		}
+
	} else {
+
		lassign $opts(-errorinfo) p f l
+
		if {$f ne ""} {
+
			set result "$f:$l: Error: "
+
		}
+
		append result "$msg\n"
+
		if {$fulltrace} {
+
			append result [stackdump $opts(-errorinfo)]
+
		}
+

+
		# Remove the trailing newline
+
		string trim $result
+
	}
+
}
+
}
+

+
# ----- @module text-formatting.tcl -----
+

+
set modsource(text-formatting.tcl) {
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module which provides text formatting
+

+
use formatting
+

+
proc wordwrap {text length {firstprefix ""} {nextprefix ""}} {
+
	set len 0
+
	set space $firstprefix
+

+
	foreach word [split $text] {
+
		set word [string trim $word]
+
		if {$word eq ""} {
+
			continue
+
		}
+
		if {[info exists partial]} {
+
			append partial " " $word
+
			if {[string first $quote $word] < 0} {
+
				# Haven't found end of quoted word
+
				continue
+
			}
+
			# Finished quoted word
+
			set word $partial
+
			unset partial
+
			unset quote
+
		} else {
+
			set quote [string index $word 0]
+
			if {$quote in {' *}} {
+
				if {[string first $quote $word 1] < 0} {
+
					# Haven't found end of quoted word
+
					# Not a whole word.
+
					set first [string index $word 0]
+
					# Start of quoted word
+
					set partial $word
+
					continue
+
				}
+
			}
+
		}
+

+
		if {$len && [string length $space$word] + $len >= $length} {
+
			puts ""
+
			set len 0
+
			set space $nextprefix
+
		}
+
		incr len [string length $space$word]
+

+
		# Use man-page conventions for highlighting 'quoted' and *quoted*
+
		# single words.
+
		# Use x^Hx for *bold* and _^Hx for 'underline'.
+
		#
+
		# less and more will both understand this.
+
		# Pipe through 'col -b' to remove them.
+
		if {[regexp {^'(.*)'(.*)} $word -> quoted after]} {
+
			set quoted [string map {~ " "} $quoted]
+
			regsub -all . $quoted "&\b&" quoted
+
			set word $quoted$after
+
		} elseif {[regexp {^[*](.*)[*](.*)} $word -> quoted after]} {
+
			set quoted [string map {~ " "} $quoted]
+
			regsub -all . $quoted "_\b&" quoted
+
			set word $quoted$after
+
		}
+
		puts -nonewline $space$word
+
		set space " "
+
	}
+
	if {[info exists partial]} {
+
		# Missing end of quote
+
		puts -nonewline $space$partial
+
	}
+
	if {$len} {
+
		puts ""
+
	}
+
}
+
proc title {text} {
+
	underline [string trim $text] =
+
	nl
+
}
+
proc p {text} {
+
	wordwrap $text 80
+
	nl
+
}
+
proc codelines {lines} {
+
	foreach line $lines {
+
		puts "	  $line"
+
	}
+
	nl
+
}
+
proc nl {} {
+
	puts ""
+
}
+
proc underline {text char} {
+
	regexp "^(\[ \t\]*)(.*)" $text -> indent words
+
	puts $text
+
	puts $indent[string repeat $char [string length $words]]
+
}
+
proc section {text} {
+
	underline "[string trim $text]" -
+
	nl
+
}
+
proc subsection {text} {
+
	underline "$text" ~
+
	nl
+
}
+
proc bullet {text} {
+
	wordwrap $text 76 "	 * " "	  "
+
}
+
proc indent {text} {
+
	wordwrap $text 76 "	   " "	  "
+
}
+
proc defn {first args} {
+
	if {$first ne ""} {
+
		underline "	   $first" ~
+
	}
+
	foreach p $args {
+
		if {$p ne ""} {
+
			indent $p
+
		}
+
	}
+
}
+
}
+

+
# ----- @module util.tcl -----
+

+
set modsource(util.tcl) {
+
# Copyright (c) 2012 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module which contains miscellaneous utility functions
+

+
# @compare-versions version1 version2
+
#
+
# Versions are of the form 'a.b.c' (may be any number of numeric components)
+
#
+
# Compares the two versions and returns:
+
## -1 if v1 < v2
+
##  0 if v1 == v2
+
##  1 if v1 > v2
+
#
+
# If one version has fewer components than the other, 0 is substituted to the right. e.g.
+
## 0.2   <  0.3
+
## 0.2.5 >  0.2
+
## 1.1   == 1.1.0
+
#
+
proc compare-versions {v1 v2} {
+
	foreach c1 [split $v1 .] c2 [split $v2 .] {
+
		if {$c1 eq ""} {
+
			set c1 0
+
		}
+
		if {$c2 eq ""} {
+
			set c2 0
+
		}
+
		if {$c1 < $c2} {
+
			return -1
+
		}
+
		if {$c1 > $c2} {
+
			return 1
+
		}
+
	}
+
	return 0
+
}
+

+
# @suffix suf list
+
#
+
# Takes a list and returns a new list with '$suf' appended
+
# to each element
+
#
+
## suffix .c {a b c} => {a.c b.c c.c}
+
#
+
proc suffix {suf list} {
+
	set result {}
+
	foreach p $list {
+
		lappend result $p$suf
+
	}
+
	return $result
+
}
+

+
# @prefix pre list
+
#
+
# Takes a list and returns a new list with '$pre' prepended
+
# to each element
+
#
+
## prefix jim- {a.c b.c} => {jim-a.c jim-b.c}
+
#
+
proc prefix {pre list} {
+
	set result {}
+
	foreach p $list {
+
		lappend result $pre$p
+
	}
+
	return $result
+
}
+
}
+

+
# ----- @module wiki-formatting.tcl -----
+

+
set modsource(wiki-formatting.tcl) {
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Module which provides text formatting
+
# wiki.tcl.tk format output
+

+
use formatting
+

+
proc joinlines {text} {
+
    set lines {}
+
    foreach l [split [string trim $text] \n] {
+
        lappend lines [string trim $l]
+
    }
+
    join $lines
+
}
+
proc p {text} {
+
    puts [joinlines $text]
+
    puts ""
+
}
+
proc title {text} {
+
    puts "*** [joinlines $text] ***"
+
    puts ""
+
}
+
proc codelines {lines} {
+
    puts "======"
+
    foreach line $lines {
+
        puts "    $line"
+
    }
+
    puts "======"
+
}
+
proc code {text} {
+
    puts "======"
+
    foreach line [parse_code_block $text] {
+
        puts "    $line"
+
    }
+
    puts "======"
+
}
+
proc nl {} {
+
}
+
proc section {text} {
+
    puts "'''$text'''"
+
    puts ""
+
}
+
proc subsection {text} {
+
    puts "''$text''"
+
    puts ""
+
}
+
proc bullet {text} {
+
    puts "   * [joinlines $text]"
+
}
+
proc indent {text} {
+
    puts "    :    [joinlines $text]"
+
}
+
proc defn {first args} {
+
    if {$first ne ""} {
+
        indent '''$first'''
+
    }
+

+
    foreach p $args {
+
        p $p
+
    }
+
}
+
}
+

+

+
##################################################################
+
#
+
# Entry/Exit
+
#
+
if {$autosetup(debug)} {
+
	main $argv
+
}
+
if {[catch {main $argv} msg opts] == 1} {
+
	show-notices
+
	autosetup-full-error [error-dump $msg $opts $autosetup(debug)]
+
	if {!$autosetup(debug)} {
+
		puts stderr "Try: '[file tail $autosetup(exe)] --debug' for a full stack trace"
+
	}
+
	exit 1
+
}
added autosetup/autosetup-config.guess
@@ -0,0 +1,1421 @@
+
#! /bin/sh
+
# Attempt to guess a canonical system name.
+
#   Copyright 1992-2014 Free Software Foundation, Inc.
+

+
timestamp='2014-11-04'
+

+
# This file is free software; you can redistribute it and/or modify it
+
# under the terms of the GNU General Public License as published by
+
# the Free Software Foundation; either version 3 of the License, or
+
# (at your option) any later version.
+
#
+
# This program is distributed in the hope that it will be useful, but
+
# WITHOUT ANY WARRANTY; without even the implied warranty of
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+
# General Public License for more details.
+
#
+
# You should have received a copy of the GNU General Public License
+
# along with this program; if not, see <http://www.gnu.org/licenses/>.
+
#
+
# As a special exception to the GNU General Public License, if you
+
# distribute this file as part of a program that contains a
+
# configuration script generated by Autoconf, you may include it under
+
# the same distribution terms that you use for the rest of that
+
# program.  This Exception is an additional permission under section 7
+
# of the GNU General Public License, version 3 ("GPLv3").
+
#
+
# Originally written by Per Bothner; maintained since 2000 by Ben Elliston.
+
#
+
# You can get the latest version of this script from:
+
# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+
#
+
# Please send patches to <config-patches@gnu.org>.
+

+

+
me=`echo "$0" | sed -e 's,.*/,,'`
+

+
usage="\
+
Usage: $0 [OPTION]
+

+
Output the configuration name of the system \`$me' is run on.
+

+
Operation modes:
+
  -h, --help         print this help, then exit
+
  -t, --time-stamp   print date of last modification, then exit
+
  -v, --version      print version number, then exit
+

+
Report bugs and patches to <config-patches@gnu.org>."
+

+
version="\
+
GNU config.guess ($timestamp)
+

+
Originally written by Per Bothner.
+
Copyright 1992-2014 Free Software Foundation, Inc.
+

+
This is free software; see the source for copying conditions.  There is NO
+
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+

+
help="
+
Try \`$me --help' for more information."
+

+
# Parse command line
+
while test $# -gt 0 ; do
+
  case $1 in
+
    --time-stamp | --time* | -t )
+
       echo "$timestamp" ; exit ;;
+
    --version | -v )
+
       echo "$version" ; exit ;;
+
    --help | --h* | -h )
+
       echo "$usage"; exit ;;
+
    -- )     # Stop option processing
+
       shift; break ;;
+
    - )	# Use stdin as input.
+
       break ;;
+
    -* )
+
       echo "$me: invalid option $1$help" >&2
+
       exit 1 ;;
+
    * )
+
       break ;;
+
  esac
+
done
+

+
if test $# != 0; then
+
  echo "$me: too many arguments$help" >&2
+
  exit 1
+
fi
+

+
trap 'exit 1' 1 2 15
+

+
# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+
# compiler to aid in system detection is discouraged as it requires
+
# temporary files to be created and, as you can see below, it is a
+
# headache to deal with in a portable fashion.
+

+
# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+
# use `HOST_CC' if defined, but it is deprecated.
+

+
# Portable tmp directory creation inspired by the Autoconf team.
+

+
set_cc_for_build='
+
trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+
trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+
: ${TMPDIR=/tmp} ;
+
 { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+
 { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+
 { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+
 { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+
dummy=$tmp/dummy ;
+
tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+
case $CC_FOR_BUILD,$HOST_CC,$CC in
+
 ,,)    echo "int x;" > $dummy.c ;
+
	for c in cc gcc c89 c99 ; do
+
	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+
	     CC_FOR_BUILD="$c"; break ;
+
	  fi ;
+
	done ;
+
	if test x"$CC_FOR_BUILD" = x ; then
+
	  CC_FOR_BUILD=no_compiler_found ;
+
	fi
+
	;;
+
 ,,*)   CC_FOR_BUILD=$CC ;;
+
 ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
+
esac ; set_cc_for_build= ;'
+

+
# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+
# (ghazi@noc.rutgers.edu 1994-08-24)
+
if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+
	PATH=$PATH:/.attbin ; export PATH
+
fi
+

+
UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+
UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+
UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
+
UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+

+
case "${UNAME_SYSTEM}" in
+
Linux|GNU|GNU/*)
+
	# If the system lacks a compiler, then just pick glibc.
+
	# We could probably try harder.
+
	LIBC=gnu
+

+
	eval $set_cc_for_build
+
	cat <<-EOF > $dummy.c
+
	#include <features.h>
+
	#if defined(__UCLIBC__)
+
	LIBC=uclibc
+
	#elif defined(__dietlibc__)
+
	LIBC=dietlibc
+
	#else
+
	LIBC=gnu
+
	#endif
+
	EOF
+
	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
+
	;;
+
esac
+

+
# Note: order is significant - the case branches are not exclusive.
+

+
case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+
    *:NetBSD:*:*)
+
	# NetBSD (nbsd) targets should (where applicable) match one or
+
	# more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,
+
	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
+
	# switched to ELF, *-*-netbsd* would select the old
+
	# object file format.  This provides both forward
+
	# compatibility and a consistent mechanism for selecting the
+
	# object file format.
+
	#
+
	# Note: NetBSD doesn't particularly care about the vendor
+
	# portion of the name.  We always set it to "unknown".
+
	sysctl="sysctl -n hw.machine_arch"
+
	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+
	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+
	case "${UNAME_MACHINE_ARCH}" in
+
	    armeb) machine=armeb-unknown ;;
+
	    arm*) machine=arm-unknown ;;
+
	    sh3el) machine=shl-unknown ;;
+
	    sh3eb) machine=sh-unknown ;;
+
	    sh5el) machine=sh5le-unknown ;;
+
	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+
	esac
+
	# The Operating System including object format, if it has switched
+
	# to ELF recently, or will in the future.
+
	case "${UNAME_MACHINE_ARCH}" in
+
	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+
		eval $set_cc_for_build
+
		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+
			| grep -q __ELF__
+
		then
+
		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+
		    # Return netbsd for either.  FIX?
+
		    os=netbsd
+
		else
+
		    os=netbsdelf
+
		fi
+
		;;
+
	    *)
+
		os=netbsd
+
		;;
+
	esac
+
	# The OS release
+
	# Debian GNU/NetBSD machines have a different userland, and
+
	# thus, need a distinct triplet. However, they do not need
+
	# kernel version information, so it can be replaced with a
+
	# suitable tag, in the style of linux-gnu.
+
	case "${UNAME_VERSION}" in
+
	    Debian*)
+
		release='-gnu'
+
		;;
+
	    *)
+
		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+
		;;
+
	esac
+
	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+
	# contains redundant information, the shorter form:
+
	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+
	echo "${machine}-${os}${release}"
+
	exit ;;
+
    *:Bitrig:*:*)
+
	UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
+
	echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE}
+
	exit ;;
+
    *:OpenBSD:*:*)
+
	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+
	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+
	exit ;;
+
    *:ekkoBSD:*:*)
+
	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+
	exit ;;
+
    *:SolidBSD:*:*)
+
	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+
	exit ;;
+
    macppc:MirBSD:*:*)
+
	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
+
	exit ;;
+
    *:MirBSD:*:*)
+
	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+
	exit ;;
+
    alpha:OSF1:*:*)
+
	case $UNAME_RELEASE in
+
	*4.0)
+
		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+
		;;
+
	*5.*)
+
		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+
		;;
+
	esac
+
	# According to Compaq, /usr/sbin/psrinfo has been available on
+
	# OSF/1 and Tru64 systems produced since 1995.  I hope that
+
	# covers most systems running today.  This code pipes the CPU
+
	# types through head -n 1, so we only detect the type of CPU 0.
+
	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+
	case "$ALPHA_CPU_TYPE" in
+
	    "EV4 (21064)")
+
		UNAME_MACHINE="alpha" ;;
+
	    "EV4.5 (21064)")
+
		UNAME_MACHINE="alpha" ;;
+
	    "LCA4 (21066/21068)")
+
		UNAME_MACHINE="alpha" ;;
+
	    "EV5 (21164)")
+
		UNAME_MACHINE="alphaev5" ;;
+
	    "EV5.6 (21164A)")
+
		UNAME_MACHINE="alphaev56" ;;
+
	    "EV5.6 (21164PC)")
+
		UNAME_MACHINE="alphapca56" ;;
+
	    "EV5.7 (21164PC)")
+
		UNAME_MACHINE="alphapca57" ;;
+
	    "EV6 (21264)")
+
		UNAME_MACHINE="alphaev6" ;;
+
	    "EV6.7 (21264A)")
+
		UNAME_MACHINE="alphaev67" ;;
+
	    "EV6.8CB (21264C)")
+
		UNAME_MACHINE="alphaev68" ;;
+
	    "EV6.8AL (21264B)")
+
		UNAME_MACHINE="alphaev68" ;;
+
	    "EV6.8CX (21264D)")
+
		UNAME_MACHINE="alphaev68" ;;
+
	    "EV6.9A (21264/EV69A)")
+
		UNAME_MACHINE="alphaev69" ;;
+
	    "EV7 (21364)")
+
		UNAME_MACHINE="alphaev7" ;;
+
	    "EV7.9 (21364A)")
+
		UNAME_MACHINE="alphaev79" ;;
+
	esac
+
	# A Pn.n version is a patched version.
+
	# A Vn.n version is a released version.
+
	# A Tn.n version is a released field test version.
+
	# A Xn.n version is an unreleased experimental baselevel.
+
	# 1.2 uses "1.2" for uname -r.
+
	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+
	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
+
	exitcode=$?
+
	trap '' 0
+
	exit $exitcode ;;
+
    Alpha\ *:Windows_NT*:*)
+
	# How do we know it's Interix rather than the generic POSIX subsystem?
+
	# Should we change UNAME_MACHINE based on the output of uname instead
+
	# of the specific Alpha model?
+
	echo alpha-pc-interix
+
	exit ;;
+
    21064:Windows_NT:50:3)
+
	echo alpha-dec-winnt3.5
+
	exit ;;
+
    Amiga*:UNIX_System_V:4.0:*)
+
	echo m68k-unknown-sysv4
+
	exit ;;
+
    *:[Aa]miga[Oo][Ss]:*:*)
+
	echo ${UNAME_MACHINE}-unknown-amigaos
+
	exit ;;
+
    *:[Mm]orph[Oo][Ss]:*:*)
+
	echo ${UNAME_MACHINE}-unknown-morphos
+
	exit ;;
+
    *:OS/390:*:*)
+
	echo i370-ibm-openedition
+
	exit ;;
+
    *:z/VM:*:*)
+
	echo s390-ibm-zvmoe
+
	exit ;;
+
    *:OS400:*:*)
+
	echo powerpc-ibm-os400
+
	exit ;;
+
    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+
	echo arm-acorn-riscix${UNAME_RELEASE}
+
	exit ;;
+
    arm*:riscos:*:*|arm*:RISCOS:*:*)
+
	echo arm-unknown-riscos
+
	exit ;;
+
    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+
	echo hppa1.1-hitachi-hiuxmpp
+
	exit ;;
+
    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+
	# akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+
	if test "`(/bin/universe) 2>/dev/null`" = att ; then
+
		echo pyramid-pyramid-sysv3
+
	else
+
		echo pyramid-pyramid-bsd
+
	fi
+
	exit ;;
+
    NILE*:*:*:dcosx)
+
	echo pyramid-pyramid-svr4
+
	exit ;;
+
    DRS?6000:unix:4.0:6*)
+
	echo sparc-icl-nx6
+
	exit ;;
+
    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+
	case `/usr/bin/uname -p` in
+
	    sparc) echo sparc-icl-nx7; exit ;;
+
	esac ;;
+
    s390x:SunOS:*:*)
+
	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+
	exit ;;
+
    sun4H:SunOS:5.*:*)
+
	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+
	exit ;;
+
    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+
	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+
	exit ;;
+
    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+
	echo i386-pc-auroraux${UNAME_RELEASE}
+
	exit ;;
+
    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+
	eval $set_cc_for_build
+
	SUN_ARCH="i386"
+
	# If there is a compiler, see if it is configured for 64-bit objects.
+
	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+
	# This test works for both compilers.
+
	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+
	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+
		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+
		grep IS_64BIT_ARCH >/dev/null
+
	    then
+
		SUN_ARCH="x86_64"
+
	    fi
+
	fi
+
	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+
	exit ;;
+
    sun4*:SunOS:6*:*)
+
	# According to config.sub, this is the proper way to canonicalize
+
	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
+
	# it's likely to be more like Solaris than SunOS4.
+
	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+
	exit ;;
+
    sun4*:SunOS:*:*)
+
	case "`/usr/bin/arch -k`" in
+
	    Series*|S4*)
+
		UNAME_RELEASE=`uname -v`
+
		;;
+
	esac
+
	# Japanese Language versions have a version number like `4.1.3-JL'.
+
	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+
	exit ;;
+
    sun3*:SunOS:*:*)
+
	echo m68k-sun-sunos${UNAME_RELEASE}
+
	exit ;;
+
    sun*:*:4.2BSD:*)
+
	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+
	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+
	case "`/bin/arch`" in
+
	    sun3)
+
		echo m68k-sun-sunos${UNAME_RELEASE}
+
		;;
+
	    sun4)
+
		echo sparc-sun-sunos${UNAME_RELEASE}
+
		;;
+
	esac
+
	exit ;;
+
    aushp:SunOS:*:*)
+
	echo sparc-auspex-sunos${UNAME_RELEASE}
+
	exit ;;
+
    # The situation for MiNT is a little confusing.  The machine name
+
    # can be virtually everything (everything which is not
+
    # "atarist" or "atariste" at least should have a processor
+
    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
+
    # to the lowercase version "mint" (or "freemint").  Finally
+
    # the system name "TOS" denotes a system which is actually not
+
    # MiNT.  But MiNT is downward compatible to TOS, so this should
+
    # be no problem.
+
    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+
	echo m68k-atari-mint${UNAME_RELEASE}
+
	exit ;;
+
    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+
	echo m68k-atari-mint${UNAME_RELEASE}
+
	exit ;;
+
    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+
	echo m68k-atari-mint${UNAME_RELEASE}
+
	exit ;;
+
    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+
	echo m68k-milan-mint${UNAME_RELEASE}
+
	exit ;;
+
    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+
	echo m68k-hades-mint${UNAME_RELEASE}
+
	exit ;;
+
    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+
	echo m68k-unknown-mint${UNAME_RELEASE}
+
	exit ;;
+
    m68k:machten:*:*)
+
	echo m68k-apple-machten${UNAME_RELEASE}
+
	exit ;;
+
    powerpc:machten:*:*)
+
	echo powerpc-apple-machten${UNAME_RELEASE}
+
	exit ;;
+
    RISC*:Mach:*:*)
+
	echo mips-dec-mach_bsd4.3
+
	exit ;;
+
    RISC*:ULTRIX:*:*)
+
	echo mips-dec-ultrix${UNAME_RELEASE}
+
	exit ;;
+
    VAX*:ULTRIX*:*:*)
+
	echo vax-dec-ultrix${UNAME_RELEASE}
+
	exit ;;
+
    2020:CLIX:*:* | 2430:CLIX:*:*)
+
	echo clipper-intergraph-clix${UNAME_RELEASE}
+
	exit ;;
+
    mips:*:*:UMIPS | mips:*:*:RISCos)
+
	eval $set_cc_for_build
+
	sed 's/^	//' << EOF >$dummy.c
+
#ifdef __cplusplus
+
#include <stdio.h>  /* for printf() prototype */
+
	int main (int argc, char *argv[]) {
+
#else
+
	int main (argc, argv) int argc; char *argv[]; {
+
#endif
+
	#if defined (host_mips) && defined (MIPSEB)
+
	#if defined (SYSTYPE_SYSV)
+
	  printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+
	#endif
+
	#if defined (SYSTYPE_SVR4)
+
	  printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+
	#endif
+
	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+
	  printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+
	#endif
+
	#endif
+
	  exit (-1);
+
	}
+
EOF
+
	$CC_FOR_BUILD -o $dummy $dummy.c &&
+
	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+
	  SYSTEM_NAME=`$dummy $dummyarg` &&
+
	    { echo "$SYSTEM_NAME"; exit; }
+
	echo mips-mips-riscos${UNAME_RELEASE}
+
	exit ;;
+
    Motorola:PowerMAX_OS:*:*)
+
	echo powerpc-motorola-powermax
+
	exit ;;
+
    Motorola:*:4.3:PL8-*)
+
	echo powerpc-harris-powermax
+
	exit ;;
+
    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+
	echo powerpc-harris-powermax
+
	exit ;;
+
    Night_Hawk:Power_UNIX:*:*)
+
	echo powerpc-harris-powerunix
+
	exit ;;
+
    m88k:CX/UX:7*:*)
+
	echo m88k-harris-cxux7
+
	exit ;;
+
    m88k:*:4*:R4*)
+
	echo m88k-motorola-sysv4
+
	exit ;;
+
    m88k:*:3*:R3*)
+
	echo m88k-motorola-sysv3
+
	exit ;;
+
    AViiON:dgux:*:*)
+
	# DG/UX returns AViiON for all architectures
+
	UNAME_PROCESSOR=`/usr/bin/uname -p`
+
	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+
	then
+
	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+
	       [ ${TARGET_BINARY_INTERFACE}x = x ]
+
	    then
+
		echo m88k-dg-dgux${UNAME_RELEASE}
+
	    else
+
		echo m88k-dg-dguxbcs${UNAME_RELEASE}
+
	    fi
+
	else
+
	    echo i586-dg-dgux${UNAME_RELEASE}
+
	fi
+
	exit ;;
+
    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
+
	echo m88k-dolphin-sysv3
+
	exit ;;
+
    M88*:*:R3*:*)
+
	# Delta 88k system running SVR3
+
	echo m88k-motorola-sysv3
+
	exit ;;
+
    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+
	echo m88k-tektronix-sysv3
+
	exit ;;
+
    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+
	echo m68k-tektronix-bsd
+
	exit ;;
+
    *:IRIX*:*:*)
+
	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+
	exit ;;
+
    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+
	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
+
	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
+
    i*86:AIX:*:*)
+
	echo i386-ibm-aix
+
	exit ;;
+
    ia64:AIX:*:*)
+
	if [ -x /usr/bin/oslevel ] ; then
+
		IBM_REV=`/usr/bin/oslevel`
+
	else
+
		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+
	fi
+
	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+
	exit ;;
+
    *:AIX:2:3)
+
	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+
		eval $set_cc_for_build
+
		sed 's/^		//' << EOF >$dummy.c
+
		#include <sys/systemcfg.h>
+

+
		main()
+
			{
+
			if (!__power_pc())
+
				exit(1);
+
			puts("powerpc-ibm-aix3.2.5");
+
			exit(0);
+
			}
+
EOF
+
		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+
		then
+
			echo "$SYSTEM_NAME"
+
		else
+
			echo rs6000-ibm-aix3.2.5
+
		fi
+
	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+
		echo rs6000-ibm-aix3.2.4
+
	else
+
		echo rs6000-ibm-aix3.2
+
	fi
+
	exit ;;
+
    *:AIX:*:[4567])
+
	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+
	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+
		IBM_ARCH=rs6000
+
	else
+
		IBM_ARCH=powerpc
+
	fi
+
	if [ -x /usr/bin/lslpp ] ; then
+
		IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc |
+
			   awk -F: '{ print $3 }' | sed s/[0-9]*$/0/`
+
	else
+
		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+
	fi
+
	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+
	exit ;;
+
    *:AIX:*:*)
+
	echo rs6000-ibm-aix
+
	exit ;;
+
    ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+
	echo romp-ibm-bsd4.4
+
	exit ;;
+
    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
+
	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
+
	exit ;;                             # report: romp-ibm BSD 4.3
+
    *:BOSX:*:*)
+
	echo rs6000-bull-bosx
+
	exit ;;
+
    DPX/2?00:B.O.S.:*:*)
+
	echo m68k-bull-sysv3
+
	exit ;;
+
    9000/[34]??:4.3bsd:1.*:*)
+
	echo m68k-hp-bsd
+
	exit ;;
+
    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+
	echo m68k-hp-bsd4.4
+
	exit ;;
+
    9000/[34678]??:HP-UX:*:*)
+
	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+
	case "${UNAME_MACHINE}" in
+
	    9000/31? )            HP_ARCH=m68000 ;;
+
	    9000/[34]?? )         HP_ARCH=m68k ;;
+
	    9000/[678][0-9][0-9])
+
		if [ -x /usr/bin/getconf ]; then
+
		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+
		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+
		    case "${sc_cpu_version}" in
+
		      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+
		      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+
		      532)                      # CPU_PA_RISC2_0
+
			case "${sc_kernel_bits}" in
+
			  32) HP_ARCH="hppa2.0n" ;;
+
			  64) HP_ARCH="hppa2.0w" ;;
+
			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+
			esac ;;
+
		    esac
+
		fi
+
		if [ "${HP_ARCH}" = "" ]; then
+
		    eval $set_cc_for_build
+
		    sed 's/^		//' << EOF >$dummy.c
+

+
		#define _HPUX_SOURCE
+
		#include <stdlib.h>
+
		#include <unistd.h>
+

+
		int main ()
+
		{
+
		#if defined(_SC_KERNEL_BITS)
+
		    long bits = sysconf(_SC_KERNEL_BITS);
+
		#endif
+
		    long cpu  = sysconf (_SC_CPU_VERSION);
+

+
		    switch (cpu)
+
			{
+
			case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+
			case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+
			case CPU_PA_RISC2_0:
+
		#if defined(_SC_KERNEL_BITS)
+
			    switch (bits)
+
				{
+
				case 64: puts ("hppa2.0w"); break;
+
				case 32: puts ("hppa2.0n"); break;
+
				default: puts ("hppa2.0"); break;
+
				} break;
+
		#else  /* !defined(_SC_KERNEL_BITS) */
+
			    puts ("hppa2.0"); break;
+
		#endif
+
			default: puts ("hppa1.0"); break;
+
			}
+
		    exit (0);
+
		}
+
EOF
+
		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+
		    test -z "$HP_ARCH" && HP_ARCH=hppa
+
		fi ;;
+
	esac
+
	if [ ${HP_ARCH} = "hppa2.0w" ]
+
	then
+
	    eval $set_cc_for_build
+

+
	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+
	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
+
	    # generating 64-bit code.  GNU and HP use different nomenclature:
+
	    #
+
	    # $ CC_FOR_BUILD=cc ./config.guess
+
	    # => hppa2.0w-hp-hpux11.23
+
	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+
	    # => hppa64-hp-hpux11.23
+

+
	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+
		grep -q __LP64__
+
	    then
+
		HP_ARCH="hppa2.0w"
+
	    else
+
		HP_ARCH="hppa64"
+
	    fi
+
	fi
+
	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+
	exit ;;
+
    ia64:HP-UX:*:*)
+
	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+
	echo ia64-hp-hpux${HPUX_REV}
+
	exit ;;
+
    3050*:HI-UX:*:*)
+
	eval $set_cc_for_build
+
	sed 's/^	//' << EOF >$dummy.c
+
	#include <unistd.h>
+
	int
+
	main ()
+
	{
+
	  long cpu = sysconf (_SC_CPU_VERSION);
+
	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+
	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
+
	     results, however.  */
+
	  if (CPU_IS_PA_RISC (cpu))
+
	    {
+
	      switch (cpu)
+
		{
+
		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+
		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+
		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+
		  default: puts ("hppa-hitachi-hiuxwe2"); break;
+
		}
+
	    }
+
	  else if (CPU_IS_HP_MC68K (cpu))
+
	    puts ("m68k-hitachi-hiuxwe2");
+
	  else puts ("unknown-hitachi-hiuxwe2");
+
	  exit (0);
+
	}
+
EOF
+
	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+
		{ echo "$SYSTEM_NAME"; exit; }
+
	echo unknown-hitachi-hiuxwe2
+
	exit ;;
+
    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+
	echo hppa1.1-hp-bsd
+
	exit ;;
+
    9000/8??:4.3bsd:*:*)
+
	echo hppa1.0-hp-bsd
+
	exit ;;
+
    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+
	echo hppa1.0-hp-mpeix
+
	exit ;;
+
    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+
	echo hppa1.1-hp-osf
+
	exit ;;
+
    hp8??:OSF1:*:*)
+
	echo hppa1.0-hp-osf
+
	exit ;;
+
    i*86:OSF1:*:*)
+
	if [ -x /usr/sbin/sysversion ] ; then
+
	    echo ${UNAME_MACHINE}-unknown-osf1mk
+
	else
+
	    echo ${UNAME_MACHINE}-unknown-osf1
+
	fi
+
	exit ;;
+
    parisc*:Lites*:*:*)
+
	echo hppa1.1-hp-lites
+
	exit ;;
+
    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+
	echo c1-convex-bsd
+
	exit ;;
+
    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+
	if getsysinfo -f scalar_acc
+
	then echo c32-convex-bsd
+
	else echo c2-convex-bsd
+
	fi
+
	exit ;;
+
    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+
	echo c34-convex-bsd
+
	exit ;;
+
    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+
	echo c38-convex-bsd
+
	exit ;;
+
    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+
	echo c4-convex-bsd
+
	exit ;;
+
    CRAY*Y-MP:*:*:*)
+
	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+
	exit ;;
+
    CRAY*[A-Z]90:*:*:*)
+
	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+
	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+
	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+
	      -e 's/\.[^.]*$/.X/'
+
	exit ;;
+
    CRAY*TS:*:*:*)
+
	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+
	exit ;;
+
    CRAY*T3E:*:*:*)
+
	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+
	exit ;;
+
    CRAY*SV1:*:*:*)
+
	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+
	exit ;;
+
    *:UNICOS/mp:*:*)
+
	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+
	exit ;;
+
    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+
	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+
	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+
	FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+
	echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+
	exit ;;
+
    5000:UNIX_System_V:4.*:*)
+
	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+
	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+
	echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+
	exit ;;
+
    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+
	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+
	exit ;;
+
    sparc*:BSD/OS:*:*)
+
	echo sparc-unknown-bsdi${UNAME_RELEASE}
+
	exit ;;
+
    *:BSD/OS:*:*)
+
	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+
	exit ;;
+
    *:FreeBSD:*:*)
+
	UNAME_PROCESSOR=`/usr/bin/uname -p`
+
	case ${UNAME_PROCESSOR} in
+
	    amd64)
+
		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+
	    *)
+
		echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+
	esac
+
	exit ;;
+
    i*:CYGWIN*:*)
+
	echo ${UNAME_MACHINE}-pc-cygwin
+
	exit ;;
+
    *:MINGW64*:*)
+
	echo ${UNAME_MACHINE}-pc-mingw64
+
	exit ;;
+
    *:MINGW*:*)
+
	echo ${UNAME_MACHINE}-pc-mingw32
+
	exit ;;
+
    *:MSYS*:*)
+
	echo ${UNAME_MACHINE}-pc-msys
+
	exit ;;
+
    i*:windows32*:*)
+
	# uname -m includes "-pc" on this system.
+
	echo ${UNAME_MACHINE}-mingw32
+
	exit ;;
+
    i*:PW*:*)
+
	echo ${UNAME_MACHINE}-pc-pw32
+
	exit ;;
+
    *:Interix*:*)
+
	case ${UNAME_MACHINE} in
+
	    x86)
+
		echo i586-pc-interix${UNAME_RELEASE}
+
		exit ;;
+
	    authenticamd | genuineintel | EM64T)
+
		echo x86_64-unknown-interix${UNAME_RELEASE}
+
		exit ;;
+
	    IA64)
+
		echo ia64-unknown-interix${UNAME_RELEASE}
+
		exit ;;
+
	esac ;;
+
    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+
	echo i${UNAME_MACHINE}-pc-mks
+
	exit ;;
+
    8664:Windows_NT:*)
+
	echo x86_64-pc-mks
+
	exit ;;
+
    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+
	# How do we know it's Interix rather than the generic POSIX subsystem?
+
	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+
	# UNAME_MACHINE based on the output of uname instead of i386?
+
	echo i586-pc-interix
+
	exit ;;
+
    i*:UWIN*:*)
+
	echo ${UNAME_MACHINE}-pc-uwin
+
	exit ;;
+
    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+
	echo x86_64-unknown-cygwin
+
	exit ;;
+
    p*:CYGWIN*:*)
+
	echo powerpcle-unknown-cygwin
+
	exit ;;
+
    prep*:SunOS:5.*:*)
+
	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+
	exit ;;
+
    *:GNU:*:*)
+
	# the GNU system
+
	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+
	exit ;;
+
    *:GNU/*:*:*)
+
	# other systems with GNU libc and userland
+
	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
+
	exit ;;
+
    i*86:Minix:*:*)
+
	echo ${UNAME_MACHINE}-pc-minix
+
	exit ;;
+
    aarch64:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    aarch64_be:Linux:*:*)
+
	UNAME_MACHINE=aarch64_be
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    alpha:Linux:*:*)
+
	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+
	  EV5)   UNAME_MACHINE=alphaev5 ;;
+
	  EV56)  UNAME_MACHINE=alphaev56 ;;
+
	  PCA56) UNAME_MACHINE=alphapca56 ;;
+
	  PCA57) UNAME_MACHINE=alphapca56 ;;
+
	  EV6)   UNAME_MACHINE=alphaev6 ;;
+
	  EV67)  UNAME_MACHINE=alphaev67 ;;
+
	  EV68*) UNAME_MACHINE=alphaev68 ;;
+
	esac
+
	objdump --private-headers /bin/sh | grep -q ld.so.1
+
	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    arc:Linux:*:* | arceb:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    arm*:Linux:*:*)
+
	eval $set_cc_for_build
+
	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+
	    | grep -q __ARM_EABI__
+
	then
+
	    echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	else
+
	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
+
		| grep -q __ARM_PCS_VFP
+
	    then
+
		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
+
	    else
+
		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
+
	    fi
+
	fi
+
	exit ;;
+
    avr32*:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    cris:Linux:*:*)
+
	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+
	exit ;;
+
    crisv32:Linux:*:*)
+
	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+
	exit ;;
+
    frv:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    hexagon:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    i*86:Linux:*:*)
+
	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
+
	exit ;;
+
    ia64:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    m32r*:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    m68*:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    mips:Linux:*:* | mips64:Linux:*:*)
+
	eval $set_cc_for_build
+
	sed 's/^	//' << EOF >$dummy.c
+
	#undef CPU
+
	#undef ${UNAME_MACHINE}
+
	#undef ${UNAME_MACHINE}el
+
	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+
	CPU=${UNAME_MACHINE}el
+
	#else
+
	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+
	CPU=${UNAME_MACHINE}
+
	#else
+
	CPU=
+
	#endif
+
	#endif
+
EOF
+
	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
+
	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
+
	;;
+
    openrisc*:Linux:*:*)
+
	echo or1k-unknown-linux-${LIBC}
+
	exit ;;
+
    or32:Linux:*:* | or1k*:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    padre:Linux:*:*)
+
	echo sparc-unknown-linux-${LIBC}
+
	exit ;;
+
    parisc64:Linux:*:* | hppa64:Linux:*:*)
+
	echo hppa64-unknown-linux-${LIBC}
+
	exit ;;
+
    parisc:Linux:*:* | hppa:Linux:*:*)
+
	# Look for CPU level
+
	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+
	  PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
+
	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
+
	  *)    echo hppa-unknown-linux-${LIBC} ;;
+
	esac
+
	exit ;;
+
    ppc64:Linux:*:*)
+
	echo powerpc64-unknown-linux-${LIBC}
+
	exit ;;
+
    ppc:Linux:*:*)
+
	echo powerpc-unknown-linux-${LIBC}
+
	exit ;;
+
    ppc64le:Linux:*:*)
+
	echo powerpc64le-unknown-linux-${LIBC}
+
	exit ;;
+
    ppcle:Linux:*:*)
+
	echo powerpcle-unknown-linux-${LIBC}
+
	exit ;;
+
    s390:Linux:*:* | s390x:Linux:*:*)
+
	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
+
	exit ;;
+
    sh64*:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    sh*:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    sparc:Linux:*:* | sparc64:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    tile*:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    vax:Linux:*:*)
+
	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
+
	exit ;;
+
    x86_64:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    xtensa*:Linux:*:*)
+
	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+
	exit ;;
+
    i*86:DYNIX/ptx:4*:*)
+
	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+
	# earlier versions are messed up and put the nodename in both
+
	# sysname and nodename.
+
	echo i386-sequent-sysv4
+
	exit ;;
+
    i*86:UNIX_SV:4.2MP:2.*)
+
	# Unixware is an offshoot of SVR4, but it has its own version
+
	# number series starting with 2...
+
	# I am not positive that other SVR4 systems won't match this,
+
	# I just have to hope.  -- rms.
+
	# Use sysv4.2uw... so that sysv4* matches it.
+
	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+
	exit ;;
+
    i*86:OS/2:*:*)
+
	# If we were able to find `uname', then EMX Unix compatibility
+
	# is probably installed.
+
	echo ${UNAME_MACHINE}-pc-os2-emx
+
	exit ;;
+
    i*86:XTS-300:*:STOP)
+
	echo ${UNAME_MACHINE}-unknown-stop
+
	exit ;;
+
    i*86:atheos:*:*)
+
	echo ${UNAME_MACHINE}-unknown-atheos
+
	exit ;;
+
    i*86:syllable:*:*)
+
	echo ${UNAME_MACHINE}-pc-syllable
+
	exit ;;
+
    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
+
	echo i386-unknown-lynxos${UNAME_RELEASE}
+
	exit ;;
+
    i*86:*DOS:*:*)
+
	echo ${UNAME_MACHINE}-pc-msdosdjgpp
+
	exit ;;
+
    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+
	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+
	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+
		echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+
	else
+
		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+
	fi
+
	exit ;;
+
    i*86:*:5:[678]*)
+
	# UnixWare 7.x, OpenUNIX and OpenServer 6.
+
	case `/bin/uname -X | grep "^Machine"` in
+
	    *486*)	     UNAME_MACHINE=i486 ;;
+
	    *Pentium)	     UNAME_MACHINE=i586 ;;
+
	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+
	esac
+
	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+
	exit ;;
+
    i*86:*:3.2:*)
+
	if test -f /usr/options/cb.name; then
+
		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+
		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+
	elif /bin/uname -X 2>/dev/null >/dev/null ; then
+
		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+
		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+
		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+
			&& UNAME_MACHINE=i586
+
		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+
			&& UNAME_MACHINE=i686
+
		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+
			&& UNAME_MACHINE=i686
+
		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+
	else
+
		echo ${UNAME_MACHINE}-pc-sysv32
+
	fi
+
	exit ;;
+
    pc:*:*:*)
+
	# Left here for compatibility:
+
	# uname -m prints for DJGPP always 'pc', but it prints nothing about
+
	# the processor, so we play safe by assuming i586.
+
	# Note: whatever this is, it MUST be the same as what config.sub
+
	# prints for the "djgpp" host, or else GDB configury will decide that
+
	# this is a cross-build.
+
	echo i586-pc-msdosdjgpp
+
	exit ;;
+
    Intel:Mach:3*:*)
+
	echo i386-pc-mach3
+
	exit ;;
+
    paragon:*:*:*)
+
	echo i860-intel-osf1
+
	exit ;;
+
    i860:*:4.*:*) # i860-SVR4
+
	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+
	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+
	else # Add other i860-SVR4 vendors below as they are discovered.
+
	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
+
	fi
+
	exit ;;
+
    mini*:CTIX:SYS*5:*)
+
	# "miniframe"
+
	echo m68010-convergent-sysv
+
	exit ;;
+
    mc68k:UNIX:SYSTEM5:3.51m)
+
	echo m68k-convergent-sysv
+
	exit ;;
+
    M680?0:D-NIX:5.3:*)
+
	echo m68k-diab-dnix
+
	exit ;;
+
    M68*:*:R3V[5678]*:*)
+
	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+
    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+
	OS_REL=''
+
	test -r /etc/.relid \
+
	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+
	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+
	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+
	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+
	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+
    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+
	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+
	  && { echo i486-ncr-sysv4; exit; } ;;
+
    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+
	OS_REL='.3'
+
	test -r /etc/.relid \
+
	    && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+
	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+
	    && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+
	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+
	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
+
	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+
	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+
    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+
	echo m68k-unknown-lynxos${UNAME_RELEASE}
+
	exit ;;
+
    mc68030:UNIX_System_V:4.*:*)
+
	echo m68k-atari-sysv4
+
	exit ;;
+
    TSUNAMI:LynxOS:2.*:*)
+
	echo sparc-unknown-lynxos${UNAME_RELEASE}
+
	exit ;;
+
    rs6000:LynxOS:2.*:*)
+
	echo rs6000-unknown-lynxos${UNAME_RELEASE}
+
	exit ;;
+
    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
+
	echo powerpc-unknown-lynxos${UNAME_RELEASE}
+
	exit ;;
+
    SM[BE]S:UNIX_SV:*:*)
+
	echo mips-dde-sysv${UNAME_RELEASE}
+
	exit ;;
+
    RM*:ReliantUNIX-*:*:*)
+
	echo mips-sni-sysv4
+
	exit ;;
+
    RM*:SINIX-*:*:*)
+
	echo mips-sni-sysv4
+
	exit ;;
+
    *:SINIX-*:*:*)
+
	if uname -p 2>/dev/null >/dev/null ; then
+
		UNAME_MACHINE=`(uname -p) 2>/dev/null`
+
		echo ${UNAME_MACHINE}-sni-sysv4
+
	else
+
		echo ns32k-sni-sysv
+
	fi
+
	exit ;;
+
    PENTIUM:*:4.0*:*)	# Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+
			# says <Richard.M.Bartel@ccMail.Census.GOV>
+
	echo i586-unisys-sysv4
+
	exit ;;
+
    *:UNIX_System_V:4*:FTX*)
+
	# From Gerald Hewes <hewes@openmarket.com>.
+
	# How about differentiating between stratus architectures? -djm
+
	echo hppa1.1-stratus-sysv4
+
	exit ;;
+
    *:*:*:FTX*)
+
	# From seanf@swdc.stratus.com.
+
	echo i860-stratus-sysv4
+
	exit ;;
+
    i*86:VOS:*:*)
+
	# From Paul.Green@stratus.com.
+
	echo ${UNAME_MACHINE}-stratus-vos
+
	exit ;;
+
    *:VOS:*:*)
+
	# From Paul.Green@stratus.com.
+
	echo hppa1.1-stratus-vos
+
	exit ;;
+
    mc68*:A/UX:*:*)
+
	echo m68k-apple-aux${UNAME_RELEASE}
+
	exit ;;
+
    news*:NEWS-OS:6*:*)
+
	echo mips-sony-newsos6
+
	exit ;;
+
    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+
	if [ -d /usr/nec ]; then
+
		echo mips-nec-sysv${UNAME_RELEASE}
+
	else
+
		echo mips-unknown-sysv${UNAME_RELEASE}
+
	fi
+
	exit ;;
+
    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
+
	echo powerpc-be-beos
+
	exit ;;
+
    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
+
	echo powerpc-apple-beos
+
	exit ;;
+
    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
+
	echo i586-pc-beos
+
	exit ;;
+
    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
+
	echo i586-pc-haiku
+
	exit ;;
+
    x86_64:Haiku:*:*)
+
	echo x86_64-unknown-haiku
+
	exit ;;
+
    SX-4:SUPER-UX:*:*)
+
	echo sx4-nec-superux${UNAME_RELEASE}
+
	exit ;;
+
    SX-5:SUPER-UX:*:*)
+
	echo sx5-nec-superux${UNAME_RELEASE}
+
	exit ;;
+
    SX-6:SUPER-UX:*:*)
+
	echo sx6-nec-superux${UNAME_RELEASE}
+
	exit ;;
+
    SX-7:SUPER-UX:*:*)
+
	echo sx7-nec-superux${UNAME_RELEASE}
+
	exit ;;
+
    SX-8:SUPER-UX:*:*)
+
	echo sx8-nec-superux${UNAME_RELEASE}
+
	exit ;;
+
    SX-8R:SUPER-UX:*:*)
+
	echo sx8r-nec-superux${UNAME_RELEASE}
+
	exit ;;
+
    Power*:Rhapsody:*:*)
+
	echo powerpc-apple-rhapsody${UNAME_RELEASE}
+
	exit ;;
+
    *:Rhapsody:*:*)
+
	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+
	exit ;;
+
    *:Darwin:*:*)
+
	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+
	eval $set_cc_for_build
+
	if test "$UNAME_PROCESSOR" = unknown ; then
+
	    UNAME_PROCESSOR=powerpc
+
	fi
+
	if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
+
	    if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+
		if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+
		    (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+
		    grep IS_64BIT_ARCH >/dev/null
+
		then
+
		    case $UNAME_PROCESSOR in
+
			i386) UNAME_PROCESSOR=x86_64 ;;
+
			powerpc) UNAME_PROCESSOR=powerpc64 ;;
+
		    esac
+
		fi
+
	    fi
+
	elif test "$UNAME_PROCESSOR" = i386 ; then
+
	    # Avoid executing cc on OS X 10.9, as it ships with a stub
+
	    # that puts up a graphical alert prompting to install
+
	    # developer tools.  Any system running Mac OS X 10.7 or
+
	    # later (Darwin 11 and later) is required to have a 64-bit
+
	    # processor. This is not true of the ARM version of Darwin
+
	    # that Apple uses in portable devices.
+
	    UNAME_PROCESSOR=x86_64
+
	fi
+
	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+
	exit ;;
+
    *:procnto*:*:* | *:QNX:[0123456789]*:*)
+
	UNAME_PROCESSOR=`uname -p`
+
	if test "$UNAME_PROCESSOR" = "x86"; then
+
		UNAME_PROCESSOR=i386
+
		UNAME_MACHINE=pc
+
	fi
+
	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+
	exit ;;
+
    *:QNX:*:4*)
+
	echo i386-pc-qnx
+
	exit ;;
+
    NEO-?:NONSTOP_KERNEL:*:*)
+
	echo neo-tandem-nsk${UNAME_RELEASE}
+
	exit ;;
+
    NSE-*:NONSTOP_KERNEL:*:*)
+
	echo nse-tandem-nsk${UNAME_RELEASE}
+
	exit ;;
+
    NSR-?:NONSTOP_KERNEL:*:*)
+
	echo nsr-tandem-nsk${UNAME_RELEASE}
+
	exit ;;
+
    *:NonStop-UX:*:*)
+
	echo mips-compaq-nonstopux
+
	exit ;;
+
    BS2000:POSIX*:*:*)
+
	echo bs2000-siemens-sysv
+
	exit ;;
+
    DS/*:UNIX_System_V:*:*)
+
	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+
	exit ;;
+
    *:Plan9:*:*)
+
	# "uname -m" is not consistent, so use $cputype instead. 386
+
	# is converted to i386 for consistency with other x86
+
	# operating systems.
+
	if test "$cputype" = "386"; then
+
	    UNAME_MACHINE=i386
+
	else
+
	    UNAME_MACHINE="$cputype"
+
	fi
+
	echo ${UNAME_MACHINE}-unknown-plan9
+
	exit ;;
+
    *:TOPS-10:*:*)
+
	echo pdp10-unknown-tops10
+
	exit ;;
+
    *:TENEX:*:*)
+
	echo pdp10-unknown-tenex
+
	exit ;;
+
    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+
	echo pdp10-dec-tops20
+
	exit ;;
+
    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+
	echo pdp10-xkl-tops20
+
	exit ;;
+
    *:TOPS-20:*:*)
+
	echo pdp10-unknown-tops20
+
	exit ;;
+
    *:ITS:*:*)
+
	echo pdp10-unknown-its
+
	exit ;;
+
    SEI:*:*:SEIUX)
+
	echo mips-sei-seiux${UNAME_RELEASE}
+
	exit ;;
+
    *:DragonFly:*:*)
+
	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+
	exit ;;
+
    *:*VMS:*:*)
+
	UNAME_MACHINE=`(uname -p) 2>/dev/null`
+
	case "${UNAME_MACHINE}" in
+
	    A*) echo alpha-dec-vms ; exit ;;
+
	    I*) echo ia64-dec-vms ; exit ;;
+
	    V*) echo vax-dec-vms ; exit ;;
+
	esac ;;
+
    *:XENIX:*:SysV)
+
	echo i386-pc-xenix
+
	exit ;;
+
    i*86:skyos:*:*)
+
	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+
	exit ;;
+
    i*86:rdos:*:*)
+
	echo ${UNAME_MACHINE}-pc-rdos
+
	exit ;;
+
    i*86:AROS:*:*)
+
	echo ${UNAME_MACHINE}-pc-aros
+
	exit ;;
+
    x86_64:VMkernel:*:*)
+
	echo ${UNAME_MACHINE}-unknown-esx
+
	exit ;;
+
esac
+

+
cat >&2 <<EOF
+
$0: unable to guess system type
+

+
This script, last modified $timestamp, has failed to recognize
+
the operating system you are using. It is advised that you
+
download the most up to date version of the config scripts from
+

+
  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+
and
+
  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+

+
If the version you run ($0) is already up to date, please
+
send the following data and any information you think might be
+
pertinent to <config-patches@gnu.org> in order to provide the needed
+
information to handle your system.
+

+
config.guess timestamp = $timestamp
+

+
uname -m = `(uname -m) 2>/dev/null || echo unknown`
+
uname -r = `(uname -r) 2>/dev/null || echo unknown`
+
uname -s = `(uname -s) 2>/dev/null || echo unknown`
+
uname -v = `(uname -v) 2>/dev/null || echo unknown`
+

+
/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+
/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`
+

+
hostinfo               = `(hostinfo) 2>/dev/null`
+
/bin/universe          = `(/bin/universe) 2>/dev/null`
+
/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
+
/bin/arch              = `(/bin/arch) 2>/dev/null`
+
/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
+
/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+

+
UNAME_MACHINE = ${UNAME_MACHINE}
+
UNAME_RELEASE = ${UNAME_RELEASE}
+
UNAME_SYSTEM  = ${UNAME_SYSTEM}
+
UNAME_VERSION = ${UNAME_VERSION}
+
EOF
+

+
exit 1
+

+
# Local variables:
+
# eval: (add-hook 'write-file-hooks 'time-stamp)
+
# time-stamp-start: "timestamp='"
+
# time-stamp-format: "%:y-%02m-%02d"
+
# time-stamp-end: "'"
+
# End:
added autosetup/autosetup-config.sub
@@ -0,0 +1,1807 @@
+
#! /bin/sh
+
# Configuration validation subroutine script.
+
#   Copyright 1992-2014 Free Software Foundation, Inc.
+

+
timestamp='2014-12-03'
+

+
# This file is free software; you can redistribute it and/or modify it
+
# under the terms of the GNU General Public License as published by
+
# the Free Software Foundation; either version 3 of the License, or
+
# (at your option) any later version.
+
#
+
# This program is distributed in the hope that it will be useful, but
+
# WITHOUT ANY WARRANTY; without even the implied warranty of
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+
# General Public License for more details.
+
#
+
# You should have received a copy of the GNU General Public License
+
# along with this program; if not, see <http://www.gnu.org/licenses/>.
+
#
+
# As a special exception to the GNU General Public License, if you
+
# distribute this file as part of a program that contains a
+
# configuration script generated by Autoconf, you may include it under
+
# the same distribution terms that you use for the rest of that
+
# program.  This Exception is an additional permission under section 7
+
# of the GNU General Public License, version 3 ("GPLv3").
+

+

+
# Please send patches to <config-patches@gnu.org>.
+
#
+
# Configuration subroutine to validate and canonicalize a configuration type.
+
# Supply the specified configuration type as an argument.
+
# If it is invalid, we print an error message on stderr and exit with code 1.
+
# Otherwise, we print the canonical config type on stdout and succeed.
+

+
# You can get the latest version of this script from:
+
# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+

+
# This file is supposed to be the same for all GNU packages
+
# and recognize all the CPU types, system types and aliases
+
# that are meaningful with *any* GNU software.
+
# Each package is responsible for reporting which valid configurations
+
# it does not support.  The user should be able to distinguish
+
# a failure to support a valid configuration from a meaningless
+
# configuration.
+

+
# The goal of this file is to map all the various variations of a given
+
# machine specification into a single specification in the form:
+
#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+
# or in some cases, the newer four-part form:
+
#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+
# It is wrong to echo any other type of specification.
+

+
me=`echo "$0" | sed -e 's,.*/,,'`
+

+
usage="\
+
Usage: $0 [OPTION] CPU-MFR-OPSYS
+
       $0 [OPTION] ALIAS
+

+
Canonicalize a configuration name.
+

+
Operation modes:
+
  -h, --help         print this help, then exit
+
  -t, --time-stamp   print date of last modification, then exit
+
  -v, --version      print version number, then exit
+

+
Report bugs and patches to <config-patches@gnu.org>."
+

+
version="\
+
GNU config.sub ($timestamp)
+

+
Copyright 1992-2014 Free Software Foundation, Inc.
+

+
This is free software; see the source for copying conditions.  There is NO
+
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+

+
help="
+
Try \`$me --help' for more information."
+

+
# Parse command line
+
while test $# -gt 0 ; do
+
  case $1 in
+
    --time-stamp | --time* | -t )
+
       echo "$timestamp" ; exit ;;
+
    --version | -v )
+
       echo "$version" ; exit ;;
+
    --help | --h* | -h )
+
       echo "$usage"; exit ;;
+
    -- )     # Stop option processing
+
       shift; break ;;
+
    - )	# Use stdin as input.
+
       break ;;
+
    -* )
+
       echo "$me: invalid option $1$help"
+
       exit 1 ;;
+

+
    *local*)
+
       # First pass through any local machine types.
+
       echo $1
+
       exit ;;
+

+
    * )
+
       break ;;
+
  esac
+
done
+

+
case $# in
+
 0) echo "$me: missing argument$help" >&2
+
    exit 1;;
+
 1) ;;
+
 *) echo "$me: too many arguments$help" >&2
+
    exit 1;;
+
esac
+

+
# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+
# Here we must recognize all the valid KERNEL-OS combinations.
+
maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+
case $maybe_os in
+
  nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
+
  linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
+
  knetbsd*-gnu* | netbsd*-gnu* | \
+
  kopensolaris*-gnu* | \
+
  storm-chaos* | os2-emx* | rtmk-nova*)
+
    os=-$maybe_os
+
    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+
    ;;
+
  android-linux)
+
    os=-linux-android
+
    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
+
    ;;
+
  *)
+
    basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+
    if [ $basic_machine != $1 ]
+
    then os=`echo $1 | sed 's/.*-/-/'`
+
    else os=; fi
+
    ;;
+
esac
+

+
### Let's recognize common machines as not being operating systems so
+
### that things like config.sub decstation-3100 work.  We also
+
### recognize some manufacturers as not being operating systems, so we
+
### can provide default operating systems below.
+
case $os in
+
	-sun*os*)
+
		# Prevent following clause from handling this invalid input.
+
		;;
+
	-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+
	-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+
	-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+
	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+
	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+
	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+
	-apple | -axis | -knuth | -cray | -microblaze*)
+
		os=
+
		basic_machine=$1
+
		;;
+
	-bluegene*)
+
		os=-cnk
+
		;;
+
	-sim | -cisco | -oki | -wec | -winbond)
+
		os=
+
		basic_machine=$1
+
		;;
+
	-scout)
+
		;;
+
	-wrs)
+
		os=-vxworks
+
		basic_machine=$1
+
		;;
+
	-chorusos*)
+
		os=-chorusos
+
		basic_machine=$1
+
		;;
+
	-chorusrdb)
+
		os=-chorusrdb
+
		basic_machine=$1
+
		;;
+
	-hiux*)
+
		os=-hiuxwe2
+
		;;
+
	-sco6)
+
		os=-sco5v6
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-sco5)
+
		os=-sco3.2v5
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-sco4)
+
		os=-sco3.2v4
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-sco3.2.[4-9]*)
+
		os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-sco3.2v[4-9]*)
+
		# Don't forget version if it is 3.2v4 or newer.
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-sco5v6*)
+
		# Don't forget version if it is 3.2v4 or newer.
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-sco*)
+
		os=-sco3.2v2
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-udk*)
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-isc)
+
		os=-isc2.2
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-clix*)
+
		basic_machine=clipper-intergraph
+
		;;
+
	-isc*)
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+
		;;
+
	-lynx*178)
+
		os=-lynxos178
+
		;;
+
	-lynx*5)
+
		os=-lynxos5
+
		;;
+
	-lynx*)
+
		os=-lynxos
+
		;;
+
	-ptx*)
+
		basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+
		;;
+
	-windowsnt*)
+
		os=`echo $os | sed -e 's/windowsnt/winnt/'`
+
		;;
+
	-psos*)
+
		os=-psos
+
		;;
+
	-mint | -mint[0-9]*)
+
		basic_machine=m68k-atari
+
		os=-mint
+
		;;
+
esac
+

+
# Decode aliases for certain CPU-COMPANY combinations.
+
case $basic_machine in
+
	# Recognize the basic CPU types without company name.
+
	# Some are omitted here because they have special meanings below.
+
	1750a | 580 \
+
	| a29k \
+
	| aarch64 | aarch64_be \
+
	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+
	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+
	| am33_2.0 \
+
	| arc | arceb \
+
	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
+
	| avr | avr32 \
+
	| be32 | be64 \
+
	| bfin \
+
	| c4x | c8051 | clipper \
+
	| d10v | d30v | dlx | dsp16xx \
+
	| epiphany \
+
	| fido | fr30 | frv \
+
	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+
	| hexagon \
+
	| i370 | i860 | i960 | ia64 \
+
	| ip2k | iq2000 \
+
	| k1om \
+
	| le32 | le64 \
+
	| lm32 \
+
	| m32c | m32r | m32rle | m68000 | m68k | m88k \
+
	| maxq | mb | microblaze | microblazeel | mcore | mep | metag \
+
	| mips | mipsbe | mipseb | mipsel | mipsle \
+
	| mips16 \
+
	| mips64 | mips64el \
+
	| mips64octeon | mips64octeonel \
+
	| mips64orion | mips64orionel \
+
	| mips64r5900 | mips64r5900el \
+
	| mips64vr | mips64vrel \
+
	| mips64vr4100 | mips64vr4100el \
+
	| mips64vr4300 | mips64vr4300el \
+
	| mips64vr5000 | mips64vr5000el \
+
	| mips64vr5900 | mips64vr5900el \
+
	| mipsisa32 | mipsisa32el \
+
	| mipsisa32r2 | mipsisa32r2el \
+
	| mipsisa32r6 | mipsisa32r6el \
+
	| mipsisa64 | mipsisa64el \
+
	| mipsisa64r2 | mipsisa64r2el \
+
	| mipsisa64r6 | mipsisa64r6el \
+
	| mipsisa64sb1 | mipsisa64sb1el \
+
	| mipsisa64sr71k | mipsisa64sr71kel \
+
	| mipsr5900 | mipsr5900el \
+
	| mipstx39 | mipstx39el \
+
	| mn10200 | mn10300 \
+
	| moxie \
+
	| mt \
+
	| msp430 \
+
	| nds32 | nds32le | nds32be \
+
	| nios | nios2 | nios2eb | nios2el \
+
	| ns16k | ns32k \
+
	| open8 | or1k | or1knd | or32 \
+
	| pdp10 | pdp11 | pj | pjl \
+
	| powerpc | powerpc64 | powerpc64le | powerpcle \
+
	| pyramid \
+
	| riscv32 | riscv64 \
+
	| rl78 | rx \
+
	| score \
+
	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+
	| sh64 | sh64le \
+
	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+
	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+
	| spu \
+
	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
+
	| ubicom32 \
+
	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+
	| visium \
+
	| we32k \
+
	| x86 | xc16x | xstormy16 | xtensa \
+
	| z8k | z80)
+
		basic_machine=$basic_machine-unknown
+
		;;
+
	c54x)
+
		basic_machine=tic54x-unknown
+
		;;
+
	c55x)
+
		basic_machine=tic55x-unknown
+
		;;
+
	c6x)
+
		basic_machine=tic6x-unknown
+
		;;
+
	leon|leon[3-9])
+
		basic_machine=sparc-$basic_machine
+
		;;
+
	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
+
		basic_machine=$basic_machine-unknown
+
		os=-none
+
		;;
+
	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+
		;;
+
	ms1)
+
		basic_machine=mt-unknown
+
		;;
+

+
	strongarm | thumb | xscale)
+
		basic_machine=arm-unknown
+
		;;
+
	xgate)
+
		basic_machine=$basic_machine-unknown
+
		os=-none
+
		;;
+
	xscaleeb)
+
		basic_machine=armeb-unknown
+
		;;
+

+
	xscaleel)
+
		basic_machine=armel-unknown
+
		;;
+

+
	# We use `pc' rather than `unknown'
+
	# because (1) that's what they normally are, and
+
	# (2) the word "unknown" tends to confuse beginning users.
+
	i*86 | x86_64)
+
	  basic_machine=$basic_machine-pc
+
	  ;;
+
	# Object if more than one company name word.
+
	*-*-*)
+
		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+
		exit 1
+
		;;
+
	# Recognize the basic CPU types with company name.
+
	580-* \
+
	| a29k-* \
+
	| aarch64-* | aarch64_be-* \
+
	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+
	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+
	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
+
	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
+
	| avr-* | avr32-* \
+
	| be32-* | be64-* \
+
	| bfin-* | bs2000-* \
+
	| c[123]* | c30-* | [cjt]90-* | c4x-* \
+
	| c8051-* | clipper-* | craynv-* | cydra-* \
+
	| d10v-* | d30v-* | dlx-* \
+
	| elxsi-* \
+
	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+
	| h8300-* | h8500-* \
+
	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+
	| hexagon-* \
+
	| i*86-* | i860-* | i960-* | ia64-* \
+
	| ip2k-* | iq2000-* \
+
	| k1om-* \
+
	| le32-* | le64-* \
+
	| lm32-* \
+
	| m32c-* | m32r-* | m32rle-* \
+
	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+
	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
+
	| microblaze-* | microblazeel-* \
+
	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+
	| mips16-* \
+
	| mips64-* | mips64el-* \
+
	| mips64octeon-* | mips64octeonel-* \
+
	| mips64orion-* | mips64orionel-* \
+
	| mips64r5900-* | mips64r5900el-* \
+
	| mips64vr-* | mips64vrel-* \
+
	| mips64vr4100-* | mips64vr4100el-* \
+
	| mips64vr4300-* | mips64vr4300el-* \
+
	| mips64vr5000-* | mips64vr5000el-* \
+
	| mips64vr5900-* | mips64vr5900el-* \
+
	| mipsisa32-* | mipsisa32el-* \
+
	| mipsisa32r2-* | mipsisa32r2el-* \
+
	| mipsisa32r6-* | mipsisa32r6el-* \
+
	| mipsisa64-* | mipsisa64el-* \
+
	| mipsisa64r2-* | mipsisa64r2el-* \
+
	| mipsisa64r6-* | mipsisa64r6el-* \
+
	| mipsisa64sb1-* | mipsisa64sb1el-* \
+
	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+
	| mipsr5900-* | mipsr5900el-* \
+
	| mipstx39-* | mipstx39el-* \
+
	| mmix-* \
+
	| mt-* \
+
	| msp430-* \
+
	| nds32-* | nds32le-* | nds32be-* \
+
	| nios-* | nios2-* | nios2eb-* | nios2el-* \
+
	| none-* | np1-* | ns16k-* | ns32k-* \
+
	| open8-* \
+
	| or1k*-* \
+
	| orion-* \
+
	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+
	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+
	| pyramid-* \
+
	| rl78-* | romp-* | rs6000-* | rx-* \
+
	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+
	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+
	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+
	| sparclite-* \
+
	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
+
	| tahoe-* \
+
	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+
	| tile*-* \
+
	| tron-* \
+
	| ubicom32-* \
+
	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
+
	| vax-* \
+
	| visium-* \
+
	| we32k-* \
+
	| x86-* | x86_64-* | xc16x-* | xps100-* \
+
	| xstormy16-* | xtensa*-* \
+
	| ymp-* \
+
	| z8k-* | z80-*)
+
		;;
+
	# Recognize the basic CPU types without company name, with glob match.
+
	xtensa*)
+
		basic_machine=$basic_machine-unknown
+
		;;
+
	# Recognize the various machine names and aliases which stand
+
	# for a CPU type and a company and sometimes even an OS.
+
	386bsd)
+
		basic_machine=i386-unknown
+
		os=-bsd
+
		;;
+
	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+
		basic_machine=m68000-att
+
		;;
+
	3b*)
+
		basic_machine=we32k-att
+
		;;
+
	a29khif)
+
		basic_machine=a29k-amd
+
		os=-udi
+
		;;
+
	abacus)
+
		basic_machine=abacus-unknown
+
		;;
+
	adobe68k)
+
		basic_machine=m68010-adobe
+
		os=-scout
+
		;;
+
	alliant | fx80)
+
		basic_machine=fx80-alliant
+
		;;
+
	altos | altos3068)
+
		basic_machine=m68k-altos
+
		;;
+
	am29k)
+
		basic_machine=a29k-none
+
		os=-bsd
+
		;;
+
	amd64)
+
		basic_machine=x86_64-pc
+
		;;
+
	amd64-*)
+
		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	amdahl)
+
		basic_machine=580-amdahl
+
		os=-sysv
+
		;;
+
	amiga | amiga-*)
+
		basic_machine=m68k-unknown
+
		;;
+
	amigaos | amigados)
+
		basic_machine=m68k-unknown
+
		os=-amigaos
+
		;;
+
	amigaunix | amix)
+
		basic_machine=m68k-unknown
+
		os=-sysv4
+
		;;
+
	apollo68)
+
		basic_machine=m68k-apollo
+
		os=-sysv
+
		;;
+
	apollo68bsd)
+
		basic_machine=m68k-apollo
+
		os=-bsd
+
		;;
+
	aros)
+
		basic_machine=i386-pc
+
		os=-aros
+
		;;
+
	aux)
+
		basic_machine=m68k-apple
+
		os=-aux
+
		;;
+
	balance)
+
		basic_machine=ns32k-sequent
+
		os=-dynix
+
		;;
+
	blackfin)
+
		basic_machine=bfin-unknown
+
		os=-linux
+
		;;
+
	blackfin-*)
+
		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		os=-linux
+
		;;
+
	bluegene*)
+
		basic_machine=powerpc-ibm
+
		os=-cnk
+
		;;
+
	c54x-*)
+
		basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	c55x-*)
+
		basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	c6x-*)
+
		basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	c90)
+
		basic_machine=c90-cray
+
		os=-unicos
+
		;;
+
	cegcc)
+
		basic_machine=arm-unknown
+
		os=-cegcc
+
		;;
+
	convex-c1)
+
		basic_machine=c1-convex
+
		os=-bsd
+
		;;
+
	convex-c2)
+
		basic_machine=c2-convex
+
		os=-bsd
+
		;;
+
	convex-c32)
+
		basic_machine=c32-convex
+
		os=-bsd
+
		;;
+
	convex-c34)
+
		basic_machine=c34-convex
+
		os=-bsd
+
		;;
+
	convex-c38)
+
		basic_machine=c38-convex
+
		os=-bsd
+
		;;
+
	cray | j90)
+
		basic_machine=j90-cray
+
		os=-unicos
+
		;;
+
	craynv)
+
		basic_machine=craynv-cray
+
		os=-unicosmp
+
		;;
+
	cr16 | cr16-*)
+
		basic_machine=cr16-unknown
+
		os=-elf
+
		;;
+
	crds | unos)
+
		basic_machine=m68k-crds
+
		;;
+
	crisv32 | crisv32-* | etraxfs*)
+
		basic_machine=crisv32-axis
+
		;;
+
	cris | cris-* | etrax*)
+
		basic_machine=cris-axis
+
		;;
+
	crx)
+
		basic_machine=crx-unknown
+
		os=-elf
+
		;;
+
	da30 | da30-*)
+
		basic_machine=m68k-da30
+
		;;
+
	decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+
		basic_machine=mips-dec
+
		;;
+
	decsystem10* | dec10*)
+
		basic_machine=pdp10-dec
+
		os=-tops10
+
		;;
+
	decsystem20* | dec20*)
+
		basic_machine=pdp10-dec
+
		os=-tops20
+
		;;
+
	delta | 3300 | motorola-3300 | motorola-delta \
+
	      | 3300-motorola | delta-motorola)
+
		basic_machine=m68k-motorola
+
		;;
+
	delta88)
+
		basic_machine=m88k-motorola
+
		os=-sysv3
+
		;;
+
	dicos)
+
		basic_machine=i686-pc
+
		os=-dicos
+
		;;
+
	djgpp)
+
		basic_machine=i586-pc
+
		os=-msdosdjgpp
+
		;;
+
	dpx20 | dpx20-*)
+
		basic_machine=rs6000-bull
+
		os=-bosx
+
		;;
+
	dpx2* | dpx2*-bull)
+
		basic_machine=m68k-bull
+
		os=-sysv3
+
		;;
+
	ebmon29k)
+
		basic_machine=a29k-amd
+
		os=-ebmon
+
		;;
+
	elxsi)
+
		basic_machine=elxsi-elxsi
+
		os=-bsd
+
		;;
+
	encore | umax | mmax)
+
		basic_machine=ns32k-encore
+
		;;
+
	es1800 | OSE68k | ose68k | ose | OSE)
+
		basic_machine=m68k-ericsson
+
		os=-ose
+
		;;
+
	fx2800)
+
		basic_machine=i860-alliant
+
		;;
+
	genix)
+
		basic_machine=ns32k-ns
+
		;;
+
	gmicro)
+
		basic_machine=tron-gmicro
+
		os=-sysv
+
		;;
+
	go32)
+
		basic_machine=i386-pc
+
		os=-go32
+
		;;
+
	h3050r* | hiux*)
+
		basic_machine=hppa1.1-hitachi
+
		os=-hiuxwe2
+
		;;
+
	h8300hms)
+
		basic_machine=h8300-hitachi
+
		os=-hms
+
		;;
+
	h8300xray)
+
		basic_machine=h8300-hitachi
+
		os=-xray
+
		;;
+
	h8500hms)
+
		basic_machine=h8500-hitachi
+
		os=-hms
+
		;;
+
	harris)
+
		basic_machine=m88k-harris
+
		os=-sysv3
+
		;;
+
	hp300-*)
+
		basic_machine=m68k-hp
+
		;;
+
	hp300bsd)
+
		basic_machine=m68k-hp
+
		os=-bsd
+
		;;
+
	hp300hpux)
+
		basic_machine=m68k-hp
+
		os=-hpux
+
		;;
+
	hp3k9[0-9][0-9] | hp9[0-9][0-9])
+
		basic_machine=hppa1.0-hp
+
		;;
+
	hp9k2[0-9][0-9] | hp9k31[0-9])
+
		basic_machine=m68000-hp
+
		;;
+
	hp9k3[2-9][0-9])
+
		basic_machine=m68k-hp
+
		;;
+
	hp9k6[0-9][0-9] | hp6[0-9][0-9])
+
		basic_machine=hppa1.0-hp
+
		;;
+
	hp9k7[0-79][0-9] | hp7[0-79][0-9])
+
		basic_machine=hppa1.1-hp
+
		;;
+
	hp9k78[0-9] | hp78[0-9])
+
		# FIXME: really hppa2.0-hp
+
		basic_machine=hppa1.1-hp
+
		;;
+
	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+
		# FIXME: really hppa2.0-hp
+
		basic_machine=hppa1.1-hp
+
		;;
+
	hp9k8[0-9][13679] | hp8[0-9][13679])
+
		basic_machine=hppa1.1-hp
+
		;;
+
	hp9k8[0-9][0-9] | hp8[0-9][0-9])
+
		basic_machine=hppa1.0-hp
+
		;;
+
	hppa-next)
+
		os=-nextstep3
+
		;;
+
	hppaosf)
+
		basic_machine=hppa1.1-hp
+
		os=-osf
+
		;;
+
	hppro)
+
		basic_machine=hppa1.1-hp
+
		os=-proelf
+
		;;
+
	i370-ibm* | ibm*)
+
		basic_machine=i370-ibm
+
		;;
+
	i*86v32)
+
		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+
		os=-sysv32
+
		;;
+
	i*86v4*)
+
		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+
		os=-sysv4
+
		;;
+
	i*86v)
+
		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+
		os=-sysv
+
		;;
+
	i*86sol2)
+
		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+
		os=-solaris2
+
		;;
+
	i386mach)
+
		basic_machine=i386-mach
+
		os=-mach
+
		;;
+
	i386-vsta | vsta)
+
		basic_machine=i386-unknown
+
		os=-vsta
+
		;;
+
	iris | iris4d)
+
		basic_machine=mips-sgi
+
		case $os in
+
		    -irix*)
+
			;;
+
		    *)
+
			os=-irix4
+
			;;
+
		esac
+
		;;
+
	isi68 | isi)
+
		basic_machine=m68k-isi
+
		os=-sysv
+
		;;
+
	leon-*|leon[3-9]-*)
+
		basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'`
+
		;;
+
	m68knommu)
+
		basic_machine=m68k-unknown
+
		os=-linux
+
		;;
+
	m68knommu-*)
+
		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		os=-linux
+
		;;
+
	m88k-omron*)
+
		basic_machine=m88k-omron
+
		;;
+
	magnum | m3230)
+
		basic_machine=mips-mips
+
		os=-sysv
+
		;;
+
	merlin)
+
		basic_machine=ns32k-utek
+
		os=-sysv
+
		;;
+
	microblaze*)
+
		basic_machine=microblaze-xilinx
+
		;;
+
	mingw64)
+
		basic_machine=x86_64-pc
+
		os=-mingw64
+
		;;
+
	mingw32)
+
		basic_machine=i686-pc
+
		os=-mingw32
+
		;;
+
	mingw32ce)
+
		basic_machine=arm-unknown
+
		os=-mingw32ce
+
		;;
+
	miniframe)
+
		basic_machine=m68000-convergent
+
		;;
+
	*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+
		basic_machine=m68k-atari
+
		os=-mint
+
		;;
+
	mips3*-*)
+
		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+
		;;
+
	mips3*)
+
		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+
		;;
+
	monitor)
+
		basic_machine=m68k-rom68k
+
		os=-coff
+
		;;
+
	morphos)
+
		basic_machine=powerpc-unknown
+
		os=-morphos
+
		;;
+
	moxiebox)
+
		basic_machine=moxie-unknown
+
		os=-moxiebox
+
		;;
+
	msdos)
+
		basic_machine=i386-pc
+
		os=-msdos
+
		;;
+
	ms1-*)
+
		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+
		;;
+
	msys)
+
		basic_machine=i686-pc
+
		os=-msys
+
		;;
+
	mvs)
+
		basic_machine=i370-ibm
+
		os=-mvs
+
		;;
+
	nacl)
+
		basic_machine=le32-unknown
+
		os=-nacl
+
		;;
+
	ncr3000)
+
		basic_machine=i486-ncr
+
		os=-sysv4
+
		;;
+
	netbsd386)
+
		basic_machine=i386-unknown
+
		os=-netbsd
+
		;;
+
	netwinder)
+
		basic_machine=armv4l-rebel
+
		os=-linux
+
		;;
+
	news | news700 | news800 | news900)
+
		basic_machine=m68k-sony
+
		os=-newsos
+
		;;
+
	news1000)
+
		basic_machine=m68030-sony
+
		os=-newsos
+
		;;
+
	news-3600 | risc-news)
+
		basic_machine=mips-sony
+
		os=-newsos
+
		;;
+
	necv70)
+
		basic_machine=v70-nec
+
		os=-sysv
+
		;;
+
	next | m*-next )
+
		basic_machine=m68k-next
+
		case $os in
+
		    -nextstep* )
+
			;;
+
		    -ns2*)
+
		      os=-nextstep2
+
			;;
+
		    *)
+
		      os=-nextstep3
+
			;;
+
		esac
+
		;;
+
	nh3000)
+
		basic_machine=m68k-harris
+
		os=-cxux
+
		;;
+
	nh[45]000)
+
		basic_machine=m88k-harris
+
		os=-cxux
+
		;;
+
	nindy960)
+
		basic_machine=i960-intel
+
		os=-nindy
+
		;;
+
	mon960)
+
		basic_machine=i960-intel
+
		os=-mon960
+
		;;
+
	nonstopux)
+
		basic_machine=mips-compaq
+
		os=-nonstopux
+
		;;
+
	np1)
+
		basic_machine=np1-gould
+
		;;
+
	neo-tandem)
+
		basic_machine=neo-tandem
+
		;;
+
	nse-tandem)
+
		basic_machine=nse-tandem
+
		;;
+
	nsr-tandem)
+
		basic_machine=nsr-tandem
+
		;;
+
	op50n-* | op60c-*)
+
		basic_machine=hppa1.1-oki
+
		os=-proelf
+
		;;
+
	openrisc | openrisc-*)
+
		basic_machine=or32-unknown
+
		;;
+
	os400)
+
		basic_machine=powerpc-ibm
+
		os=-os400
+
		;;
+
	OSE68000 | ose68000)
+
		basic_machine=m68000-ericsson
+
		os=-ose
+
		;;
+
	os68k)
+
		basic_machine=m68k-none
+
		os=-os68k
+
		;;
+
	pa-hitachi)
+
		basic_machine=hppa1.1-hitachi
+
		os=-hiuxwe2
+
		;;
+
	paragon)
+
		basic_machine=i860-intel
+
		os=-osf
+
		;;
+
	parisc)
+
		basic_machine=hppa-unknown
+
		os=-linux
+
		;;
+
	parisc-*)
+
		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		os=-linux
+
		;;
+
	pbd)
+
		basic_machine=sparc-tti
+
		;;
+
	pbb)
+
		basic_machine=m68k-tti
+
		;;
+
	pc532 | pc532-*)
+
		basic_machine=ns32k-pc532
+
		;;
+
	pc98)
+
		basic_machine=i386-pc
+
		;;
+
	pc98-*)
+
		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	pentium | p5 | k5 | k6 | nexgen | viac3)
+
		basic_machine=i586-pc
+
		;;
+
	pentiumpro | p6 | 6x86 | athlon | athlon_*)
+
		basic_machine=i686-pc
+
		;;
+
	pentiumii | pentium2 | pentiumiii | pentium3)
+
		basic_machine=i686-pc
+
		;;
+
	pentium4)
+
		basic_machine=i786-pc
+
		;;
+
	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+
		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	pentiumpro-* | p6-* | 6x86-* | athlon-*)
+
		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+
		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	pentium4-*)
+
		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	pn)
+
		basic_machine=pn-gould
+
		;;
+
	power)	basic_machine=power-ibm
+
		;;
+
	ppc | ppcbe)	basic_machine=powerpc-unknown
+
		;;
+
	ppc-* | ppcbe-*)
+
		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	ppcle | powerpclittle | ppc-le | powerpc-little)
+
		basic_machine=powerpcle-unknown
+
		;;
+
	ppcle-* | powerpclittle-*)
+
		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	ppc64)	basic_machine=powerpc64-unknown
+
		;;
+
	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+
		basic_machine=powerpc64le-unknown
+
		;;
+
	ppc64le-* | powerpc64little-*)
+
		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	ps2)
+
		basic_machine=i386-ibm
+
		;;
+
	pw32)
+
		basic_machine=i586-unknown
+
		os=-pw32
+
		;;
+
	rdos | rdos64)
+
		basic_machine=x86_64-pc
+
		os=-rdos
+
		;;
+
	rdos32)
+
		basic_machine=i386-pc
+
		os=-rdos
+
		;;
+
	rom68k)
+
		basic_machine=m68k-rom68k
+
		os=-coff
+
		;;
+
	rm[46]00)
+
		basic_machine=mips-siemens
+
		;;
+
	rtpc | rtpc-*)
+
		basic_machine=romp-ibm
+
		;;
+
	s390 | s390-*)
+
		basic_machine=s390-ibm
+
		;;
+
	s390x | s390x-*)
+
		basic_machine=s390x-ibm
+
		;;
+
	sa29200)
+
		basic_machine=a29k-amd
+
		os=-udi
+
		;;
+
	sb1)
+
		basic_machine=mipsisa64sb1-unknown
+
		;;
+
	sb1el)
+
		basic_machine=mipsisa64sb1el-unknown
+
		;;
+
	sde)
+
		basic_machine=mipsisa32-sde
+
		os=-elf
+
		;;
+
	sei)
+
		basic_machine=mips-sei
+
		os=-seiux
+
		;;
+
	sequent)
+
		basic_machine=i386-sequent
+
		;;
+
	sh)
+
		basic_machine=sh-hitachi
+
		os=-hms
+
		;;
+
	sh5el)
+
		basic_machine=sh5le-unknown
+
		;;
+
	sh64)
+
		basic_machine=sh64-unknown
+
		;;
+
	sparclite-wrs | simso-wrs)
+
		basic_machine=sparclite-wrs
+
		os=-vxworks
+
		;;
+
	sps7)
+
		basic_machine=m68k-bull
+
		os=-sysv2
+
		;;
+
	spur)
+
		basic_machine=spur-unknown
+
		;;
+
	st2000)
+
		basic_machine=m68k-tandem
+
		;;
+
	stratus)
+
		basic_machine=i860-stratus
+
		os=-sysv4
+
		;;
+
	strongarm-* | thumb-*)
+
		basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
+
		;;
+
	sun2)
+
		basic_machine=m68000-sun
+
		;;
+
	sun2os3)
+
		basic_machine=m68000-sun
+
		os=-sunos3
+
		;;
+
	sun2os4)
+
		basic_machine=m68000-sun
+
		os=-sunos4
+
		;;
+
	sun3os3)
+
		basic_machine=m68k-sun
+
		os=-sunos3
+
		;;
+
	sun3os4)
+
		basic_machine=m68k-sun
+
		os=-sunos4
+
		;;
+
	sun4os3)
+
		basic_machine=sparc-sun
+
		os=-sunos3
+
		;;
+
	sun4os4)
+
		basic_machine=sparc-sun
+
		os=-sunos4
+
		;;
+
	sun4sol2)
+
		basic_machine=sparc-sun
+
		os=-solaris2
+
		;;
+
	sun3 | sun3-*)
+
		basic_machine=m68k-sun
+
		;;
+
	sun4)
+
		basic_machine=sparc-sun
+
		;;
+
	sun386 | sun386i | roadrunner)
+
		basic_machine=i386-sun
+
		;;
+
	sv1)
+
		basic_machine=sv1-cray
+
		os=-unicos
+
		;;
+
	symmetry)
+
		basic_machine=i386-sequent
+
		os=-dynix
+
		;;
+
	t3e)
+
		basic_machine=alphaev5-cray
+
		os=-unicos
+
		;;
+
	t90)
+
		basic_machine=t90-cray
+
		os=-unicos
+
		;;
+
	tile*)
+
		basic_machine=$basic_machine-unknown
+
		os=-linux-gnu
+
		;;
+
	tx39)
+
		basic_machine=mipstx39-unknown
+
		;;
+
	tx39el)
+
		basic_machine=mipstx39el-unknown
+
		;;
+
	toad1)
+
		basic_machine=pdp10-xkl
+
		os=-tops20
+
		;;
+
	tower | tower-32)
+
		basic_machine=m68k-ncr
+
		;;
+
	tpf)
+
		basic_machine=s390x-ibm
+
		os=-tpf
+
		;;
+
	udi29k)
+
		basic_machine=a29k-amd
+
		os=-udi
+
		;;
+
	ultra3)
+
		basic_machine=a29k-nyu
+
		os=-sym1
+
		;;
+
	v810 | necv810)
+
		basic_machine=v810-nec
+
		os=-none
+
		;;
+
	vaxv)
+
		basic_machine=vax-dec
+
		os=-sysv
+
		;;
+
	vms)
+
		basic_machine=vax-dec
+
		os=-vms
+
		;;
+
	vpp*|vx|vx-*)
+
		basic_machine=f301-fujitsu
+
		;;
+
	vxworks960)
+
		basic_machine=i960-wrs
+
		os=-vxworks
+
		;;
+
	vxworks68)
+
		basic_machine=m68k-wrs
+
		os=-vxworks
+
		;;
+
	vxworks29k)
+
		basic_machine=a29k-wrs
+
		os=-vxworks
+
		;;
+
	w65*)
+
		basic_machine=w65-wdc
+
		os=-none
+
		;;
+
	w89k-*)
+
		basic_machine=hppa1.1-winbond
+
		os=-proelf
+
		;;
+
	xbox)
+
		basic_machine=i686-pc
+
		os=-mingw32
+
		;;
+
	xps | xps100)
+
		basic_machine=xps100-honeywell
+
		;;
+
	xscale-* | xscalee[bl]-*)
+
		basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
+
		;;
+
	ymp)
+
		basic_machine=ymp-cray
+
		os=-unicos
+
		;;
+
	z8k-*-coff)
+
		basic_machine=z8k-unknown
+
		os=-sim
+
		;;
+
	z80-*-coff)
+
		basic_machine=z80-unknown
+
		os=-sim
+
		;;
+
	none)
+
		basic_machine=none-none
+
		os=-none
+
		;;
+

+
# Here we handle the default manufacturer of certain CPU types.  It is in
+
# some cases the only manufacturer, in others, it is the most popular.
+
	w89k)
+
		basic_machine=hppa1.1-winbond
+
		;;
+
	op50n)
+
		basic_machine=hppa1.1-oki
+
		;;
+
	op60c)
+
		basic_machine=hppa1.1-oki
+
		;;
+
	romp)
+
		basic_machine=romp-ibm
+
		;;
+
	mmix)
+
		basic_machine=mmix-knuth
+
		;;
+
	rs6000)
+
		basic_machine=rs6000-ibm
+
		;;
+
	vax)
+
		basic_machine=vax-dec
+
		;;
+
	pdp10)
+
		# there are many clones, so DEC is not a safe bet
+
		basic_machine=pdp10-unknown
+
		;;
+
	pdp11)
+
		basic_machine=pdp11-dec
+
		;;
+
	we32k)
+
		basic_machine=we32k-att
+
		;;
+
	sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
+
		basic_machine=sh-unknown
+
		;;
+
	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
+
		basic_machine=sparc-sun
+
		;;
+
	cydra)
+
		basic_machine=cydra-cydrome
+
		;;
+
	orion)
+
		basic_machine=orion-highlevel
+
		;;
+
	orion105)
+
		basic_machine=clipper-highlevel
+
		;;
+
	mac | mpw | mac-mpw)
+
		basic_machine=m68k-apple
+
		;;
+
	pmac | pmac-mpw)
+
		basic_machine=powerpc-apple
+
		;;
+
	*-unknown)
+
		# Make sure to match an already-canonicalized machine name.
+
		;;
+
	*)
+
		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+
		exit 1
+
		;;
+
esac
+

+
# Here we canonicalize certain aliases for manufacturers.
+
case $basic_machine in
+
	*-digital*)
+
		basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+
		;;
+
	*-commodore*)
+
		basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+
		;;
+
	*)
+
		;;
+
esac
+

+
# Decode manufacturer-specific aliases for certain operating systems.
+

+
if [ x"$os" != x"" ]
+
then
+
case $os in
+
	# First match some system type aliases
+
	# that might get confused with valid system types.
+
	# -solaris* is a basic system type, with this one exception.
+
	-auroraux)
+
		os=-auroraux
+
		;;
+
	-solaris1 | -solaris1.*)
+
		os=`echo $os | sed -e 's|solaris1|sunos4|'`
+
		;;
+
	-solaris)
+
		os=-solaris2
+
		;;
+
	-svr4*)
+
		os=-sysv4
+
		;;
+
	-unixware*)
+
		os=-sysv4.2uw
+
		;;
+
	-gnu/linux*)
+
		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+
		;;
+
	# First accept the basic system types.
+
	# The portable systems comes first.
+
	# Each alternative MUST END IN A *, to match a version number.
+
	# -sysv* is not here because it comes later, after sysvr4.
+
	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+
	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
+
	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
+
	      | -sym* | -kopensolaris* | -plan9* \
+
	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+
	      | -aos* | -aros* \
+
	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+
	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+
	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+
	      | -bitrig* | -openbsd* | -solidbsd* \
+
	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+
	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+
	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+
	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+
	      | -chorusos* | -chorusrdb* | -cegcc* \
+
	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+
	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
+
	      | -linux-newlib* | -linux-musl* | -linux-uclibc* \
+
	      | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
+
	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+
	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+
	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+
	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+
	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+
	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+
	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*)
+
	# Remember, each alternative MUST END IN *, to match a version number.
+
		;;
+
	-qnx*)
+
		case $basic_machine in
+
		    x86-* | i*86-*)
+
			;;
+
		    *)
+
			os=-nto$os
+
			;;
+
		esac
+
		;;
+
	-nto-qnx*)
+
		;;
+
	-nto*)
+
		os=`echo $os | sed -e 's|nto|nto-qnx|'`
+
		;;
+
	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+
	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+
	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+
		;;
+
	-mac*)
+
		os=`echo $os | sed -e 's|mac|macos|'`
+
		;;
+
	-linux-dietlibc)
+
		os=-linux-dietlibc
+
		;;
+
	-linux*)
+
		os=`echo $os | sed -e 's|linux|linux-gnu|'`
+
		;;
+
	-sunos5*)
+
		os=`echo $os | sed -e 's|sunos5|solaris2|'`
+
		;;
+
	-sunos6*)
+
		os=`echo $os | sed -e 's|sunos6|solaris3|'`
+
		;;
+
	-opened*)
+
		os=-openedition
+
		;;
+
	-os400*)
+
		os=-os400
+
		;;
+
	-wince*)
+
		os=-wince
+
		;;
+
	-osfrose*)
+
		os=-osfrose
+
		;;
+
	-osf*)
+
		os=-osf
+
		;;
+
	-utek*)
+
		os=-bsd
+
		;;
+
	-dynix*)
+
		os=-bsd
+
		;;
+
	-acis*)
+
		os=-aos
+
		;;
+
	-atheos*)
+
		os=-atheos
+
		;;
+
	-syllable*)
+
		os=-syllable
+
		;;
+
	-386bsd)
+
		os=-bsd
+
		;;
+
	-ctix* | -uts*)
+
		os=-sysv
+
		;;
+
	-nova*)
+
		os=-rtmk-nova
+
		;;
+
	-ns2 )
+
		os=-nextstep2
+
		;;
+
	-nsk*)
+
		os=-nsk
+
		;;
+
	# Preserve the version number of sinix5.
+
	-sinix5.*)
+
		os=`echo $os | sed -e 's|sinix|sysv|'`
+
		;;
+
	-sinix*)
+
		os=-sysv4
+
		;;
+
	-tpf*)
+
		os=-tpf
+
		;;
+
	-triton*)
+
		os=-sysv3
+
		;;
+
	-oss*)
+
		os=-sysv3
+
		;;
+
	-svr4)
+
		os=-sysv4
+
		;;
+
	-svr3)
+
		os=-sysv3
+
		;;
+
	-sysvr4)
+
		os=-sysv4
+
		;;
+
	# This must come after -sysvr4.
+
	-sysv*)
+
		;;
+
	-ose*)
+
		os=-ose
+
		;;
+
	-es1800*)
+
		os=-ose
+
		;;
+
	-xenix)
+
		os=-xenix
+
		;;
+
	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+
		os=-mint
+
		;;
+
	-aros*)
+
		os=-aros
+
		;;
+
	-zvmoe)
+
		os=-zvmoe
+
		;;
+
	-dicos*)
+
		os=-dicos
+
		;;
+
	-nacl*)
+
		;;
+
	-none)
+
		;;
+
	*)
+
		# Get rid of the `-' at the beginning of $os.
+
		os=`echo $os | sed 's/[^-]*-//'`
+
		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+
		exit 1
+
		;;
+
esac
+
else
+

+
# Here we handle the default operating systems that come with various machines.
+
# The value should be what the vendor currently ships out the door with their
+
# machine or put another way, the most popular os provided with the machine.
+

+
# Note that if you're going to try to match "-MANUFACTURER" here (say,
+
# "-sun"), then you have to tell the case statement up towards the top
+
# that MANUFACTURER isn't an operating system.  Otherwise, code above
+
# will signal an error saying that MANUFACTURER isn't an operating
+
# system, and we'll never get to this point.
+

+
case $basic_machine in
+
	score-*)
+
		os=-elf
+
		;;
+
	spu-*)
+
		os=-elf
+
		;;
+
	*-acorn)
+
		os=-riscix1.2
+
		;;
+
	arm*-rebel)
+
		os=-linux
+
		;;
+
	arm*-semi)
+
		os=-aout
+
		;;
+
	c4x-* | tic4x-*)
+
		os=-coff
+
		;;
+
	c8051-*)
+
		os=-elf
+
		;;
+
	hexagon-*)
+
		os=-elf
+
		;;
+
	tic54x-*)
+
		os=-coff
+
		;;
+
	tic55x-*)
+
		os=-coff
+
		;;
+
	tic6x-*)
+
		os=-coff
+
		;;
+
	# This must come before the *-dec entry.
+
	pdp10-*)
+
		os=-tops20
+
		;;
+
	pdp11-*)
+
		os=-none
+
		;;
+
	*-dec | vax-*)
+
		os=-ultrix4.2
+
		;;
+
	m68*-apollo)
+
		os=-domain
+
		;;
+
	i386-sun)
+
		os=-sunos4.0.2
+
		;;
+
	m68000-sun)
+
		os=-sunos3
+
		;;
+
	m68*-cisco)
+
		os=-aout
+
		;;
+
	mep-*)
+
		os=-elf
+
		;;
+
	mips*-cisco)
+
		os=-elf
+
		;;
+
	mips*-*)
+
		os=-elf
+
		;;
+
	or32-*)
+
		os=-coff
+
		;;
+
	*-tti)	# must be before sparc entry or we get the wrong os.
+
		os=-sysv3
+
		;;
+
	sparc-* | *-sun)
+
		os=-sunos4.1.1
+
		;;
+
	*-be)
+
		os=-beos
+
		;;
+
	*-haiku)
+
		os=-haiku
+
		;;
+
	*-ibm)
+
		os=-aix
+
		;;
+
	*-knuth)
+
		os=-mmixware
+
		;;
+
	*-wec)
+
		os=-proelf
+
		;;
+
	*-winbond)
+
		os=-proelf
+
		;;
+
	*-oki)
+
		os=-proelf
+
		;;
+
	*-hp)
+
		os=-hpux
+
		;;
+
	*-hitachi)
+
		os=-hiux
+
		;;
+
	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+
		os=-sysv
+
		;;
+
	*-cbm)
+
		os=-amigaos
+
		;;
+
	*-dg)
+
		os=-dgux
+
		;;
+
	*-dolphin)
+
		os=-sysv3
+
		;;
+
	m68k-ccur)
+
		os=-rtu
+
		;;
+
	m88k-omron*)
+
		os=-luna
+
		;;
+
	*-next )
+
		os=-nextstep
+
		;;
+
	*-sequent)
+
		os=-ptx
+
		;;
+
	*-crds)
+
		os=-unos
+
		;;
+
	*-ns)
+
		os=-genix
+
		;;
+
	i370-*)
+
		os=-mvs
+
		;;
+
	*-next)
+
		os=-nextstep3
+
		;;
+
	*-gould)
+
		os=-sysv
+
		;;
+
	*-highlevel)
+
		os=-bsd
+
		;;
+
	*-encore)
+
		os=-bsd
+
		;;
+
	*-sgi)
+
		os=-irix
+
		;;
+
	*-siemens)
+
		os=-sysv4
+
		;;
+
	*-masscomp)
+
		os=-rtu
+
		;;
+
	f30[01]-fujitsu | f700-fujitsu)
+
		os=-uxpv
+
		;;
+
	*-rom68k)
+
		os=-coff
+
		;;
+
	*-*bug)
+
		os=-coff
+
		;;
+
	*-apple)
+
		os=-macos
+
		;;
+
	*-atari*)
+
		os=-mint
+
		;;
+
	*)
+
		os=-none
+
		;;
+
esac
+
fi
+

+
# Here we handle the case where we know the os, and the CPU type, but not the
+
# manufacturer.  We pick the logical manufacturer.
+
vendor=unknown
+
case $basic_machine in
+
	*-unknown)
+
		case $os in
+
			-riscix*)
+
				vendor=acorn
+
				;;
+
			-sunos*)
+
				vendor=sun
+
				;;
+
			-cnk*|-aix*)
+
				vendor=ibm
+
				;;
+
			-beos*)
+
				vendor=be
+
				;;
+
			-hpux*)
+
				vendor=hp
+
				;;
+
			-mpeix*)
+
				vendor=hp
+
				;;
+
			-hiux*)
+
				vendor=hitachi
+
				;;
+
			-unos*)
+
				vendor=crds
+
				;;
+
			-dgux*)
+
				vendor=dg
+
				;;
+
			-luna*)
+
				vendor=omron
+
				;;
+
			-genix*)
+
				vendor=ns
+
				;;
+
			-mvs* | -opened*)
+
				vendor=ibm
+
				;;
+
			-os400*)
+
				vendor=ibm
+
				;;
+
			-ptx*)
+
				vendor=sequent
+
				;;
+
			-tpf*)
+
				vendor=ibm
+
				;;
+
			-vxsim* | -vxworks* | -windiss*)
+
				vendor=wrs
+
				;;
+
			-aux*)
+
				vendor=apple
+
				;;
+
			-hms*)
+
				vendor=hitachi
+
				;;
+
			-mpw* | -macos*)
+
				vendor=apple
+
				;;
+
			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+
				vendor=atari
+
				;;
+
			-vos*)
+
				vendor=stratus
+
				;;
+
		esac
+
		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+
		;;
+
esac
+

+
echo $basic_machine$os
+
exit
+

+
# Local variables:
+
# eval: (add-hook 'write-file-hooks 'time-stamp)
+
# time-stamp-start: "timestamp='"
+
# time-stamp-format: "%:y-%02m-%02d"
+
# time-stamp-end: "'"
+
# End:
added autosetup/autosetup-find-tclsh
@@ -0,0 +1,17 @@
+
#!/bin/sh
+
# Looks for a suitable tclsh or jimsh in the PATH
+
# If not found, builds a bootstrap jimsh from source
+
# Prefer $autosetup_tclsh if is set in the environment
+
d=`dirname "$0"`
+
{ "$d/jimsh0" "$d/autosetup-test-tclsh"; } 2>/dev/null && exit 0
+
PATH="$PATH:$d"; export PATH
+
for tclsh in $autosetup_tclsh jimsh tclsh tclsh8.5 tclsh8.6; do
+
	{ $tclsh "$d/autosetup-test-tclsh"; } 2>/dev/null && exit 0
+
done
+
echo 1>&2 "No installed jimsh or tclsh, building local bootstrap jimsh0"
+
for cc in ${CC_FOR_BUILD:-cc} gcc; do
+
	{ $cc -o "$d/jimsh0" "$d/jimsh0.c"; } 2>/dev/null || continue
+
	"$d/jimsh0" "$d/autosetup-test-tclsh" && exit 0
+
done
+
echo 1>&2 "No working C compiler found. Tried ${CC_FOR_BUILD:-cc} and gcc."
+
echo false
added autosetup/autosetup-test-tclsh
@@ -0,0 +1,20 @@
+
# A small Tcl script to verify that the chosen
+
# interpreter works. Sometimes we might e.g. pick up
+
# an interpreter for a different arch.
+
# Outputs the full path to the interpreter
+

+
if {[catch {info version} version] == 0} {
+
	# This is Jim Tcl
+
	if {$version >= 0.72} {
+
		# Ensure that regexp works
+
		regexp (a.*?) a
+
		puts [info nameofexecutable]
+
		exit 0
+
	}
+
} elseif {[catch {info tclversion} version] == 0} {
+
	if {$version >= 8.5 && ![string match 8.5a* [info patchlevel]]} {
+
		puts [info nameofexecutable]
+
		exit 0
+
	}
+
}
+
exit 1
added autosetup/cc-db.tcl
@@ -0,0 +1,15 @@
+
# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# @synopsis:
+
#
+
# The 'cc-db' module provides a knowledge-base of system idiosyncrasies.
+
# In general, this module can always be included.
+

+
use cc
+

+
module-options {}
+

+
# openbsd needs sys/types.h to detect some system headers
+
cc-include-needs sys/socket.h sys/types.h
+
cc-include-needs netinet/in.h sys/types.h
added autosetup/cc-lib.tcl
@@ -0,0 +1,189 @@
+
# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# @synopsis:
+
#
+
# Provides a library of common tests on top of the 'cc' module.
+

+
use cc
+

+
module-options {}
+

+
# @cc-check-lfs
+
#
+
# The equivalent of the 'AC_SYS_LARGEFILE' macro.
+
# 
+
# defines 'HAVE_LFS' if LFS is available,
+
# and defines '_FILE_OFFSET_BITS=64' if necessary
+
#
+
# Returns 1 if 'LFS' is available or 0 otherwise
+
#
+
proc cc-check-lfs {} {
+
	cc-check-includes sys/types.h
+
	msg-checking "Checking if -D_FILE_OFFSET_BITS=64 is needed..."
+
	set lfs 1
+
	if {[msg-quiet cc-with {-includes sys/types.h} {cc-check-sizeof off_t}] == 8} {
+
		msg-result no
+
	} elseif {[msg-quiet cc-with {-includes sys/types.h -cflags -D_FILE_OFFSET_BITS=64} {cc-check-sizeof off_t}] == 8} {
+
		define _FILE_OFFSET_BITS 64
+
		msg-result yes
+
	} else {
+
		set lfs 0
+
		msg-result none
+
	}
+
	define-feature lfs $lfs
+
	return $lfs
+
}
+

+
# @cc-check-endian
+
#
+
# The equivalent of the 'AC_C_BIGENDIAN' macro.
+
# 
+
# defines 'HAVE_BIG_ENDIAN' if endian is known to be big,
+
# or 'HAVE_LITTLE_ENDIAN' if endian is known to be little.
+
#
+
# Returns 1 if determined, or 0 if not.
+
#
+
proc cc-check-endian {} {
+
	cc-check-includes sys/types.h sys/param.h
+
	set rc 0
+
	msg-checking "Checking endian..."
+
	cc-with {-includes {sys/types.h sys/param.h}} {
+
		if {[cctest -code {
+
			#if !defined(BIG_ENDIAN) || !defined(BYTE_ORDER)
+
				#error unknown
+
			#elif BYTE_ORDER != BIG_ENDIAN
+
				#error little
+
			#endif
+
		}]} {
+
			define-feature big-endian
+
			msg-result "big"
+
			set rc 1
+
		} elseif {[cctest -code {
+
			#if !defined(LITTLE_ENDIAN) || !defined(BYTE_ORDER)
+
				#error unknown
+
			#elif BYTE_ORDER != LITTLE_ENDIAN
+
				#error big
+
			#endif
+
		}]} {
+
			define-feature little-endian
+
			msg-result "little"
+
			set rc 1
+
		} else {
+
			msg-result "unknown"
+
		}
+
	}
+
	return $rc
+
}
+

+
# @cc-check-flags flag ?...?
+
#
+
# Checks whether the given C/C++ compiler flags can be used. Defines feature
+
# names prefixed with 'HAVE_CFLAG' and 'HAVE_CXXFLAG' respectively, and
+
# appends working flags to '-cflags' and 'CFLAGS' or 'CXXFLAGS'.
+
proc cc-check-flags {args} {
+
	set result 1
+
	array set opts [cc-get-settings]
+
	switch -exact -- $opts(-lang) {
+
		c++ {
+
			set lang C++
+
			set prefix CXXFLAG
+
		}
+
		c {
+
			set lang C
+
			set prefix CFLAG
+
		}
+
		default {
+
			autosetup-error "cc-check-flags failed with unknown language: $opts(-lang)"
+
		}
+
	}
+
	foreach flag $args {
+
		msg-checking "Checking whether the $lang compiler accepts $flag..."
+
		if {[cctest -cflags $flag]} {
+
			msg-result yes
+
			define-feature $prefix$flag
+
			cc-with [list -cflags [list $flag]]
+
			define-append ${prefix}S $flag
+
		} else {
+
			msg-result no
+
			set result 0
+
		}
+
	}
+
	return $result
+
}
+

+
# @cc-check-standards ver ?...?
+
#
+
# Checks whether the C/C++ compiler accepts one of the specified '-std=$ver'
+
# options, and appends the first working one to '-cflags' and 'CFLAGS' or
+
# 'CXXFLAGS'.
+
proc cc-check-standards {args} {
+
	array set opts [cc-get-settings]
+
	foreach std $args {
+
		if {[cc-check-flags -std=$std]} {
+
			return $std
+
		}
+
	}
+
	return ""
+
}
+

+
# Checks whether $keyword is usable as alignof
+
proc cctest_alignof {keyword} {
+
	msg-checking "Checking for $keyword..."
+
	if {[cctest -code "int x = ${keyword}(char), y = ${keyword}('x');"]} then {
+
		msg-result ok
+
		define-feature $keyword
+
	} else {
+
		msg-result "not found"
+
	}
+
}
+

+
# @cc-check-c11
+
#
+
# Checks for several C11/C++11 extensions and their alternatives. Currently
+
# checks for '_Static_assert', '_Alignof', '__alignof__', '__alignof'.
+
proc cc-check-c11 {} {
+
	msg-checking "Checking for _Static_assert..."
+
	if {[cctest -code {
+
		_Static_assert(1, "static assertions are available");
+
	}]} then {
+
		msg-result ok
+
		define-feature _Static_assert
+
	} else {
+
		msg-result "not found"
+
	}
+

+
	cctest_alignof _Alignof
+
	cctest_alignof __alignof__
+
	cctest_alignof __alignof
+
}
+

+
# @cc-check-alloca
+
#
+
# The equivalent of the 'AC_FUNC_ALLOCA' macro.
+
#
+
# Checks for the existence of 'alloca'
+
# defines 'HAVE_ALLOCA' and returns 1 if it exists.
+
proc cc-check-alloca {} {
+
	cc-check-some-feature alloca {
+
		cctest -includes alloca.h -code { alloca (2 * sizeof (int)); }
+
	}
+
}
+

+
# @cc-signal-return-type
+
#
+
# The equivalent of the 'AC_TYPE_SIGNAL' macro.
+
#
+
# defines 'RETSIGTYPE' to 'int' or 'void'.
+
proc cc-signal-return-type {} {
+
	msg-checking "Checking return type of signal handlers..."
+
	cc-with {-includes {sys/types.h signal.h}} {
+
		if {[cctest -code {return *(signal (0, 0)) (0) == 1;}]} {
+
				set type int
+
		} else {
+
				set type void
+
		}
+
		define RETSIGTYPE $type
+
		msg-result $type
+
	}
+
}
added autosetup/cc-shared.tcl
@@ -0,0 +1,117 @@
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# @synopsis:
+
#
+
# The 'cc-shared' module provides support for shared libraries and shared objects.
+
# It defines the following variables:
+
#
+
## SH_CFLAGS         Flags to use compiling sources destined for a shared library
+
## SH_LDFLAGS        Flags to use linking (creating) a shared library
+
## SH_SOPREFIX       Prefix to use to set the soname when creating a shared library
+
## SH_SOEXT          Extension for shared libs
+
## SH_SOEXTVER       Format for versioned shared libs - %s = version
+
## SHOBJ_CFLAGS      Flags to use compiling sources destined for a shared object
+
## SHOBJ_LDFLAGS     Flags to use linking a shared object, undefined symbols allowed
+
## SHOBJ_LDFLAGS_R   - as above, but all symbols must be resolved
+
## SH_LINKFLAGS      Flags to use linking an executable which will load shared objects
+
## LD_LIBRARY_PATH   Environment variable which specifies path to shared libraries
+
## STRIPLIBFLAGS     Arguments to strip a dynamic library
+

+
module-options {}
+

+
# Defaults: gcc on unix
+
define SHOBJ_CFLAGS -fpic
+
define SHOBJ_LDFLAGS -shared
+
define SH_CFLAGS -fpic
+
define SH_LDFLAGS -shared
+
define SH_LINKFLAGS -rdynamic
+
define SH_SOEXT .so
+
define SH_SOEXTVER .so.%s
+
define SH_SOPREFIX -Wl,-soname,
+
define LD_LIBRARY_PATH LD_LIBRARY_PATH
+
define STRIPLIBFLAGS --strip-unneeded
+

+
# Note: This is a helpful reference for identifying the toolchain
+
#       http://sourceforge.net/apps/mediawiki/predef/index.php?title=Compilers
+

+
switch -glob -- [get-define host] {
+
	*-*-darwin* {
+
		define SHOBJ_CFLAGS "-dynamic -fno-common"
+
		define SHOBJ_LDFLAGS "-bundle -undefined dynamic_lookup"
+
		define SHOBJ_LDFLAGS_R -bundle
+
		define SH_CFLAGS -dynamic
+
		define SH_LDFLAGS -dynamiclib
+
		define SH_LINKFLAGS ""
+
		define SH_SOEXT .dylib
+
		define SH_SOEXTVER .%s.dylib
+
		define SH_SOPREFIX -Wl,-install_name,
+
		define LD_LIBRARY_PATH DYLD_LIBRARY_PATH
+
		define STRIPLIBFLAGS -x
+
	}
+
	*-*-ming* - *-*-cygwin - *-*-msys {
+
		define SHOBJ_CFLAGS ""
+
		define SHOBJ_LDFLAGS -shared
+
		define SH_CFLAGS ""
+
		define SH_LDFLAGS -shared
+
		define SH_LINKFLAGS ""
+
		define SH_SOEXT .dll
+
		define SH_SOEXTVER .dll
+
		define SH_SOPREFIX ""
+
		define LD_LIBRARY_PATH PATH
+
	}
+
	sparc* {
+
		if {[msg-quiet cc-check-decls __SUNPRO_C]} {
+
			msg-result "Found sun stdio compiler"
+
			# sun stdio compiler
+
			# XXX: These haven't been fully tested. 
+
			define SHOBJ_CFLAGS -KPIC
+
			define SHOBJ_LDFLAGS "-G"
+
			define SH_CFLAGS -KPIC
+
			define SH_LINKFLAGS -Wl,-export-dynamic
+
			define SH_SOPREFIX -Wl,-h,
+
		} else {
+
			# sparc has a very small GOT table limit, so use -fPIC
+
			define SH_CFLAGS -fPIC
+
			define SHOBJ_CFLAGS -fPIC
+
		}
+
	}
+
	*-*-solaris* {
+
		if {[msg-quiet cc-check-decls __SUNPRO_C]} {
+
			msg-result "Found sun stdio compiler"
+
			# sun stdio compiler
+
			# XXX: These haven't been fully tested. 
+
			define SHOBJ_CFLAGS -KPIC
+
			define SHOBJ_LDFLAGS "-G"
+
			define SH_CFLAGS -KPIC
+
			define SH_LINKFLAGS -Wl,-export-dynamic
+
			define SH_SOPREFIX -Wl,-h,
+
		}
+
	}
+
	*-*-hpux {
+
		# XXX: These haven't been tested
+
		define SHOBJ_CFLAGS "+O3 +z"
+
		define SHOBJ_LDFLAGS -b
+
		define SH_CFLAGS +z
+
		define SH_LINKFLAGS -Wl,+s
+
		define LD_LIBRARY_PATH SHLIB_PATH
+
	}
+
	*-*-haiku {
+
		define SHOBJ_CFLAGS ""
+
		define SHOBJ_LDFLAGS -shared
+
		define SH_CFLAGS ""
+
		define SH_LDFLAGS -shared
+
		define SH_LINKFLAGS ""
+
		define SH_SOPREFIX ""
+
		define LD_LIBRARY_PATH LIBRARY_PATH
+
	}
+
	microblaze* {
+
		# Microblaze generally needs -fPIC rather than -fpic
+
		define SHOBJ_CFLAGS -fPIC
+
		define SH_CFLAGS -fPIC
+
	}
+
}
+

+
if {![is-defined SHOBJ_LDFLAGS_R]} {
+
	define SHOBJ_LDFLAGS_R [get-define SHOBJ_LDFLAGS]
+
}
added autosetup/cc.tcl
@@ -0,0 +1,722 @@
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# @synopsis:
+
#
+
# The 'cc' module supports checking various 'features' of the C or C++
+
# compiler/linker environment. Common commands are 'cc-check-includes',
+
# 'cc-check-types', 'cc-check-functions', 'cc-with', 'make-config-header' and 'make-template'.
+
#
+
# The following environment variables are used if set:
+
#
+
## CC       - C compiler
+
## CXX      - C++ compiler
+
## CCACHE   - Set to "none" to disable automatic use of ccache
+
## CFLAGS   - Additional C compiler flags
+
## CXXFLAGS - Additional C++ compiler flags
+
## LDFLAGS  - Additional compiler flags during linking
+
## LIBS     - Additional libraries to use (for all tests)
+
## CROSS    - Tool prefix for cross compilation
+
#
+
# The following variables are defined from the corresponding
+
# environment variables if set.
+
#
+
## CPPFLAGS
+
## LINKFLAGS
+
## CC_FOR_BUILD
+
## LD
+

+
use system
+

+
module-options {}
+

+
# Checks for the existence of the given function by linking
+
#
+
proc cctest_function {function} {
+
	cctest -link 1 -declare "extern void $function\(void);" -code "$function\();"
+
}
+

+
# Checks for the existence of the given type by compiling
+
proc cctest_type {type} {
+
	cctest -code "$type _x;"
+
}
+

+
# Checks for the existence of the given type/structure member.
+
# e.g. "struct stat.st_mtime"
+
proc cctest_member {struct_member} {
+
	# split at the first dot
+
	regexp {^([^.]+)[.](.*)$} $struct_member -> struct member
+
	cctest -code "static $struct _s; return sizeof(_s.$member);"
+
}
+

+
# Checks for the existence of the given define by compiling
+
#
+
proc cctest_define {name} {
+
	cctest -code "#ifndef $name\n#error not defined\n#endif"
+
}
+

+
# Checks for the existence of the given name either as
+
# a macro (#define) or an rvalue (such as an enum)
+
#
+
proc cctest_decl {name} {
+
	cctest -code "#ifndef $name\n(void)$name;\n#endif"
+
}
+

+
# @cc-check-sizeof type ...
+
#
+
# Checks the size of the given types (between 1 and 32, inclusive).
+
# Defines a variable with the size determined, or 'unknown' otherwise.
+
# e.g. for type 'long long', defines 'SIZEOF_LONG_LONG'.
+
# Returns the size of the last type.
+
#
+
proc cc-check-sizeof {args} {
+
	foreach type $args {
+
		msg-checking "Checking for sizeof $type..."
+
		set size unknown
+
		# Try the most common sizes first
+
		foreach i {4 8 1 2 16 32} {
+
			if {[cctest -code "static int _x\[sizeof($type) == $i ? 1 : -1\] = { 1 };"]} {
+
				set size $i
+
				break
+
			}
+
		}
+
		msg-result $size
+
		set define [feature-define-name $type SIZEOF_]
+
		define $define $size
+
	}
+
	# Return the last result
+
	get-define $define
+
}
+

+
# Checks for each feature in $list by using the given script.
+
#
+
# When the script is evaluated, $each is set to the feature
+
# being checked, and $extra is set to any additional cctest args.
+
#
+
# Returns 1 if all features were found, or 0 otherwise.
+
proc cc-check-some-feature {list script} {
+
	set ret 1
+
	foreach each $list {
+
		if {![check-feature $each $script]} {
+
			set ret 0
+
		}
+
	}
+
	return $ret
+
}
+

+
# @cc-check-includes includes ...
+
#
+
# Checks that the given include files can be used.
+
proc cc-check-includes {args} {
+
	cc-check-some-feature $args {
+
		set with {}
+
		if {[dict exists $::autosetup(cc-include-deps) $each]} {
+
			set deps [dict keys [dict get $::autosetup(cc-include-deps) $each]]
+
			msg-quiet cc-check-includes {*}$deps
+
			foreach i $deps {
+
				if {[have-feature $i]} {
+
					lappend with $i
+
				}
+
			}
+
		}
+
		if {[llength $with]} {
+
			cc-with [list -includes $with] {
+
				cctest -includes $each
+
			}
+
		} else {
+
			cctest -includes $each
+
		}
+
	}
+
}
+

+
# @cc-include-needs include required ...
+
#
+
# Ensures that when checking for '$include', a check is first
+
# made for each '$required' file, and if found, it is included with '#include'.
+
proc cc-include-needs {file args} {
+
	foreach depfile $args {
+
		dict set ::autosetup(cc-include-deps) $file $depfile 1
+
	}
+
}
+

+
# @cc-check-types type ...
+
#
+
# Checks that the types exist.
+
proc cc-check-types {args} {
+
	cc-check-some-feature $args {
+
		cctest_type $each
+
	}
+
}
+

+
# @cc-check-defines define ...
+
#
+
# Checks that the given preprocessor symbols are defined.
+
proc cc-check-defines {args} {
+
	cc-check-some-feature $args {
+
		cctest_define $each
+
	}
+
}
+

+
# @cc-check-decls name ...
+
#
+
# Checks that each given name is either a preprocessor symbol or rvalue
+
# such as an enum. Note that the define used is 'HAVE_DECL_xxx'
+
# rather than 'HAVE_xxx'.
+
proc cc-check-decls {args} {
+
	set ret 1
+
	foreach name $args {
+
		msg-checking "Checking for $name..."
+
		set r [cctest_decl $name]
+
		define-feature "decl $name" $r
+
		if {$r} {
+
			msg-result "ok"
+
		} else {
+
			msg-result "not found"
+
			set ret 0
+
		}
+
	}
+
	return $ret
+
}
+

+
# @cc-check-functions function ...
+
#
+
# Checks that the given functions exist (can be linked).
+
proc cc-check-functions {args} {
+
	cc-check-some-feature $args {
+
		cctest_function $each
+
	}
+
}
+

+
# @cc-check-members type.member ...
+
#
+
# Checks that the given type/structure members exist.
+
# A structure member is of the form 'struct stat.st_mtime'.
+
proc cc-check-members {args} {
+
	cc-check-some-feature $args {
+
		cctest_member $each
+
	}
+
}
+

+
# @cc-check-function-in-lib function libs ?otherlibs?
+
#
+
# Checks that the given function can be found in one of the libs.
+
#
+
# First checks for no library required, then checks each of the libraries
+
# in turn.
+
#
+
# If the function is found, the feature is defined and 'lib_$function' is defined
+
# to '-l$lib' where the function was found, or "" if no library required.
+
# In addition, '-l$lib' is prepended to the 'LIBS' define.
+
#
+
# If additional libraries may be needed for linking, they should be specified
+
# with '$extralibs' as '-lotherlib1 -lotherlib2'.
+
# These libraries are not automatically added to 'LIBS'.
+
#
+
# Returns 1 if found or 0 if not.
+
# 
+
proc cc-check-function-in-lib {function libs {otherlibs {}}} {
+
	msg-checking "Checking libs for $function..."
+
	set found 0
+
	cc-with [list -libs $otherlibs] {
+
		if {[cctest_function $function]} {
+
			msg-result "none needed"
+
			define lib_$function ""
+
			incr found
+
		} else {
+
			foreach lib $libs {
+
				cc-with [list -libs -l$lib] {
+
					if {[cctest_function $function]} {
+
						msg-result -l$lib
+
						define lib_$function -l$lib
+
						# prepend to LIBS
+
						define LIBS "-l$lib [get-define LIBS]"
+
						incr found
+
						break
+
					}
+
				}
+
			}
+
		}
+
	}
+
	define-feature $function $found
+
	if {!$found} {
+
		msg-result "no"
+
	}
+
	return $found
+
}
+

+
# @cc-check-tools tool ...
+
#
+
# Checks for existence of the given compiler tools, taking
+
# into account any cross compilation prefix.
+
#
+
# For example, when checking for 'ar', first 'AR' is checked on the command
+
# line and then in the environment. If not found, '${host}-ar' or
+
# simply 'ar' is assumed depending upon whether cross compiling.
+
# The path is searched for this executable, and if found 'AR' is defined
+
# to the executable name.
+
# Note that even when cross compiling, the simple 'ar' is used as a fallback,
+
# but a warning is generated. This is necessary for some toolchains.
+
#
+
# It is an error if the executable is not found.
+
#
+
proc cc-check-tools {args} {
+
	foreach tool $args {
+
		set TOOL [string toupper $tool]
+
		set exe [get-env $TOOL [get-define cross]$tool]
+
		if {[find-executable {*}$exe]} {
+
			define $TOOL $exe
+
			continue
+
		}
+
		if {[find-executable {*}$tool]} {
+
			msg-result "Warning: Failed to find $exe, falling back to $tool which may be incorrect"
+
			define $TOOL $tool
+
			continue
+
		}
+
		user-error "Failed to find $exe"
+
	}
+
}
+

+
# @cc-check-progs prog ...
+
#
+
# Checks for existence of the given executables on the path.
+
#
+
# For example, when checking for 'grep', the path is searched for
+
# the executable, 'grep', and if found 'GREP' is defined as 'grep'.
+
#
+
# If the executable is not found, the variable is defined as 'false'.
+
# Returns 1 if all programs were found, or 0 otherwise.
+
#
+
proc cc-check-progs {args} {
+
	set failed 0
+
	foreach prog $args {
+
		set PROG [string toupper $prog]
+
		msg-checking "Checking for $prog..."
+
		if {![find-executable $prog]} {
+
			msg-result no
+
			define $PROG false
+
			incr failed
+
		} else {
+
			msg-result ok
+
			define $PROG $prog
+
		}
+
	}
+
	expr {!$failed}
+
}
+

+
# @cc-path-progs prog ...
+
#
+
# Like cc-check-progs, but sets the define to the full path rather
+
# than just the program name.
+
#
+
proc cc-path-progs {args} {
+
	set failed 0
+
	foreach prog $args {
+
		set PROG [string toupper $prog]
+
		msg-checking "Checking for $prog..."
+
		set path [find-executable-path $prog]
+
		if {$path eq ""} {
+
			msg-result no
+
			define $PROG false
+
			incr failed
+
		} else {
+
			msg-result $path
+
			define $PROG $path
+
		}
+
	}
+
	expr {!$failed}
+
}
+

+
# Adds the given settings to $::autosetup(ccsettings) and
+
# returns the old settings.
+
#
+
proc cc-add-settings {settings} {
+
	if {[llength $settings] % 2} {
+
		autosetup-error "settings list is missing a value: $settings"
+
	}
+

+
	set prev [cc-get-settings]
+
	# workaround a bug in some versions of jimsh by forcing
+
	# conversion of $prev to a list
+
	llength $prev
+

+
	array set new $prev
+

+
	foreach {name value} $settings {
+
		switch -exact -- $name {
+
			-cflags - -includes {
+
				# These are given as lists
+
				lappend new($name) {*}[list-non-empty $value]
+
			}
+
			-declare {
+
				lappend new($name) $value
+
			}
+
			-libs {
+
				# Note that new libraries are added before previous libraries
+
				set new($name) [list {*}[list-non-empty $value] {*}$new($name)]
+
			}
+
			-link - -lang - -nooutput {
+
				set new($name) $value
+
			}
+
			-source - -sourcefile - -code {
+
				# XXX: These probably are only valid directly from cctest
+
				set new($name) $value
+
			}
+
			default {
+
				autosetup-error "unknown cctest setting: $name"
+
			}
+
		}
+
	}
+

+
	cc-store-settings [array get new]
+

+
	return $prev
+
}
+

+
proc cc-store-settings {new} {
+
	set ::autosetup(ccsettings) $new
+
}
+

+
proc cc-get-settings {} {
+
	return $::autosetup(ccsettings)
+
}
+

+
# Similar to cc-add-settings, but each given setting
+
# simply replaces the existing value.
+
#
+
# Returns the previous settings
+
proc cc-update-settings {args} {
+
	set prev [cc-get-settings]
+
	cc-store-settings [dict merge $prev $args]
+
	return $prev
+
}
+

+
# @cc-with settings ?{ script }?
+
#
+
# Sets the given 'cctest' settings and then runs the tests in '$script'.
+
# Note that settings such as '-lang' replace the current setting, while
+
# those such as '-includes' are appended to the existing setting.
+
#
+
# If no script is given, the settings become the default for the remainder
+
# of the 'auto.def' file.
+
#
+
## cc-with {-lang c++} {
+
##   # This will check with the C++ compiler
+
##   cc-check-types bool
+
##   cc-with {-includes signal.h} {
+
##     # This will check with the C++ compiler, signal.h and any existing includes.
+
##     ...
+
##   }
+
##   # back to just the C++ compiler
+
## }
+
#
+
# The '-libs' setting is special in that newer values are added *before* earlier ones.
+
#
+
## cc-with {-libs {-lc -lm}} {
+
##   cc-with {-libs -ldl} {
+
##     cctest -libs -lsocket ...
+
##     # libs will be in this order: -lsocket -ldl -lc -lm
+
##   }
+
## }
+
proc cc-with {settings args} {
+
	if {[llength $args] == 0} {
+
		cc-add-settings $settings
+
	} elseif {[llength $args] > 1} {
+
		autosetup-error "usage: cc-with settings ?script?"
+
	} else {
+
		set save [cc-add-settings $settings]
+
		set rc [catch {uplevel 1 [lindex $args 0]} result info]
+
		cc-store-settings $save
+
		if {$rc != 0} {
+
			return -code [dict get $info -code] $result
+
		}
+
		return $result
+
	}
+
}
+

+
# @cctest ?settings?
+
# 
+
# Low level C/C++ compiler checker. Compiles and or links a small C program
+
# according to the arguments and returns 1 if OK, or 0 if not.
+
#
+
# Supported settings are:
+
#
+
## -cflags cflags      A list of flags to pass to the compiler
+
## -includes list      A list of includes, e.g. {stdlib.h stdio.h}
+
## -declare code       Code to declare before main()
+
## -link 1             Don't just compile, link too
+
## -lang c|c++         Use the C (default) or C++ compiler
+
## -libs liblist       List of libraries to link, e.g. {-ldl -lm}
+
## -code code          Code to compile in the body of main()
+
## -source code        Compile a complete program. Ignore -includes, -declare and -code
+
## -sourcefile file    Shorthand for -source [readfile [get-define srcdir]/$file]
+
## -nooutput 1         Treat any compiler output (e.g. a warning) as an error
+
#
+
# Unless '-source' or '-sourcefile' is specified, the C program looks like:
+
#
+
## #include <firstinclude>   /* same for remaining includes in the list */
+
##
+
## declare-code              /* any code in -declare, verbatim */
+
##
+
## int main(void) {
+
##   code                    /* any code in -code, verbatim */
+
##   return 0;
+
## }
+
#
+
# Any failures are recorded in 'config.log'
+
#
+
proc cctest {args} {
+
	set src conftest__.c
+
	set tmp conftest__
+

+
	# Easiest way to merge in the settings
+
	cc-with $args {
+
		array set opts [cc-get-settings]
+
	}
+

+
	if {[info exists opts(-sourcefile)]} {
+
		set opts(-source) [readfile [get-define srcdir]/$opts(-sourcefile) "#error can't find $opts(-sourcefile)"]
+
	}
+
	if {[info exists opts(-source)]} {
+
		set lines $opts(-source)
+
	} else {
+
		foreach i $opts(-includes) {
+
			if {$opts(-code) ne "" && ![feature-checked $i]} {
+
				# Compiling real code with an unchecked header file
+
				# Quickly (and silently) check for it now
+

+
				# Remove all -includes from settings before checking
+
				set saveopts [cc-update-settings -includes {}]
+
				msg-quiet cc-check-includes $i
+
				cc-store-settings $saveopts
+
			}
+
			if {$opts(-code) eq "" || [have-feature $i]} {
+
				lappend source "#include <$i>"
+
			}
+
		}
+
		lappend source {*}$opts(-declare)
+
		lappend source "int main(void) {"
+
		lappend source $opts(-code)
+
		lappend source "return 0;"
+
		lappend source "}"
+

+
		set lines [join $source \n]
+
	}
+

+
	# Build the command line
+
	set cmdline {}
+
	lappend cmdline {*}[get-define CCACHE]
+
	switch -exact -- $opts(-lang) {
+
		c++ {
+
			lappend cmdline {*}[get-define CXX] {*}[get-define CXXFLAGS]
+
		}
+
		c {
+
			lappend cmdline {*}[get-define CC] {*}[get-define CFLAGS]
+
		}
+
		default {
+
			autosetup-error "cctest called with unknown language: $opts(-lang)"
+
		}
+
	}
+

+
	if {$opts(-link)} {
+
		lappend cmdline {*}[get-define LDFLAGS]
+
	} else {
+
		set tmp conftest__.o
+
		lappend cmdline -c
+
	}
+
	lappend cmdline {*}$opts(-cflags) {*}[get-define cc-default-debug ""]
+
	lappend cmdline $src -o $tmp {*}$opts(-libs)
+
	if {$opts(-link)} {
+
		lappend cmdline {*}[get-define LIBS]
+
	}
+

+
	# At this point we have the complete command line and the
+
	# complete source to be compiled. Get the result from cache if
+
	# we can
+
	if {[info exists ::cc_cache($cmdline,$lines)]} {
+
		msg-checking "(cached) "
+
		set ok $::cc_cache($cmdline,$lines)
+
		if {$::autosetup(debug)} {
+
			configlog "From cache (ok=$ok): [join $cmdline]"
+
			configlog "============"
+
			configlog $lines
+
			configlog "============"
+
		}
+
		return $ok
+
	}
+

+
	writefile $src $lines\n
+

+
	set ok 1
+
	set err [catch {exec-with-stderr {*}$cmdline} result errinfo]
+
	if {$err || ($opts(-nooutput) && [string length $result])} {
+
		configlog "Failed: [join $cmdline]"
+
		configlog $result
+
		configlog "============"
+
		configlog "The failed code was:"
+
		configlog $lines
+
		configlog "============"
+
		set ok 0
+
	} elseif {$::autosetup(debug)} {
+
		configlog "Compiled OK: [join $cmdline]"
+
		configlog "============"
+
		configlog $lines
+
		configlog "============"
+
	}
+
	file delete $src
+
	file delete $tmp
+

+
	# cache it
+
	set ::cc_cache($cmdline,$lines) $ok
+

+
	return $ok
+
}
+

+
# @make-autoconf-h outfile ?auto-patterns=HAVE_*? ?bare-patterns=SIZEOF_*?
+
#
+
# Deprecated - see 'make-config-header'
+
proc make-autoconf-h {file {autopatterns {HAVE_*}} {barepatterns {SIZEOF_* HAVE_DECL_*}}} {
+
	user-notice "*** make-autoconf-h is deprecated -- use make-config-header instead"
+
	make-config-header $file -auto $autopatterns -bare $barepatterns
+
}
+

+
# @make-config-header outfile ?-auto patternlist? ?-bare patternlist? ?-none patternlist? ?-str patternlist? ...
+
#
+
# Examines all defined variables which match the given patterns
+
# and writes an include file, '$file', which defines each of these.
+
# Variables which match '-auto' are output as follows:
+
# - defines which have the value '0' are ignored.
+
# - defines which have integer values are defined as the integer value.
+
# - any other value is defined as a string, e.g. '"value"'
+
# Variables which match '-bare' are defined as-is.
+
# Variables which match '-str' are defined as a string, e.g. '"value"'
+
# Variables which match '-none' are omitted.
+
#
+
# Note that order is important. The first pattern that matches is selected.
+
# Default behaviour is:
+
#
+
##  -bare {SIZEOF_* HAVE_DECL_*} -auto HAVE_* -none *
+
#
+
# If the file would be unchanged, it is not written.
+
proc make-config-header {file args} {
+
	set guard _[string toupper [regsub -all {[^a-zA-Z0-9]} [file tail $file] _]]
+
	file mkdir [file dirname $file]
+
	set lines {}
+
	lappend lines "#ifndef $guard"
+
	lappend lines "#define $guard"
+

+
	# Add some defaults
+
	lappend args -bare {SIZEOF_* HAVE_DECL_*} -auto HAVE_*
+

+
	foreach n [lsort [dict keys [all-defines]]] {
+
		set value [get-define $n]
+
		set type [calc-define-output-type $n $args]
+
		switch -exact -- $type {
+
			-bare {
+
				# Just output the value unchanged
+
			}
+
			-none {
+
				continue
+
			}
+
			-str {
+
				set value \"[string map [list \\ \\\\ \" \\\"] $value]\"
+
			}
+
			-auto {
+
				# Automatically determine the type
+
				if {$value eq "0"} {
+
					lappend lines "/* #undef $n */"
+
					continue
+
				}
+
				if {![string is integer -strict $value]} {
+
					set value \"[string map [list \\ \\\\ \" \\\"] $value]\"
+
				}
+
			}
+
			"" {
+
				continue
+
			}
+
			default {
+
				autosetup-error "Unknown type in make-config-header: $type"
+
			}
+
		}
+
		lappend lines "#define $n $value"
+
	}
+
	lappend lines "#endif"
+
	set buf [join $lines \n]
+
	write-if-changed $file $buf {
+
		msg-result "Created $file"
+
	}
+
}
+

+
proc calc-define-output-type {name spec} {
+
	foreach {type patterns} $spec {
+
		foreach pattern $patterns {
+
			if {[string match $pattern $name]} {
+
				return $type
+
			}
+
		}
+
	}
+
	return ""
+
}
+

+
# Initialise some values from the environment or commandline or default settings
+
foreach i {LDFLAGS LIBS CPPFLAGS LINKFLAGS {CFLAGS "-g -O2"}} {
+
	lassign $i var default
+
	define $var [get-env $var $default]
+
}
+

+
if {[env-is-set CC]} {
+
	# Set by the user, so don't try anything else
+
	set try [list [get-env CC ""]]
+
} else {
+
	# Try some reasonable options
+
	set try [list [get-define cross]cc [get-define cross]gcc]
+
}
+
define CC [find-an-executable {*}$try]
+
if {[get-define CC] eq ""} {
+
	user-error "Could not find a C compiler. Tried: [join $try ", "]"
+
}
+

+
define CPP [get-env CPP "[get-define CC] -E"]
+

+
# XXX: Could avoid looking for a C++ compiler until requested
+
# Note that if CXX isn't found, we just set it to "false". It might not be needed.
+
if {[env-is-set CXX]} {
+
	define CXX [find-an-executable -required [get-env CXX ""]]
+
} else {
+
	define CXX [find-an-executable [get-define cross]c++ [get-define cross]g++ false]
+
}
+

+
# CXXFLAGS default to CFLAGS if not specified
+
define CXXFLAGS [get-env CXXFLAGS [get-define CFLAGS]]
+

+
# May need a CC_FOR_BUILD, so look for one
+
define CC_FOR_BUILD [find-an-executable [get-env CC_FOR_BUILD ""] cc gcc false]
+

+
if {[get-define CC] eq ""} {
+
	user-error "Could not find a C compiler. Tried: [join $try ", "]"
+
}
+

+
define CCACHE [find-an-executable [get-env CCACHE ccache]]
+

+
# Initial cctest settings
+
cc-store-settings {-cflags {} -includes {} -declare {} -link 0 -lang c -libs {} -code {} -nooutput 0}
+
set autosetup(cc-include-deps) {}
+

+
msg-result "C compiler...[get-define CCACHE] [get-define CC] [get-define CFLAGS]"
+
if {[get-define CXX] ne "false"} {
+
	msg-result "C++ compiler...[get-define CCACHE] [get-define CXX] [get-define CXXFLAGS]"
+
}
+
msg-result "Build C compiler...[get-define CC_FOR_BUILD]"
+

+
# On Darwin, we prefer to use -g0 to avoid creating .dSYM directories
+
# but some compilers may not support it, so test here.
+
switch -glob -- [get-define host] {
+
	*-*-darwin* {
+
		if {[cctest -cflags {-g0}]} {
+
			define cc-default-debug -g0
+
		}
+
	}
+
}
+

+
if {![cc-check-includes stdlib.h]} {
+
	user-error "Compiler does not work. See config.log"
+
}
added autosetup/default.auto
@@ -0,0 +1,25 @@
+
# Copyright (c) 2012 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Auto-load module for 'make' build system integration
+

+
use init
+

+
autosetup_add_init_type make {Simple "make" build system} {
+
	autosetup_check_create auto.def \
+
{# Initial auto.def created by 'autosetup --init=make'
+

+
use cc
+

+
# Add any user options here
+
options {
+
}
+

+
make-config-header config.h
+
make-template Makefile.in
+
}
+

+
	if {![file exists Makefile.in]} {
+
		puts "Note: I don't see Makefile.in. You will probably need to create one."
+
	}
+
}
added autosetup/jimsh0.c
@@ -0,0 +1,22274 @@
+
/* This is single source file, bootstrap version of Jim Tcl. See http://jim.tcl.tk/ */
+
#define JIM_TCL_COMPAT
+
#define JIM_ANSIC
+
#define JIM_REGEXP
+
#define HAVE_NO_AUTOCONF
+
#define _JIMAUTOCONF_H
+
#define TCL_LIBRARY "."
+
#define jim_ext_bootstrap
+
#define jim_ext_aio
+
#define jim_ext_readdir
+
#define jim_ext_regexp
+
#define jim_ext_file
+
#define jim_ext_glob
+
#define jim_ext_exec
+
#define jim_ext_clock
+
#define jim_ext_array
+
#define jim_ext_stdlib
+
#define jim_ext_tclcompat
+
#if defined(_MSC_VER)
+
#define TCL_PLATFORM_OS "windows"
+
#define TCL_PLATFORM_PLATFORM "windows"
+
#define TCL_PLATFORM_PATH_SEPARATOR ";"
+
#define HAVE_MKDIR_ONE_ARG
+
#define HAVE_SYSTEM
+
#elif defined(__MINGW32__)
+
#define TCL_PLATFORM_OS "mingw"
+
#define TCL_PLATFORM_PLATFORM "windows"
+
#define TCL_PLATFORM_PATH_SEPARATOR ";"
+
#define HAVE_MKDIR_ONE_ARG
+
#define HAVE_SYSTEM
+
#define HAVE_SYS_TIME_H
+
#define HAVE_DIRENT_H
+
#define HAVE_UNISTD_H
+
#define HAVE_UMASK
+
#include <sys/stat.h>
+
#ifndef S_IRWXG
+
#define S_IRWXG 0
+
#endif
+
#ifndef S_IRWXO
+
#define S_IRWXO 0
+
#endif
+
#else
+
#define TCL_PLATFORM_OS "unknown"
+
#define TCL_PLATFORM_PLATFORM "unix"
+
#define TCL_PLATFORM_PATH_SEPARATOR ":"
+
#ifdef _MINIX
+
#define vfork fork
+
#define _POSIX_SOURCE
+
#else
+
#define _GNU_SOURCE
+
#endif
+
#define HAVE_VFORK
+
#define HAVE_WAITPID
+
#define HAVE_ISATTY
+
#define HAVE_MKSTEMP
+
#define HAVE_LINK
+
#define HAVE_SYS_TIME_H
+
#define HAVE_DIRENT_H
+
#define HAVE_UNISTD_H
+
#define HAVE_UMASK
+
#endif
+
#define JIM_VERSION 77
+
#ifndef JIM_WIN32COMPAT_H
+
#define JIM_WIN32COMPAT_H
+

+

+

+
#ifdef __cplusplus
+
extern "C" {
+
#endif
+

+

+
#if defined(_WIN32) || defined(WIN32)
+

+
#define HAVE_DLOPEN
+
void *dlopen(const char *path, int mode);
+
int dlclose(void *handle);
+
void *dlsym(void *handle, const char *symbol);
+
char *dlerror(void);
+

+

+
#if defined(__MINGW32__)
+
    #define JIM_SPRINTF_DOUBLE_NEEDS_FIX
+
#endif
+

+
#ifdef _MSC_VER
+

+

+
#if _MSC_VER >= 1000
+
	#pragma warning(disable:4146)
+
#endif
+

+
#include <limits.h>
+
#define jim_wide _int64
+
#ifndef LLONG_MAX
+
	#define LLONG_MAX    9223372036854775807I64
+
#endif
+
#ifndef LLONG_MIN
+
	#define LLONG_MIN    (-LLONG_MAX - 1I64)
+
#endif
+
#define JIM_WIDE_MIN LLONG_MIN
+
#define JIM_WIDE_MAX LLONG_MAX
+
#define JIM_WIDE_MODIFIER "I64d"
+
#define strcasecmp _stricmp
+
#define strtoull _strtoui64
+

+
#include <io.h>
+

+
struct timeval {
+
	long tv_sec;
+
	long tv_usec;
+
};
+

+
int gettimeofday(struct timeval *tv, void *unused);
+

+
#define HAVE_OPENDIR
+
struct dirent {
+
	char *d_name;
+
};
+

+
typedef struct DIR {
+
	long                handle;
+
	struct _finddata_t  info;
+
	struct dirent       result;
+
	char                *name;
+
} DIR;
+

+
DIR *opendir(const char *name);
+
int closedir(DIR *dir);
+
struct dirent *readdir(DIR *dir);
+

+
#elif defined(__MINGW32__)
+

+
#include <stdlib.h>
+
#define strtod __strtod
+

+
#endif
+

+
#endif
+

+
#ifdef __cplusplus
+
}
+
#endif
+

+
#endif
+
#ifndef UTF8_UTIL_H
+
#define UTF8_UTIL_H
+

+
#ifdef __cplusplus
+
extern "C" {
+
#endif
+

+

+

+
#define MAX_UTF8_LEN 4
+

+
int utf8_fromunicode(char *p, unsigned uc);
+

+
#ifndef JIM_UTF8
+
#include <ctype.h>
+

+

+
#define utf8_strlen(S, B) ((B) < 0 ? (int)strlen(S) : (B))
+
#define utf8_strwidth(S, B) utf8_strlen((S), (B))
+
#define utf8_tounicode(S, CP) (*(CP) = (unsigned char)*(S), 1)
+
#define utf8_getchars(CP, C) (*(CP) = (C), 1)
+
#define utf8_upper(C) toupper(C)
+
#define utf8_title(C) toupper(C)
+
#define utf8_lower(C) tolower(C)
+
#define utf8_index(C, I) (I)
+
#define utf8_charlen(C) 1
+
#define utf8_prev_len(S, L) 1
+
#define utf8_width(C) 1
+

+
#else
+

+
#endif
+

+
#ifdef __cplusplus
+
}
+
#endif
+

+
#endif
+

+
#ifndef __JIM__H
+
#define __JIM__H
+

+
#ifdef __cplusplus
+
extern "C" {
+
#endif
+

+
#include <time.h>
+
#include <limits.h>
+
#include <stdio.h>
+
#include <stdlib.h>
+
#include <stdarg.h>
+

+

+
#ifndef HAVE_NO_AUTOCONF
+
#endif
+

+

+

+
#ifndef jim_wide
+
#  ifdef HAVE_LONG_LONG
+
#    define jim_wide long long
+
#    ifndef LLONG_MAX
+
#      define LLONG_MAX    9223372036854775807LL
+
#    endif
+
#    ifndef LLONG_MIN
+
#      define LLONG_MIN    (-LLONG_MAX - 1LL)
+
#    endif
+
#    define JIM_WIDE_MIN LLONG_MIN
+
#    define JIM_WIDE_MAX LLONG_MAX
+
#  else
+
#    define jim_wide long
+
#    define JIM_WIDE_MIN LONG_MIN
+
#    define JIM_WIDE_MAX LONG_MAX
+
#  endif
+

+

+
#  ifdef HAVE_LONG_LONG
+
#    define JIM_WIDE_MODIFIER "lld"
+
#  else
+
#    define JIM_WIDE_MODIFIER "ld"
+
#    define strtoull strtoul
+
#  endif
+
#endif
+

+
#define UCHAR(c) ((unsigned char)(c))
+

+

+
#define JIM_OK 0
+
#define JIM_ERR 1
+
#define JIM_RETURN 2
+
#define JIM_BREAK 3
+
#define JIM_CONTINUE 4
+
#define JIM_SIGNAL 5
+
#define JIM_EXIT 6
+

+
#define JIM_EVAL 7
+

+
#define JIM_MAX_CALLFRAME_DEPTH 1000
+
#define JIM_MAX_EVAL_DEPTH 2000
+

+

+
#define JIM_PRIV_FLAG_SHIFT 20
+

+
#define JIM_NONE 0
+
#define JIM_ERRMSG 1
+
#define JIM_ENUM_ABBREV 2
+
#define JIM_UNSHARED 4
+
#define JIM_MUSTEXIST 8
+

+

+
#define JIM_SUBST_NOVAR 1
+
#define JIM_SUBST_NOCMD 2
+
#define JIM_SUBST_NOESC 4
+
#define JIM_SUBST_FLAG 128
+

+

+
#define JIM_CASESENS    0
+
#define JIM_NOCASE      1
+

+

+
#define JIM_PATH_LEN 1024
+

+

+
#define JIM_NOTUSED(V) ((void) V)
+

+
#define JIM_LIBPATH "auto_path"
+
#define JIM_INTERACTIVE "tcl_interactive"
+

+

+
typedef struct Jim_Stack {
+
    int len;
+
    int maxlen;
+
    void **vector;
+
} Jim_Stack;
+

+

+
typedef struct Jim_HashEntry {
+
    void *key;
+
    union {
+
        void *val;
+
        int intval;
+
    } u;
+
    struct Jim_HashEntry *next;
+
} Jim_HashEntry;
+

+
typedef struct Jim_HashTableType {
+
    unsigned int (*hashFunction)(const void *key);
+
    void *(*keyDup)(void *privdata, const void *key);
+
    void *(*valDup)(void *privdata, const void *obj);
+
    int (*keyCompare)(void *privdata, const void *key1, const void *key2);
+
    void (*keyDestructor)(void *privdata, void *key);
+
    void (*valDestructor)(void *privdata, void *obj);
+
} Jim_HashTableType;
+

+
typedef struct Jim_HashTable {
+
    Jim_HashEntry **table;
+
    const Jim_HashTableType *type;
+
    void *privdata;
+
    unsigned int size;
+
    unsigned int sizemask;
+
    unsigned int used;
+
    unsigned int collisions;
+
    unsigned int uniq;
+
} Jim_HashTable;
+

+
typedef struct Jim_HashTableIterator {
+
    Jim_HashTable *ht;
+
    Jim_HashEntry *entry, *nextEntry;
+
    int index;
+
} Jim_HashTableIterator;
+

+

+
#define JIM_HT_INITIAL_SIZE     16
+

+

+
#define Jim_FreeEntryVal(ht, entry) \
+
    if ((ht)->type->valDestructor) \
+
        (ht)->type->valDestructor((ht)->privdata, (entry)->u.val)
+

+
#define Jim_SetHashVal(ht, entry, _val_) do { \
+
    if ((ht)->type->valDup) \
+
        (entry)->u.val = (ht)->type->valDup((ht)->privdata, (_val_)); \
+
    else \
+
        (entry)->u.val = (_val_); \
+
} while(0)
+

+
#define Jim_FreeEntryKey(ht, entry) \
+
    if ((ht)->type->keyDestructor) \
+
        (ht)->type->keyDestructor((ht)->privdata, (entry)->key)
+

+
#define Jim_SetHashKey(ht, entry, _key_) do { \
+
    if ((ht)->type->keyDup) \
+
        (entry)->key = (ht)->type->keyDup((ht)->privdata, (_key_)); \
+
    else \
+
        (entry)->key = (void *)(_key_); \
+
} while(0)
+

+
#define Jim_CompareHashKeys(ht, key1, key2) \
+
    (((ht)->type->keyCompare) ? \
+
        (ht)->type->keyCompare((ht)->privdata, (key1), (key2)) : \
+
        (key1) == (key2))
+

+
#define Jim_HashKey(ht, key) ((ht)->type->hashFunction(key) + (ht)->uniq)
+

+
#define Jim_GetHashEntryKey(he) ((he)->key)
+
#define Jim_GetHashEntryVal(he) ((he)->u.val)
+
#define Jim_GetHashTableCollisions(ht) ((ht)->collisions)
+
#define Jim_GetHashTableSize(ht) ((ht)->size)
+
#define Jim_GetHashTableUsed(ht) ((ht)->used)
+

+

+
typedef struct Jim_Obj {
+
    char *bytes;
+
    const struct Jim_ObjType *typePtr;
+
    int refCount;
+
    int length;
+

+
    union {
+

+
        jim_wide wideValue;
+

+
        int intValue;
+

+
        double doubleValue;
+

+
        void *ptr;
+

+
        struct {
+
            void *ptr1;
+
            void *ptr2;
+
        } twoPtrValue;
+

+
        struct {
+
            struct Jim_Var *varPtr;
+
            unsigned long callFrameId;
+
            int global;
+
        } varValue;
+

+
        struct {
+
            struct Jim_Obj *nsObj;
+
            struct Jim_Cmd *cmdPtr;
+
            unsigned long procEpoch;
+
        } cmdValue;
+

+
        struct {
+
            struct Jim_Obj **ele;
+
            int len;
+
            int maxLen;
+
        } listValue;
+

+
        struct {
+
            int maxLength;
+
            int charLength;
+
        } strValue;
+

+
        struct {
+
            unsigned long id;
+
            struct Jim_Reference *refPtr;
+
        } refValue;
+

+
        struct {
+
            struct Jim_Obj *fileNameObj;
+
            int lineNumber;
+
        } sourceValue;
+

+
        struct {
+
            struct Jim_Obj *varNameObjPtr;
+
            struct Jim_Obj *indexObjPtr;
+
        } dictSubstValue;
+

+
        struct {
+
            void *compre;
+
            unsigned flags;
+
        } regexpValue;
+
        struct {
+
            int line;
+
            int argc;
+
        } scriptLineValue;
+
    } internalRep;
+
    struct Jim_Obj *prevObjPtr;
+
    struct Jim_Obj *nextObjPtr;
+
} Jim_Obj;
+

+

+
#define Jim_IncrRefCount(objPtr) \
+
    ++(objPtr)->refCount
+
#define Jim_DecrRefCount(interp, objPtr) \
+
    if (--(objPtr)->refCount <= 0) Jim_FreeObj(interp, objPtr)
+
#define Jim_IsShared(objPtr) \
+
    ((objPtr)->refCount > 1)
+

+
#define Jim_FreeNewObj Jim_FreeObj
+

+

+
#define Jim_FreeIntRep(i,o) \
+
    if ((o)->typePtr && (o)->typePtr->freeIntRepProc) \
+
        (o)->typePtr->freeIntRepProc(i, o)
+

+

+
#define Jim_GetIntRepPtr(o) (o)->internalRep.ptr
+

+

+
#define Jim_SetIntRepPtr(o, p) \
+
    (o)->internalRep.ptr = (p)
+

+

+
struct Jim_Interp;
+

+
typedef void (Jim_FreeInternalRepProc)(struct Jim_Interp *interp,
+
        struct Jim_Obj *objPtr);
+
typedef void (Jim_DupInternalRepProc)(struct Jim_Interp *interp,
+
        struct Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
typedef void (Jim_UpdateStringProc)(struct Jim_Obj *objPtr);
+

+
typedef struct Jim_ObjType {
+
    const char *name;
+
    Jim_FreeInternalRepProc *freeIntRepProc;
+
    Jim_DupInternalRepProc *dupIntRepProc;
+
    Jim_UpdateStringProc *updateStringProc;
+
    int flags;
+
} Jim_ObjType;
+

+

+
#define JIM_TYPE_NONE 0
+
#define JIM_TYPE_REFERENCES 1
+

+

+

+
typedef struct Jim_CallFrame {
+
    unsigned long id;
+
    int level;
+
    struct Jim_HashTable vars;
+
    struct Jim_HashTable *staticVars;
+
    struct Jim_CallFrame *parent;
+
    Jim_Obj *const *argv;
+
    int argc;
+
    Jim_Obj *procArgsObjPtr;
+
    Jim_Obj *procBodyObjPtr;
+
    struct Jim_CallFrame *next;
+
    Jim_Obj *nsObj;
+
    Jim_Obj *fileNameObj;
+
    int line;
+
    Jim_Stack *localCommands;
+
    struct Jim_Obj *tailcallObj;
+
    struct Jim_Cmd *tailcallCmd;
+
} Jim_CallFrame;
+

+
typedef struct Jim_Var {
+
    Jim_Obj *objPtr;
+
    struct Jim_CallFrame *linkFramePtr;
+
} Jim_Var;
+

+

+
typedef int Jim_CmdProc(struct Jim_Interp *interp, int argc,
+
    Jim_Obj *const *argv);
+
typedef void Jim_DelCmdProc(struct Jim_Interp *interp, void *privData);
+

+

+

+
typedef struct Jim_Cmd {
+
    int inUse;
+
    int isproc;
+
    struct Jim_Cmd *prevCmd;
+
    union {
+
        struct {
+

+
            Jim_CmdProc *cmdProc;
+
            Jim_DelCmdProc *delProc;
+
            void *privData;
+
        } native;
+
        struct {
+

+
            Jim_Obj *argListObjPtr;
+
            Jim_Obj *bodyObjPtr;
+
            Jim_HashTable *staticVars;
+
            int argListLen;
+
            int reqArity;
+
            int optArity;
+
            int argsPos;
+
            int upcall;
+
            struct Jim_ProcArg {
+
                Jim_Obj *nameObjPtr;
+
                Jim_Obj *defaultObjPtr;
+
            } *arglist;
+
            Jim_Obj *nsObj;
+
        } proc;
+
    } u;
+
} Jim_Cmd;
+

+

+
typedef struct Jim_PrngState {
+
    unsigned char sbox[256];
+
    unsigned int i, j;
+
} Jim_PrngState;
+

+
typedef struct Jim_Interp {
+
    Jim_Obj *result;
+
    int errorLine;
+
    Jim_Obj *errorFileNameObj;
+
    int addStackTrace;
+
    int maxCallFrameDepth;
+
    int maxEvalDepth;
+
    int evalDepth;
+
    int returnCode;
+
    int returnLevel;
+
    int exitCode;
+
    long id;
+
    int signal_level;
+
    jim_wide sigmask;
+
    int (*signal_set_result)(struct Jim_Interp *interp, jim_wide sigmask);
+
    Jim_CallFrame *framePtr;
+
    Jim_CallFrame *topFramePtr;
+
    struct Jim_HashTable commands;
+
    unsigned long procEpoch; /* Incremented every time the result
+
                of procedures names lookup caching
+
                may no longer be valid. */
+
    unsigned long callFrameEpoch; /* Incremented every time a new
+
                callframe is created. This id is used for the
+
                'ID' field contained in the Jim_CallFrame
+
                structure. */
+
    int local;
+
    Jim_Obj *liveList;
+
    Jim_Obj *freeList;
+
    Jim_Obj *currentScriptObj;
+
    Jim_Obj *nullScriptObj;
+
    Jim_Obj *emptyObj;
+
    Jim_Obj *trueObj;
+
    Jim_Obj *falseObj;
+
    unsigned long referenceNextId;
+
    struct Jim_HashTable references;
+
    unsigned long lastCollectId; /* reference max Id of the last GC
+
                execution. It's set to -1 while the collection
+
                is running as sentinel to avoid to recursive
+
                calls via the [collect] command inside
+
                finalizers. */
+
    time_t lastCollectTime;
+
    Jim_Obj *stackTrace;
+
    Jim_Obj *errorProc;
+
    Jim_Obj *unknown;
+
    int unknown_called;
+
    int errorFlag;
+
    void *cmdPrivData; /* Used to pass the private data pointer to
+
                  a command. It is set to what the user specified
+
                  via Jim_CreateCommand(). */
+

+
    struct Jim_CallFrame *freeFramesList;
+
    struct Jim_HashTable assocData;
+
    Jim_PrngState *prngState;
+
    struct Jim_HashTable packages;
+
    Jim_Stack *loadHandles;
+
} Jim_Interp;
+

+
#define Jim_InterpIncrProcEpoch(i) (i)->procEpoch++
+
#define Jim_SetResultString(i,s,l) Jim_SetResult(i, Jim_NewStringObj(i,s,l))
+
#define Jim_SetResultInt(i,intval) Jim_SetResult(i, Jim_NewIntObj(i,intval))
+

+
#define Jim_SetResultBool(i,b) Jim_SetResultInt(i, b)
+
#define Jim_SetEmptyResult(i) Jim_SetResult(i, (i)->emptyObj)
+
#define Jim_GetResult(i) ((i)->result)
+
#define Jim_CmdPrivData(i) ((i)->cmdPrivData)
+

+
#define Jim_SetResult(i,o) do {     \
+
    Jim_Obj *_resultObjPtr_ = (o);    \
+
    Jim_IncrRefCount(_resultObjPtr_); \
+
    Jim_DecrRefCount(i,(i)->result);  \
+
    (i)->result = _resultObjPtr_;     \
+
} while(0)
+

+

+
#define Jim_GetId(i) (++(i)->id)
+

+

+
#define JIM_REFERENCE_TAGLEN 7 /* The tag is fixed-length, because the reference
+
                                  string representation must be fixed length. */
+
typedef struct Jim_Reference {
+
    Jim_Obj *objPtr;
+
    Jim_Obj *finalizerCmdNamePtr;
+
    char tag[JIM_REFERENCE_TAGLEN+1];
+
} Jim_Reference;
+

+

+
#define Jim_NewEmptyStringObj(i) Jim_NewStringObj(i, "", 0)
+
#define Jim_FreeHashTableIterator(iter) Jim_Free(iter)
+

+
#define JIM_EXPORT
+

+

+
JIM_EXPORT void *Jim_Alloc (int size);
+
JIM_EXPORT void *Jim_Realloc(void *ptr, int size);
+
JIM_EXPORT void Jim_Free (void *ptr);
+
JIM_EXPORT char * Jim_StrDup (const char *s);
+
JIM_EXPORT char *Jim_StrDupLen(const char *s, int l);
+

+

+
JIM_EXPORT char **Jim_GetEnviron(void);
+
JIM_EXPORT void Jim_SetEnviron(char **env);
+
JIM_EXPORT int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template);
+

+

+
JIM_EXPORT int Jim_Eval(Jim_Interp *interp, const char *script);
+

+

+
JIM_EXPORT int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script);
+

+
#define Jim_Eval_Named(I, S, F, L) Jim_EvalSource((I), (F), (L), (S))
+

+
JIM_EXPORT int Jim_EvalGlobal(Jim_Interp *interp, const char *script);
+
JIM_EXPORT int Jim_EvalFile(Jim_Interp *interp, const char *filename);
+
JIM_EXPORT int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename);
+
JIM_EXPORT int Jim_EvalObj (Jim_Interp *interp, Jim_Obj *scriptObjPtr);
+
JIM_EXPORT int Jim_EvalObjVector (Jim_Interp *interp, int objc,
+
        Jim_Obj *const *objv);
+
JIM_EXPORT int Jim_EvalObjList(Jim_Interp *interp, Jim_Obj *listObj);
+
JIM_EXPORT int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix,
+
        int objc, Jim_Obj *const *objv);
+
#define Jim_EvalPrefix(i, p, oc, ov) Jim_EvalObjPrefix((i), Jim_NewStringObj((i), (p), -1), (oc), (ov))
+
JIM_EXPORT int Jim_EvalNamespace(Jim_Interp *interp, Jim_Obj *scriptObj, Jim_Obj *nsObj);
+
JIM_EXPORT int Jim_SubstObj (Jim_Interp *interp, Jim_Obj *substObjPtr,
+
        Jim_Obj **resObjPtrPtr, int flags);
+

+

+
JIM_EXPORT void Jim_InitStack(Jim_Stack *stack);
+
JIM_EXPORT void Jim_FreeStack(Jim_Stack *stack);
+
JIM_EXPORT int Jim_StackLen(Jim_Stack *stack);
+
JIM_EXPORT void Jim_StackPush(Jim_Stack *stack, void *element);
+
JIM_EXPORT void * Jim_StackPop(Jim_Stack *stack);
+
JIM_EXPORT void * Jim_StackPeek(Jim_Stack *stack);
+
JIM_EXPORT void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc)(void *ptr));
+

+

+
JIM_EXPORT int Jim_InitHashTable (Jim_HashTable *ht,
+
        const Jim_HashTableType *type, void *privdata);
+
JIM_EXPORT void Jim_ExpandHashTable (Jim_HashTable *ht,
+
        unsigned int size);
+
JIM_EXPORT int Jim_AddHashEntry (Jim_HashTable *ht, const void *key,
+
        void *val);
+
JIM_EXPORT int Jim_ReplaceHashEntry (Jim_HashTable *ht,
+
        const void *key, void *val);
+
JIM_EXPORT int Jim_DeleteHashEntry (Jim_HashTable *ht,
+
        const void *key);
+
JIM_EXPORT int Jim_FreeHashTable (Jim_HashTable *ht);
+
JIM_EXPORT Jim_HashEntry * Jim_FindHashEntry (Jim_HashTable *ht,
+
        const void *key);
+
JIM_EXPORT void Jim_ResizeHashTable (Jim_HashTable *ht);
+
JIM_EXPORT Jim_HashTableIterator *Jim_GetHashTableIterator
+
        (Jim_HashTable *ht);
+
JIM_EXPORT Jim_HashEntry * Jim_NextHashEntry
+
        (Jim_HashTableIterator *iter);
+

+

+
JIM_EXPORT Jim_Obj * Jim_NewObj (Jim_Interp *interp);
+
JIM_EXPORT void Jim_FreeObj (Jim_Interp *interp, Jim_Obj *objPtr);
+
JIM_EXPORT void Jim_InvalidateStringRep (Jim_Obj *objPtr);
+
JIM_EXPORT Jim_Obj * Jim_DuplicateObj (Jim_Interp *interp,
+
        Jim_Obj *objPtr);
+
JIM_EXPORT const char * Jim_GetString(Jim_Obj *objPtr,
+
        int *lenPtr);
+
JIM_EXPORT const char *Jim_String(Jim_Obj *objPtr);
+
JIM_EXPORT int Jim_Length(Jim_Obj *objPtr);
+

+

+
JIM_EXPORT Jim_Obj * Jim_NewStringObj (Jim_Interp *interp,
+
        const char *s, int len);
+
JIM_EXPORT Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp,
+
        const char *s, int charlen);
+
JIM_EXPORT Jim_Obj * Jim_NewStringObjNoAlloc (Jim_Interp *interp,
+
        char *s, int len);
+
JIM_EXPORT void Jim_AppendString (Jim_Interp *interp, Jim_Obj *objPtr,
+
        const char *str, int len);
+
JIM_EXPORT void Jim_AppendObj (Jim_Interp *interp, Jim_Obj *objPtr,
+
        Jim_Obj *appendObjPtr);
+
JIM_EXPORT void Jim_AppendStrings (Jim_Interp *interp,
+
        Jim_Obj *objPtr, ...);
+
JIM_EXPORT int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr);
+
JIM_EXPORT int Jim_StringMatchObj (Jim_Interp *interp, Jim_Obj *patternObjPtr,
+
        Jim_Obj *objPtr, int nocase);
+
JIM_EXPORT Jim_Obj * Jim_StringRangeObj (Jim_Interp *interp,
+
        Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr,
+
        Jim_Obj *lastObjPtr);
+
JIM_EXPORT Jim_Obj * Jim_FormatString (Jim_Interp *interp,
+
        Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv);
+
JIM_EXPORT Jim_Obj * Jim_ScanString (Jim_Interp *interp, Jim_Obj *strObjPtr,
+
        Jim_Obj *fmtObjPtr, int flags);
+
JIM_EXPORT int Jim_CompareStringImmediate (Jim_Interp *interp,
+
        Jim_Obj *objPtr, const char *str);
+
JIM_EXPORT int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr,
+
        Jim_Obj *secondObjPtr, int nocase);
+
JIM_EXPORT int Jim_StringCompareLenObj(Jim_Interp *interp, Jim_Obj *firstObjPtr,
+
        Jim_Obj *secondObjPtr, int nocase);
+
JIM_EXPORT int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr);
+

+

+
JIM_EXPORT Jim_Obj * Jim_NewReference (Jim_Interp *interp,
+
        Jim_Obj *objPtr, Jim_Obj *tagPtr, Jim_Obj *cmdNamePtr);
+
JIM_EXPORT Jim_Reference * Jim_GetReference (Jim_Interp *interp,
+
        Jim_Obj *objPtr);
+
JIM_EXPORT int Jim_SetFinalizer (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr);
+
JIM_EXPORT int Jim_GetFinalizer (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr);
+

+

+
JIM_EXPORT Jim_Interp * Jim_CreateInterp (void);
+
JIM_EXPORT void Jim_FreeInterp (Jim_Interp *i);
+
JIM_EXPORT int Jim_GetExitCode (Jim_Interp *interp);
+
JIM_EXPORT const char *Jim_ReturnCode(int code);
+
JIM_EXPORT void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...);
+

+

+
JIM_EXPORT void Jim_RegisterCoreCommands (Jim_Interp *interp);
+
JIM_EXPORT int Jim_CreateCommand (Jim_Interp *interp,
+
        const char *cmdName, Jim_CmdProc *cmdProc, void *privData,
+
         Jim_DelCmdProc *delProc);
+
JIM_EXPORT int Jim_DeleteCommand (Jim_Interp *interp,
+
        const char *cmdName);
+
JIM_EXPORT int Jim_RenameCommand (Jim_Interp *interp,
+
        const char *oldName, const char *newName);
+
JIM_EXPORT Jim_Cmd * Jim_GetCommand (Jim_Interp *interp,
+
        Jim_Obj *objPtr, int flags);
+
JIM_EXPORT int Jim_SetVariable (Jim_Interp *interp,
+
        Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr);
+
JIM_EXPORT int Jim_SetVariableStr (Jim_Interp *interp,
+
        const char *name, Jim_Obj *objPtr);
+
JIM_EXPORT int Jim_SetGlobalVariableStr (Jim_Interp *interp,
+
        const char *name, Jim_Obj *objPtr);
+
JIM_EXPORT int Jim_SetVariableStrWithStr (Jim_Interp *interp,
+
        const char *name, const char *val);
+
JIM_EXPORT int Jim_SetVariableLink (Jim_Interp *interp,
+
        Jim_Obj *nameObjPtr, Jim_Obj *targetNameObjPtr,
+
        Jim_CallFrame *targetCallFrame);
+
JIM_EXPORT Jim_Obj * Jim_MakeGlobalNamespaceName(Jim_Interp *interp,
+
        Jim_Obj *nameObjPtr);
+
JIM_EXPORT Jim_Obj * Jim_GetVariable (Jim_Interp *interp,
+
        Jim_Obj *nameObjPtr, int flags);
+
JIM_EXPORT Jim_Obj * Jim_GetGlobalVariable (Jim_Interp *interp,
+
        Jim_Obj *nameObjPtr, int flags);
+
JIM_EXPORT Jim_Obj * Jim_GetVariableStr (Jim_Interp *interp,
+
        const char *name, int flags);
+
JIM_EXPORT Jim_Obj * Jim_GetGlobalVariableStr (Jim_Interp *interp,
+
        const char *name, int flags);
+
JIM_EXPORT int Jim_UnsetVariable (Jim_Interp *interp,
+
        Jim_Obj *nameObjPtr, int flags);
+

+

+
JIM_EXPORT Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp,
+
        Jim_Obj *levelObjPtr);
+

+

+
JIM_EXPORT int Jim_Collect (Jim_Interp *interp);
+
JIM_EXPORT void Jim_CollectIfNeeded (Jim_Interp *interp);
+

+

+
JIM_EXPORT int Jim_GetIndex (Jim_Interp *interp, Jim_Obj *objPtr,
+
        int *indexPtr);
+

+

+
JIM_EXPORT Jim_Obj * Jim_NewListObj (Jim_Interp *interp,
+
        Jim_Obj *const *elements, int len);
+
JIM_EXPORT void Jim_ListInsertElements (Jim_Interp *interp,
+
        Jim_Obj *listPtr, int listindex, int objc, Jim_Obj *const *objVec);
+
JIM_EXPORT void Jim_ListAppendElement (Jim_Interp *interp,
+
        Jim_Obj *listPtr, Jim_Obj *objPtr);
+
JIM_EXPORT void Jim_ListAppendList (Jim_Interp *interp,
+
        Jim_Obj *listPtr, Jim_Obj *appendListPtr);
+
JIM_EXPORT int Jim_ListLength (Jim_Interp *interp, Jim_Obj *objPtr);
+
JIM_EXPORT int Jim_ListIndex (Jim_Interp *interp, Jim_Obj *listPrt,
+
        int listindex, Jim_Obj **objPtrPtr, int seterr);
+
JIM_EXPORT Jim_Obj *Jim_ListGetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx);
+
JIM_EXPORT int Jim_SetListIndex (Jim_Interp *interp,
+
        Jim_Obj *varNamePtr, Jim_Obj *const *indexv, int indexc,
+
        Jim_Obj *newObjPtr);
+
JIM_EXPORT Jim_Obj * Jim_ConcatObj (Jim_Interp *interp, int objc,
+
        Jim_Obj *const *objv);
+
JIM_EXPORT Jim_Obj *Jim_ListJoin(Jim_Interp *interp,
+
        Jim_Obj *listObjPtr, const char *joinStr, int joinStrLen);
+

+

+
JIM_EXPORT Jim_Obj * Jim_NewDictObj (Jim_Interp *interp,
+
        Jim_Obj *const *elements, int len);
+
JIM_EXPORT int Jim_DictKey (Jim_Interp *interp, Jim_Obj *dictPtr,
+
        Jim_Obj *keyPtr, Jim_Obj **objPtrPtr, int flags);
+
JIM_EXPORT int Jim_DictKeysVector (Jim_Interp *interp,
+
        Jim_Obj *dictPtr, Jim_Obj *const *keyv, int keyc,
+
        Jim_Obj **objPtrPtr, int flags);
+
JIM_EXPORT int Jim_SetDictKeysVector (Jim_Interp *interp,
+
        Jim_Obj *varNamePtr, Jim_Obj *const *keyv, int keyc,
+
        Jim_Obj *newObjPtr, int flags);
+
JIM_EXPORT int Jim_DictPairs(Jim_Interp *interp,
+
        Jim_Obj *dictPtr, Jim_Obj ***objPtrPtr, int *len);
+
JIM_EXPORT int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
+
        Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr);
+

+
#define JIM_DICTMATCH_KEYS 0x0001
+
#define JIM_DICTMATCH_VALUES 0x002
+

+
JIM_EXPORT int Jim_DictMatchTypes(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj, int match_type, int return_types);
+
JIM_EXPORT int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr);
+
JIM_EXPORT int Jim_DictInfo(Jim_Interp *interp, Jim_Obj *objPtr);
+
JIM_EXPORT Jim_Obj *Jim_DictMerge(Jim_Interp *interp, int objc, Jim_Obj *const *objv);
+

+

+
JIM_EXPORT int Jim_GetReturnCode (Jim_Interp *interp, Jim_Obj *objPtr,
+
        int *intPtr);
+

+

+
JIM_EXPORT int Jim_EvalExpression (Jim_Interp *interp,
+
        Jim_Obj *exprObjPtr, Jim_Obj **exprResultPtrPtr);
+
JIM_EXPORT int Jim_GetBoolFromExpr (Jim_Interp *interp,
+
        Jim_Obj *exprObjPtr, int *boolPtr);
+

+

+
JIM_EXPORT int Jim_GetBoolean(Jim_Interp *interp, Jim_Obj *objPtr,
+
        int *booleanPtr);
+

+

+
JIM_EXPORT int Jim_GetWide (Jim_Interp *interp, Jim_Obj *objPtr,
+
        jim_wide *widePtr);
+
JIM_EXPORT int Jim_GetLong (Jim_Interp *interp, Jim_Obj *objPtr,
+
        long *longPtr);
+
#define Jim_NewWideObj  Jim_NewIntObj
+
JIM_EXPORT Jim_Obj * Jim_NewIntObj (Jim_Interp *interp,
+
        jim_wide wideValue);
+

+

+
JIM_EXPORT int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr,
+
        double *doublePtr);
+
JIM_EXPORT void Jim_SetDouble(Jim_Interp *interp, Jim_Obj *objPtr,
+
        double doubleValue);
+
JIM_EXPORT Jim_Obj * Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue);
+

+

+
JIM_EXPORT void Jim_WrongNumArgs (Jim_Interp *interp, int argc,
+
        Jim_Obj *const *argv, const char *msg);
+
JIM_EXPORT int Jim_GetEnum (Jim_Interp *interp, Jim_Obj *objPtr,
+
        const char * const *tablePtr, int *indexPtr, const char *name, int flags);
+
JIM_EXPORT int Jim_CheckShowCommands(Jim_Interp *interp, Jim_Obj *objPtr,
+
        const char *const *tablePtr);
+
JIM_EXPORT int Jim_ScriptIsComplete(Jim_Interp *interp,
+
        Jim_Obj *scriptObj, char *stateCharPtr);
+

+
JIM_EXPORT int Jim_FindByName(const char *name, const char * const array[], size_t len);
+

+

+
typedef void (Jim_InterpDeleteProc)(Jim_Interp *interp, void *data);
+
JIM_EXPORT void * Jim_GetAssocData(Jim_Interp *interp, const char *key);
+
JIM_EXPORT int Jim_SetAssocData(Jim_Interp *interp, const char *key,
+
        Jim_InterpDeleteProc *delProc, void *data);
+
JIM_EXPORT int Jim_DeleteAssocData(Jim_Interp *interp, const char *key);
+

+

+

+
JIM_EXPORT int Jim_PackageProvide (Jim_Interp *interp,
+
        const char *name, const char *ver, int flags);
+
JIM_EXPORT int Jim_PackageRequire (Jim_Interp *interp,
+
        const char *name, int flags);
+

+

+
JIM_EXPORT void Jim_MakeErrorMessage (Jim_Interp *interp);
+

+

+
JIM_EXPORT int Jim_InteractivePrompt (Jim_Interp *interp);
+
JIM_EXPORT void Jim_HistoryLoad(const char *filename);
+
JIM_EXPORT void Jim_HistorySave(const char *filename);
+
JIM_EXPORT char *Jim_HistoryGetline(const char *prompt);
+
JIM_EXPORT void Jim_HistoryAdd(const char *line);
+
JIM_EXPORT void Jim_HistoryShow(void);
+

+

+
JIM_EXPORT int Jim_InitStaticExtensions(Jim_Interp *interp);
+
JIM_EXPORT int Jim_StringToWide(const char *str, jim_wide *widePtr, int base);
+
JIM_EXPORT int Jim_IsBigEndian(void);
+

+
#define Jim_CheckSignal(i) ((i)->signal_level && (i)->sigmask)
+

+

+
JIM_EXPORT int Jim_LoadLibrary(Jim_Interp *interp, const char *pathName);
+
JIM_EXPORT void Jim_FreeLoadHandles(Jim_Interp *interp);
+

+

+
JIM_EXPORT FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command);
+

+

+
JIM_EXPORT int Jim_IsDict(Jim_Obj *objPtr);
+
JIM_EXPORT int Jim_IsList(Jim_Obj *objPtr);
+

+
#ifdef __cplusplus
+
}
+
#endif
+

+
#endif
+

+
#ifndef JIM_SUBCMD_H
+
#define JIM_SUBCMD_H
+

+

+
#ifdef __cplusplus
+
extern "C" {
+
#endif
+

+

+
#define JIM_MODFLAG_HIDDEN   0x0001
+
#define JIM_MODFLAG_FULLARGV 0x0002
+

+

+

+
typedef int jim_subcmd_function(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
+

+
typedef struct {
+
	const char *cmd;
+
	const char *args;
+
	jim_subcmd_function *function;
+
	short minargs;
+
	short maxargs;
+
	unsigned short flags;
+
} jim_subcmd_type;
+

+
const jim_subcmd_type *
+
Jim_ParseSubCmd(Jim_Interp *interp, const jim_subcmd_type *command_table, int argc, Jim_Obj *const *argv);
+

+
int Jim_SubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
+

+
int Jim_CallSubCmd(Jim_Interp *interp, const jim_subcmd_type *ct, int argc, Jim_Obj *const *argv);
+

+
#ifdef __cplusplus
+
}
+
#endif
+

+
#endif
+
#ifndef JIMREGEXP_H
+
#define JIMREGEXP_H
+

+

+
#ifdef __cplusplus
+
extern "C" {
+
#endif
+

+
#include <stdlib.h>
+

+
typedef struct {
+
	int rm_so;
+
	int rm_eo;
+
} regmatch_t;
+

+

+
typedef struct regexp {
+

+
	int re_nsub;
+

+

+
	int cflags;
+
	int err;
+
	int regstart;
+
	int reganch;
+
	int regmust;
+
	int regmlen;
+
	int *program;
+

+

+
	const char *regparse;
+
	int p;
+
	int proglen;
+

+

+
	int eflags;
+
	const char *start;
+
	const char *reginput;
+
	const char *regbol;
+

+

+
	regmatch_t *pmatch;
+
	int nmatch;
+
} regexp;
+

+
typedef regexp regex_t;
+

+
#define REG_EXTENDED 0
+
#define REG_NEWLINE 1
+
#define REG_ICASE 2
+

+
#define REG_NOTBOL 16
+

+
enum {
+
	REG_NOERROR,
+
	REG_NOMATCH,
+
	REG_BADPAT,
+
	REG_ERR_NULL_ARGUMENT,
+
	REG_ERR_UNKNOWN,
+
	REG_ERR_TOO_BIG,
+
	REG_ERR_NOMEM,
+
	REG_ERR_TOO_MANY_PAREN,
+
	REG_ERR_UNMATCHED_PAREN,
+
	REG_ERR_UNMATCHED_BRACES,
+
	REG_ERR_BAD_COUNT,
+
	REG_ERR_JUNK_ON_END,
+
	REG_ERR_OPERAND_COULD_BE_EMPTY,
+
	REG_ERR_NESTED_COUNT,
+
	REG_ERR_INTERNAL,
+
	REG_ERR_COUNT_FOLLOWS_NOTHING,
+
	REG_ERR_TRAILING_BACKSLASH,
+
	REG_ERR_CORRUPTED,
+
	REG_ERR_NULL_CHAR,
+
	REG_ERR_NUM
+
};
+

+
int regcomp(regex_t *preg, const char *regex, int cflags);
+
int regexec(regex_t  *preg,  const  char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
+
size_t regerror(int errcode, const regex_t *preg, char *errbuf,  size_t errbuf_size);
+
void regfree(regex_t *preg);
+

+
#ifdef __cplusplus
+
}
+
#endif
+

+
#endif
+
int Jim_bootstrapInit(Jim_Interp *interp)
+
{
+
	if (Jim_PackageProvide(interp, "bootstrap", "1.0", JIM_ERRMSG))
+
		return JIM_ERR;
+

+
	return Jim_EvalSource(interp, "bootstrap.tcl", 1,
+
"\n"
+
"\n"
+
"proc package {cmd pkg} {\n"
+
"	if {$cmd eq \"require\"} {\n"
+
"		foreach path $::auto_path {\n"
+
"			if {[file exists $path/$pkg.tcl]} {\n"
+
"				uplevel #0 [list source $path/$pkg.tcl]\n"
+
"				return\n"
+
"			}\n"
+
"		}\n"
+
"	}\n"
+
"}\n"
+
);
+
}
+
int Jim_initjimshInit(Jim_Interp *interp)
+
{
+
	if (Jim_PackageProvide(interp, "initjimsh", "1.0", JIM_ERRMSG))
+
		return JIM_ERR;
+

+
	return Jim_EvalSource(interp, "initjimsh.tcl", 1,
+
"\n"
+
"\n"
+
"\n"
+
"proc _jimsh_init {} {\n"
+
"	rename _jimsh_init {}\n"
+
"	global jim::exe jim::argv0 tcl_interactive auto_path tcl_platform\n"
+
"\n"
+
"\n"
+
"	if {[exists jim::argv0]} {\n"
+
"		if {[string match \"*/*\" $jim::argv0]} {\n"
+
"			set jim::exe [file join [pwd] $jim::argv0]\n"
+
"		} else {\n"
+
"			foreach path [split [env PATH \"\"] $tcl_platform(pathSeparator)] {\n"
+
"				set exec [file join [pwd] [string map {\\\\ /} $path] $jim::argv0]\n"
+
"				if {[file executable $exec]} {\n"
+
"					set jim::exe $exec\n"
+
"					break\n"
+
"				}\n"
+
"			}\n"
+
"		}\n"
+
"	}\n"
+
"\n"
+
"\n"
+
"	lappend p {*}[split [env JIMLIB {}] $tcl_platform(pathSeparator)]\n"
+
"	if {[exists jim::exe]} {\n"
+
"		lappend p [file dirname $jim::exe]\n"
+
"	}\n"
+
"	lappend p {*}$auto_path\n"
+
"	set auto_path $p\n"
+
"\n"
+
"	if {$tcl_interactive && [env HOME {}] ne \"\"} {\n"
+
"		foreach src {.jimrc jimrc.tcl} {\n"
+
"			if {[file exists [env HOME]/$src]} {\n"
+
"				uplevel #0 source [env HOME]/$src\n"
+
"				break\n"
+
"			}\n"
+
"		}\n"
+
"	}\n"
+
"	return \"\"\n"
+
"}\n"
+
"\n"
+
"if {$tcl_platform(platform) eq \"windows\"} {\n"
+
"	set jim::argv0 [string map {\\\\ /} $jim::argv0]\n"
+
"}\n"
+
"\n"
+
"\n"
+
"set tcl::autocomplete_commands {info tcl::prefix socket namespace array clock file package string dict signal history}\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc tcl::autocomplete {prefix} {\n"
+
"	if {[set space [string first \" \" $prefix]] != -1} {\n"
+
"		set cmd [string range $prefix 0 $space-1]\n"
+
"		if {$cmd in $::tcl::autocomplete_commands || [info channel $cmd] ne \"\"} {\n"
+
"			set arg [string range $prefix $space+1 end]\n"
+
"\n"
+
"			return [lmap p [$cmd -commands] {\n"
+
"				if {![string match \"${arg}*\" $p]} continue\n"
+
"				function \"$cmd $p\"\n"
+
"			}]\n"
+
"		}\n"
+
"	}\n"
+
"\n"
+
"	if {[string match \"source *\" $prefix]} {\n"
+
"		set path [string range $prefix 7 end]\n"
+
"		return [lmap p [glob -nocomplain \"${path}*\"] {\n"
+
"			function \"source $p\"\n"
+
"		}]\n"
+
"	}\n"
+
"\n"
+
"	return [lmap p [lsort [info commands $prefix*]] {\n"
+
"		if {[string match \"* *\" $p]} {\n"
+
"			continue\n"
+
"		}\n"
+
"		function $p\n"
+
"	}]\n"
+
"}\n"
+
"\n"
+
"_jimsh_init\n"
+
);
+
}
+
int Jim_globInit(Jim_Interp *interp)
+
{
+
	if (Jim_PackageProvide(interp, "glob", "1.0", JIM_ERRMSG))
+
		return JIM_ERR;
+

+
	return Jim_EvalSource(interp, "glob.tcl", 1,
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"package require readdir\n"
+
"\n"
+
"\n"
+
"proc glob.globdir {dir pattern} {\n"
+
"	if {[file exists $dir/$pattern]} {\n"
+
"\n"
+
"		return [list $pattern]\n"
+
"	}\n"
+
"\n"
+
"	set result {}\n"
+
"	set files [readdir $dir]\n"
+
"	lappend files . ..\n"
+
"\n"
+
"	foreach name $files {\n"
+
"		if {[string match $pattern $name]} {\n"
+
"\n"
+
"			if {[string index $name 0] eq \".\" && [string index $pattern 0] ne \".\"} {\n"
+
"				continue\n"
+
"			}\n"
+
"			lappend result $name\n"
+
"		}\n"
+
"	}\n"
+
"\n"
+
"	return $result\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc glob.explode {pattern} {\n"
+
"	set oldexp {}\n"
+
"	set newexp {\"\"}\n"
+
"\n"
+
"	while 1 {\n"
+
"		set oldexp $newexp\n"
+
"		set newexp {}\n"
+
"		set ob [string first \\{ $pattern]\n"
+
"		set cb [string first \\} $pattern]\n"
+
"\n"
+
"		if {$ob < $cb && $ob != -1} {\n"
+
"			set mid [string range $pattern 0 $ob-1]\n"
+
"			set subexp [lassign [glob.explode [string range $pattern $ob+1 end]] pattern]\n"
+
"			if {$pattern eq \"\"} {\n"
+
"				error \"unmatched open brace in glob pattern\"\n"
+
"			}\n"
+
"			set pattern [string range $pattern 1 end]\n"
+
"\n"
+
"			foreach subs $subexp {\n"
+
"				foreach sub [split $subs ,] {\n"
+
"					foreach old $oldexp {\n"
+
"						lappend newexp $old$mid$sub\n"
+
"					}\n"
+
"				}\n"
+
"			}\n"
+
"		} elseif {$cb != -1} {\n"
+
"			set suf  [string range $pattern 0 $cb-1]\n"
+
"			set rest [string range $pattern $cb end]\n"
+
"			break\n"
+
"		} else {\n"
+
"			set suf  $pattern\n"
+
"			set rest \"\"\n"
+
"			break\n"
+
"		}\n"
+
"	}\n"
+
"\n"
+
"	foreach old $oldexp {\n"
+
"		lappend newexp $old$suf\n"
+
"	}\n"
+
"	list $rest {*}$newexp\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc glob.glob {base pattern} {\n"
+
"	set dir [file dirname $pattern]\n"
+
"	if {$pattern eq $dir || $pattern eq \"\"} {\n"
+
"		return [list [file join $base $dir] $pattern]\n"
+
"	} elseif {$pattern eq [file tail $pattern]} {\n"
+
"		set dir \"\"\n"
+
"	}\n"
+
"\n"
+
"\n"
+
"	set dirlist [glob.glob $base $dir]\n"
+
"	set pattern [file tail $pattern]\n"
+
"\n"
+
"\n"
+
"	set result {}\n"
+
"	foreach {realdir dir} $dirlist {\n"
+
"		if {![file isdir $realdir]} {\n"
+
"			continue\n"
+
"		}\n"
+
"		if {[string index $dir end] ne \"/\" && $dir ne \"\"} {\n"
+
"			append dir /\n"
+
"		}\n"
+
"		foreach name [glob.globdir $realdir $pattern] {\n"
+
"			lappend result [file join $realdir $name] $dir$name\n"
+
"		}\n"
+
"	}\n"
+
"	return $result\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc glob {args} {\n"
+
"	set nocomplain 0\n"
+
"	set base \"\"\n"
+
"	set tails 0\n"
+
"\n"
+
"	set n 0\n"
+
"	foreach arg $args {\n"
+
"		if {[info exists param]} {\n"
+
"			set $param $arg\n"
+
"			unset param\n"
+
"			incr n\n"
+
"			continue\n"
+
"		}\n"
+
"		switch -glob -- $arg {\n"
+
"			-d* {\n"
+
"				set switch $arg\n"
+
"				set param base\n"
+
"			}\n"
+
"			-n* {\n"
+
"				set nocomplain 1\n"
+
"			}\n"
+
"			-ta* {\n"
+
"				set tails 1\n"
+
"			}\n"
+
"			-- {\n"
+
"				incr n\n"
+
"				break\n"
+
"			}\n"
+
"			-* {\n"
+
"				return -code error \"bad option \\\"$arg\\\": must be -directory, -nocomplain, -tails, or --\"\n"
+
"			}\n"
+
"			*  {\n"
+
"				break\n"
+
"			}\n"
+
"		}\n"
+
"		incr n\n"
+
"	}\n"
+
"	if {[info exists param]} {\n"
+
"		return -code error \"missing argument to \\\"$switch\\\"\"\n"
+
"	}\n"
+
"	if {[llength $args] <= $n} {\n"
+
"		return -code error \"wrong # args: should be \\\"glob ?options? pattern ?pattern ...?\\\"\"\n"
+
"	}\n"
+
"\n"
+
"	set args [lrange $args $n end]\n"
+
"\n"
+
"	set result {}\n"
+
"	foreach pattern $args {\n"
+
"		set escpattern [string map {\n"
+
"			\\\\\\\\ \\x01 \\\\\\{ \\x02 \\\\\\} \\x03 \\\\, \\x04\n"
+
"		} $pattern]\n"
+
"		set patexps [lassign [glob.explode $escpattern] rest]\n"
+
"		if {$rest ne \"\"} {\n"
+
"			return -code error \"unmatched close brace in glob pattern\"\n"
+
"		}\n"
+
"		foreach patexp $patexps {\n"
+
"			set patexp [string map {\n"
+
"				\\x01 \\\\\\\\ \\x02 \\{ \\x03 \\} \\x04 ,\n"
+
"			} $patexp]\n"
+
"			foreach {realname name} [glob.glob $base $patexp] {\n"
+
"				incr n\n"
+
"				if {$tails} {\n"
+
"					lappend result $name\n"
+
"				} else {\n"
+
"					lappend result [file join $base $name]\n"
+
"				}\n"
+
"			}\n"
+
"		}\n"
+
"	}\n"
+
"\n"
+
"	if {!$nocomplain && [llength $result] == 0} {\n"
+
"		set s $(([llength $args] > 1) ? \"s\" : \"\")\n"
+
"		return -code error \"no files matched glob pattern$s \\\"[join $args]\\\"\"\n"
+
"	}\n"
+
"\n"
+
"	return $result\n"
+
"}\n"
+
);
+
}
+
int Jim_stdlibInit(Jim_Interp *interp)
+
{
+
	if (Jim_PackageProvide(interp, "stdlib", "1.0", JIM_ERRMSG))
+
		return JIM_ERR;
+

+
	return Jim_EvalSource(interp, "stdlib.tcl", 1,
+
"\n"
+
"\n"
+
"\n"
+
"proc lambda {arglist args} {\n"
+
"	tailcall proc [ref {} function lambda.finalizer] $arglist {*}$args\n"
+
"}\n"
+
"\n"
+
"proc lambda.finalizer {name val} {\n"
+
"	rename $name {}\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc curry {args} {\n"
+
"	alias [ref {} function lambda.finalizer] {*}$args\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc function {value} {\n"
+
"	return $value\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc stacktrace {{skip 0}} {\n"
+
"	set trace {}\n"
+
"	incr skip\n"
+
"	foreach level [range $skip [info level]] {\n"
+
"		lappend trace {*}[info frame -$level]\n"
+
"	}\n"
+
"	return $trace\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc stackdump {stacktrace} {\n"
+
"	set lines {}\n"
+
"	foreach {l f p} [lreverse $stacktrace] {\n"
+
"		set line {}\n"
+
"		if {$p ne \"\"} {\n"
+
"			append line \"in procedure '$p' \"\n"
+
"			if {$f ne \"\"} {\n"
+
"				append line \"called \"\n"
+
"			}\n"
+
"		}\n"
+
"		if {$f ne \"\"} {\n"
+
"			append line \"at file \\\"$f\\\", line $l\"\n"
+
"		}\n"
+
"		if {$line ne \"\"} {\n"
+
"			lappend lines $line\n"
+
"		}\n"
+
"	}\n"
+
"	join $lines \\n\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc errorInfo {msg {stacktrace \"\"}} {\n"
+
"	if {$stacktrace eq \"\"} {\n"
+
"\n"
+
"		set stacktrace [info stacktrace]\n"
+
"\n"
+
"		lappend stacktrace {*}[stacktrace 1]\n"
+
"	}\n"
+
"	lassign $stacktrace p f l\n"
+
"	if {$f ne \"\"} {\n"
+
"		set result \"$f:$l: Error: \"\n"
+
"	}\n"
+
"	append result \"$msg\\n\"\n"
+
"	append result [stackdump $stacktrace]\n"
+
"\n"
+
"\n"
+
"	string trim $result\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc {info nameofexecutable} {} {\n"
+
"	if {[exists ::jim::exe]} {\n"
+
"		return $::jim::exe\n"
+
"	}\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc {dict update} {&varName args script} {\n"
+
"	set keys {}\n"
+
"	foreach {n v} $args {\n"
+
"		upvar $v var_$v\n"
+
"		if {[dict exists $varName $n]} {\n"
+
"			set var_$v [dict get $varName $n]\n"
+
"		}\n"
+
"	}\n"
+
"	catch {uplevel 1 $script} msg opts\n"
+
"	if {[info exists varName]} {\n"
+
"		foreach {n v} $args {\n"
+
"			if {[info exists var_$v]} {\n"
+
"				dict set varName $n [set var_$v]\n"
+
"			} else {\n"
+
"				dict unset varName $n\n"
+
"			}\n"
+
"		}\n"
+
"	}\n"
+
"	return {*}$opts $msg\n"
+
"}\n"
+
"\n"
+
"proc {dict replace} {dictionary {args {key value}}} {\n"
+
"	if {[llength ${key value}] % 2} {\n"
+
"		tailcall {dict replace}\n"
+
"	}\n"
+
"	tailcall dict merge $dictionary ${key value}\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc {dict lappend} {varName key {args value}} {\n"
+
"	upvar $varName dict\n"
+
"	if {[exists dict] && [dict exists $dict $key]} {\n"
+
"		set list [dict get $dict $key]\n"
+
"	}\n"
+
"	lappend list {*}$value\n"
+
"	dict set dict $key $list\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc {dict append} {varName key {args value}} {\n"
+
"	upvar $varName dict\n"
+
"	if {[exists dict] && [dict exists $dict $key]} {\n"
+
"		set str [dict get $dict $key]\n"
+
"	}\n"
+
"	append str {*}$value\n"
+
"	dict set dict $key $str\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc {dict incr} {varName key {increment 1}} {\n"
+
"	upvar $varName dict\n"
+
"	if {[exists dict] && [dict exists $dict $key]} {\n"
+
"		set value [dict get $dict $key]\n"
+
"	}\n"
+
"	incr value $increment\n"
+
"	dict set dict $key $value\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc {dict remove} {dictionary {args key}} {\n"
+
"	foreach k $key {\n"
+
"		dict unset dictionary $k\n"
+
"	}\n"
+
"	return $dictionary\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc {dict for} {vars dictionary script} {\n"
+
"	if {[llength $vars] != 2} {\n"
+
"		return -code error \"must have exactly two variable names\"\n"
+
"	}\n"
+
"	dict size $dictionary\n"
+
"	tailcall foreach $vars $dictionary $script\n"
+
"}\n"
+
);
+
}
+
int Jim_tclcompatInit(Jim_Interp *interp)
+
{
+
	if (Jim_PackageProvide(interp, "tclcompat", "1.0", JIM_ERRMSG))
+
		return JIM_ERR;
+

+
	return Jim_EvalSource(interp, "tclcompat.tcl", 1,
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"set env [env]\n"
+
"\n"
+
"\n"
+
"if {[info commands stdout] ne \"\"} {\n"
+
"\n"
+
"	foreach p {gets flush close eof seek tell} {\n"
+
"		proc $p {chan args} {p} {\n"
+
"			tailcall $chan $p {*}$args\n"
+
"		}\n"
+
"	}\n"
+
"	unset p\n"
+
"\n"
+
"\n"
+
"\n"
+
"	proc puts {{-nonewline {}} {chan stdout} msg} {\n"
+
"		if {${-nonewline} ni {-nonewline {}}} {\n"
+
"			tailcall ${-nonewline} puts $msg\n"
+
"		}\n"
+
"		tailcall $chan puts {*}${-nonewline} $msg\n"
+
"	}\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"	proc read {{-nonewline {}} chan} {\n"
+
"		if {${-nonewline} ni {-nonewline {}}} {\n"
+
"			tailcall ${-nonewline} read {*}${chan}\n"
+
"		}\n"
+
"		tailcall $chan read {*}${-nonewline}\n"
+
"	}\n"
+
"\n"
+
"	proc fconfigure {f args} {\n"
+
"		foreach {n v} $args {\n"
+
"			switch -glob -- $n {\n"
+
"				-bl* {\n"
+
"					$f ndelay $(!$v)\n"
+
"				}\n"
+
"				-bu* {\n"
+
"					$f buffering $v\n"
+
"				}\n"
+
"				-tr* {\n"
+
"\n"
+
"				}\n"
+
"				default {\n"
+
"					return -code error \"fconfigure: unknown option $n\"\n"
+
"				}\n"
+
"			}\n"
+
"		}\n"
+
"	}\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc fileevent {args} {\n"
+
"	tailcall {*}$args\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc parray {arrayname {pattern *} {puts puts}} {\n"
+
"	upvar $arrayname a\n"
+
"\n"
+
"	set max 0\n"
+
"	foreach name [array names a $pattern]] {\n"
+
"		if {[string length $name] > $max} {\n"
+
"			set max [string length $name]\n"
+
"		}\n"
+
"	}\n"
+
"	incr max [string length $arrayname]\n"
+
"	incr max 2\n"
+
"	foreach name [lsort [array names a $pattern]] {\n"
+
"		$puts [format \"%-${max}s = %s\" $arrayname\\($name\\) $a($name)]\n"
+
"	}\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc {file copy} {{force {}} source target} {\n"
+
"	try {\n"
+
"		if {$force ni {{} -force}} {\n"
+
"			error \"bad option \\\"$force\\\": should be -force\"\n"
+
"		}\n"
+
"\n"
+
"		set in [open $source rb]\n"
+
"\n"
+
"		if {[file exists $target]} {\n"
+
"			if {$force eq \"\"} {\n"
+
"				error \"error copying \\\"$source\\\" to \\\"$target\\\": file already exists\"\n"
+
"			}\n"
+
"\n"
+
"			if {$source eq $target} {\n"
+
"				return\n"
+
"			}\n"
+
"\n"
+
"\n"
+
"			file stat $source ss\n"
+
"			file stat $target ts\n"
+
"			if {$ss(dev) == $ts(dev) && $ss(ino) == $ts(ino) && $ss(ino)} {\n"
+
"				return\n"
+
"			}\n"
+
"		}\n"
+
"		set out [open $target wb]\n"
+
"		$in copyto $out\n"
+
"		$out close\n"
+
"	} on error {msg opts} {\n"
+
"		incr opts(-level)\n"
+
"		return {*}$opts $msg\n"
+
"	} finally {\n"
+
"		catch {$in close}\n"
+
"	}\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc popen {cmd {mode r}} {\n"
+
"	lassign [socket pipe] r w\n"
+
"	try {\n"
+
"		if {[string match \"w*\" $mode]} {\n"
+
"			lappend cmd <@$r &\n"
+
"			set pids [exec {*}$cmd]\n"
+
"			$r close\n"
+
"			set f $w\n"
+
"		} else {\n"
+
"			lappend cmd >@$w &\n"
+
"			set pids [exec {*}$cmd]\n"
+
"			$w close\n"
+
"			set f $r\n"
+
"		}\n"
+
"		lambda {cmd args} {f pids} {\n"
+
"			if {$cmd eq \"pid\"} {\n"
+
"				return $pids\n"
+
"			}\n"
+
"			if {$cmd eq \"close\"} {\n"
+
"				$f close\n"
+
"\n"
+
"				foreach p $pids { os.wait $p }\n"
+
"				return\n"
+
"			}\n"
+
"			tailcall $f $cmd {*}$args\n"
+
"		}\n"
+
"	} on error {error opts} {\n"
+
"		$r close\n"
+
"		$w close\n"
+
"		error $error\n"
+
"	}\n"
+
"}\n"
+
"\n"
+
"\n"
+
"local proc pid {{channelId {}}} {\n"
+
"	if {$channelId eq \"\"} {\n"
+
"		tailcall upcall pid\n"
+
"	}\n"
+
"	if {[catch {$channelId tell}]} {\n"
+
"		return -code error \"can not find channel named \\\"$channelId\\\"\"\n"
+
"	}\n"
+
"	if {[catch {$channelId pid} pids]} {\n"
+
"		return \"\"\n"
+
"	}\n"
+
"	return $pids\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc try {args} {\n"
+
"	set catchopts {}\n"
+
"	while {[string match -* [lindex $args 0]]} {\n"
+
"		set args [lassign $args opt]\n"
+
"		if {$opt eq \"--\"} {\n"
+
"			break\n"
+
"		}\n"
+
"		lappend catchopts $opt\n"
+
"	}\n"
+
"	if {[llength $args] == 0} {\n"
+
"		return -code error {wrong # args: should be \"try ?options? script ?argument ...?\"}\n"
+
"	}\n"
+
"	set args [lassign $args script]\n"
+
"	set code [catch -eval {*}$catchopts {uplevel 1 $script} msg opts]\n"
+
"\n"
+
"	set handled 0\n"
+
"\n"
+
"	foreach {on codes vars script} $args {\n"
+
"		switch -- $on \\\n"
+
"			on {\n"
+
"				if {!$handled && ($codes eq \"*\" || [info returncode $code] in $codes)} {\n"
+
"					lassign $vars msgvar optsvar\n"
+
"					if {$msgvar ne \"\"} {\n"
+
"						upvar $msgvar hmsg\n"
+
"						set hmsg $msg\n"
+
"					}\n"
+
"					if {$optsvar ne \"\"} {\n"
+
"						upvar $optsvar hopts\n"
+
"						set hopts $opts\n"
+
"					}\n"
+
"\n"
+
"					set code [catch {uplevel 1 $script} msg opts]\n"
+
"					incr handled\n"
+
"				}\n"
+
"			} \\\n"
+
"			finally {\n"
+
"				set finalcode [catch {uplevel 1 $codes} finalmsg finalopts]\n"
+
"				if {$finalcode} {\n"
+
"\n"
+
"					set code $finalcode\n"
+
"					set msg $finalmsg\n"
+
"					set opts $finalopts\n"
+
"				}\n"
+
"				break\n"
+
"			} \\\n"
+
"			default {\n"
+
"				return -code error \"try: expected 'on' or 'finally', got '$on'\"\n"
+
"			}\n"
+
"	}\n"
+
"\n"
+
"	if {$code} {\n"
+
"		incr opts(-level)\n"
+
"		return {*}$opts $msg\n"
+
"	}\n"
+
"	return $msg\n"
+
"}\n"
+
"\n"
+
"\n"
+
"\n"
+
"proc throw {code {msg \"\"}} {\n"
+
"	return -code $code $msg\n"
+
"}\n"
+
"\n"
+
"\n"
+
"proc {file delete force} {path} {\n"
+
"	foreach e [readdir $path] {\n"
+
"		file delete -force $path/$e\n"
+
"	}\n"
+
"	file delete $path\n"
+
"}\n"
+
);
+
}
+

+

+
#ifndef _GNU_SOURCE
+
#define _GNU_SOURCE
+
#endif
+
#include <stdio.h>
+
#include <string.h>
+
#include <errno.h>
+
#include <fcntl.h>
+
#ifdef HAVE_UNISTD_H
+
#include <unistd.h>
+
#include <sys/stat.h>
+
#endif
+

+

+
#if defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SELECT) && defined(HAVE_NETINET_IN_H) && defined(HAVE_NETDB_H) && defined(HAVE_ARPA_INET_H)
+
#include <sys/socket.h>
+
#include <netinet/in.h>
+
#include <arpa/inet.h>
+
#include <netdb.h>
+
#ifdef HAVE_SYS_UN_H
+
#include <sys/un.h>
+
#endif
+
#else
+
#define JIM_ANSIC
+
#endif
+

+
#if defined(JIM_SSL)
+
#include <openssl/ssl.h>
+
#include <openssl/err.h>
+
#endif
+

+
#ifdef HAVE_TERMIOS_H
+
#endif
+

+

+
#define AIO_CMD_LEN 32
+
#define AIO_BUF_LEN 256
+

+
#ifndef HAVE_FTELLO
+
    #define ftello ftell
+
#endif
+
#ifndef HAVE_FSEEKO
+
    #define fseeko fseek
+
#endif
+

+
#define AIO_KEEPOPEN 1
+

+
#if defined(JIM_IPV6)
+
#define IPV6 1
+
#else
+
#define IPV6 0
+
#ifndef PF_INET6
+
#define PF_INET6 0
+
#endif
+
#endif
+

+
#define JimCheckStreamError(interp, af) af->fops->error(af)
+

+

+
struct AioFile;
+

+
typedef struct {
+
    int (*writer)(struct AioFile *af, const char *buf, int len);
+
    int (*reader)(struct AioFile *af, char *buf, int len);
+
    const char *(*getline)(struct AioFile *af, char *buf, int len);
+
    int (*error)(const struct AioFile *af);
+
    const char *(*strerror)(struct AioFile *af);
+
    int (*verify)(struct AioFile *af);
+
} JimAioFopsType;
+

+
typedef struct AioFile
+
{
+
    FILE *fp;
+
    Jim_Obj *filename;
+
    int type;
+
    int openFlags;
+
    int fd;
+
    Jim_Obj *rEvent;
+
    Jim_Obj *wEvent;
+
    Jim_Obj *eEvent;
+
    int addr_family;
+
    void *ssl;
+
    const JimAioFopsType *fops;
+
} AioFile;
+

+
static int stdio_writer(struct AioFile *af, const char *buf, int len)
+
{
+
    return fwrite(buf, 1, len, af->fp);
+
}
+

+
static int stdio_reader(struct AioFile *af, char *buf, int len)
+
{
+
    return fread(buf, 1, len, af->fp);
+
}
+

+
static const char *stdio_getline(struct AioFile *af, char *buf, int len)
+
{
+
    return fgets(buf, len, af->fp);
+
}
+

+
static int stdio_error(const AioFile *af)
+
{
+
    if (!ferror(af->fp)) {
+
        return JIM_OK;
+
    }
+
    clearerr(af->fp);
+

+
    if (feof(af->fp) || errno == EAGAIN || errno == EINTR) {
+
        return JIM_OK;
+
    }
+
#ifdef ECONNRESET
+
    if (errno == ECONNRESET) {
+
        return JIM_OK;
+
    }
+
#endif
+
#ifdef ECONNABORTED
+
    if (errno == ECONNABORTED) {
+
        return JIM_OK;
+
    }
+
#endif
+
    return JIM_ERR;
+
}
+

+
static const char *stdio_strerror(struct AioFile *af)
+
{
+
    return strerror(errno);
+
}
+

+
static const JimAioFopsType stdio_fops = {
+
    stdio_writer,
+
    stdio_reader,
+
    stdio_getline,
+
    stdio_error,
+
    stdio_strerror,
+
    NULL
+
};
+

+

+
static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
+
static AioFile *JimMakeChannel(Jim_Interp *interp, FILE *fh, int fd, Jim_Obj *filename,
+
    const char *hdlfmt, int family, const char *mode);
+

+

+
static const char *JimAioErrorString(AioFile *af)
+
{
+
    if (af && af->fops)
+
        return af->fops->strerror(af);
+

+
    return strerror(errno);
+
}
+

+
static void JimAioSetError(Jim_Interp *interp, Jim_Obj *name)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    if (name) {
+
        Jim_SetResultFormatted(interp, "%#s: %s", name, JimAioErrorString(af));
+
    }
+
    else {
+
        Jim_SetResultString(interp, JimAioErrorString(af), -1);
+
    }
+
}
+

+
static void JimAioDelProc(Jim_Interp *interp, void *privData)
+
{
+
    AioFile *af = privData;
+

+
    JIM_NOTUSED(interp);
+

+
    Jim_DecrRefCount(interp, af->filename);
+

+
#ifdef jim_ext_eventloop
+

+
    Jim_DeleteFileHandler(interp, af->fd, JIM_EVENT_READABLE | JIM_EVENT_WRITABLE | JIM_EVENT_EXCEPTION);
+
#endif
+

+
#if defined(JIM_SSL)
+
    if (af->ssl != NULL) {
+
        SSL_free(af->ssl);
+
    }
+
#endif
+
    if (!(af->openFlags & AIO_KEEPOPEN)) {
+
        fclose(af->fp);
+
    }
+

+
    Jim_Free(af);
+
}
+

+
static int aio_cmd_read(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+
    char buf[AIO_BUF_LEN];
+
    Jim_Obj *objPtr;
+
    int nonewline = 0;
+
    jim_wide neededLen = -1;
+

+
    if (argc && Jim_CompareStringImmediate(interp, argv[0], "-nonewline")) {
+
        nonewline = 1;
+
        argv++;
+
        argc--;
+
    }
+
    if (argc == 1) {
+
        if (Jim_GetWide(interp, argv[0], &neededLen) != JIM_OK)
+
            return JIM_ERR;
+
        if (neededLen < 0) {
+
            Jim_SetResultString(interp, "invalid parameter: negative len", -1);
+
            return JIM_ERR;
+
        }
+
    }
+
    else if (argc) {
+
        return -1;
+
    }
+
    objPtr = Jim_NewStringObj(interp, NULL, 0);
+
    while (neededLen != 0) {
+
        int retval;
+
        int readlen;
+

+
        if (neededLen == -1) {
+
            readlen = AIO_BUF_LEN;
+
        }
+
        else {
+
            readlen = (neededLen > AIO_BUF_LEN ? AIO_BUF_LEN : neededLen);
+
        }
+
        retval = af->fops->reader(af, buf, readlen);
+
        if (retval > 0) {
+
            Jim_AppendString(interp, objPtr, buf, retval);
+
            if (neededLen != -1) {
+
                neededLen -= retval;
+
            }
+
        }
+
        if (retval != readlen)
+
            break;
+
    }
+

+
    if (JimCheckStreamError(interp, af)) {
+
        Jim_FreeNewObj(interp, objPtr);
+
        return JIM_ERR;
+
    }
+
    if (nonewline) {
+
        int len;
+
        const char *s = Jim_GetString(objPtr, &len);
+

+
        if (len > 0 && s[len - 1] == '\n') {
+
            objPtr->length--;
+
            objPtr->bytes[objPtr->length] = '\0';
+
        }
+
    }
+
    Jim_SetResult(interp, objPtr);
+
    return JIM_OK;
+
}
+

+
AioFile *Jim_AioFile(Jim_Interp *interp, Jim_Obj *command)
+
{
+
    Jim_Cmd *cmdPtr = Jim_GetCommand(interp, command, JIM_ERRMSG);
+

+

+
    if (cmdPtr && !cmdPtr->isproc && cmdPtr->u.native.cmdProc == JimAioSubCmdProc) {
+
        return (AioFile *) cmdPtr->u.native.privData;
+
    }
+
    Jim_SetResultFormatted(interp, "Not a filehandle: \"%#s\"", command);
+
    return NULL;
+
}
+

+
FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command)
+
{
+
    AioFile *af;
+

+
    af = Jim_AioFile(interp, command);
+
    if (af == NULL) {
+
        return NULL;
+
    }
+

+
    return af->fp;
+
}
+

+
static int aio_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+
    jim_wide count = 0;
+
    jim_wide maxlen = JIM_WIDE_MAX;
+
    AioFile *outf = Jim_AioFile(interp, argv[0]);
+

+
    if (outf == NULL) {
+
        return JIM_ERR;
+
    }
+

+
    if (argc == 2) {
+
        if (Jim_GetWide(interp, argv[1], &maxlen) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
    }
+

+
    while (count < maxlen) {
+
        char ch;
+

+
        if (af->fops->reader(af, &ch, 1) != 1) {
+
            break;
+
        }
+
        if (outf->fops->writer(outf, &ch, 1) != 1) {
+
            break;
+
        }
+
        count++;
+
    }
+

+
    if (JimCheckStreamError(interp, af) || JimCheckStreamError(interp, outf)) {
+
        return JIM_ERR;
+
    }
+

+
    Jim_SetResultInt(interp, count);
+

+
    return JIM_OK;
+
}
+

+
static int aio_cmd_gets(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+
    char buf[AIO_BUF_LEN];
+
    Jim_Obj *objPtr;
+
    int len;
+

+
    errno = 0;
+

+
    objPtr = Jim_NewStringObj(interp, NULL, 0);
+
    while (1) {
+
        buf[AIO_BUF_LEN - 1] = '_';
+

+
        if (af->fops->getline(af, buf, AIO_BUF_LEN) == NULL)
+
            break;
+

+
        if (buf[AIO_BUF_LEN - 1] == '\0' && buf[AIO_BUF_LEN - 2] != '\n') {
+
            Jim_AppendString(interp, objPtr, buf, AIO_BUF_LEN - 1);
+
        }
+
        else {
+
            len = strlen(buf);
+

+
            if (len && (buf[len - 1] == '\n')) {
+

+
                len--;
+
            }
+

+
            Jim_AppendString(interp, objPtr, buf, len);
+
            break;
+
        }
+
    }
+

+
    if (JimCheckStreamError(interp, af)) {
+

+
        Jim_FreeNewObj(interp, objPtr);
+
        return JIM_ERR;
+
    }
+

+
    if (argc) {
+
        if (Jim_SetVariable(interp, argv[0], objPtr) != JIM_OK) {
+
            Jim_FreeNewObj(interp, objPtr);
+
            return JIM_ERR;
+
        }
+

+
        len = Jim_Length(objPtr);
+

+
        if (len == 0 && feof(af->fp)) {
+

+
            len = -1;
+
        }
+
        Jim_SetResultInt(interp, len);
+
    }
+
    else {
+
        Jim_SetResult(interp, objPtr);
+
    }
+
    return JIM_OK;
+
}
+

+
static int aio_cmd_puts(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+
    int wlen;
+
    const char *wdata;
+
    Jim_Obj *strObj;
+

+
    if (argc == 2) {
+
        if (!Jim_CompareStringImmediate(interp, argv[0], "-nonewline")) {
+
            return -1;
+
        }
+
        strObj = argv[1];
+
    }
+
    else {
+
        strObj = argv[0];
+
    }
+

+
    wdata = Jim_GetString(strObj, &wlen);
+
    if (af->fops->writer(af, wdata, wlen) == wlen) {
+
        if (argc == 2 || af->fops->writer(af, "\n", 1) == 1) {
+
            return JIM_OK;
+
        }
+
    }
+
    JimAioSetError(interp, af->filename);
+
    return JIM_ERR;
+
}
+

+
static int aio_cmd_isatty(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
#ifdef HAVE_ISATTY
+
    AioFile *af = Jim_CmdPrivData(interp);
+
    Jim_SetResultInt(interp, isatty(fileno(af->fp)));
+
#else
+
    Jim_SetResultInt(interp, 0);
+
#endif
+

+
    return JIM_OK;
+
}
+

+

+
static int aio_cmd_flush(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    if (fflush(af->fp) == EOF) {
+
        JimAioSetError(interp, af->filename);
+
        return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+
static int aio_cmd_eof(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    Jim_SetResultInt(interp, feof(af->fp));
+
    return JIM_OK;
+
}
+

+
static int aio_cmd_close(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc == 3) {
+
#if !defined(JIM_ANSIC) && defined(HAVE_SHUTDOWN)
+
        static const char * const options[] = { "r", "w", NULL };
+
        enum { OPT_R, OPT_W, };
+
        int option;
+
        AioFile *af = Jim_CmdPrivData(interp);
+

+
        if (Jim_GetEnum(interp, argv[2], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        if (shutdown(af->fd, option == OPT_R ? SHUT_RD : SHUT_WR) == 0) {
+
            return JIM_OK;
+
        }
+
        JimAioSetError(interp, NULL);
+
#else
+
        Jim_SetResultString(interp, "async close not supported", -1);
+
#endif
+
        return JIM_ERR;
+
    }
+

+
    return Jim_DeleteCommand(interp, Jim_String(argv[0]));
+
}
+

+
static int aio_cmd_seek(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+
    int orig = SEEK_SET;
+
    jim_wide offset;
+

+
    if (argc == 2) {
+
        if (Jim_CompareStringImmediate(interp, argv[1], "start"))
+
            orig = SEEK_SET;
+
        else if (Jim_CompareStringImmediate(interp, argv[1], "current"))
+
            orig = SEEK_CUR;
+
        else if (Jim_CompareStringImmediate(interp, argv[1], "end"))
+
            orig = SEEK_END;
+
        else {
+
            return -1;
+
        }
+
    }
+
    if (Jim_GetWide(interp, argv[0], &offset) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    if (fseeko(af->fp, offset, orig) == -1) {
+
        JimAioSetError(interp, af->filename);
+
        return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+
static int aio_cmd_tell(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    Jim_SetResultInt(interp, ftello(af->fp));
+
    return JIM_OK;
+
}
+

+
static int aio_cmd_filename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    Jim_SetResult(interp, af->filename);
+
    return JIM_OK;
+
}
+

+
#ifdef O_NDELAY
+
static int aio_cmd_ndelay(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    int fmode = fcntl(af->fd, F_GETFL);
+

+
    if (argc) {
+
        long nb;
+

+
        if (Jim_GetLong(interp, argv[0], &nb) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        if (nb) {
+
            fmode |= O_NDELAY;
+
        }
+
        else {
+
            fmode &= ~O_NDELAY;
+
        }
+
        (void)fcntl(af->fd, F_SETFL, fmode);
+
    }
+
    Jim_SetResultInt(interp, (fmode & O_NONBLOCK) ? 1 : 0);
+
    return JIM_OK;
+
}
+
#endif
+

+
#ifdef HAVE_FSYNC
+
static int aio_cmd_sync(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    fflush(af->fp);
+
    fsync(af->fd);
+
    return JIM_OK;
+
}
+
#endif
+

+
static int aio_cmd_buffering(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    static const char * const options[] = {
+
        "none",
+
        "line",
+
        "full",
+
        NULL
+
    };
+
    enum
+
    {
+
        OPT_NONE,
+
        OPT_LINE,
+
        OPT_FULL,
+
    };
+
    int option;
+

+
    if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    switch (option) {
+
        case OPT_NONE:
+
            setvbuf(af->fp, NULL, _IONBF, 0);
+
            break;
+
        case OPT_LINE:
+
            setvbuf(af->fp, NULL, _IOLBF, BUFSIZ);
+
            break;
+
        case OPT_FULL:
+
            setvbuf(af->fp, NULL, _IOFBF, BUFSIZ);
+
            break;
+
    }
+
    return JIM_OK;
+
}
+

+
#ifdef jim_ext_eventloop
+
static void JimAioFileEventFinalizer(Jim_Interp *interp, void *clientData)
+
{
+
    Jim_Obj **objPtrPtr = clientData;
+

+
    Jim_DecrRefCount(interp, *objPtrPtr);
+
    *objPtrPtr = NULL;
+
}
+

+
static int JimAioFileEventHandler(Jim_Interp *interp, void *clientData, int mask)
+
{
+
    Jim_Obj **objPtrPtr = clientData;
+

+
    return Jim_EvalObjBackground(interp, *objPtrPtr);
+
}
+

+
static int aio_eventinfo(Jim_Interp *interp, AioFile * af, unsigned mask, Jim_Obj **scriptHandlerObj,
+
    int argc, Jim_Obj * const *argv)
+
{
+
    if (argc == 0) {
+

+
        if (*scriptHandlerObj) {
+
            Jim_SetResult(interp, *scriptHandlerObj);
+
        }
+
        return JIM_OK;
+
    }
+

+
    if (*scriptHandlerObj) {
+

+
        Jim_DeleteFileHandler(interp, af->fd, mask);
+
    }
+

+

+
    if (Jim_Length(argv[0]) == 0) {
+

+
        return JIM_OK;
+
    }
+

+

+
    Jim_IncrRefCount(argv[0]);
+
    *scriptHandlerObj = argv[0];
+

+
    Jim_CreateFileHandler(interp, af->fd, mask,
+
        JimAioFileEventHandler, scriptHandlerObj, JimAioFileEventFinalizer);
+

+
    return JIM_OK;
+
}
+

+
static int aio_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    return aio_eventinfo(interp, af, JIM_EVENT_READABLE, &af->rEvent, argc, argv);
+
}
+

+
static int aio_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    return aio_eventinfo(interp, af, JIM_EVENT_WRITABLE, &af->wEvent, argc, argv);
+
}
+

+
static int aio_cmd_onexception(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    AioFile *af = Jim_CmdPrivData(interp);
+

+
    return aio_eventinfo(interp, af, JIM_EVENT_EXCEPTION, &af->eEvent, argc, argv);
+
}
+
#endif
+

+

+

+

+
static const jim_subcmd_type aio_command_table[] = {
+
    {   "read",
+
        "?-nonewline? ?len?",
+
        aio_cmd_read,
+
        0,
+
        2,
+

+
    },
+
    {   "copyto",
+
        "handle ?size?",
+
        aio_cmd_copy,
+
        1,
+
        2,
+

+
    },
+
    {   "gets",
+
        "?var?",
+
        aio_cmd_gets,
+
        0,
+
        1,
+

+
    },
+
    {   "puts",
+
        "?-nonewline? str",
+
        aio_cmd_puts,
+
        1,
+
        2,
+

+
    },
+
    {   "isatty",
+
        NULL,
+
        aio_cmd_isatty,
+
        0,
+
        0,
+

+
    },
+
    {   "flush",
+
        NULL,
+
        aio_cmd_flush,
+
        0,
+
        0,
+

+
    },
+
    {   "eof",
+
        NULL,
+
        aio_cmd_eof,
+
        0,
+
        0,
+

+
    },
+
    {   "close",
+
        "?r(ead)|w(rite)?",
+
        aio_cmd_close,
+
        0,
+
        1,
+
        JIM_MODFLAG_FULLARGV,
+

+
    },
+
    {   "seek",
+
        "offset ?start|current|end",
+
        aio_cmd_seek,
+
        1,
+
        2,
+

+
    },
+
    {   "tell",
+
        NULL,
+
        aio_cmd_tell,
+
        0,
+
        0,
+

+
    },
+
    {   "filename",
+
        NULL,
+
        aio_cmd_filename,
+
        0,
+
        0,
+

+
    },
+
#ifdef O_NDELAY
+
    {   "ndelay",
+
        "?0|1?",
+
        aio_cmd_ndelay,
+
        0,
+
        1,
+

+
    },
+
#endif
+
#ifdef HAVE_FSYNC
+
    {   "sync",
+
        NULL,
+
        aio_cmd_sync,
+
        0,
+
        0,
+

+
    },
+
#endif
+
    {   "buffering",
+
        "none|line|full",
+
        aio_cmd_buffering,
+
        1,
+
        1,
+

+
    },
+
#ifdef jim_ext_eventloop
+
    {   "readable",
+
        "?readable-script?",
+
        aio_cmd_readable,
+
        0,
+
        1,
+

+
    },
+
    {   "writable",
+
        "?writable-script?",
+
        aio_cmd_writable,
+
        0,
+
        1,
+

+
    },
+
    {   "onexception",
+
        "?exception-script?",
+
        aio_cmd_onexception,
+
        0,
+
        1,
+

+
    },
+
#endif
+
    { NULL }
+
};
+

+
static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return Jim_CallSubCmd(interp, Jim_ParseSubCmd(interp, aio_command_table, argc, argv), argc, argv);
+
}
+

+
static int JimAioOpenCommand(Jim_Interp *interp, int argc,
+
        Jim_Obj *const *argv)
+
{
+
    const char *mode;
+

+
    if (argc != 2 && argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "filename ?mode?");
+
        return JIM_ERR;
+
    }
+

+
    mode = (argc == 3) ? Jim_String(argv[2]) : "r";
+

+
#ifdef jim_ext_tclcompat
+
    {
+
        const char *filename = Jim_String(argv[1]);
+

+

+
        if (*filename == '|') {
+
            Jim_Obj *evalObj[3];
+

+
            evalObj[0] = Jim_NewStringObj(interp, "::popen", -1);
+
            evalObj[1] = Jim_NewStringObj(interp, filename + 1, -1);
+
            evalObj[2] = Jim_NewStringObj(interp, mode, -1);
+

+
            return Jim_EvalObjVector(interp, 3, evalObj);
+
        }
+
    }
+
#endif
+
    return JimMakeChannel(interp, NULL, -1, argv[1], "aio.handle%ld", 0, mode) ? JIM_OK : JIM_ERR;
+
}
+

+

+
static AioFile *JimMakeChannel(Jim_Interp *interp, FILE *fh, int fd, Jim_Obj *filename,
+
    const char *hdlfmt, int family, const char *mode)
+
{
+
    AioFile *af;
+
    char buf[AIO_CMD_LEN];
+
    int openFlags = 0;
+

+
    snprintf(buf, sizeof(buf), hdlfmt, Jim_GetId(interp));
+

+
    if (fh) {
+
        openFlags = AIO_KEEPOPEN;
+
    }
+

+
    snprintf(buf, sizeof(buf), hdlfmt, Jim_GetId(interp));
+
    if (!filename) {
+
        filename = Jim_NewStringObj(interp, buf, -1);
+
    }
+

+
    Jim_IncrRefCount(filename);
+

+
    if (fh == NULL) {
+
#if !defined(JIM_ANSIC)
+
        if (fd >= 0) {
+
            fh = fdopen(fd, mode);
+
        }
+
        else
+
#endif
+
            fh = fopen(Jim_String(filename), mode);
+

+
        if (fh == NULL) {
+
            JimAioSetError(interp, filename);
+
#if !defined(JIM_ANSIC)
+
            if (fd >= 0) {
+
                close(fd);
+
            }
+
#endif
+
            Jim_DecrRefCount(interp, filename);
+
            return NULL;
+
        }
+
    }
+

+

+
    af = Jim_Alloc(sizeof(*af));
+
    memset(af, 0, sizeof(*af));
+
    af->fp = fh;
+
    af->fd = fileno(fh);
+
    af->filename = filename;
+
#ifdef FD_CLOEXEC
+
    if ((openFlags & AIO_KEEPOPEN) == 0) {
+
        (void)fcntl(af->fd, F_SETFD, FD_CLOEXEC);
+
    }
+
#endif
+
    af->openFlags = openFlags;
+
    af->addr_family = family;
+
    af->fops = &stdio_fops;
+
    af->ssl = NULL;
+

+
    Jim_CreateCommand(interp, buf, JimAioSubCmdProc, af, JimAioDelProc);
+

+
    Jim_SetResult(interp, Jim_MakeGlobalNamespaceName(interp, Jim_NewStringObj(interp, buf, -1)));
+

+
    return af;
+
}
+

+
#if defined(HAVE_PIPE) || (defined(HAVE_SOCKETPAIR) && defined(HAVE_SYS_UN_H))
+
static int JimMakeChannelPair(Jim_Interp *interp, int p[2], Jim_Obj *filename,
+
    const char *hdlfmt, int family, const char *mode[2])
+
{
+
    if (JimMakeChannel(interp, NULL, p[0], filename, hdlfmt, family, mode[0])) {
+
        Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
+
        Jim_ListAppendElement(interp, objPtr, Jim_GetResult(interp));
+

+
        if (JimMakeChannel(interp, NULL, p[1], filename, hdlfmt, family, mode[1])) {
+
            Jim_ListAppendElement(interp, objPtr, Jim_GetResult(interp));
+
            Jim_SetResult(interp, objPtr);
+
            return JIM_OK;
+
        }
+
    }
+

+

+
    close(p[0]);
+
    close(p[1]);
+
    JimAioSetError(interp, NULL);
+
    return JIM_ERR;
+
}
+
#endif
+

+

+
int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template)
+
{
+
#ifdef HAVE_MKSTEMP
+
    int fd;
+
    mode_t mask;
+
    Jim_Obj *filenameObj;
+

+
    if (filename_template == NULL) {
+
        const char *tmpdir = getenv("TMPDIR");
+
        if (tmpdir == NULL || *tmpdir == '\0' || access(tmpdir, W_OK) != 0) {
+
            tmpdir = "/tmp/";
+
        }
+
        filenameObj = Jim_NewStringObj(interp, tmpdir, -1);
+
        if (tmpdir[0] && tmpdir[strlen(tmpdir) - 1] != '/') {
+
            Jim_AppendString(interp, filenameObj, "/", 1);
+
        }
+
        Jim_AppendString(interp, filenameObj, "tcl.tmp.XXXXXX", -1);
+
    }
+
    else {
+
        filenameObj = Jim_NewStringObj(interp, filename_template, -1);
+
    }
+

+

+
    mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
+
    fd = mkstemp(filenameObj->bytes);
+
    umask(mask);
+
    if (fd < 0) {
+
        JimAioSetError(interp, filenameObj);
+
        Jim_FreeNewObj(interp, filenameObj);
+
        return -1;
+
    }
+

+
    Jim_SetResult(interp, filenameObj);
+
    return fd;
+
#else
+
    Jim_SetResultString(interp, "platform has no tempfile support", -1);
+
    return -1;
+
#endif
+
}
+

+

+
int Jim_aioInit(Jim_Interp *interp)
+
{
+
    if (Jim_PackageProvide(interp, "aio", "1.0", JIM_ERRMSG))
+
        return JIM_ERR;
+

+
#if defined(JIM_SSL)
+
    Jim_CreateCommand(interp, "load_ssl_certs", JimAioLoadSSLCertsCommand, NULL, NULL);
+
#endif
+

+
    Jim_CreateCommand(interp, "open", JimAioOpenCommand, NULL, NULL);
+
#ifndef JIM_ANSIC
+
    Jim_CreateCommand(interp, "socket", JimAioSockCommand, NULL, NULL);
+
#endif
+

+

+
    JimMakeChannel(interp, stdin, -1, NULL, "stdin", 0, "r");
+
    JimMakeChannel(interp, stdout, -1, NULL, "stdout", 0, "w");
+
    JimMakeChannel(interp, stderr, -1, NULL, "stderr", 0, "w");
+

+
    return JIM_OK;
+
}
+

+
#include <errno.h>
+
#include <stdio.h>
+
#include <string.h>
+

+

+
#ifdef HAVE_DIRENT_H
+
#include <dirent.h>
+
#endif
+

+
int Jim_ReaddirCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *dirPath;
+
    DIR *dirPtr;
+
    struct dirent *entryPtr;
+
    int nocomplain = 0;
+

+
    if (argc == 3 && Jim_CompareStringImmediate(interp, argv[1], "-nocomplain")) {
+
        nocomplain = 1;
+
    }
+
    if (argc != 2 && !nocomplain) {
+
        Jim_WrongNumArgs(interp, 1, argv, "?-nocomplain? dirPath");
+
        return JIM_ERR;
+
    }
+

+
    dirPath = Jim_String(argv[1 + nocomplain]);
+

+
    dirPtr = opendir(dirPath);
+
    if (dirPtr == NULL) {
+
        if (nocomplain) {
+
            return JIM_OK;
+
        }
+
        Jim_SetResultString(interp, strerror(errno), -1);
+
        return JIM_ERR;
+
    }
+
    else {
+
        Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
+

+
        while ((entryPtr = readdir(dirPtr)) != NULL) {
+
            if (entryPtr->d_name[0] == '.') {
+
                if (entryPtr->d_name[1] == '\0') {
+
                    continue;
+
                }
+
                if ((entryPtr->d_name[1] == '.') && (entryPtr->d_name[2] == '\0'))
+
                    continue;
+
            }
+
            Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, entryPtr->d_name, -1));
+
        }
+
        closedir(dirPtr);
+

+
        Jim_SetResult(interp, listObj);
+

+
        return JIM_OK;
+
    }
+
}
+

+
int Jim_readdirInit(Jim_Interp *interp)
+
{
+
    if (Jim_PackageProvide(interp, "readdir", "1.0", JIM_ERRMSG))
+
        return JIM_ERR;
+

+
    Jim_CreateCommand(interp, "readdir", Jim_ReaddirCmd, NULL, NULL);
+
    return JIM_OK;
+
}
+

+
#include <stdlib.h>
+
#include <string.h>
+

+
#if defined(JIM_REGEXP)
+
#else
+
    #include <regex.h>
+
#endif
+

+
static void FreeRegexpInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    regfree(objPtr->internalRep.regexpValue.compre);
+
    Jim_Free(objPtr->internalRep.regexpValue.compre);
+
}
+

+
static const Jim_ObjType regexpObjType = {
+
    "regexp",
+
    FreeRegexpInternalRep,
+
    NULL,
+
    NULL,
+
    JIM_TYPE_NONE
+
};
+

+
static regex_t *SetRegexpFromAny(Jim_Interp *interp, Jim_Obj *objPtr, unsigned flags)
+
{
+
    regex_t *compre;
+
    const char *pattern;
+
    int ret;
+

+

+
    if (objPtr->typePtr == &regexpObjType &&
+
        objPtr->internalRep.regexpValue.compre && objPtr->internalRep.regexpValue.flags == flags) {
+

+
        return objPtr->internalRep.regexpValue.compre;
+
    }
+

+

+

+

+
    pattern = Jim_String(objPtr);
+
    compre = Jim_Alloc(sizeof(regex_t));
+

+
    if ((ret = regcomp(compre, pattern, REG_EXTENDED | flags)) != 0) {
+
        char buf[100];
+

+
        regerror(ret, compre, buf, sizeof(buf));
+
        Jim_SetResultFormatted(interp, "couldn't compile regular expression pattern: %s", buf);
+
        regfree(compre);
+
        Jim_Free(compre);
+
        return NULL;
+
    }
+

+
    Jim_FreeIntRep(interp, objPtr);
+

+
    objPtr->typePtr = &regexpObjType;
+
    objPtr->internalRep.regexpValue.flags = flags;
+
    objPtr->internalRep.regexpValue.compre = compre;
+

+
    return compre;
+
}
+

+
int Jim_RegexpCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int opt_indices = 0;
+
    int opt_all = 0;
+
    int opt_inline = 0;
+
    regex_t *regex;
+
    int match, i, j;
+
    int offset = 0;
+
    regmatch_t *pmatch = NULL;
+
    int source_len;
+
    int result = JIM_OK;
+
    const char *pattern;
+
    const char *source_str;
+
    int num_matches = 0;
+
    int num_vars;
+
    Jim_Obj *resultListObj = NULL;
+
    int regcomp_flags = 0;
+
    int eflags = 0;
+
    int option;
+
    enum {
+
        OPT_INDICES,  OPT_NOCASE, OPT_LINE, OPT_ALL, OPT_INLINE, OPT_START, OPT_END
+
    };
+
    static const char * const options[] = {
+
        "-indices", "-nocase", "-line", "-all", "-inline", "-start", "--", NULL
+
    };
+

+
    if (argc < 3) {
+
      wrongNumArgs:
+
        Jim_WrongNumArgs(interp, 1, argv,
+
            "?-switch ...? exp string ?matchVar? ?subMatchVar ...?");
+
        return JIM_ERR;
+
    }
+

+
    for (i = 1; i < argc; i++) {
+
        const char *opt = Jim_String(argv[i]);
+

+
        if (*opt != '-') {
+
            break;
+
        }
+
        if (Jim_GetEnum(interp, argv[i], options, &option, "switch", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        if (option == OPT_END) {
+
            i++;
+
            break;
+
        }
+
        switch (option) {
+
            case OPT_INDICES:
+
                opt_indices = 1;
+
                break;
+

+
            case OPT_NOCASE:
+
                regcomp_flags |= REG_ICASE;
+
                break;
+

+
            case OPT_LINE:
+
                regcomp_flags |= REG_NEWLINE;
+
                break;
+

+
            case OPT_ALL:
+
                opt_all = 1;
+
                break;
+

+
            case OPT_INLINE:
+
                opt_inline = 1;
+
                break;
+

+
            case OPT_START:
+
                if (++i == argc) {
+
                    goto wrongNumArgs;
+
                }
+
                if (Jim_GetIndex(interp, argv[i], &offset) != JIM_OK) {
+
                    return JIM_ERR;
+
                }
+
                break;
+
        }
+
    }
+
    if (argc - i < 2) {
+
        goto wrongNumArgs;
+
    }
+

+
    regex = SetRegexpFromAny(interp, argv[i], regcomp_flags);
+
    if (!regex) {
+
        return JIM_ERR;
+
    }
+

+
    pattern = Jim_String(argv[i]);
+
    source_str = Jim_GetString(argv[i + 1], &source_len);
+

+
    num_vars = argc - i - 2;
+

+
    if (opt_inline) {
+
        if (num_vars) {
+
            Jim_SetResultString(interp, "regexp match variables not allowed when using -inline",
+
                -1);
+
            result = JIM_ERR;
+
            goto done;
+
        }
+
        num_vars = regex->re_nsub + 1;
+
    }
+

+
    pmatch = Jim_Alloc((num_vars + 1) * sizeof(*pmatch));
+

+
    if (offset) {
+
        if (offset < 0) {
+
            offset += source_len + 1;
+
        }
+
        if (offset > source_len) {
+
            source_str += source_len;
+
        }
+
        else if (offset > 0) {
+
            source_str += offset;
+
        }
+
        eflags |= REG_NOTBOL;
+
    }
+

+
    if (opt_inline) {
+
        resultListObj = Jim_NewListObj(interp, NULL, 0);
+
    }
+

+
  next_match:
+
    match = regexec(regex, source_str, num_vars + 1, pmatch, eflags);
+
    if (match >= REG_BADPAT) {
+
        char buf[100];
+

+
        regerror(match, regex, buf, sizeof(buf));
+
        Jim_SetResultFormatted(interp, "error while matching pattern: %s", buf);
+
        result = JIM_ERR;
+
        goto done;
+
    }
+

+
    if (match == REG_NOMATCH) {
+
        goto done;
+
    }
+

+
    num_matches++;
+

+
    if (opt_all && !opt_inline) {
+

+
        goto try_next_match;
+
    }
+

+

+
    j = 0;
+
    for (i += 2; opt_inline ? j < num_vars : i < argc; i++, j++) {
+
        Jim_Obj *resultObj;
+

+
        if (opt_indices) {
+
            resultObj = Jim_NewListObj(interp, NULL, 0);
+
        }
+
        else {
+
            resultObj = Jim_NewStringObj(interp, "", 0);
+
        }
+

+
        if (pmatch[j].rm_so == -1) {
+
            if (opt_indices) {
+
                Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, -1));
+
                Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, -1));
+
            }
+
        }
+
        else {
+
            int len = pmatch[j].rm_eo - pmatch[j].rm_so;
+

+
            if (opt_indices) {
+
                Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp,
+
                        offset + pmatch[j].rm_so));
+
                Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp,
+
                        offset + pmatch[j].rm_so + len - 1));
+
            }
+
            else {
+
                Jim_AppendString(interp, resultObj, source_str + pmatch[j].rm_so, len);
+
            }
+
        }
+

+
        if (opt_inline) {
+
            Jim_ListAppendElement(interp, resultListObj, resultObj);
+
        }
+
        else {
+

+
            result = Jim_SetVariable(interp, argv[i], resultObj);
+

+
            if (result != JIM_OK) {
+
                Jim_FreeObj(interp, resultObj);
+
                break;
+
            }
+
        }
+
    }
+

+
  try_next_match:
+
    if (opt_all && (pattern[0] != '^' || (regcomp_flags & REG_NEWLINE)) && *source_str) {
+
        if (pmatch[0].rm_eo) {
+
            offset += pmatch[0].rm_eo;
+
            source_str += pmatch[0].rm_eo;
+
        }
+
        else {
+
            source_str++;
+
            offset++;
+
        }
+
        if (*source_str) {
+
            eflags = REG_NOTBOL;
+
            goto next_match;
+
        }
+
    }
+

+
  done:
+
    if (result == JIM_OK) {
+
        if (opt_inline) {
+
            Jim_SetResult(interp, resultListObj);
+
        }
+
        else {
+
            Jim_SetResultInt(interp, num_matches);
+
        }
+
    }
+

+
    Jim_Free(pmatch);
+
    return result;
+
}
+

+
#define MAX_SUB_MATCHES 50
+

+
int Jim_RegsubCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int regcomp_flags = 0;
+
    int regexec_flags = 0;
+
    int opt_all = 0;
+
    int offset = 0;
+
    regex_t *regex;
+
    const char *p;
+
    int result;
+
    regmatch_t pmatch[MAX_SUB_MATCHES + 1];
+
    int num_matches = 0;
+

+
    int i, j, n;
+
    Jim_Obj *varname;
+
    Jim_Obj *resultObj;
+
    const char *source_str;
+
    int source_len;
+
    const char *replace_str;
+
    int replace_len;
+
    const char *pattern;
+
    int option;
+
    enum {
+
        OPT_NOCASE, OPT_LINE, OPT_ALL, OPT_START, OPT_END
+
    };
+
    static const char * const options[] = {
+
        "-nocase", "-line", "-all", "-start", "--", NULL
+
    };
+

+
    if (argc < 4) {
+
      wrongNumArgs:
+
        Jim_WrongNumArgs(interp, 1, argv,
+
            "?-switch ...? exp string subSpec ?varName?");
+
        return JIM_ERR;
+
    }
+

+
    for (i = 1; i < argc; i++) {
+
        const char *opt = Jim_String(argv[i]);
+

+
        if (*opt != '-') {
+
            break;
+
        }
+
        if (Jim_GetEnum(interp, argv[i], options, &option, "switch", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        if (option == OPT_END) {
+
            i++;
+
            break;
+
        }
+
        switch (option) {
+
            case OPT_NOCASE:
+
                regcomp_flags |= REG_ICASE;
+
                break;
+

+
            case OPT_LINE:
+
                regcomp_flags |= REG_NEWLINE;
+
                break;
+

+
            case OPT_ALL:
+
                opt_all = 1;
+
                break;
+

+
            case OPT_START:
+
                if (++i == argc) {
+
                    goto wrongNumArgs;
+
                }
+
                if (Jim_GetIndex(interp, argv[i], &offset) != JIM_OK) {
+
                    return JIM_ERR;
+
                }
+
                break;
+
        }
+
    }
+
    if (argc - i != 3 && argc - i != 4) {
+
        goto wrongNumArgs;
+
    }
+

+
    regex = SetRegexpFromAny(interp, argv[i], regcomp_flags);
+
    if (!regex) {
+
        return JIM_ERR;
+
    }
+
    pattern = Jim_String(argv[i]);
+

+
    source_str = Jim_GetString(argv[i + 1], &source_len);
+
    replace_str = Jim_GetString(argv[i + 2], &replace_len);
+
    varname = argv[i + 3];
+

+

+
    resultObj = Jim_NewStringObj(interp, "", 0);
+

+
    if (offset) {
+
        if (offset < 0) {
+
            offset += source_len + 1;
+
        }
+
        if (offset > source_len) {
+
            offset = source_len;
+
        }
+
        else if (offset < 0) {
+
            offset = 0;
+
        }
+
    }
+

+

+
    Jim_AppendString(interp, resultObj, source_str, offset);
+

+

+
    n = source_len - offset;
+
    p = source_str + offset;
+
    do {
+
        int match = regexec(regex, p, MAX_SUB_MATCHES, pmatch, regexec_flags);
+

+
        if (match >= REG_BADPAT) {
+
            char buf[100];
+

+
            regerror(match, regex, buf, sizeof(buf));
+
            Jim_SetResultFormatted(interp, "error while matching pattern: %s", buf);
+
            return JIM_ERR;
+
        }
+
        if (match == REG_NOMATCH) {
+
            break;
+
        }
+

+
        num_matches++;
+

+
        Jim_AppendString(interp, resultObj, p, pmatch[0].rm_so);
+

+

+
        for (j = 0; j < replace_len; j++) {
+
            int idx;
+
            int c = replace_str[j];
+

+
            if (c == '&') {
+
                idx = 0;
+
            }
+
            else if (c == '\\' && j < replace_len) {
+
                c = replace_str[++j];
+
                if ((c >= '0') && (c <= '9')) {
+
                    idx = c - '0';
+
                }
+
                else if ((c == '\\') || (c == '&')) {
+
                    Jim_AppendString(interp, resultObj, replace_str + j, 1);
+
                    continue;
+
                }
+
                else {
+
                    Jim_AppendString(interp, resultObj, replace_str + j - 1, (j == replace_len) ? 1 : 2);
+
                    continue;
+
                }
+
            }
+
            else {
+
                Jim_AppendString(interp, resultObj, replace_str + j, 1);
+
                continue;
+
            }
+
            if ((idx < MAX_SUB_MATCHES) && pmatch[idx].rm_so != -1 && pmatch[idx].rm_eo != -1) {
+
                Jim_AppendString(interp, resultObj, p + pmatch[idx].rm_so,
+
                    pmatch[idx].rm_eo - pmatch[idx].rm_so);
+
            }
+
        }
+

+
        p += pmatch[0].rm_eo;
+
        n -= pmatch[0].rm_eo;
+

+

+
        if (!opt_all || n == 0) {
+
            break;
+
        }
+

+

+
        if ((regcomp_flags & REG_NEWLINE) == 0 && pattern[0] == '^') {
+
            break;
+
        }
+

+

+
        if (pattern[0] == '\0' && n) {
+

+
            Jim_AppendString(interp, resultObj, p, 1);
+
            p++;
+
            n--;
+
        }
+

+
        regexec_flags |= REG_NOTBOL;
+
    } while (n);
+

+
    Jim_AppendString(interp, resultObj, p, -1);
+

+

+
    if (argc - i == 4) {
+
        result = Jim_SetVariable(interp, varname, resultObj);
+

+
        if (result == JIM_OK) {
+
            Jim_SetResultInt(interp, num_matches);
+
        }
+
        else {
+
            Jim_FreeObj(interp, resultObj);
+
        }
+
    }
+
    else {
+
        Jim_SetResult(interp, resultObj);
+
        result = JIM_OK;
+
    }
+

+
    return result;
+
}
+

+
int Jim_regexpInit(Jim_Interp *interp)
+
{
+
    if (Jim_PackageProvide(interp, "regexp", "1.0", JIM_ERRMSG))
+
        return JIM_ERR;
+

+
    Jim_CreateCommand(interp, "regexp", Jim_RegexpCmd, NULL, NULL);
+
    Jim_CreateCommand(interp, "regsub", Jim_RegsubCmd, NULL, NULL);
+
    return JIM_OK;
+
}
+

+
#include <limits.h>
+
#include <stdlib.h>
+
#include <string.h>
+
#include <stdio.h>
+
#include <errno.h>
+
#include <sys/stat.h>
+

+

+
#ifdef HAVE_UTIMES
+
#include <sys/time.h>
+
#endif
+
#ifdef HAVE_UNISTD_H
+
#include <unistd.h>
+
#elif defined(_MSC_VER)
+
#include <direct.h>
+
#define F_OK 0
+
#define W_OK 2
+
#define R_OK 4
+
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
+
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
+
#endif
+

+
# ifndef MAXPATHLEN
+
# define MAXPATHLEN JIM_PATH_LEN
+
# endif
+

+
#if defined(__MINGW32__) || defined(_MSC_VER)
+
#define ISWINDOWS 1
+
#else
+
#define ISWINDOWS 0
+
#endif
+

+

+
static const char *JimGetFileType(int mode)
+
{
+
    if (S_ISREG(mode)) {
+
        return "file";
+
    }
+
    else if (S_ISDIR(mode)) {
+
        return "directory";
+
    }
+
#ifdef S_ISCHR
+
    else if (S_ISCHR(mode)) {
+
        return "characterSpecial";
+
    }
+
#endif
+
#ifdef S_ISBLK
+
    else if (S_ISBLK(mode)) {
+
        return "blockSpecial";
+
    }
+
#endif
+
#ifdef S_ISFIFO
+
    else if (S_ISFIFO(mode)) {
+
        return "fifo";
+
    }
+
#endif
+
#ifdef S_ISLNK
+
    else if (S_ISLNK(mode)) {
+
        return "link";
+
    }
+
#endif
+
#ifdef S_ISSOCK
+
    else if (S_ISSOCK(mode)) {
+
        return "socket";
+
    }
+
#endif
+
    return "unknown";
+
}
+

+
static void AppendStatElement(Jim_Interp *interp, Jim_Obj *listObj, const char *key, jim_wide value)
+
{
+
    Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, key, -1));
+
    Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, value));
+
}
+

+
static int StoreStatData(Jim_Interp *interp, Jim_Obj *varName, const struct stat *sb)
+
{
+

+
    Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
+

+
    AppendStatElement(interp, listObj, "dev", sb->st_dev);
+
    AppendStatElement(interp, listObj, "ino", sb->st_ino);
+
    AppendStatElement(interp, listObj, "mode", sb->st_mode);
+
    AppendStatElement(interp, listObj, "nlink", sb->st_nlink);
+
    AppendStatElement(interp, listObj, "uid", sb->st_uid);
+
    AppendStatElement(interp, listObj, "gid", sb->st_gid);
+
    AppendStatElement(interp, listObj, "size", sb->st_size);
+
    AppendStatElement(interp, listObj, "atime", sb->st_atime);
+
    AppendStatElement(interp, listObj, "mtime", sb->st_mtime);
+
    AppendStatElement(interp, listObj, "ctime", sb->st_ctime);
+
    Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "type", -1));
+
    Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, JimGetFileType((int)sb->st_mode), -1));
+

+

+
    if (varName) {
+
        Jim_Obj *objPtr;
+
        objPtr = Jim_GetVariable(interp, varName, JIM_NONE);
+

+
        if (objPtr) {
+
            Jim_Obj *objv[2];
+

+
            objv[0] = objPtr;
+
            objv[1] = listObj;
+

+
            objPtr = Jim_DictMerge(interp, 2, objv);
+
            if (objPtr == NULL) {
+

+
                Jim_SetResultFormatted(interp, "can't set \"%#s(dev)\": variable isn't array", varName);
+
                Jim_FreeNewObj(interp, listObj);
+
                return JIM_ERR;
+
            }
+

+
            Jim_InvalidateStringRep(objPtr);
+

+
            Jim_FreeNewObj(interp, listObj);
+
            listObj = objPtr;
+
        }
+
        Jim_SetVariable(interp, varName, listObj);
+
    }
+

+

+
    Jim_SetResult(interp, listObj);
+

+
    return JIM_OK;
+
}
+

+
static int file_cmd_dirname(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *path = Jim_String(argv[0]);
+
    const char *p = strrchr(path, '/');
+

+
    if (!p && path[0] == '.' && path[1] == '.' && path[2] == '\0') {
+
        Jim_SetResultString(interp, "..", -1);
+
    } else if (!p) {
+
        Jim_SetResultString(interp, ".", -1);
+
    }
+
    else if (p == path) {
+
        Jim_SetResultString(interp, "/", -1);
+
    }
+
    else if (ISWINDOWS && p[-1] == ':') {
+

+
        Jim_SetResultString(interp, path, p - path + 1);
+
    }
+
    else {
+
        Jim_SetResultString(interp, path, p - path);
+
    }
+
    return JIM_OK;
+
}
+

+
static int file_cmd_rootname(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *path = Jim_String(argv[0]);
+
    const char *lastSlash = strrchr(path, '/');
+
    const char *p = strrchr(path, '.');
+

+
    if (p == NULL || (lastSlash != NULL && lastSlash > p)) {
+
        Jim_SetResult(interp, argv[0]);
+
    }
+
    else {
+
        Jim_SetResultString(interp, path, p - path);
+
    }
+
    return JIM_OK;
+
}
+

+
static int file_cmd_extension(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *path = Jim_String(argv[0]);
+
    const char *lastSlash = strrchr(path, '/');
+
    const char *p = strrchr(path, '.');
+

+
    if (p == NULL || (lastSlash != NULL && lastSlash >= p)) {
+
        p = "";
+
    }
+
    Jim_SetResultString(interp, p, -1);
+
    return JIM_OK;
+
}
+

+
static int file_cmd_tail(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *path = Jim_String(argv[0]);
+
    const char *lastSlash = strrchr(path, '/');
+

+
    if (lastSlash) {
+
        Jim_SetResultString(interp, lastSlash + 1, -1);
+
    }
+
    else {
+
        Jim_SetResult(interp, argv[0]);
+
    }
+
    return JIM_OK;
+
}
+

+
static int file_cmd_normalize(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
#ifdef HAVE_REALPATH
+
    const char *path = Jim_String(argv[0]);
+
    char *newname = Jim_Alloc(MAXPATHLEN + 1);
+

+
    if (realpath(path, newname)) {
+
        Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, newname, -1));
+
        return JIM_OK;
+
    }
+
    else {
+
        Jim_Free(newname);
+
        Jim_SetResultFormatted(interp, "can't normalize \"%#s\": %s", argv[0], strerror(errno));
+
        return JIM_ERR;
+
    }
+
#else
+
    Jim_SetResultString(interp, "Not implemented", -1);
+
    return JIM_ERR;
+
#endif
+
}
+

+
static int file_cmd_join(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int i;
+
    char *newname = Jim_Alloc(MAXPATHLEN + 1);
+
    char *last = newname;
+

+
    *newname = 0;
+

+

+
    for (i = 0; i < argc; i++) {
+
        int len;
+
        const char *part = Jim_GetString(argv[i], &len);
+

+
        if (*part == '/') {
+

+
            last = newname;
+
        }
+
        else if (ISWINDOWS && strchr(part, ':')) {
+

+
            last = newname;
+
        }
+
        else if (part[0] == '.') {
+
            if (part[1] == '/') {
+
                part += 2;
+
                len -= 2;
+
            }
+
            else if (part[1] == 0 && last != newname) {
+

+
                continue;
+
            }
+
        }
+

+

+
        if (last != newname && last[-1] != '/') {
+
            *last++ = '/';
+
        }
+

+
        if (len) {
+
            if (last + len - newname >= MAXPATHLEN) {
+
                Jim_Free(newname);
+
                Jim_SetResultString(interp, "Path too long", -1);
+
                return JIM_ERR;
+
            }
+
            memcpy(last, part, len);
+
            last += len;
+
        }
+

+

+
        if (last > newname + 1 && last[-1] == '/') {
+

+
            if (!ISWINDOWS || !(last > newname + 2 && last[-2] == ':')) {
+
                *--last = 0;
+
            }
+
        }
+
    }
+

+
    *last = 0;
+

+

+

+
    Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, newname, last - newname));
+

+
    return JIM_OK;
+
}
+

+
static int file_access(Jim_Interp *interp, Jim_Obj *filename, int mode)
+
{
+
    Jim_SetResultBool(interp, access(Jim_String(filename), mode) != -1);
+

+
    return JIM_OK;
+
}
+

+
static int file_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return file_access(interp, argv[0], R_OK);
+
}
+

+
static int file_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return file_access(interp, argv[0], W_OK);
+
}
+

+
static int file_cmd_executable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
#ifdef X_OK
+
    return file_access(interp, argv[0], X_OK);
+
#else
+

+
    Jim_SetResultBool(interp, 1);
+
    return JIM_OK;
+
#endif
+
}
+

+
static int file_cmd_exists(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return file_access(interp, argv[0], F_OK);
+
}
+

+
static int file_cmd_delete(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int force = Jim_CompareStringImmediate(interp, argv[0], "-force");
+

+
    if (force || Jim_CompareStringImmediate(interp, argv[0], "--")) {
+
        argc++;
+
        argv--;
+
    }
+

+
    while (argc--) {
+
        const char *path = Jim_String(argv[0]);
+

+
        if (unlink(path) == -1 && errno != ENOENT) {
+
            if (rmdir(path) == -1) {
+

+
                if (!force || Jim_EvalPrefix(interp, "file delete force", 1, argv) != JIM_OK) {
+
                    Jim_SetResultFormatted(interp, "couldn't delete file \"%s\": %s", path,
+
                        strerror(errno));
+
                    return JIM_ERR;
+
                }
+
            }
+
        }
+
        argv++;
+
    }
+
    return JIM_OK;
+
}
+

+
#ifdef HAVE_MKDIR_ONE_ARG
+
#define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
+
#else
+
#define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
+
#endif
+

+
static int mkdir_all(char *path)
+
{
+
    int ok = 1;
+

+

+
    goto first;
+

+
    while (ok--) {
+

+
        {
+
            char *slash = strrchr(path, '/');
+

+
            if (slash && slash != path) {
+
                *slash = 0;
+
                if (mkdir_all(path) != 0) {
+
                    return -1;
+
                }
+
                *slash = '/';
+
            }
+
        }
+
      first:
+
        if (MKDIR_DEFAULT(path) == 0) {
+
            return 0;
+
        }
+
        if (errno == ENOENT) {
+

+
            continue;
+
        }
+

+
        if (errno == EEXIST) {
+
            struct stat sb;
+

+
            if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
+
                return 0;
+
            }
+

+
            errno = EEXIST;
+
        }
+

+
        break;
+
    }
+
    return -1;
+
}
+

+
static int file_cmd_mkdir(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    while (argc--) {
+
        char *path = Jim_StrDup(Jim_String(argv[0]));
+
        int rc = mkdir_all(path);
+

+
        Jim_Free(path);
+
        if (rc != 0) {
+
            Jim_SetResultFormatted(interp, "can't create directory \"%#s\": %s", argv[0],
+
                strerror(errno));
+
            return JIM_ERR;
+
        }
+
        argv++;
+
    }
+
    return JIM_OK;
+
}
+

+
static int file_cmd_tempfile(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int fd = Jim_MakeTempFile(interp, (argc >= 1) ? Jim_String(argv[0]) : NULL);
+

+
    if (fd < 0) {
+
        return JIM_ERR;
+
    }
+
    close(fd);
+

+
    return JIM_OK;
+
}
+

+
static int file_cmd_rename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *source;
+
    const char *dest;
+
    int force = 0;
+

+
    if (argc == 3) {
+
        if (!Jim_CompareStringImmediate(interp, argv[0], "-force")) {
+
            return -1;
+
        }
+
        force++;
+
        argv++;
+
        argc--;
+
    }
+

+
    source = Jim_String(argv[0]);
+
    dest = Jim_String(argv[1]);
+

+
    if (!force && access(dest, F_OK) == 0) {
+
        Jim_SetResultFormatted(interp, "error renaming \"%#s\" to \"%#s\": target exists", argv[0],
+
            argv[1]);
+
        return JIM_ERR;
+
    }
+

+
    if (rename(source, dest) != 0) {
+
        Jim_SetResultFormatted(interp, "error renaming \"%#s\" to \"%#s\": %s", argv[0], argv[1],
+
            strerror(errno));
+
        return JIM_ERR;
+
    }
+

+
    return JIM_OK;
+
}
+

+
#if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
+
static int file_cmd_link(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int ret;
+
    const char *source;
+
    const char *dest;
+
    static const char * const options[] = { "-hard", "-symbolic", NULL };
+
    enum { OPT_HARD, OPT_SYMBOLIC, };
+
    int option = OPT_HARD;
+

+
    if (argc == 3) {
+
        if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ENUM_ABBREV | JIM_ERRMSG) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        argv++;
+
        argc--;
+
    }
+

+
    dest = Jim_String(argv[0]);
+
    source = Jim_String(argv[1]);
+

+
    if (option == OPT_HARD) {
+
        ret = link(source, dest);
+
    }
+
    else {
+
        ret = symlink(source, dest);
+
    }
+

+
    if (ret != 0) {
+
        Jim_SetResultFormatted(interp, "error linking \"%#s\" to \"%#s\": %s", argv[0], argv[1],
+
            strerror(errno));
+
        return JIM_ERR;
+
    }
+

+
    return JIM_OK;
+
}
+
#endif
+

+
static int file_stat(Jim_Interp *interp, Jim_Obj *filename, struct stat *sb)
+
{
+
    const char *path = Jim_String(filename);
+

+
    if (stat(path, sb) == -1) {
+
        Jim_SetResultFormatted(interp, "could not read \"%#s\": %s", filename, strerror(errno));
+
        return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+
#ifdef HAVE_LSTAT
+
static int file_lstat(Jim_Interp *interp, Jim_Obj *filename, struct stat *sb)
+
{
+
    const char *path = Jim_String(filename);
+

+
    if (lstat(path, sb) == -1) {
+
        Jim_SetResultFormatted(interp, "could not read \"%#s\": %s", filename, strerror(errno));
+
        return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+
#else
+
#define file_lstat file_stat
+
#endif
+

+
static int file_cmd_atime(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+

+
    if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    Jim_SetResultInt(interp, sb.st_atime);
+
    return JIM_OK;
+
}
+

+
static int file_cmd_mtime(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+

+
    if (argc == 2) {
+
#ifdef HAVE_UTIMES
+
        jim_wide newtime;
+
        struct timeval times[2];
+

+
        if (Jim_GetWide(interp, argv[1], &newtime) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+

+
        times[1].tv_sec = times[0].tv_sec = newtime;
+
        times[1].tv_usec = times[0].tv_usec = 0;
+

+
        if (utimes(Jim_String(argv[0]), times) != 0) {
+
            Jim_SetResultFormatted(interp, "can't set time on \"%#s\": %s", argv[0], strerror(errno));
+
            return JIM_ERR;
+
        }
+
#else
+
        Jim_SetResultString(interp, "Not implemented", -1);
+
        return JIM_ERR;
+
#endif
+
    }
+
    if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    Jim_SetResultInt(interp, sb.st_mtime);
+
    return JIM_OK;
+
}
+

+
static int file_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return Jim_EvalPrefix(interp, "file copy", argc, argv);
+
}
+

+
static int file_cmd_size(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+

+
    if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    Jim_SetResultInt(interp, sb.st_size);
+
    return JIM_OK;
+
}
+

+
static int file_cmd_isdirectory(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+
    int ret = 0;
+

+
    if (file_stat(interp, argv[0], &sb) == JIM_OK) {
+
        ret = S_ISDIR(sb.st_mode);
+
    }
+
    Jim_SetResultInt(interp, ret);
+
    return JIM_OK;
+
}
+

+
static int file_cmd_isfile(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+
    int ret = 0;
+

+
    if (file_stat(interp, argv[0], &sb) == JIM_OK) {
+
        ret = S_ISREG(sb.st_mode);
+
    }
+
    Jim_SetResultInt(interp, ret);
+
    return JIM_OK;
+
}
+

+
#ifdef HAVE_GETEUID
+
static int file_cmd_owned(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+
    int ret = 0;
+

+
    if (file_stat(interp, argv[0], &sb) == JIM_OK) {
+
        ret = (geteuid() == sb.st_uid);
+
    }
+
    Jim_SetResultInt(interp, ret);
+
    return JIM_OK;
+
}
+
#endif
+

+
#if defined(HAVE_READLINK)
+
static int file_cmd_readlink(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *path = Jim_String(argv[0]);
+
    char *linkValue = Jim_Alloc(MAXPATHLEN + 1);
+

+
    int linkLength = readlink(path, linkValue, MAXPATHLEN);
+

+
    if (linkLength == -1) {
+
        Jim_Free(linkValue);
+
        Jim_SetResultFormatted(interp, "couldn't readlink \"%#s\": %s", argv[0], strerror(errno));
+
        return JIM_ERR;
+
    }
+
    linkValue[linkLength] = 0;
+
    Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, linkValue, linkLength));
+
    return JIM_OK;
+
}
+
#endif
+

+
static int file_cmd_type(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+

+
    if (file_lstat(interp, argv[0], &sb) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    Jim_SetResultString(interp, JimGetFileType((int)sb.st_mode), -1);
+
    return JIM_OK;
+
}
+

+
#ifdef HAVE_LSTAT
+
static int file_cmd_lstat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+

+
    if (file_lstat(interp, argv[0], &sb) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    return StoreStatData(interp, argc == 2 ? argv[1] : NULL, &sb);
+
}
+
#else
+
#define file_cmd_lstat file_cmd_stat
+
#endif
+

+
static int file_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct stat sb;
+

+
    if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    return StoreStatData(interp, argc == 2 ? argv[1] : NULL, &sb);
+
}
+

+
static const jim_subcmd_type file_command_table[] = {
+
    {   "atime",
+
        "name",
+
        file_cmd_atime,
+
        1,
+
        1,
+

+
    },
+
    {   "mtime",
+
        "name ?time?",
+
        file_cmd_mtime,
+
        1,
+
        2,
+

+
    },
+
    {   "copy",
+
        "?-force? source dest",
+
        file_cmd_copy,
+
        2,
+
        3,
+

+
    },
+
    {   "dirname",
+
        "name",
+
        file_cmd_dirname,
+
        1,
+
        1,
+

+
    },
+
    {   "rootname",
+
        "name",
+
        file_cmd_rootname,
+
        1,
+
        1,
+

+
    },
+
    {   "extension",
+
        "name",
+
        file_cmd_extension,
+
        1,
+
        1,
+

+
    },
+
    {   "tail",
+
        "name",
+
        file_cmd_tail,
+
        1,
+
        1,
+

+
    },
+
    {   "normalize",
+
        "name",
+
        file_cmd_normalize,
+
        1,
+
        1,
+

+
    },
+
    {   "join",
+
        "name ?name ...?",
+
        file_cmd_join,
+
        1,
+
        -1,
+

+
    },
+
    {   "readable",
+
        "name",
+
        file_cmd_readable,
+
        1,
+
        1,
+

+
    },
+
    {   "writable",
+
        "name",
+
        file_cmd_writable,
+
        1,
+
        1,
+

+
    },
+
    {   "executable",
+
        "name",
+
        file_cmd_executable,
+
        1,
+
        1,
+

+
    },
+
    {   "exists",
+
        "name",
+
        file_cmd_exists,
+
        1,
+
        1,
+

+
    },
+
    {   "delete",
+
        "?-force|--? name ...",
+
        file_cmd_delete,
+
        1,
+
        -1,
+

+
    },
+
    {   "mkdir",
+
        "dir ...",
+
        file_cmd_mkdir,
+
        1,
+
        -1,
+

+
    },
+
    {   "tempfile",
+
        "?template?",
+
        file_cmd_tempfile,
+
        0,
+
        1,
+

+
    },
+
    {   "rename",
+
        "?-force? source dest",
+
        file_cmd_rename,
+
        2,
+
        3,
+

+
    },
+
#if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
+
    {   "link",
+
        "?-symbolic|-hard? newname target",
+
        file_cmd_link,
+
        2,
+
        3,
+

+
    },
+
#endif
+
#if defined(HAVE_READLINK)
+
    {   "readlink",
+
        "name",
+
        file_cmd_readlink,
+
        1,
+
        1,
+

+
    },
+
#endif
+
    {   "size",
+
        "name",
+
        file_cmd_size,
+
        1,
+
        1,
+

+
    },
+
    {   "stat",
+
        "name ?var?",
+
        file_cmd_stat,
+
        1,
+
        2,
+

+
    },
+
    {   "lstat",
+
        "name ?var?",
+
        file_cmd_lstat,
+
        1,
+
        2,
+

+
    },
+
    {   "type",
+
        "name",
+
        file_cmd_type,
+
        1,
+
        1,
+

+
    },
+
#ifdef HAVE_GETEUID
+
    {   "owned",
+
        "name",
+
        file_cmd_owned,
+
        1,
+
        1,
+

+
    },
+
#endif
+
    {   "isdirectory",
+
        "name",
+
        file_cmd_isdirectory,
+
        1,
+
        1,
+

+
    },
+
    {   "isfile",
+
        "name",
+
        file_cmd_isfile,
+
        1,
+
        1,
+

+
    },
+
    {
+
        NULL
+
    }
+
};
+

+
static int Jim_CdCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *path;
+

+
    if (argc != 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "dirname");
+
        return JIM_ERR;
+
    }
+

+
    path = Jim_String(argv[1]);
+

+
    if (chdir(path) != 0) {
+
        Jim_SetResultFormatted(interp, "couldn't change working directory to \"%s\": %s", path,
+
            strerror(errno));
+
        return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+
static int Jim_PwdCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    char *cwd = Jim_Alloc(MAXPATHLEN);
+

+
    if (getcwd(cwd, MAXPATHLEN) == NULL) {
+
        Jim_SetResultString(interp, "Failed to get pwd", -1);
+
        Jim_Free(cwd);
+
        return JIM_ERR;
+
    }
+
    else if (ISWINDOWS) {
+

+
        char *p = cwd;
+
        while ((p = strchr(p, '\\')) != NULL) {
+
            *p++ = '/';
+
        }
+
    }
+

+
    Jim_SetResultString(interp, cwd, -1);
+

+
    Jim_Free(cwd);
+
    return JIM_OK;
+
}
+

+
int Jim_fileInit(Jim_Interp *interp)
+
{
+
    if (Jim_PackageProvide(interp, "file", "1.0", JIM_ERRMSG))
+
        return JIM_ERR;
+

+
    Jim_CreateCommand(interp, "file", Jim_SubCmdProc, (void *)file_command_table, NULL);
+
    Jim_CreateCommand(interp, "pwd", Jim_PwdCmd, NULL, NULL);
+
    Jim_CreateCommand(interp, "cd", Jim_CdCmd, NULL, NULL);
+
    return JIM_OK;
+
}
+

+
#ifndef _GNU_SOURCE
+
#define _GNU_SOURCE
+
#endif
+
#include <string.h>
+
#include <ctype.h>
+

+

+
#if (!defined(HAVE_VFORK) || !defined(HAVE_WAITPID)) && !defined(__MINGW32__)
+
static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *cmdlineObj = Jim_NewEmptyStringObj(interp);
+
    int i, j;
+
    int rc;
+

+

+
    for (i = 1; i < argc; i++) {
+
        int len;
+
        const char *arg = Jim_GetString(argv[i], &len);
+

+
        if (i > 1) {
+
            Jim_AppendString(interp, cmdlineObj, " ", 1);
+
        }
+
        if (strpbrk(arg, "\\\" ") == NULL) {
+

+
            Jim_AppendString(interp, cmdlineObj, arg, len);
+
            continue;
+
        }
+

+
        Jim_AppendString(interp, cmdlineObj, "\"", 1);
+
        for (j = 0; j < len; j++) {
+
            if (arg[j] == '\\' || arg[j] == '"') {
+
                Jim_AppendString(interp, cmdlineObj, "\\", 1);
+
            }
+
            Jim_AppendString(interp, cmdlineObj, &arg[j], 1);
+
        }
+
        Jim_AppendString(interp, cmdlineObj, "\"", 1);
+
    }
+
    rc = system(Jim_String(cmdlineObj));
+

+
    Jim_FreeNewObj(interp, cmdlineObj);
+

+
    if (rc) {
+
        Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
+
        Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
+
        Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, 0));
+
        Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, rc));
+
        Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
+
        return JIM_ERR;
+
    }
+

+
    return JIM_OK;
+
}
+

+
int Jim_execInit(Jim_Interp *interp)
+
{
+
    if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
+
        return JIM_ERR;
+

+
    Jim_CreateCommand(interp, "exec", Jim_ExecCmd, NULL, NULL);
+
    return JIM_OK;
+
}
+
#else
+

+

+
#include <errno.h>
+
#include <signal.h>
+

+
#if defined(__MINGW32__)
+

+
    #ifndef STRICT
+
    #define STRICT
+
    #endif
+
    #define WIN32_LEAN_AND_MEAN
+
    #include <windows.h>
+
    #include <fcntl.h>
+

+
    typedef HANDLE fdtype;
+
    typedef HANDLE pidtype;
+
    #define JIM_BAD_FD INVALID_HANDLE_VALUE
+
    #define JIM_BAD_PID INVALID_HANDLE_VALUE
+
    #define JimCloseFd CloseHandle
+

+
    #define WIFEXITED(STATUS) 1
+
    #define WEXITSTATUS(STATUS) (STATUS)
+
    #define WIFSIGNALED(STATUS) 0
+
    #define WTERMSIG(STATUS) 0
+
    #define WNOHANG 1
+

+
    static fdtype JimFileno(FILE *fh);
+
    static pidtype JimWaitPid(pidtype pid, int *status, int nohang);
+
    static fdtype JimDupFd(fdtype infd);
+
    static fdtype JimOpenForRead(const char *filename);
+
    static FILE *JimFdOpenForRead(fdtype fd);
+
    static int JimPipe(fdtype pipefd[2]);
+
    static pidtype JimStartWinProcess(Jim_Interp *interp, char **argv, char **env,
+
        fdtype inputId, fdtype outputId, fdtype errorId);
+
    static int JimErrno(void);
+
#else
+
    #include <unistd.h>
+
    #include <fcntl.h>
+
    #include <sys/wait.h>
+
    #include <sys/stat.h>
+

+
    typedef int fdtype;
+
    typedef int pidtype;
+
    #define JimPipe pipe
+
    #define JimErrno() errno
+
    #define JIM_BAD_FD -1
+
    #define JIM_BAD_PID -1
+
    #define JimFileno fileno
+
    #define JimReadFd read
+
    #define JimCloseFd close
+
    #define JimWaitPid waitpid
+
    #define JimDupFd dup
+
    #define JimFdOpenForRead(FD) fdopen((FD), "r")
+
    #define JimOpenForRead(NAME) open((NAME), O_RDONLY, 0)
+

+
    #ifndef HAVE_EXECVPE
+
        #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
+
    #endif
+
#endif
+

+
static const char *JimStrError(void);
+
static char **JimOriginalEnviron(void);
+
static char **JimSaveEnv(char **env);
+
static void JimRestoreEnv(char **env);
+
static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
+
    pidtype **pidArrayPtr, fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr);
+
static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr);
+
static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, Jim_Obj *errStrObj);
+
static fdtype JimCreateTemp(Jim_Interp *interp, const char *contents, int len);
+
static fdtype JimOpenForWrite(const char *filename, int append);
+
static int JimRewindFd(fdtype fd);
+

+
static void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
+
{
+
    Jim_SetResultFormatted(interp, "%s: %s", msg, JimStrError());
+
}
+

+
static const char *JimStrError(void)
+
{
+
    return strerror(JimErrno());
+
}
+

+
static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
+
{
+
    int len;
+
    const char *s = Jim_GetString(objPtr, &len);
+

+
    if (len > 0 && s[len - 1] == '\n') {
+
        objPtr->length--;
+
        objPtr->bytes[objPtr->length] = '\0';
+
    }
+
}
+

+
static int JimAppendStreamToString(Jim_Interp *interp, fdtype fd, Jim_Obj *strObj)
+
{
+
    char buf[256];
+
    FILE *fh = JimFdOpenForRead(fd);
+
    int ret = 0;
+

+
    if (fh == NULL) {
+
        return -1;
+
    }
+

+
    while (1) {
+
        int retval = fread(buf, 1, sizeof(buf), fh);
+
        if (retval > 0) {
+
            ret = 1;
+
            Jim_AppendString(interp, strObj, buf, retval);
+
        }
+
        if (retval != sizeof(buf)) {
+
            break;
+
        }
+
    }
+
    fclose(fh);
+
    return ret;
+
}
+

+
static char **JimBuildEnv(Jim_Interp *interp)
+
{
+
    int i;
+
    int size;
+
    int num;
+
    int n;
+
    char **envptr;
+
    char *envdata;
+

+
    Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
+

+
    if (!objPtr) {
+
        return JimOriginalEnviron();
+
    }
+

+

+

+
    num = Jim_ListLength(interp, objPtr);
+
    if (num % 2) {
+

+
        num--;
+
    }
+
    size = Jim_Length(objPtr) + 2;
+

+
    envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
+
    envdata = (char *)&envptr[num / 2 + 1];
+

+
    n = 0;
+
    for (i = 0; i < num; i += 2) {
+
        const char *s1, *s2;
+
        Jim_Obj *elemObj;
+

+
        Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
+
        s1 = Jim_String(elemObj);
+
        Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
+
        s2 = Jim_String(elemObj);
+

+
        envptr[n] = envdata;
+
        envdata += sprintf(envdata, "%s=%s", s1, s2);
+
        envdata++;
+
        n++;
+
    }
+
    envptr[n] = NULL;
+
    *envdata = 0;
+

+
    return envptr;
+
}
+

+
static void JimFreeEnv(char **env, char **original_environ)
+
{
+
    if (env != original_environ) {
+
        Jim_Free(env);
+
    }
+
}
+

+
#ifndef jim_ext_signal
+

+
const char *Jim_SignalId(int sig)
+
{
+
    static char buf[10];
+
    snprintf(buf, sizeof(buf), "%d", sig);
+
    return buf;
+
}
+

+
const char *Jim_SignalName(int sig)
+
{
+
    return Jim_SignalId(sig);
+
}
+
#endif
+

+
static int JimCheckWaitStatus(Jim_Interp *interp, pidtype pid, int waitStatus, Jim_Obj *errStrObj)
+
{
+
    Jim_Obj *errorCode;
+

+
    if (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus) == 0) {
+
        return JIM_OK;
+
    }
+
    errorCode = Jim_NewListObj(interp, NULL, 0);
+

+
    if (WIFEXITED(waitStatus)) {
+
        Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
+
        Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
+
        Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
+
    }
+
    else {
+
        const char *type;
+
        const char *action;
+

+
        if (WIFSIGNALED(waitStatus)) {
+
            type = "CHILDKILLED";
+
            action = "killed";
+
        }
+
        else {
+
            type = "CHILDSUSP";
+
            action = "suspended";
+
        }
+

+
        Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
+

+
        if (errStrObj) {
+
            Jim_AppendStrings(interp, errStrObj, "child ", action, " by signal ", Jim_SignalId(WTERMSIG(waitStatus)), "\n", NULL);
+
        }
+

+
        Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
+
        Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalId(WTERMSIG(waitStatus)), -1));
+
        Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, Jim_SignalName(WTERMSIG(waitStatus)), -1));
+
    }
+
    Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
+

+
    return JIM_ERR;
+
}
+

+

+
struct WaitInfo
+
{
+
    pidtype pid;
+
    int status;
+
    int flags;
+
};
+

+
struct WaitInfoTable {
+
    struct WaitInfo *info;
+
    int size;
+
    int used;
+
};
+

+

+
#define WI_DETACHED 2
+

+
#define WAIT_TABLE_GROW_BY 4
+

+
static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
+
{
+
    struct WaitInfoTable *table = privData;
+

+
    Jim_Free(table->info);
+
    Jim_Free(table);
+
}
+

+
static struct WaitInfoTable *JimAllocWaitInfoTable(void)
+
{
+
    struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
+
    table->info = NULL;
+
    table->size = table->used = 0;
+

+
    return table;
+
}
+

+
static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    fdtype outputId;
+
    fdtype errorId;
+
    pidtype *pidPtr;
+
    int numPids, result;
+
    int child_siginfo = 1;
+
    Jim_Obj *childErrObj;
+
    Jim_Obj *errStrObj;
+

+
    if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
+
        Jim_Obj *listObj;
+
        int i;
+

+
        argc--;
+
        numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
+
        if (numPids < 0) {
+
            return JIM_ERR;
+
        }
+

+
        listObj = Jim_NewListObj(interp, NULL, 0);
+
        for (i = 0; i < numPids; i++) {
+
            Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, (long)pidPtr[i]));
+
        }
+
        Jim_SetResult(interp, listObj);
+
        JimDetachPids(interp, numPids, pidPtr);
+
        Jim_Free(pidPtr);
+
        return JIM_OK;
+
    }
+

+
    numPids =
+
        JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
+

+
    if (numPids < 0) {
+
        return JIM_ERR;
+
    }
+

+
    result = JIM_OK;
+

+
    errStrObj = Jim_NewStringObj(interp, "", 0);
+

+

+
    if (outputId != JIM_BAD_FD) {
+
        if (JimAppendStreamToString(interp, outputId, errStrObj) < 0) {
+
            result = JIM_ERR;
+
            Jim_SetResultErrno(interp, "error reading from output pipe");
+
        }
+
    }
+

+

+
    childErrObj = Jim_NewStringObj(interp, "", 0);
+
    Jim_IncrRefCount(childErrObj);
+

+
    if (JimCleanupChildren(interp, numPids, pidPtr, childErrObj) != JIM_OK) {
+
        result = JIM_ERR;
+
    }
+

+
    if (errorId != JIM_BAD_FD) {
+
        int ret;
+
        JimRewindFd(errorId);
+
        ret = JimAppendStreamToString(interp, errorId, errStrObj);
+
        if (ret < 0) {
+
            Jim_SetResultErrno(interp, "error reading from error pipe");
+
            result = JIM_ERR;
+
        }
+
        else if (ret > 0) {
+

+
            child_siginfo = 0;
+
        }
+
    }
+

+
    if (child_siginfo) {
+

+
        Jim_AppendObj(interp, errStrObj, childErrObj);
+
    }
+
    Jim_DecrRefCount(interp, childErrObj);
+

+

+
    Jim_RemoveTrailingNewline(errStrObj);
+

+

+
    Jim_SetResult(interp, errStrObj);
+

+
    return result;
+
}
+

+
static void JimReapDetachedPids(struct WaitInfoTable *table)
+
{
+
    struct WaitInfo *waitPtr;
+
    int count;
+
    int dest;
+

+
    if (!table) {
+
        return;
+
    }
+

+
    waitPtr = table->info;
+
    dest = 0;
+
    for (count = table->used; count > 0; waitPtr++, count--) {
+
        if (waitPtr->flags & WI_DETACHED) {
+
            int status;
+
            pidtype pid = JimWaitPid(waitPtr->pid, &status, WNOHANG);
+
            if (pid == waitPtr->pid) {
+

+
                table->used--;
+
                continue;
+
            }
+
        }
+
        if (waitPtr != &table->info[dest]) {
+
            table->info[dest] = *waitPtr;
+
        }
+
        dest++;
+
    }
+
}
+

+
static pidtype JimWaitForProcess(struct WaitInfoTable *table, pidtype pid, int *statusPtr)
+
{
+
    int i;
+

+

+
    for (i = 0; i < table->used; i++) {
+
        if (pid == table->info[i].pid) {
+

+
            JimWaitPid(pid, statusPtr, 0);
+

+

+
            if (i != table->used - 1) {
+
                table->info[i] = table->info[table->used - 1];
+
            }
+
            table->used--;
+
            return pid;
+
        }
+
    }
+

+

+
    return JIM_BAD_PID;
+
}
+

+
static void JimDetachPids(Jim_Interp *interp, int numPids, const pidtype *pidPtr)
+
{
+
    int j;
+
    struct WaitInfoTable *table = Jim_CmdPrivData(interp);
+

+
    for (j = 0; j < numPids; j++) {
+

+
        int i;
+
        for (i = 0; i < table->used; i++) {
+
            if (pidPtr[j] == table->info[i].pid) {
+
                table->info[i].flags |= WI_DETACHED;
+
                break;
+
            }
+
        }
+
    }
+
}
+

+
static FILE *JimGetAioFilehandle(Jim_Interp *interp, const char *name)
+
{
+
    FILE *fh;
+
    Jim_Obj *fhObj;
+

+
    fhObj = Jim_NewStringObj(interp, name, -1);
+
    Jim_IncrRefCount(fhObj);
+
    fh = Jim_AioFilehandle(interp, fhObj);
+
    Jim_DecrRefCount(interp, fhObj);
+

+
    return fh;
+
}
+

+
static int
+
JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, pidtype **pidArrayPtr,
+
    fdtype *inPipePtr, fdtype *outPipePtr, fdtype *errFilePtr)
+
{
+
    pidtype *pidPtr = NULL;         /* Points to malloc-ed array holding all
+
                                 * the pids of child processes. */
+
    int numPids = 0;            /* Actual number of processes that exist
+
                                 * at *pidPtr right now. */
+
    int cmdCount;               /* Count of number of distinct commands
+
                                 * found in argc/argv. */
+
    const char *input = NULL;   /* Describes input for pipeline, depending
+
                                 * on "inputFile".  NULL means take input
+
                                 * from stdin/pipe. */
+
    int input_len = 0;
+

+
#define FILE_NAME   0
+
#define FILE_APPEND 1
+
#define FILE_HANDLE 2
+
#define FILE_TEXT   3
+

+
    int inputFile = FILE_NAME;  /* 1 means input is name of input file.
+
                                 * 2 means input is filehandle name.
+
                                 * 0 means input holds actual
+
                                 * text to be input to command. */
+

+
    int outputFile = FILE_NAME; /* 0 means output is the name of output file.
+
                                 * 1 means output is the name of output file, and append.
+
                                 * 2 means output is filehandle name.
+
                                 * All this is ignored if output is NULL
+
                                 */
+
    int errorFile = FILE_NAME;  /* 0 means error is the name of error file.
+
                                 * 1 means error is the name of error file, and append.
+
                                 * 2 means error is filehandle name.
+
                                 * All this is ignored if error is NULL
+
                                 */
+
    const char *output = NULL;  /* Holds name of output file to pipe to,
+
                                 * or NULL if output goes to stdout/pipe. */
+
    const char *error = NULL;   /* Holds name of stderr file to pipe to,
+
                                 * or NULL if stderr goes to stderr/pipe. */
+
    fdtype inputId = JIM_BAD_FD;
+
    fdtype outputId = JIM_BAD_FD;
+
    fdtype errorId = JIM_BAD_FD;
+
    fdtype lastOutputId = JIM_BAD_FD;
+
    fdtype pipeIds[2];
+
    int firstArg, lastArg;      /* Indexes of first and last arguments in
+
                                 * current command. */
+
    int lastBar;
+
    int i;
+
    pidtype pid;
+
    char **save_environ;
+
    struct WaitInfoTable *table = Jim_CmdPrivData(interp);
+

+

+
    char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
+
    int arg_count = 0;
+

+
    JimReapDetachedPids(table);
+

+
    if (inPipePtr != NULL) {
+
        *inPipePtr = JIM_BAD_FD;
+
    }
+
    if (outPipePtr != NULL) {
+
        *outPipePtr = JIM_BAD_FD;
+
    }
+
    if (errFilePtr != NULL) {
+
        *errFilePtr = JIM_BAD_FD;
+
    }
+
    pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
+

+
    cmdCount = 1;
+
    lastBar = -1;
+
    for (i = 0; i < argc; i++) {
+
        const char *arg = Jim_String(argv[i]);
+

+
        if (arg[0] == '<') {
+
            inputFile = FILE_NAME;
+
            input = arg + 1;
+
            if (*input == '<') {
+
                inputFile = FILE_TEXT;
+
                input_len = Jim_Length(argv[i]) - 2;
+
                input++;
+
            }
+
            else if (*input == '@') {
+
                inputFile = FILE_HANDLE;
+
                input++;
+
            }
+

+
            if (!*input && ++i < argc) {
+
                input = Jim_GetString(argv[i], &input_len);
+
            }
+
        }
+
        else if (arg[0] == '>') {
+
            int dup_error = 0;
+

+
            outputFile = FILE_NAME;
+

+
            output = arg + 1;
+
            if (*output == '>') {
+
                outputFile = FILE_APPEND;
+
                output++;
+
            }
+
            if (*output == '&') {
+

+
                output++;
+
                dup_error = 1;
+
            }
+
            if (*output == '@') {
+
                outputFile = FILE_HANDLE;
+
                output++;
+
            }
+
            if (!*output && ++i < argc) {
+
                output = Jim_String(argv[i]);
+
            }
+
            if (dup_error) {
+
                errorFile = outputFile;
+
                error = output;
+
            }
+
        }
+
        else if (arg[0] == '2' && arg[1] == '>') {
+
            error = arg + 2;
+
            errorFile = FILE_NAME;
+

+
            if (*error == '@') {
+
                errorFile = FILE_HANDLE;
+
                error++;
+
            }
+
            else if (*error == '>') {
+
                errorFile = FILE_APPEND;
+
                error++;
+
            }
+
            if (!*error && ++i < argc) {
+
                error = Jim_String(argv[i]);
+
            }
+
        }
+
        else {
+
            if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
+
                if (i == lastBar + 1 || i == argc - 1) {
+
                    Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
+
                    goto badargs;
+
                }
+
                lastBar = i;
+
                cmdCount++;
+
            }
+

+
            arg_array[arg_count++] = (char *)arg;
+
            continue;
+
        }
+

+
        if (i >= argc) {
+
            Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
+
            goto badargs;
+
        }
+
    }
+

+
    if (arg_count == 0) {
+
        Jim_SetResultString(interp, "didn't specify command to execute", -1);
+
badargs:
+
        Jim_Free(arg_array);
+
        return -1;
+
    }
+

+

+
    save_environ = JimSaveEnv(JimBuildEnv(interp));
+

+
    if (input != NULL) {
+
        if (inputFile == FILE_TEXT) {
+
            inputId = JimCreateTemp(interp, input, input_len);
+
            if (inputId == JIM_BAD_FD) {
+
                goto error;
+
            }
+
        }
+
        else if (inputFile == FILE_HANDLE) {
+

+
            FILE *fh = JimGetAioFilehandle(interp, input);
+

+
            if (fh == NULL) {
+
                goto error;
+
            }
+
            inputId = JimDupFd(JimFileno(fh));
+
        }
+
        else {
+
            inputId = JimOpenForRead(input);
+
            if (inputId == JIM_BAD_FD) {
+
                Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, JimStrError());
+
                goto error;
+
            }
+
        }
+
    }
+
    else if (inPipePtr != NULL) {
+
        if (JimPipe(pipeIds) != 0) {
+
            Jim_SetResultErrno(interp, "couldn't create input pipe for command");
+
            goto error;
+
        }
+
        inputId = pipeIds[0];
+
        *inPipePtr = pipeIds[1];
+
        pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
+
    }
+

+
    if (output != NULL) {
+
        if (outputFile == FILE_HANDLE) {
+
            FILE *fh = JimGetAioFilehandle(interp, output);
+
            if (fh == NULL) {
+
                goto error;
+
            }
+
            fflush(fh);
+
            lastOutputId = JimDupFd(JimFileno(fh));
+
        }
+
        else {
+
            lastOutputId = JimOpenForWrite(output, outputFile == FILE_APPEND);
+
            if (lastOutputId == JIM_BAD_FD) {
+
                Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, JimStrError());
+
                goto error;
+
            }
+
        }
+
    }
+
    else if (outPipePtr != NULL) {
+
        if (JimPipe(pipeIds) != 0) {
+
            Jim_SetResultErrno(interp, "couldn't create output pipe");
+
            goto error;
+
        }
+
        lastOutputId = pipeIds[1];
+
        *outPipePtr = pipeIds[0];
+
        pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
+
    }
+

+
    if (error != NULL) {
+
        if (errorFile == FILE_HANDLE) {
+
            if (strcmp(error, "1") == 0) {
+

+
                if (lastOutputId != JIM_BAD_FD) {
+
                    errorId = JimDupFd(lastOutputId);
+
                }
+
                else {
+

+
                    error = "stdout";
+
                }
+
            }
+
            if (errorId == JIM_BAD_FD) {
+
                FILE *fh = JimGetAioFilehandle(interp, error);
+
                if (fh == NULL) {
+
                    goto error;
+
                }
+
                fflush(fh);
+
                errorId = JimDupFd(JimFileno(fh));
+
            }
+
        }
+
        else {
+
            errorId = JimOpenForWrite(error, errorFile == FILE_APPEND);
+
            if (errorId == JIM_BAD_FD) {
+
                Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, JimStrError());
+
                goto error;
+
            }
+
        }
+
    }
+
    else if (errFilePtr != NULL) {
+
        errorId = JimCreateTemp(interp, NULL, 0);
+
        if (errorId == JIM_BAD_FD) {
+
            goto error;
+
        }
+
        *errFilePtr = JimDupFd(errorId);
+
    }
+

+

+
    pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
+
    for (i = 0; i < numPids; i++) {
+
        pidPtr[i] = JIM_BAD_PID;
+
    }
+
    for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
+
        int pipe_dup_err = 0;
+
        fdtype origErrorId = errorId;
+

+
        for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
+
            if (arg_array[lastArg][0] == '|') {
+
                if (arg_array[lastArg][1] == '&') {
+
                    pipe_dup_err = 1;
+
                }
+
                break;
+
            }
+
        }
+

+
        arg_array[lastArg] = NULL;
+
        if (lastArg == arg_count) {
+
            outputId = lastOutputId;
+
        }
+
        else {
+
            if (JimPipe(pipeIds) != 0) {
+
                Jim_SetResultErrno(interp, "couldn't create pipe");
+
                goto error;
+
            }
+
            outputId = pipeIds[1];
+
        }
+

+

+
        if (pipe_dup_err) {
+
            errorId = outputId;
+
        }
+

+

+

+
#ifdef __MINGW32__
+
        pid = JimStartWinProcess(interp, &arg_array[firstArg], save_environ, inputId, outputId, errorId);
+
        if (pid == JIM_BAD_PID) {
+
            Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
+
            goto error;
+
        }
+
#else
+
        pid = vfork();
+
        if (pid < 0) {
+
            Jim_SetResultErrno(interp, "couldn't fork child process");
+
            goto error;
+
        }
+
        if (pid == 0) {
+

+

+
            if (inputId != -1) dup2(inputId, 0);
+
            if (outputId != -1) dup2(outputId, 1);
+
            if (errorId != -1) dup2(errorId, 2);
+

+
            for (i = 3; (i <= outputId) || (i <= inputId) || (i <= errorId); i++) {
+
                close(i);
+
            }
+

+

+
            (void)signal(SIGPIPE, SIG_DFL);
+

+
            execvpe(arg_array[firstArg], &arg_array[firstArg], Jim_GetEnviron());
+

+

+
            fprintf(stderr, "couldn't exec \"%s\"\n", arg_array[firstArg]);
+
#ifdef JIM_MAINTAINER
+
            {
+

+
                static char *const false_argv[2] = {"false", NULL};
+
                execvp(false_argv[0],false_argv);
+
            }
+
#endif
+
            _exit(127);
+
        }
+
#endif
+

+

+

+
        if (table->used == table->size) {
+
            table->size += WAIT_TABLE_GROW_BY;
+
            table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
+
        }
+

+
        table->info[table->used].pid = pid;
+
        table->info[table->used].flags = 0;
+
        table->used++;
+

+
        pidPtr[numPids] = pid;
+

+

+
        errorId = origErrorId;
+

+

+
        if (inputId != JIM_BAD_FD) {
+
            JimCloseFd(inputId);
+
        }
+
        if (outputId != JIM_BAD_FD) {
+
            JimCloseFd(outputId);
+
            outputId = JIM_BAD_FD;
+
        }
+
        inputId = pipeIds[0];
+
        pipeIds[0] = pipeIds[1] = JIM_BAD_FD;
+
    }
+
    *pidArrayPtr = pidPtr;
+

+

+
  cleanup:
+
    if (inputId != JIM_BAD_FD) {
+
        JimCloseFd(inputId);
+
    }
+
    if (lastOutputId != JIM_BAD_FD) {
+
        JimCloseFd(lastOutputId);
+
    }
+
    if (errorId != JIM_BAD_FD) {
+
        JimCloseFd(errorId);
+
    }
+
    Jim_Free(arg_array);
+

+
    JimRestoreEnv(save_environ);
+

+
    return numPids;
+

+

+
  error:
+
    if ((inPipePtr != NULL) && (*inPipePtr != JIM_BAD_FD)) {
+
        JimCloseFd(*inPipePtr);
+
        *inPipePtr = JIM_BAD_FD;
+
    }
+
    if ((outPipePtr != NULL) && (*outPipePtr != JIM_BAD_FD)) {
+
        JimCloseFd(*outPipePtr);
+
        *outPipePtr = JIM_BAD_FD;
+
    }
+
    if ((errFilePtr != NULL) && (*errFilePtr != JIM_BAD_FD)) {
+
        JimCloseFd(*errFilePtr);
+
        *errFilePtr = JIM_BAD_FD;
+
    }
+
    if (pipeIds[0] != JIM_BAD_FD) {
+
        JimCloseFd(pipeIds[0]);
+
    }
+
    if (pipeIds[1] != JIM_BAD_FD) {
+
        JimCloseFd(pipeIds[1]);
+
    }
+
    if (pidPtr != NULL) {
+
        for (i = 0; i < numPids; i++) {
+
            if (pidPtr[i] != JIM_BAD_PID) {
+
                JimDetachPids(interp, 1, &pidPtr[i]);
+
            }
+
        }
+
        Jim_Free(pidPtr);
+
    }
+
    numPids = -1;
+
    goto cleanup;
+
}
+

+

+
static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, Jim_Obj *errStrObj)
+
{
+
    struct WaitInfoTable *table = Jim_CmdPrivData(interp);
+
    int result = JIM_OK;
+
    int i;
+

+

+
    for (i = 0; i < numPids; i++) {
+
        int waitStatus = 0;
+
        if (JimWaitForProcess(table, pidPtr[i], &waitStatus) != JIM_BAD_PID) {
+
            if (JimCheckWaitStatus(interp, pidPtr[i], waitStatus, errStrObj) != JIM_OK) {
+
                result = JIM_ERR;
+
            }
+
        }
+
    }
+
    Jim_Free(pidPtr);
+

+
    return result;
+
}
+

+
int Jim_execInit(Jim_Interp *interp)
+
{
+
    if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
+
        return JIM_ERR;
+

+
#ifdef SIGPIPE
+
    (void)signal(SIGPIPE, SIG_IGN);
+
#endif
+

+
    Jim_CreateCommand(interp, "exec", Jim_ExecCmd, JimAllocWaitInfoTable(), JimFreeWaitInfoTable);
+
    return JIM_OK;
+
}
+

+
#if defined(__MINGW32__)
+

+

+
static SECURITY_ATTRIBUTES *JimStdSecAttrs(void)
+
{
+
    static SECURITY_ATTRIBUTES secAtts;
+

+
    secAtts.nLength = sizeof(SECURITY_ATTRIBUTES);
+
    secAtts.lpSecurityDescriptor = NULL;
+
    secAtts.bInheritHandle = TRUE;
+
    return &secAtts;
+
}
+

+
static int JimErrno(void)
+
{
+
    switch (GetLastError()) {
+
    case ERROR_FILE_NOT_FOUND: return ENOENT;
+
    case ERROR_PATH_NOT_FOUND: return ENOENT;
+
    case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
+
    case ERROR_ACCESS_DENIED: return EACCES;
+
    case ERROR_INVALID_HANDLE: return EBADF;
+
    case ERROR_BAD_ENVIRONMENT: return E2BIG;
+
    case ERROR_BAD_FORMAT: return ENOEXEC;
+
    case ERROR_INVALID_ACCESS: return EACCES;
+
    case ERROR_INVALID_DRIVE: return ENOENT;
+
    case ERROR_CURRENT_DIRECTORY: return EACCES;
+
    case ERROR_NOT_SAME_DEVICE: return EXDEV;
+
    case ERROR_NO_MORE_FILES: return ENOENT;
+
    case ERROR_WRITE_PROTECT: return EROFS;
+
    case ERROR_BAD_UNIT: return ENXIO;
+
    case ERROR_NOT_READY: return EBUSY;
+
    case ERROR_BAD_COMMAND: return EIO;
+
    case ERROR_CRC: return EIO;
+
    case ERROR_BAD_LENGTH: return EIO;
+
    case ERROR_SEEK: return EIO;
+
    case ERROR_WRITE_FAULT: return EIO;
+
    case ERROR_READ_FAULT: return EIO;
+
    case ERROR_GEN_FAILURE: return EIO;
+
    case ERROR_SHARING_VIOLATION: return EACCES;
+
    case ERROR_LOCK_VIOLATION: return EACCES;
+
    case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
+
    case ERROR_HANDLE_DISK_FULL: return ENOSPC;
+
    case ERROR_NOT_SUPPORTED: return ENODEV;
+
    case ERROR_REM_NOT_LIST: return EBUSY;
+
    case ERROR_DUP_NAME: return EEXIST;
+
    case ERROR_BAD_NETPATH: return ENOENT;
+
    case ERROR_NETWORK_BUSY: return EBUSY;
+
    case ERROR_DEV_NOT_EXIST: return ENODEV;
+
    case ERROR_TOO_MANY_CMDS: return EAGAIN;
+
    case ERROR_ADAP_HDW_ERR: return EIO;
+
    case ERROR_BAD_NET_RESP: return EIO;
+
    case ERROR_UNEXP_NET_ERR: return EIO;
+
    case ERROR_NETNAME_DELETED: return ENOENT;
+
    case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
+
    case ERROR_BAD_DEV_TYPE: return ENODEV;
+
    case ERROR_BAD_NET_NAME: return ENOENT;
+
    case ERROR_TOO_MANY_NAMES: return ENFILE;
+
    case ERROR_TOO_MANY_SESS: return EIO;
+
    case ERROR_SHARING_PAUSED: return EAGAIN;
+
    case ERROR_REDIR_PAUSED: return EAGAIN;
+
    case ERROR_FILE_EXISTS: return EEXIST;
+
    case ERROR_CANNOT_MAKE: return ENOSPC;
+
    case ERROR_OUT_OF_STRUCTURES: return ENFILE;
+
    case ERROR_ALREADY_ASSIGNED: return EEXIST;
+
    case ERROR_INVALID_PASSWORD: return EPERM;
+
    case ERROR_NET_WRITE_FAULT: return EIO;
+
    case ERROR_NO_PROC_SLOTS: return EAGAIN;
+
    case ERROR_DISK_CHANGE: return EXDEV;
+
    case ERROR_BROKEN_PIPE: return EPIPE;
+
    case ERROR_OPEN_FAILED: return ENOENT;
+
    case ERROR_DISK_FULL: return ENOSPC;
+
    case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
+
    case ERROR_INVALID_TARGET_HANDLE: return EBADF;
+
    case ERROR_INVALID_NAME: return ENOENT;
+
    case ERROR_PROC_NOT_FOUND: return ESRCH;
+
    case ERROR_WAIT_NO_CHILDREN: return ECHILD;
+
    case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
+
    case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
+
    case ERROR_SEEK_ON_DEVICE: return ESPIPE;
+
    case ERROR_BUSY_DRIVE: return EAGAIN;
+
    case ERROR_DIR_NOT_EMPTY: return EEXIST;
+
    case ERROR_NOT_LOCKED: return EACCES;
+
    case ERROR_BAD_PATHNAME: return ENOENT;
+
    case ERROR_LOCK_FAILED: return EACCES;
+
    case ERROR_ALREADY_EXISTS: return EEXIST;
+
    case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
+
    case ERROR_BAD_PIPE: return EPIPE;
+
    case ERROR_PIPE_BUSY: return EAGAIN;
+
    case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
+
    case ERROR_DIRECTORY: return ENOTDIR;
+
    }
+
    return EINVAL;
+
}
+

+
static int JimPipe(fdtype pipefd[2])
+
{
+
    if (CreatePipe(&pipefd[0], &pipefd[1], NULL, 0)) {
+
        return 0;
+
    }
+
    return -1;
+
}
+

+
static fdtype JimDupFd(fdtype infd)
+
{
+
    fdtype dupfd;
+
    pidtype pid = GetCurrentProcess();
+

+
    if (DuplicateHandle(pid, infd, pid, &dupfd, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
+
        return dupfd;
+
    }
+
    return JIM_BAD_FD;
+
}
+

+
static int JimRewindFd(fdtype fd)
+
{
+
    return SetFilePointer(fd, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ? -1 : 0;
+
}
+

+
#if 0
+
static int JimReadFd(fdtype fd, char *buffer, size_t len)
+
{
+
    DWORD num;
+

+
    if (ReadFile(fd, buffer, len, &num, NULL)) {
+
        return num;
+
    }
+
    if (GetLastError() == ERROR_HANDLE_EOF || GetLastError() == ERROR_BROKEN_PIPE) {
+
        return 0;
+
    }
+
    return -1;
+
}
+
#endif
+

+
static FILE *JimFdOpenForRead(fdtype fd)
+
{
+
    return _fdopen(_open_osfhandle((int)fd, _O_RDONLY | _O_TEXT), "r");
+
}
+

+
static fdtype JimFileno(FILE *fh)
+
{
+
    return (fdtype)_get_osfhandle(_fileno(fh));
+
}
+

+
static fdtype JimOpenForRead(const char *filename)
+
{
+
    return CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
+
        JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+
}
+

+
static fdtype JimOpenForWrite(const char *filename, int append)
+
{
+
    fdtype fd = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
+
        JimStdSecAttrs(), append ? OPEN_ALWAYS : CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);
+
    if (append && fd != JIM_BAD_FD) {
+
        SetFilePointer(fd, 0, NULL, FILE_END);
+
    }
+
    return fd;
+
}
+

+
static FILE *JimFdOpenForWrite(fdtype fd)
+
{
+
    return _fdopen(_open_osfhandle((int)fd, _O_TEXT), "w");
+
}
+

+
static pidtype JimWaitPid(pidtype pid, int *status, int nohang)
+
{
+
    DWORD ret = WaitForSingleObject(pid, nohang ? 0 : INFINITE);
+
    if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
+

+
        return JIM_BAD_PID;
+
    }
+
    GetExitCodeProcess(pid, &ret);
+
    *status = ret;
+
    CloseHandle(pid);
+
    return pid;
+
}
+

+
static HANDLE JimCreateTemp(Jim_Interp *interp, const char *contents, int len)
+
{
+
    char name[MAX_PATH];
+
    HANDLE handle;
+

+
    if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, "JIM", 0, name)) {
+
        return JIM_BAD_FD;
+
    }
+

+
    handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, JimStdSecAttrs(),
+
            CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
+
            NULL);
+

+
    if (handle == INVALID_HANDLE_VALUE) {
+
        goto error;
+
    }
+

+
    if (contents != NULL) {
+

+
        FILE *fh = JimFdOpenForWrite(JimDupFd(handle));
+
        if (fh == NULL) {
+
            goto error;
+
        }
+

+
        if (fwrite(contents, len, 1, fh) != 1) {
+
            fclose(fh);
+
            goto error;
+
        }
+
        fseek(fh, 0, SEEK_SET);
+
        fclose(fh);
+
    }
+
    return handle;
+

+
  error:
+
    Jim_SetResultErrno(interp, "failed to create temp file");
+
    CloseHandle(handle);
+
    DeleteFile(name);
+
    return JIM_BAD_FD;
+
}
+

+
static int
+
JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
+
{
+
    int i;
+
    static char extensions[][5] = {".exe", "", ".bat"};
+

+
    for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
+
        snprintf(fullPath, MAX_PATH, "%s%s", originalName, extensions[i]);
+

+
        if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
+
            continue;
+
        }
+
        if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
+
            continue;
+
        }
+
        return 0;
+
    }
+

+
    return -1;
+
}
+

+
static char **JimSaveEnv(char **env)
+
{
+
    return env;
+
}
+

+
static void JimRestoreEnv(char **env)
+
{
+
    JimFreeEnv(env, Jim_GetEnviron());
+
}
+

+
static char **JimOriginalEnviron(void)
+
{
+
    return NULL;
+
}
+

+
static Jim_Obj *
+
JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
+
{
+
    char *start, *special;
+
    int quote, i;
+

+
    Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
+

+
    for (i = 0; argv[i]; i++) {
+
        if (i > 0) {
+
            Jim_AppendString(interp, strObj, " ", 1);
+
        }
+

+
        if (argv[i][0] == '\0') {
+
            quote = 1;
+
        }
+
        else {
+
            quote = 0;
+
            for (start = argv[i]; *start != '\0'; start++) {
+
                if (isspace(UCHAR(*start))) {
+
                    quote = 1;
+
                    break;
+
                }
+
            }
+
        }
+
        if (quote) {
+
            Jim_AppendString(interp, strObj, "\"" , 1);
+
        }
+

+
        start = argv[i];
+
        for (special = argv[i]; ; ) {
+
            if ((*special == '\\') && (special[1] == '\\' ||
+
                    special[1] == '"' || (quote && special[1] == '\0'))) {
+
                Jim_AppendString(interp, strObj, start, special - start);
+
                start = special;
+
                while (1) {
+
                    special++;
+
                    if (*special == '"' || (quote && *special == '\0')) {
+

+
                        Jim_AppendString(interp, strObj, start, special - start);
+
                        break;
+
                    }
+
                    if (*special != '\\') {
+
                        break;
+
                    }
+
                }
+
                Jim_AppendString(interp, strObj, start, special - start);
+
                start = special;
+
            }
+
            if (*special == '"') {
+
        if (special == start) {
+
            Jim_AppendString(interp, strObj, "\"", 1);
+
        }
+
        else {
+
            Jim_AppendString(interp, strObj, start, special - start);
+
        }
+
                Jim_AppendString(interp, strObj, "\\\"", 2);
+
                start = special + 1;
+
            }
+
            if (*special == '\0') {
+
                break;
+
            }
+
            special++;
+
        }
+
        Jim_AppendString(interp, strObj, start, special - start);
+
        if (quote) {
+
            Jim_AppendString(interp, strObj, "\"", 1);
+
        }
+
    }
+
    return strObj;
+
}
+

+
static pidtype
+
JimStartWinProcess(Jim_Interp *interp, char **argv, char **env, fdtype inputId, fdtype outputId, fdtype errorId)
+
{
+
    STARTUPINFO startInfo;
+
    PROCESS_INFORMATION procInfo;
+
    HANDLE hProcess, h;
+
    char execPath[MAX_PATH];
+
    pidtype pid = JIM_BAD_PID;
+
    Jim_Obj *cmdLineObj;
+
    char *winenv;
+

+
    if (JimWinFindExecutable(argv[0], execPath) < 0) {
+
        return JIM_BAD_PID;
+
    }
+
    argv[0] = execPath;
+

+
    hProcess = GetCurrentProcess();
+
    cmdLineObj = JimWinBuildCommandLine(interp, argv);
+

+

+
    ZeroMemory(&startInfo, sizeof(startInfo));
+
    startInfo.cb = sizeof(startInfo);
+
    startInfo.dwFlags   = STARTF_USESTDHANDLES;
+
    startInfo.hStdInput = INVALID_HANDLE_VALUE;
+
    startInfo.hStdOutput= INVALID_HANDLE_VALUE;
+
    startInfo.hStdError = INVALID_HANDLE_VALUE;
+

+
    if (inputId == JIM_BAD_FD) {
+
        if (CreatePipe(&startInfo.hStdInput, &h, JimStdSecAttrs(), 0) != FALSE) {
+
            CloseHandle(h);
+
        }
+
    } else {
+
        DuplicateHandle(hProcess, inputId, hProcess, &startInfo.hStdInput,
+
                0, TRUE, DUPLICATE_SAME_ACCESS);
+
    }
+
    if (startInfo.hStdInput == JIM_BAD_FD) {
+
        goto end;
+
    }
+

+
    if (outputId == JIM_BAD_FD) {
+
        startInfo.hStdOutput = CreateFile("NUL:", GENERIC_WRITE, 0,
+
                JimStdSecAttrs(), OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+
    } else {
+
        DuplicateHandle(hProcess, outputId, hProcess, &startInfo.hStdOutput,
+
                0, TRUE, DUPLICATE_SAME_ACCESS);
+
    }
+
    if (startInfo.hStdOutput == JIM_BAD_FD) {
+
        goto end;
+
    }
+

+
    if (errorId == JIM_BAD_FD) {
+

+
        startInfo.hStdError = CreateFile("NUL:", GENERIC_WRITE, 0,
+
                JimStdSecAttrs(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+
    } else {
+
        DuplicateHandle(hProcess, errorId, hProcess, &startInfo.hStdError,
+
                0, TRUE, DUPLICATE_SAME_ACCESS);
+
    }
+
    if (startInfo.hStdError == JIM_BAD_FD) {
+
        goto end;
+
    }
+

+
    if (env == NULL) {
+

+
        winenv = NULL;
+
    }
+
    else if (env[0] == NULL) {
+
        winenv = (char *)"\0";
+
    }
+
    else {
+
        winenv = env[0];
+
    }
+

+
    if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
+
            0, winenv, NULL, &startInfo, &procInfo)) {
+
        goto end;
+
    }
+

+

+
    WaitForInputIdle(procInfo.hProcess, 5000);
+
    CloseHandle(procInfo.hThread);
+

+
    pid = procInfo.hProcess;
+

+
    end:
+
    Jim_FreeNewObj(interp, cmdLineObj);
+
    if (startInfo.hStdInput != JIM_BAD_FD) {
+
        CloseHandle(startInfo.hStdInput);
+
    }
+
    if (startInfo.hStdOutput != JIM_BAD_FD) {
+
        CloseHandle(startInfo.hStdOutput);
+
    }
+
    if (startInfo.hStdError != JIM_BAD_FD) {
+
        CloseHandle(startInfo.hStdError);
+
    }
+
    return pid;
+
}
+
#else
+

+
static int JimOpenForWrite(const char *filename, int append)
+
{
+
    return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
+
}
+

+
static int JimRewindFd(int fd)
+
{
+
    return lseek(fd, 0L, SEEK_SET);
+
}
+

+
static int JimCreateTemp(Jim_Interp *interp, const char *contents, int len)
+
{
+
    int fd = Jim_MakeTempFile(interp, NULL);
+

+
    if (fd != JIM_BAD_FD) {
+
        unlink(Jim_String(Jim_GetResult(interp)));
+
        if (contents) {
+
            if (write(fd, contents, len) != len) {
+
                Jim_SetResultErrno(interp, "couldn't write temp file");
+
                close(fd);
+
                return -1;
+
            }
+
            lseek(fd, 0L, SEEK_SET);
+
        }
+
    }
+
    return fd;
+
}
+

+
static char **JimOriginalEnviron(void)
+
{
+
    return Jim_GetEnviron();
+
}
+

+
static char **JimSaveEnv(char **env)
+
{
+
    char **saveenv = Jim_GetEnviron();
+
    Jim_SetEnviron(env);
+
    return saveenv;
+
}
+

+
static void JimRestoreEnv(char **env)
+
{
+
    JimFreeEnv(Jim_GetEnviron(), env);
+
    Jim_SetEnviron(env);
+
}
+
#endif
+
#endif
+

+

+
#ifndef _XOPEN_SOURCE
+
#define _XOPEN_SOURCE 500
+
#endif
+

+
#include <stdlib.h>
+
#include <string.h>
+
#include <stdio.h>
+
#include <time.h>
+

+

+
#ifdef HAVE_SYS_TIME_H
+
#include <sys/time.h>
+
#endif
+

+
static int clock_cmd_format(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+

+
    char buf[100];
+
    time_t t;
+
    long seconds;
+

+
    const char *format = "%a %b %d %H:%M:%S %Z %Y";
+

+
    if (argc == 2 || (argc == 3 && !Jim_CompareStringImmediate(interp, argv[1], "-format"))) {
+
        return -1;
+
    }
+

+
    if (argc == 3) {
+
        format = Jim_String(argv[2]);
+
    }
+

+
    if (Jim_GetLong(interp, argv[0], &seconds) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    t = seconds;
+

+
    if (strftime(buf, sizeof(buf), format, localtime(&t)) == 0) {
+
        Jim_SetResultString(interp, "format string too long", -1);
+
        return JIM_ERR;
+
    }
+

+
    Jim_SetResultString(interp, buf, -1);
+

+
    return JIM_OK;
+
}
+

+
#ifdef HAVE_STRPTIME
+
static int clock_cmd_scan(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    char *pt;
+
    struct tm tm;
+
    time_t now = time(0);
+

+
    if (!Jim_CompareStringImmediate(interp, argv[1], "-format")) {
+
        return -1;
+
    }
+

+

+
    localtime_r(&now, &tm);
+

+
    pt = strptime(Jim_String(argv[0]), Jim_String(argv[2]), &tm);
+
    if (pt == 0 || *pt != 0) {
+
        Jim_SetResultString(interp, "Failed to parse time according to format", -1);
+
        return JIM_ERR;
+
    }
+

+

+
    Jim_SetResultInt(interp, mktime(&tm));
+

+
    return JIM_OK;
+
}
+
#endif
+

+
static int clock_cmd_seconds(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_SetResultInt(interp, time(NULL));
+

+
    return JIM_OK;
+
}
+

+
static int clock_cmd_micros(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct timeval tv;
+

+
    gettimeofday(&tv, NULL);
+

+
    Jim_SetResultInt(interp, (jim_wide) tv.tv_sec * 1000000 + tv.tv_usec);
+

+
    return JIM_OK;
+
}
+

+
static int clock_cmd_millis(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    struct timeval tv;
+

+
    gettimeofday(&tv, NULL);
+

+
    Jim_SetResultInt(interp, (jim_wide) tv.tv_sec * 1000 + tv.tv_usec / 1000);
+

+
    return JIM_OK;
+
}
+

+
static const jim_subcmd_type clock_command_table[] = {
+
    {   "seconds",
+
        NULL,
+
        clock_cmd_seconds,
+
        0,
+
        0,
+

+
    },
+
    {   "clicks",
+
        NULL,
+
        clock_cmd_micros,
+
        0,
+
        0,
+

+
    },
+
    {   "microseconds",
+
        NULL,
+
        clock_cmd_micros,
+
        0,
+
        0,
+

+
    },
+
    {   "milliseconds",
+
        NULL,
+
        clock_cmd_millis,
+
        0,
+
        0,
+

+
    },
+
    {   "format",
+
        "seconds ?-format format?",
+
        clock_cmd_format,
+
        1,
+
        3,
+

+
    },
+
#ifdef HAVE_STRPTIME
+
    {   "scan",
+
        "str -format format",
+
        clock_cmd_scan,
+
        3,
+
        3,
+

+
    },
+
#endif
+
    { NULL }
+
};
+

+
int Jim_clockInit(Jim_Interp *interp)
+
{
+
    if (Jim_PackageProvide(interp, "clock", "1.0", JIM_ERRMSG))
+
        return JIM_ERR;
+

+
    Jim_CreateCommand(interp, "clock", Jim_SubCmdProc, (void *)clock_command_table, NULL);
+
    return JIM_OK;
+
}
+

+
#include <limits.h>
+
#include <stdlib.h>
+
#include <string.h>
+
#include <stdio.h>
+
#include <errno.h>
+

+

+
static int array_cmd_exists(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+

+
    Jim_Obj *dictObj = Jim_GetVariable(interp, argv[0], JIM_UNSHARED);
+
    Jim_SetResultInt(interp, dictObj && Jim_DictSize(interp, dictObj) != -1);
+
    return JIM_OK;
+
}
+

+
static int array_cmd_get(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+
    Jim_Obj *patternObj;
+

+
    if (!objPtr) {
+
        return JIM_OK;
+
    }
+

+
    patternObj = (argc == 1) ? NULL : argv[1];
+

+

+
    if (patternObj == NULL || Jim_CompareStringImmediate(interp, patternObj, "*")) {
+
        if (Jim_IsList(objPtr) && Jim_ListLength(interp, objPtr) % 2 == 0) {
+

+
            Jim_SetResult(interp, objPtr);
+
            return JIM_OK;
+
        }
+
    }
+

+
    return Jim_DictMatchTypes(interp, objPtr, patternObj, JIM_DICTMATCH_KEYS, JIM_DICTMATCH_KEYS | JIM_DICTMATCH_VALUES);
+
}
+

+
static int array_cmd_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+

+
    if (!objPtr) {
+
        return JIM_OK;
+
    }
+

+
    return Jim_DictMatchTypes(interp, objPtr, argc == 1 ? NULL : argv[1], JIM_DICTMATCH_KEYS, JIM_DICTMATCH_KEYS);
+
}
+

+
static int array_cmd_unset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int i;
+
    int len;
+
    Jim_Obj *resultObj;
+
    Jim_Obj *objPtr;
+
    Jim_Obj **dictValuesObj;
+

+
    if (argc == 1 || Jim_CompareStringImmediate(interp, argv[1], "*")) {
+

+
        Jim_UnsetVariable(interp, argv[0], JIM_NONE);
+
        return JIM_OK;
+
    }
+

+
    objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+

+
    if (objPtr == NULL) {
+

+
        return JIM_OK;
+
    }
+

+
    if (Jim_DictPairs(interp, objPtr, &dictValuesObj, &len) != JIM_OK) {
+

+
        Jim_SetResultString(interp, "", -1);
+
        return JIM_OK;
+
    }
+

+

+
    resultObj = Jim_NewDictObj(interp, NULL, 0);
+

+
    for (i = 0; i < len; i += 2) {
+
        if (!Jim_StringMatchObj(interp, argv[1], dictValuesObj[i], 0)) {
+
            Jim_DictAddElement(interp, resultObj, dictValuesObj[i], dictValuesObj[i + 1]);
+
        }
+
    }
+
    Jim_Free(dictValuesObj);
+

+
    Jim_SetVariable(interp, argv[0], resultObj);
+
    return JIM_OK;
+
}
+

+
static int array_cmd_size(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr;
+
    int len = 0;
+

+

+
    objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+
    if (objPtr) {
+
        len = Jim_DictSize(interp, objPtr);
+
        if (len < 0) {
+

+
            Jim_SetResultInt(interp, 0);
+
            return JIM_OK;
+
        }
+
    }
+

+
    Jim_SetResultInt(interp, len);
+

+
    return JIM_OK;
+
}
+

+
static int array_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+
    if (objPtr) {
+
        return Jim_DictInfo(interp, objPtr);
+
    }
+
    Jim_SetResultFormatted(interp, "\"%#s\" isn't an array", argv[0], NULL);
+
    return JIM_ERR;
+
}
+

+
static int array_cmd_set(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int i;
+
    int len;
+
    Jim_Obj *listObj = argv[1];
+
    Jim_Obj *dictObj;
+

+
    len = Jim_ListLength(interp, listObj);
+
    if (len % 2) {
+
        Jim_SetResultString(interp, "list must have an even number of elements", -1);
+
        return JIM_ERR;
+
    }
+

+
    dictObj = Jim_GetVariable(interp, argv[0], JIM_UNSHARED);
+
    if (!dictObj) {
+

+
        return Jim_SetVariable(interp, argv[0], listObj);
+
    }
+
    else if (Jim_DictSize(interp, dictObj) < 0) {
+
        return JIM_ERR;
+
    }
+

+
    if (Jim_IsShared(dictObj)) {
+
        dictObj = Jim_DuplicateObj(interp, dictObj);
+
    }
+

+
    for (i = 0; i < len; i += 2) {
+
        Jim_Obj *nameObj;
+
        Jim_Obj *valueObj;
+

+
        Jim_ListIndex(interp, listObj, i, &nameObj, JIM_NONE);
+
        Jim_ListIndex(interp, listObj, i + 1, &valueObj, JIM_NONE);
+

+
        Jim_DictAddElement(interp, dictObj, nameObj, valueObj);
+
    }
+
    return Jim_SetVariable(interp, argv[0], dictObj);
+
}
+

+
static const jim_subcmd_type array_command_table[] = {
+
        {       "exists",
+
                "arrayName",
+
                array_cmd_exists,
+
                1,
+
                1,
+

+
        },
+
        {       "get",
+
                "arrayName ?pattern?",
+
                array_cmd_get,
+
                1,
+
                2,
+

+
        },
+
        {       "names",
+
                "arrayName ?pattern?",
+
                array_cmd_names,
+
                1,
+
                2,
+

+
        },
+
        {       "set",
+
                "arrayName list",
+
                array_cmd_set,
+
                2,
+
                2,
+

+
        },
+
        {       "size",
+
                "arrayName",
+
                array_cmd_size,
+
                1,
+
                1,
+

+
        },
+
        {       "stat",
+
                "arrayName",
+
                array_cmd_stat,
+
                1,
+
                1,
+

+
        },
+
        {       "unset",
+
                "arrayName ?pattern?",
+
                array_cmd_unset,
+
                1,
+
                2,
+

+
        },
+
        {       NULL
+
        }
+
};
+

+
int Jim_arrayInit(Jim_Interp *interp)
+
{
+
    if (Jim_PackageProvide(interp, "array", "1.0", JIM_ERRMSG))
+
        return JIM_ERR;
+

+
    Jim_CreateCommand(interp, "array", Jim_SubCmdProc, (void *)array_command_table, NULL);
+
    return JIM_OK;
+
}
+
int Jim_InitStaticExtensions(Jim_Interp *interp)
+
{
+
extern int Jim_bootstrapInit(Jim_Interp *);
+
extern int Jim_aioInit(Jim_Interp *);
+
extern int Jim_readdirInit(Jim_Interp *);
+
extern int Jim_regexpInit(Jim_Interp *);
+
extern int Jim_fileInit(Jim_Interp *);
+
extern int Jim_globInit(Jim_Interp *);
+
extern int Jim_execInit(Jim_Interp *);
+
extern int Jim_clockInit(Jim_Interp *);
+
extern int Jim_arrayInit(Jim_Interp *);
+
extern int Jim_stdlibInit(Jim_Interp *);
+
extern int Jim_tclcompatInit(Jim_Interp *);
+
Jim_bootstrapInit(interp);
+
Jim_aioInit(interp);
+
Jim_readdirInit(interp);
+
Jim_regexpInit(interp);
+
Jim_fileInit(interp);
+
Jim_globInit(interp);
+
Jim_execInit(interp);
+
Jim_clockInit(interp);
+
Jim_arrayInit(interp);
+
Jim_stdlibInit(interp);
+
Jim_tclcompatInit(interp);
+
return JIM_OK;
+
}
+
#define JIM_OPTIMIZATION
+
#ifndef _GNU_SOURCE
+
#define _GNU_SOURCE
+
#endif
+

+
#include <stdio.h>
+
#include <stdlib.h>
+

+
#include <string.h>
+
#include <stdarg.h>
+
#include <ctype.h>
+
#include <limits.h>
+
#include <assert.h>
+
#include <errno.h>
+
#include <time.h>
+
#include <setjmp.h>
+

+

+
#ifdef HAVE_SYS_TIME_H
+
#include <sys/time.h>
+
#endif
+
#ifdef HAVE_BACKTRACE
+
#include <execinfo.h>
+
#endif
+
#ifdef HAVE_CRT_EXTERNS_H
+
#include <crt_externs.h>
+
#endif
+

+

+
#include <math.h>
+

+

+

+

+

+
#ifndef TCL_LIBRARY
+
#define TCL_LIBRARY "."
+
#endif
+
#ifndef TCL_PLATFORM_OS
+
#define TCL_PLATFORM_OS "unknown"
+
#endif
+
#ifndef TCL_PLATFORM_PLATFORM
+
#define TCL_PLATFORM_PLATFORM "unknown"
+
#endif
+
#ifndef TCL_PLATFORM_PATH_SEPARATOR
+
#define TCL_PLATFORM_PATH_SEPARATOR ":"
+
#endif
+

+

+

+

+

+

+

+
#ifdef JIM_MAINTAINER
+
#define JIM_DEBUG_COMMAND
+
#define JIM_DEBUG_PANIC
+
#endif
+

+

+

+
#define JIM_INTEGER_SPACE 24
+

+
const char *jim_tt_name(int type);
+

+
#ifdef JIM_DEBUG_PANIC
+
static void JimPanicDump(int fail_condition, const char *fmt, ...);
+
#define JimPanic(X) JimPanicDump X
+
#else
+
#define JimPanic(X)
+
#endif
+

+
#ifdef JIM_OPTIMIZATION
+
#define JIM_IF_OPTIM(X) X
+
#else
+
#define JIM_IF_OPTIM(X)
+
#endif
+

+

+
static char JimEmptyStringRep[] = "";
+

+
static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action);
+
static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int listindex, Jim_Obj *newObjPtr,
+
    int flags);
+
static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands);
+
static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr);
+
static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
+
static Jim_Obj **JimDictPairs(Jim_Obj *dictPtr, int *len);
+
static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
+
    const char *prefix, const char *const *tablePtr, const char *name);
+
static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv);
+
static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr);
+
static int JimSign(jim_wide w);
+
static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr);
+
static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen);
+
static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len);
+

+

+

+
#define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
+

+
#define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
+

+
static int utf8_tounicode_case(const char *s, int *uc, int upper)
+
{
+
    int l = utf8_tounicode(s, uc);
+
    if (upper) {
+
        *uc = utf8_upper(*uc);
+
    }
+
    return l;
+
}
+

+

+
#define JIM_CHARSET_SCAN 2
+
#define JIM_CHARSET_GLOB 0
+

+
static const char *JimCharsetMatch(const char *pattern, int c, int flags)
+
{
+
    int not = 0;
+
    int pchar;
+
    int match = 0;
+
    int nocase = 0;
+

+
    if (flags & JIM_NOCASE) {
+
        nocase++;
+
        c = utf8_upper(c);
+
    }
+

+
    if (flags & JIM_CHARSET_SCAN) {
+
        if (*pattern == '^') {
+
            not++;
+
            pattern++;
+
        }
+

+

+
        if (*pattern == ']') {
+
            goto first;
+
        }
+
    }
+

+
    while (*pattern && *pattern != ']') {
+

+
        if (pattern[0] == '\\') {
+
first:
+
            pattern += utf8_tounicode_case(pattern, &pchar, nocase);
+
        }
+
        else {
+

+
            int start;
+
            int end;
+

+
            pattern += utf8_tounicode_case(pattern, &start, nocase);
+
            if (pattern[0] == '-' && pattern[1]) {
+

+
                pattern += utf8_tounicode(pattern, &pchar);
+
                pattern += utf8_tounicode_case(pattern, &end, nocase);
+

+

+
                if ((c >= start && c <= end) || (c >= end && c <= start)) {
+
                    match = 1;
+
                }
+
                continue;
+
            }
+
            pchar = start;
+
        }
+

+
        if (pchar == c) {
+
            match = 1;
+
        }
+
    }
+
    if (not) {
+
        match = !match;
+
    }
+

+
    return match ? pattern : NULL;
+
}
+

+

+

+
static int JimGlobMatch(const char *pattern, const char *string, int nocase)
+
{
+
    int c;
+
    int pchar;
+
    while (*pattern) {
+
        switch (pattern[0]) {
+
            case '*':
+
                while (pattern[1] == '*') {
+
                    pattern++;
+
                }
+
                pattern++;
+
                if (!pattern[0]) {
+
                    return 1;
+
                }
+
                while (*string) {
+

+
                    if (JimGlobMatch(pattern, string, nocase))
+
                        return 1;
+
                    string += utf8_tounicode(string, &c);
+
                }
+
                return 0;
+

+
            case '?':
+
                string += utf8_tounicode(string, &c);
+
                break;
+

+
            case '[': {
+
                    string += utf8_tounicode(string, &c);
+
                    pattern = JimCharsetMatch(pattern + 1, c, nocase ? JIM_NOCASE : 0);
+
                    if (!pattern) {
+
                        return 0;
+
                    }
+
                    if (!*pattern) {
+

+
                        continue;
+
                    }
+
                    break;
+
                }
+
            case '\\':
+
                if (pattern[1]) {
+
                    pattern++;
+
                }
+

+
            default:
+
                string += utf8_tounicode_case(string, &c, nocase);
+
                utf8_tounicode_case(pattern, &pchar, nocase);
+
                if (pchar != c) {
+
                    return 0;
+
                }
+
                break;
+
        }
+
        pattern += utf8_tounicode_case(pattern, &pchar, nocase);
+
        if (!*string) {
+
            while (*pattern == '*') {
+
                pattern++;
+
            }
+
            break;
+
        }
+
    }
+
    if (!*pattern && !*string) {
+
        return 1;
+
    }
+
    return 0;
+
}
+

+
static int JimStringCompare(const char *s1, int l1, const char *s2, int l2)
+
{
+
    if (l1 < l2) {
+
        return memcmp(s1, s2, l1) <= 0 ? -1 : 1;
+
    }
+
    else if (l2 < l1) {
+
        return memcmp(s1, s2, l2) >= 0 ? 1 : -1;
+
    }
+
    else {
+
        return JimSign(memcmp(s1, s2, l1));
+
    }
+
}
+

+
static int JimStringCompareLen(const char *s1, const char *s2, int maxchars, int nocase)
+
{
+
    while (*s1 && *s2 && maxchars) {
+
        int c1, c2;
+
        s1 += utf8_tounicode_case(s1, &c1, nocase);
+
        s2 += utf8_tounicode_case(s2, &c2, nocase);
+
        if (c1 != c2) {
+
            return JimSign(c1 - c2);
+
        }
+
        maxchars--;
+
    }
+
    if (!maxchars) {
+
        return 0;
+
    }
+

+
    if (*s1) {
+
        return 1;
+
    }
+
    if (*s2) {
+
        return -1;
+
    }
+
    return 0;
+
}
+

+
static int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int idx)
+
{
+
    int i;
+
    int l1bytelen;
+

+
    if (!l1 || !l2 || l1 > l2) {
+
        return -1;
+
    }
+
    if (idx < 0)
+
        idx = 0;
+
    s2 += utf8_index(s2, idx);
+

+
    l1bytelen = utf8_index(s1, l1);
+

+
    for (i = idx; i <= l2 - l1; i++) {
+
        int c;
+
        if (memcmp(s2, s1, l1bytelen) == 0) {
+
            return i;
+
        }
+
        s2 += utf8_tounicode(s2, &c);
+
    }
+
    return -1;
+
}
+

+
static int JimStringLast(const char *s1, int l1, const char *s2, int l2)
+
{
+
    const char *p;
+

+
    if (!l1 || !l2 || l1 > l2)
+
        return -1;
+

+

+
    for (p = s2 + l2 - 1; p != s2 - 1; p--) {
+
        if (*p == *s1 && memcmp(s1, p, l1) == 0) {
+
            return p - s2;
+
        }
+
    }
+
    return -1;
+
}
+

+
#ifdef JIM_UTF8
+
static int JimStringLastUtf8(const char *s1, int l1, const char *s2, int l2)
+
{
+
    int n = JimStringLast(s1, utf8_index(s1, l1), s2, utf8_index(s2, l2));
+
    if (n > 0) {
+
        n = utf8_strlen(s2, n);
+
    }
+
    return n;
+
}
+
#endif
+

+
static int JimCheckConversion(const char *str, const char *endptr)
+
{
+
    if (str[0] == '\0' || str == endptr) {
+
        return JIM_ERR;
+
    }
+

+
    if (endptr[0] != '\0') {
+
        while (*endptr) {
+
            if (!isspace(UCHAR(*endptr))) {
+
                return JIM_ERR;
+
            }
+
            endptr++;
+
        }
+
    }
+
    return JIM_OK;
+
}
+

+
static int JimNumberBase(const char *str, int *base, int *sign)
+
{
+
    int i = 0;
+

+
    *base = 10;
+

+
    while (isspace(UCHAR(str[i]))) {
+
        i++;
+
    }
+

+
    if (str[i] == '-') {
+
        *sign = -1;
+
        i++;
+
    }
+
    else {
+
        if (str[i] == '+') {
+
            i++;
+
        }
+
        *sign = 1;
+
    }
+

+
    if (str[i] != '0') {
+

+
        return 0;
+
    }
+

+

+
    switch (str[i + 1]) {
+
        case 'x': case 'X': *base = 16; break;
+
        case 'o': case 'O': *base = 8; break;
+
        case 'b': case 'B': *base = 2; break;
+
        default: return 0;
+
    }
+
    i += 2;
+

+
    if (str[i] != '-' && str[i] != '+' && !isspace(UCHAR(str[i]))) {
+

+
        return i;
+
    }
+

+
    *base = 10;
+
    return 0;
+
}
+

+
static long jim_strtol(const char *str, char **endptr)
+
{
+
    int sign;
+
    int base;
+
    int i = JimNumberBase(str, &base, &sign);
+

+
    if (base != 10) {
+
        long value = strtol(str + i, endptr, base);
+
        if (endptr == NULL || *endptr != str + i) {
+
            return value * sign;
+
        }
+
    }
+

+

+
    return strtol(str, endptr, 10);
+
}
+

+

+
static jim_wide jim_strtoull(const char *str, char **endptr)
+
{
+
#ifdef HAVE_LONG_LONG
+
    int sign;
+
    int base;
+
    int i = JimNumberBase(str, &base, &sign);
+

+
    if (base != 10) {
+
        jim_wide value = strtoull(str + i, endptr, base);
+
        if (endptr == NULL || *endptr != str + i) {
+
            return value * sign;
+
        }
+
    }
+

+

+
    return strtoull(str, endptr, 10);
+
#else
+
    return (unsigned long)jim_strtol(str, endptr);
+
#endif
+
}
+

+
int Jim_StringToWide(const char *str, jim_wide * widePtr, int base)
+
{
+
    char *endptr;
+

+
    if (base) {
+
        *widePtr = strtoull(str, &endptr, base);
+
    }
+
    else {
+
        *widePtr = jim_strtoull(str, &endptr);
+
    }
+

+
    return JimCheckConversion(str, endptr);
+
}
+

+
int Jim_StringToDouble(const char *str, double *doublePtr)
+
{
+
    char *endptr;
+

+

+
    errno = 0;
+

+
    *doublePtr = strtod(str, &endptr);
+

+
    return JimCheckConversion(str, endptr);
+
}
+

+
static jim_wide JimPowWide(jim_wide b, jim_wide e)
+
{
+
    jim_wide res = 1;
+

+

+
    if (b == 1) {
+

+
        return 1;
+
    }
+
    if (e < 0) {
+
        if (b != -1) {
+
            return 0;
+
        }
+
        e = -e;
+
    }
+
    while (e)
+
    {
+
        if (e & 1) {
+
            res *= b;
+
        }
+
        e >>= 1;
+
        b *= b;
+
    }
+
    return res;
+
}
+

+
#ifdef JIM_DEBUG_PANIC
+
static void JimPanicDump(int condition, const char *fmt, ...)
+
{
+
    va_list ap;
+

+
    if (!condition) {
+
        return;
+
    }
+

+
    va_start(ap, fmt);
+

+
    fprintf(stderr, "\nJIM INTERPRETER PANIC: ");
+
    vfprintf(stderr, fmt, ap);
+
    fprintf(stderr, "\n\n");
+
    va_end(ap);
+

+
#ifdef HAVE_BACKTRACE
+
    {
+
        void *array[40];
+
        int size, i;
+
        char **strings;
+

+
        size = backtrace(array, 40);
+
        strings = backtrace_symbols(array, size);
+
        for (i = 0; i < size; i++)
+
            fprintf(stderr, "[backtrace] %s\n", strings[i]);
+
        fprintf(stderr, "[backtrace] Include the above lines and the output\n");
+
        fprintf(stderr, "[backtrace] of 'nm <executable>' in the bug report.\n");
+
    }
+
#endif
+

+
    exit(1);
+
}
+
#endif
+

+

+
void *Jim_Alloc(int size)
+
{
+
    return size ? malloc(size) : NULL;
+
}
+

+
void Jim_Free(void *ptr)
+
{
+
    free(ptr);
+
}
+

+
void *Jim_Realloc(void *ptr, int size)
+
{
+
    return realloc(ptr, size);
+
}
+

+
char *Jim_StrDup(const char *s)
+
{
+
    return strdup(s);
+
}
+

+
char *Jim_StrDupLen(const char *s, int l)
+
{
+
    char *copy = Jim_Alloc(l + 1);
+

+
    memcpy(copy, s, l + 1);
+
    copy[l] = 0;
+
    return copy;
+
}
+

+

+

+
static jim_wide JimClock(void)
+
{
+
    struct timeval tv;
+

+
    gettimeofday(&tv, NULL);
+
    return (jim_wide) tv.tv_sec * 1000000 + tv.tv_usec;
+
}
+

+

+

+
static void JimExpandHashTableIfNeeded(Jim_HashTable *ht);
+
static unsigned int JimHashTableNextPower(unsigned int size);
+
static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace);
+

+

+

+

+
unsigned int Jim_IntHashFunction(unsigned int key)
+
{
+
    key += ~(key << 15);
+
    key ^= (key >> 10);
+
    key += (key << 3);
+
    key ^= (key >> 6);
+
    key += ~(key << 11);
+
    key ^= (key >> 16);
+
    return key;
+
}
+

+
unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)
+
{
+
    unsigned int h = 0;
+

+
    while (len--)
+
        h += (h << 3) + *buf++;
+
    return h;
+
}
+

+

+

+

+
static void JimResetHashTable(Jim_HashTable *ht)
+
{
+
    ht->table = NULL;
+
    ht->size = 0;
+
    ht->sizemask = 0;
+
    ht->used = 0;
+
    ht->collisions = 0;
+
#ifdef JIM_RANDOMISE_HASH
+
    ht->uniq = (rand() ^ time(NULL) ^ clock());
+
#else
+
    ht->uniq = 0;
+
#endif
+
}
+

+
static void JimInitHashTableIterator(Jim_HashTable *ht, Jim_HashTableIterator *iter)
+
{
+
    iter->ht = ht;
+
    iter->index = -1;
+
    iter->entry = NULL;
+
    iter->nextEntry = NULL;
+
}
+

+

+
int Jim_InitHashTable(Jim_HashTable *ht, const Jim_HashTableType *type, void *privDataPtr)
+
{
+
    JimResetHashTable(ht);
+
    ht->type = type;
+
    ht->privdata = privDataPtr;
+
    return JIM_OK;
+
}
+

+
void Jim_ResizeHashTable(Jim_HashTable *ht)
+
{
+
    int minimal = ht->used;
+

+
    if (minimal < JIM_HT_INITIAL_SIZE)
+
        minimal = JIM_HT_INITIAL_SIZE;
+
    Jim_ExpandHashTable(ht, minimal);
+
}
+

+

+
void Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
+
{
+
    Jim_HashTable n;
+
    unsigned int realsize = JimHashTableNextPower(size), i;
+

+
     if (size <= ht->used)
+
        return;
+

+
    Jim_InitHashTable(&n, ht->type, ht->privdata);
+
    n.size = realsize;
+
    n.sizemask = realsize - 1;
+
    n.table = Jim_Alloc(realsize * sizeof(Jim_HashEntry *));
+

+
    n.uniq = ht->uniq;
+

+

+
    memset(n.table, 0, realsize * sizeof(Jim_HashEntry *));
+

+
    n.used = ht->used;
+
    for (i = 0; ht->used > 0; i++) {
+
        Jim_HashEntry *he, *nextHe;
+

+
        if (ht->table[i] == NULL)
+
            continue;
+

+

+
        he = ht->table[i];
+
        while (he) {
+
            unsigned int h;
+

+
            nextHe = he->next;
+

+
            h = Jim_HashKey(ht, he->key) & n.sizemask;
+
            he->next = n.table[h];
+
            n.table[h] = he;
+
            ht->used--;
+

+
            he = nextHe;
+
        }
+
    }
+
    assert(ht->used == 0);
+
    Jim_Free(ht->table);
+

+

+
    *ht = n;
+
}
+

+

+
int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
+
{
+
    Jim_HashEntry *entry;
+

+
    entry = JimInsertHashEntry(ht, key, 0);
+
    if (entry == NULL)
+
        return JIM_ERR;
+

+

+
    Jim_SetHashKey(ht, entry, key);
+
    Jim_SetHashVal(ht, entry, val);
+
    return JIM_OK;
+
}
+

+

+
int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
+
{
+
    int existed;
+
    Jim_HashEntry *entry;
+

+
    entry = JimInsertHashEntry(ht, key, 1);
+
    if (entry->key) {
+
        if (ht->type->valDestructor && ht->type->valDup) {
+
            void *newval = ht->type->valDup(ht->privdata, val);
+
            ht->type->valDestructor(ht->privdata, entry->u.val);
+
            entry->u.val = newval;
+
        }
+
        else {
+
            Jim_FreeEntryVal(ht, entry);
+
            Jim_SetHashVal(ht, entry, val);
+
        }
+
        existed = 1;
+
    }
+
    else {
+

+
        Jim_SetHashKey(ht, entry, key);
+
        Jim_SetHashVal(ht, entry, val);
+
        existed = 0;
+
    }
+

+
    return existed;
+
}
+

+

+
int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
+
{
+
    unsigned int h;
+
    Jim_HashEntry *he, *prevHe;
+

+
    if (ht->used == 0)
+
        return JIM_ERR;
+
    h = Jim_HashKey(ht, key) & ht->sizemask;
+
    he = ht->table[h];
+

+
    prevHe = NULL;
+
    while (he) {
+
        if (Jim_CompareHashKeys(ht, key, he->key)) {
+

+
            if (prevHe)
+
                prevHe->next = he->next;
+
            else
+
                ht->table[h] = he->next;
+
            Jim_FreeEntryKey(ht, he);
+
            Jim_FreeEntryVal(ht, he);
+
            Jim_Free(he);
+
            ht->used--;
+
            return JIM_OK;
+
        }
+
        prevHe = he;
+
        he = he->next;
+
    }
+
    return JIM_ERR;
+
}
+

+

+
int Jim_FreeHashTable(Jim_HashTable *ht)
+
{
+
    unsigned int i;
+

+

+
    for (i = 0; ht->used > 0; i++) {
+
        Jim_HashEntry *he, *nextHe;
+

+
        if ((he = ht->table[i]) == NULL)
+
            continue;
+
        while (he) {
+
            nextHe = he->next;
+
            Jim_FreeEntryKey(ht, he);
+
            Jim_FreeEntryVal(ht, he);
+
            Jim_Free(he);
+
            ht->used--;
+
            he = nextHe;
+
        }
+
    }
+

+
    Jim_Free(ht->table);
+

+
    JimResetHashTable(ht);
+
    return JIM_OK;
+
}
+

+
Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
+
{
+
    Jim_HashEntry *he;
+
    unsigned int h;
+

+
    if (ht->used == 0)
+
        return NULL;
+
    h = Jim_HashKey(ht, key) & ht->sizemask;
+
    he = ht->table[h];
+
    while (he) {
+
        if (Jim_CompareHashKeys(ht, key, he->key))
+
            return he;
+
        he = he->next;
+
    }
+
    return NULL;
+
}
+

+
Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
+
{
+
    Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
+
    JimInitHashTableIterator(ht, iter);
+
    return iter;
+
}
+

+
Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
+
{
+
    while (1) {
+
        if (iter->entry == NULL) {
+
            iter->index++;
+
            if (iter->index >= (signed)iter->ht->size)
+
                break;
+
            iter->entry = iter->ht->table[iter->index];
+
        }
+
        else {
+
            iter->entry = iter->nextEntry;
+
        }
+
        if (iter->entry) {
+
            iter->nextEntry = iter->entry->next;
+
            return iter->entry;
+
        }
+
    }
+
    return NULL;
+
}
+

+

+

+

+
static void JimExpandHashTableIfNeeded(Jim_HashTable *ht)
+
{
+
    if (ht->size == 0)
+
        Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
+
    if (ht->size == ht->used)
+
        Jim_ExpandHashTable(ht, ht->size * 2);
+
}
+

+

+
static unsigned int JimHashTableNextPower(unsigned int size)
+
{
+
    unsigned int i = JIM_HT_INITIAL_SIZE;
+

+
    if (size >= 2147483648U)
+
        return 2147483648U;
+
    while (1) {
+
        if (i >= size)
+
            return i;
+
        i *= 2;
+
    }
+
}
+

+
static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace)
+
{
+
    unsigned int h;
+
    Jim_HashEntry *he;
+

+

+
    JimExpandHashTableIfNeeded(ht);
+

+

+
    h = Jim_HashKey(ht, key) & ht->sizemask;
+

+
    he = ht->table[h];
+
    while (he) {
+
        if (Jim_CompareHashKeys(ht, key, he->key))
+
            return replace ? he : NULL;
+
        he = he->next;
+
    }
+

+

+
    he = Jim_Alloc(sizeof(*he));
+
    he->next = ht->table[h];
+
    ht->table[h] = he;
+
    ht->used++;
+
    he->key = NULL;
+

+
    return he;
+
}
+

+

+

+
static unsigned int JimStringCopyHTHashFunction(const void *key)
+
{
+
    return Jim_GenHashFunction(key, strlen(key));
+
}
+

+
static void *JimStringCopyHTDup(void *privdata, const void *key)
+
{
+
    return Jim_StrDup(key);
+
}
+

+
static int JimStringCopyHTKeyCompare(void *privdata, const void *key1, const void *key2)
+
{
+
    return strcmp(key1, key2) == 0;
+
}
+

+
static void JimStringCopyHTKeyDestructor(void *privdata, void *key)
+
{
+
    Jim_Free(key);
+
}
+

+
static const Jim_HashTableType JimPackageHashTableType = {
+
    JimStringCopyHTHashFunction,
+
    JimStringCopyHTDup,
+
    NULL,
+
    JimStringCopyHTKeyCompare,
+
    JimStringCopyHTKeyDestructor,
+
    NULL
+
};
+

+
typedef struct AssocDataValue
+
{
+
    Jim_InterpDeleteProc *delProc;
+
    void *data;
+
} AssocDataValue;
+

+
static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
+
{
+
    AssocDataValue *assocPtr = (AssocDataValue *) data;
+

+
    if (assocPtr->delProc != NULL)
+
        assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
+
    Jim_Free(data);
+
}
+

+
static const Jim_HashTableType JimAssocDataHashTableType = {
+
    JimStringCopyHTHashFunction,
+
    JimStringCopyHTDup,
+
    NULL,
+
    JimStringCopyHTKeyCompare,
+
    JimStringCopyHTKeyDestructor,
+
    JimAssocDataHashTableValueDestructor
+
};
+

+
void Jim_InitStack(Jim_Stack *stack)
+
{
+
    stack->len = 0;
+
    stack->maxlen = 0;
+
    stack->vector = NULL;
+
}
+

+
void Jim_FreeStack(Jim_Stack *stack)
+
{
+
    Jim_Free(stack->vector);
+
}
+

+
int Jim_StackLen(Jim_Stack *stack)
+
{
+
    return stack->len;
+
}
+

+
void Jim_StackPush(Jim_Stack *stack, void *element)
+
{
+
    int neededLen = stack->len + 1;
+

+
    if (neededLen > stack->maxlen) {
+
        stack->maxlen = neededLen < 20 ? 20 : neededLen * 2;
+
        stack->vector = Jim_Realloc(stack->vector, sizeof(void *) * stack->maxlen);
+
    }
+
    stack->vector[stack->len] = element;
+
    stack->len++;
+
}
+

+
void *Jim_StackPop(Jim_Stack *stack)
+
{
+
    if (stack->len == 0)
+
        return NULL;
+
    stack->len--;
+
    return stack->vector[stack->len];
+
}
+

+
void *Jim_StackPeek(Jim_Stack *stack)
+
{
+
    if (stack->len == 0)
+
        return NULL;
+
    return stack->vector[stack->len - 1];
+
}
+

+
void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc) (void *ptr))
+
{
+
    int i;
+

+
    for (i = 0; i < stack->len; i++)
+
        freeFunc(stack->vector[i]);
+
}
+

+

+

+
#define JIM_TT_NONE    0
+
#define JIM_TT_STR     1
+
#define JIM_TT_ESC     2
+
#define JIM_TT_VAR     3
+
#define JIM_TT_DICTSUGAR   4
+
#define JIM_TT_CMD     5
+

+
#define JIM_TT_SEP     6
+
#define JIM_TT_EOL     7
+
#define JIM_TT_EOF     8
+

+
#define JIM_TT_LINE    9
+
#define JIM_TT_WORD   10
+

+

+
#define JIM_TT_SUBEXPR_START  11
+
#define JIM_TT_SUBEXPR_END    12
+
#define JIM_TT_SUBEXPR_COMMA  13
+
#define JIM_TT_EXPR_INT       14
+
#define JIM_TT_EXPR_DOUBLE    15
+
#define JIM_TT_EXPR_BOOLEAN   16
+

+
#define JIM_TT_EXPRSUGAR      17
+

+

+
#define JIM_TT_EXPR_OP        20
+

+
#define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
+

+
#define TOKEN_IS_EXPR_START(type) (type == JIM_TT_NONE || type == JIM_TT_SUBEXPR_START || type == JIM_TT_SUBEXPR_COMMA)
+

+
#define TOKEN_IS_EXPR_OP(type) (type >= JIM_TT_EXPR_OP)
+

+
struct JimParseMissing {
+
    int ch;
+
    int line;
+
};
+

+
struct JimParserCtx
+
{
+
    const char *p;
+
    int len;
+
    int linenr;
+
    const char *tstart;
+
    const char *tend;
+
    int tline;
+
    int tt;
+
    int eof;
+
    int inquote;
+
    int comment;
+
    struct JimParseMissing missing;
+
};
+

+
static int JimParseScript(struct JimParserCtx *pc);
+
static int JimParseSep(struct JimParserCtx *pc);
+
static int JimParseEol(struct JimParserCtx *pc);
+
static int JimParseCmd(struct JimParserCtx *pc);
+
static int JimParseQuote(struct JimParserCtx *pc);
+
static int JimParseVar(struct JimParserCtx *pc);
+
static int JimParseBrace(struct JimParserCtx *pc);
+
static int JimParseStr(struct JimParserCtx *pc);
+
static int JimParseComment(struct JimParserCtx *pc);
+
static void JimParseSubCmd(struct JimParserCtx *pc);
+
static int JimParseSubQuote(struct JimParserCtx *pc);
+
static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc);
+

+
static void JimParserInit(struct JimParserCtx *pc, const char *prg, int len, int linenr)
+
{
+
    pc->p = prg;
+
    pc->len = len;
+
    pc->tstart = NULL;
+
    pc->tend = NULL;
+
    pc->tline = 0;
+
    pc->tt = JIM_TT_NONE;
+
    pc->eof = 0;
+
    pc->inquote = 0;
+
    pc->linenr = linenr;
+
    pc->comment = 1;
+
    pc->missing.ch = ' ';
+
    pc->missing.line = linenr;
+
}
+

+
static int JimParseScript(struct JimParserCtx *pc)
+
{
+
    while (1) {
+
        if (!pc->len) {
+
            pc->tstart = pc->p;
+
            pc->tend = pc->p - 1;
+
            pc->tline = pc->linenr;
+
            pc->tt = JIM_TT_EOL;
+
            pc->eof = 1;
+
            return JIM_OK;
+
        }
+
        switch (*(pc->p)) {
+
            case '\\':
+
                if (*(pc->p + 1) == '\n' && !pc->inquote) {
+
                    return JimParseSep(pc);
+
                }
+
                pc->comment = 0;
+
                return JimParseStr(pc);
+
            case ' ':
+
            case '\t':
+
            case '\r':
+
            case '\f':
+
                if (!pc->inquote)
+
                    return JimParseSep(pc);
+
                pc->comment = 0;
+
                return JimParseStr(pc);
+
            case '\n':
+
            case ';':
+
                pc->comment = 1;
+
                if (!pc->inquote)
+
                    return JimParseEol(pc);
+
                return JimParseStr(pc);
+
            case '[':
+
                pc->comment = 0;
+
                return JimParseCmd(pc);
+
            case '$':
+
                pc->comment = 0;
+
                if (JimParseVar(pc) == JIM_ERR) {
+

+
                    pc->tstart = pc->tend = pc->p++;
+
                    pc->len--;
+
                    pc->tt = JIM_TT_ESC;
+
                }
+
                return JIM_OK;
+
            case '#':
+
                if (pc->comment) {
+
                    JimParseComment(pc);
+
                    continue;
+
                }
+
                return JimParseStr(pc);
+
            default:
+
                pc->comment = 0;
+
                return JimParseStr(pc);
+
        }
+
        return JIM_OK;
+
    }
+
}
+

+
static int JimParseSep(struct JimParserCtx *pc)
+
{
+
    pc->tstart = pc->p;
+
    pc->tline = pc->linenr;
+
    while (isspace(UCHAR(*pc->p)) || (*pc->p == '\\' && *(pc->p + 1) == '\n')) {
+
        if (*pc->p == '\n') {
+
            break;
+
        }
+
        if (*pc->p == '\\') {
+
            pc->p++;
+
            pc->len--;
+
            pc->linenr++;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+
    pc->tend = pc->p - 1;
+
    pc->tt = JIM_TT_SEP;
+
    return JIM_OK;
+
}
+

+
static int JimParseEol(struct JimParserCtx *pc)
+
{
+
    pc->tstart = pc->p;
+
    pc->tline = pc->linenr;
+
    while (isspace(UCHAR(*pc->p)) || *pc->p == ';') {
+
        if (*pc->p == '\n')
+
            pc->linenr++;
+
        pc->p++;
+
        pc->len--;
+
    }
+
    pc->tend = pc->p - 1;
+
    pc->tt = JIM_TT_EOL;
+
    return JIM_OK;
+
}
+

+

+
static void JimParseSubBrace(struct JimParserCtx *pc)
+
{
+
    int level = 1;
+

+

+
    pc->p++;
+
    pc->len--;
+
    while (pc->len) {
+
        switch (*pc->p) {
+
            case '\\':
+
                if (pc->len > 1) {
+
                    if (*++pc->p == '\n') {
+
                        pc->linenr++;
+
                    }
+
                    pc->len--;
+
                }
+
                break;
+

+
            case '{':
+
                level++;
+
                break;
+

+
            case '}':
+
                if (--level == 0) {
+
                    pc->tend = pc->p - 1;
+
                    pc->p++;
+
                    pc->len--;
+
                    return;
+
                }
+
                break;
+

+
            case '\n':
+
                pc->linenr++;
+
                break;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+
    pc->missing.ch = '{';
+
    pc->missing.line = pc->tline;
+
    pc->tend = pc->p - 1;
+
}
+

+
static int JimParseSubQuote(struct JimParserCtx *pc)
+
{
+
    int tt = JIM_TT_STR;
+
    int line = pc->tline;
+

+

+
    pc->p++;
+
    pc->len--;
+
    while (pc->len) {
+
        switch (*pc->p) {
+
            case '\\':
+
                if (pc->len > 1) {
+
                    if (*++pc->p == '\n') {
+
                        pc->linenr++;
+
                    }
+
                    pc->len--;
+
                    tt = JIM_TT_ESC;
+
                }
+
                break;
+

+
            case '"':
+
                pc->tend = pc->p - 1;
+
                pc->p++;
+
                pc->len--;
+
                return tt;
+

+
            case '[':
+
                JimParseSubCmd(pc);
+
                tt = JIM_TT_ESC;
+
                continue;
+

+
            case '\n':
+
                pc->linenr++;
+
                break;
+

+
            case '$':
+
                tt = JIM_TT_ESC;
+
                break;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+
    pc->missing.ch = '"';
+
    pc->missing.line = line;
+
    pc->tend = pc->p - 1;
+
    return tt;
+
}
+

+
static void JimParseSubCmd(struct JimParserCtx *pc)
+
{
+
    int level = 1;
+
    int startofword = 1;
+
    int line = pc->tline;
+

+

+
    pc->p++;
+
    pc->len--;
+
    while (pc->len) {
+
        switch (*pc->p) {
+
            case '\\':
+
                if (pc->len > 1) {
+
                    if (*++pc->p == '\n') {
+
                        pc->linenr++;
+
                    }
+
                    pc->len--;
+
                }
+
                break;
+

+
            case '[':
+
                level++;
+
                break;
+

+
            case ']':
+
                if (--level == 0) {
+
                    pc->tend = pc->p - 1;
+
                    pc->p++;
+
                    pc->len--;
+
                    return;
+
                }
+
                break;
+

+
            case '"':
+
                if (startofword) {
+
                    JimParseSubQuote(pc);
+
                    continue;
+
                }
+
                break;
+

+
            case '{':
+
                JimParseSubBrace(pc);
+
                startofword = 0;
+
                continue;
+

+
            case '\n':
+
                pc->linenr++;
+
                break;
+
        }
+
        startofword = isspace(UCHAR(*pc->p));
+
        pc->p++;
+
        pc->len--;
+
    }
+
    pc->missing.ch = '[';
+
    pc->missing.line = line;
+
    pc->tend = pc->p - 1;
+
}
+

+
static int JimParseBrace(struct JimParserCtx *pc)
+
{
+
    pc->tstart = pc->p + 1;
+
    pc->tline = pc->linenr;
+
    pc->tt = JIM_TT_STR;
+
    JimParseSubBrace(pc);
+
    return JIM_OK;
+
}
+

+
static int JimParseCmd(struct JimParserCtx *pc)
+
{
+
    pc->tstart = pc->p + 1;
+
    pc->tline = pc->linenr;
+
    pc->tt = JIM_TT_CMD;
+
    JimParseSubCmd(pc);
+
    return JIM_OK;
+
}
+

+
static int JimParseQuote(struct JimParserCtx *pc)
+
{
+
    pc->tstart = pc->p + 1;
+
    pc->tline = pc->linenr;
+
    pc->tt = JimParseSubQuote(pc);
+
    return JIM_OK;
+
}
+

+
static int JimParseVar(struct JimParserCtx *pc)
+
{
+

+
    pc->p++;
+
    pc->len--;
+

+
#ifdef EXPRSUGAR_BRACKET
+
    if (*pc->p == '[') {
+

+
        JimParseCmd(pc);
+
        pc->tt = JIM_TT_EXPRSUGAR;
+
        return JIM_OK;
+
    }
+
#endif
+

+
    pc->tstart = pc->p;
+
    pc->tt = JIM_TT_VAR;
+
    pc->tline = pc->linenr;
+

+
    if (*pc->p == '{') {
+
        pc->tstart = ++pc->p;
+
        pc->len--;
+

+
        while (pc->len && *pc->p != '}') {
+
            if (*pc->p == '\n') {
+
                pc->linenr++;
+
            }
+
            pc->p++;
+
            pc->len--;
+
        }
+
        pc->tend = pc->p - 1;
+
        if (pc->len) {
+
            pc->p++;
+
            pc->len--;
+
        }
+
    }
+
    else {
+
        while (1) {
+

+
            if (pc->p[0] == ':' && pc->p[1] == ':') {
+
                while (*pc->p == ':') {
+
                    pc->p++;
+
                    pc->len--;
+
                }
+
                continue;
+
            }
+
            if (isalnum(UCHAR(*pc->p)) || *pc->p == '_' || UCHAR(*pc->p) >= 0x80) {
+
                pc->p++;
+
                pc->len--;
+
                continue;
+
            }
+
            break;
+
        }
+

+
        if (*pc->p == '(') {
+
            int count = 1;
+
            const char *paren = NULL;
+

+
            pc->tt = JIM_TT_DICTSUGAR;
+

+
            while (count && pc->len) {
+
                pc->p++;
+
                pc->len--;
+
                if (*pc->p == '\\' && pc->len >= 1) {
+
                    pc->p++;
+
                    pc->len--;
+
                }
+
                else if (*pc->p == '(') {
+
                    count++;
+
                }
+
                else if (*pc->p == ')') {
+
                    paren = pc->p;
+
                    count--;
+
                }
+
            }
+
            if (count == 0) {
+
                pc->p++;
+
                pc->len--;
+
            }
+
            else if (paren) {
+

+
                paren++;
+
                pc->len += (pc->p - paren);
+
                pc->p = paren;
+
            }
+
#ifndef EXPRSUGAR_BRACKET
+
            if (*pc->tstart == '(') {
+
                pc->tt = JIM_TT_EXPRSUGAR;
+
            }
+
#endif
+
        }
+
        pc->tend = pc->p - 1;
+
    }
+
    if (pc->tstart == pc->p) {
+
        pc->p--;
+
        pc->len++;
+
        return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+
static int JimParseStr(struct JimParserCtx *pc)
+
{
+
    if (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
+
        pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR) {
+

+
        if (*pc->p == '{') {
+
            return JimParseBrace(pc);
+
        }
+
        if (*pc->p == '"') {
+
            pc->inquote = 1;
+
            pc->p++;
+
            pc->len--;
+

+
            pc->missing.line = pc->tline;
+
        }
+
    }
+
    pc->tstart = pc->p;
+
    pc->tline = pc->linenr;
+
    while (1) {
+
        if (pc->len == 0) {
+
            if (pc->inquote) {
+
                pc->missing.ch = '"';
+
            }
+
            pc->tend = pc->p - 1;
+
            pc->tt = JIM_TT_ESC;
+
            return JIM_OK;
+
        }
+
        switch (*pc->p) {
+
            case '\\':
+
                if (!pc->inquote && *(pc->p + 1) == '\n') {
+
                    pc->tend = pc->p - 1;
+
                    pc->tt = JIM_TT_ESC;
+
                    return JIM_OK;
+
                }
+
                if (pc->len >= 2) {
+
                    if (*(pc->p + 1) == '\n') {
+
                        pc->linenr++;
+
                    }
+
                    pc->p++;
+
                    pc->len--;
+
                }
+
                else if (pc->len == 1) {
+

+
                    pc->missing.ch = '\\';
+
                }
+
                break;
+
            case '(':
+

+
                if (pc->len > 1 && pc->p[1] != '$') {
+
                    break;
+
                }
+

+
            case ')':
+

+
                if (*pc->p == '(' || pc->tt == JIM_TT_VAR) {
+
                    if (pc->p == pc->tstart) {
+

+
                        pc->p++;
+
                        pc->len--;
+
                    }
+
                    pc->tend = pc->p - 1;
+
                    pc->tt = JIM_TT_ESC;
+
                    return JIM_OK;
+
                }
+
                break;
+

+
            case '$':
+
            case '[':
+
                pc->tend = pc->p - 1;
+
                pc->tt = JIM_TT_ESC;
+
                return JIM_OK;
+
            case ' ':
+
            case '\t':
+
            case '\n':
+
            case '\r':
+
            case '\f':
+
            case ';':
+
                if (!pc->inquote) {
+
                    pc->tend = pc->p - 1;
+
                    pc->tt = JIM_TT_ESC;
+
                    return JIM_OK;
+
                }
+
                else if (*pc->p == '\n') {
+
                    pc->linenr++;
+
                }
+
                break;
+
            case '"':
+
                if (pc->inquote) {
+
                    pc->tend = pc->p - 1;
+
                    pc->tt = JIM_TT_ESC;
+
                    pc->p++;
+
                    pc->len--;
+
                    pc->inquote = 0;
+
                    return JIM_OK;
+
                }
+
                break;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+
    return JIM_OK;
+
}
+

+
static int JimParseComment(struct JimParserCtx *pc)
+
{
+
    while (*pc->p) {
+
        if (*pc->p == '\\') {
+
            pc->p++;
+
            pc->len--;
+
            if (pc->len == 0) {
+
                pc->missing.ch = '\\';
+
                return JIM_OK;
+
            }
+
            if (*pc->p == '\n') {
+
                pc->linenr++;
+
            }
+
        }
+
        else if (*pc->p == '\n') {
+
            pc->p++;
+
            pc->len--;
+
            pc->linenr++;
+
            break;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+
    return JIM_OK;
+
}
+

+

+
static int xdigitval(int c)
+
{
+
    if (c >= '0' && c <= '9')
+
        return c - '0';
+
    if (c >= 'a' && c <= 'f')
+
        return c - 'a' + 10;
+
    if (c >= 'A' && c <= 'F')
+
        return c - 'A' + 10;
+
    return -1;
+
}
+

+
static int odigitval(int c)
+
{
+
    if (c >= '0' && c <= '7')
+
        return c - '0';
+
    return -1;
+
}
+

+
static int JimEscape(char *dest, const char *s, int slen)
+
{
+
    char *p = dest;
+
    int i, len;
+

+
    for (i = 0; i < slen; i++) {
+
        switch (s[i]) {
+
            case '\\':
+
                switch (s[i + 1]) {
+
                    case 'a':
+
                        *p++ = 0x7;
+
                        i++;
+
                        break;
+
                    case 'b':
+
                        *p++ = 0x8;
+
                        i++;
+
                        break;
+
                    case 'f':
+
                        *p++ = 0xc;
+
                        i++;
+
                        break;
+
                    case 'n':
+
                        *p++ = 0xa;
+
                        i++;
+
                        break;
+
                    case 'r':
+
                        *p++ = 0xd;
+
                        i++;
+
                        break;
+
                    case 't':
+
                        *p++ = 0x9;
+
                        i++;
+
                        break;
+
                    case 'u':
+
                    case 'U':
+
                    case 'x':
+
                        {
+
                            unsigned val = 0;
+
                            int k;
+
                            int maxchars = 2;
+

+
                            i++;
+

+
                            if (s[i] == 'U') {
+
                                maxchars = 8;
+
                            }
+
                            else if (s[i] == 'u') {
+
                                if (s[i + 1] == '{') {
+
                                    maxchars = 6;
+
                                    i++;
+
                                }
+
                                else {
+
                                    maxchars = 4;
+
                                }
+
                            }
+

+
                            for (k = 0; k < maxchars; k++) {
+
                                int c = xdigitval(s[i + k + 1]);
+
                                if (c == -1) {
+
                                    break;
+
                                }
+
                                val = (val << 4) | c;
+
                            }
+

+
                            if (s[i] == '{') {
+
                                if (k == 0 || val > 0x1fffff || s[i + k + 1] != '}') {
+

+
                                    i--;
+
                                    k = 0;
+
                                }
+
                                else {
+

+
                                    k++;
+
                                }
+
                            }
+
                            if (k) {
+

+
                                if (s[i] == 'x') {
+
                                    *p++ = val;
+
                                }
+
                                else {
+
                                    p += utf8_fromunicode(p, val);
+
                                }
+
                                i += k;
+
                                break;
+
                            }
+

+
                            *p++ = s[i];
+
                        }
+
                        break;
+
                    case 'v':
+
                        *p++ = 0xb;
+
                        i++;
+
                        break;
+
                    case '\0':
+
                        *p++ = '\\';
+
                        i++;
+
                        break;
+
                    case '\n':
+

+
                        *p++ = ' ';
+
                        do {
+
                            i++;
+
                        } while (s[i + 1] == ' ' || s[i + 1] == '\t');
+
                        break;
+
                    case '0':
+
                    case '1':
+
                    case '2':
+
                    case '3':
+
                    case '4':
+
                    case '5':
+
                    case '6':
+
                    case '7':
+

+
                        {
+
                            int val = 0;
+
                            int c = odigitval(s[i + 1]);
+

+
                            val = c;
+
                            c = odigitval(s[i + 2]);
+
                            if (c == -1) {
+
                                *p++ = val;
+
                                i++;
+
                                break;
+
                            }
+
                            val = (val * 8) + c;
+
                            c = odigitval(s[i + 3]);
+
                            if (c == -1) {
+
                                *p++ = val;
+
                                i += 2;
+
                                break;
+
                            }
+
                            val = (val * 8) + c;
+
                            *p++ = val;
+
                            i += 3;
+
                        }
+
                        break;
+
                    default:
+
                        *p++ = s[i + 1];
+
                        i++;
+
                        break;
+
                }
+
                break;
+
            default:
+
                *p++ = s[i];
+
                break;
+
        }
+
    }
+
    len = p - dest;
+
    *p = '\0';
+
    return len;
+
}
+

+
static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc)
+
{
+
    const char *start, *end;
+
    char *token;
+
    int len;
+

+
    start = pc->tstart;
+
    end = pc->tend;
+
    if (start > end) {
+
        len = 0;
+
        token = Jim_Alloc(1);
+
        token[0] = '\0';
+
    }
+
    else {
+
        len = (end - start) + 1;
+
        token = Jim_Alloc(len + 1);
+
        if (pc->tt != JIM_TT_ESC) {
+

+
            memcpy(token, start, len);
+
            token[len] = '\0';
+
        }
+
        else {
+

+
            len = JimEscape(token, start, len);
+
        }
+
    }
+

+
    return Jim_NewStringObjNoAlloc(interp, token, len);
+
}
+

+
static int JimParseListSep(struct JimParserCtx *pc);
+
static int JimParseListStr(struct JimParserCtx *pc);
+
static int JimParseListQuote(struct JimParserCtx *pc);
+

+
static int JimParseList(struct JimParserCtx *pc)
+
{
+
    if (isspace(UCHAR(*pc->p))) {
+
        return JimParseListSep(pc);
+
    }
+
    switch (*pc->p) {
+
        case '"':
+
            return JimParseListQuote(pc);
+

+
        case '{':
+
            return JimParseBrace(pc);
+

+
        default:
+
            if (pc->len) {
+
                return JimParseListStr(pc);
+
            }
+
            break;
+
    }
+

+
    pc->tstart = pc->tend = pc->p;
+
    pc->tline = pc->linenr;
+
    pc->tt = JIM_TT_EOL;
+
    pc->eof = 1;
+
    return JIM_OK;
+
}
+

+
static int JimParseListSep(struct JimParserCtx *pc)
+
{
+
    pc->tstart = pc->p;
+
    pc->tline = pc->linenr;
+
    while (isspace(UCHAR(*pc->p))) {
+
        if (*pc->p == '\n') {
+
            pc->linenr++;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+
    pc->tend = pc->p - 1;
+
    pc->tt = JIM_TT_SEP;
+
    return JIM_OK;
+
}
+

+
static int JimParseListQuote(struct JimParserCtx *pc)
+
{
+
    pc->p++;
+
    pc->len--;
+

+
    pc->tstart = pc->p;
+
    pc->tline = pc->linenr;
+
    pc->tt = JIM_TT_STR;
+

+
    while (pc->len) {
+
        switch (*pc->p) {
+
            case '\\':
+
                pc->tt = JIM_TT_ESC;
+
                if (--pc->len == 0) {
+

+
                    pc->tend = pc->p;
+
                    return JIM_OK;
+
                }
+
                pc->p++;
+
                break;
+
            case '\n':
+
                pc->linenr++;
+
                break;
+
            case '"':
+
                pc->tend = pc->p - 1;
+
                pc->p++;
+
                pc->len--;
+
                return JIM_OK;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+

+
    pc->tend = pc->p - 1;
+
    return JIM_OK;
+
}
+

+
static int JimParseListStr(struct JimParserCtx *pc)
+
{
+
    pc->tstart = pc->p;
+
    pc->tline = pc->linenr;
+
    pc->tt = JIM_TT_STR;
+

+
    while (pc->len) {
+
        if (isspace(UCHAR(*pc->p))) {
+
            pc->tend = pc->p - 1;
+
            return JIM_OK;
+
        }
+
        if (*pc->p == '\\') {
+
            if (--pc->len == 0) {
+

+
                pc->tend = pc->p;
+
                return JIM_OK;
+
            }
+
            pc->tt = JIM_TT_ESC;
+
            pc->p++;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+
    pc->tend = pc->p - 1;
+
    return JIM_OK;
+
}
+

+

+

+
Jim_Obj *Jim_NewObj(Jim_Interp *interp)
+
{
+
    Jim_Obj *objPtr;
+

+

+
    if (interp->freeList != NULL) {
+

+
        objPtr = interp->freeList;
+
        interp->freeList = objPtr->nextObjPtr;
+
    }
+
    else {
+

+
        objPtr = Jim_Alloc(sizeof(*objPtr));
+
    }
+

+
    objPtr->refCount = 0;
+

+

+
    objPtr->prevObjPtr = NULL;
+
    objPtr->nextObjPtr = interp->liveList;
+
    if (interp->liveList)
+
        interp->liveList->prevObjPtr = objPtr;
+
    interp->liveList = objPtr;
+

+
    return objPtr;
+
}
+

+
void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+

+
    JimPanic((objPtr->refCount != 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr,
+
        objPtr->refCount, objPtr->typePtr ? objPtr->typePtr->name : "<none>"));
+

+

+
    Jim_FreeIntRep(interp, objPtr);
+

+
    if (objPtr->bytes != NULL) {
+
        if (objPtr->bytes != JimEmptyStringRep)
+
            Jim_Free(objPtr->bytes);
+
    }
+

+
    if (objPtr->prevObjPtr)
+
        objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
+
    if (objPtr->nextObjPtr)
+
        objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
+
    if (interp->liveList == objPtr)
+
        interp->liveList = objPtr->nextObjPtr;
+
#ifdef JIM_DISABLE_OBJECT_POOL
+
    Jim_Free(objPtr);
+
#else
+

+
    objPtr->prevObjPtr = NULL;
+
    objPtr->nextObjPtr = interp->freeList;
+
    if (interp->freeList)
+
        interp->freeList->prevObjPtr = objPtr;
+
    interp->freeList = objPtr;
+
    objPtr->refCount = -1;
+
#endif
+
}
+

+

+
void Jim_InvalidateStringRep(Jim_Obj *objPtr)
+
{
+
    if (objPtr->bytes != NULL) {
+
        if (objPtr->bytes != JimEmptyStringRep)
+
            Jim_Free(objPtr->bytes);
+
    }
+
    objPtr->bytes = NULL;
+
}
+

+

+
Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    Jim_Obj *dupPtr;
+

+
    dupPtr = Jim_NewObj(interp);
+
    if (objPtr->bytes == NULL) {
+

+
        dupPtr->bytes = NULL;
+
    }
+
    else if (objPtr->length == 0) {
+

+
        dupPtr->bytes = JimEmptyStringRep;
+
        dupPtr->length = 0;
+
        dupPtr->typePtr = NULL;
+
        return dupPtr;
+
    }
+
    else {
+
        dupPtr->bytes = Jim_Alloc(objPtr->length + 1);
+
        dupPtr->length = objPtr->length;
+

+
        memcpy(dupPtr->bytes, objPtr->bytes, objPtr->length + 1);
+
    }
+

+

+
    dupPtr->typePtr = objPtr->typePtr;
+
    if (objPtr->typePtr != NULL) {
+
        if (objPtr->typePtr->dupIntRepProc == NULL) {
+
            dupPtr->internalRep = objPtr->internalRep;
+
        }
+
        else {
+

+
            objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
+
        }
+
    }
+
    return dupPtr;
+
}
+

+
const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
+
{
+
    if (objPtr->bytes == NULL) {
+

+
        JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
+
        objPtr->typePtr->updateStringProc(objPtr);
+
    }
+
    if (lenPtr)
+
        *lenPtr = objPtr->length;
+
    return objPtr->bytes;
+
}
+

+

+
int Jim_Length(Jim_Obj *objPtr)
+
{
+
    if (objPtr->bytes == NULL) {
+

+
        JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
+
        objPtr->typePtr->updateStringProc(objPtr);
+
    }
+
    return objPtr->length;
+
}
+

+

+
const char *Jim_String(Jim_Obj *objPtr)
+
{
+
    if (objPtr->bytes == NULL) {
+

+
        JimPanic((objPtr->typePtr == NULL, "UpdateStringProc called against typeless value."));
+
        JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
+
        objPtr->typePtr->updateStringProc(objPtr);
+
    }
+
    return objPtr->bytes;
+
}
+

+
static void JimSetStringBytes(Jim_Obj *objPtr, const char *str)
+
{
+
    objPtr->bytes = Jim_StrDup(str);
+
    objPtr->length = strlen(str);
+
}
+

+
static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+
static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+

+
static const Jim_ObjType dictSubstObjType = {
+
    "dict-substitution",
+
    FreeDictSubstInternalRep,
+
    DupDictSubstInternalRep,
+
    NULL,
+
    JIM_TYPE_NONE,
+
};
+

+
static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
+
}
+

+
static const Jim_ObjType interpolatedObjType = {
+
    "interpolated",
+
    FreeInterpolatedInternalRep,
+
    NULL,
+
    NULL,
+
    JIM_TYPE_NONE,
+
};
+

+
static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+

+
static const Jim_ObjType stringObjType = {
+
    "string",
+
    NULL,
+
    DupStringInternalRep,
+
    NULL,
+
    JIM_TYPE_REFERENCES,
+
};
+

+
static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    JIM_NOTUSED(interp);
+

+
    dupPtr->internalRep.strValue.maxLength = srcPtr->length;
+
    dupPtr->internalRep.strValue.charLength = srcPtr->internalRep.strValue.charLength;
+
}
+

+
static int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    if (objPtr->typePtr != &stringObjType) {
+

+
        if (objPtr->bytes == NULL) {
+

+
            JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
+
            objPtr->typePtr->updateStringProc(objPtr);
+
        }
+

+
        Jim_FreeIntRep(interp, objPtr);
+

+
        objPtr->typePtr = &stringObjType;
+
        objPtr->internalRep.strValue.maxLength = objPtr->length;
+

+
        objPtr->internalRep.strValue.charLength = -1;
+
    }
+
    return JIM_OK;
+
}
+

+
int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
#ifdef JIM_UTF8
+
    SetStringFromAny(interp, objPtr);
+

+
    if (objPtr->internalRep.strValue.charLength < 0) {
+
        objPtr->internalRep.strValue.charLength = utf8_strlen(objPtr->bytes, objPtr->length);
+
    }
+
    return objPtr->internalRep.strValue.charLength;
+
#else
+
    return Jim_Length(objPtr);
+
#endif
+
}
+

+

+
Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
+
{
+
    Jim_Obj *objPtr = Jim_NewObj(interp);
+

+

+
    if (len == -1)
+
        len = strlen(s);
+

+
    if (len == 0) {
+
        objPtr->bytes = JimEmptyStringRep;
+
    }
+
    else {
+
        objPtr->bytes = Jim_Alloc(len + 1);
+
        memcpy(objPtr->bytes, s, len);
+
        objPtr->bytes[len] = '\0';
+
    }
+
    objPtr->length = len;
+

+

+
    objPtr->typePtr = NULL;
+
    return objPtr;
+
}
+

+

+
Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp, const char *s, int charlen)
+
{
+
#ifdef JIM_UTF8
+

+
    int bytelen = utf8_index(s, charlen);
+

+
    Jim_Obj *objPtr = Jim_NewStringObj(interp, s, bytelen);
+

+

+
    objPtr->typePtr = &stringObjType;
+
    objPtr->internalRep.strValue.maxLength = bytelen;
+
    objPtr->internalRep.strValue.charLength = charlen;
+

+
    return objPtr;
+
#else
+
    return Jim_NewStringObj(interp, s, charlen);
+
#endif
+
}
+

+
Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
+
{
+
    Jim_Obj *objPtr = Jim_NewObj(interp);
+

+
    objPtr->bytes = s;
+
    objPtr->length = (len == -1) ? strlen(s) : len;
+
    objPtr->typePtr = NULL;
+
    return objPtr;
+
}
+

+
static void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
+
{
+
    int needlen;
+

+
    if (len == -1)
+
        len = strlen(str);
+
    needlen = objPtr->length + len;
+
    if (objPtr->internalRep.strValue.maxLength < needlen ||
+
        objPtr->internalRep.strValue.maxLength == 0) {
+
        needlen *= 2;
+

+
        if (needlen < 7) {
+
            needlen = 7;
+
        }
+
        if (objPtr->bytes == JimEmptyStringRep) {
+
            objPtr->bytes = Jim_Alloc(needlen + 1);
+
        }
+
        else {
+
            objPtr->bytes = Jim_Realloc(objPtr->bytes, needlen + 1);
+
        }
+
        objPtr->internalRep.strValue.maxLength = needlen;
+
    }
+
    memcpy(objPtr->bytes + objPtr->length, str, len);
+
    objPtr->bytes[objPtr->length + len] = '\0';
+

+
    if (objPtr->internalRep.strValue.charLength >= 0) {
+

+
        objPtr->internalRep.strValue.charLength += utf8_strlen(objPtr->bytes + objPtr->length, len);
+
    }
+
    objPtr->length += len;
+
}
+

+
void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str, int len)
+
{
+
    JimPanic((Jim_IsShared(objPtr), "Jim_AppendString called with shared object"));
+
    SetStringFromAny(interp, objPtr);
+
    StringAppendString(objPtr, str, len);
+
}
+

+
void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
+
{
+
    int len;
+
    const char *str = Jim_GetString(appendObjPtr, &len);
+
    Jim_AppendString(interp, objPtr, str, len);
+
}
+

+
void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
+
{
+
    va_list ap;
+

+
    SetStringFromAny(interp, objPtr);
+
    va_start(ap, objPtr);
+
    while (1) {
+
        const char *s = va_arg(ap, const char *);
+

+
        if (s == NULL)
+
            break;
+
        Jim_AppendString(interp, objPtr, s, -1);
+
    }
+
    va_end(ap);
+
}
+

+
int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr)
+
{
+
    if (aObjPtr == bObjPtr) {
+
        return 1;
+
    }
+
    else {
+
        int Alen, Blen;
+
        const char *sA = Jim_GetString(aObjPtr, &Alen);
+
        const char *sB = Jim_GetString(bObjPtr, &Blen);
+

+
        return Alen == Blen && memcmp(sA, sB, Alen) == 0;
+
    }
+
}
+

+
int Jim_StringMatchObj(Jim_Interp *interp, Jim_Obj *patternObjPtr, Jim_Obj *objPtr, int nocase)
+
{
+
    return JimGlobMatch(Jim_String(patternObjPtr), Jim_String(objPtr), nocase);
+
}
+

+
int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
+
{
+
    int l1, l2;
+
    const char *s1 = Jim_GetString(firstObjPtr, &l1);
+
    const char *s2 = Jim_GetString(secondObjPtr, &l2);
+

+
    if (nocase) {
+

+
        return JimStringCompareLen(s1, s2, -1, nocase);
+
    }
+
    return JimStringCompare(s1, l1, s2, l2);
+
}
+

+
int Jim_StringCompareLenObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
+
{
+
    const char *s1 = Jim_String(firstObjPtr);
+
    const char *s2 = Jim_String(secondObjPtr);
+

+
    return JimStringCompareLen(s1, s2, Jim_Utf8Length(interp, firstObjPtr), nocase);
+
}
+

+
static int JimRelToAbsIndex(int len, int idx)
+
{
+
    if (idx < 0)
+
        return len + idx;
+
    return idx;
+
}
+

+
static void JimRelToAbsRange(int len, int *firstPtr, int *lastPtr, int *rangeLenPtr)
+
{
+
    int rangeLen;
+

+
    if (*firstPtr > *lastPtr) {
+
        rangeLen = 0;
+
    }
+
    else {
+
        rangeLen = *lastPtr - *firstPtr + 1;
+
        if (rangeLen) {
+
            if (*firstPtr < 0) {
+
                rangeLen += *firstPtr;
+
                *firstPtr = 0;
+
            }
+
            if (*lastPtr >= len) {
+
                rangeLen -= (*lastPtr - (len - 1));
+
                *lastPtr = len - 1;
+
            }
+
        }
+
    }
+
    if (rangeLen < 0)
+
        rangeLen = 0;
+

+
    *rangeLenPtr = rangeLen;
+
}
+

+
static int JimStringGetRange(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr,
+
    int len, int *first, int *last, int *range)
+
{
+
    if (Jim_GetIndex(interp, firstObjPtr, first) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    if (Jim_GetIndex(interp, lastObjPtr, last) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    *first = JimRelToAbsIndex(len, *first);
+
    *last = JimRelToAbsIndex(len, *last);
+
    JimRelToAbsRange(len, first, last, range);
+
    return JIM_OK;
+
}
+

+
Jim_Obj *Jim_StringByteRangeObj(Jim_Interp *interp,
+
    Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
+
{
+
    int first, last;
+
    const char *str;
+
    int rangeLen;
+
    int bytelen;
+

+
    str = Jim_GetString(strObjPtr, &bytelen);
+

+
    if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, bytelen, &first, &last, &rangeLen) != JIM_OK) {
+
        return NULL;
+
    }
+

+
    if (first == 0 && rangeLen == bytelen) {
+
        return strObjPtr;
+
    }
+
    return Jim_NewStringObj(interp, str + first, rangeLen);
+
}
+

+
Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
+
    Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
+
{
+
#ifdef JIM_UTF8
+
    int first, last;
+
    const char *str;
+
    int len, rangeLen;
+
    int bytelen;
+

+
    str = Jim_GetString(strObjPtr, &bytelen);
+
    len = Jim_Utf8Length(interp, strObjPtr);
+

+
    if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
+
        return NULL;
+
    }
+

+
    if (first == 0 && rangeLen == len) {
+
        return strObjPtr;
+
    }
+
    if (len == bytelen) {
+

+
        return Jim_NewStringObj(interp, str + first, rangeLen);
+
    }
+
    return Jim_NewStringObjUtf8(interp, str + utf8_index(str, first), rangeLen);
+
#else
+
    return Jim_StringByteRangeObj(interp, strObjPtr, firstObjPtr, lastObjPtr);
+
#endif
+
}
+

+
Jim_Obj *JimStringReplaceObj(Jim_Interp *interp,
+
    Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr, Jim_Obj *newStrObj)
+
{
+
    int first, last;
+
    const char *str;
+
    int len, rangeLen;
+
    Jim_Obj *objPtr;
+

+
    len = Jim_Utf8Length(interp, strObjPtr);
+

+
    if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
+
        return NULL;
+
    }
+

+
    if (last < first) {
+
        return strObjPtr;
+
    }
+

+
    str = Jim_String(strObjPtr);
+

+

+
    objPtr = Jim_NewStringObjUtf8(interp, str, first);
+

+

+
    if (newStrObj) {
+
        Jim_AppendObj(interp, objPtr, newStrObj);
+
    }
+

+

+
    Jim_AppendString(interp, objPtr, str + utf8_index(str, last + 1), len - last - 1);
+

+
    return objPtr;
+
}
+

+
static void JimStrCopyUpperLower(char *dest, const char *str, int uc)
+
{
+
    while (*str) {
+
        int c;
+
        str += utf8_tounicode(str, &c);
+
        dest += utf8_getchars(dest, uc ? utf8_upper(c) : utf8_lower(c));
+
    }
+
    *dest = 0;
+
}
+

+
static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
+
{
+
    char *buf;
+
    int len;
+
    const char *str;
+

+
    SetStringFromAny(interp, strObjPtr);
+

+
    str = Jim_GetString(strObjPtr, &len);
+

+
#ifdef JIM_UTF8
+
    len *= 2;
+
#endif
+
    buf = Jim_Alloc(len + 1);
+
    JimStrCopyUpperLower(buf, str, 0);
+
    return Jim_NewStringObjNoAlloc(interp, buf, -1);
+
}
+

+
static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
+
{
+
    char *buf;
+
    const char *str;
+
    int len;
+

+
    if (strObjPtr->typePtr != &stringObjType) {
+
        SetStringFromAny(interp, strObjPtr);
+
    }
+

+
    str = Jim_GetString(strObjPtr, &len);
+

+
#ifdef JIM_UTF8
+
    len *= 2;
+
#endif
+
    buf = Jim_Alloc(len + 1);
+
    JimStrCopyUpperLower(buf, str, 1);
+
    return Jim_NewStringObjNoAlloc(interp, buf, -1);
+
}
+

+
static Jim_Obj *JimStringToTitle(Jim_Interp *interp, Jim_Obj *strObjPtr)
+
{
+
    char *buf, *p;
+
    int len;
+
    int c;
+
    const char *str;
+

+
    str = Jim_GetString(strObjPtr, &len);
+
    if (len == 0) {
+
        return strObjPtr;
+
    }
+
#ifdef JIM_UTF8
+
    len *= 2;
+
#endif
+
    buf = p = Jim_Alloc(len + 1);
+

+
    str += utf8_tounicode(str, &c);
+
    p += utf8_getchars(p, utf8_title(c));
+

+
    JimStrCopyUpperLower(p, str, 0);
+

+
    return Jim_NewStringObjNoAlloc(interp, buf, -1);
+
}
+

+
static const char *utf8_memchr(const char *str, int len, int c)
+
{
+
#ifdef JIM_UTF8
+
    while (len) {
+
        int sc;
+
        int n = utf8_tounicode(str, &sc);
+
        if (sc == c) {
+
            return str;
+
        }
+
        str += n;
+
        len -= n;
+
    }
+
    return NULL;
+
#else
+
    return memchr(str, c, len);
+
#endif
+
}
+

+
static const char *JimFindTrimLeft(const char *str, int len, const char *trimchars, int trimlen)
+
{
+
    while (len) {
+
        int c;
+
        int n = utf8_tounicode(str, &c);
+

+
        if (utf8_memchr(trimchars, trimlen, c) == NULL) {
+

+
            break;
+
        }
+
        str += n;
+
        len -= n;
+
    }
+
    return str;
+
}
+

+
static const char *JimFindTrimRight(const char *str, int len, const char *trimchars, int trimlen)
+
{
+
    str += len;
+

+
    while (len) {
+
        int c;
+
        int n = utf8_prev_len(str, len);
+

+
        len -= n;
+
        str -= n;
+

+
        n = utf8_tounicode(str, &c);
+

+
        if (utf8_memchr(trimchars, trimlen, c) == NULL) {
+
            return str + n;
+
        }
+
    }
+

+
    return NULL;
+
}
+

+
static const char default_trim_chars[] = " \t\n\r";
+

+
static int default_trim_chars_len = sizeof(default_trim_chars);
+

+
static Jim_Obj *JimStringTrimLeft(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
+
{
+
    int len;
+
    const char *str = Jim_GetString(strObjPtr, &len);
+
    const char *trimchars = default_trim_chars;
+
    int trimcharslen = default_trim_chars_len;
+
    const char *newstr;
+

+
    if (trimcharsObjPtr) {
+
        trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
+
    }
+

+
    newstr = JimFindTrimLeft(str, len, trimchars, trimcharslen);
+
    if (newstr == str) {
+
        return strObjPtr;
+
    }
+

+
    return Jim_NewStringObj(interp, newstr, len - (newstr - str));
+
}
+

+
static Jim_Obj *JimStringTrimRight(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
+
{
+
    int len;
+
    const char *trimchars = default_trim_chars;
+
    int trimcharslen = default_trim_chars_len;
+
    const char *nontrim;
+

+
    if (trimcharsObjPtr) {
+
        trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
+
    }
+

+
    SetStringFromAny(interp, strObjPtr);
+

+
    len = Jim_Length(strObjPtr);
+
    nontrim = JimFindTrimRight(strObjPtr->bytes, len, trimchars, trimcharslen);
+

+
    if (nontrim == NULL) {
+

+
        return Jim_NewEmptyStringObj(interp);
+
    }
+
    if (nontrim == strObjPtr->bytes + len) {
+

+
        return strObjPtr;
+
    }
+

+
    if (Jim_IsShared(strObjPtr)) {
+
        strObjPtr = Jim_NewStringObj(interp, strObjPtr->bytes, (nontrim - strObjPtr->bytes));
+
    }
+
    else {
+

+
        strObjPtr->bytes[nontrim - strObjPtr->bytes] = 0;
+
        strObjPtr->length = (nontrim - strObjPtr->bytes);
+
    }
+

+
    return strObjPtr;
+
}
+

+
static Jim_Obj *JimStringTrim(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
+
{
+

+
    Jim_Obj *objPtr = JimStringTrimLeft(interp, strObjPtr, trimcharsObjPtr);
+

+

+
    strObjPtr = JimStringTrimRight(interp, objPtr, trimcharsObjPtr);
+

+

+
    if (objPtr != strObjPtr && objPtr->refCount == 0) {
+

+
        Jim_FreeNewObj(interp, objPtr);
+
    }
+

+
    return strObjPtr;
+
}
+

+

+
#ifdef HAVE_ISASCII
+
#define jim_isascii isascii
+
#else
+
static int jim_isascii(int c)
+
{
+
    return !(c & ~0x7f);
+
}
+
#endif
+

+
static int JimStringIs(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *strClass, int strict)
+
{
+
    static const char * const strclassnames[] = {
+
        "integer", "alpha", "alnum", "ascii", "digit",
+
        "double", "lower", "upper", "space", "xdigit",
+
        "control", "print", "graph", "punct", "boolean",
+
        NULL
+
    };
+
    enum {
+
        STR_IS_INTEGER, STR_IS_ALPHA, STR_IS_ALNUM, STR_IS_ASCII, STR_IS_DIGIT,
+
        STR_IS_DOUBLE, STR_IS_LOWER, STR_IS_UPPER, STR_IS_SPACE, STR_IS_XDIGIT,
+
        STR_IS_CONTROL, STR_IS_PRINT, STR_IS_GRAPH, STR_IS_PUNCT, STR_IS_BOOLEAN,
+
    };
+
    int strclass;
+
    int len;
+
    int i;
+
    const char *str;
+
    int (*isclassfunc)(int c) = NULL;
+

+
    if (Jim_GetEnum(interp, strClass, strclassnames, &strclass, "class", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+

+
    str = Jim_GetString(strObjPtr, &len);
+
    if (len == 0) {
+
        Jim_SetResultBool(interp, !strict);
+
        return JIM_OK;
+
    }
+

+
    switch (strclass) {
+
        case STR_IS_INTEGER:
+
            {
+
                jim_wide w;
+
                Jim_SetResultBool(interp, JimGetWideNoErr(interp, strObjPtr, &w) == JIM_OK);
+
                return JIM_OK;
+
            }
+

+
        case STR_IS_DOUBLE:
+
            {
+
                double d;
+
                Jim_SetResultBool(interp, Jim_GetDouble(interp, strObjPtr, &d) == JIM_OK && errno != ERANGE);
+
                return JIM_OK;
+
            }
+

+
        case STR_IS_BOOLEAN:
+
            {
+
                int b;
+
                Jim_SetResultBool(interp, Jim_GetBoolean(interp, strObjPtr, &b) == JIM_OK);
+
                return JIM_OK;
+
            }
+

+
        case STR_IS_ALPHA: isclassfunc = isalpha; break;
+
        case STR_IS_ALNUM: isclassfunc = isalnum; break;
+
        case STR_IS_ASCII: isclassfunc = jim_isascii; break;
+
        case STR_IS_DIGIT: isclassfunc = isdigit; break;
+
        case STR_IS_LOWER: isclassfunc = islower; break;
+
        case STR_IS_UPPER: isclassfunc = isupper; break;
+
        case STR_IS_SPACE: isclassfunc = isspace; break;
+
        case STR_IS_XDIGIT: isclassfunc = isxdigit; break;
+
        case STR_IS_CONTROL: isclassfunc = iscntrl; break;
+
        case STR_IS_PRINT: isclassfunc = isprint; break;
+
        case STR_IS_GRAPH: isclassfunc = isgraph; break;
+
        case STR_IS_PUNCT: isclassfunc = ispunct; break;
+
        default:
+
            return JIM_ERR;
+
    }
+

+
    for (i = 0; i < len; i++) {
+
        if (!isclassfunc(UCHAR(str[i]))) {
+
            Jim_SetResultBool(interp, 0);
+
            return JIM_OK;
+
        }
+
    }
+
    Jim_SetResultBool(interp, 1);
+
    return JIM_OK;
+
}
+

+

+

+
static const Jim_ObjType comparedStringObjType = {
+
    "compared-string",
+
    NULL,
+
    NULL,
+
    NULL,
+
    JIM_TYPE_REFERENCES,
+
};
+

+
int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr, const char *str)
+
{
+
    if (objPtr->typePtr == &comparedStringObjType && objPtr->internalRep.ptr == str) {
+
        return 1;
+
    }
+
    else {
+
        const char *objStr = Jim_String(objPtr);
+

+
        if (strcmp(str, objStr) != 0)
+
            return 0;
+

+
        if (objPtr->typePtr != &comparedStringObjType) {
+
            Jim_FreeIntRep(interp, objPtr);
+
            objPtr->typePtr = &comparedStringObjType;
+
        }
+
        objPtr->internalRep.ptr = (char *)str;
+
        return 1;
+
    }
+
}
+

+
static int qsortCompareStringPointers(const void *a, const void *b)
+
{
+
    char *const *sa = (char *const *)a;
+
    char *const *sb = (char *const *)b;
+

+
    return strcmp(*sa, *sb);
+
}
+

+

+

+
static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+
static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+

+
static const Jim_ObjType sourceObjType = {
+
    "source",
+
    FreeSourceInternalRep,
+
    DupSourceInternalRep,
+
    NULL,
+
    JIM_TYPE_REFERENCES,
+
};
+

+
void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    Jim_DecrRefCount(interp, objPtr->internalRep.sourceValue.fileNameObj);
+
}
+

+
void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    dupPtr->internalRep.sourceValue = srcPtr->internalRep.sourceValue;
+
    Jim_IncrRefCount(dupPtr->internalRep.sourceValue.fileNameObj);
+
}
+

+
static void JimSetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
+
    Jim_Obj *fileNameObj, int lineNumber)
+
{
+
    JimPanic((Jim_IsShared(objPtr), "JimSetSourceInfo called with shared object"));
+
    JimPanic((objPtr->typePtr != NULL, "JimSetSourceInfo called with typed object"));
+
    Jim_IncrRefCount(fileNameObj);
+
    objPtr->internalRep.sourceValue.fileNameObj = fileNameObj;
+
    objPtr->internalRep.sourceValue.lineNumber = lineNumber;
+
    objPtr->typePtr = &sourceObjType;
+
}
+

+
static const Jim_ObjType scriptLineObjType = {
+
    "scriptline",
+
    NULL,
+
    NULL,
+
    NULL,
+
    JIM_NONE,
+
};
+

+
static Jim_Obj *JimNewScriptLineObj(Jim_Interp *interp, int argc, int line)
+
{
+
    Jim_Obj *objPtr;
+

+
#ifdef DEBUG_SHOW_SCRIPT
+
    char buf[100];
+
    snprintf(buf, sizeof(buf), "line=%d, argc=%d", line, argc);
+
    objPtr = Jim_NewStringObj(interp, buf, -1);
+
#else
+
    objPtr = Jim_NewEmptyStringObj(interp);
+
#endif
+
    objPtr->typePtr = &scriptLineObjType;
+
    objPtr->internalRep.scriptLineValue.argc = argc;
+
    objPtr->internalRep.scriptLineValue.line = line;
+

+
    return objPtr;
+
}
+

+
static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+
static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+

+
static const Jim_ObjType scriptObjType = {
+
    "script",
+
    FreeScriptInternalRep,
+
    DupScriptInternalRep,
+
    NULL,
+
    JIM_TYPE_REFERENCES,
+
};
+

+
typedef struct ScriptToken
+
{
+
    Jim_Obj *objPtr;
+
    int type;
+
} ScriptToken;
+

+
typedef struct ScriptObj
+
{
+
    ScriptToken *token;
+
    Jim_Obj *fileNameObj;
+
    int len;
+
    int substFlags;
+
    int inUse;                  /* Used to share a ScriptObj. Currently
+
                                   only used by Jim_EvalObj() as protection against
+
                                   shimmering of the currently evaluated object. */
+
    int firstline;
+
    int linenr;
+
    int missing;
+
} ScriptObj;
+

+
static void JimSetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
static int JimParseCheckMissing(Jim_Interp *interp, int ch);
+
static ScriptObj *JimGetScript(Jim_Interp *interp, Jim_Obj *objPtr);
+

+
void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    int i;
+
    struct ScriptObj *script = (void *)objPtr->internalRep.ptr;
+

+
    if (--script->inUse != 0)
+
        return;
+
    for (i = 0; i < script->len; i++) {
+
        Jim_DecrRefCount(interp, script->token[i].objPtr);
+
    }
+
    Jim_Free(script->token);
+
    Jim_DecrRefCount(interp, script->fileNameObj);
+
    Jim_Free(script);
+
}
+

+
void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    JIM_NOTUSED(interp);
+
    JIM_NOTUSED(srcPtr);
+

+
    dupPtr->typePtr = NULL;
+
}
+

+
typedef struct
+
{
+
    const char *token;
+
    int len;
+
    int type;
+
    int line;
+
} ParseToken;
+

+
typedef struct
+
{
+

+
    ParseToken *list;
+
    int size;
+
    int count;
+
    ParseToken static_list[20];
+
} ParseTokenList;
+

+
static void ScriptTokenListInit(ParseTokenList *tokenlist)
+
{
+
    tokenlist->list = tokenlist->static_list;
+
    tokenlist->size = sizeof(tokenlist->static_list) / sizeof(ParseToken);
+
    tokenlist->count = 0;
+
}
+

+
static void ScriptTokenListFree(ParseTokenList *tokenlist)
+
{
+
    if (tokenlist->list != tokenlist->static_list) {
+
        Jim_Free(tokenlist->list);
+
    }
+
}
+

+
static void ScriptAddToken(ParseTokenList *tokenlist, const char *token, int len, int type,
+
    int line)
+
{
+
    ParseToken *t;
+

+
    if (tokenlist->count == tokenlist->size) {
+

+
        tokenlist->size *= 2;
+
        if (tokenlist->list != tokenlist->static_list) {
+
            tokenlist->list =
+
                Jim_Realloc(tokenlist->list, tokenlist->size * sizeof(*tokenlist->list));
+
        }
+
        else {
+

+
            tokenlist->list = Jim_Alloc(tokenlist->size * sizeof(*tokenlist->list));
+
            memcpy(tokenlist->list, tokenlist->static_list,
+
                tokenlist->count * sizeof(*tokenlist->list));
+
        }
+
    }
+
    t = &tokenlist->list[tokenlist->count++];
+
    t->token = token;
+
    t->len = len;
+
    t->type = type;
+
    t->line = line;
+
}
+

+
static int JimCountWordTokens(ParseToken *t)
+
{
+
    int expand = 1;
+
    int count = 0;
+

+

+
    if (t->type == JIM_TT_STR && !TOKEN_IS_SEP(t[1].type)) {
+
        if ((t->len == 1 && *t->token == '*') || (t->len == 6 && strncmp(t->token, "expand", 6) == 0)) {
+

+
            expand = -1;
+
            t++;
+
        }
+
    }
+

+

+
    while (!TOKEN_IS_SEP(t->type)) {
+
        t++;
+
        count++;
+
    }
+

+
    return count * expand;
+
}
+

+
static Jim_Obj *JimMakeScriptObj(Jim_Interp *interp, const ParseToken *t)
+
{
+
    Jim_Obj *objPtr;
+

+
    if (t->type == JIM_TT_ESC && memchr(t->token, '\\', t->len) != NULL) {
+

+
        int len = t->len;
+
        char *str = Jim_Alloc(len + 1);
+
        len = JimEscape(str, t->token, len);
+
        objPtr = Jim_NewStringObjNoAlloc(interp, str, len);
+
    }
+
    else {
+
        objPtr = Jim_NewStringObj(interp, t->token, t->len);
+
    }
+
    return objPtr;
+
}
+

+
static void ScriptObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
+
    ParseTokenList *tokenlist)
+
{
+
    int i;
+
    struct ScriptToken *token;
+

+
    int lineargs = 0;
+

+
    ScriptToken *linefirst;
+
    int count;
+
    int linenr;
+

+
#ifdef DEBUG_SHOW_SCRIPT_TOKENS
+
    printf("==== Tokens ====\n");
+
    for (i = 0; i < tokenlist->count; i++) {
+
        printf("[%2d]@%d %s '%.*s'\n", i, tokenlist->list[i].line, jim_tt_name(tokenlist->list[i].type),
+
            tokenlist->list[i].len, tokenlist->list[i].token);
+
    }
+
#endif
+

+

+
    count = tokenlist->count;
+
    for (i = 0; i < tokenlist->count; i++) {
+
        if (tokenlist->list[i].type == JIM_TT_EOL) {
+
            count++;
+
        }
+
    }
+
    linenr = script->firstline = tokenlist->list[0].line;
+

+
    token = script->token = Jim_Alloc(sizeof(ScriptToken) * count);
+

+

+
    linefirst = token++;
+

+
    for (i = 0; i < tokenlist->count; ) {
+

+
        int wordtokens;
+

+

+
        while (tokenlist->list[i].type == JIM_TT_SEP) {
+
            i++;
+
        }
+

+
        wordtokens = JimCountWordTokens(tokenlist->list + i);
+

+
        if (wordtokens == 0) {
+

+
            if (lineargs) {
+
                linefirst->type = JIM_TT_LINE;
+
                linefirst->objPtr = JimNewScriptLineObj(interp, lineargs, linenr);
+
                Jim_IncrRefCount(linefirst->objPtr);
+

+

+
                lineargs = 0;
+
                linefirst = token++;
+
            }
+
            i++;
+
            continue;
+
        }
+
        else if (wordtokens != 1) {
+

+
            token->type = JIM_TT_WORD;
+
            token->objPtr = Jim_NewIntObj(interp, wordtokens);
+
            Jim_IncrRefCount(token->objPtr);
+
            token++;
+
            if (wordtokens < 0) {
+

+
                i++;
+
                wordtokens = -wordtokens - 1;
+
                lineargs--;
+
            }
+
        }
+

+
        if (lineargs == 0) {
+

+
            linenr = tokenlist->list[i].line;
+
        }
+
        lineargs++;
+

+

+
        while (wordtokens--) {
+
            const ParseToken *t = &tokenlist->list[i++];
+

+
            token->type = t->type;
+
            token->objPtr = JimMakeScriptObj(interp, t);
+
            Jim_IncrRefCount(token->objPtr);
+

+
            JimSetSourceInfo(interp, token->objPtr, script->fileNameObj, t->line);
+
            token++;
+
        }
+
    }
+

+
    if (lineargs == 0) {
+
        token--;
+
    }
+

+
    script->len = token - script->token;
+

+
    JimPanic((script->len >= count, "allocated script array is too short"));
+

+
#ifdef DEBUG_SHOW_SCRIPT
+
    printf("==== Script (%s) ====\n", Jim_String(script->fileNameObj));
+
    for (i = 0; i < script->len; i++) {
+
        const ScriptToken *t = &script->token[i];
+
        printf("[%2d] %s %s\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
+
    }
+
#endif
+

+
}
+

+
int Jim_ScriptIsComplete(Jim_Interp *interp, Jim_Obj *scriptObj, char *stateCharPtr)
+
{
+
    ScriptObj *script = JimGetScript(interp, scriptObj);
+
    if (stateCharPtr) {
+
        *stateCharPtr = script->missing;
+
    }
+
    return (script->missing == ' ');
+
}
+

+
static int JimParseCheckMissing(Jim_Interp *interp, int ch)
+
{
+
    const char *msg;
+

+
    switch (ch) {
+
        case '\\':
+
        case ' ':
+
            return JIM_OK;
+

+
        case '[':
+
            msg = "unmatched \"[\"";
+
            break;
+
        case '{':
+
            msg = "missing close-brace";
+
            break;
+
        case '"':
+
        default:
+
            msg = "missing quote";
+
            break;
+
    }
+

+
    Jim_SetResultString(interp, msg, -1);
+
    return JIM_ERR;
+
}
+

+
static void SubstObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
+
    ParseTokenList *tokenlist)
+
{
+
    int i;
+
    struct ScriptToken *token;
+

+
    token = script->token = Jim_Alloc(sizeof(ScriptToken) * tokenlist->count);
+

+
    for (i = 0; i < tokenlist->count; i++) {
+
        const ParseToken *t = &tokenlist->list[i];
+

+

+
        token->type = t->type;
+
        token->objPtr = JimMakeScriptObj(interp, t);
+
        Jim_IncrRefCount(token->objPtr);
+
        token++;
+
    }
+

+
    script->len = i;
+
}
+

+
static void JimSetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+
{
+
    int scriptTextLen;
+
    const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
+
    struct JimParserCtx parser;
+
    struct ScriptObj *script;
+
    ParseTokenList tokenlist;
+
    int line = 1;
+

+

+
    if (objPtr->typePtr == &sourceObjType) {
+
        line = objPtr->internalRep.sourceValue.lineNumber;
+
    }
+

+

+
    ScriptTokenListInit(&tokenlist);
+

+
    JimParserInit(&parser, scriptText, scriptTextLen, line);
+
    while (!parser.eof) {
+
        JimParseScript(&parser);
+
        ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
+
            parser.tline);
+
    }
+

+

+
    ScriptAddToken(&tokenlist, scriptText + scriptTextLen, 0, JIM_TT_EOF, 0);
+

+

+
    script = Jim_Alloc(sizeof(*script));
+
    memset(script, 0, sizeof(*script));
+
    script->inUse = 1;
+
    if (objPtr->typePtr == &sourceObjType) {
+
        script->fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
+
    }
+
    else {
+
        script->fileNameObj = interp->emptyObj;
+
    }
+
    Jim_IncrRefCount(script->fileNameObj);
+
    script->missing = parser.missing.ch;
+
    script->linenr = parser.missing.line;
+

+
    ScriptObjAddTokens(interp, script, &tokenlist);
+

+

+
    ScriptTokenListFree(&tokenlist);
+

+

+
    Jim_FreeIntRep(interp, objPtr);
+
    Jim_SetIntRepPtr(objPtr, script);
+
    objPtr->typePtr = &scriptObjType;
+
}
+

+
static void JimAddErrorToStack(Jim_Interp *interp, ScriptObj *script);
+

+
static ScriptObj *JimGetScript(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    if (objPtr == interp->emptyObj) {
+

+
        objPtr = interp->nullScriptObj;
+
    }
+

+
    if (objPtr->typePtr != &scriptObjType || ((struct ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags) {
+
        JimSetScriptFromAny(interp, objPtr);
+
    }
+

+
    return (ScriptObj *)Jim_GetIntRepPtr(objPtr);
+
}
+

+
static int JimScriptValid(Jim_Interp *interp, ScriptObj *script)
+
{
+
    if (JimParseCheckMissing(interp, script->missing) == JIM_ERR) {
+
        JimAddErrorToStack(interp, script);
+
        return 0;
+
    }
+
    return 1;
+
}
+

+

+
static void JimIncrCmdRefCount(Jim_Cmd *cmdPtr)
+
{
+
    cmdPtr->inUse++;
+
}
+

+
static void JimDecrCmdRefCount(Jim_Interp *interp, Jim_Cmd *cmdPtr)
+
{
+
    if (--cmdPtr->inUse == 0) {
+
        if (cmdPtr->isproc) {
+
            Jim_DecrRefCount(interp, cmdPtr->u.proc.argListObjPtr);
+
            Jim_DecrRefCount(interp, cmdPtr->u.proc.bodyObjPtr);
+
            Jim_DecrRefCount(interp, cmdPtr->u.proc.nsObj);
+
            if (cmdPtr->u.proc.staticVars) {
+
                Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
+
                Jim_Free(cmdPtr->u.proc.staticVars);
+
            }
+
        }
+
        else {
+

+
            if (cmdPtr->u.native.delProc) {
+
                cmdPtr->u.native.delProc(interp, cmdPtr->u.native.privData);
+
            }
+
        }
+
        if (cmdPtr->prevCmd) {
+

+
            JimDecrCmdRefCount(interp, cmdPtr->prevCmd);
+
        }
+
        Jim_Free(cmdPtr);
+
    }
+
}
+

+

+
static void JimVariablesHTValDestructor(void *interp, void *val)
+
{
+
    Jim_DecrRefCount(interp, ((Jim_Var *)val)->objPtr);
+
    Jim_Free(val);
+
}
+

+
static const Jim_HashTableType JimVariablesHashTableType = {
+
    JimStringCopyHTHashFunction,
+
    JimStringCopyHTDup,
+
    NULL,
+
    JimStringCopyHTKeyCompare,
+
    JimStringCopyHTKeyDestructor,
+
    JimVariablesHTValDestructor
+
};
+

+
static void JimCommandsHT_ValDestructor(void *interp, void *val)
+
{
+
    JimDecrCmdRefCount(interp, val);
+
}
+

+
static const Jim_HashTableType JimCommandsHashTableType = {
+
    JimStringCopyHTHashFunction,
+
    JimStringCopyHTDup,
+
    NULL,
+
    JimStringCopyHTKeyCompare,
+
    JimStringCopyHTKeyDestructor,
+
    JimCommandsHT_ValDestructor
+
};
+

+

+

+
#ifdef jim_ext_namespace
+
static Jim_Obj *JimQualifyNameObj(Jim_Interp *interp, Jim_Obj *nsObj)
+
{
+
    const char *name = Jim_String(nsObj);
+
    if (name[0] == ':' && name[1] == ':') {
+

+
        while (*++name == ':') {
+
        }
+
        nsObj = Jim_NewStringObj(interp, name, -1);
+
    }
+
    else if (Jim_Length(interp->framePtr->nsObj)) {
+

+
        nsObj = Jim_DuplicateObj(interp, interp->framePtr->nsObj);
+
        Jim_AppendStrings(interp, nsObj, "::", name, NULL);
+
    }
+
    return nsObj;
+
}
+

+
Jim_Obj *Jim_MakeGlobalNamespaceName(Jim_Interp *interp, Jim_Obj *nameObjPtr)
+
{
+
    Jim_Obj *resultObj;
+

+
    const char *name = Jim_String(nameObjPtr);
+
    if (name[0] == ':' && name[1] == ':') {
+
        return nameObjPtr;
+
    }
+
    Jim_IncrRefCount(nameObjPtr);
+
    resultObj = Jim_NewStringObj(interp, "::", -1);
+
    Jim_AppendObj(interp, resultObj, nameObjPtr);
+
    Jim_DecrRefCount(interp, nameObjPtr);
+

+
    return resultObj;
+
}
+

+
static const char *JimQualifyName(Jim_Interp *interp, const char *name, Jim_Obj **objPtrPtr)
+
{
+
    Jim_Obj *objPtr = interp->emptyObj;
+

+
    if (name[0] == ':' && name[1] == ':') {
+

+
        while (*++name == ':') {
+
        }
+
    }
+
    else if (Jim_Length(interp->framePtr->nsObj)) {
+

+
        objPtr = Jim_DuplicateObj(interp, interp->framePtr->nsObj);
+
        Jim_AppendStrings(interp, objPtr, "::", name, NULL);
+
        name = Jim_String(objPtr);
+
    }
+
    Jim_IncrRefCount(objPtr);
+
    *objPtrPtr = objPtr;
+
    return name;
+
}
+

+
    #define JimFreeQualifiedName(INTERP, OBJ) Jim_DecrRefCount((INTERP), (OBJ))
+

+
#else
+

+
    #define JimQualifyName(INTERP, NAME, DUMMY) (((NAME)[0] == ':' && (NAME)[1] == ':') ? (NAME) + 2 : (NAME))
+
    #define JimFreeQualifiedName(INTERP, DUMMY) (void)(DUMMY)
+

+
Jim_Obj *Jim_MakeGlobalNamespaceName(Jim_Interp *interp, Jim_Obj *nameObjPtr)
+
{
+
    return nameObjPtr;
+
}
+
#endif
+

+
static int JimCreateCommand(Jim_Interp *interp, const char *name, Jim_Cmd *cmd)
+
{
+
    Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, name);
+
    if (he) {
+

+
        Jim_InterpIncrProcEpoch(interp);
+
    }
+

+
    if (he && interp->local) {
+

+
        cmd->prevCmd = Jim_GetHashEntryVal(he);
+
        Jim_SetHashVal(&interp->commands, he, cmd);
+
    }
+
    else {
+
        if (he) {
+

+
            Jim_DeleteHashEntry(&interp->commands, name);
+
        }
+

+
        Jim_AddHashEntry(&interp->commands, name, cmd);
+
    }
+
    return JIM_OK;
+
}
+

+

+
int Jim_CreateCommand(Jim_Interp *interp, const char *cmdNameStr,
+
    Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc)
+
{
+
    Jim_Cmd *cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
+

+

+
    memset(cmdPtr, 0, sizeof(*cmdPtr));
+
    cmdPtr->inUse = 1;
+
    cmdPtr->u.native.delProc = delProc;
+
    cmdPtr->u.native.cmdProc = cmdProc;
+
    cmdPtr->u.native.privData = privData;
+

+
    JimCreateCommand(interp, cmdNameStr, cmdPtr);
+

+
    return JIM_OK;
+
}
+

+
static int JimCreateProcedureStatics(Jim_Interp *interp, Jim_Cmd *cmdPtr, Jim_Obj *staticsListObjPtr)
+
{
+
    int len, i;
+

+
    len = Jim_ListLength(interp, staticsListObjPtr);
+
    if (len == 0) {
+
        return JIM_OK;
+
    }
+

+
    cmdPtr->u.proc.staticVars = Jim_Alloc(sizeof(Jim_HashTable));
+
    Jim_InitHashTable(cmdPtr->u.proc.staticVars, &JimVariablesHashTableType, interp);
+
    for (i = 0; i < len; i++) {
+
        Jim_Obj *objPtr, *initObjPtr, *nameObjPtr;
+
        Jim_Var *varPtr;
+
        int subLen;
+

+
        objPtr = Jim_ListGetIndex(interp, staticsListObjPtr, i);
+

+
        subLen = Jim_ListLength(interp, objPtr);
+
        if (subLen == 1 || subLen == 2) {
+
            nameObjPtr = Jim_ListGetIndex(interp, objPtr, 0);
+
            if (subLen == 1) {
+
                initObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_NONE);
+
                if (initObjPtr == NULL) {
+
                    Jim_SetResultFormatted(interp,
+
                        "variable for initialization of static \"%#s\" not found in the local context",
+
                        nameObjPtr);
+
                    return JIM_ERR;
+
                }
+
            }
+
            else {
+
                initObjPtr = Jim_ListGetIndex(interp, objPtr, 1);
+
            }
+
            if (JimValidName(interp, "static variable", nameObjPtr) != JIM_OK) {
+
                return JIM_ERR;
+
            }
+

+
            varPtr = Jim_Alloc(sizeof(*varPtr));
+
            varPtr->objPtr = initObjPtr;
+
            Jim_IncrRefCount(initObjPtr);
+
            varPtr->linkFramePtr = NULL;
+
            if (Jim_AddHashEntry(cmdPtr->u.proc.staticVars,
+
                Jim_String(nameObjPtr), varPtr) != JIM_OK) {
+
                Jim_SetResultFormatted(interp,
+
                    "static variable name \"%#s\" duplicated in statics list", nameObjPtr);
+
                Jim_DecrRefCount(interp, initObjPtr);
+
                Jim_Free(varPtr);
+
                return JIM_ERR;
+
            }
+
        }
+
        else {
+
            Jim_SetResultFormatted(interp, "too many fields in static specifier \"%#s\"",
+
                objPtr);
+
            return JIM_ERR;
+
        }
+
    }
+
    return JIM_OK;
+
}
+

+
static void JimUpdateProcNamespace(Jim_Interp *interp, Jim_Cmd *cmdPtr, const char *cmdname)
+
{
+
#ifdef jim_ext_namespace
+
    if (cmdPtr->isproc) {
+

+
        const char *pt = strrchr(cmdname, ':');
+
        if (pt && pt != cmdname && pt[-1] == ':') {
+
            Jim_DecrRefCount(interp, cmdPtr->u.proc.nsObj);
+
            cmdPtr->u.proc.nsObj = Jim_NewStringObj(interp, cmdname, pt - cmdname - 1);
+
            Jim_IncrRefCount(cmdPtr->u.proc.nsObj);
+

+
            if (Jim_FindHashEntry(&interp->commands, pt + 1)) {
+

+
                Jim_InterpIncrProcEpoch(interp);
+
            }
+
        }
+
    }
+
#endif
+
}
+

+
static Jim_Cmd *JimCreateProcedureCmd(Jim_Interp *interp, Jim_Obj *argListObjPtr,
+
    Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr, Jim_Obj *nsObj)
+
{
+
    Jim_Cmd *cmdPtr;
+
    int argListLen;
+
    int i;
+

+
    argListLen = Jim_ListLength(interp, argListObjPtr);
+

+

+
    cmdPtr = Jim_Alloc(sizeof(*cmdPtr) + sizeof(struct Jim_ProcArg) * argListLen);
+
    memset(cmdPtr, 0, sizeof(*cmdPtr));
+
    cmdPtr->inUse = 1;
+
    cmdPtr->isproc = 1;
+
    cmdPtr->u.proc.argListObjPtr = argListObjPtr;
+
    cmdPtr->u.proc.argListLen = argListLen;
+
    cmdPtr->u.proc.bodyObjPtr = bodyObjPtr;
+
    cmdPtr->u.proc.argsPos = -1;
+
    cmdPtr->u.proc.arglist = (struct Jim_ProcArg *)(cmdPtr + 1);
+
    cmdPtr->u.proc.nsObj = nsObj ? nsObj : interp->emptyObj;
+
    Jim_IncrRefCount(argListObjPtr);
+
    Jim_IncrRefCount(bodyObjPtr);
+
    Jim_IncrRefCount(cmdPtr->u.proc.nsObj);
+

+

+
    if (staticsListObjPtr && JimCreateProcedureStatics(interp, cmdPtr, staticsListObjPtr) != JIM_OK) {
+
        goto err;
+
    }
+

+

+

+
    for (i = 0; i < argListLen; i++) {
+
        Jim_Obj *argPtr;
+
        Jim_Obj *nameObjPtr;
+
        Jim_Obj *defaultObjPtr;
+
        int len;
+

+

+
        argPtr = Jim_ListGetIndex(interp, argListObjPtr, i);
+
        len = Jim_ListLength(interp, argPtr);
+
        if (len == 0) {
+
            Jim_SetResultString(interp, "argument with no name", -1);
+
err:
+
            JimDecrCmdRefCount(interp, cmdPtr);
+
            return NULL;
+
        }
+
        if (len > 2) {
+
            Jim_SetResultFormatted(interp, "too many fields in argument specifier \"%#s\"", argPtr);
+
            goto err;
+
        }
+

+
        if (len == 2) {
+

+
            nameObjPtr = Jim_ListGetIndex(interp, argPtr, 0);
+
            defaultObjPtr = Jim_ListGetIndex(interp, argPtr, 1);
+
        }
+
        else {
+

+
            nameObjPtr = argPtr;
+
            defaultObjPtr = NULL;
+
        }
+

+

+
        if (Jim_CompareStringImmediate(interp, nameObjPtr, "args")) {
+
            if (cmdPtr->u.proc.argsPos >= 0) {
+
                Jim_SetResultString(interp, "'args' specified more than once", -1);
+
                goto err;
+
            }
+
            cmdPtr->u.proc.argsPos = i;
+
        }
+
        else {
+
            if (len == 2) {
+
                cmdPtr->u.proc.optArity++;
+
            }
+
            else {
+
                cmdPtr->u.proc.reqArity++;
+
            }
+
        }
+

+
        cmdPtr->u.proc.arglist[i].nameObjPtr = nameObjPtr;
+
        cmdPtr->u.proc.arglist[i].defaultObjPtr = defaultObjPtr;
+
    }
+

+
    return cmdPtr;
+
}
+

+
int Jim_DeleteCommand(Jim_Interp *interp, const char *name)
+
{
+
    int ret = JIM_OK;
+
    Jim_Obj *qualifiedNameObj;
+
    const char *qualname = JimQualifyName(interp, name, &qualifiedNameObj);
+

+
    if (Jim_DeleteHashEntry(&interp->commands, qualname) == JIM_ERR) {
+
        Jim_SetResultFormatted(interp, "can't delete \"%s\": command doesn't exist", name);
+
        ret = JIM_ERR;
+
    }
+
    else {
+
        Jim_InterpIncrProcEpoch(interp);
+
    }
+

+
    JimFreeQualifiedName(interp, qualifiedNameObj);
+

+
    return ret;
+
}
+

+
int Jim_RenameCommand(Jim_Interp *interp, const char *oldName, const char *newName)
+
{
+
    int ret = JIM_ERR;
+
    Jim_HashEntry *he;
+
    Jim_Cmd *cmdPtr;
+
    Jim_Obj *qualifiedOldNameObj;
+
    Jim_Obj *qualifiedNewNameObj;
+
    const char *fqold;
+
    const char *fqnew;
+

+
    if (newName[0] == 0) {
+
        return Jim_DeleteCommand(interp, oldName);
+
    }
+

+
    fqold = JimQualifyName(interp, oldName, &qualifiedOldNameObj);
+
    fqnew = JimQualifyName(interp, newName, &qualifiedNewNameObj);
+

+

+
    he = Jim_FindHashEntry(&interp->commands, fqold);
+
    if (he == NULL) {
+
        Jim_SetResultFormatted(interp, "can't rename \"%s\": command doesn't exist", oldName);
+
    }
+
    else if (Jim_FindHashEntry(&interp->commands, fqnew)) {
+
        Jim_SetResultFormatted(interp, "can't rename to \"%s\": command already exists", newName);
+
    }
+
    else {
+

+
        cmdPtr = Jim_GetHashEntryVal(he);
+
        JimIncrCmdRefCount(cmdPtr);
+
        JimUpdateProcNamespace(interp, cmdPtr, fqnew);
+
        Jim_AddHashEntry(&interp->commands, fqnew, cmdPtr);
+

+

+
        Jim_DeleteHashEntry(&interp->commands, fqold);
+

+

+
        Jim_InterpIncrProcEpoch(interp);
+

+
        ret = JIM_OK;
+
    }
+

+
    JimFreeQualifiedName(interp, qualifiedOldNameObj);
+
    JimFreeQualifiedName(interp, qualifiedNewNameObj);
+

+
    return ret;
+
}
+

+

+
static void FreeCommandInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    Jim_DecrRefCount(interp, objPtr->internalRep.cmdValue.nsObj);
+
}
+

+
static void DupCommandInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    dupPtr->internalRep.cmdValue = srcPtr->internalRep.cmdValue;
+
    dupPtr->typePtr = srcPtr->typePtr;
+
    Jim_IncrRefCount(dupPtr->internalRep.cmdValue.nsObj);
+
}
+

+
static const Jim_ObjType commandObjType = {
+
    "command",
+
    FreeCommandInternalRep,
+
    DupCommandInternalRep,
+
    NULL,
+
    JIM_TYPE_REFERENCES,
+
};
+

+
Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+
{
+
    Jim_Cmd *cmd;
+

+
    if (objPtr->typePtr != &commandObjType ||
+
            objPtr->internalRep.cmdValue.procEpoch != interp->procEpoch
+
#ifdef jim_ext_namespace
+
            || !Jim_StringEqObj(objPtr->internalRep.cmdValue.nsObj, interp->framePtr->nsObj)
+
#endif
+
        ) {
+

+

+

+
        const char *name = Jim_String(objPtr);
+
        Jim_HashEntry *he;
+

+
        if (name[0] == ':' && name[1] == ':') {
+
            while (*++name == ':') {
+
            }
+
        }
+
#ifdef jim_ext_namespace
+
        else if (Jim_Length(interp->framePtr->nsObj)) {
+

+
            Jim_Obj *nameObj = Jim_DuplicateObj(interp, interp->framePtr->nsObj);
+
            Jim_AppendStrings(interp, nameObj, "::", name, NULL);
+
            he = Jim_FindHashEntry(&interp->commands, Jim_String(nameObj));
+
            Jim_FreeNewObj(interp, nameObj);
+
            if (he) {
+
                goto found;
+
            }
+
        }
+
#endif
+

+

+
        he = Jim_FindHashEntry(&interp->commands, name);
+
        if (he == NULL) {
+
            if (flags & JIM_ERRMSG) {
+
                Jim_SetResultFormatted(interp, "invalid command name \"%#s\"", objPtr);
+
            }
+
            return NULL;
+
        }
+
#ifdef jim_ext_namespace
+
found:
+
#endif
+
        cmd = Jim_GetHashEntryVal(he);
+

+

+
        Jim_FreeIntRep(interp, objPtr);
+
        objPtr->typePtr = &commandObjType;
+
        objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
+
        objPtr->internalRep.cmdValue.cmdPtr = cmd;
+
        objPtr->internalRep.cmdValue.nsObj = interp->framePtr->nsObj;
+
        Jim_IncrRefCount(interp->framePtr->nsObj);
+
    }
+
    else {
+
        cmd = objPtr->internalRep.cmdValue.cmdPtr;
+
    }
+
    while (cmd->u.proc.upcall) {
+
        cmd = cmd->prevCmd;
+
    }
+
    return cmd;
+
}
+

+

+

+
#define JIM_DICT_SUGAR 100
+

+
static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+

+
static const Jim_ObjType variableObjType = {
+
    "variable",
+
    NULL,
+
    NULL,
+
    NULL,
+
    JIM_TYPE_REFERENCES,
+
};
+

+
static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr)
+
{
+

+
    if (nameObjPtr->typePtr != &variableObjType) {
+
        int len;
+
        const char *str = Jim_GetString(nameObjPtr, &len);
+
        if (memchr(str, '\0', len)) {
+
            Jim_SetResultFormatted(interp, "%s name contains embedded null", type);
+
            return JIM_ERR;
+
        }
+
    }
+
    return JIM_OK;
+
}
+

+
static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+
{
+
    const char *varName;
+
    Jim_CallFrame *framePtr;
+
    Jim_HashEntry *he;
+
    int global;
+
    int len;
+

+

+
    if (objPtr->typePtr == &variableObjType) {
+
        framePtr = objPtr->internalRep.varValue.global ? interp->topFramePtr : interp->framePtr;
+
        if (objPtr->internalRep.varValue.callFrameId == framePtr->id) {
+

+
            return JIM_OK;
+
        }
+

+
    }
+
    else if (objPtr->typePtr == &dictSubstObjType) {
+
        return JIM_DICT_SUGAR;
+
    }
+
    else if (JimValidName(interp, "variable", objPtr) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+

+

+
    varName = Jim_GetString(objPtr, &len);
+

+

+
    if (len && varName[len - 1] == ')' && strchr(varName, '(') != NULL) {
+
        return JIM_DICT_SUGAR;
+
    }
+

+
    if (varName[0] == ':' && varName[1] == ':') {
+
        while (*++varName == ':') {
+
        }
+
        global = 1;
+
        framePtr = interp->topFramePtr;
+
    }
+
    else {
+
        global = 0;
+
        framePtr = interp->framePtr;
+
    }
+

+

+
    he = Jim_FindHashEntry(&framePtr->vars, varName);
+
    if (he == NULL) {
+
        if (!global && framePtr->staticVars) {
+

+
            he = Jim_FindHashEntry(framePtr->staticVars, varName);
+
        }
+
        if (he == NULL) {
+
            return JIM_ERR;
+
        }
+
    }
+

+

+
    Jim_FreeIntRep(interp, objPtr);
+
    objPtr->typePtr = &variableObjType;
+
    objPtr->internalRep.varValue.callFrameId = framePtr->id;
+
    objPtr->internalRep.varValue.varPtr = Jim_GetHashEntryVal(he);
+
    objPtr->internalRep.varValue.global = global;
+
    return JIM_OK;
+
}
+

+

+
static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr, Jim_Obj *valObjPtr);
+
static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr, int flags);
+

+
static Jim_Var *JimCreateVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
+
{
+
    const char *name;
+
    Jim_CallFrame *framePtr;
+
    int global;
+

+

+
    Jim_Var *var = Jim_Alloc(sizeof(*var));
+

+
    var->objPtr = valObjPtr;
+
    Jim_IncrRefCount(valObjPtr);
+
    var->linkFramePtr = NULL;
+

+
    name = Jim_String(nameObjPtr);
+
    if (name[0] == ':' && name[1] == ':') {
+
        while (*++name == ':') {
+
        }
+
        framePtr = interp->topFramePtr;
+
        global = 1;
+
    }
+
    else {
+
        framePtr = interp->framePtr;
+
        global = 0;
+
    }
+

+

+
    Jim_AddHashEntry(&framePtr->vars, name, var);
+

+

+
    Jim_FreeIntRep(interp, nameObjPtr);
+
    nameObjPtr->typePtr = &variableObjType;
+
    nameObjPtr->internalRep.varValue.callFrameId = framePtr->id;
+
    nameObjPtr->internalRep.varValue.varPtr = var;
+
    nameObjPtr->internalRep.varValue.global = global;
+

+
    return var;
+
}
+

+

+
int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
+
{
+
    int err;
+
    Jim_Var *var;
+

+
    switch (SetVariableFromAny(interp, nameObjPtr)) {
+
        case JIM_DICT_SUGAR:
+
            return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
+

+
        case JIM_ERR:
+
            if (JimValidName(interp, "variable", nameObjPtr) != JIM_OK) {
+
                return JIM_ERR;
+
            }
+
            JimCreateVariable(interp, nameObjPtr, valObjPtr);
+
            break;
+

+
        case JIM_OK:
+
            var = nameObjPtr->internalRep.varValue.varPtr;
+
            if (var->linkFramePtr == NULL) {
+
                Jim_IncrRefCount(valObjPtr);
+
                Jim_DecrRefCount(interp, var->objPtr);
+
                var->objPtr = valObjPtr;
+
            }
+
            else {
+
                Jim_CallFrame *savedCallFrame;
+

+
                savedCallFrame = interp->framePtr;
+
                interp->framePtr = var->linkFramePtr;
+
                err = Jim_SetVariable(interp, var->objPtr, valObjPtr);
+
                interp->framePtr = savedCallFrame;
+
                if (err != JIM_OK)
+
                    return err;
+
            }
+
    }
+
    return JIM_OK;
+
}
+

+
int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
+
{
+
    Jim_Obj *nameObjPtr;
+
    int result;
+

+
    nameObjPtr = Jim_NewStringObj(interp, name, -1);
+
    Jim_IncrRefCount(nameObjPtr);
+
    result = Jim_SetVariable(interp, nameObjPtr, objPtr);
+
    Jim_DecrRefCount(interp, nameObjPtr);
+
    return result;
+
}
+

+
int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
+
{
+
    Jim_CallFrame *savedFramePtr;
+
    int result;
+

+
    savedFramePtr = interp->framePtr;
+
    interp->framePtr = interp->topFramePtr;
+
    result = Jim_SetVariableStr(interp, name, objPtr);
+
    interp->framePtr = savedFramePtr;
+
    return result;
+
}
+

+
int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
+
{
+
    Jim_Obj *nameObjPtr, *valObjPtr;
+
    int result;
+

+
    nameObjPtr = Jim_NewStringObj(interp, name, -1);
+
    valObjPtr = Jim_NewStringObj(interp, val, -1);
+
    Jim_IncrRefCount(nameObjPtr);
+
    Jim_IncrRefCount(valObjPtr);
+
    result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
+
    Jim_DecrRefCount(interp, nameObjPtr);
+
    Jim_DecrRefCount(interp, valObjPtr);
+
    return result;
+
}
+

+
int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
+
    Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
+
{
+
    const char *varName;
+
    const char *targetName;
+
    Jim_CallFrame *framePtr;
+
    Jim_Var *varPtr;
+

+

+
    switch (SetVariableFromAny(interp, nameObjPtr)) {
+
        case JIM_DICT_SUGAR:
+

+
            Jim_SetResultFormatted(interp, "bad variable name \"%#s\": upvar won't create a scalar variable that looks like an array element", nameObjPtr);
+
            return JIM_ERR;
+

+
        case JIM_OK:
+
            varPtr = nameObjPtr->internalRep.varValue.varPtr;
+

+
            if (varPtr->linkFramePtr == NULL) {
+
                Jim_SetResultFormatted(interp, "variable \"%#s\" already exists", nameObjPtr);
+
                return JIM_ERR;
+
            }
+

+

+
            varPtr->linkFramePtr = NULL;
+
            break;
+
    }
+

+

+

+
    varName = Jim_String(nameObjPtr);
+

+
    if (varName[0] == ':' && varName[1] == ':') {
+
        while (*++varName == ':') {
+
        }
+

+
        framePtr = interp->topFramePtr;
+
    }
+
    else {
+
        framePtr = interp->framePtr;
+
    }
+

+
    targetName = Jim_String(targetNameObjPtr);
+
    if (targetName[0] == ':' && targetName[1] == ':') {
+
        while (*++targetName == ':') {
+
        }
+
        targetNameObjPtr = Jim_NewStringObj(interp, targetName, -1);
+
        targetCallFrame = interp->topFramePtr;
+
    }
+
    Jim_IncrRefCount(targetNameObjPtr);
+

+
    if (framePtr->level < targetCallFrame->level) {
+
        Jim_SetResultFormatted(interp,
+
            "bad variable name \"%#s\": upvar won't create namespace variable that refers to procedure variable",
+
            nameObjPtr);
+
        Jim_DecrRefCount(interp, targetNameObjPtr);
+
        return JIM_ERR;
+
    }
+

+

+
    if (framePtr == targetCallFrame) {
+
        Jim_Obj *objPtr = targetNameObjPtr;
+

+

+
        while (1) {
+
            if (strcmp(Jim_String(objPtr), varName) == 0) {
+
                Jim_SetResultString(interp, "can't upvar from variable to itself", -1);
+
                Jim_DecrRefCount(interp, targetNameObjPtr);
+
                return JIM_ERR;
+
            }
+
            if (SetVariableFromAny(interp, objPtr) != JIM_OK)
+
                break;
+
            varPtr = objPtr->internalRep.varValue.varPtr;
+
            if (varPtr->linkFramePtr != targetCallFrame)
+
                break;
+
            objPtr = varPtr->objPtr;
+
        }
+
    }
+

+

+
    Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
+

+
    nameObjPtr->internalRep.varValue.varPtr->linkFramePtr = targetCallFrame;
+
    Jim_DecrRefCount(interp, targetNameObjPtr);
+
    return JIM_OK;
+
}
+

+
Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
+
{
+
    switch (SetVariableFromAny(interp, nameObjPtr)) {
+
        case JIM_OK:{
+
                Jim_Var *varPtr = nameObjPtr->internalRep.varValue.varPtr;
+

+
                if (varPtr->linkFramePtr == NULL) {
+
                    return varPtr->objPtr;
+
                }
+
                else {
+
                    Jim_Obj *objPtr;
+

+

+
                    Jim_CallFrame *savedCallFrame = interp->framePtr;
+

+
                    interp->framePtr = varPtr->linkFramePtr;
+
                    objPtr = Jim_GetVariable(interp, varPtr->objPtr, flags);
+
                    interp->framePtr = savedCallFrame;
+
                    if (objPtr) {
+
                        return objPtr;
+
                    }
+

+
                }
+
            }
+
            break;
+

+
        case JIM_DICT_SUGAR:
+

+
            return JimDictSugarGet(interp, nameObjPtr, flags);
+
    }
+
    if (flags & JIM_ERRMSG) {
+
        Jim_SetResultFormatted(interp, "can't read \"%#s\": no such variable", nameObjPtr);
+
    }
+
    return NULL;
+
}
+

+
Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
+
{
+
    Jim_CallFrame *savedFramePtr;
+
    Jim_Obj *objPtr;
+

+
    savedFramePtr = interp->framePtr;
+
    interp->framePtr = interp->topFramePtr;
+
    objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
+
    interp->framePtr = savedFramePtr;
+

+
    return objPtr;
+
}
+

+
Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
+
{
+
    Jim_Obj *nameObjPtr, *varObjPtr;
+

+
    nameObjPtr = Jim_NewStringObj(interp, name, -1);
+
    Jim_IncrRefCount(nameObjPtr);
+
    varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
+
    Jim_DecrRefCount(interp, nameObjPtr);
+
    return varObjPtr;
+
}
+

+
Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name, int flags)
+
{
+
    Jim_CallFrame *savedFramePtr;
+
    Jim_Obj *objPtr;
+

+
    savedFramePtr = interp->framePtr;
+
    interp->framePtr = interp->topFramePtr;
+
    objPtr = Jim_GetVariableStr(interp, name, flags);
+
    interp->framePtr = savedFramePtr;
+

+
    return objPtr;
+
}
+

+
int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
+
{
+
    Jim_Var *varPtr;
+
    int retval;
+
    Jim_CallFrame *framePtr;
+

+
    retval = SetVariableFromAny(interp, nameObjPtr);
+
    if (retval == JIM_DICT_SUGAR) {
+

+
        return JimDictSugarSet(interp, nameObjPtr, NULL);
+
    }
+
    else if (retval == JIM_OK) {
+
        varPtr = nameObjPtr->internalRep.varValue.varPtr;
+

+

+
        if (varPtr->linkFramePtr) {
+
            framePtr = interp->framePtr;
+
            interp->framePtr = varPtr->linkFramePtr;
+
            retval = Jim_UnsetVariable(interp, varPtr->objPtr, JIM_NONE);
+
            interp->framePtr = framePtr;
+
        }
+
        else {
+
            const char *name = Jim_String(nameObjPtr);
+
            if (nameObjPtr->internalRep.varValue.global) {
+
                name += 2;
+
                framePtr = interp->topFramePtr;
+
            }
+
            else {
+
                framePtr = interp->framePtr;
+
            }
+

+
            retval = Jim_DeleteHashEntry(&framePtr->vars, name);
+
            if (retval == JIM_OK) {
+

+
                framePtr->id = interp->callFrameEpoch++;
+
            }
+
        }
+
    }
+
    if (retval != JIM_OK && (flags & JIM_ERRMSG)) {
+
        Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such variable", nameObjPtr);
+
    }
+
    return retval;
+
}
+

+

+

+
static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,
+
    Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)
+
{
+
    const char *str, *p;
+
    int len, keyLen;
+
    Jim_Obj *varObjPtr, *keyObjPtr;
+

+
    str = Jim_GetString(objPtr, &len);
+

+
    p = strchr(str, '(');
+
    JimPanic((p == NULL, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str));
+

+
    varObjPtr = Jim_NewStringObj(interp, str, p - str);
+

+
    p++;
+
    keyLen = (str + len) - p;
+
    if (str[len - 1] == ')') {
+
        keyLen--;
+
    }
+

+

+
    keyObjPtr = Jim_NewStringObj(interp, p, keyLen);
+

+
    Jim_IncrRefCount(varObjPtr);
+
    Jim_IncrRefCount(keyObjPtr);
+
    *varPtrPtr = varObjPtr;
+
    *keyPtrPtr = keyObjPtr;
+
}
+

+
static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *valObjPtr)
+
{
+
    int err;
+

+
    SetDictSubstFromAny(interp, objPtr);
+

+
    err = Jim_SetDictKeysVector(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
+
        &objPtr->internalRep.dictSubstValue.indexObjPtr, 1, valObjPtr, JIM_MUSTEXIST);
+

+
    if (err == JIM_OK) {
+

+
        Jim_SetEmptyResult(interp);
+
    }
+
    else {
+
        if (!valObjPtr) {
+

+
            if (Jim_GetVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_NONE)) {
+
                Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such element in array",
+
                    objPtr);
+
                return err;
+
            }
+
        }
+

+
        Jim_SetResultFormatted(interp, "can't %s \"%#s\": variable isn't array",
+
            (valObjPtr ? "set" : "unset"), objPtr);
+
    }
+
    return err;
+
}
+

+
static Jim_Obj *JimDictExpandArrayVariable(Jim_Interp *interp, Jim_Obj *varObjPtr,
+
    Jim_Obj *keyObjPtr, int flags)
+
{
+
    Jim_Obj *dictObjPtr;
+
    Jim_Obj *resObjPtr = NULL;
+
    int ret;
+

+
    dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
+
    if (!dictObjPtr) {
+
        return NULL;
+
    }
+

+
    ret = Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
+
    if (ret != JIM_OK) {
+
        Jim_SetResultFormatted(interp,
+
            "can't read \"%#s(%#s)\": %s array", varObjPtr, keyObjPtr,
+
            ret < 0 ? "variable isn't" : "no such element in");
+
    }
+
    else if ((flags & JIM_UNSHARED) && Jim_IsShared(dictObjPtr)) {
+

+
        Jim_SetVariable(interp, varObjPtr, Jim_DuplicateObj(interp, dictObjPtr));
+
    }
+

+
    return resObjPtr;
+
}
+

+

+
static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+
{
+
    SetDictSubstFromAny(interp, objPtr);
+

+
    return JimDictExpandArrayVariable(interp,
+
        objPtr->internalRep.dictSubstValue.varNameObjPtr,
+
        objPtr->internalRep.dictSubstValue.indexObjPtr, flags);
+
}
+

+

+

+
void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);
+
    Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
+
}
+

+
void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    JIM_NOTUSED(interp);
+

+
    dupPtr->internalRep.dictSubstValue.varNameObjPtr =
+
        srcPtr->internalRep.dictSubstValue.varNameObjPtr;
+
    dupPtr->internalRep.dictSubstValue.indexObjPtr = srcPtr->internalRep.dictSubstValue.indexObjPtr;
+
    dupPtr->typePtr = &dictSubstObjType;
+
}
+

+

+
static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    if (objPtr->typePtr != &dictSubstObjType) {
+
        Jim_Obj *varObjPtr, *keyObjPtr;
+

+
        if (objPtr->typePtr == &interpolatedObjType) {
+

+

+
            varObjPtr = objPtr->internalRep.dictSubstValue.varNameObjPtr;
+
            keyObjPtr = objPtr->internalRep.dictSubstValue.indexObjPtr;
+

+
            Jim_IncrRefCount(varObjPtr);
+
            Jim_IncrRefCount(keyObjPtr);
+
        }
+
        else {
+
            JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
+
        }
+

+
        Jim_FreeIntRep(interp, objPtr);
+
        objPtr->typePtr = &dictSubstObjType;
+
        objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;
+
        objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;
+
    }
+
}
+

+
static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    Jim_Obj *resObjPtr = NULL;
+
    Jim_Obj *substKeyObjPtr = NULL;
+

+
    SetDictSubstFromAny(interp, objPtr);
+

+
    if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,
+
            &substKeyObjPtr, JIM_NONE)
+
        != JIM_OK) {
+
        return NULL;
+
    }
+
    Jim_IncrRefCount(substKeyObjPtr);
+
    resObjPtr =
+
        JimDictExpandArrayVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
+
        substKeyObjPtr, 0);
+
    Jim_DecrRefCount(interp, substKeyObjPtr);
+

+
    return resObjPtr;
+
}
+

+
static Jim_Obj *JimExpandExprSugar(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    Jim_Obj *resultObjPtr;
+

+
    if (Jim_EvalExpression(interp, objPtr, &resultObjPtr) == JIM_OK) {
+

+
        resultObjPtr->refCount--;
+
        return resultObjPtr;
+
    }
+
    return NULL;
+
}
+

+

+
static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp, Jim_CallFrame *parent, Jim_Obj *nsObj)
+
{
+
    Jim_CallFrame *cf;
+

+
    if (interp->freeFramesList) {
+
        cf = interp->freeFramesList;
+
        interp->freeFramesList = cf->next;
+

+
        cf->argv = NULL;
+
        cf->argc = 0;
+
        cf->procArgsObjPtr = NULL;
+
        cf->procBodyObjPtr = NULL;
+
        cf->next = NULL;
+
        cf->staticVars = NULL;
+
        cf->localCommands = NULL;
+
        cf->tailcallObj = NULL;
+
        cf->tailcallCmd = NULL;
+
    }
+
    else {
+
        cf = Jim_Alloc(sizeof(*cf));
+
        memset(cf, 0, sizeof(*cf));
+

+
        Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);
+
    }
+

+
    cf->id = interp->callFrameEpoch++;
+
    cf->parent = parent;
+
    cf->level = parent ? parent->level + 1 : 0;
+
    cf->nsObj = nsObj;
+
    Jim_IncrRefCount(nsObj);
+

+
    return cf;
+
}
+

+
static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands)
+
{
+

+
    if (localCommands) {
+
        Jim_Obj *cmdNameObj;
+

+
        while ((cmdNameObj = Jim_StackPop(localCommands)) != NULL) {
+
            Jim_HashEntry *he;
+
            Jim_Obj *fqObjName;
+
            Jim_HashTable *ht = &interp->commands;
+

+
            const char *fqname = JimQualifyName(interp, Jim_String(cmdNameObj), &fqObjName);
+

+
            he = Jim_FindHashEntry(ht, fqname);
+

+
            if (he) {
+
                Jim_Cmd *cmd = Jim_GetHashEntryVal(he);
+
                if (cmd->prevCmd) {
+
                    Jim_Cmd *prevCmd = cmd->prevCmd;
+
                    cmd->prevCmd = NULL;
+

+

+
                    JimDecrCmdRefCount(interp, cmd);
+

+

+
                    Jim_SetHashVal(ht, he, prevCmd);
+
                }
+
                else {
+
                    Jim_DeleteHashEntry(ht, fqname);
+
                }
+
                Jim_InterpIncrProcEpoch(interp);
+
            }
+
            Jim_DecrRefCount(interp, cmdNameObj);
+
            JimFreeQualifiedName(interp, fqObjName);
+
        }
+
        Jim_FreeStack(localCommands);
+
        Jim_Free(localCommands);
+
    }
+
    return JIM_OK;
+
}
+

+

+
#define JIM_FCF_FULL 0
+
#define JIM_FCF_REUSE 1
+
static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action)
+
 {
+
    JimDeleteLocalProcs(interp, cf->localCommands);
+

+
    if (cf->procArgsObjPtr)
+
        Jim_DecrRefCount(interp, cf->procArgsObjPtr);
+
    if (cf->procBodyObjPtr)
+
        Jim_DecrRefCount(interp, cf->procBodyObjPtr);
+
    Jim_DecrRefCount(interp, cf->nsObj);
+
    if (action == JIM_FCF_FULL || cf->vars.size != JIM_HT_INITIAL_SIZE)
+
        Jim_FreeHashTable(&cf->vars);
+
    else {
+
        int i;
+
        Jim_HashEntry **table = cf->vars.table, *he;
+

+
        for (i = 0; i < JIM_HT_INITIAL_SIZE; i++) {
+
            he = table[i];
+
            while (he != NULL) {
+
                Jim_HashEntry *nextEntry = he->next;
+
                Jim_Var *varPtr = Jim_GetHashEntryVal(he);
+

+
                Jim_DecrRefCount(interp, varPtr->objPtr);
+
                Jim_Free(Jim_GetHashEntryKey(he));
+
                Jim_Free(varPtr);
+
                Jim_Free(he);
+
                table[i] = NULL;
+
                he = nextEntry;
+
            }
+
        }
+
        cf->vars.used = 0;
+
    }
+
    cf->next = interp->freeFramesList;
+
    interp->freeFramesList = cf;
+
}
+

+

+

+
int Jim_IsBigEndian(void)
+
{
+
    union {
+
        unsigned short s;
+
        unsigned char c[2];
+
    } uval = {0x0102};
+

+
    return uval.c[0] == 1;
+
}
+

+

+
Jim_Interp *Jim_CreateInterp(void)
+
{
+
    Jim_Interp *i = Jim_Alloc(sizeof(*i));
+

+
    memset(i, 0, sizeof(*i));
+

+
    i->maxCallFrameDepth = JIM_MAX_CALLFRAME_DEPTH;
+
    i->maxEvalDepth = JIM_MAX_EVAL_DEPTH;
+
    i->lastCollectTime = time(NULL);
+

+
    Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
+
#ifdef JIM_REFERENCES
+
    Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
+
#endif
+
    Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
+
    Jim_InitHashTable(&i->packages, &JimPackageHashTableType, NULL);
+
    i->emptyObj = Jim_NewEmptyStringObj(i);
+
    i->trueObj = Jim_NewIntObj(i, 1);
+
    i->falseObj = Jim_NewIntObj(i, 0);
+
    i->framePtr = i->topFramePtr = JimCreateCallFrame(i, NULL, i->emptyObj);
+
    i->errorFileNameObj = i->emptyObj;
+
    i->result = i->emptyObj;
+
    i->stackTrace = Jim_NewListObj(i, NULL, 0);
+
    i->unknown = Jim_NewStringObj(i, "unknown", -1);
+
    i->errorProc = i->emptyObj;
+
    i->currentScriptObj = Jim_NewEmptyStringObj(i);
+
    i->nullScriptObj = Jim_NewEmptyStringObj(i);
+
    Jim_IncrRefCount(i->emptyObj);
+
    Jim_IncrRefCount(i->errorFileNameObj);
+
    Jim_IncrRefCount(i->result);
+
    Jim_IncrRefCount(i->stackTrace);
+
    Jim_IncrRefCount(i->unknown);
+
    Jim_IncrRefCount(i->currentScriptObj);
+
    Jim_IncrRefCount(i->nullScriptObj);
+
    Jim_IncrRefCount(i->errorProc);
+
    Jim_IncrRefCount(i->trueObj);
+
    Jim_IncrRefCount(i->falseObj);
+

+

+
    Jim_SetVariableStrWithStr(i, JIM_LIBPATH, TCL_LIBRARY);
+
    Jim_SetVariableStrWithStr(i, JIM_INTERACTIVE, "0");
+

+
    Jim_SetVariableStrWithStr(i, "tcl_platform(engine)", "Jim");
+
    Jim_SetVariableStrWithStr(i, "tcl_platform(os)", TCL_PLATFORM_OS);
+
    Jim_SetVariableStrWithStr(i, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM);
+
    Jim_SetVariableStrWithStr(i, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR);
+
    Jim_SetVariableStrWithStr(i, "tcl_platform(byteOrder)", Jim_IsBigEndian() ? "bigEndian" : "littleEndian");
+
    Jim_SetVariableStrWithStr(i, "tcl_platform(threaded)", "0");
+
    Jim_SetVariableStr(i, "tcl_platform(pointerSize)", Jim_NewIntObj(i, sizeof(void *)));
+
    Jim_SetVariableStr(i, "tcl_platform(wordSize)", Jim_NewIntObj(i, sizeof(jim_wide)));
+

+
    return i;
+
}
+

+
void Jim_FreeInterp(Jim_Interp *i)
+
{
+
    Jim_CallFrame *cf, *cfx;
+

+
    Jim_Obj *objPtr, *nextObjPtr;
+

+

+
    for (cf = i->framePtr; cf; cf = cfx) {
+
        cfx = cf->parent;
+
        JimFreeCallFrame(i, cf, JIM_FCF_FULL);
+
    }
+

+
    Jim_DecrRefCount(i, i->emptyObj);
+
    Jim_DecrRefCount(i, i->trueObj);
+
    Jim_DecrRefCount(i, i->falseObj);
+
    Jim_DecrRefCount(i, i->result);
+
    Jim_DecrRefCount(i, i->stackTrace);
+
    Jim_DecrRefCount(i, i->errorProc);
+
    Jim_DecrRefCount(i, i->unknown);
+
    Jim_DecrRefCount(i, i->errorFileNameObj);
+
    Jim_DecrRefCount(i, i->currentScriptObj);
+
    Jim_DecrRefCount(i, i->nullScriptObj);
+
    Jim_FreeHashTable(&i->commands);
+
#ifdef JIM_REFERENCES
+
    Jim_FreeHashTable(&i->references);
+
#endif
+
    Jim_FreeHashTable(&i->packages);
+
    Jim_Free(i->prngState);
+
    Jim_FreeHashTable(&i->assocData);
+

+
#ifdef JIM_MAINTAINER
+
    if (i->liveList != NULL) {
+
        objPtr = i->liveList;
+

+
        printf("\n-------------------------------------\n");
+
        printf("Objects still in the free list:\n");
+
        while (objPtr) {
+
            const char *type = objPtr->typePtr ? objPtr->typePtr->name : "string";
+

+
            if (objPtr->bytes && strlen(objPtr->bytes) > 20) {
+
                printf("%p (%d) %-10s: '%.20s...'\n",
+
                    (void *)objPtr, objPtr->refCount, type, objPtr->bytes);
+
            }
+
            else {
+
                printf("%p (%d) %-10s: '%s'\n",
+
                    (void *)objPtr, objPtr->refCount, type, objPtr->bytes ? objPtr->bytes : "(null)");
+
            }
+
            if (objPtr->typePtr == &sourceObjType) {
+
                printf("FILE %s LINE %d\n",
+
                    Jim_String(objPtr->internalRep.sourceValue.fileNameObj),
+
                    objPtr->internalRep.sourceValue.lineNumber);
+
            }
+
            objPtr = objPtr->nextObjPtr;
+
        }
+
        printf("-------------------------------------\n\n");
+
        JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
+
    }
+
#endif
+

+

+
    objPtr = i->freeList;
+
    while (objPtr) {
+
        nextObjPtr = objPtr->nextObjPtr;
+
        Jim_Free(objPtr);
+
        objPtr = nextObjPtr;
+
    }
+

+

+
    for (cf = i->freeFramesList; cf; cf = cfx) {
+
        cfx = cf->next;
+
        if (cf->vars.table)
+
            Jim_FreeHashTable(&cf->vars);
+
        Jim_Free(cf);
+
    }
+

+

+
    Jim_Free(i);
+
}
+

+
Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr)
+
{
+
    long level;
+
    const char *str;
+
    Jim_CallFrame *framePtr;
+

+
    if (levelObjPtr) {
+
        str = Jim_String(levelObjPtr);
+
        if (str[0] == '#') {
+
            char *endptr;
+

+
            level = jim_strtol(str + 1, &endptr);
+
            if (str[1] == '\0' || endptr[0] != '\0') {
+
                level = -1;
+
            }
+
        }
+
        else {
+
            if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0) {
+
                level = -1;
+
            }
+
            else {
+

+
                level = interp->framePtr->level - level;
+
            }
+
        }
+
    }
+
    else {
+
        str = "1";
+
        level = interp->framePtr->level - 1;
+
    }
+

+
    if (level == 0) {
+
        return interp->topFramePtr;
+
    }
+
    if (level > 0) {
+

+
        for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parent) {
+
            if (framePtr->level == level) {
+
                return framePtr;
+
            }
+
        }
+
    }
+

+
    Jim_SetResultFormatted(interp, "bad level \"%s\"", str);
+
    return NULL;
+
}
+

+
static Jim_CallFrame *JimGetCallFrameByInteger(Jim_Interp *interp, Jim_Obj *levelObjPtr)
+
{
+
    long level;
+
    Jim_CallFrame *framePtr;
+

+
    if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
+
        if (level <= 0) {
+

+
            level = interp->framePtr->level + level;
+
        }
+

+
        if (level == 0) {
+
            return interp->topFramePtr;
+
        }
+

+

+
        for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parent) {
+
            if (framePtr->level == level) {
+
                return framePtr;
+
            }
+
        }
+
    }
+

+
    Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
+
    return NULL;
+
}
+

+
static void JimResetStackTrace(Jim_Interp *interp)
+
{
+
    Jim_DecrRefCount(interp, interp->stackTrace);
+
    interp->stackTrace = Jim_NewListObj(interp, NULL, 0);
+
    Jim_IncrRefCount(interp->stackTrace);
+
}
+

+
static void JimSetStackTrace(Jim_Interp *interp, Jim_Obj *stackTraceObj)
+
{
+
    int len;
+

+

+
    Jim_IncrRefCount(stackTraceObj);
+
    Jim_DecrRefCount(interp, interp->stackTrace);
+
    interp->stackTrace = stackTraceObj;
+
    interp->errorFlag = 1;
+

+
    len = Jim_ListLength(interp, interp->stackTrace);
+
    if (len >= 3) {
+
        if (Jim_Length(Jim_ListGetIndex(interp, interp->stackTrace, len - 2)) == 0) {
+
            interp->addStackTrace = 1;
+
        }
+
    }
+
}
+

+
static void JimAppendStackTrace(Jim_Interp *interp, const char *procname,
+
    Jim_Obj *fileNameObj, int linenr)
+
{
+
    if (strcmp(procname, "unknown") == 0) {
+
        procname = "";
+
    }
+
    if (!*procname && !Jim_Length(fileNameObj)) {
+

+
        return;
+
    }
+

+
    if (Jim_IsShared(interp->stackTrace)) {
+
        Jim_DecrRefCount(interp, interp->stackTrace);
+
        interp->stackTrace = Jim_DuplicateObj(interp, interp->stackTrace);
+
        Jim_IncrRefCount(interp->stackTrace);
+
    }
+

+

+
    if (!*procname && Jim_Length(fileNameObj)) {
+

+
        int len = Jim_ListLength(interp, interp->stackTrace);
+

+
        if (len >= 3) {
+
            Jim_Obj *objPtr = Jim_ListGetIndex(interp, interp->stackTrace, len - 3);
+
            if (Jim_Length(objPtr)) {
+

+
                objPtr = Jim_ListGetIndex(interp, interp->stackTrace, len - 2);
+
                if (Jim_Length(objPtr) == 0) {
+

+
                    ListSetIndex(interp, interp->stackTrace, len - 2, fileNameObj, 0);
+
                    ListSetIndex(interp, interp->stackTrace, len - 1, Jim_NewIntObj(interp, linenr), 0);
+
                    return;
+
                }
+
            }
+
        }
+
    }
+

+
    Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewStringObj(interp, procname, -1));
+
    Jim_ListAppendElement(interp, interp->stackTrace, fileNameObj);
+
    Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewIntObj(interp, linenr));
+
}
+

+
int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc * delProc,
+
    void *data)
+
{
+
    AssocDataValue *assocEntryPtr = (AssocDataValue *) Jim_Alloc(sizeof(AssocDataValue));
+

+
    assocEntryPtr->delProc = delProc;
+
    assocEntryPtr->data = data;
+
    return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
+
}
+

+
void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
+
{
+
    Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
+

+
    if (entryPtr != NULL) {
+
        AssocDataValue *assocEntryPtr = Jim_GetHashEntryVal(entryPtr);
+
        return assocEntryPtr->data;
+
    }
+
    return NULL;
+
}
+

+
int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
+
{
+
    return Jim_DeleteHashEntry(&interp->assocData, key);
+
}
+

+
int Jim_GetExitCode(Jim_Interp *interp)
+
{
+
    return interp->exitCode;
+
}
+

+
static void UpdateStringOfInt(struct Jim_Obj *objPtr);
+
static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
+

+
static const Jim_ObjType intObjType = {
+
    "int",
+
    NULL,
+
    NULL,
+
    UpdateStringOfInt,
+
    JIM_TYPE_NONE,
+
};
+

+
static const Jim_ObjType coercedDoubleObjType = {
+
    "coerced-double",
+
    NULL,
+
    NULL,
+
    UpdateStringOfInt,
+
    JIM_TYPE_NONE,
+
};
+

+

+
static void UpdateStringOfInt(struct Jim_Obj *objPtr)
+
{
+
    char buf[JIM_INTEGER_SPACE + 1];
+
    jim_wide wideValue = JimWideValue(objPtr);
+
    int pos = 0;
+

+
    if (wideValue == 0) {
+
        buf[pos++] = '0';
+
    }
+
    else {
+
        char tmp[JIM_INTEGER_SPACE];
+
        int num = 0;
+
        int i;
+

+
        if (wideValue < 0) {
+
            buf[pos++] = '-';
+
            i = wideValue % 10;
+
            tmp[num++] = (i > 0) ? (10 - i) : -i;
+
            wideValue /= -10;
+
        }
+

+
        while (wideValue) {
+
            tmp[num++] = wideValue % 10;
+
            wideValue /= 10;
+
        }
+

+
        for (i = 0; i < num; i++) {
+
            buf[pos++] = '0' + tmp[num - i - 1];
+
        }
+
    }
+
    buf[pos] = 0;
+

+
    JimSetStringBytes(objPtr, buf);
+
}
+

+
static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+
{
+
    jim_wide wideValue;
+
    const char *str;
+

+
    if (objPtr->typePtr == &coercedDoubleObjType) {
+

+
        objPtr->typePtr = &intObjType;
+
        return JIM_OK;
+
    }
+

+

+
    str = Jim_String(objPtr);
+

+
    if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
+
        if (flags & JIM_ERRMSG) {
+
            Jim_SetResultFormatted(interp, "expected integer but got \"%#s\"", objPtr);
+
        }
+
        return JIM_ERR;
+
    }
+
    if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) && errno == ERANGE) {
+
        Jim_SetResultString(interp, "Integer value too big to be represented", -1);
+
        return JIM_ERR;
+
    }
+

+
    Jim_FreeIntRep(interp, objPtr);
+
    objPtr->typePtr = &intObjType;
+
    objPtr->internalRep.wideValue = wideValue;
+
    return JIM_OK;
+
}
+

+
#ifdef JIM_OPTIMIZATION
+
static int JimIsWide(Jim_Obj *objPtr)
+
{
+
    return objPtr->typePtr == &intObjType;
+
}
+
#endif
+

+
int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
+
{
+
    if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
+
        return JIM_ERR;
+
    *widePtr = JimWideValue(objPtr);
+
    return JIM_OK;
+
}
+

+

+
static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
+
{
+
    if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
+
        return JIM_ERR;
+
    *widePtr = JimWideValue(objPtr);
+
    return JIM_OK;
+
}
+

+
int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
+
{
+
    jim_wide wideValue;
+
    int retval;
+

+
    retval = Jim_GetWide(interp, objPtr, &wideValue);
+
    if (retval == JIM_OK) {
+
        *longPtr = (long)wideValue;
+
        return JIM_OK;
+
    }
+
    return JIM_ERR;
+
}
+

+
Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
+
{
+
    Jim_Obj *objPtr;
+

+
    objPtr = Jim_NewObj(interp);
+
    objPtr->typePtr = &intObjType;
+
    objPtr->bytes = NULL;
+
    objPtr->internalRep.wideValue = wideValue;
+
    return objPtr;
+
}
+

+
#define JIM_DOUBLE_SPACE 30
+

+
static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
+
static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
+

+
static const Jim_ObjType doubleObjType = {
+
    "double",
+
    NULL,
+
    NULL,
+
    UpdateStringOfDouble,
+
    JIM_TYPE_NONE,
+
};
+

+
#ifndef HAVE_ISNAN
+
#undef isnan
+
#define isnan(X) ((X) != (X))
+
#endif
+
#ifndef HAVE_ISINF
+
#undef isinf
+
#define isinf(X) (1.0 / (X) == 0.0)
+
#endif
+

+
static void UpdateStringOfDouble(struct Jim_Obj *objPtr)
+
{
+
    double value = objPtr->internalRep.doubleValue;
+

+
    if (isnan(value)) {
+
        JimSetStringBytes(objPtr, "NaN");
+
        return;
+
    }
+
    if (isinf(value)) {
+
        if (value < 0) {
+
            JimSetStringBytes(objPtr, "-Inf");
+
        }
+
        else {
+
            JimSetStringBytes(objPtr, "Inf");
+
        }
+
        return;
+
    }
+
    {
+
        char buf[JIM_DOUBLE_SPACE + 1];
+
        int i;
+
        int len = sprintf(buf, "%.12g", value);
+

+

+
        for (i = 0; i < len; i++) {
+
            if (buf[i] == '.' || buf[i] == 'e') {
+
#if defined(JIM_SPRINTF_DOUBLE_NEEDS_FIX)
+
                char *e = strchr(buf, 'e');
+
                if (e && (e[1] == '-' || e[1] == '+') && e[2] == '0') {
+

+
                    e += 2;
+
                    memmove(e, e + 1, len - (e - buf));
+
                }
+
#endif
+
                break;
+
            }
+
        }
+
        if (buf[i] == '\0') {
+
            buf[i++] = '.';
+
            buf[i++] = '0';
+
            buf[i] = '\0';
+
        }
+
        JimSetStringBytes(objPtr, buf);
+
    }
+
}
+

+
static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    double doubleValue;
+
    jim_wide wideValue;
+
    const char *str;
+

+
    str = Jim_String(objPtr);
+

+
#ifdef HAVE_LONG_LONG
+

+
#define MIN_INT_IN_DOUBLE -(1LL << 53)
+
#define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
+

+
    if (objPtr->typePtr == &intObjType
+
        && JimWideValue(objPtr) >= MIN_INT_IN_DOUBLE
+
        && JimWideValue(objPtr) <= MAX_INT_IN_DOUBLE) {
+

+

+
        objPtr->typePtr = &coercedDoubleObjType;
+
        return JIM_OK;
+
    }
+
    else
+
#endif
+
    if (Jim_StringToWide(str, &wideValue, 10) == JIM_OK) {
+

+
        Jim_FreeIntRep(interp, objPtr);
+
        objPtr->typePtr = &coercedDoubleObjType;
+
        objPtr->internalRep.wideValue = wideValue;
+
        return JIM_OK;
+
    }
+
    else {
+

+
        if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
+
            Jim_SetResultFormatted(interp, "expected floating-point number but got \"%#s\"", objPtr);
+
            return JIM_ERR;
+
        }
+

+
        Jim_FreeIntRep(interp, objPtr);
+
    }
+
    objPtr->typePtr = &doubleObjType;
+
    objPtr->internalRep.doubleValue = doubleValue;
+
    return JIM_OK;
+
}
+

+
int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
+
{
+
    if (objPtr->typePtr == &coercedDoubleObjType) {
+
        *doublePtr = JimWideValue(objPtr);
+
        return JIM_OK;
+
    }
+
    if (objPtr->typePtr != &doubleObjType && SetDoubleFromAny(interp, objPtr) == JIM_ERR)
+
        return JIM_ERR;
+

+
    if (objPtr->typePtr == &coercedDoubleObjType) {
+
        *doublePtr = JimWideValue(objPtr);
+
    }
+
    else {
+
        *doublePtr = objPtr->internalRep.doubleValue;
+
    }
+
    return JIM_OK;
+
}
+

+
Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
+
{
+
    Jim_Obj *objPtr;
+

+
    objPtr = Jim_NewObj(interp);
+
    objPtr->typePtr = &doubleObjType;
+
    objPtr->bytes = NULL;
+
    objPtr->internalRep.doubleValue = doubleValue;
+
    return objPtr;
+
}
+

+
static int SetBooleanFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
+

+
int Jim_GetBoolean(Jim_Interp *interp, Jim_Obj *objPtr, int * booleanPtr)
+
{
+
    if (objPtr->typePtr != &intObjType && SetBooleanFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
+
        return JIM_ERR;
+
    *booleanPtr = (int) JimWideValue(objPtr);
+
    return JIM_OK;
+
}
+

+
static int SetBooleanFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+
{
+
    static const char * const falses[] = {
+
        "0", "false", "no", "off", NULL
+
    };
+
    static const char * const trues[] = {
+
        "1", "true", "yes", "on", NULL
+
    };
+

+
    int boolean;
+

+
    int index;
+
    if (Jim_GetEnum(interp, objPtr, falses, &index, NULL, 0) == JIM_OK) {
+
        boolean = 0;
+
    } else if (Jim_GetEnum(interp, objPtr, trues, &index, NULL, 0) == JIM_OK) {
+
        boolean = 1;
+
    } else {
+
        if (flags & JIM_ERRMSG) {
+
            Jim_SetResultFormatted(interp, "expected boolean but got \"%#s\"", objPtr);
+
        }
+
        return JIM_ERR;
+
    }
+

+

+
    Jim_FreeIntRep(interp, objPtr);
+
    objPtr->typePtr = &intObjType;
+
    objPtr->internalRep.wideValue = boolean;
+
    return JIM_OK;
+
}
+

+
static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec);
+
static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
+
static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+
static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
static void UpdateStringOfList(struct Jim_Obj *objPtr);
+
static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+

+
static const Jim_ObjType listObjType = {
+
    "list",
+
    FreeListInternalRep,
+
    DupListInternalRep,
+
    UpdateStringOfList,
+
    JIM_TYPE_NONE,
+
};
+

+
void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    int i;
+

+
    for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
+
        Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
+
    }
+
    Jim_Free(objPtr->internalRep.listValue.ele);
+
}
+

+
void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    int i;
+

+
    JIM_NOTUSED(interp);
+

+
    dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
+
    dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
+
    dupPtr->internalRep.listValue.ele =
+
        Jim_Alloc(sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.maxLen);
+
    memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
+
        sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.len);
+
    for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
+
        Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
+
    }
+
    dupPtr->typePtr = &listObjType;
+
}
+

+
#define JIM_ELESTR_SIMPLE 0
+
#define JIM_ELESTR_BRACE 1
+
#define JIM_ELESTR_QUOTE 2
+
static unsigned char ListElementQuotingType(const char *s, int len)
+
{
+
    int i, level, blevel, trySimple = 1;
+

+

+
    if (len == 0)
+
        return JIM_ELESTR_BRACE;
+
    if (s[0] == '"' || s[0] == '{') {
+
        trySimple = 0;
+
        goto testbrace;
+
    }
+
    for (i = 0; i < len; i++) {
+
        switch (s[i]) {
+
            case ' ':
+
            case '$':
+
            case '"':
+
            case '[':
+
            case ']':
+
            case ';':
+
            case '\\':
+
            case '\r':
+
            case '\n':
+
            case '\t':
+
            case '\f':
+
            case '\v':
+
                trySimple = 0;
+

+
            case '{':
+
            case '}':
+
                goto testbrace;
+
        }
+
    }
+
    return JIM_ELESTR_SIMPLE;
+

+
  testbrace:
+

+
    if (s[len - 1] == '\\')
+
        return JIM_ELESTR_QUOTE;
+
    level = 0;
+
    blevel = 0;
+
    for (i = 0; i < len; i++) {
+
        switch (s[i]) {
+
            case '{':
+
                level++;
+
                break;
+
            case '}':
+
                level--;
+
                if (level < 0)
+
                    return JIM_ELESTR_QUOTE;
+
                break;
+
            case '[':
+
                blevel++;
+
                break;
+
            case ']':
+
                blevel--;
+
                break;
+
            case '\\':
+
                if (s[i + 1] == '\n')
+
                    return JIM_ELESTR_QUOTE;
+
                else if (s[i + 1] != '\0')
+
                    i++;
+
                break;
+
        }
+
    }
+
    if (blevel < 0) {
+
        return JIM_ELESTR_QUOTE;
+
    }
+

+
    if (level == 0) {
+
        if (!trySimple)
+
            return JIM_ELESTR_BRACE;
+
        for (i = 0; i < len; i++) {
+
            switch (s[i]) {
+
                case ' ':
+
                case '$':
+
                case '"':
+
                case '[':
+
                case ']':
+
                case ';':
+
                case '\\':
+
                case '\r':
+
                case '\n':
+
                case '\t':
+
                case '\f':
+
                case '\v':
+
                    return JIM_ELESTR_BRACE;
+
                    break;
+
            }
+
        }
+
        return JIM_ELESTR_SIMPLE;
+
    }
+
    return JIM_ELESTR_QUOTE;
+
}
+

+
static int BackslashQuoteString(const char *s, int len, char *q)
+
{
+
    char *p = q;
+

+
    while (len--) {
+
        switch (*s) {
+
            case ' ':
+
            case '$':
+
            case '"':
+
            case '[':
+
            case ']':
+
            case '{':
+
            case '}':
+
            case ';':
+
            case '\\':
+
                *p++ = '\\';
+
                *p++ = *s++;
+
                break;
+
            case '\n':
+
                *p++ = '\\';
+
                *p++ = 'n';
+
                s++;
+
                break;
+
            case '\r':
+
                *p++ = '\\';
+
                *p++ = 'r';
+
                s++;
+
                break;
+
            case '\t':
+
                *p++ = '\\';
+
                *p++ = 't';
+
                s++;
+
                break;
+
            case '\f':
+
                *p++ = '\\';
+
                *p++ = 'f';
+
                s++;
+
                break;
+
            case '\v':
+
                *p++ = '\\';
+
                *p++ = 'v';
+
                s++;
+
                break;
+
            default:
+
                *p++ = *s++;
+
                break;
+
        }
+
    }
+
    *p = '\0';
+

+
    return p - q;
+
}
+

+
static void JimMakeListStringRep(Jim_Obj *objPtr, Jim_Obj **objv, int objc)
+
{
+
    #define STATIC_QUOTING_LEN 32
+
    int i, bufLen, realLength;
+
    const char *strRep;
+
    char *p;
+
    unsigned char *quotingType, staticQuoting[STATIC_QUOTING_LEN];
+

+

+
    if (objc > STATIC_QUOTING_LEN) {
+
        quotingType = Jim_Alloc(objc);
+
    }
+
    else {
+
        quotingType = staticQuoting;
+
    }
+
    bufLen = 0;
+
    for (i = 0; i < objc; i++) {
+
        int len;
+

+
        strRep = Jim_GetString(objv[i], &len);
+
        quotingType[i] = ListElementQuotingType(strRep, len);
+
        switch (quotingType[i]) {
+
            case JIM_ELESTR_SIMPLE:
+
                if (i != 0 || strRep[0] != '#') {
+
                    bufLen += len;
+
                    break;
+
                }
+

+
                quotingType[i] = JIM_ELESTR_BRACE;
+

+
            case JIM_ELESTR_BRACE:
+
                bufLen += len + 2;
+
                break;
+
            case JIM_ELESTR_QUOTE:
+
                bufLen += len * 2;
+
                break;
+
        }
+
        bufLen++;
+
    }
+
    bufLen++;
+

+

+
    p = objPtr->bytes = Jim_Alloc(bufLen + 1);
+
    realLength = 0;
+
    for (i = 0; i < objc; i++) {
+
        int len, qlen;
+

+
        strRep = Jim_GetString(objv[i], &len);
+

+
        switch (quotingType[i]) {
+
            case JIM_ELESTR_SIMPLE:
+
                memcpy(p, strRep, len);
+
                p += len;
+
                realLength += len;
+
                break;
+
            case JIM_ELESTR_BRACE:
+
                *p++ = '{';
+
                memcpy(p, strRep, len);
+
                p += len;
+
                *p++ = '}';
+
                realLength += len + 2;
+
                break;
+
            case JIM_ELESTR_QUOTE:
+
                if (i == 0 && strRep[0] == '#') {
+
                    *p++ = '\\';
+
                    realLength++;
+
                }
+
                qlen = BackslashQuoteString(strRep, len, p);
+
                p += qlen;
+
                realLength += qlen;
+
                break;
+
        }
+

+
        if (i + 1 != objc) {
+
            *p++ = ' ';
+
            realLength++;
+
        }
+
    }
+
    *p = '\0';
+
    objPtr->length = realLength;
+

+
    if (quotingType != staticQuoting) {
+
        Jim_Free(quotingType);
+
    }
+
}
+

+
static void UpdateStringOfList(struct Jim_Obj *objPtr)
+
{
+
    JimMakeListStringRep(objPtr, objPtr->internalRep.listValue.ele, objPtr->internalRep.listValue.len);
+
}
+

+
static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+
{
+
    struct JimParserCtx parser;
+
    const char *str;
+
    int strLen;
+
    Jim_Obj *fileNameObj;
+
    int linenr;
+

+
    if (objPtr->typePtr == &listObjType) {
+
        return JIM_OK;
+
    }
+

+
    if (Jim_IsDict(objPtr) && objPtr->bytes == NULL) {
+
        Jim_Obj **listObjPtrPtr;
+
        int len;
+
        int i;
+

+
        listObjPtrPtr = JimDictPairs(objPtr, &len);
+
        for (i = 0; i < len; i++) {
+
            Jim_IncrRefCount(listObjPtrPtr[i]);
+
        }
+

+

+
        Jim_FreeIntRep(interp, objPtr);
+
        objPtr->typePtr = &listObjType;
+
        objPtr->internalRep.listValue.len = len;
+
        objPtr->internalRep.listValue.maxLen = len;
+
        objPtr->internalRep.listValue.ele = listObjPtrPtr;
+

+
        return JIM_OK;
+
    }
+

+

+
    if (objPtr->typePtr == &sourceObjType) {
+
        fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
+
        linenr = objPtr->internalRep.sourceValue.lineNumber;
+
    }
+
    else {
+
        fileNameObj = interp->emptyObj;
+
        linenr = 1;
+
    }
+
    Jim_IncrRefCount(fileNameObj);
+

+

+
    str = Jim_GetString(objPtr, &strLen);
+

+
    Jim_FreeIntRep(interp, objPtr);
+
    objPtr->typePtr = &listObjType;
+
    objPtr->internalRep.listValue.len = 0;
+
    objPtr->internalRep.listValue.maxLen = 0;
+
    objPtr->internalRep.listValue.ele = NULL;
+

+

+
    if (strLen) {
+
        JimParserInit(&parser, str, strLen, linenr);
+
        while (!parser.eof) {
+
            Jim_Obj *elementPtr;
+

+
            JimParseList(&parser);
+
            if (parser.tt != JIM_TT_STR && parser.tt != JIM_TT_ESC)
+
                continue;
+
            elementPtr = JimParserGetTokenObj(interp, &parser);
+
            JimSetSourceInfo(interp, elementPtr, fileNameObj, parser.tline);
+
            ListAppendElement(objPtr, elementPtr);
+
        }
+
    }
+
    Jim_DecrRefCount(interp, fileNameObj);
+
    return JIM_OK;
+
}
+

+
Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
+
{
+
    Jim_Obj *objPtr;
+

+
    objPtr = Jim_NewObj(interp);
+
    objPtr->typePtr = &listObjType;
+
    objPtr->bytes = NULL;
+
    objPtr->internalRep.listValue.ele = NULL;
+
    objPtr->internalRep.listValue.len = 0;
+
    objPtr->internalRep.listValue.maxLen = 0;
+

+
    if (len) {
+
        ListInsertElements(objPtr, 0, len, elements);
+
    }
+

+
    return objPtr;
+
}
+

+
static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *listLen,
+
    Jim_Obj ***listVec)
+
{
+
    *listLen = Jim_ListLength(interp, listObj);
+
    *listVec = listObj->internalRep.listValue.ele;
+
}
+

+

+
static int JimSign(jim_wide w)
+
{
+
    if (w == 0) {
+
        return 0;
+
    }
+
    else if (w < 0) {
+
        return -1;
+
    }
+
    return 1;
+
}
+

+

+
struct lsort_info {
+
    jmp_buf jmpbuf;
+
    Jim_Obj *command;
+
    Jim_Interp *interp;
+
    enum {
+
        JIM_LSORT_ASCII,
+
        JIM_LSORT_NOCASE,
+
        JIM_LSORT_INTEGER,
+
        JIM_LSORT_REAL,
+
        JIM_LSORT_COMMAND
+
    } type;
+
    int order;
+
    int index;
+
    int indexed;
+
    int unique;
+
    int (*subfn)(Jim_Obj **, Jim_Obj **);
+
};
+

+
static struct lsort_info *sort_info;
+

+
static int ListSortIndexHelper(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+
{
+
    Jim_Obj *lObj, *rObj;
+

+
    if (Jim_ListIndex(sort_info->interp, *lhsObj, sort_info->index, &lObj, JIM_ERRMSG) != JIM_OK ||
+
        Jim_ListIndex(sort_info->interp, *rhsObj, sort_info->index, &rObj, JIM_ERRMSG) != JIM_OK) {
+
        longjmp(sort_info->jmpbuf, JIM_ERR);
+
    }
+
    return sort_info->subfn(&lObj, &rObj);
+
}
+

+

+
static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+
{
+
    return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
+
}
+

+
static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+
{
+
    return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 1) * sort_info->order;
+
}
+

+
static int ListSortInteger(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+
{
+
    jim_wide lhs = 0, rhs = 0;
+

+
    if (Jim_GetWide(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
+
        Jim_GetWide(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
+
        longjmp(sort_info->jmpbuf, JIM_ERR);
+
    }
+

+
    return JimSign(lhs - rhs) * sort_info->order;
+
}
+

+
static int ListSortReal(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+
{
+
    double lhs = 0, rhs = 0;
+

+
    if (Jim_GetDouble(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
+
        Jim_GetDouble(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
+
        longjmp(sort_info->jmpbuf, JIM_ERR);
+
    }
+
    if (lhs == rhs) {
+
        return 0;
+
    }
+
    if (lhs > rhs) {
+
        return sort_info->order;
+
    }
+
    return -sort_info->order;
+
}
+

+
static int ListSortCommand(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+
{
+
    Jim_Obj *compare_script;
+
    int rc;
+

+
    jim_wide ret = 0;
+

+

+
    compare_script = Jim_DuplicateObj(sort_info->interp, sort_info->command);
+
    Jim_ListAppendElement(sort_info->interp, compare_script, *lhsObj);
+
    Jim_ListAppendElement(sort_info->interp, compare_script, *rhsObj);
+

+
    rc = Jim_EvalObj(sort_info->interp, compare_script);
+

+
    if (rc != JIM_OK || Jim_GetWide(sort_info->interp, Jim_GetResult(sort_info->interp), &ret) != JIM_OK) {
+
        longjmp(sort_info->jmpbuf, rc);
+
    }
+

+
    return JimSign(ret) * sort_info->order;
+
}
+

+
static void ListRemoveDuplicates(Jim_Obj *listObjPtr, int (*comp)(Jim_Obj **lhs, Jim_Obj **rhs))
+
{
+
    int src;
+
    int dst = 0;
+
    Jim_Obj **ele = listObjPtr->internalRep.listValue.ele;
+

+
    for (src = 1; src < listObjPtr->internalRep.listValue.len; src++) {
+
        if (comp(&ele[dst], &ele[src]) == 0) {
+

+
            Jim_DecrRefCount(sort_info->interp, ele[dst]);
+
        }
+
        else {
+

+
            dst++;
+
        }
+
        ele[dst] = ele[src];
+
    }
+

+
    ele[++dst] = ele[src];
+

+

+
    listObjPtr->internalRep.listValue.len = dst;
+
}
+

+

+
static int ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, struct lsort_info *info)
+
{
+
    struct lsort_info *prev_info;
+

+
    typedef int (qsort_comparator) (const void *, const void *);
+
    int (*fn) (Jim_Obj **, Jim_Obj **);
+
    Jim_Obj **vector;
+
    int len;
+
    int rc;
+

+
    JimPanic((Jim_IsShared(listObjPtr), "ListSortElements called with shared object"));
+
    SetListFromAny(interp, listObjPtr);
+

+

+
    prev_info = sort_info;
+
    sort_info = info;
+

+
    vector = listObjPtr->internalRep.listValue.ele;
+
    len = listObjPtr->internalRep.listValue.len;
+
    switch (info->type) {
+
        case JIM_LSORT_ASCII:
+
            fn = ListSortString;
+
            break;
+
        case JIM_LSORT_NOCASE:
+
            fn = ListSortStringNoCase;
+
            break;
+
        case JIM_LSORT_INTEGER:
+
            fn = ListSortInteger;
+
            break;
+
        case JIM_LSORT_REAL:
+
            fn = ListSortReal;
+
            break;
+
        case JIM_LSORT_COMMAND:
+
            fn = ListSortCommand;
+
            break;
+
        default:
+
            fn = NULL;
+
            JimPanic((1, "ListSort called with invalid sort type"));
+
            return -1;
+
    }
+

+
    if (info->indexed) {
+

+
        info->subfn = fn;
+
        fn = ListSortIndexHelper;
+
    }
+

+
    if ((rc = setjmp(info->jmpbuf)) == 0) {
+
        qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *) fn);
+

+
        if (info->unique && len > 1) {
+
            ListRemoveDuplicates(listObjPtr, fn);
+
        }
+

+
        Jim_InvalidateStringRep(listObjPtr);
+
    }
+
    sort_info = prev_info;
+

+
    return rc;
+
}
+

+
static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec)
+
{
+
    int currentLen = listPtr->internalRep.listValue.len;
+
    int requiredLen = currentLen + elemc;
+
    int i;
+
    Jim_Obj **point;
+

+
    if (requiredLen > listPtr->internalRep.listValue.maxLen) {
+
        if (requiredLen < 2) {
+

+
            requiredLen = 4;
+
        }
+
        else {
+
            requiredLen *= 2;
+
        }
+

+
        listPtr->internalRep.listValue.ele = Jim_Realloc(listPtr->internalRep.listValue.ele,
+
            sizeof(Jim_Obj *) * requiredLen);
+

+
        listPtr->internalRep.listValue.maxLen = requiredLen;
+
    }
+
    if (idx < 0) {
+
        idx = currentLen;
+
    }
+
    point = listPtr->internalRep.listValue.ele + idx;
+
    memmove(point + elemc, point, (currentLen - idx) * sizeof(Jim_Obj *));
+
    for (i = 0; i < elemc; ++i) {
+
        point[i] = elemVec[i];
+
        Jim_IncrRefCount(point[i]);
+
    }
+
    listPtr->internalRep.listValue.len += elemc;
+
}
+

+
static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
+
{
+
    ListInsertElements(listPtr, -1, 1, &objPtr);
+
}
+

+
static void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
+
{
+
    ListInsertElements(listPtr, -1,
+
        appendListPtr->internalRep.listValue.len, appendListPtr->internalRep.listValue.ele);
+
}
+

+
void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
+
{
+
    JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendElement called with shared object"));
+
    SetListFromAny(interp, listPtr);
+
    Jim_InvalidateStringRep(listPtr);
+
    ListAppendElement(listPtr, objPtr);
+
}
+

+
void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
+
{
+
    JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendList called with shared object"));
+
    SetListFromAny(interp, listPtr);
+
    SetListFromAny(interp, appendListPtr);
+
    Jim_InvalidateStringRep(listPtr);
+
    ListAppendList(listPtr, appendListPtr);
+
}
+

+
int Jim_ListLength(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    SetListFromAny(interp, objPtr);
+
    return objPtr->internalRep.listValue.len;
+
}
+

+
void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
+
    int objc, Jim_Obj *const *objVec)
+
{
+
    JimPanic((Jim_IsShared(listPtr), "Jim_ListInsertElement called with shared object"));
+
    SetListFromAny(interp, listPtr);
+
    if (idx >= 0 && idx > listPtr->internalRep.listValue.len)
+
        idx = listPtr->internalRep.listValue.len;
+
    else if (idx < 0)
+
        idx = 0;
+
    Jim_InvalidateStringRep(listPtr);
+
    ListInsertElements(listPtr, idx, objc, objVec);
+
}
+

+
Jim_Obj *Jim_ListGetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx)
+
{
+
    SetListFromAny(interp, listPtr);
+
    if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
+
        (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
+
        return NULL;
+
    }
+
    if (idx < 0)
+
        idx = listPtr->internalRep.listValue.len + idx;
+
    return listPtr->internalRep.listValue.ele[idx];
+
}
+

+
int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx, Jim_Obj **objPtrPtr, int flags)
+
{
+
    *objPtrPtr = Jim_ListGetIndex(interp, listPtr, idx);
+
    if (*objPtrPtr == NULL) {
+
        if (flags & JIM_ERRMSG) {
+
            Jim_SetResultString(interp, "list index out of range", -1);
+
        }
+
        return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+
static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
+
    Jim_Obj *newObjPtr, int flags)
+
{
+
    SetListFromAny(interp, listPtr);
+
    if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
+
        (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
+
        if (flags & JIM_ERRMSG) {
+
            Jim_SetResultString(interp, "list index out of range", -1);
+
        }
+
        return JIM_ERR;
+
    }
+
    if (idx < 0)
+
        idx = listPtr->internalRep.listValue.len + idx;
+
    Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[idx]);
+
    listPtr->internalRep.listValue.ele[idx] = newObjPtr;
+
    Jim_IncrRefCount(newObjPtr);
+
    return JIM_OK;
+
}
+

+
int Jim_ListSetIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
+
    Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
+
{
+
    Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
+
    int shared, i, idx;
+

+
    varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG | JIM_UNSHARED);
+
    if (objPtr == NULL)
+
        return JIM_ERR;
+
    if ((shared = Jim_IsShared(objPtr)))
+
        varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
+
    for (i = 0; i < indexc - 1; i++) {
+
        listObjPtr = objPtr;
+
        if (Jim_GetIndex(interp, indexv[i], &idx) != JIM_OK)
+
            goto err;
+
        if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_ERRMSG) != JIM_OK) {
+
            goto err;
+
        }
+
        if (Jim_IsShared(objPtr)) {
+
            objPtr = Jim_DuplicateObj(interp, objPtr);
+
            ListSetIndex(interp, listObjPtr, idx, objPtr, JIM_NONE);
+
        }
+
        Jim_InvalidateStringRep(listObjPtr);
+
    }
+
    if (Jim_GetIndex(interp, indexv[indexc - 1], &idx) != JIM_OK)
+
        goto err;
+
    if (ListSetIndex(interp, objPtr, idx, newObjPtr, JIM_ERRMSG) == JIM_ERR)
+
        goto err;
+
    Jim_InvalidateStringRep(objPtr);
+
    Jim_InvalidateStringRep(varObjPtr);
+
    if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
+
        goto err;
+
    Jim_SetResult(interp, varObjPtr);
+
    return JIM_OK;
+
  err:
+
    if (shared) {
+
        Jim_FreeNewObj(interp, varObjPtr);
+
    }
+
    return JIM_ERR;
+
}
+

+
Jim_Obj *Jim_ListJoin(Jim_Interp *interp, Jim_Obj *listObjPtr, const char *joinStr, int joinStrLen)
+
{
+
    int i;
+
    int listLen = Jim_ListLength(interp, listObjPtr);
+
    Jim_Obj *resObjPtr = Jim_NewEmptyStringObj(interp);
+

+
    for (i = 0; i < listLen; ) {
+
        Jim_AppendObj(interp, resObjPtr, Jim_ListGetIndex(interp, listObjPtr, i));
+
        if (++i != listLen) {
+
            Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
+
        }
+
    }
+
    return resObjPtr;
+
}
+

+
Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+
{
+
    int i;
+

+
    for (i = 0; i < objc; i++) {
+
        if (!Jim_IsList(objv[i]))
+
            break;
+
    }
+
    if (i == objc) {
+
        Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
+

+
        for (i = 0; i < objc; i++)
+
            ListAppendList(objPtr, objv[i]);
+
        return objPtr;
+
    }
+
    else {
+

+
        int len = 0, objLen;
+
        char *bytes, *p;
+

+

+
        for (i = 0; i < objc; i++) {
+
            len += Jim_Length(objv[i]);
+
        }
+
        if (objc)
+
            len += objc - 1;
+

+
        p = bytes = Jim_Alloc(len + 1);
+
        for (i = 0; i < objc; i++) {
+
            const char *s = Jim_GetString(objv[i], &objLen);
+

+

+
            while (objLen && isspace(UCHAR(*s))) {
+
                s++;
+
                objLen--;
+
                len--;
+
            }
+

+
            while (objLen && isspace(UCHAR(s[objLen - 1]))) {
+

+
                if (objLen > 1 && s[objLen - 2] == '\\') {
+
                    break;
+
                }
+
                objLen--;
+
                len--;
+
            }
+
            memcpy(p, s, objLen);
+
            p += objLen;
+
            if (i + 1 != objc) {
+
                if (objLen)
+
                    *p++ = ' ';
+
                else {
+
                    len--;
+
                }
+
            }
+
        }
+
        *p = '\0';
+
        return Jim_NewStringObjNoAlloc(interp, bytes, len);
+
    }
+
}
+

+
Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr,
+
    Jim_Obj *lastObjPtr)
+
{
+
    int first, last;
+
    int len, rangeLen;
+

+
    if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
+
        Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
+
        return NULL;
+
    len = Jim_ListLength(interp, listObjPtr);
+
    first = JimRelToAbsIndex(len, first);
+
    last = JimRelToAbsIndex(len, last);
+
    JimRelToAbsRange(len, &first, &last, &rangeLen);
+
    if (first == 0 && last == len) {
+
        return listObjPtr;
+
    }
+
    return Jim_NewListObj(interp, listObjPtr->internalRep.listValue.ele + first, rangeLen);
+
}
+

+
static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+
static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
static void UpdateStringOfDict(struct Jim_Obj *objPtr);
+
static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+

+

+
static unsigned int JimObjectHTHashFunction(const void *key)
+
{
+
    int len;
+
    const char *str = Jim_GetString((Jim_Obj *)key, &len);
+
    return Jim_GenHashFunction((const unsigned char *)str, len);
+
}
+

+
static int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)
+
{
+
    return Jim_StringEqObj((Jim_Obj *)key1, (Jim_Obj *)key2);
+
}
+

+
static void *JimObjectHTKeyValDup(void *privdata, const void *val)
+
{
+
    Jim_IncrRefCount((Jim_Obj *)val);
+
    return (void *)val;
+
}
+

+
static void JimObjectHTKeyValDestructor(void *interp, void *val)
+
{
+
    Jim_DecrRefCount(interp, (Jim_Obj *)val);
+
}
+

+
static const Jim_HashTableType JimDictHashTableType = {
+
    JimObjectHTHashFunction,
+
    JimObjectHTKeyValDup,
+
    JimObjectHTKeyValDup,
+
    JimObjectHTKeyCompare,
+
    JimObjectHTKeyValDestructor,
+
    JimObjectHTKeyValDestructor
+
};
+

+
static const Jim_ObjType dictObjType = {
+
    "dict",
+
    FreeDictInternalRep,
+
    DupDictInternalRep,
+
    UpdateStringOfDict,
+
    JIM_TYPE_NONE,
+
};
+

+
void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    JIM_NOTUSED(interp);
+

+
    Jim_FreeHashTable(objPtr->internalRep.ptr);
+
    Jim_Free(objPtr->internalRep.ptr);
+
}
+

+
void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    Jim_HashTable *ht, *dupHt;
+
    Jim_HashTableIterator htiter;
+
    Jim_HashEntry *he;
+

+

+
    ht = srcPtr->internalRep.ptr;
+
    dupHt = Jim_Alloc(sizeof(*dupHt));
+
    Jim_InitHashTable(dupHt, &JimDictHashTableType, interp);
+
    if (ht->size != 0)
+
        Jim_ExpandHashTable(dupHt, ht->size);
+

+
    JimInitHashTableIterator(ht, &htiter);
+
    while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+
        Jim_AddHashEntry(dupHt, he->key, he->u.val);
+
    }
+

+
    dupPtr->internalRep.ptr = dupHt;
+
    dupPtr->typePtr = &dictObjType;
+
}
+

+
static Jim_Obj **JimDictPairs(Jim_Obj *dictPtr, int *len)
+
{
+
    Jim_HashTable *ht;
+
    Jim_HashTableIterator htiter;
+
    Jim_HashEntry *he;
+
    Jim_Obj **objv;
+
    int i;
+

+
    ht = dictPtr->internalRep.ptr;
+

+

+
    objv = Jim_Alloc((ht->used * 2) * sizeof(Jim_Obj *));
+
    JimInitHashTableIterator(ht, &htiter);
+
    i = 0;
+
    while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+
        objv[i++] = Jim_GetHashEntryKey(he);
+
        objv[i++] = Jim_GetHashEntryVal(he);
+
    }
+
    *len = i;
+
    return objv;
+
}
+

+
static void UpdateStringOfDict(struct Jim_Obj *objPtr)
+
{
+

+
    int len;
+
    Jim_Obj **objv = JimDictPairs(objPtr, &len);
+

+

+
    JimMakeListStringRep(objPtr, objv, len);
+

+
    Jim_Free(objv);
+
}
+

+
static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+
{
+
    int listlen;
+

+
    if (objPtr->typePtr == &dictObjType) {
+
        return JIM_OK;
+
    }
+

+
    if (Jim_IsList(objPtr) && Jim_IsShared(objPtr)) {
+
        Jim_String(objPtr);
+
    }
+

+

+
    listlen = Jim_ListLength(interp, objPtr);
+
    if (listlen % 2) {
+
        Jim_SetResultString(interp, "missing value to go with key", -1);
+
        return JIM_ERR;
+
    }
+
    else {
+

+
        Jim_HashTable *ht;
+
        int i;
+

+
        ht = Jim_Alloc(sizeof(*ht));
+
        Jim_InitHashTable(ht, &JimDictHashTableType, interp);
+

+
        for (i = 0; i < listlen; i += 2) {
+
            Jim_Obj *keyObjPtr = Jim_ListGetIndex(interp, objPtr, i);
+
            Jim_Obj *valObjPtr = Jim_ListGetIndex(interp, objPtr, i + 1);
+

+
            Jim_ReplaceHashEntry(ht, keyObjPtr, valObjPtr);
+
        }
+

+
        Jim_FreeIntRep(interp, objPtr);
+
        objPtr->typePtr = &dictObjType;
+
        objPtr->internalRep.ptr = ht;
+

+
        return JIM_OK;
+
    }
+
}
+

+

+

+
static int DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
+
    Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
+
{
+
    Jim_HashTable *ht = objPtr->internalRep.ptr;
+

+
    if (valueObjPtr == NULL) {
+
        return Jim_DeleteHashEntry(ht, keyObjPtr);
+
    }
+
    Jim_ReplaceHashEntry(ht, keyObjPtr, valueObjPtr);
+
    return JIM_OK;
+
}
+

+
int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
+
    Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
+
{
+
    JimPanic((Jim_IsShared(objPtr), "Jim_DictAddElement called with shared object"));
+
    if (SetDictFromAny(interp, objPtr) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    Jim_InvalidateStringRep(objPtr);
+
    return DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);
+
}
+

+
Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
+
{
+
    Jim_Obj *objPtr;
+
    int i;
+

+
    JimPanic((len % 2, "Jim_NewDictObj() 'len' argument must be even"));
+

+
    objPtr = Jim_NewObj(interp);
+
    objPtr->typePtr = &dictObjType;
+
    objPtr->bytes = NULL;
+
    objPtr->internalRep.ptr = Jim_Alloc(sizeof(Jim_HashTable));
+
    Jim_InitHashTable(objPtr->internalRep.ptr, &JimDictHashTableType, interp);
+
    for (i = 0; i < len; i += 2)
+
        DictAddElement(interp, objPtr, elements[i], elements[i + 1]);
+
    return objPtr;
+
}
+

+
int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,
+
    Jim_Obj **objPtrPtr, int flags)
+
{
+
    Jim_HashEntry *he;
+
    Jim_HashTable *ht;
+

+
    if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
+
        return -1;
+
    }
+
    ht = dictPtr->internalRep.ptr;
+
    if ((he = Jim_FindHashEntry(ht, keyPtr)) == NULL) {
+
        if (flags & JIM_ERRMSG) {
+
            Jim_SetResultFormatted(interp, "key \"%#s\" not known in dictionary", keyPtr);
+
        }
+
        return JIM_ERR;
+
    }
+
    else {
+
        *objPtrPtr = Jim_GetHashEntryVal(he);
+
        return JIM_OK;
+
    }
+
}
+

+

+
int Jim_DictPairs(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj ***objPtrPtr, int *len)
+
{
+
    if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    *objPtrPtr = JimDictPairs(dictPtr, len);
+

+
    return JIM_OK;
+
}
+

+

+

+
int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,
+
    Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)
+
{
+
    int i;
+

+
    if (keyc == 0) {
+
        *objPtrPtr = dictPtr;
+
        return JIM_OK;
+
    }
+

+
    for (i = 0; i < keyc; i++) {
+
        Jim_Obj *objPtr;
+

+
        int rc = Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags);
+
        if (rc != JIM_OK) {
+
            return rc;
+
        }
+
        dictPtr = objPtr;
+
    }
+
    *objPtrPtr = dictPtr;
+
    return JIM_OK;
+
}
+

+
int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
+
    Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr, int flags)
+
{
+
    Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
+
    int shared, i;
+

+
    varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, flags);
+
    if (objPtr == NULL) {
+
        if (newObjPtr == NULL && (flags & JIM_MUSTEXIST)) {
+

+
            return JIM_ERR;
+
        }
+
        varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
+
        if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
+
            Jim_FreeNewObj(interp, varObjPtr);
+
            return JIM_ERR;
+
        }
+
    }
+
    if ((shared = Jim_IsShared(objPtr)))
+
        varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
+
    for (i = 0; i < keyc; i++) {
+
        dictObjPtr = objPtr;
+

+

+
        if (SetDictFromAny(interp, dictObjPtr) != JIM_OK) {
+
            goto err;
+
        }
+

+
        if (i == keyc - 1) {
+

+
            if (Jim_DictAddElement(interp, objPtr, keyv[keyc - 1], newObjPtr) != JIM_OK) {
+
                if (newObjPtr || (flags & JIM_MUSTEXIST)) {
+
                    goto err;
+
                }
+
            }
+
            break;
+
        }
+

+

+
        Jim_InvalidateStringRep(dictObjPtr);
+
        if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
+
                newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK) {
+
            if (Jim_IsShared(objPtr)) {
+
                objPtr = Jim_DuplicateObj(interp, objPtr);
+
                DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
+
            }
+
        }
+
        else {
+
            if (newObjPtr == NULL) {
+
                goto err;
+
            }
+
            objPtr = Jim_NewDictObj(interp, NULL, 0);
+
            DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
+
        }
+
    }
+

+
    Jim_InvalidateStringRep(objPtr);
+
    Jim_InvalidateStringRep(varObjPtr);
+
    if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK) {
+
        goto err;
+
    }
+
    Jim_SetResult(interp, varObjPtr);
+
    return JIM_OK;
+
  err:
+
    if (shared) {
+
        Jim_FreeNewObj(interp, varObjPtr);
+
    }
+
    return JIM_ERR;
+
}
+

+
static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
+
static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+

+
static const Jim_ObjType indexObjType = {
+
    "index",
+
    NULL,
+
    NULL,
+
    UpdateStringOfIndex,
+
    JIM_TYPE_NONE,
+
};
+

+
static void UpdateStringOfIndex(struct Jim_Obj *objPtr)
+
{
+
    if (objPtr->internalRep.intValue == -1) {
+
        JimSetStringBytes(objPtr, "end");
+
    }
+
    else {
+
        char buf[JIM_INTEGER_SPACE + 1];
+
        if (objPtr->internalRep.intValue >= 0) {
+
            sprintf(buf, "%d", objPtr->internalRep.intValue);
+
        }
+
        else {
+

+
            sprintf(buf, "end%d", objPtr->internalRep.intValue + 1);
+
        }
+
        JimSetStringBytes(objPtr, buf);
+
    }
+
}
+

+
static int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    int idx, end = 0;
+
    const char *str;
+
    char *endptr;
+

+

+
    str = Jim_String(objPtr);
+

+

+
    if (strncmp(str, "end", 3) == 0) {
+
        end = 1;
+
        str += 3;
+
        idx = 0;
+
    }
+
    else {
+
        idx = jim_strtol(str, &endptr);
+

+
        if (endptr == str) {
+
            goto badindex;
+
        }
+
        str = endptr;
+
    }
+

+

+
    if (*str == '+' || *str == '-') {
+
        int sign = (*str == '+' ? 1 : -1);
+

+
        idx += sign * jim_strtol(++str, &endptr);
+
        if (str == endptr || *endptr) {
+
            goto badindex;
+
        }
+
        str = endptr;
+
    }
+

+
    while (isspace(UCHAR(*str))) {
+
        str++;
+
    }
+
    if (*str) {
+
        goto badindex;
+
    }
+
    if (end) {
+
        if (idx > 0) {
+
            idx = INT_MAX;
+
        }
+
        else {
+

+
            idx--;
+
        }
+
    }
+
    else if (idx < 0) {
+
        idx = -INT_MAX;
+
    }
+

+

+
    Jim_FreeIntRep(interp, objPtr);
+
    objPtr->typePtr = &indexObjType;
+
    objPtr->internalRep.intValue = idx;
+
    return JIM_OK;
+

+
  badindex:
+
    Jim_SetResultFormatted(interp,
+
        "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr);
+
    return JIM_ERR;
+
}
+

+
int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
+
{
+

+
    if (objPtr->typePtr == &intObjType) {
+
        jim_wide val = JimWideValue(objPtr);
+

+
        if (val < 0)
+
            *indexPtr = -INT_MAX;
+
        else if (val > INT_MAX)
+
            *indexPtr = INT_MAX;
+
        else
+
            *indexPtr = (int)val;
+
        return JIM_OK;
+
    }
+
    if (objPtr->typePtr != &indexObjType && SetIndexFromAny(interp, objPtr) == JIM_ERR)
+
        return JIM_ERR;
+
    *indexPtr = objPtr->internalRep.intValue;
+
    return JIM_OK;
+
}
+

+

+

+
static const char * const jimReturnCodes[] = {
+
    "ok",
+
    "error",
+
    "return",
+
    "break",
+
    "continue",
+
    "signal",
+
    "exit",
+
    "eval",
+
    NULL
+
};
+

+
#define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
+

+
static const Jim_ObjType returnCodeObjType = {
+
    "return-code",
+
    NULL,
+
    NULL,
+
    NULL,
+
    JIM_TYPE_NONE,
+
};
+

+
const char *Jim_ReturnCode(int code)
+
{
+
    if (code < 0 || code >= (int)jimReturnCodesSize) {
+
        return "?";
+
    }
+
    else {
+
        return jimReturnCodes[code];
+
    }
+
}
+

+
static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    int returnCode;
+
    jim_wide wideValue;
+

+

+
    if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
+
        returnCode = (int)wideValue;
+
    else if (Jim_GetEnum(interp, objPtr, jimReturnCodes, &returnCode, NULL, JIM_NONE) != JIM_OK) {
+
        Jim_SetResultFormatted(interp, "expected return code but got \"%#s\"", objPtr);
+
        return JIM_ERR;
+
    }
+

+
    Jim_FreeIntRep(interp, objPtr);
+
    objPtr->typePtr = &returnCodeObjType;
+
    objPtr->internalRep.intValue = returnCode;
+
    return JIM_OK;
+
}
+

+
int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
+
{
+
    if (objPtr->typePtr != &returnCodeObjType && SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
+
        return JIM_ERR;
+
    *intPtr = objPtr->internalRep.intValue;
+
    return JIM_OK;
+
}
+

+
static int JimParseExprOperator(struct JimParserCtx *pc);
+
static int JimParseExprNumber(struct JimParserCtx *pc);
+
static int JimParseExprIrrational(struct JimParserCtx *pc);
+
static int JimParseExprBoolean(struct JimParserCtx *pc);
+

+

+

+

+
enum
+
{
+

+

+
    JIM_EXPROP_MUL = JIM_TT_EXPR_OP,
+
    JIM_EXPROP_DIV,
+
    JIM_EXPROP_MOD,
+
    JIM_EXPROP_SUB,
+
    JIM_EXPROP_ADD,
+
    JIM_EXPROP_LSHIFT,
+
    JIM_EXPROP_RSHIFT,
+
    JIM_EXPROP_ROTL,
+
    JIM_EXPROP_ROTR,
+
    JIM_EXPROP_LT,
+
    JIM_EXPROP_GT,
+
    JIM_EXPROP_LTE,
+
    JIM_EXPROP_GTE,
+
    JIM_EXPROP_NUMEQ,
+
    JIM_EXPROP_NUMNE,
+
    JIM_EXPROP_BITAND,
+
    JIM_EXPROP_BITXOR,
+
    JIM_EXPROP_BITOR,
+

+

+
    JIM_EXPROP_LOGICAND,
+
    JIM_EXPROP_LOGICAND_LEFT,
+
    JIM_EXPROP_LOGICAND_RIGHT,
+

+

+
    JIM_EXPROP_LOGICOR,
+
    JIM_EXPROP_LOGICOR_LEFT,
+
    JIM_EXPROP_LOGICOR_RIGHT,
+

+

+

+
    JIM_EXPROP_TERNARY,
+
    JIM_EXPROP_TERNARY_LEFT,
+
    JIM_EXPROP_TERNARY_RIGHT,
+

+

+
    JIM_EXPROP_COLON,
+
    JIM_EXPROP_COLON_LEFT,
+
    JIM_EXPROP_COLON_RIGHT,
+

+
    JIM_EXPROP_POW,
+

+

+
    JIM_EXPROP_STREQ,
+
    JIM_EXPROP_STRNE,
+
    JIM_EXPROP_STRIN,
+
    JIM_EXPROP_STRNI,
+

+

+
    JIM_EXPROP_NOT,
+
    JIM_EXPROP_BITNOT,
+
    JIM_EXPROP_UNARYMINUS,
+
    JIM_EXPROP_UNARYPLUS,
+

+

+
    JIM_EXPROP_FUNC_FIRST,
+
    JIM_EXPROP_FUNC_INT = JIM_EXPROP_FUNC_FIRST,
+
    JIM_EXPROP_FUNC_WIDE,
+
    JIM_EXPROP_FUNC_ABS,
+
    JIM_EXPROP_FUNC_DOUBLE,
+
    JIM_EXPROP_FUNC_ROUND,
+
    JIM_EXPROP_FUNC_RAND,
+
    JIM_EXPROP_FUNC_SRAND,
+

+

+
    JIM_EXPROP_FUNC_SIN,
+
    JIM_EXPROP_FUNC_COS,
+
    JIM_EXPROP_FUNC_TAN,
+
    JIM_EXPROP_FUNC_ASIN,
+
    JIM_EXPROP_FUNC_ACOS,
+
    JIM_EXPROP_FUNC_ATAN,
+
    JIM_EXPROP_FUNC_ATAN2,
+
    JIM_EXPROP_FUNC_SINH,
+
    JIM_EXPROP_FUNC_COSH,
+
    JIM_EXPROP_FUNC_TANH,
+
    JIM_EXPROP_FUNC_CEIL,
+
    JIM_EXPROP_FUNC_FLOOR,
+
    JIM_EXPROP_FUNC_EXP,
+
    JIM_EXPROP_FUNC_LOG,
+
    JIM_EXPROP_FUNC_LOG10,
+
    JIM_EXPROP_FUNC_SQRT,
+
    JIM_EXPROP_FUNC_POW,
+
    JIM_EXPROP_FUNC_HYPOT,
+
    JIM_EXPROP_FUNC_FMOD,
+
};
+

+
struct JimExprState
+
{
+
    Jim_Obj **stack;
+
    int stacklen;
+
    int opcode;
+
    int skip;
+
};
+

+

+
typedef struct Jim_ExprOperator
+
{
+
    const char *name;
+
    int (*funcop) (Jim_Interp *interp, struct JimExprState * e);
+
    unsigned char precedence;
+
    unsigned char arity;
+
    unsigned char lazy;
+
    unsigned char namelen;
+
} Jim_ExprOperator;
+

+
static void ExprPush(struct JimExprState *e, Jim_Obj *obj)
+
{
+
    Jim_IncrRefCount(obj);
+
    e->stack[e->stacklen++] = obj;
+
}
+

+
static Jim_Obj *ExprPop(struct JimExprState *e)
+
{
+
    return e->stack[--e->stacklen];
+
}
+

+
static int JimExprOpNumUnary(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    int intresult = 1;
+
    int rc = JIM_OK;
+
    Jim_Obj *A = ExprPop(e);
+
    double dA, dC = 0;
+
    jim_wide wA, wC = 0;
+

+
    if ((A->typePtr != &doubleObjType || A->bytes) && JimGetWideNoErr(interp, A, &wA) == JIM_OK) {
+
        switch (e->opcode) {
+
            case JIM_EXPROP_FUNC_INT:
+
            case JIM_EXPROP_FUNC_WIDE:
+
            case JIM_EXPROP_FUNC_ROUND:
+
            case JIM_EXPROP_UNARYPLUS:
+
                wC = wA;
+
                break;
+
            case JIM_EXPROP_FUNC_DOUBLE:
+
                dC = wA;
+
                intresult = 0;
+
                break;
+
            case JIM_EXPROP_FUNC_ABS:
+
                wC = wA >= 0 ? wA : -wA;
+
                break;
+
            case JIM_EXPROP_UNARYMINUS:
+
                wC = -wA;
+
                break;
+
            case JIM_EXPROP_NOT:
+
                wC = !wA;
+
                break;
+
            default:
+
                abort();
+
        }
+
    }
+
    else if ((rc = Jim_GetDouble(interp, A, &dA)) == JIM_OK) {
+
        switch (e->opcode) {
+
            case JIM_EXPROP_FUNC_INT:
+
            case JIM_EXPROP_FUNC_WIDE:
+
                wC = dA;
+
                break;
+
            case JIM_EXPROP_FUNC_ROUND:
+
                wC = dA < 0 ? (dA - 0.5) : (dA + 0.5);
+
                break;
+
            case JIM_EXPROP_FUNC_DOUBLE:
+
            case JIM_EXPROP_UNARYPLUS:
+
                dC = dA;
+
                intresult = 0;
+
                break;
+
            case JIM_EXPROP_FUNC_ABS:
+
#ifdef JIM_MATH_FUNCTIONS
+
                dC = fabs(dA);
+
#else
+
                dC = dA >= 0 ? dA : -dA;
+
#endif
+
                intresult = 0;
+
                break;
+
            case JIM_EXPROP_UNARYMINUS:
+
                dC = -dA;
+
                intresult = 0;
+
                break;
+
            case JIM_EXPROP_NOT:
+
                wC = !dA;
+
                break;
+
            default:
+
                abort();
+
        }
+
    }
+

+
    if (rc == JIM_OK) {
+
        if (intresult) {
+
            ExprPush(e, Jim_NewIntObj(interp, wC));
+
        }
+
        else {
+
            ExprPush(e, Jim_NewDoubleObj(interp, dC));
+
        }
+
    }
+

+
    Jim_DecrRefCount(interp, A);
+

+
    return rc;
+
}
+

+
static double JimRandDouble(Jim_Interp *interp)
+
{
+
    unsigned long x;
+
    JimRandomBytes(interp, &x, sizeof(x));
+

+
    return (double)x / (unsigned long)~0;
+
}
+

+
static int JimExprOpIntUnary(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    Jim_Obj *A = ExprPop(e);
+
    jim_wide wA;
+

+
    int rc = Jim_GetWide(interp, A, &wA);
+
    if (rc == JIM_OK) {
+
        switch (e->opcode) {
+
            case JIM_EXPROP_BITNOT:
+
                ExprPush(e, Jim_NewIntObj(interp, ~wA));
+
                break;
+
            case JIM_EXPROP_FUNC_SRAND:
+
                JimPrngSeed(interp, (unsigned char *)&wA, sizeof(wA));
+
                ExprPush(e, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
+
                break;
+
            default:
+
                abort();
+
        }
+
    }
+

+
    Jim_DecrRefCount(interp, A);
+

+
    return rc;
+
}
+

+
static int JimExprOpNone(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    JimPanic((e->opcode != JIM_EXPROP_FUNC_RAND, "JimExprOpNone only support rand()"));
+

+
    ExprPush(e, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
+

+
    return JIM_OK;
+
}
+

+
#ifdef JIM_MATH_FUNCTIONS
+
static int JimExprOpDoubleUnary(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    int rc;
+
    Jim_Obj *A = ExprPop(e);
+
    double dA, dC;
+

+
    rc = Jim_GetDouble(interp, A, &dA);
+
    if (rc == JIM_OK) {
+
        switch (e->opcode) {
+
            case JIM_EXPROP_FUNC_SIN:
+
                dC = sin(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_COS:
+
                dC = cos(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_TAN:
+
                dC = tan(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_ASIN:
+
                dC = asin(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_ACOS:
+
                dC = acos(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_ATAN:
+
                dC = atan(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_SINH:
+
                dC = sinh(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_COSH:
+
                dC = cosh(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_TANH:
+
                dC = tanh(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_CEIL:
+
                dC = ceil(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_FLOOR:
+
                dC = floor(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_EXP:
+
                dC = exp(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_LOG:
+
                dC = log(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_LOG10:
+
                dC = log10(dA);
+
                break;
+
            case JIM_EXPROP_FUNC_SQRT:
+
                dC = sqrt(dA);
+
                break;
+
            default:
+
                abort();
+
        }
+
        ExprPush(e, Jim_NewDoubleObj(interp, dC));
+
    }
+

+
    Jim_DecrRefCount(interp, A);
+

+
    return rc;
+
}
+
#endif
+

+

+
static int JimExprOpIntBin(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    Jim_Obj *B = ExprPop(e);
+
    Jim_Obj *A = ExprPop(e);
+
    jim_wide wA, wB;
+
    int rc = JIM_ERR;
+

+
    if (Jim_GetWide(interp, A, &wA) == JIM_OK && Jim_GetWide(interp, B, &wB) == JIM_OK) {
+
        jim_wide wC;
+

+
        rc = JIM_OK;
+

+
        switch (e->opcode) {
+
            case JIM_EXPROP_LSHIFT:
+
                wC = wA << wB;
+
                break;
+
            case JIM_EXPROP_RSHIFT:
+
                wC = wA >> wB;
+
                break;
+
            case JIM_EXPROP_BITAND:
+
                wC = wA & wB;
+
                break;
+
            case JIM_EXPROP_BITXOR:
+
                wC = wA ^ wB;
+
                break;
+
            case JIM_EXPROP_BITOR:
+
                wC = wA | wB;
+
                break;
+
            case JIM_EXPROP_MOD:
+
                if (wB == 0) {
+
                    wC = 0;
+
                    Jim_SetResultString(interp, "Division by zero", -1);
+
                    rc = JIM_ERR;
+
                }
+
                else {
+
                    int negative = 0;
+

+
                    if (wB < 0) {
+
                        wB = -wB;
+
                        wA = -wA;
+
                        negative = 1;
+
                    }
+
                    wC = wA % wB;
+
                    if (wC < 0) {
+
                        wC += wB;
+
                    }
+
                    if (negative) {
+
                        wC = -wC;
+
                    }
+
                }
+
                break;
+
            case JIM_EXPROP_ROTL:
+
            case JIM_EXPROP_ROTR:{
+

+
                    unsigned long uA = (unsigned long)wA;
+
                    unsigned long uB = (unsigned long)wB;
+
                    const unsigned int S = sizeof(unsigned long) * 8;
+

+

+
                    uB %= S;
+

+
                    if (e->opcode == JIM_EXPROP_ROTR) {
+
                        uB = S - uB;
+
                    }
+
                    wC = (unsigned long)(uA << uB) | (uA >> (S - uB));
+
                    break;
+
                }
+
            default:
+
                abort();
+
        }
+
        ExprPush(e, Jim_NewIntObj(interp, wC));
+

+
    }
+

+
    Jim_DecrRefCount(interp, A);
+
    Jim_DecrRefCount(interp, B);
+

+
    return rc;
+
}
+

+

+

+
static int JimExprOpBin(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    int rc = JIM_OK;
+
    double dA, dB, dC = 0;
+
    jim_wide wA, wB, wC = 0;
+

+
    Jim_Obj *B = ExprPop(e);
+
    Jim_Obj *A = ExprPop(e);
+

+
    if ((A->typePtr != &doubleObjType || A->bytes) &&
+
        (B->typePtr != &doubleObjType || B->bytes) &&
+
        JimGetWideNoErr(interp, A, &wA) == JIM_OK && JimGetWideNoErr(interp, B, &wB) == JIM_OK) {
+

+

+

+
        switch (e->opcode) {
+
            case JIM_EXPROP_POW:
+
            case JIM_EXPROP_FUNC_POW:
+
                if (wA == 0 && wB < 0) {
+
                    Jim_SetResultString(interp, "exponentiation of zero by negative power", -1);
+
                    rc = JIM_ERR;
+
                    goto done;
+
                }
+
                wC = JimPowWide(wA, wB);
+
                goto intresult;
+
            case JIM_EXPROP_ADD:
+
                wC = wA + wB;
+
                goto intresult;
+
            case JIM_EXPROP_SUB:
+
                wC = wA - wB;
+
                goto intresult;
+
            case JIM_EXPROP_MUL:
+
                wC = wA * wB;
+
                goto intresult;
+
            case JIM_EXPROP_DIV:
+
                if (wB == 0) {
+
                    Jim_SetResultString(interp, "Division by zero", -1);
+
                    rc = JIM_ERR;
+
                    goto done;
+
                }
+
                else {
+
                    if (wB < 0) {
+
                        wB = -wB;
+
                        wA = -wA;
+
                    }
+
                    wC = wA / wB;
+
                    if (wA % wB < 0) {
+
                        wC--;
+
                    }
+
                    goto intresult;
+
                }
+
            case JIM_EXPROP_LT:
+
                wC = wA < wB;
+
                goto intresult;
+
            case JIM_EXPROP_GT:
+
                wC = wA > wB;
+
                goto intresult;
+
            case JIM_EXPROP_LTE:
+
                wC = wA <= wB;
+
                goto intresult;
+
            case JIM_EXPROP_GTE:
+
                wC = wA >= wB;
+
                goto intresult;
+
            case JIM_EXPROP_NUMEQ:
+
                wC = wA == wB;
+
                goto intresult;
+
            case JIM_EXPROP_NUMNE:
+
                wC = wA != wB;
+
                goto intresult;
+
        }
+
    }
+
    if (Jim_GetDouble(interp, A, &dA) == JIM_OK && Jim_GetDouble(interp, B, &dB) == JIM_OK) {
+
        switch (e->opcode) {
+
#ifndef JIM_MATH_FUNCTIONS
+
            case JIM_EXPROP_POW:
+
            case JIM_EXPROP_FUNC_POW:
+
            case JIM_EXPROP_FUNC_ATAN2:
+
            case JIM_EXPROP_FUNC_HYPOT:
+
            case JIM_EXPROP_FUNC_FMOD:
+
                Jim_SetResultString(interp, "unsupported", -1);
+
                rc = JIM_ERR;
+
                goto done;
+
#else
+
            case JIM_EXPROP_POW:
+
            case JIM_EXPROP_FUNC_POW:
+
                dC = pow(dA, dB);
+
                goto doubleresult;
+
            case JIM_EXPROP_FUNC_ATAN2:
+
                dC = atan2(dA, dB);
+
                goto doubleresult;
+
            case JIM_EXPROP_FUNC_HYPOT:
+
                dC = hypot(dA, dB);
+
                goto doubleresult;
+
            case JIM_EXPROP_FUNC_FMOD:
+
                dC = fmod(dA, dB);
+
                goto doubleresult;
+
#endif
+
            case JIM_EXPROP_ADD:
+
                dC = dA + dB;
+
                goto doubleresult;
+
            case JIM_EXPROP_SUB:
+
                dC = dA - dB;
+
                goto doubleresult;
+
            case JIM_EXPROP_MUL:
+
                dC = dA * dB;
+
                goto doubleresult;
+
            case JIM_EXPROP_DIV:
+
                if (dB == 0) {
+
#ifdef INFINITY
+
                    dC = dA < 0 ? -INFINITY : INFINITY;
+
#else
+
                    dC = (dA < 0 ? -1.0 : 1.0) * strtod("Inf", NULL);
+
#endif
+
                }
+
                else {
+
                    dC = dA / dB;
+
                }
+
                goto doubleresult;
+
            case JIM_EXPROP_LT:
+
                wC = dA < dB;
+
                goto intresult;
+
            case JIM_EXPROP_GT:
+
                wC = dA > dB;
+
                goto intresult;
+
            case JIM_EXPROP_LTE:
+
                wC = dA <= dB;
+
                goto intresult;
+
            case JIM_EXPROP_GTE:
+
                wC = dA >= dB;
+
                goto intresult;
+
            case JIM_EXPROP_NUMEQ:
+
                wC = dA == dB;
+
                goto intresult;
+
            case JIM_EXPROP_NUMNE:
+
                wC = dA != dB;
+
                goto intresult;
+
        }
+
    }
+
    else {
+

+

+

+
        int i = Jim_StringCompareObj(interp, A, B, 0);
+

+
        switch (e->opcode) {
+
            case JIM_EXPROP_LT:
+
                wC = i < 0;
+
                goto intresult;
+
            case JIM_EXPROP_GT:
+
                wC = i > 0;
+
                goto intresult;
+
            case JIM_EXPROP_LTE:
+
                wC = i <= 0;
+
                goto intresult;
+
            case JIM_EXPROP_GTE:
+
                wC = i >= 0;
+
                goto intresult;
+
            case JIM_EXPROP_NUMEQ:
+
                wC = i == 0;
+
                goto intresult;
+
            case JIM_EXPROP_NUMNE:
+
                wC = i != 0;
+
                goto intresult;
+
        }
+
    }
+

+
    rc = JIM_ERR;
+
done:
+
    Jim_DecrRefCount(interp, A);
+
    Jim_DecrRefCount(interp, B);
+
    return rc;
+
intresult:
+
    ExprPush(e, Jim_NewIntObj(interp, wC));
+
    goto done;
+
doubleresult:
+
    ExprPush(e, Jim_NewDoubleObj(interp, dC));
+
    goto done;
+
}
+

+
static int JimSearchList(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *valObj)
+
{
+
    int listlen;
+
    int i;
+

+
    listlen = Jim_ListLength(interp, listObjPtr);
+
    for (i = 0; i < listlen; i++) {
+
        if (Jim_StringEqObj(Jim_ListGetIndex(interp, listObjPtr, i), valObj)) {
+
            return 1;
+
        }
+
    }
+
    return 0;
+
}
+

+
static int JimExprOpStrBin(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    Jim_Obj *B = ExprPop(e);
+
    Jim_Obj *A = ExprPop(e);
+

+
    jim_wide wC;
+

+
    switch (e->opcode) {
+
        case JIM_EXPROP_STREQ:
+
        case JIM_EXPROP_STRNE:
+
            wC = Jim_StringEqObj(A, B);
+
            if (e->opcode == JIM_EXPROP_STRNE) {
+
                wC = !wC;
+
            }
+
            break;
+
        case JIM_EXPROP_STRIN:
+
            wC = JimSearchList(interp, B, A);
+
            break;
+
        case JIM_EXPROP_STRNI:
+
            wC = !JimSearchList(interp, B, A);
+
            break;
+
        default:
+
            abort();
+
    }
+
    ExprPush(e, Jim_NewIntObj(interp, wC));
+

+
    Jim_DecrRefCount(interp, A);
+
    Jim_DecrRefCount(interp, B);
+

+
    return JIM_OK;
+
}
+

+
static int ExprBool(Jim_Interp *interp, Jim_Obj *obj)
+
{
+
    long l;
+
    double d;
+
    int b;
+

+
    if (Jim_GetLong(interp, obj, &l) == JIM_OK) {
+
        return l != 0;
+
    }
+
    if (Jim_GetDouble(interp, obj, &d) == JIM_OK) {
+
        return d != 0;
+
    }
+
    if (Jim_GetBoolean(interp, obj, &b) == JIM_OK) {
+
        return b != 0;
+
    }
+
    return -1;
+
}
+

+
static int JimExprOpAndLeft(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    Jim_Obj *skip = ExprPop(e);
+
    Jim_Obj *A = ExprPop(e);
+
    int rc = JIM_OK;
+

+
    switch (ExprBool(interp, A)) {
+
        case 0:
+

+
            e->skip = JimWideValue(skip);
+
            ExprPush(e, Jim_NewIntObj(interp, 0));
+
            break;
+

+
        case 1:
+

+
            break;
+

+
        case -1:
+

+
            rc = JIM_ERR;
+
    }
+
    Jim_DecrRefCount(interp, A);
+
    Jim_DecrRefCount(interp, skip);
+

+
    return rc;
+
}
+

+
static int JimExprOpOrLeft(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    Jim_Obj *skip = ExprPop(e);
+
    Jim_Obj *A = ExprPop(e);
+
    int rc = JIM_OK;
+

+
    switch (ExprBool(interp, A)) {
+
        case 0:
+

+
            break;
+

+
        case 1:
+

+
            e->skip = JimWideValue(skip);
+
            ExprPush(e, Jim_NewIntObj(interp, 1));
+
            break;
+

+
        case -1:
+

+
            rc = JIM_ERR;
+
            break;
+
    }
+
    Jim_DecrRefCount(interp, A);
+
    Jim_DecrRefCount(interp, skip);
+

+
    return rc;
+
}
+

+
static int JimExprOpAndOrRight(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    Jim_Obj *A = ExprPop(e);
+
    int rc = JIM_OK;
+

+
    switch (ExprBool(interp, A)) {
+
        case 0:
+
            ExprPush(e, Jim_NewIntObj(interp, 0));
+
            break;
+

+
        case 1:
+
            ExprPush(e, Jim_NewIntObj(interp, 1));
+
            break;
+

+
        case -1:
+

+
            rc = JIM_ERR;
+
            break;
+
    }
+
    Jim_DecrRefCount(interp, A);
+

+
    return rc;
+
}
+

+
static int JimExprOpTernaryLeft(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    Jim_Obj *skip = ExprPop(e);
+
    Jim_Obj *A = ExprPop(e);
+
    int rc = JIM_OK;
+

+

+
    ExprPush(e, A);
+

+
    switch (ExprBool(interp, A)) {
+
        case 0:
+

+
            e->skip = JimWideValue(skip);
+

+
            ExprPush(e, Jim_NewIntObj(interp, 0));
+
            break;
+

+
        case 1:
+

+
            break;
+

+
        case -1:
+

+
            rc = JIM_ERR;
+
            break;
+
    }
+
    Jim_DecrRefCount(interp, A);
+
    Jim_DecrRefCount(interp, skip);
+

+
    return rc;
+
}
+

+
static int JimExprOpColonLeft(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    Jim_Obj *skip = ExprPop(e);
+
    Jim_Obj *B = ExprPop(e);
+
    Jim_Obj *A = ExprPop(e);
+

+

+
    if (ExprBool(interp, A)) {
+

+
        e->skip = JimWideValue(skip);
+

+
        ExprPush(e, B);
+
    }
+

+
    Jim_DecrRefCount(interp, skip);
+
    Jim_DecrRefCount(interp, A);
+
    Jim_DecrRefCount(interp, B);
+
    return JIM_OK;
+
}
+

+
static int JimExprOpNull(Jim_Interp *interp, struct JimExprState *e)
+
{
+
    return JIM_OK;
+
}
+

+
enum
+
{
+
    LAZY_NONE,
+
    LAZY_OP,
+
    LAZY_LEFT,
+
    LAZY_RIGHT,
+
    RIGHT_ASSOC,
+
};
+

+
#define OPRINIT_ATTR(N, P, ARITY, F, ATTR) {N, F, P, ARITY, ATTR, sizeof(N) - 1}
+
#define OPRINIT(N, P, ARITY, F) OPRINIT_ATTR(N, P, ARITY, F, LAZY_NONE)
+

+
static const struct Jim_ExprOperator Jim_ExprOperators[] = {
+
    OPRINIT("*", 110, 2, JimExprOpBin),
+
    OPRINIT("/", 110, 2, JimExprOpBin),
+
    OPRINIT("%", 110, 2, JimExprOpIntBin),
+

+
    OPRINIT("-", 100, 2, JimExprOpBin),
+
    OPRINIT("+", 100, 2, JimExprOpBin),
+

+
    OPRINIT("<<", 90, 2, JimExprOpIntBin),
+
    OPRINIT(">>", 90, 2, JimExprOpIntBin),
+

+
    OPRINIT("<<<", 90, 2, JimExprOpIntBin),
+
    OPRINIT(">>>", 90, 2, JimExprOpIntBin),
+

+
    OPRINIT("<", 80, 2, JimExprOpBin),
+
    OPRINIT(">", 80, 2, JimExprOpBin),
+
    OPRINIT("<=", 80, 2, JimExprOpBin),
+
    OPRINIT(">=", 80, 2, JimExprOpBin),
+

+
    OPRINIT("==", 70, 2, JimExprOpBin),
+
    OPRINIT("!=", 70, 2, JimExprOpBin),
+

+
    OPRINIT("&", 50, 2, JimExprOpIntBin),
+
    OPRINIT("^", 49, 2, JimExprOpIntBin),
+
    OPRINIT("|", 48, 2, JimExprOpIntBin),
+

+
    OPRINIT_ATTR("&&", 10, 2, NULL, LAZY_OP),
+
    OPRINIT_ATTR(NULL, 10, 2, JimExprOpAndLeft, LAZY_LEFT),
+
    OPRINIT_ATTR(NULL, 10, 2, JimExprOpAndOrRight, LAZY_RIGHT),
+

+
    OPRINIT_ATTR("||", 9, 2, NULL, LAZY_OP),
+
    OPRINIT_ATTR(NULL, 9, 2, JimExprOpOrLeft, LAZY_LEFT),
+
    OPRINIT_ATTR(NULL, 9, 2, JimExprOpAndOrRight, LAZY_RIGHT),
+

+
    OPRINIT_ATTR("?", 5, 2, JimExprOpNull, LAZY_OP),
+
    OPRINIT_ATTR(NULL, 5, 2, JimExprOpTernaryLeft, LAZY_LEFT),
+
    OPRINIT_ATTR(NULL, 5, 2, JimExprOpNull, LAZY_RIGHT),
+

+
    OPRINIT_ATTR(":", 5, 2, JimExprOpNull, LAZY_OP),
+
    OPRINIT_ATTR(NULL, 5, 2, JimExprOpColonLeft, LAZY_LEFT),
+
    OPRINIT_ATTR(NULL, 5, 2, JimExprOpNull, LAZY_RIGHT),
+

+

+
    OPRINIT_ATTR("**", 120, 2, JimExprOpBin, RIGHT_ASSOC),
+

+
    OPRINIT("eq", 60, 2, JimExprOpStrBin),
+
    OPRINIT("ne", 60, 2, JimExprOpStrBin),
+

+
    OPRINIT("in", 55, 2, JimExprOpStrBin),
+
    OPRINIT("ni", 55, 2, JimExprOpStrBin),
+

+
    OPRINIT("!", 150, 1, JimExprOpNumUnary),
+
    OPRINIT("~", 150, 1, JimExprOpIntUnary),
+
    OPRINIT(NULL, 150, 1, JimExprOpNumUnary),
+
    OPRINIT(NULL, 150, 1, JimExprOpNumUnary),
+

+

+

+
    OPRINIT("int", 200, 1, JimExprOpNumUnary),
+
    OPRINIT("wide", 200, 1, JimExprOpNumUnary),
+
    OPRINIT("abs", 200, 1, JimExprOpNumUnary),
+
    OPRINIT("double", 200, 1, JimExprOpNumUnary),
+
    OPRINIT("round", 200, 1, JimExprOpNumUnary),
+
    OPRINIT("rand", 200, 0, JimExprOpNone),
+
    OPRINIT("srand", 200, 1, JimExprOpIntUnary),
+

+
#ifdef JIM_MATH_FUNCTIONS
+
    OPRINIT("sin", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("cos", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("tan", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("asin", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("acos", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("atan", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("atan2", 200, 2, JimExprOpBin),
+
    OPRINIT("sinh", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("cosh", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("tanh", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("ceil", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("floor", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("exp", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("log", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("log10", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("sqrt", 200, 1, JimExprOpDoubleUnary),
+
    OPRINIT("pow", 200, 2, JimExprOpBin),
+
    OPRINIT("hypot", 200, 2, JimExprOpBin),
+
    OPRINIT("fmod", 200, 2, JimExprOpBin),
+
#endif
+
};
+
#undef OPRINIT
+
#undef OPRINIT_LAZY
+

+
#define JIM_EXPR_OPERATORS_NUM \
+
    (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
+

+
static int JimParseExpression(struct JimParserCtx *pc)
+
{
+

+
    while (isspace(UCHAR(*pc->p)) || (*(pc->p) == '\\' && *(pc->p + 1) == '\n')) {
+
        if (*pc->p == '\n') {
+
            pc->linenr++;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+

+

+
    pc->tline = pc->linenr;
+
    pc->tstart = pc->p;
+

+
    if (pc->len == 0) {
+
        pc->tend = pc->p;
+
        pc->tt = JIM_TT_EOL;
+
        pc->eof = 1;
+
        return JIM_OK;
+
    }
+
    switch (*(pc->p)) {
+
        case '(':
+
                pc->tt = JIM_TT_SUBEXPR_START;
+
                goto singlechar;
+
        case ')':
+
                pc->tt = JIM_TT_SUBEXPR_END;
+
                goto singlechar;
+
        case ',':
+
            pc->tt = JIM_TT_SUBEXPR_COMMA;
+
singlechar:
+
            pc->tend = pc->p;
+
            pc->p++;
+
            pc->len--;
+
            break;
+
        case '[':
+
            return JimParseCmd(pc);
+
        case '$':
+
            if (JimParseVar(pc) == JIM_ERR)
+
                return JimParseExprOperator(pc);
+
            else {
+

+
                if (pc->tt == JIM_TT_EXPRSUGAR) {
+
                    return JIM_ERR;
+
                }
+
                return JIM_OK;
+
            }
+
            break;
+
        case '0':
+
        case '1':
+
        case '2':
+
        case '3':
+
        case '4':
+
        case '5':
+
        case '6':
+
        case '7':
+
        case '8':
+
        case '9':
+
        case '.':
+
            return JimParseExprNumber(pc);
+
        case '"':
+
            return JimParseQuote(pc);
+
        case '{':
+
            return JimParseBrace(pc);
+

+
        case 'N':
+
        case 'I':
+
        case 'n':
+
        case 'i':
+
            if (JimParseExprIrrational(pc) == JIM_ERR)
+
                if (JimParseExprBoolean(pc) == JIM_ERR)
+
                    return JimParseExprOperator(pc);
+
            break;
+
        case 't':
+
        case 'f':
+
        case 'o':
+
        case 'y':
+
            if (JimParseExprBoolean(pc) == JIM_ERR)
+
                return JimParseExprOperator(pc);
+
            break;
+
        default:
+
            return JimParseExprOperator(pc);
+
            break;
+
    }
+
    return JIM_OK;
+
}
+

+
static int JimParseExprNumber(struct JimParserCtx *pc)
+
{
+
    char *end;
+

+

+
    pc->tt = JIM_TT_EXPR_INT;
+

+
    jim_strtoull(pc->p, (char **)&pc->p);
+

+
    if (strchr("eENnIi.", *pc->p) || pc->p == pc->tstart) {
+
        if (strtod(pc->tstart, &end)) { }
+
        if (end == pc->tstart)
+
            return JIM_ERR;
+
        if (end > pc->p) {
+

+
            pc->tt = JIM_TT_EXPR_DOUBLE;
+
            pc->p = end;
+
        }
+
    }
+
    pc->tend = pc->p - 1;
+
    pc->len -= (pc->p - pc->tstart);
+
    return JIM_OK;
+
}
+

+
static int JimParseExprIrrational(struct JimParserCtx *pc)
+
{
+
    const char *irrationals[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL };
+
    int i;
+

+
    for (i = 0; irrationals[i]; i++) {
+
        const char *irr = irrationals[i];
+

+
        if (strncmp(irr, pc->p, 3) == 0) {
+
            pc->p += 3;
+
            pc->len -= 3;
+
            pc->tend = pc->p - 1;
+
            pc->tt = JIM_TT_EXPR_DOUBLE;
+
            return JIM_OK;
+
        }
+
    }
+
    return JIM_ERR;
+
}
+

+
static int JimParseExprBoolean(struct JimParserCtx *pc)
+
{
+
    const char *booleans[] = { "false", "no", "off", "true", "yes", "on", NULL };
+
    const int lengths[] = { 5, 2, 3, 4, 3, 2, 0 };
+
    int i;
+

+
    for (i = 0; booleans[i]; i++) {
+
        const char *boolean = booleans[i];
+
        int length = lengths[i];
+

+
        if (strncmp(boolean, pc->p, length) == 0) {
+
            pc->p += length;
+
            pc->len -= length;
+
            pc->tend = pc->p - 1;
+
            pc->tt = JIM_TT_EXPR_BOOLEAN;
+
            return JIM_OK;
+
        }
+
    }
+
    return JIM_ERR;
+
}
+

+
static int JimParseExprOperator(struct JimParserCtx *pc)
+
{
+
    int i;
+
    int bestIdx = -1, bestLen = 0;
+

+

+
    for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
+
        const char * const opname = Jim_ExprOperators[i].name;
+
        const int oplen = Jim_ExprOperators[i].namelen;
+

+
        if (opname == NULL || opname[0] != pc->p[0]) {
+
            continue;
+
        }
+

+
        if (oplen > bestLen && strncmp(opname, pc->p, oplen) == 0) {
+
            bestIdx = i + JIM_TT_EXPR_OP;
+
            bestLen = oplen;
+
        }
+
    }
+
    if (bestIdx == -1) {
+
        return JIM_ERR;
+
    }
+

+

+
    if (bestIdx >= JIM_EXPROP_FUNC_FIRST) {
+
        const char *p = pc->p + bestLen;
+
        int len = pc->len - bestLen;
+

+
        while (len && isspace(UCHAR(*p))) {
+
            len--;
+
            p++;
+
        }
+
        if (*p != '(') {
+
            return JIM_ERR;
+
        }
+
    }
+
    pc->tend = pc->p + bestLen - 1;
+
    pc->p += bestLen;
+
    pc->len -= bestLen;
+

+
    pc->tt = bestIdx;
+
    return JIM_OK;
+
}
+

+
static const struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
+
{
+
    static Jim_ExprOperator dummy_op;
+
    if (opcode < JIM_TT_EXPR_OP) {
+
        return &dummy_op;
+
    }
+
    return &Jim_ExprOperators[opcode - JIM_TT_EXPR_OP];
+
}
+

+
const char *jim_tt_name(int type)
+
{
+
    static const char * const tt_names[JIM_TT_EXPR_OP] =
+
        { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", ",,,", "INT",
+
            "DBL", "BOO", "$()" };
+
    if (type < JIM_TT_EXPR_OP) {
+
        return tt_names[type];
+
    }
+
    else if (type == JIM_EXPROP_UNARYMINUS) {
+
        return "-VE";
+
    }
+
    else if (type == JIM_EXPROP_UNARYPLUS) {
+
        return "+VE";
+
    }
+
    else {
+
        const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(type);
+
        static char buf[20];
+

+
        if (op->name) {
+
            return op->name;
+
        }
+
        sprintf(buf, "(%d)", type);
+
        return buf;
+
    }
+
}
+

+
static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+
static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+

+
static const Jim_ObjType exprObjType = {
+
    "expression",
+
    FreeExprInternalRep,
+
    DupExprInternalRep,
+
    NULL,
+
    JIM_TYPE_REFERENCES,
+
};
+

+

+
typedef struct ExprByteCode
+
{
+
    ScriptToken *token;
+
    int len;
+
    int inUse;
+
} ExprByteCode;
+

+
static void ExprFreeByteCode(Jim_Interp *interp, ExprByteCode * expr)
+
{
+
    int i;
+

+
    for (i = 0; i < expr->len; i++) {
+
        Jim_DecrRefCount(interp, expr->token[i].objPtr);
+
    }
+
    Jim_Free(expr->token);
+
    Jim_Free(expr);
+
}
+

+
static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    ExprByteCode *expr = (void *)objPtr->internalRep.ptr;
+

+
    if (expr) {
+
        if (--expr->inUse != 0) {
+
            return;
+
        }
+

+
        ExprFreeByteCode(interp, expr);
+
    }
+
}
+

+
static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    JIM_NOTUSED(interp);
+
    JIM_NOTUSED(srcPtr);
+

+

+
    dupPtr->typePtr = NULL;
+
}
+

+
static int ExprCheckCorrectness(Jim_Interp *interp, Jim_Obj *exprObjPtr, ExprByteCode * expr)
+
{
+
    int i;
+
    int stacklen = 0;
+
    int ternary = 0;
+
    int lasttt = JIM_TT_NONE;
+
    const char *errmsg;
+

+
    for (i = 0; i < expr->len; i++) {
+
        ScriptToken *t = &expr->token[i];
+
        const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
+
        lasttt = t->type;
+

+
        stacklen -= op->arity;
+

+
        if (stacklen < 0) {
+
            break;
+
        }
+
        if (t->type == JIM_EXPROP_TERNARY || t->type == JIM_EXPROP_TERNARY_LEFT) {
+
            ternary++;
+
        }
+
        else if (t->type == JIM_EXPROP_COLON || t->type == JIM_EXPROP_COLON_LEFT) {
+
            ternary--;
+
        }
+

+

+
        stacklen++;
+
    }
+
    if (stacklen == 1 && ternary == 0) {
+
        return JIM_OK;
+
    }
+

+
    if (stacklen <= 0) {
+

+
        if (lasttt >= JIM_EXPROP_FUNC_FIRST) {
+
            errmsg = "too few arguments for math function";
+
            Jim_SetResultString(interp, "too few arguments for math function", -1);
+
        } else {
+
            errmsg = "premature end of expression";
+
        }
+
    }
+
    else if (stacklen > 1) {
+
        if (lasttt >= JIM_EXPROP_FUNC_FIRST) {
+
            errmsg = "too many arguments for math function";
+
        } else {
+
            errmsg = "extra tokens at end of expression";
+
        }
+
    }
+
    else {
+
        errmsg = "invalid ternary expression";
+
    }
+
    Jim_SetResultFormatted(interp, "syntax error in expression \"%#s\": %s", exprObjPtr, errmsg);
+
    return JIM_ERR;
+
}
+

+
static int ExprAddLazyOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
+
{
+
    int i;
+

+
    int leftindex, arity, offset;
+

+

+
    leftindex = expr->len - 1;
+

+
    arity = 1;
+
    while (arity) {
+
        ScriptToken *tt = &expr->token[leftindex];
+

+
        if (tt->type >= JIM_TT_EXPR_OP) {
+
            arity += JimExprOperatorInfoByOpcode(tt->type)->arity;
+
        }
+
        arity--;
+
        if (--leftindex < 0) {
+
            return JIM_ERR;
+
        }
+
    }
+
    leftindex++;
+

+

+
    memmove(&expr->token[leftindex + 2], &expr->token[leftindex],
+
        sizeof(*expr->token) * (expr->len - leftindex));
+
    expr->len += 2;
+
    offset = (expr->len - leftindex) - 1;
+

+
    expr->token[leftindex + 1].type = t->type + 1;
+
    expr->token[leftindex + 1].objPtr = interp->emptyObj;
+

+
    expr->token[leftindex].type = JIM_TT_EXPR_INT;
+
    expr->token[leftindex].objPtr = Jim_NewIntObj(interp, offset);
+

+

+
    expr->token[expr->len].objPtr = interp->emptyObj;
+
    expr->token[expr->len].type = t->type + 2;
+
    expr->len++;
+

+

+
    for (i = leftindex - 1; i > 0; i--) {
+
        const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(expr->token[i].type);
+
        if (op->lazy == LAZY_LEFT) {
+
            if (JimWideValue(expr->token[i - 1].objPtr) + i - 1 >= leftindex) {
+
                JimWideValue(expr->token[i - 1].objPtr) += 2;
+
            }
+
        }
+
    }
+
    return JIM_OK;
+
}
+

+
static int ExprAddOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
+
{
+
    struct ScriptToken *token = &expr->token[expr->len];
+
    const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
+

+
    if (op->lazy == LAZY_OP) {
+
        if (ExprAddLazyOperator(interp, expr, t) != JIM_OK) {
+
            Jim_SetResultFormatted(interp, "Expression has bad operands to %s", op->name);
+
            return JIM_ERR;
+
        }
+
    }
+
    else {
+
        token->objPtr = interp->emptyObj;
+
        token->type = t->type;
+
        expr->len++;
+
    }
+
    return JIM_OK;
+
}
+

+
static int ExprTernaryGetColonLeftIndex(ExprByteCode *expr, int right_index)
+
{
+
    int ternary_count = 1;
+

+
    right_index--;
+

+
    while (right_index > 1) {
+
        if (expr->token[right_index].type == JIM_EXPROP_TERNARY_LEFT) {
+
            ternary_count--;
+
        }
+
        else if (expr->token[right_index].type == JIM_EXPROP_COLON_RIGHT) {
+
            ternary_count++;
+
        }
+
        else if (expr->token[right_index].type == JIM_EXPROP_COLON_LEFT && ternary_count == 1) {
+
            return right_index;
+
        }
+
        right_index--;
+
    }
+

+

+
    return -1;
+
}
+

+
static int ExprTernaryGetMoveIndices(ExprByteCode *expr, int right_index, int *prev_right_index, int *prev_left_index)
+
{
+
    int i = right_index - 1;
+
    int ternary_count = 1;
+

+
    while (i > 1) {
+
        if (expr->token[i].type == JIM_EXPROP_TERNARY_LEFT) {
+
            if (--ternary_count == 0 && expr->token[i - 2].type == JIM_EXPROP_COLON_RIGHT) {
+
                *prev_right_index = i - 2;
+
                *prev_left_index = ExprTernaryGetColonLeftIndex(expr, *prev_right_index);
+
                return 1;
+
            }
+
        }
+
        else if (expr->token[i].type == JIM_EXPROP_COLON_RIGHT) {
+
            if (ternary_count == 0) {
+
                return 0;
+
            }
+
            ternary_count++;
+
        }
+
        i--;
+
    }
+
    return 0;
+
}
+

+
static void ExprTernaryReorderExpression(Jim_Interp *interp, ExprByteCode *expr)
+
{
+
    int i;
+

+
    for (i = expr->len - 1; i > 1; i--) {
+
        int prev_right_index;
+
        int prev_left_index;
+
        int j;
+
        ScriptToken tmp;
+

+
        if (expr->token[i].type != JIM_EXPROP_COLON_RIGHT) {
+
            continue;
+
        }
+

+

+
        if (ExprTernaryGetMoveIndices(expr, i, &prev_right_index, &prev_left_index) == 0) {
+
            continue;
+
        }
+

+
        tmp = expr->token[prev_right_index];
+
        for (j = prev_right_index; j < i; j++) {
+
            expr->token[j] = expr->token[j + 1];
+
        }
+
        expr->token[i] = tmp;
+

+
        JimWideValue(expr->token[prev_left_index-1].objPtr) += (i - prev_right_index);
+

+

+
        i++;
+
    }
+
}
+

+
static ExprByteCode *ExprCreateByteCode(Jim_Interp *interp, const ParseTokenList *tokenlist, Jim_Obj *exprObjPtr, Jim_Obj *fileNameObj)
+
{
+
    Jim_Stack stack;
+
    ExprByteCode *expr;
+
    int ok = 1;
+
    int i;
+
    int prevtt = JIM_TT_NONE;
+
    int have_ternary = 0;
+

+

+
    int count = tokenlist->count - 1;
+

+
    expr = Jim_Alloc(sizeof(*expr));
+
    expr->inUse = 1;
+
    expr->len = 0;
+

+
    Jim_InitStack(&stack);
+

+
    for (i = 0; i < tokenlist->count; i++) {
+
        ParseToken *t = &tokenlist->list[i];
+
        const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
+

+
        if (op->lazy == LAZY_OP) {
+
            count += 2;
+

+
            if (t->type == JIM_EXPROP_TERNARY) {
+
                have_ternary = 1;
+
            }
+
        }
+
    }
+

+
    expr->token = Jim_Alloc(sizeof(ScriptToken) * count);
+

+
    for (i = 0; i < tokenlist->count && ok; i++) {
+
        ParseToken *t = &tokenlist->list[i];
+

+

+
        struct ScriptToken *token = &expr->token[expr->len];
+

+
        if (t->type == JIM_TT_EOL) {
+
            break;
+
        }
+

+
        if (TOKEN_IS_EXPR_OP(t->type)) {
+
            const struct Jim_ExprOperator *op;
+
            ParseToken *tt;
+

+

+
            if (prevtt == JIM_TT_NONE || prevtt == JIM_TT_SUBEXPR_START || prevtt == JIM_TT_SUBEXPR_COMMA || prevtt >= JIM_TT_EXPR_OP) {
+
                if (t->type == JIM_EXPROP_SUB) {
+
                    t->type = JIM_EXPROP_UNARYMINUS;
+
                }
+
                else if (t->type == JIM_EXPROP_ADD) {
+
                    t->type = JIM_EXPROP_UNARYPLUS;
+
                }
+
            }
+

+
            op = JimExprOperatorInfoByOpcode(t->type);
+

+

+
            while ((tt = Jim_StackPeek(&stack)) != NULL) {
+
                const struct Jim_ExprOperator *tt_op =
+
                    JimExprOperatorInfoByOpcode(tt->type);
+

+

+
                if (op->arity != 1 && tt_op->precedence >= op->precedence) {
+

+
                    if (tt_op->precedence == op->precedence && tt_op->lazy == RIGHT_ASSOC) {
+
                        break;
+
                    }
+
                    if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
+
                        ok = 0;
+
                        goto err;
+
                    }
+
                    Jim_StackPop(&stack);
+
                }
+
                else {
+
                    break;
+
                }
+
            }
+
            Jim_StackPush(&stack, t);
+
        }
+
        else if (t->type == JIM_TT_SUBEXPR_START) {
+
            Jim_StackPush(&stack, t);
+
        }
+
        else if (t->type == JIM_TT_SUBEXPR_END || t->type == JIM_TT_SUBEXPR_COMMA) {
+

+
            ok = 0;
+
            while (Jim_StackLen(&stack)) {
+
                ParseToken *tt = Jim_StackPop(&stack);
+

+
                if (tt->type == JIM_TT_SUBEXPR_START || tt->type == JIM_TT_SUBEXPR_COMMA) {
+
                    if (t->type == JIM_TT_SUBEXPR_COMMA) {
+

+
                        Jim_StackPush(&stack, tt);
+
                    }
+
                    ok = 1;
+
                    break;
+
                }
+
                if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
+
                    goto err;
+
                }
+
            }
+
            if (!ok) {
+
                Jim_SetResultFormatted(interp, "Unexpected close parenthesis in expression: \"%#s\"", exprObjPtr);
+
                goto err;
+
            }
+
        }
+
        else {
+
            Jim_Obj *objPtr = NULL;
+

+

+
            token->type = t->type;
+

+

+
            if (!TOKEN_IS_EXPR_START(prevtt) && !TOKEN_IS_EXPR_OP(prevtt)) {
+
                Jim_SetResultFormatted(interp, "missing operator in expression: \"%#s\"", exprObjPtr);
+
                ok = 0;
+
                goto err;
+
            }
+

+

+
            if (t->type == JIM_TT_EXPR_INT || t->type == JIM_TT_EXPR_DOUBLE) {
+
                char *endptr;
+
                if (t->type == JIM_TT_EXPR_INT) {
+
                    objPtr = Jim_NewIntObj(interp, jim_strtoull(t->token, &endptr));
+
                }
+
                else {
+
                    objPtr = Jim_NewDoubleObj(interp, strtod(t->token, &endptr));
+
                }
+
                if (endptr != t->token + t->len) {
+

+
                    Jim_FreeNewObj(interp, objPtr);
+
                    objPtr = NULL;
+
                }
+
            }
+

+
            if (objPtr) {
+
                token->objPtr = objPtr;
+
            }
+
            else {
+

+
                token->objPtr = Jim_NewStringObj(interp, t->token, t->len);
+
                if (t->type == JIM_TT_CMD) {
+

+
                    JimSetSourceInfo(interp, token->objPtr, fileNameObj, t->line);
+
                }
+
            }
+
            expr->len++;
+
        }
+
        prevtt = t->type;
+
    }
+

+

+
    while (Jim_StackLen(&stack)) {
+
        ParseToken *tt = Jim_StackPop(&stack);
+

+
        if (tt->type == JIM_TT_SUBEXPR_START) {
+
            ok = 0;
+
            Jim_SetResultString(interp, "Missing close parenthesis", -1);
+
            goto err;
+
        }
+
        if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
+
            ok = 0;
+
            goto err;
+
        }
+
    }
+

+
    if (have_ternary) {
+
        ExprTernaryReorderExpression(interp, expr);
+
    }
+

+
  err:
+

+
    Jim_FreeStack(&stack);
+

+
    for (i = 0; i < expr->len; i++) {
+
        Jim_IncrRefCount(expr->token[i].objPtr);
+
    }
+

+
    if (!ok) {
+
        ExprFreeByteCode(interp, expr);
+
        return NULL;
+
    }
+

+
    return expr;
+
}
+

+

+
static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+
{
+
    int exprTextLen;
+
    const char *exprText;
+
    struct JimParserCtx parser;
+
    struct ExprByteCode *expr;
+
    ParseTokenList tokenlist;
+
    int line;
+
    Jim_Obj *fileNameObj;
+
    int rc = JIM_ERR;
+

+

+
    if (objPtr->typePtr == &sourceObjType) {
+
        fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
+
        line = objPtr->internalRep.sourceValue.lineNumber;
+
    }
+
    else {
+
        fileNameObj = interp->emptyObj;
+
        line = 1;
+
    }
+
    Jim_IncrRefCount(fileNameObj);
+

+
    exprText = Jim_GetString(objPtr, &exprTextLen);
+

+

+
    ScriptTokenListInit(&tokenlist);
+

+
    JimParserInit(&parser, exprText, exprTextLen, line);
+
    while (!parser.eof) {
+
        if (JimParseExpression(&parser) != JIM_OK) {
+
            ScriptTokenListFree(&tokenlist);
+
            Jim_SetResultFormatted(interp, "syntax error in expression: \"%#s\"", objPtr);
+
            expr = NULL;
+
            goto err;
+
        }
+

+
        ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
+
            parser.tline);
+
    }
+

+
#ifdef DEBUG_SHOW_EXPR_TOKENS
+
    {
+
        int i;
+
        printf("==== Expr Tokens (%s) ====\n", Jim_String(fileNameObj));
+
        for (i = 0; i < tokenlist.count; i++) {
+
            printf("[%2d]@%d %s '%.*s'\n", i, tokenlist.list[i].line, jim_tt_name(tokenlist.list[i].type),
+
                tokenlist.list[i].len, tokenlist.list[i].token);
+
        }
+
    }
+
#endif
+

+
    if (JimParseCheckMissing(interp, parser.missing.ch) == JIM_ERR) {
+
        ScriptTokenListFree(&tokenlist);
+
        Jim_DecrRefCount(interp, fileNameObj);
+
        return JIM_ERR;
+
    }
+

+

+
    expr = ExprCreateByteCode(interp, &tokenlist, objPtr, fileNameObj);
+

+

+
    ScriptTokenListFree(&tokenlist);
+

+
    if (!expr) {
+
        goto err;
+
    }
+

+
#ifdef DEBUG_SHOW_EXPR
+
    {
+
        int i;
+

+
        printf("==== Expr ====\n");
+
        for (i = 0; i < expr->len; i++) {
+
            ScriptToken *t = &expr->token[i];
+

+
            printf("[%2d] %s '%s'\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
+
        }
+
    }
+
#endif
+

+

+
    if (ExprCheckCorrectness(interp, objPtr, expr) != JIM_OK) {
+

+
        ExprFreeByteCode(interp, expr);
+
        expr = NULL;
+
        goto err;
+
    }
+

+
    rc = JIM_OK;
+

+
  err:
+

+
    Jim_DecrRefCount(interp, fileNameObj);
+
    Jim_FreeIntRep(interp, objPtr);
+
    Jim_SetIntRepPtr(objPtr, expr);
+
    objPtr->typePtr = &exprObjType;
+
    return rc;
+
}
+

+
static ExprByteCode *JimGetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    if (objPtr->typePtr != &exprObjType) {
+
        if (SetExprFromAny(interp, objPtr) != JIM_OK) {
+
            return NULL;
+
        }
+
    }
+
    return (ExprByteCode *) Jim_GetIntRepPtr(objPtr);
+
}
+

+
#ifdef JIM_OPTIMIZATION
+
static Jim_Obj *JimExprIntValOrVar(Jim_Interp *interp, const ScriptToken *token)
+
{
+
    if (token->type == JIM_TT_EXPR_INT)
+
        return token->objPtr;
+
    else if (token->type == JIM_TT_VAR)
+
        return Jim_GetVariable(interp, token->objPtr, JIM_NONE);
+
    else if (token->type == JIM_TT_DICTSUGAR)
+
        return JimExpandDictSugar(interp, token->objPtr);
+
    else
+
        return NULL;
+
}
+
#endif
+

+
#define JIM_EE_STATICSTACK_LEN 10
+

+
int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr, Jim_Obj **exprResultPtrPtr)
+
{
+
    ExprByteCode *expr;
+
    Jim_Obj *staticStack[JIM_EE_STATICSTACK_LEN];
+
    int i;
+
    int retcode = JIM_OK;
+
    struct JimExprState e;
+

+
    expr = JimGetExpression(interp, exprObjPtr);
+
    if (!expr) {
+
        return JIM_ERR;
+
    }
+

+
#ifdef JIM_OPTIMIZATION
+
    {
+
        Jim_Obj *objPtr;
+

+

+
        switch (expr->len) {
+
            case 1:
+
                objPtr = JimExprIntValOrVar(interp, &expr->token[0]);
+
                if (objPtr) {
+
                    Jim_IncrRefCount(objPtr);
+
                    *exprResultPtrPtr = objPtr;
+
                    return JIM_OK;
+
                }
+
                break;
+

+
            case 2:
+
                if (expr->token[1].type == JIM_EXPROP_NOT) {
+
                    objPtr = JimExprIntValOrVar(interp, &expr->token[0]);
+

+
                    if (objPtr && JimIsWide(objPtr)) {
+
                        *exprResultPtrPtr = JimWideValue(objPtr) ? interp->falseObj : interp->trueObj;
+
                        Jim_IncrRefCount(*exprResultPtrPtr);
+
                        return JIM_OK;
+
                    }
+
                }
+
                break;
+

+
            case 3:
+
                objPtr = JimExprIntValOrVar(interp, &expr->token[0]);
+
                if (objPtr && JimIsWide(objPtr)) {
+
                    Jim_Obj *objPtr2 = JimExprIntValOrVar(interp, &expr->token[1]);
+
                    if (objPtr2 && JimIsWide(objPtr2)) {
+
                        jim_wide wideValueA = JimWideValue(objPtr);
+
                        jim_wide wideValueB = JimWideValue(objPtr2);
+
                        int cmpRes;
+
                        switch (expr->token[2].type) {
+
                            case JIM_EXPROP_LT:
+
                                cmpRes = wideValueA < wideValueB;
+
                                break;
+
                            case JIM_EXPROP_LTE:
+
                                cmpRes = wideValueA <= wideValueB;
+
                                break;
+
                            case JIM_EXPROP_GT:
+
                                cmpRes = wideValueA > wideValueB;
+
                                break;
+
                            case JIM_EXPROP_GTE:
+
                                cmpRes = wideValueA >= wideValueB;
+
                                break;
+
                            case JIM_EXPROP_NUMEQ:
+
                                cmpRes = wideValueA == wideValueB;
+
                                break;
+
                            case JIM_EXPROP_NUMNE:
+
                                cmpRes = wideValueA != wideValueB;
+
                                break;
+
                            default:
+
                                goto noopt;
+
                        }
+
                        *exprResultPtrPtr = cmpRes ? interp->trueObj : interp->falseObj;
+
                        Jim_IncrRefCount(*exprResultPtrPtr);
+
                        return JIM_OK;
+
                    }
+
                }
+
                break;
+
        }
+
    }
+
noopt:
+
#endif
+

+
    expr->inUse++;
+

+

+

+
    if (expr->len > JIM_EE_STATICSTACK_LEN)
+
        e.stack = Jim_Alloc(sizeof(Jim_Obj *) * expr->len);
+
    else
+
        e.stack = staticStack;
+

+
    e.stacklen = 0;
+

+

+
    for (i = 0; i < expr->len && retcode == JIM_OK; i++) {
+
        Jim_Obj *objPtr;
+

+
        switch (expr->token[i].type) {
+
            case JIM_TT_EXPR_INT:
+
            case JIM_TT_EXPR_DOUBLE:
+
            case JIM_TT_EXPR_BOOLEAN:
+
            case JIM_TT_STR:
+
                ExprPush(&e, expr->token[i].objPtr);
+
                break;
+

+
            case JIM_TT_VAR:
+
                objPtr = Jim_GetVariable(interp, expr->token[i].objPtr, JIM_ERRMSG);
+
                if (objPtr) {
+
                    ExprPush(&e, objPtr);
+
                }
+
                else {
+
                    retcode = JIM_ERR;
+
                }
+
                break;
+

+
            case JIM_TT_DICTSUGAR:
+
                objPtr = JimExpandDictSugar(interp, expr->token[i].objPtr);
+
                if (objPtr) {
+
                    ExprPush(&e, objPtr);
+
                }
+
                else {
+
                    retcode = JIM_ERR;
+
                }
+
                break;
+

+
            case JIM_TT_ESC:
+
                retcode = Jim_SubstObj(interp, expr->token[i].objPtr, &objPtr, JIM_NONE);
+
                if (retcode == JIM_OK) {
+
                    ExprPush(&e, objPtr);
+
                }
+
                break;
+

+
            case JIM_TT_CMD:
+
                retcode = Jim_EvalObj(interp, expr->token[i].objPtr);
+
                if (retcode == JIM_OK) {
+
                    ExprPush(&e, Jim_GetResult(interp));
+
                }
+
                break;
+

+
            default:{
+

+
                    e.skip = 0;
+
                    e.opcode = expr->token[i].type;
+

+
                    retcode = JimExprOperatorInfoByOpcode(e.opcode)->funcop(interp, &e);
+

+
                    i += e.skip;
+
                    continue;
+
                }
+
        }
+
    }
+

+
    expr->inUse--;
+

+
    if (retcode == JIM_OK) {
+
        *exprResultPtrPtr = ExprPop(&e);
+
    }
+
    else {
+
        for (i = 0; i < e.stacklen; i++) {
+
            Jim_DecrRefCount(interp, e.stack[i]);
+
        }
+
    }
+
    if (e.stack != staticStack) {
+
        Jim_Free(e.stack);
+
    }
+
    return retcode;
+
}
+

+
int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
+
{
+
    int retcode;
+
    jim_wide wideValue;
+
    double doubleValue;
+
    int booleanValue;
+
    Jim_Obj *exprResultPtr;
+

+
    retcode = Jim_EvalExpression(interp, exprObjPtr, &exprResultPtr);
+
    if (retcode != JIM_OK)
+
        return retcode;
+

+
    if (JimGetWideNoErr(interp, exprResultPtr, &wideValue) != JIM_OK) {
+
        if (Jim_GetDouble(interp, exprResultPtr, &doubleValue) != JIM_OK) {
+
            if (Jim_GetBoolean(interp, exprResultPtr, &booleanValue) != JIM_OK) {
+
                Jim_DecrRefCount(interp, exprResultPtr);
+
                return JIM_ERR;
+
            } else {
+
                Jim_DecrRefCount(interp, exprResultPtr);
+
                *boolPtr = booleanValue;
+
                return JIM_OK;
+
            }
+
        }
+
        else {
+
            Jim_DecrRefCount(interp, exprResultPtr);
+
            *boolPtr = doubleValue != 0;
+
            return JIM_OK;
+
        }
+
    }
+
    *boolPtr = wideValue != 0;
+

+
    Jim_DecrRefCount(interp, exprResultPtr);
+
    return JIM_OK;
+
}
+

+

+

+

+
typedef struct ScanFmtPartDescr
+
{
+
    char *arg;
+
    char *prefix;
+
    size_t width;
+
    int pos;
+
    char type;
+
    char modifier;
+
} ScanFmtPartDescr;
+

+

+
typedef struct ScanFmtStringObj
+
{
+
    jim_wide size;
+
    char *stringRep;
+
    size_t count;
+
    size_t convCount;
+
    size_t maxPos;
+
    const char *error;
+
    char *scratch;
+
    ScanFmtPartDescr descr[1];
+
} ScanFmtStringObj;
+

+

+
static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+
static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
+

+
static const Jim_ObjType scanFmtStringObjType = {
+
    "scanformatstring",
+
    FreeScanFmtInternalRep,
+
    DupScanFmtInternalRep,
+
    UpdateStringOfScanFmt,
+
    JIM_TYPE_NONE,
+
};
+

+
void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    JIM_NOTUSED(interp);
+
    Jim_Free((char *)objPtr->internalRep.ptr);
+
    objPtr->internalRep.ptr = 0;
+
}
+

+
void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+
{
+
    size_t size = (size_t) ((ScanFmtStringObj *) srcPtr->internalRep.ptr)->size;
+
    ScanFmtStringObj *newVec = (ScanFmtStringObj *) Jim_Alloc(size);
+

+
    JIM_NOTUSED(interp);
+
    memcpy(newVec, srcPtr->internalRep.ptr, size);
+
    dupPtr->internalRep.ptr = newVec;
+
    dupPtr->typePtr = &scanFmtStringObjType;
+
}
+

+
static void UpdateStringOfScanFmt(Jim_Obj *objPtr)
+
{
+
    JimSetStringBytes(objPtr, ((ScanFmtStringObj *) objPtr->internalRep.ptr)->stringRep);
+
}
+

+

+
static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    ScanFmtStringObj *fmtObj;
+
    char *buffer;
+
    int maxCount, i, approxSize, lastPos = -1;
+
    const char *fmt = objPtr->bytes;
+
    int maxFmtLen = objPtr->length;
+
    const char *fmtEnd = fmt + maxFmtLen;
+
    int curr;
+

+
    Jim_FreeIntRep(interp, objPtr);
+

+
    for (i = 0, maxCount = 0; i < maxFmtLen; ++i)
+
        if (fmt[i] == '%')
+
            ++maxCount;
+

+
    approxSize = sizeof(ScanFmtStringObj)
+
        +(maxCount + 1) * sizeof(ScanFmtPartDescr)
+
        +maxFmtLen * sizeof(char) + 3 + 1
+
        + maxFmtLen * sizeof(char) + 1
+
        + maxFmtLen * sizeof(char)
+
        +(maxCount + 1) * sizeof(char)
+
        +1;
+
    fmtObj = (ScanFmtStringObj *) Jim_Alloc(approxSize);
+
    memset(fmtObj, 0, approxSize);
+
    fmtObj->size = approxSize;
+
    fmtObj->maxPos = 0;
+
    fmtObj->scratch = (char *)&fmtObj->descr[maxCount + 1];
+
    fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
+
    memcpy(fmtObj->stringRep, fmt, maxFmtLen);
+
    buffer = fmtObj->stringRep + maxFmtLen + 1;
+
    objPtr->internalRep.ptr = fmtObj;
+
    objPtr->typePtr = &scanFmtStringObjType;
+
    for (i = 0, curr = 0; fmt < fmtEnd; ++fmt) {
+
        int width = 0, skip;
+
        ScanFmtPartDescr *descr = &fmtObj->descr[curr];
+

+
        fmtObj->count++;
+
        descr->width = 0;
+

+
        if (*fmt != '%' || fmt[1] == '%') {
+
            descr->type = 0;
+
            descr->prefix = &buffer[i];
+
            for (; fmt < fmtEnd; ++fmt) {
+
                if (*fmt == '%') {
+
                    if (fmt[1] != '%')
+
                        break;
+
                    ++fmt;
+
                }
+
                buffer[i++] = *fmt;
+
            }
+
            buffer[i++] = 0;
+
        }
+

+
        ++fmt;
+

+
        if (fmt >= fmtEnd)
+
            goto done;
+
        descr->pos = 0;
+
        if (*fmt == '*') {
+
            descr->pos = -1;
+
            ++fmt;
+
        }
+
        else
+
            fmtObj->convCount++;
+

+
        if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
+
            fmt += skip;
+

+
            if (descr->pos != -1 && *fmt == '$') {
+
                int prev;
+

+
                ++fmt;
+
                descr->pos = width;
+
                width = 0;
+

+
                if ((lastPos == 0 && descr->pos > 0)
+
                    || (lastPos > 0 && descr->pos == 0)) {
+
                    fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
+
                    return JIM_ERR;
+
                }
+

+
                for (prev = 0; prev < curr; ++prev) {
+
                    if (fmtObj->descr[prev].pos == -1)
+
                        continue;
+
                    if (fmtObj->descr[prev].pos == descr->pos) {
+
                        fmtObj->error =
+
                            "variable is assigned by multiple \"%n$\" conversion specifiers";
+
                        return JIM_ERR;
+
                    }
+
                }
+

+
                if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
+
                    descr->width = width;
+
                    fmt += skip;
+
                }
+
                if (descr->pos > 0 && (size_t) descr->pos > fmtObj->maxPos)
+
                    fmtObj->maxPos = descr->pos;
+
            }
+
            else {
+

+
                descr->width = width;
+
            }
+
        }
+

+
        if (lastPos == -1)
+
            lastPos = descr->pos;
+

+
        if (*fmt == '[') {
+
            int swapped = 1, beg = i, end, j;
+

+
            descr->type = '[';
+
            descr->arg = &buffer[i];
+
            ++fmt;
+
            if (*fmt == '^')
+
                buffer[i++] = *fmt++;
+
            if (*fmt == ']')
+
                buffer[i++] = *fmt++;
+
            while (*fmt && *fmt != ']')
+
                buffer[i++] = *fmt++;
+
            if (*fmt != ']') {
+
                fmtObj->error = "unmatched [ in format string";
+
                return JIM_ERR;
+
            }
+
            end = i;
+
            buffer[i++] = 0;
+

+
            while (swapped) {
+
                swapped = 0;
+
                for (j = beg + 1; j < end - 1; ++j) {
+
                    if (buffer[j] == '-' && buffer[j - 1] > buffer[j + 1]) {
+
                        char tmp = buffer[j - 1];
+

+
                        buffer[j - 1] = buffer[j + 1];
+
                        buffer[j + 1] = tmp;
+
                        swapped = 1;
+
                    }
+
                }
+
            }
+
        }
+
        else {
+

+
            if (strchr("hlL", *fmt) != 0)
+
                descr->modifier = tolower((int)*fmt++);
+

+
            descr->type = *fmt;
+
            if (strchr("efgcsndoxui", *fmt) == 0) {
+
                fmtObj->error = "bad scan conversion character";
+
                return JIM_ERR;
+
            }
+
            else if (*fmt == 'c' && descr->width != 0) {
+
                fmtObj->error = "field width may not be specified in %c " "conversion";
+
                return JIM_ERR;
+
            }
+
            else if (*fmt == 'u' && descr->modifier == 'l') {
+
                fmtObj->error = "unsigned wide not supported";
+
                return JIM_ERR;
+
            }
+
        }
+
        curr++;
+
    }
+
  done:
+
    return JIM_OK;
+
}
+

+

+

+
#define FormatGetCnvCount(_fo_) \
+
    ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
+
#define FormatGetMaxPos(_fo_) \
+
    ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
+
#define FormatGetError(_fo_) \
+
    ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
+

+
static Jim_Obj *JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
+
{
+
    char *buffer = Jim_StrDup(str);
+
    char *p = buffer;
+

+
    while (*str) {
+
        int c;
+
        int n;
+

+
        if (!sdescr && isspace(UCHAR(*str)))
+
            break;
+

+
        n = utf8_tounicode(str, &c);
+
        if (sdescr && !JimCharsetMatch(sdescr, c, JIM_CHARSET_SCAN))
+
            break;
+
        while (n--)
+
            *p++ = *str++;
+
    }
+
    *p = 0;
+
    return Jim_NewStringObjNoAlloc(interp, buffer, p - buffer);
+
}
+

+

+
static int ScanOneEntry(Jim_Interp *interp, const char *str, int pos, int strLen,
+
    ScanFmtStringObj * fmtObj, long idx, Jim_Obj **valObjPtr)
+
{
+
    const char *tok;
+
    const ScanFmtPartDescr *descr = &fmtObj->descr[idx];
+
    size_t scanned = 0;
+
    size_t anchor = pos;
+
    int i;
+
    Jim_Obj *tmpObj = NULL;
+

+

+
    *valObjPtr = 0;
+
    if (descr->prefix) {
+
        for (i = 0; pos < strLen && descr->prefix[i]; ++i) {
+

+
            if (isspace(UCHAR(descr->prefix[i])))
+
                while (pos < strLen && isspace(UCHAR(str[pos])))
+
                    ++pos;
+
            else if (descr->prefix[i] != str[pos])
+
                break;
+
            else
+
                ++pos;
+
        }
+
        if (pos >= strLen) {
+
            return -1;
+
        }
+
        else if (descr->prefix[i] != 0)
+
            return 0;
+
    }
+

+
    if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
+
        while (isspace(UCHAR(str[pos])))
+
            ++pos;
+

+
    scanned = pos - anchor;
+

+

+
    if (descr->type == 'n') {
+

+
        *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
+
    }
+
    else if (pos >= strLen) {
+

+
        return -1;
+
    }
+
    else if (descr->type == 'c') {
+
            int c;
+
            scanned += utf8_tounicode(&str[pos], &c);
+
            *valObjPtr = Jim_NewIntObj(interp, c);
+
            return scanned;
+
    }
+
    else {
+

+
        if (descr->width > 0) {
+
            size_t sLen = utf8_strlen(&str[pos], strLen - pos);
+
            size_t tLen = descr->width > sLen ? sLen : descr->width;
+

+
            tmpObj = Jim_NewStringObjUtf8(interp, str + pos, tLen);
+
            tok = tmpObj->bytes;
+
        }
+
        else {
+

+
            tok = &str[pos];
+
        }
+
        switch (descr->type) {
+
            case 'd':
+
            case 'o':
+
            case 'x':
+
            case 'u':
+
            case 'i':{
+
                    char *endp;
+
                    jim_wide w;
+

+
                    int base = descr->type == 'o' ? 8
+
                        : descr->type == 'x' ? 16 : descr->type == 'i' ? 0 : 10;
+

+

+
                    if (base == 0) {
+
                        w = jim_strtoull(tok, &endp);
+
                    }
+
                    else {
+
                        w = strtoull(tok, &endp, base);
+
                    }
+

+
                    if (endp != tok) {
+

+
                        *valObjPtr = Jim_NewIntObj(interp, w);
+

+

+
                        scanned += endp - tok;
+
                    }
+
                    else {
+
                        scanned = *tok ? 0 : -1;
+
                    }
+
                    break;
+
                }
+
            case 's':
+
            case '[':{
+
                    *valObjPtr = JimScanAString(interp, descr->arg, tok);
+
                    scanned += Jim_Length(*valObjPtr);
+
                    break;
+
                }
+
            case 'e':
+
            case 'f':
+
            case 'g':{
+
                    char *endp;
+
                    double value = strtod(tok, &endp);
+

+
                    if (endp != tok) {
+

+
                        *valObjPtr = Jim_NewDoubleObj(interp, value);
+

+
                        scanned += endp - tok;
+
                    }
+
                    else {
+
                        scanned = *tok ? 0 : -1;
+
                    }
+
                    break;
+
                }
+
        }
+
        if (tmpObj) {
+
            Jim_FreeNewObj(interp, tmpObj);
+
        }
+
    }
+
    return scanned;
+
}
+

+

+
Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *fmtObjPtr, int flags)
+
{
+
    size_t i, pos;
+
    int scanned = 1;
+
    const char *str = Jim_String(strObjPtr);
+
    int strLen = Jim_Utf8Length(interp, strObjPtr);
+
    Jim_Obj *resultList = 0;
+
    Jim_Obj **resultVec = 0;
+
    int resultc;
+
    Jim_Obj *emptyStr = 0;
+
    ScanFmtStringObj *fmtObj;
+

+

+
    JimPanic((fmtObjPtr->typePtr != &scanFmtStringObjType, "Jim_ScanString() for non-scan format"));
+

+
    fmtObj = (ScanFmtStringObj *) fmtObjPtr->internalRep.ptr;
+

+
    if (fmtObj->error != 0) {
+
        if (flags & JIM_ERRMSG)
+
            Jim_SetResultString(interp, fmtObj->error, -1);
+
        return 0;
+
    }
+

+
    emptyStr = Jim_NewEmptyStringObj(interp);
+
    Jim_IncrRefCount(emptyStr);
+

+
    resultList = Jim_NewListObj(interp, NULL, 0);
+
    if (fmtObj->maxPos > 0) {
+
        for (i = 0; i < fmtObj->maxPos; ++i)
+
            Jim_ListAppendElement(interp, resultList, emptyStr);
+
        JimListGetElements(interp, resultList, &resultc, &resultVec);
+
    }
+

+
    for (i = 0, pos = 0; i < fmtObj->count; ++i) {
+
        ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
+
        Jim_Obj *value = 0;
+

+

+
        if (descr->type == 0)
+
            continue;
+

+
        if (scanned > 0)
+
            scanned = ScanOneEntry(interp, str, pos, strLen, fmtObj, i, &value);
+

+
        if (scanned == -1 && i == 0)
+
            goto eof;
+

+
        pos += scanned;
+

+

+
        if (value == 0)
+
            value = Jim_NewEmptyStringObj(interp);
+

+
        if (descr->pos == -1) {
+
            Jim_FreeNewObj(interp, value);
+
        }
+
        else if (descr->pos == 0)
+

+
            Jim_ListAppendElement(interp, resultList, value);
+
        else if (resultVec[descr->pos - 1] == emptyStr) {
+

+
            Jim_DecrRefCount(interp, resultVec[descr->pos - 1]);
+
            Jim_IncrRefCount(value);
+
            resultVec[descr->pos - 1] = value;
+
        }
+
        else {
+

+
            Jim_FreeNewObj(interp, value);
+
            goto err;
+
        }
+
    }
+
    Jim_DecrRefCount(interp, emptyStr);
+
    return resultList;
+
  eof:
+
    Jim_DecrRefCount(interp, emptyStr);
+
    Jim_FreeNewObj(interp, resultList);
+
    return (Jim_Obj *)EOF;
+
  err:
+
    Jim_DecrRefCount(interp, emptyStr);
+
    Jim_FreeNewObj(interp, resultList);
+
    return 0;
+
}
+

+

+
static void JimPrngInit(Jim_Interp *interp)
+
{
+
#define PRNG_SEED_SIZE 256
+
    int i;
+
    unsigned int *seed;
+
    time_t t = time(NULL);
+

+
    interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
+

+
    seed = Jim_Alloc(PRNG_SEED_SIZE * sizeof(*seed));
+
    for (i = 0; i < PRNG_SEED_SIZE; i++) {
+
        seed[i] = (rand() ^ t ^ clock());
+
    }
+
    JimPrngSeed(interp, (unsigned char *)seed, PRNG_SEED_SIZE * sizeof(*seed));
+
    Jim_Free(seed);
+
}
+

+

+
static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
+
{
+
    Jim_PrngState *prng;
+
    unsigned char *destByte = (unsigned char *)dest;
+
    unsigned int si, sj, x;
+

+

+
    if (interp->prngState == NULL)
+
        JimPrngInit(interp);
+
    prng = interp->prngState;
+

+
    for (x = 0; x < len; x++) {
+
        prng->i = (prng->i + 1) & 0xff;
+
        si = prng->sbox[prng->i];
+
        prng->j = (prng->j + si) & 0xff;
+
        sj = prng->sbox[prng->j];
+
        prng->sbox[prng->i] = sj;
+
        prng->sbox[prng->j] = si;
+
        *destByte++ = prng->sbox[(si + sj) & 0xff];
+
    }
+
}
+

+

+
static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen)
+
{
+
    int i;
+
    Jim_PrngState *prng;
+

+

+
    if (interp->prngState == NULL)
+
        JimPrngInit(interp);
+
    prng = interp->prngState;
+

+

+
    for (i = 0; i < 256; i++)
+
        prng->sbox[i] = i;
+

+
    for (i = 0; i < seedLen; i++) {
+
        unsigned char t;
+

+
        t = prng->sbox[i & 0xFF];
+
        prng->sbox[i & 0xFF] = prng->sbox[seed[i]];
+
        prng->sbox[seed[i]] = t;
+
    }
+
    prng->i = prng->j = 0;
+

+
    for (i = 0; i < 256; i += seedLen) {
+
        JimRandomBytes(interp, seed, seedLen);
+
    }
+
}
+

+

+
static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    jim_wide wideValue, increment = 1;
+
    Jim_Obj *intObjPtr;
+

+
    if (argc != 2 && argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
+
        return JIM_ERR;
+
    }
+
    if (argc == 3) {
+
        if (Jim_GetWide(interp, argv[2], &increment) != JIM_OK)
+
            return JIM_ERR;
+
    }
+
    intObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
+
    if (!intObjPtr) {
+

+
        wideValue = 0;
+
    }
+
    else if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    if (!intObjPtr || Jim_IsShared(intObjPtr)) {
+
        intObjPtr = Jim_NewIntObj(interp, wideValue + increment);
+
        if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
+
            Jim_FreeNewObj(interp, intObjPtr);
+
            return JIM_ERR;
+
        }
+
    }
+
    else {
+

+
        Jim_InvalidateStringRep(intObjPtr);
+
        JimWideValue(intObjPtr) = wideValue + increment;
+

+
        if (argv[1]->typePtr != &variableObjType) {
+

+
            Jim_SetVariable(interp, argv[1], intObjPtr);
+
        }
+
    }
+
    Jim_SetResult(interp, intObjPtr);
+
    return JIM_OK;
+
}
+

+

+
#define JIM_EVAL_SARGV_LEN 8
+
#define JIM_EVAL_SINTV_LEN 8
+

+

+
static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int retcode;
+

+
    if (interp->unknown_called > 50) {
+
        return JIM_ERR;
+
    }
+

+

+

+
    if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
+
        return JIM_ERR;
+

+
    interp->unknown_called++;
+

+
    retcode = Jim_EvalObjPrefix(interp, interp->unknown, argc, argv);
+
    interp->unknown_called--;
+

+
    return retcode;
+
}
+

+
static int JimInvokeCommand(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+
{
+
    int retcode;
+
    Jim_Cmd *cmdPtr;
+

+
#if 0
+
    printf("invoke");
+
    int j;
+
    for (j = 0; j < objc; j++) {
+
        printf(" '%s'", Jim_String(objv[j]));
+
    }
+
    printf("\n");
+
#endif
+

+
    if (interp->framePtr->tailcallCmd) {
+

+
        cmdPtr = interp->framePtr->tailcallCmd;
+
        interp->framePtr->tailcallCmd = NULL;
+
    }
+
    else {
+
        cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
+
        if (cmdPtr == NULL) {
+
            return JimUnknown(interp, objc, objv);
+
        }
+
        JimIncrCmdRefCount(cmdPtr);
+
    }
+

+
    if (interp->evalDepth == interp->maxEvalDepth) {
+
        Jim_SetResultString(interp, "Infinite eval recursion", -1);
+
        retcode = JIM_ERR;
+
        goto out;
+
    }
+
    interp->evalDepth++;
+

+

+
    Jim_SetEmptyResult(interp);
+
    if (cmdPtr->isproc) {
+
        retcode = JimCallProcedure(interp, cmdPtr, objc, objv);
+
    }
+
    else {
+
        interp->cmdPrivData = cmdPtr->u.native.privData;
+
        retcode = cmdPtr->u.native.cmdProc(interp, objc, objv);
+
    }
+
    interp->evalDepth--;
+

+
out:
+
    JimDecrCmdRefCount(interp, cmdPtr);
+

+
    return retcode;
+
}
+

+
int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+
{
+
    int i, retcode;
+

+

+
    for (i = 0; i < objc; i++)
+
        Jim_IncrRefCount(objv[i]);
+

+
    retcode = JimInvokeCommand(interp, objc, objv);
+

+

+
    for (i = 0; i < objc; i++)
+
        Jim_DecrRefCount(interp, objv[i]);
+

+
    return retcode;
+
}
+

+
int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix, int objc, Jim_Obj *const *objv)
+
{
+
    int ret;
+
    Jim_Obj **nargv = Jim_Alloc((objc + 1) * sizeof(*nargv));
+

+
    nargv[0] = prefix;
+
    memcpy(&nargv[1], &objv[0], sizeof(nargv[0]) * objc);
+
    ret = Jim_EvalObjVector(interp, objc + 1, nargv);
+
    Jim_Free(nargv);
+
    return ret;
+
}
+

+
static void JimAddErrorToStack(Jim_Interp *interp, ScriptObj *script)
+
{
+
    if (!interp->errorFlag) {
+

+
        interp->errorFlag = 1;
+
        Jim_IncrRefCount(script->fileNameObj);
+
        Jim_DecrRefCount(interp, interp->errorFileNameObj);
+
        interp->errorFileNameObj = script->fileNameObj;
+
        interp->errorLine = script->linenr;
+

+
        JimResetStackTrace(interp);
+

+
        interp->addStackTrace++;
+
    }
+

+

+
    if (interp->addStackTrace > 0) {
+

+

+
        JimAppendStackTrace(interp, Jim_String(interp->errorProc), script->fileNameObj, script->linenr);
+

+
        if (Jim_Length(script->fileNameObj)) {
+
            interp->addStackTrace = 0;
+
        }
+

+
        Jim_DecrRefCount(interp, interp->errorProc);
+
        interp->errorProc = interp->emptyObj;
+
        Jim_IncrRefCount(interp->errorProc);
+
    }
+
}
+

+
static int JimSubstOneToken(Jim_Interp *interp, const ScriptToken *token, Jim_Obj **objPtrPtr)
+
{
+
    Jim_Obj *objPtr;
+

+
    switch (token->type) {
+
        case JIM_TT_STR:
+
        case JIM_TT_ESC:
+
            objPtr = token->objPtr;
+
            break;
+
        case JIM_TT_VAR:
+
            objPtr = Jim_GetVariable(interp, token->objPtr, JIM_ERRMSG);
+
            break;
+
        case JIM_TT_DICTSUGAR:
+
            objPtr = JimExpandDictSugar(interp, token->objPtr);
+
            break;
+
        case JIM_TT_EXPRSUGAR:
+
            objPtr = JimExpandExprSugar(interp, token->objPtr);
+
            break;
+
        case JIM_TT_CMD:
+
            switch (Jim_EvalObj(interp, token->objPtr)) {
+
                case JIM_OK:
+
                case JIM_RETURN:
+
                    objPtr = interp->result;
+
                    break;
+
                case JIM_BREAK:
+

+
                    return JIM_BREAK;
+
                case JIM_CONTINUE:
+

+
                    return JIM_CONTINUE;
+
                default:
+
                    return JIM_ERR;
+
            }
+
            break;
+
        default:
+
            JimPanic((1,
+
                "default token type (%d) reached " "in Jim_SubstObj().", token->type));
+
            objPtr = NULL;
+
            break;
+
    }
+
    if (objPtr) {
+
        *objPtrPtr = objPtr;
+
        return JIM_OK;
+
    }
+
    return JIM_ERR;
+
}
+

+
static Jim_Obj *JimInterpolateTokens(Jim_Interp *interp, const ScriptToken * token, int tokens, int flags)
+
{
+
    int totlen = 0, i;
+
    Jim_Obj **intv;
+
    Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
+
    Jim_Obj *objPtr;
+
    char *s;
+

+
    if (tokens <= JIM_EVAL_SINTV_LEN)
+
        intv = sintv;
+
    else
+
        intv = Jim_Alloc(sizeof(Jim_Obj *) * tokens);
+

+
    for (i = 0; i < tokens; i++) {
+
        switch (JimSubstOneToken(interp, &token[i], &intv[i])) {
+
            case JIM_OK:
+
            case JIM_RETURN:
+
                break;
+
            case JIM_BREAK:
+
                if (flags & JIM_SUBST_FLAG) {
+

+
                    tokens = i;
+
                    continue;
+
                }
+

+

+
            case JIM_CONTINUE:
+
                if (flags & JIM_SUBST_FLAG) {
+
                    intv[i] = NULL;
+
                    continue;
+
                }
+

+

+
            default:
+
                while (i--) {
+
                    Jim_DecrRefCount(interp, intv[i]);
+
                }
+
                if (intv != sintv) {
+
                    Jim_Free(intv);
+
                }
+
                return NULL;
+
        }
+
        Jim_IncrRefCount(intv[i]);
+
        Jim_String(intv[i]);
+
        totlen += intv[i]->length;
+
    }
+

+

+
    if (tokens == 1 && intv[0] && intv == sintv) {
+
        Jim_DecrRefCount(interp, intv[0]);
+
        return intv[0];
+
    }
+

+
    objPtr = Jim_NewStringObjNoAlloc(interp, NULL, 0);
+

+
    if (tokens == 4 && token[0].type == JIM_TT_ESC && token[1].type == JIM_TT_ESC
+
        && token[2].type == JIM_TT_VAR) {
+

+
        objPtr->typePtr = &interpolatedObjType;
+
        objPtr->internalRep.dictSubstValue.varNameObjPtr = token[0].objPtr;
+
        objPtr->internalRep.dictSubstValue.indexObjPtr = intv[2];
+
        Jim_IncrRefCount(intv[2]);
+
    }
+
    else if (tokens && intv[0] && intv[0]->typePtr == &sourceObjType) {
+

+
        JimSetSourceInfo(interp, objPtr, intv[0]->internalRep.sourceValue.fileNameObj, intv[0]->internalRep.sourceValue.lineNumber);
+
    }
+

+

+
    s = objPtr->bytes = Jim_Alloc(totlen + 1);
+
    objPtr->length = totlen;
+
    for (i = 0; i < tokens; i++) {
+
        if (intv[i]) {
+
            memcpy(s, intv[i]->bytes, intv[i]->length);
+
            s += intv[i]->length;
+
            Jim_DecrRefCount(interp, intv[i]);
+
        }
+
    }
+
    objPtr->bytes[totlen] = '\0';
+

+
    if (intv != sintv) {
+
        Jim_Free(intv);
+
    }
+

+
    return objPtr;
+
}
+

+

+
static int JimEvalObjList(Jim_Interp *interp, Jim_Obj *listPtr)
+
{
+
    int retcode = JIM_OK;
+

+
    JimPanic((Jim_IsList(listPtr) == 0, "JimEvalObjList() invoked on non-list."));
+

+
    if (listPtr->internalRep.listValue.len) {
+
        Jim_IncrRefCount(listPtr);
+
        retcode = JimInvokeCommand(interp,
+
            listPtr->internalRep.listValue.len,
+
            listPtr->internalRep.listValue.ele);
+
        Jim_DecrRefCount(interp, listPtr);
+
    }
+
    return retcode;
+
}
+

+
int Jim_EvalObjList(Jim_Interp *interp, Jim_Obj *listPtr)
+
{
+
    SetListFromAny(interp, listPtr);
+
    return JimEvalObjList(interp, listPtr);
+
}
+

+
int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
+
{
+
    int i;
+
    ScriptObj *script;
+
    ScriptToken *token;
+
    int retcode = JIM_OK;
+
    Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL;
+
    Jim_Obj *prevScriptObj;
+

+
    if (Jim_IsList(scriptObjPtr) && scriptObjPtr->bytes == NULL) {
+
        return JimEvalObjList(interp, scriptObjPtr);
+
    }
+

+
    Jim_IncrRefCount(scriptObjPtr);
+
    script = JimGetScript(interp, scriptObjPtr);
+
    if (!JimScriptValid(interp, script)) {
+
        Jim_DecrRefCount(interp, scriptObjPtr);
+
        return JIM_ERR;
+
    }
+

+
    Jim_SetEmptyResult(interp);
+

+
    token = script->token;
+

+
#ifdef JIM_OPTIMIZATION
+
    if (script->len == 0) {
+
        Jim_DecrRefCount(interp, scriptObjPtr);
+
        return JIM_OK;
+
    }
+
    if (script->len == 3
+
        && token[1].objPtr->typePtr == &commandObjType
+
        && token[1].objPtr->internalRep.cmdValue.cmdPtr->isproc == 0
+
        && token[1].objPtr->internalRep.cmdValue.cmdPtr->u.native.cmdProc == Jim_IncrCoreCommand
+
        && token[2].objPtr->typePtr == &variableObjType) {
+

+
        Jim_Obj *objPtr = Jim_GetVariable(interp, token[2].objPtr, JIM_NONE);
+

+
        if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
+
            JimWideValue(objPtr)++;
+
            Jim_InvalidateStringRep(objPtr);
+
            Jim_DecrRefCount(interp, scriptObjPtr);
+
            Jim_SetResult(interp, objPtr);
+
            return JIM_OK;
+
        }
+
    }
+
#endif
+

+
    script->inUse++;
+

+

+
    prevScriptObj = interp->currentScriptObj;
+
    interp->currentScriptObj = scriptObjPtr;
+

+
    interp->errorFlag = 0;
+
    argv = sargv;
+

+
    for (i = 0; i < script->len && retcode == JIM_OK; ) {
+
        int argc;
+
        int j;
+

+

+
        argc = token[i].objPtr->internalRep.scriptLineValue.argc;
+
        script->linenr = token[i].objPtr->internalRep.scriptLineValue.line;
+

+

+
        if (argc > JIM_EVAL_SARGV_LEN)
+
            argv = Jim_Alloc(sizeof(Jim_Obj *) * argc);
+

+

+
        i++;
+

+
        for (j = 0; j < argc; j++) {
+
            long wordtokens = 1;
+
            int expand = 0;
+
            Jim_Obj *wordObjPtr = NULL;
+

+
            if (token[i].type == JIM_TT_WORD) {
+
                wordtokens = JimWideValue(token[i++].objPtr);
+
                if (wordtokens < 0) {
+
                    expand = 1;
+
                    wordtokens = -wordtokens;
+
                }
+
            }
+

+
            if (wordtokens == 1) {
+

+
                switch (token[i].type) {
+
                    case JIM_TT_ESC:
+
                    case JIM_TT_STR:
+
                        wordObjPtr = token[i].objPtr;
+
                        break;
+
                    case JIM_TT_VAR:
+
                        wordObjPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
+
                        break;
+
                    case JIM_TT_EXPRSUGAR:
+
                        wordObjPtr = JimExpandExprSugar(interp, token[i].objPtr);
+
                        break;
+
                    case JIM_TT_DICTSUGAR:
+
                        wordObjPtr = JimExpandDictSugar(interp, token[i].objPtr);
+
                        break;
+
                    case JIM_TT_CMD:
+
                        retcode = Jim_EvalObj(interp, token[i].objPtr);
+
                        if (retcode == JIM_OK) {
+
                            wordObjPtr = Jim_GetResult(interp);
+
                        }
+
                        break;
+
                    default:
+
                        JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
+
                }
+
            }
+
            else {
+
                wordObjPtr = JimInterpolateTokens(interp, token + i, wordtokens, JIM_NONE);
+
            }
+

+
            if (!wordObjPtr) {
+
                if (retcode == JIM_OK) {
+
                    retcode = JIM_ERR;
+
                }
+
                break;
+
            }
+

+
            Jim_IncrRefCount(wordObjPtr);
+
            i += wordtokens;
+

+
            if (!expand) {
+
                argv[j] = wordObjPtr;
+
            }
+
            else {
+

+
                int len = Jim_ListLength(interp, wordObjPtr);
+
                int newargc = argc + len - 1;
+
                int k;
+

+
                if (len > 1) {
+
                    if (argv == sargv) {
+
                        if (newargc > JIM_EVAL_SARGV_LEN) {
+
                            argv = Jim_Alloc(sizeof(*argv) * newargc);
+
                            memcpy(argv, sargv, sizeof(*argv) * j);
+
                        }
+
                    }
+
                    else {
+

+
                        argv = Jim_Realloc(argv, sizeof(*argv) * newargc);
+
                    }
+
                }
+

+

+
                for (k = 0; k < len; k++) {
+
                    argv[j++] = wordObjPtr->internalRep.listValue.ele[k];
+
                    Jim_IncrRefCount(wordObjPtr->internalRep.listValue.ele[k]);
+
                }
+

+
                Jim_DecrRefCount(interp, wordObjPtr);
+

+

+
                j--;
+
                argc += len - 1;
+
            }
+
        }
+

+
        if (retcode == JIM_OK && argc) {
+

+
            retcode = JimInvokeCommand(interp, argc, argv);
+

+
            if (Jim_CheckSignal(interp)) {
+
                retcode = JIM_SIGNAL;
+
            }
+
        }
+

+

+
        while (j-- > 0) {
+
            Jim_DecrRefCount(interp, argv[j]);
+
        }
+

+
        if (argv != sargv) {
+
            Jim_Free(argv);
+
            argv = sargv;
+
        }
+
    }
+

+

+
    if (retcode == JIM_ERR) {
+
        JimAddErrorToStack(interp, script);
+
    }
+

+
    else if (retcode != JIM_RETURN || interp->returnCode != JIM_ERR) {
+

+
        interp->addStackTrace = 0;
+
    }
+

+

+
    interp->currentScriptObj = prevScriptObj;
+

+
    Jim_FreeIntRep(interp, scriptObjPtr);
+
    scriptObjPtr->typePtr = &scriptObjType;
+
    Jim_SetIntRepPtr(scriptObjPtr, script);
+
    Jim_DecrRefCount(interp, scriptObjPtr);
+

+
    return retcode;
+
}
+

+
static int JimSetProcArg(Jim_Interp *interp, Jim_Obj *argNameObj, Jim_Obj *argValObj)
+
{
+
    int retcode;
+

+
    const char *varname = Jim_String(argNameObj);
+
    if (*varname == '&') {
+

+
        Jim_Obj *objPtr;
+
        Jim_CallFrame *savedCallFrame = interp->framePtr;
+

+
        interp->framePtr = interp->framePtr->parent;
+
        objPtr = Jim_GetVariable(interp, argValObj, JIM_ERRMSG);
+
        interp->framePtr = savedCallFrame;
+
        if (!objPtr) {
+
            return JIM_ERR;
+
        }
+

+

+
        objPtr = Jim_NewStringObj(interp, varname + 1, -1);
+
        Jim_IncrRefCount(objPtr);
+
        retcode = Jim_SetVariableLink(interp, objPtr, argValObj, interp->framePtr->parent);
+
        Jim_DecrRefCount(interp, objPtr);
+
    }
+
    else {
+
        retcode = Jim_SetVariable(interp, argNameObj, argValObj);
+
    }
+
    return retcode;
+
}
+

+
static void JimSetProcWrongArgs(Jim_Interp *interp, Jim_Obj *procNameObj, Jim_Cmd *cmd)
+
{
+

+
    Jim_Obj *argmsg = Jim_NewStringObj(interp, "", 0);
+
    int i;
+

+
    for (i = 0; i < cmd->u.proc.argListLen; i++) {
+
        Jim_AppendString(interp, argmsg, " ", 1);
+

+
        if (i == cmd->u.proc.argsPos) {
+
            if (cmd->u.proc.arglist[i].defaultObjPtr) {
+

+
                Jim_AppendString(interp, argmsg, "?", 1);
+
                Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].defaultObjPtr);
+
                Jim_AppendString(interp, argmsg, " ...?", -1);
+
            }
+
            else {
+

+
                Jim_AppendString(interp, argmsg, "?arg...?", -1);
+
            }
+
        }
+
        else {
+
            if (cmd->u.proc.arglist[i].defaultObjPtr) {
+
                Jim_AppendString(interp, argmsg, "?", 1);
+
                Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
+
                Jim_AppendString(interp, argmsg, "?", 1);
+
            }
+
            else {
+
                const char *arg = Jim_String(cmd->u.proc.arglist[i].nameObjPtr);
+
                if (*arg == '&') {
+
                    arg++;
+
                }
+
                Jim_AppendString(interp, argmsg, arg, -1);
+
            }
+
        }
+
    }
+
    Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s%#s\"", procNameObj, argmsg);
+
}
+

+
#ifdef jim_ext_namespace
+
int Jim_EvalNamespace(Jim_Interp *interp, Jim_Obj *scriptObj, Jim_Obj *nsObj)
+
{
+
    Jim_CallFrame *callFramePtr;
+
    int retcode;
+

+

+
    callFramePtr = JimCreateCallFrame(interp, interp->framePtr, nsObj);
+
    callFramePtr->argv = &interp->emptyObj;
+
    callFramePtr->argc = 0;
+
    callFramePtr->procArgsObjPtr = NULL;
+
    callFramePtr->procBodyObjPtr = scriptObj;
+
    callFramePtr->staticVars = NULL;
+
    callFramePtr->fileNameObj = interp->emptyObj;
+
    callFramePtr->line = 0;
+
    Jim_IncrRefCount(scriptObj);
+
    interp->framePtr = callFramePtr;
+

+

+
    if (interp->framePtr->level == interp->maxCallFrameDepth) {
+
        Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
+
        retcode = JIM_ERR;
+
    }
+
    else {
+

+
        retcode = Jim_EvalObj(interp, scriptObj);
+
    }
+

+

+
    interp->framePtr = interp->framePtr->parent;
+
    JimFreeCallFrame(interp, callFramePtr, JIM_FCF_REUSE);
+

+
    return retcode;
+
}
+
#endif
+

+
static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_CallFrame *callFramePtr;
+
    int i, d, retcode, optargs;
+
    ScriptObj *script;
+

+

+
    if (argc - 1 < cmd->u.proc.reqArity ||
+
        (cmd->u.proc.argsPos < 0 && argc - 1 > cmd->u.proc.reqArity + cmd->u.proc.optArity)) {
+
        JimSetProcWrongArgs(interp, argv[0], cmd);
+
        return JIM_ERR;
+
    }
+

+
    if (Jim_Length(cmd->u.proc.bodyObjPtr) == 0) {
+

+
        return JIM_OK;
+
    }
+

+

+
    if (interp->framePtr->level == interp->maxCallFrameDepth) {
+
        Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
+
        return JIM_ERR;
+
    }
+

+

+
    callFramePtr = JimCreateCallFrame(interp, interp->framePtr, cmd->u.proc.nsObj);
+
    callFramePtr->argv = argv;
+
    callFramePtr->argc = argc;
+
    callFramePtr->procArgsObjPtr = cmd->u.proc.argListObjPtr;
+
    callFramePtr->procBodyObjPtr = cmd->u.proc.bodyObjPtr;
+
    callFramePtr->staticVars = cmd->u.proc.staticVars;
+

+

+
    script = JimGetScript(interp, interp->currentScriptObj);
+
    callFramePtr->fileNameObj = script->fileNameObj;
+
    callFramePtr->line = script->linenr;
+

+
    Jim_IncrRefCount(cmd->u.proc.argListObjPtr);
+
    Jim_IncrRefCount(cmd->u.proc.bodyObjPtr);
+
    interp->framePtr = callFramePtr;
+

+

+
    optargs = (argc - 1 - cmd->u.proc.reqArity);
+

+

+
    i = 1;
+
    for (d = 0; d < cmd->u.proc.argListLen; d++) {
+
        Jim_Obj *nameObjPtr = cmd->u.proc.arglist[d].nameObjPtr;
+
        if (d == cmd->u.proc.argsPos) {
+

+
            Jim_Obj *listObjPtr;
+
            int argsLen = 0;
+
            if (cmd->u.proc.reqArity + cmd->u.proc.optArity < argc - 1) {
+
                argsLen = argc - 1 - (cmd->u.proc.reqArity + cmd->u.proc.optArity);
+
            }
+
            listObjPtr = Jim_NewListObj(interp, &argv[i], argsLen);
+

+

+
            if (cmd->u.proc.arglist[d].defaultObjPtr) {
+
                nameObjPtr =cmd->u.proc.arglist[d].defaultObjPtr;
+
            }
+
            retcode = Jim_SetVariable(interp, nameObjPtr, listObjPtr);
+
            if (retcode != JIM_OK) {
+
                goto badargset;
+
            }
+

+
            i += argsLen;
+
            continue;
+
        }
+

+

+
        if (cmd->u.proc.arglist[d].defaultObjPtr == NULL || optargs-- > 0) {
+
            retcode = JimSetProcArg(interp, nameObjPtr, argv[i++]);
+
        }
+
        else {
+

+
            retcode = Jim_SetVariable(interp, nameObjPtr, cmd->u.proc.arglist[d].defaultObjPtr);
+
        }
+
        if (retcode != JIM_OK) {
+
            goto badargset;
+
        }
+
    }
+

+

+
    retcode = Jim_EvalObj(interp, cmd->u.proc.bodyObjPtr);
+

+
badargset:
+

+

+
    interp->framePtr = interp->framePtr->parent;
+
    JimFreeCallFrame(interp, callFramePtr, JIM_FCF_REUSE);
+

+

+
    if (interp->framePtr->tailcallObj) {
+
        do {
+
            Jim_Obj *tailcallObj = interp->framePtr->tailcallObj;
+

+
            interp->framePtr->tailcallObj = NULL;
+

+
            if (retcode == JIM_EVAL) {
+
                retcode = Jim_EvalObjList(interp, tailcallObj);
+
                if (retcode == JIM_RETURN) {
+
                    interp->returnLevel++;
+
                }
+
            }
+
            Jim_DecrRefCount(interp, tailcallObj);
+
        } while (interp->framePtr->tailcallObj);
+

+

+
        if (interp->framePtr->tailcallCmd) {
+
            JimDecrCmdRefCount(interp, interp->framePtr->tailcallCmd);
+
            interp->framePtr->tailcallCmd = NULL;
+
        }
+
    }
+

+

+
    if (retcode == JIM_RETURN) {
+
        if (--interp->returnLevel <= 0) {
+
            retcode = interp->returnCode;
+
            interp->returnCode = JIM_OK;
+
            interp->returnLevel = 0;
+
        }
+
    }
+
    else if (retcode == JIM_ERR) {
+
        interp->addStackTrace++;
+
        Jim_DecrRefCount(interp, interp->errorProc);
+
        interp->errorProc = argv[0];
+
        Jim_IncrRefCount(interp->errorProc);
+
    }
+

+
    return retcode;
+
}
+

+
int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script)
+
{
+
    int retval;
+
    Jim_Obj *scriptObjPtr;
+

+
    scriptObjPtr = Jim_NewStringObj(interp, script, -1);
+
    Jim_IncrRefCount(scriptObjPtr);
+

+
    if (filename) {
+
        Jim_Obj *prevScriptObj;
+

+
        JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), lineno);
+

+
        prevScriptObj = interp->currentScriptObj;
+
        interp->currentScriptObj = scriptObjPtr;
+

+
        retval = Jim_EvalObj(interp, scriptObjPtr);
+

+
        interp->currentScriptObj = prevScriptObj;
+
    }
+
    else {
+
        retval = Jim_EvalObj(interp, scriptObjPtr);
+
    }
+
    Jim_DecrRefCount(interp, scriptObjPtr);
+
    return retval;
+
}
+

+
int Jim_Eval(Jim_Interp *interp, const char *script)
+
{
+
    return Jim_EvalObj(interp, Jim_NewStringObj(interp, script, -1));
+
}
+

+

+
int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
+
{
+
    int retval;
+
    Jim_CallFrame *savedFramePtr = interp->framePtr;
+

+
    interp->framePtr = interp->topFramePtr;
+
    retval = Jim_Eval(interp, script);
+
    interp->framePtr = savedFramePtr;
+

+
    return retval;
+
}
+

+
int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename)
+
{
+
    int retval;
+
    Jim_CallFrame *savedFramePtr = interp->framePtr;
+

+
    interp->framePtr = interp->topFramePtr;
+
    retval = Jim_EvalFile(interp, filename);
+
    interp->framePtr = savedFramePtr;
+

+
    return retval;
+
}
+

+
#include <sys/stat.h>
+

+
int Jim_EvalFile(Jim_Interp *interp, const char *filename)
+
{
+
    FILE *fp;
+
    char *buf;
+
    Jim_Obj *scriptObjPtr;
+
    Jim_Obj *prevScriptObj;
+
    struct stat sb;
+
    int retcode;
+
    int readlen;
+

+
    if (stat(filename, &sb) != 0 || (fp = fopen(filename, "rt")) == NULL) {
+
        Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno));
+
        return JIM_ERR;
+
    }
+
    if (sb.st_size == 0) {
+
        fclose(fp);
+
        return JIM_OK;
+
    }
+

+
    buf = Jim_Alloc(sb.st_size + 1);
+
    readlen = fread(buf, 1, sb.st_size, fp);
+
    if (ferror(fp)) {
+
        fclose(fp);
+
        Jim_Free(buf);
+
        Jim_SetResultFormatted(interp, "failed to load file \"%s\": %s", filename, strerror(errno));
+
        return JIM_ERR;
+
    }
+
    fclose(fp);
+
    buf[readlen] = 0;
+

+
    scriptObjPtr = Jim_NewStringObjNoAlloc(interp, buf, readlen);
+
    JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), 1);
+
    Jim_IncrRefCount(scriptObjPtr);
+

+
    prevScriptObj = interp->currentScriptObj;
+
    interp->currentScriptObj = scriptObjPtr;
+

+
    retcode = Jim_EvalObj(interp, scriptObjPtr);
+

+

+
    if (retcode == JIM_RETURN) {
+
        if (--interp->returnLevel <= 0) {
+
            retcode = interp->returnCode;
+
            interp->returnCode = JIM_OK;
+
            interp->returnLevel = 0;
+
        }
+
    }
+
    if (retcode == JIM_ERR) {
+

+
        interp->addStackTrace++;
+
    }
+

+
    interp->currentScriptObj = prevScriptObj;
+

+
    Jim_DecrRefCount(interp, scriptObjPtr);
+

+
    return retcode;
+
}
+

+
static void JimParseSubst(struct JimParserCtx *pc, int flags)
+
{
+
    pc->tstart = pc->p;
+
    pc->tline = pc->linenr;
+

+
    if (pc->len == 0) {
+
        pc->tend = pc->p;
+
        pc->tt = JIM_TT_EOL;
+
        pc->eof = 1;
+
        return;
+
    }
+
    if (*pc->p == '[' && !(flags & JIM_SUBST_NOCMD)) {
+
        JimParseCmd(pc);
+
        return;
+
    }
+
    if (*pc->p == '$' && !(flags & JIM_SUBST_NOVAR)) {
+
        if (JimParseVar(pc) == JIM_OK) {
+
            return;
+
        }
+

+
        pc->tstart = pc->p;
+
        flags |= JIM_SUBST_NOVAR;
+
    }
+
    while (pc->len) {
+
        if (*pc->p == '$' && !(flags & JIM_SUBST_NOVAR)) {
+
            break;
+
        }
+
        if (*pc->p == '[' && !(flags & JIM_SUBST_NOCMD)) {
+
            break;
+
        }
+
        if (*pc->p == '\\' && pc->len > 1) {
+
            pc->p++;
+
            pc->len--;
+
        }
+
        pc->p++;
+
        pc->len--;
+
    }
+
    pc->tend = pc->p - 1;
+
    pc->tt = (flags & JIM_SUBST_NOESC) ? JIM_TT_STR : JIM_TT_ESC;
+
}
+

+

+
static int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
+
{
+
    int scriptTextLen;
+
    const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
+
    struct JimParserCtx parser;
+
    struct ScriptObj *script = Jim_Alloc(sizeof(*script));
+
    ParseTokenList tokenlist;
+

+

+
    ScriptTokenListInit(&tokenlist);
+

+
    JimParserInit(&parser, scriptText, scriptTextLen, 1);
+
    while (1) {
+
        JimParseSubst(&parser, flags);
+
        if (parser.eof) {
+

+
            break;
+
        }
+
        ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
+
            parser.tline);
+
    }
+

+

+
    script->inUse = 1;
+
    script->substFlags = flags;
+
    script->fileNameObj = interp->emptyObj;
+
    Jim_IncrRefCount(script->fileNameObj);
+
    SubstObjAddTokens(interp, script, &tokenlist);
+

+

+
    ScriptTokenListFree(&tokenlist);
+

+
#ifdef DEBUG_SHOW_SUBST
+
    {
+
        int i;
+

+
        printf("==== Subst ====\n");
+
        for (i = 0; i < script->len; i++) {
+
            printf("[%2d] %s '%s'\n", i, jim_tt_name(script->token[i].type),
+
                Jim_String(script->token[i].objPtr));
+
        }
+
    }
+
#endif
+

+

+
    Jim_FreeIntRep(interp, objPtr);
+
    Jim_SetIntRepPtr(objPtr, script);
+
    objPtr->typePtr = &scriptObjType;
+
    return JIM_OK;
+
}
+

+
static ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+
{
+
    if (objPtr->typePtr != &scriptObjType || ((ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags != flags)
+
        SetSubstFromAny(interp, objPtr, flags);
+
    return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
+
}
+

+
int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr, Jim_Obj **resObjPtrPtr, int flags)
+
{
+
    ScriptObj *script = Jim_GetSubst(interp, substObjPtr, flags);
+

+
    Jim_IncrRefCount(substObjPtr);
+
    script->inUse++;
+

+
    *resObjPtrPtr = JimInterpolateTokens(interp, script->token, script->len, flags);
+

+
    script->inUse--;
+
    Jim_DecrRefCount(interp, substObjPtr);
+
    if (*resObjPtrPtr == NULL) {
+
        return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+
void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, const char *msg)
+
{
+
    Jim_Obj *objPtr;
+
    Jim_Obj *listObjPtr;
+

+
    JimPanic((argc == 0, "Jim_WrongNumArgs() called with argc=0"));
+

+
    listObjPtr = Jim_NewListObj(interp, argv, argc);
+

+
    if (*msg) {
+
        Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, msg, -1));
+
    }
+
    Jim_IncrRefCount(listObjPtr);
+
    objPtr = Jim_ListJoin(interp, listObjPtr, " ", 1);
+
    Jim_DecrRefCount(interp, listObjPtr);
+

+
    Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s\"", objPtr);
+
}
+

+
typedef void JimHashtableIteratorCallbackType(Jim_Interp *interp, Jim_Obj *listObjPtr,
+
    Jim_HashEntry *he, int type);
+

+
#define JimTrivialMatch(pattern)    (strpbrk((pattern), "*[?\\") == NULL)
+

+
static Jim_Obj *JimHashtablePatternMatch(Jim_Interp *interp, Jim_HashTable *ht, Jim_Obj *patternObjPtr,
+
    JimHashtableIteratorCallbackType *callback, int type)
+
{
+
    Jim_HashEntry *he;
+
    Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
+

+

+
    if (patternObjPtr && JimTrivialMatch(Jim_String(patternObjPtr))) {
+
        he = Jim_FindHashEntry(ht, Jim_String(patternObjPtr));
+
        if (he) {
+
            callback(interp, listObjPtr, he, type);
+
        }
+
    }
+
    else {
+
        Jim_HashTableIterator htiter;
+
        JimInitHashTableIterator(ht, &htiter);
+
        while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+
            if (patternObjPtr == NULL || JimGlobMatch(Jim_String(patternObjPtr), he->key, 0)) {
+
                callback(interp, listObjPtr, he, type);
+
            }
+
        }
+
    }
+
    return listObjPtr;
+
}
+

+

+
#define JIM_CMDLIST_COMMANDS 0
+
#define JIM_CMDLIST_PROCS 1
+
#define JIM_CMDLIST_CHANNELS 2
+

+
static void JimCommandMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
+
    Jim_HashEntry *he, int type)
+
{
+
    Jim_Cmd *cmdPtr = Jim_GetHashEntryVal(he);
+
    Jim_Obj *objPtr;
+

+
    if (type == JIM_CMDLIST_PROCS && !cmdPtr->isproc) {
+

+
        return;
+
    }
+

+
    objPtr = Jim_NewStringObj(interp, he->key, -1);
+
    Jim_IncrRefCount(objPtr);
+

+
    if (type != JIM_CMDLIST_CHANNELS || Jim_AioFilehandle(interp, objPtr)) {
+
        Jim_ListAppendElement(interp, listObjPtr, objPtr);
+
    }
+
    Jim_DecrRefCount(interp, objPtr);
+
}
+

+

+
static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int type)
+
{
+
    return JimHashtablePatternMatch(interp, &interp->commands, patternObjPtr, JimCommandMatch, type);
+
}
+

+

+
#define JIM_VARLIST_GLOBALS 0
+
#define JIM_VARLIST_LOCALS 1
+
#define JIM_VARLIST_VARS 2
+

+
#define JIM_VARLIST_VALUES 0x1000
+

+
static void JimVariablesMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
+
    Jim_HashEntry *he, int type)
+
{
+
    Jim_Var *varPtr = Jim_GetHashEntryVal(he);
+

+
    if (type != JIM_VARLIST_LOCALS || varPtr->linkFramePtr == NULL) {
+
        Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, he->key, -1));
+
        if (type & JIM_VARLIST_VALUES) {
+
            Jim_ListAppendElement(interp, listObjPtr, varPtr->objPtr);
+
        }
+
    }
+
}
+

+

+
static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int mode)
+
{
+
    if (mode == JIM_VARLIST_LOCALS && interp->framePtr == interp->topFramePtr) {
+
        return interp->emptyObj;
+
    }
+
    else {
+
        Jim_CallFrame *framePtr = (mode == JIM_VARLIST_GLOBALS) ? interp->topFramePtr : interp->framePtr;
+
        return JimHashtablePatternMatch(interp, &framePtr->vars, patternObjPtr, JimVariablesMatch, mode);
+
    }
+
}
+

+
static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,
+
    Jim_Obj **objPtrPtr, int info_level_cmd)
+
{
+
    Jim_CallFrame *targetCallFrame;
+

+
    targetCallFrame = JimGetCallFrameByInteger(interp, levelObjPtr);
+
    if (targetCallFrame == NULL) {
+
        return JIM_ERR;
+
    }
+

+
    if (targetCallFrame == interp->topFramePtr) {
+
        Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
+
        return JIM_ERR;
+
    }
+
    if (info_level_cmd) {
+
        *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, targetCallFrame->argc);
+
    }
+
    else {
+
        Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
+

+
        Jim_ListAppendElement(interp, listObj, targetCallFrame->argv[0]);
+
        Jim_ListAppendElement(interp, listObj, targetCallFrame->fileNameObj);
+
        Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, targetCallFrame->line));
+
        *objPtrPtr = listObj;
+
    }
+
    return JIM_OK;
+
}
+

+

+

+
static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc != 2 && argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "?-nonewline? string");
+
        return JIM_ERR;
+
    }
+
    if (argc == 3) {
+
        if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline")) {
+
            Jim_SetResultString(interp, "The second argument must " "be -nonewline", -1);
+
            return JIM_ERR;
+
        }
+
        else {
+
            fputs(Jim_String(argv[2]), stdout);
+
        }
+
    }
+
    else {
+
        puts(Jim_String(argv[1]));
+
    }
+
    return JIM_OK;
+
}
+

+

+
static int JimAddMulHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
+
{
+
    jim_wide wideValue, res;
+
    double doubleValue, doubleRes;
+
    int i;
+

+
    res = (op == JIM_EXPROP_ADD) ? 0 : 1;
+

+
    for (i = 1; i < argc; i++) {
+
        if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
+
            goto trydouble;
+
        if (op == JIM_EXPROP_ADD)
+
            res += wideValue;
+
        else
+
            res *= wideValue;
+
    }
+
    Jim_SetResultInt(interp, res);
+
    return JIM_OK;
+
  trydouble:
+
    doubleRes = (double)res;
+
    for (; i < argc; i++) {
+
        if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
+
            return JIM_ERR;
+
        if (op == JIM_EXPROP_ADD)
+
            doubleRes += doubleValue;
+
        else
+
            doubleRes *= doubleValue;
+
    }
+
    Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+
    return JIM_OK;
+
}
+

+

+
static int JimSubDivHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
+
{
+
    jim_wide wideValue, res = 0;
+
    double doubleValue, doubleRes = 0;
+
    int i = 2;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
+
        return JIM_ERR;
+
    }
+
    else if (argc == 2) {
+
        if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
+
            if (Jim_GetDouble(interp, argv[1], &doubleValue) != JIM_OK) {
+
                return JIM_ERR;
+
            }
+
            else {
+
                if (op == JIM_EXPROP_SUB)
+
                    doubleRes = -doubleValue;
+
                else
+
                    doubleRes = 1.0 / doubleValue;
+
                Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+
                return JIM_OK;
+
            }
+
        }
+
        if (op == JIM_EXPROP_SUB) {
+
            res = -wideValue;
+
            Jim_SetResultInt(interp, res);
+
        }
+
        else {
+
            doubleRes = 1.0 / wideValue;
+
            Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+
        }
+
        return JIM_OK;
+
    }
+
    else {
+
        if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
+
            if (Jim_GetDouble(interp, argv[1], &doubleRes)
+
                != JIM_OK) {
+
                return JIM_ERR;
+
            }
+
            else {
+
                goto trydouble;
+
            }
+
        }
+
    }
+
    for (i = 2; i < argc; i++) {
+
        if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
+
            doubleRes = (double)res;
+
            goto trydouble;
+
        }
+
        if (op == JIM_EXPROP_SUB)
+
            res -= wideValue;
+
        else
+
            res /= wideValue;
+
    }
+
    Jim_SetResultInt(interp, res);
+
    return JIM_OK;
+
  trydouble:
+
    for (; i < argc; i++) {
+
        if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
+
            return JIM_ERR;
+
        if (op == JIM_EXPROP_SUB)
+
            doubleRes -= doubleValue;
+
        else
+
            doubleRes /= doubleValue;
+
    }
+
    Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+
    return JIM_OK;
+
}
+

+

+

+
static int Jim_AddCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
+
}
+

+

+
static int Jim_MulCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
+
}
+

+

+
static int Jim_SubCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
+
}
+

+

+
static int Jim_DivCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
+
}
+

+

+
static int Jim_SetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc != 2 && argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
+
        return JIM_ERR;
+
    }
+
    if (argc == 2) {
+
        Jim_Obj *objPtr;
+

+
        objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+
        if (!objPtr)
+
            return JIM_ERR;
+
        Jim_SetResult(interp, objPtr);
+
        return JIM_OK;
+
    }
+

+
    if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
+
        return JIM_ERR;
+
    Jim_SetResult(interp, argv[2]);
+
    return JIM_OK;
+
}
+

+
static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int i = 1;
+
    int complain = 1;
+

+
    while (i < argc) {
+
        if (Jim_CompareStringImmediate(interp, argv[i], "--")) {
+
            i++;
+
            break;
+
        }
+
        if (Jim_CompareStringImmediate(interp, argv[i], "-nocomplain")) {
+
            complain = 0;
+
            i++;
+
            continue;
+
        }
+
        break;
+
    }
+

+
    while (i < argc) {
+
        if (Jim_UnsetVariable(interp, argv[i], complain ? JIM_ERRMSG : JIM_NONE) != JIM_OK
+
            && complain) {
+
            return JIM_ERR;
+
        }
+
        i++;
+
    }
+
    return JIM_OK;
+
}
+

+

+
static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "condition body");
+
        return JIM_ERR;
+
    }
+

+

+
    while (1) {
+
        int boolean, retval;
+

+
        if ((retval = Jim_GetBoolFromExpr(interp, argv[1], &boolean)) != JIM_OK)
+
            return retval;
+
        if (!boolean)
+
            break;
+

+
        if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
+
            switch (retval) {
+
                case JIM_BREAK:
+
                    goto out;
+
                    break;
+
                case JIM_CONTINUE:
+
                    continue;
+
                    break;
+
                default:
+
                    return retval;
+
            }
+
        }
+
    }
+
  out:
+
    Jim_SetEmptyResult(interp);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int retval;
+
    int boolean = 1;
+
    Jim_Obj *varNamePtr = NULL;
+
    Jim_Obj *stopVarNamePtr = NULL;
+

+
    if (argc != 5) {
+
        Jim_WrongNumArgs(interp, 1, argv, "start test next body");
+
        return JIM_ERR;
+
    }
+

+

+
    if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK) {
+
        return retval;
+
    }
+

+
    retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
+

+

+
#ifdef JIM_OPTIMIZATION
+
    if (retval == JIM_OK && boolean) {
+
        ScriptObj *incrScript;
+
        ExprByteCode *expr;
+
        jim_wide stop, currentVal;
+
        Jim_Obj *objPtr;
+
        int cmpOffset;
+

+

+
        expr = JimGetExpression(interp, argv[2]);
+
        incrScript = JimGetScript(interp, argv[3]);
+

+

+
        if (incrScript == NULL || incrScript->len != 3 || !expr || expr->len != 3) {
+
            goto evalstart;
+
        }
+

+
        if (incrScript->token[1].type != JIM_TT_ESC ||
+
            expr->token[0].type != JIM_TT_VAR ||
+
            (expr->token[1].type != JIM_TT_EXPR_INT && expr->token[1].type != JIM_TT_VAR)) {
+
            goto evalstart;
+
        }
+

+
        if (expr->token[2].type == JIM_EXPROP_LT) {
+
            cmpOffset = 0;
+
        }
+
        else if (expr->token[2].type == JIM_EXPROP_LTE) {
+
            cmpOffset = 1;
+
        }
+
        else {
+
            goto evalstart;
+
        }
+

+

+
        if (!Jim_CompareStringImmediate(interp, incrScript->token[1].objPtr, "incr")) {
+
            goto evalstart;
+
        }
+

+

+
        if (!Jim_StringEqObj(incrScript->token[2].objPtr, expr->token[0].objPtr)) {
+
            goto evalstart;
+
        }
+

+

+
        if (expr->token[1].type == JIM_TT_EXPR_INT) {
+
            if (Jim_GetWide(interp, expr->token[1].objPtr, &stop) == JIM_ERR) {
+
                goto evalstart;
+
            }
+
        }
+
        else {
+
            stopVarNamePtr = expr->token[1].objPtr;
+
            Jim_IncrRefCount(stopVarNamePtr);
+

+
            stop = 0;
+
        }
+

+

+
        varNamePtr = expr->token[0].objPtr;
+
        Jim_IncrRefCount(varNamePtr);
+

+
        objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
+
        if (objPtr == NULL || Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK) {
+
            goto testcond;
+
        }
+

+

+
        while (retval == JIM_OK) {
+

+

+

+

+
            if (stopVarNamePtr) {
+
                objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
+
                if (objPtr == NULL || Jim_GetWide(interp, objPtr, &stop) != JIM_OK) {
+
                    goto testcond;
+
                }
+
            }
+

+
            if (currentVal >= stop + cmpOffset) {
+
                break;
+
            }
+

+

+
            retval = Jim_EvalObj(interp, argv[4]);
+
            if (retval == JIM_OK || retval == JIM_CONTINUE) {
+
                retval = JIM_OK;
+

+
                objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
+

+

+
                if (objPtr == NULL) {
+
                    retval = JIM_ERR;
+
                    goto out;
+
                }
+
                if (!Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
+
                    currentVal = ++JimWideValue(objPtr);
+
                    Jim_InvalidateStringRep(objPtr);
+
                }
+
                else {
+
                    if (Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK ||
+
                        Jim_SetVariable(interp, varNamePtr, Jim_NewIntObj(interp,
+
                                ++currentVal)) != JIM_OK) {
+
                        goto evalnext;
+
                    }
+
                }
+
            }
+
        }
+
        goto out;
+
    }
+
  evalstart:
+
#endif
+

+
    while (boolean && (retval == JIM_OK || retval == JIM_CONTINUE)) {
+

+
        retval = Jim_EvalObj(interp, argv[4]);
+

+
        if (retval == JIM_OK || retval == JIM_CONTINUE) {
+

+
JIM_IF_OPTIM(evalnext:)
+
            retval = Jim_EvalObj(interp, argv[3]);
+
            if (retval == JIM_OK || retval == JIM_CONTINUE) {
+

+
JIM_IF_OPTIM(testcond:)
+
                retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
+
            }
+
        }
+
    }
+
JIM_IF_OPTIM(out:)
+
    if (stopVarNamePtr) {
+
        Jim_DecrRefCount(interp, stopVarNamePtr);
+
    }
+
    if (varNamePtr) {
+
        Jim_DecrRefCount(interp, varNamePtr);
+
    }
+

+
    if (retval == JIM_CONTINUE || retval == JIM_BREAK || retval == JIM_OK) {
+
        Jim_SetEmptyResult(interp);
+
        return JIM_OK;
+
    }
+

+
    return retval;
+
}
+

+

+
static int Jim_LoopCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int retval;
+
    jim_wide i;
+
    jim_wide limit;
+
    jim_wide incr = 1;
+
    Jim_Obj *bodyObjPtr;
+

+
    if (argc != 5 && argc != 6) {
+
        Jim_WrongNumArgs(interp, 1, argv, "var first limit ?incr? body");
+
        return JIM_ERR;
+
    }
+

+
    if (Jim_GetWide(interp, argv[2], &i) != JIM_OK ||
+
        Jim_GetWide(interp, argv[3], &limit) != JIM_OK ||
+
          (argc == 6 && Jim_GetWide(interp, argv[4], &incr) != JIM_OK)) {
+
        return JIM_ERR;
+
    }
+
    bodyObjPtr = (argc == 5) ? argv[4] : argv[5];
+

+
    retval = Jim_SetVariable(interp, argv[1], argv[2]);
+

+
    while (((i < limit && incr > 0) || (i > limit && incr < 0)) && retval == JIM_OK) {
+
        retval = Jim_EvalObj(interp, bodyObjPtr);
+
        if (retval == JIM_OK || retval == JIM_CONTINUE) {
+
            Jim_Obj *objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+

+
            retval = JIM_OK;
+

+

+
            i += incr;
+

+
            if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
+
                if (argv[1]->typePtr != &variableObjType) {
+
                    if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
+
                        return JIM_ERR;
+
                    }
+
                }
+
                JimWideValue(objPtr) = i;
+
                Jim_InvalidateStringRep(objPtr);
+

+
                if (argv[1]->typePtr != &variableObjType) {
+
                    if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
+
                        retval = JIM_ERR;
+
                        break;
+
                    }
+
                }
+
            }
+
            else {
+
                objPtr = Jim_NewIntObj(interp, i);
+
                retval = Jim_SetVariable(interp, argv[1], objPtr);
+
                if (retval != JIM_OK) {
+
                    Jim_FreeNewObj(interp, objPtr);
+
                }
+
            }
+
        }
+
    }
+

+
    if (retval == JIM_OK || retval == JIM_CONTINUE || retval == JIM_BREAK) {
+
        Jim_SetEmptyResult(interp);
+
        return JIM_OK;
+
    }
+
    return retval;
+
}
+

+
typedef struct {
+
    Jim_Obj *objPtr;
+
    int idx;
+
} Jim_ListIter;
+

+
static void JimListIterInit(Jim_ListIter *iter, Jim_Obj *objPtr)
+
{
+
    iter->objPtr = objPtr;
+
    iter->idx = 0;
+
}
+

+
static Jim_Obj *JimListIterNext(Jim_Interp *interp, Jim_ListIter *iter)
+
{
+
    if (iter->idx >= Jim_ListLength(interp, iter->objPtr)) {
+
        return NULL;
+
    }
+
    return iter->objPtr->internalRep.listValue.ele[iter->idx++];
+
}
+

+
static int JimListIterDone(Jim_Interp *interp, Jim_ListIter *iter)
+
{
+
    return iter->idx >= Jim_ListLength(interp, iter->objPtr);
+
}
+

+

+
static int JimForeachMapHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int doMap)
+
{
+
    int result = JIM_OK;
+
    int i, numargs;
+
    Jim_ListIter twoiters[2];
+
    Jim_ListIter *iters;
+
    Jim_Obj *script;
+
    Jim_Obj *resultObj;
+

+
    if (argc < 4 || argc % 2 != 0) {
+
        Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
+
        return JIM_ERR;
+
    }
+
    script = argv[argc - 1];
+
    numargs = (argc - 1 - 1);
+

+
    if (numargs == 2) {
+
        iters = twoiters;
+
    }
+
    else {
+
        iters = Jim_Alloc(numargs * sizeof(*iters));
+
    }
+
    for (i = 0; i < numargs; i++) {
+
        JimListIterInit(&iters[i], argv[i + 1]);
+
        if (i % 2 == 0 && JimListIterDone(interp, &iters[i])) {
+
            result = JIM_ERR;
+
        }
+
    }
+
    if (result != JIM_OK) {
+
        Jim_SetResultString(interp, "foreach varlist is empty", -1);
+
        return result;
+
    }
+

+
    if (doMap) {
+
        resultObj = Jim_NewListObj(interp, NULL, 0);
+
    }
+
    else {
+
        resultObj = interp->emptyObj;
+
    }
+
    Jim_IncrRefCount(resultObj);
+

+
    while (1) {
+

+
        for (i = 0; i < numargs; i += 2) {
+
            if (!JimListIterDone(interp, &iters[i + 1])) {
+
                break;
+
            }
+
        }
+
        if (i == numargs) {
+

+
            break;
+
        }
+

+

+
        for (i = 0; i < numargs; i += 2) {
+
            Jim_Obj *varName;
+

+

+
            JimListIterInit(&iters[i], argv[i + 1]);
+
            while ((varName = JimListIterNext(interp, &iters[i])) != NULL) {
+
                Jim_Obj *valObj = JimListIterNext(interp, &iters[i + 1]);
+
                if (!valObj) {
+

+
                    valObj = interp->emptyObj;
+
                }
+

+
                Jim_IncrRefCount(valObj);
+
                result = Jim_SetVariable(interp, varName, valObj);
+
                Jim_DecrRefCount(interp, valObj);
+
                if (result != JIM_OK) {
+
                    goto err;
+
                }
+
            }
+
        }
+
        switch (result = Jim_EvalObj(interp, script)) {
+
            case JIM_OK:
+
                if (doMap) {
+
                    Jim_ListAppendElement(interp, resultObj, interp->result);
+
                }
+
                break;
+
            case JIM_CONTINUE:
+
                break;
+
            case JIM_BREAK:
+
                goto out;
+
            default:
+
                goto err;
+
        }
+
    }
+
  out:
+
    result = JIM_OK;
+
    Jim_SetResult(interp, resultObj);
+
  err:
+
    Jim_DecrRefCount(interp, resultObj);
+
    if (numargs > 2) {
+
        Jim_Free(iters);
+
    }
+
    return result;
+
}
+

+

+
static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return JimForeachMapHelper(interp, argc, argv, 0);
+
}
+

+

+
static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    return JimForeachMapHelper(interp, argc, argv, 1);
+
}
+

+

+
static int Jim_LassignCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int result = JIM_ERR;
+
    int i;
+
    Jim_ListIter iter;
+
    Jim_Obj *resultObj;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "varList list ?varName ...?");
+
        return JIM_ERR;
+
    }
+

+
    JimListIterInit(&iter, argv[1]);
+

+
    for (i = 2; i < argc; i++) {
+
        Jim_Obj *valObj = JimListIterNext(interp, &iter);
+
        result = Jim_SetVariable(interp, argv[i], valObj ? valObj : interp->emptyObj);
+
        if (result != JIM_OK) {
+
            return result;
+
        }
+
    }
+

+
    resultObj = Jim_NewListObj(interp, NULL, 0);
+
    while (!JimListIterDone(interp, &iter)) {
+
        Jim_ListAppendElement(interp, resultObj, JimListIterNext(interp, &iter));
+
    }
+

+
    Jim_SetResult(interp, resultObj);
+

+
    return JIM_OK;
+
}
+

+

+
static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int boolean, retval, current = 1, falsebody = 0;
+

+
    if (argc >= 3) {
+
        while (1) {
+

+
            if (current >= argc)
+
                goto err;
+
            if ((retval = Jim_GetBoolFromExpr(interp, argv[current++], &boolean))
+
                != JIM_OK)
+
                return retval;
+

+
            if (current >= argc)
+
                goto err;
+
            if (Jim_CompareStringImmediate(interp, argv[current], "then"))
+
                current++;
+

+
            if (current >= argc)
+
                goto err;
+
            if (boolean)
+
                return Jim_EvalObj(interp, argv[current]);
+

+
            if (++current >= argc) {
+
                Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+
                return JIM_OK;
+
            }
+
            falsebody = current++;
+
            if (Jim_CompareStringImmediate(interp, argv[falsebody], "else")) {
+

+
                if (current != argc - 1)
+
                    goto err;
+
                return Jim_EvalObj(interp, argv[current]);
+
            }
+
            else if (Jim_CompareStringImmediate(interp, argv[falsebody], "elseif"))
+
                continue;
+

+
            else if (falsebody != argc - 1)
+
                goto err;
+
            return Jim_EvalObj(interp, argv[falsebody]);
+
        }
+
        return JIM_OK;
+
    }
+
  err:
+
    Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
+
    return JIM_ERR;
+
}
+

+

+

+
int Jim_CommandMatchObj(Jim_Interp *interp, Jim_Obj *commandObj, Jim_Obj *patternObj,
+
    Jim_Obj *stringObj, int nocase)
+
{
+
    Jim_Obj *parms[4];
+
    int argc = 0;
+
    long eq;
+
    int rc;
+

+
    parms[argc++] = commandObj;
+
    if (nocase) {
+
        parms[argc++] = Jim_NewStringObj(interp, "-nocase", -1);
+
    }
+
    parms[argc++] = patternObj;
+
    parms[argc++] = stringObj;
+

+
    rc = Jim_EvalObjVector(interp, argc, parms);
+

+
    if (rc != JIM_OK || Jim_GetLong(interp, Jim_GetResult(interp), &eq) != JIM_OK) {
+
        eq = -rc;
+
    }
+

+
    return eq;
+
}
+

+
enum
+
{ SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD };
+

+

+
static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int matchOpt = SWITCH_EXACT, opt = 1, patCount, i;
+
    Jim_Obj *command = 0, *const *caseList = 0, *strObj;
+
    Jim_Obj *script = 0;
+

+
    if (argc < 3) {
+
      wrongnumargs:
+
        Jim_WrongNumArgs(interp, 1, argv, "?options? string "
+
            "pattern body ... ?default body?   or   " "{pattern body ?pattern body ...?}");
+
        return JIM_ERR;
+
    }
+
    for (opt = 1; opt < argc; ++opt) {
+
        const char *option = Jim_String(argv[opt]);
+

+
        if (*option != '-')
+
            break;
+
        else if (strncmp(option, "--", 2) == 0) {
+
            ++opt;
+
            break;
+
        }
+
        else if (strncmp(option, "-exact", 2) == 0)
+
            matchOpt = SWITCH_EXACT;
+
        else if (strncmp(option, "-glob", 2) == 0)
+
            matchOpt = SWITCH_GLOB;
+
        else if (strncmp(option, "-regexp", 2) == 0)
+
            matchOpt = SWITCH_RE;
+
        else if (strncmp(option, "-command", 2) == 0) {
+
            matchOpt = SWITCH_CMD;
+
            if ((argc - opt) < 2)
+
                goto wrongnumargs;
+
            command = argv[++opt];
+
        }
+
        else {
+
            Jim_SetResultFormatted(interp,
+
                "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
+
                argv[opt]);
+
            return JIM_ERR;
+
        }
+
        if ((argc - opt) < 2)
+
            goto wrongnumargs;
+
    }
+
    strObj = argv[opt++];
+
    patCount = argc - opt;
+
    if (patCount == 1) {
+
        Jim_Obj **vector;
+

+
        JimListGetElements(interp, argv[opt], &patCount, &vector);
+
        caseList = vector;
+
    }
+
    else
+
        caseList = &argv[opt];
+
    if (patCount == 0 || patCount % 2 != 0)
+
        goto wrongnumargs;
+
    for (i = 0; script == 0 && i < patCount; i += 2) {
+
        Jim_Obj *patObj = caseList[i];
+

+
        if (!Jim_CompareStringImmediate(interp, patObj, "default")
+
            || i < (patCount - 2)) {
+
            switch (matchOpt) {
+
                case SWITCH_EXACT:
+
                    if (Jim_StringEqObj(strObj, patObj))
+
                        script = caseList[i + 1];
+
                    break;
+
                case SWITCH_GLOB:
+
                    if (Jim_StringMatchObj(interp, patObj, strObj, 0))
+
                        script = caseList[i + 1];
+
                    break;
+
                case SWITCH_RE:
+
                    command = Jim_NewStringObj(interp, "regexp", -1);
+

+
                case SWITCH_CMD:{
+
                        int rc = Jim_CommandMatchObj(interp, command, patObj, strObj, 0);
+

+
                        if (argc - opt == 1) {
+
                            Jim_Obj **vector;
+

+
                            JimListGetElements(interp, argv[opt], &patCount, &vector);
+
                            caseList = vector;
+
                        }
+

+
                        if (rc < 0) {
+
                            return -rc;
+
                        }
+
                        if (rc)
+
                            script = caseList[i + 1];
+
                        break;
+
                    }
+
            }
+
        }
+
        else {
+
            script = caseList[i + 1];
+
        }
+
    }
+
    for (; i < patCount && Jim_CompareStringImmediate(interp, script, "-"); i += 2)
+
        script = caseList[i + 1];
+
    if (script && Jim_CompareStringImmediate(interp, script, "-")) {
+
        Jim_SetResultFormatted(interp, "no body specified for pattern \"%#s\"", caseList[i - 2]);
+
        return JIM_ERR;
+
    }
+
    Jim_SetEmptyResult(interp);
+
    if (script) {
+
        return Jim_EvalObj(interp, script);
+
    }
+
    return JIM_OK;
+
}
+

+

+
static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *listObjPtr;
+

+
    listObjPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
+
    Jim_SetResult(interp, listObjPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr, *listObjPtr;
+
    int i;
+
    int idx;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "list ?index ...?");
+
        return JIM_ERR;
+
    }
+
    objPtr = argv[1];
+
    Jim_IncrRefCount(objPtr);
+
    for (i = 2; i < argc; i++) {
+
        listObjPtr = objPtr;
+
        if (Jim_GetIndex(interp, argv[i], &idx) != JIM_OK) {
+
            Jim_DecrRefCount(interp, listObjPtr);
+
            return JIM_ERR;
+
        }
+
        if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_NONE) != JIM_OK) {
+
            Jim_DecrRefCount(interp, listObjPtr);
+
            Jim_SetEmptyResult(interp);
+
            return JIM_OK;
+
        }
+
        Jim_IncrRefCount(objPtr);
+
        Jim_DecrRefCount(interp, listObjPtr);
+
    }
+
    Jim_SetResult(interp, objPtr);
+
    Jim_DecrRefCount(interp, objPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc != 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "list");
+
        return JIM_ERR;
+
    }
+
    Jim_SetResultInt(interp, Jim_ListLength(interp, argv[1]));
+
    return JIM_OK;
+
}
+

+

+
static int Jim_LsearchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    static const char * const options[] = {
+
        "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
+
            NULL
+
    };
+
    enum
+
    { OPT_BOOL, OPT_NOT, OPT_NOCASE, OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_ALL, OPT_INLINE,
+
            OPT_COMMAND };
+
    int i;
+
    int opt_bool = 0;
+
    int opt_not = 0;
+
    int opt_nocase = 0;
+
    int opt_all = 0;
+
    int opt_inline = 0;
+
    int opt_match = OPT_EXACT;
+
    int listlen;
+
    int rc = JIM_OK;
+
    Jim_Obj *listObjPtr = NULL;
+
    Jim_Obj *commandObj = NULL;
+

+
    if (argc < 3) {
+
      wrongargs:
+
        Jim_WrongNumArgs(interp, 1, argv,
+
            "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
+
        return JIM_ERR;
+
    }
+

+
    for (i = 1; i < argc - 2; i++) {
+
        int option;
+

+
        if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        switch (option) {
+
            case OPT_BOOL:
+
                opt_bool = 1;
+
                opt_inline = 0;
+
                break;
+
            case OPT_NOT:
+
                opt_not = 1;
+
                break;
+
            case OPT_NOCASE:
+
                opt_nocase = 1;
+
                break;
+
            case OPT_INLINE:
+
                opt_inline = 1;
+
                opt_bool = 0;
+
                break;
+
            case OPT_ALL:
+
                opt_all = 1;
+
                break;
+
            case OPT_COMMAND:
+
                if (i >= argc - 2) {
+
                    goto wrongargs;
+
                }
+
                commandObj = argv[++i];
+

+
            case OPT_EXACT:
+
            case OPT_GLOB:
+
            case OPT_REGEXP:
+
                opt_match = option;
+
                break;
+
        }
+
    }
+

+
    argv += i;
+

+
    if (opt_all) {
+
        listObjPtr = Jim_NewListObj(interp, NULL, 0);
+
    }
+
    if (opt_match == OPT_REGEXP) {
+
        commandObj = Jim_NewStringObj(interp, "regexp", -1);
+
    }
+
    if (commandObj) {
+
        Jim_IncrRefCount(commandObj);
+
    }
+

+
    listlen = Jim_ListLength(interp, argv[0]);
+
    for (i = 0; i < listlen; i++) {
+
        int eq = 0;
+
        Jim_Obj *objPtr = Jim_ListGetIndex(interp, argv[0], i);
+

+
        switch (opt_match) {
+
            case OPT_EXACT:
+
                eq = Jim_StringCompareObj(interp, argv[1], objPtr, opt_nocase) == 0;
+
                break;
+

+
            case OPT_GLOB:
+
                eq = Jim_StringMatchObj(interp, argv[1], objPtr, opt_nocase);
+
                break;
+

+
            case OPT_REGEXP:
+
            case OPT_COMMAND:
+
                eq = Jim_CommandMatchObj(interp, commandObj, argv[1], objPtr, opt_nocase);
+
                if (eq < 0) {
+
                    if (listObjPtr) {
+
                        Jim_FreeNewObj(interp, listObjPtr);
+
                    }
+
                    rc = JIM_ERR;
+
                    goto done;
+
                }
+
                break;
+
        }
+

+

+
        if (!eq && opt_bool && opt_not && !opt_all) {
+
            continue;
+
        }
+

+
        if ((!opt_bool && eq == !opt_not) || (opt_bool && (eq || opt_all))) {
+

+
            Jim_Obj *resultObj;
+

+
            if (opt_bool) {
+
                resultObj = Jim_NewIntObj(interp, eq ^ opt_not);
+
            }
+
            else if (!opt_inline) {
+
                resultObj = Jim_NewIntObj(interp, i);
+
            }
+
            else {
+
                resultObj = objPtr;
+
            }
+

+
            if (opt_all) {
+
                Jim_ListAppendElement(interp, listObjPtr, resultObj);
+
            }
+
            else {
+
                Jim_SetResult(interp, resultObj);
+
                goto done;
+
            }
+
        }
+
    }
+

+
    if (opt_all) {
+
        Jim_SetResult(interp, listObjPtr);
+
    }
+
    else {
+

+
        if (opt_bool) {
+
            Jim_SetResultBool(interp, opt_not);
+
        }
+
        else if (!opt_inline) {
+
            Jim_SetResultInt(interp, -1);
+
        }
+
    }
+

+
  done:
+
    if (commandObj) {
+
        Jim_DecrRefCount(interp, commandObj);
+
    }
+
    return rc;
+
}
+

+

+
static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *listObjPtr;
+
    int new_obj = 0;
+
    int i;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
+
        return JIM_ERR;
+
    }
+
    listObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
+
    if (!listObjPtr) {
+

+
        listObjPtr = Jim_NewListObj(interp, NULL, 0);
+
        new_obj = 1;
+
    }
+
    else if (Jim_IsShared(listObjPtr)) {
+
        listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
+
        new_obj = 1;
+
    }
+
    for (i = 2; i < argc; i++)
+
        Jim_ListAppendElement(interp, listObjPtr, argv[i]);
+
    if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
+
        if (new_obj)
+
            Jim_FreeNewObj(interp, listObjPtr);
+
        return JIM_ERR;
+
    }
+
    Jim_SetResult(interp, listObjPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int idx, len;
+
    Jim_Obj *listPtr;
+

+
    if (argc < 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "list index ?element ...?");
+
        return JIM_ERR;
+
    }
+
    listPtr = argv[1];
+
    if (Jim_IsShared(listPtr))
+
        listPtr = Jim_DuplicateObj(interp, listPtr);
+
    if (Jim_GetIndex(interp, argv[2], &idx) != JIM_OK)
+
        goto err;
+
    len = Jim_ListLength(interp, listPtr);
+
    if (idx >= len)
+
        idx = len;
+
    else if (idx < 0)
+
        idx = len + idx + 1;
+
    Jim_ListInsertElements(interp, listPtr, idx, argc - 3, &argv[3]);
+
    Jim_SetResult(interp, listPtr);
+
    return JIM_OK;
+
  err:
+
    if (listPtr != argv[1]) {
+
        Jim_FreeNewObj(interp, listPtr);
+
    }
+
    return JIM_ERR;
+
}
+

+

+
static int Jim_LreplaceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int first, last, len, rangeLen;
+
    Jim_Obj *listObj;
+
    Jim_Obj *newListObj;
+

+
    if (argc < 4) {
+
        Jim_WrongNumArgs(interp, 1, argv, "list first last ?element ...?");
+
        return JIM_ERR;
+
    }
+
    if (Jim_GetIndex(interp, argv[2], &first) != JIM_OK ||
+
        Jim_GetIndex(interp, argv[3], &last) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+

+
    listObj = argv[1];
+
    len = Jim_ListLength(interp, listObj);
+

+
    first = JimRelToAbsIndex(len, first);
+
    last = JimRelToAbsIndex(len, last);
+
    JimRelToAbsRange(len, &first, &last, &rangeLen);
+

+

+

+
    if (first < len) {
+

+
    }
+
    else if (len == 0) {
+

+
        first = 0;
+
    }
+
    else {
+
        Jim_SetResultString(interp, "list doesn't contain element ", -1);
+
        Jim_AppendObj(interp, Jim_GetResult(interp), argv[2]);
+
        return JIM_ERR;
+
    }
+

+

+
    newListObj = Jim_NewListObj(interp, listObj->internalRep.listValue.ele, first);
+

+

+
    ListInsertElements(newListObj, -1, argc - 4, argv + 4);
+

+

+
    ListInsertElements(newListObj, -1, len - first - rangeLen, listObj->internalRep.listValue.ele + first + rangeLen);
+

+
    Jim_SetResult(interp, newListObj);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc < 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "listVar ?index...? newVal");
+
        return JIM_ERR;
+
    }
+
    else if (argc == 3) {
+

+
        if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
+
            return JIM_ERR;
+
        Jim_SetResult(interp, argv[2]);
+
        return JIM_OK;
+
    }
+
    return Jim_ListSetIndex(interp, argv[1], argv + 2, argc - 3, argv[argc - 1]);
+
}
+

+

+
static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
+
{
+
    static const char * const options[] = {
+
        "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-real", "-index", "-unique", NULL
+
    };
+
    enum
+
    { OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING, OPT_COMMAND, OPT_INTEGER, OPT_REAL, OPT_INDEX, OPT_UNIQUE };
+
    Jim_Obj *resObj;
+
    int i;
+
    int retCode;
+

+
    struct lsort_info info;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "?options? list");
+
        return JIM_ERR;
+
    }
+

+
    info.type = JIM_LSORT_ASCII;
+
    info.order = 1;
+
    info.indexed = 0;
+
    info.unique = 0;
+
    info.command = NULL;
+
    info.interp = interp;
+

+
    for (i = 1; i < (argc - 1); i++) {
+
        int option;
+

+
        if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ENUM_ABBREV | JIM_ERRMSG)
+
            != JIM_OK)
+
            return JIM_ERR;
+
        switch (option) {
+
            case OPT_ASCII:
+
                info.type = JIM_LSORT_ASCII;
+
                break;
+
            case OPT_NOCASE:
+
                info.type = JIM_LSORT_NOCASE;
+
                break;
+
            case OPT_INTEGER:
+
                info.type = JIM_LSORT_INTEGER;
+
                break;
+
            case OPT_REAL:
+
                info.type = JIM_LSORT_REAL;
+
                break;
+
            case OPT_INCREASING:
+
                info.order = 1;
+
                break;
+
            case OPT_DECREASING:
+
                info.order = -1;
+
                break;
+
            case OPT_UNIQUE:
+
                info.unique = 1;
+
                break;
+
            case OPT_COMMAND:
+
                if (i >= (argc - 2)) {
+
                    Jim_SetResultString(interp, "\"-command\" option must be followed by comparison command", -1);
+
                    return JIM_ERR;
+
                }
+
                info.type = JIM_LSORT_COMMAND;
+
                info.command = argv[i + 1];
+
                i++;
+
                break;
+
            case OPT_INDEX:
+
                if (i >= (argc - 2)) {
+
                    Jim_SetResultString(interp, "\"-index\" option must be followed by list index", -1);
+
                    return JIM_ERR;
+
                }
+
                if (Jim_GetIndex(interp, argv[i + 1], &info.index) != JIM_OK) {
+
                    return JIM_ERR;
+
                }
+
                info.indexed = 1;
+
                i++;
+
                break;
+
        }
+
    }
+
    resObj = Jim_DuplicateObj(interp, argv[argc - 1]);
+
    retCode = ListSortElements(interp, resObj, &info);
+
    if (retCode == JIM_OK) {
+
        Jim_SetResult(interp, resObj);
+
    }
+
    else {
+
        Jim_FreeNewObj(interp, resObj);
+
    }
+
    return retCode;
+
}
+

+

+
static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *stringObjPtr;
+
    int i;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "varName ?value ...?");
+
        return JIM_ERR;
+
    }
+
    if (argc == 2) {
+
        stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+
        if (!stringObjPtr)
+
            return JIM_ERR;
+
    }
+
    else {
+
        int new_obj = 0;
+
        stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
+
        if (!stringObjPtr) {
+

+
            stringObjPtr = Jim_NewEmptyStringObj(interp);
+
            new_obj = 1;
+
        }
+
        else if (Jim_IsShared(stringObjPtr)) {
+
            new_obj = 1;
+
            stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
+
        }
+
        for (i = 2; i < argc; i++) {
+
            Jim_AppendObj(interp, stringObjPtr, argv[i]);
+
        }
+
        if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
+
            if (new_obj) {
+
                Jim_FreeNewObj(interp, stringObjPtr);
+
            }
+
            return JIM_ERR;
+
        }
+
    }
+
    Jim_SetResult(interp, stringObjPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_DebugCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
#if !defined(JIM_DEBUG_COMMAND)
+
    Jim_SetResultString(interp, "unsupported", -1);
+
    return JIM_ERR;
+
#endif
+
}
+

+

+
static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int rc;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "arg ?arg ...?");
+
        return JIM_ERR;
+
    }
+

+
    if (argc == 2) {
+
        rc = Jim_EvalObj(interp, argv[1]);
+
    }
+
    else {
+
        rc = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
+
    }
+

+
    if (rc == JIM_ERR) {
+

+
        interp->addStackTrace++;
+
    }
+
    return rc;
+
}
+

+

+
static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc >= 2) {
+
        int retcode;
+
        Jim_CallFrame *savedCallFrame, *targetCallFrame;
+
        const char *str;
+

+

+
        savedCallFrame = interp->framePtr;
+

+

+
        str = Jim_String(argv[1]);
+
        if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#') {
+
            targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
+
            argc--;
+
            argv++;
+
        }
+
        else {
+
            targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
+
        }
+
        if (targetCallFrame == NULL) {
+
            return JIM_ERR;
+
        }
+
        if (argc < 2) {
+
            Jim_WrongNumArgs(interp, 1, argv - 1, "?level? command ?arg ...?");
+
            return JIM_ERR;
+
        }
+

+
        interp->framePtr = targetCallFrame;
+
        if (argc == 2) {
+
            retcode = Jim_EvalObj(interp, argv[1]);
+
        }
+
        else {
+
            retcode = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
+
        }
+
        interp->framePtr = savedCallFrame;
+
        return retcode;
+
    }
+
    else {
+
        Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
+
        return JIM_ERR;
+
    }
+
}
+

+

+
static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *exprResultPtr;
+
    int retcode;
+

+
    if (argc == 2) {
+
        retcode = Jim_EvalExpression(interp, argv[1], &exprResultPtr);
+
    }
+
    else if (argc > 2) {
+
        Jim_Obj *objPtr;
+

+
        objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
+
        Jim_IncrRefCount(objPtr);
+
        retcode = Jim_EvalExpression(interp, objPtr, &exprResultPtr);
+
        Jim_DecrRefCount(interp, objPtr);
+
    }
+
    else {
+
        Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
+
        return JIM_ERR;
+
    }
+
    if (retcode != JIM_OK)
+
        return retcode;
+
    Jim_SetResult(interp, exprResultPtr);
+
    Jim_DecrRefCount(interp, exprResultPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc != 1) {
+
        Jim_WrongNumArgs(interp, 1, argv, "");
+
        return JIM_ERR;
+
    }
+
    return JIM_BREAK;
+
}
+

+

+
static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc != 1) {
+
        Jim_WrongNumArgs(interp, 1, argv, "");
+
        return JIM_ERR;
+
    }
+
    return JIM_CONTINUE;
+
}
+

+

+
static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int i;
+
    Jim_Obj *stackTraceObj = NULL;
+
    Jim_Obj *errorCodeObj = NULL;
+
    int returnCode = JIM_OK;
+
    long level = 1;
+

+
    for (i = 1; i < argc - 1; i += 2) {
+
        if (Jim_CompareStringImmediate(interp, argv[i], "-code")) {
+
            if (Jim_GetReturnCode(interp, argv[i + 1], &returnCode) == JIM_ERR) {
+
                return JIM_ERR;
+
            }
+
        }
+
        else if (Jim_CompareStringImmediate(interp, argv[i], "-errorinfo")) {
+
            stackTraceObj = argv[i + 1];
+
        }
+
        else if (Jim_CompareStringImmediate(interp, argv[i], "-errorcode")) {
+
            errorCodeObj = argv[i + 1];
+
        }
+
        else if (Jim_CompareStringImmediate(interp, argv[i], "-level")) {
+
            if (Jim_GetLong(interp, argv[i + 1], &level) != JIM_OK || level < 0) {
+
                Jim_SetResultFormatted(interp, "bad level \"%#s\"", argv[i + 1]);
+
                return JIM_ERR;
+
            }
+
        }
+
        else {
+
            break;
+
        }
+
    }
+

+
    if (i != argc - 1 && i != argc) {
+
        Jim_WrongNumArgs(interp, 1, argv,
+
            "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
+
    }
+

+

+
    if (stackTraceObj && returnCode == JIM_ERR) {
+
        JimSetStackTrace(interp, stackTraceObj);
+
    }
+

+
    if (errorCodeObj && returnCode == JIM_ERR) {
+
        Jim_SetGlobalVariableStr(interp, "errorCode", errorCodeObj);
+
    }
+
    interp->returnCode = returnCode;
+
    interp->returnLevel = level;
+

+
    if (i == argc - 1) {
+
        Jim_SetResult(interp, argv[i]);
+
    }
+
    return JIM_RETURN;
+
}
+

+

+
static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (interp->framePtr->level == 0) {
+
        Jim_SetResultString(interp, "tailcall can only be called from a proc or lambda", -1);
+
        return JIM_ERR;
+
    }
+
    else if (argc >= 2) {
+

+
        Jim_CallFrame *cf = interp->framePtr->parent;
+

+
        Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
+
        if (cmdPtr == NULL) {
+
            return JIM_ERR;
+
        }
+

+
        JimPanic((cf->tailcallCmd != NULL, "Already have a tailcallCmd"));
+

+

+
        JimIncrCmdRefCount(cmdPtr);
+
        cf->tailcallCmd = cmdPtr;
+

+

+
        JimPanic((cf->tailcallObj != NULL, "Already have a tailcallobj"));
+

+
        cf->tailcallObj = Jim_NewListObj(interp, argv + 1, argc - 1);
+
        Jim_IncrRefCount(cf->tailcallObj);
+

+

+
        return JIM_EVAL;
+
    }
+
    return JIM_OK;
+
}
+

+
static int JimAliasCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *cmdList;
+
    Jim_Obj *prefixListObj = Jim_CmdPrivData(interp);
+

+

+
    cmdList = Jim_DuplicateObj(interp, prefixListObj);
+
    Jim_ListInsertElements(interp, cmdList, Jim_ListLength(interp, cmdList), argc - 1, argv + 1);
+

+
    return JimEvalObjList(interp, cmdList);
+
}
+

+
static void JimAliasCmdDelete(Jim_Interp *interp, void *privData)
+
{
+
    Jim_Obj *prefixListObj = privData;
+
    Jim_DecrRefCount(interp, prefixListObj);
+
}
+

+
static int Jim_AliasCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *prefixListObj;
+
    const char *newname;
+

+
    if (argc < 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "newname command ?args ...?");
+
        return JIM_ERR;
+
    }
+

+
    prefixListObj = Jim_NewListObj(interp, argv + 2, argc - 2);
+
    Jim_IncrRefCount(prefixListObj);
+
    newname = Jim_String(argv[1]);
+
    if (newname[0] == ':' && newname[1] == ':') {
+
        while (*++newname == ':') {
+
        }
+
    }
+

+
    Jim_SetResult(interp, argv[1]);
+

+
    return Jim_CreateCommand(interp, newname, JimAliasCmd, prefixListObj, JimAliasCmdDelete);
+
}
+

+

+
static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Cmd *cmd;
+

+
    if (argc != 4 && argc != 5) {
+
        Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
+
        return JIM_ERR;
+
    }
+

+
    if (JimValidName(interp, "procedure", argv[1]) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+

+
    if (argc == 4) {
+
        cmd = JimCreateProcedureCmd(interp, argv[2], NULL, argv[3], NULL);
+
    }
+
    else {
+
        cmd = JimCreateProcedureCmd(interp, argv[2], argv[3], argv[4], NULL);
+
    }
+

+
    if (cmd) {
+

+
        Jim_Obj *qualifiedCmdNameObj;
+
        const char *cmdname = JimQualifyName(interp, Jim_String(argv[1]), &qualifiedCmdNameObj);
+

+
        JimCreateCommand(interp, cmdname, cmd);
+

+

+
        JimUpdateProcNamespace(interp, cmd, cmdname);
+

+
        JimFreeQualifiedName(interp, qualifiedCmdNameObj);
+

+

+
        Jim_SetResult(interp, argv[1]);
+
        return JIM_OK;
+
    }
+
    return JIM_ERR;
+
}
+

+

+
static int Jim_LocalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int retcode;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
+
        return JIM_ERR;
+
    }
+

+

+
    interp->local++;
+
    retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
+
    interp->local--;
+

+

+

+
    if (retcode == 0) {
+
        Jim_Obj *cmdNameObj = Jim_GetResult(interp);
+

+
        if (Jim_GetCommand(interp, cmdNameObj, JIM_ERRMSG) == NULL) {
+
            return JIM_ERR;
+
        }
+
        if (interp->framePtr->localCommands == NULL) {
+
            interp->framePtr->localCommands = Jim_Alloc(sizeof(*interp->framePtr->localCommands));
+
            Jim_InitStack(interp->framePtr->localCommands);
+
        }
+
        Jim_IncrRefCount(cmdNameObj);
+
        Jim_StackPush(interp->framePtr->localCommands, cmdNameObj);
+
    }
+

+
    return retcode;
+
}
+

+

+
static int Jim_UpcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
+
        return JIM_ERR;
+
    }
+
    else {
+
        int retcode;
+

+
        Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
+
        if (cmdPtr == NULL || !cmdPtr->isproc || !cmdPtr->prevCmd) {
+
            Jim_SetResultFormatted(interp, "no previous command: \"%#s\"", argv[1]);
+
            return JIM_ERR;
+
        }
+

+
        cmdPtr->u.proc.upcall++;
+
        JimIncrCmdRefCount(cmdPtr);
+

+

+
        retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
+

+

+
        cmdPtr->u.proc.upcall--;
+
        JimDecrCmdRefCount(interp, cmdPtr);
+

+
        return retcode;
+
    }
+
}
+

+

+
static int Jim_ApplyCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "lambdaExpr ?arg ...?");
+
        return JIM_ERR;
+
    }
+
    else {
+
        int ret;
+
        Jim_Cmd *cmd;
+
        Jim_Obj *argListObjPtr;
+
        Jim_Obj *bodyObjPtr;
+
        Jim_Obj *nsObj = NULL;
+
        Jim_Obj **nargv;
+

+
        int len = Jim_ListLength(interp, argv[1]);
+
        if (len != 2 && len != 3) {
+
            Jim_SetResultFormatted(interp, "can't interpret \"%#s\" as a lambda expression", argv[1]);
+
            return JIM_ERR;
+
        }
+

+
        if (len == 3) {
+
#ifdef jim_ext_namespace
+

+
            nsObj = JimQualifyNameObj(interp, Jim_ListGetIndex(interp, argv[1], 2));
+
#else
+
            Jim_SetResultString(interp, "namespaces not enabled", -1);
+
            return JIM_ERR;
+
#endif
+
        }
+
        argListObjPtr = Jim_ListGetIndex(interp, argv[1], 0);
+
        bodyObjPtr = Jim_ListGetIndex(interp, argv[1], 1);
+

+
        cmd = JimCreateProcedureCmd(interp, argListObjPtr, NULL, bodyObjPtr, nsObj);
+

+
        if (cmd) {
+

+
            nargv = Jim_Alloc((argc - 2 + 1) * sizeof(*nargv));
+
            nargv[0] = Jim_NewStringObj(interp, "apply lambdaExpr", -1);
+
            Jim_IncrRefCount(nargv[0]);
+
            memcpy(&nargv[1], argv + 2, (argc - 2) * sizeof(*nargv));
+
            ret = JimCallProcedure(interp, cmd, argc - 2 + 1, nargv);
+
            Jim_DecrRefCount(interp, nargv[0]);
+
            Jim_Free(nargv);
+

+
            JimDecrCmdRefCount(interp, cmd);
+
            return ret;
+
        }
+
        return JIM_ERR;
+
    }
+
}
+

+

+

+
static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_SetResult(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
+
    return JIM_OK;
+
}
+

+

+
static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int i;
+
    Jim_CallFrame *targetCallFrame;
+

+

+
    if (argc > 3 && (argc % 2 == 0)) {
+
        targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
+
        argc--;
+
        argv++;
+
    }
+
    else {
+
        targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
+
    }
+
    if (targetCallFrame == NULL) {
+
        return JIM_ERR;
+
    }
+

+

+
    if (argc < 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
+
        return JIM_ERR;
+
    }
+

+

+
    for (i = 1; i < argc; i += 2) {
+
        if (Jim_SetVariableLink(interp, argv[i + 1], argv[i], targetCallFrame) != JIM_OK)
+
            return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+

+
static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int i;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
+
        return JIM_ERR;
+
    }
+

+
    if (interp->framePtr->level == 0)
+
        return JIM_OK;
+
    for (i = 1; i < argc; i++) {
+

+
        const char *name = Jim_String(argv[i]);
+
        if (name[0] != ':' || name[1] != ':') {
+
            if (Jim_SetVariableLink(interp, argv[i], argv[i], interp->topFramePtr) != JIM_OK)
+
                return JIM_ERR;
+
        }
+
    }
+
    return JIM_OK;
+
}
+

+
static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
+
    Jim_Obj *objPtr, int nocase)
+
{
+
    int numMaps;
+
    const char *str, *noMatchStart = NULL;
+
    int strLen, i;
+
    Jim_Obj *resultObjPtr;
+

+
    numMaps = Jim_ListLength(interp, mapListObjPtr);
+
    if (numMaps % 2) {
+
        Jim_SetResultString(interp, "list must contain an even number of elements", -1);
+
        return NULL;
+
    }
+

+
    str = Jim_String(objPtr);
+
    strLen = Jim_Utf8Length(interp, objPtr);
+

+

+
    resultObjPtr = Jim_NewStringObj(interp, "", 0);
+
    while (strLen) {
+
        for (i = 0; i < numMaps; i += 2) {
+
            Jim_Obj *eachObjPtr;
+
            const char *k;
+
            int kl;
+

+
            eachObjPtr = Jim_ListGetIndex(interp, mapListObjPtr, i);
+
            k = Jim_String(eachObjPtr);
+
            kl = Jim_Utf8Length(interp, eachObjPtr);
+

+
            if (strLen >= kl && kl) {
+
                int rc;
+
                rc = JimStringCompareLen(str, k, kl, nocase);
+
                if (rc == 0) {
+
                    if (noMatchStart) {
+
                        Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
+
                        noMatchStart = NULL;
+
                    }
+
                    Jim_AppendObj(interp, resultObjPtr, Jim_ListGetIndex(interp, mapListObjPtr, i + 1));
+
                    str += utf8_index(str, kl);
+
                    strLen -= kl;
+
                    break;
+
                }
+
            }
+
        }
+
        if (i == numMaps) {
+
            int c;
+
            if (noMatchStart == NULL)
+
                noMatchStart = str;
+
            str += utf8_tounicode(str, &c);
+
            strLen--;
+
        }
+
    }
+
    if (noMatchStart) {
+
        Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
+
    }
+
    return resultObjPtr;
+
}
+

+

+
static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int len;
+
    int opt_case = 1;
+
    int option;
+
    static const char * const options[] = {
+
        "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "replace",
+
        "map", "repeat", "reverse", "index", "first", "last", "cat",
+
        "trim", "trimleft", "trimright", "tolower", "toupper", "totitle", NULL
+
    };
+
    enum
+
    {
+
        OPT_BYTELENGTH, OPT_LENGTH, OPT_COMPARE, OPT_MATCH, OPT_EQUAL, OPT_IS, OPT_BYTERANGE, OPT_RANGE, OPT_REPLACE,
+
        OPT_MAP, OPT_REPEAT, OPT_REVERSE, OPT_INDEX, OPT_FIRST, OPT_LAST, OPT_CAT,
+
        OPT_TRIM, OPT_TRIMLEFT, OPT_TRIMRIGHT, OPT_TOLOWER, OPT_TOUPPER, OPT_TOTITLE
+
    };
+
    static const char * const nocase_options[] = {
+
        "-nocase", NULL
+
    };
+
    static const char * const nocase_length_options[] = {
+
        "-nocase", "-length", NULL
+
    };
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
+
        return JIM_ERR;
+
    }
+
    if (Jim_GetEnum(interp, argv[1], options, &option, NULL,
+
            JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK)
+
        return Jim_CheckShowCommands(interp, argv[1], options);
+

+
    switch (option) {
+
        case OPT_LENGTH:
+
        case OPT_BYTELENGTH:
+
            if (argc != 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "string");
+
                return JIM_ERR;
+
            }
+
            if (option == OPT_LENGTH) {
+
                len = Jim_Utf8Length(interp, argv[2]);
+
            }
+
            else {
+
                len = Jim_Length(argv[2]);
+
            }
+
            Jim_SetResultInt(interp, len);
+
            return JIM_OK;
+

+
        case OPT_CAT:{
+
                Jim_Obj *objPtr;
+
                if (argc == 3) {
+

+
                    objPtr = argv[2];
+
                }
+
                else {
+
                    int i;
+

+
                    objPtr = Jim_NewStringObj(interp, "", 0);
+

+
                    for (i = 2; i < argc; i++) {
+
                        Jim_AppendObj(interp, objPtr, argv[i]);
+
                    }
+
                }
+
                Jim_SetResult(interp, objPtr);
+
                return JIM_OK;
+
            }
+

+
        case OPT_COMPARE:
+
        case OPT_EQUAL:
+
            {
+

+
                long opt_length = -1;
+
                int n = argc - 4;
+
                int i = 2;
+
                while (n > 0) {
+
                    int subopt;
+
                    if (Jim_GetEnum(interp, argv[i++], nocase_length_options, &subopt, NULL,
+
                            JIM_ENUM_ABBREV) != JIM_OK) {
+
badcompareargs:
+
                        Jim_WrongNumArgs(interp, 2, argv, "?-nocase? ?-length int? string1 string2");
+
                        return JIM_ERR;
+
                    }
+
                    if (subopt == 0) {
+

+
                        opt_case = 0;
+
                        n--;
+
                    }
+
                    else {
+

+
                        if (n < 2) {
+
                            goto badcompareargs;
+
                        }
+
                        if (Jim_GetLong(interp, argv[i++], &opt_length) != JIM_OK) {
+
                            return JIM_ERR;
+
                        }
+
                        n -= 2;
+
                    }
+
                }
+
                if (n) {
+
                    goto badcompareargs;
+
                }
+
                argv += argc - 2;
+
                if (opt_length < 0 && option != OPT_COMPARE && opt_case) {
+

+
                    Jim_SetResultBool(interp, Jim_StringEqObj(argv[0], argv[1]));
+
                }
+
                else {
+
                    if (opt_length >= 0) {
+
                        n = JimStringCompareLen(Jim_String(argv[0]), Jim_String(argv[1]), opt_length, !opt_case);
+
                    }
+
                    else {
+
                        n = Jim_StringCompareObj(interp, argv[0], argv[1], !opt_case);
+
                    }
+
                    Jim_SetResultInt(interp, option == OPT_COMPARE ? n : n == 0);
+
                }
+
                return JIM_OK;
+
            }
+

+
        case OPT_MATCH:
+
            if (argc != 4 &&
+
                (argc != 5 ||
+
                    Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
+
                        JIM_ENUM_ABBREV) != JIM_OK)) {
+
                Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern string");
+
                return JIM_ERR;
+
            }
+
            if (opt_case == 0) {
+
                argv++;
+
            }
+
            Jim_SetResultBool(interp, Jim_StringMatchObj(interp, argv[2], argv[3], !opt_case));
+
            return JIM_OK;
+

+
        case OPT_MAP:{
+
                Jim_Obj *objPtr;
+

+
                if (argc != 4 &&
+
                    (argc != 5 ||
+
                        Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
+
                            JIM_ENUM_ABBREV) != JIM_OK)) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList string");
+
                    return JIM_ERR;
+
                }
+

+
                if (opt_case == 0) {
+
                    argv++;
+
                }
+
                objPtr = JimStringMap(interp, argv[2], argv[3], !opt_case);
+
                if (objPtr == NULL) {
+
                    return JIM_ERR;
+
                }
+
                Jim_SetResult(interp, objPtr);
+
                return JIM_OK;
+
            }
+

+
        case OPT_RANGE:
+
        case OPT_BYTERANGE:{
+
                Jim_Obj *objPtr;
+

+
                if (argc != 5) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "string first last");
+
                    return JIM_ERR;
+
                }
+
                if (option == OPT_RANGE) {
+
                    objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
+
                }
+
                else
+
                {
+
                    objPtr = Jim_StringByteRangeObj(interp, argv[2], argv[3], argv[4]);
+
                }
+

+
                if (objPtr == NULL) {
+
                    return JIM_ERR;
+
                }
+
                Jim_SetResult(interp, objPtr);
+
                return JIM_OK;
+
            }
+

+
        case OPT_REPLACE:{
+
                Jim_Obj *objPtr;
+

+
                if (argc != 5 && argc != 6) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "string first last ?string?");
+
                    return JIM_ERR;
+
                }
+
                objPtr = JimStringReplaceObj(interp, argv[2], argv[3], argv[4], argc == 6 ? argv[5] : NULL);
+
                if (objPtr == NULL) {
+
                    return JIM_ERR;
+
                }
+
                Jim_SetResult(interp, objPtr);
+
                return JIM_OK;
+
            }
+

+

+
        case OPT_REPEAT:{
+
                Jim_Obj *objPtr;
+
                jim_wide count;
+

+
                if (argc != 4) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "string count");
+
                    return JIM_ERR;
+
                }
+
                if (Jim_GetWide(interp, argv[3], &count) != JIM_OK) {
+
                    return JIM_ERR;
+
                }
+
                objPtr = Jim_NewStringObj(interp, "", 0);
+
                if (count > 0) {
+
                    while (count--) {
+
                        Jim_AppendObj(interp, objPtr, argv[2]);
+
                    }
+
                }
+
                Jim_SetResult(interp, objPtr);
+
                return JIM_OK;
+
            }
+

+
        case OPT_REVERSE:{
+
                char *buf, *p;
+
                const char *str;
+
                int i;
+

+
                if (argc != 3) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "string");
+
                    return JIM_ERR;
+
                }
+

+
                str = Jim_GetString(argv[2], &len);
+
                buf = Jim_Alloc(len + 1);
+
                p = buf + len;
+
                *p = 0;
+
                for (i = 0; i < len; ) {
+
                    int c;
+
                    int l = utf8_tounicode(str, &c);
+
                    memcpy(p - l, str, l);
+
                    p -= l;
+
                    i += l;
+
                    str += l;
+
                }
+
                Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
+
                return JIM_OK;
+
            }
+

+
        case OPT_INDEX:{
+
                int idx;
+
                const char *str;
+

+
                if (argc != 4) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "string index");
+
                    return JIM_ERR;
+
                }
+
                if (Jim_GetIndex(interp, argv[3], &idx) != JIM_OK) {
+
                    return JIM_ERR;
+
                }
+
                str = Jim_String(argv[2]);
+
                len = Jim_Utf8Length(interp, argv[2]);
+
                if (idx != INT_MIN && idx != INT_MAX) {
+
                    idx = JimRelToAbsIndex(len, idx);
+
                }
+
                if (idx < 0 || idx >= len || str == NULL) {
+
                    Jim_SetResultString(interp, "", 0);
+
                }
+
                else if (len == Jim_Length(argv[2])) {
+

+
                    Jim_SetResultString(interp, str + idx, 1);
+
                }
+
                else {
+
                    int c;
+
                    int i = utf8_index(str, idx);
+
                    Jim_SetResultString(interp, str + i, utf8_tounicode(str + i, &c));
+
                }
+
                return JIM_OK;
+
            }
+

+
        case OPT_FIRST:
+
        case OPT_LAST:{
+
                int idx = 0, l1, l2;
+
                const char *s1, *s2;
+

+
                if (argc != 4 && argc != 5) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "subString string ?index?");
+
                    return JIM_ERR;
+
                }
+
                s1 = Jim_String(argv[2]);
+
                s2 = Jim_String(argv[3]);
+
                l1 = Jim_Utf8Length(interp, argv[2]);
+
                l2 = Jim_Utf8Length(interp, argv[3]);
+
                if (argc == 5) {
+
                    if (Jim_GetIndex(interp, argv[4], &idx) != JIM_OK) {
+
                        return JIM_ERR;
+
                    }
+
                    idx = JimRelToAbsIndex(l2, idx);
+
                }
+
                else if (option == OPT_LAST) {
+
                    idx = l2;
+
                }
+
                if (option == OPT_FIRST) {
+
                    Jim_SetResultInt(interp, JimStringFirst(s1, l1, s2, l2, idx));
+
                }
+
                else {
+
#ifdef JIM_UTF8
+
                    Jim_SetResultInt(interp, JimStringLastUtf8(s1, l1, s2, idx));
+
#else
+
                    Jim_SetResultInt(interp, JimStringLast(s1, l1, s2, idx));
+
#endif
+
                }
+
                return JIM_OK;
+
            }
+

+
        case OPT_TRIM:
+
        case OPT_TRIMLEFT:
+
        case OPT_TRIMRIGHT:{
+
                Jim_Obj *trimchars;
+

+
                if (argc != 3 && argc != 4) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "string ?trimchars?");
+
                    return JIM_ERR;
+
                }
+
                trimchars = (argc == 4 ? argv[3] : NULL);
+
                if (option == OPT_TRIM) {
+
                    Jim_SetResult(interp, JimStringTrim(interp, argv[2], trimchars));
+
                }
+
                else if (option == OPT_TRIMLEFT) {
+
                    Jim_SetResult(interp, JimStringTrimLeft(interp, argv[2], trimchars));
+
                }
+
                else if (option == OPT_TRIMRIGHT) {
+
                    Jim_SetResult(interp, JimStringTrimRight(interp, argv[2], trimchars));
+
                }
+
                return JIM_OK;
+
            }
+

+
        case OPT_TOLOWER:
+
        case OPT_TOUPPER:
+
        case OPT_TOTITLE:
+
            if (argc != 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "string");
+
                return JIM_ERR;
+
            }
+
            if (option == OPT_TOLOWER) {
+
                Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
+
            }
+
            else if (option == OPT_TOUPPER) {
+
                Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
+
            }
+
            else {
+
                Jim_SetResult(interp, JimStringToTitle(interp, argv[2]));
+
            }
+
            return JIM_OK;
+

+
        case OPT_IS:
+
            if (argc == 4 || (argc == 5 && Jim_CompareStringImmediate(interp, argv[3], "-strict"))) {
+
                return JimStringIs(interp, argv[argc - 1], argv[2], argc == 5);
+
            }
+
            Jim_WrongNumArgs(interp, 2, argv, "class ?-strict? str");
+
            return JIM_ERR;
+
    }
+
    return JIM_OK;
+
}
+

+

+
static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    long i, count = 1;
+
    jim_wide start, elapsed;
+
    char buf[60];
+
    const char *fmt = "%" JIM_WIDE_MODIFIER " microseconds per iteration";
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
+
        return JIM_ERR;
+
    }
+
    if (argc == 3) {
+
        if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
+
            return JIM_ERR;
+
    }
+
    if (count < 0)
+
        return JIM_OK;
+
    i = count;
+
    start = JimClock();
+
    while (i-- > 0) {
+
        int retval;
+

+
        retval = Jim_EvalObj(interp, argv[1]);
+
        if (retval != JIM_OK) {
+
            return retval;
+
        }
+
    }
+
    elapsed = JimClock() - start;
+
    sprintf(buf, fmt, count == 0 ? 0 : elapsed / count);
+
    Jim_SetResultString(interp, buf, -1);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    long exitCode = 0;
+

+
    if (argc > 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
+
        return JIM_ERR;
+
    }
+
    if (argc == 2) {
+
        if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
+
            return JIM_ERR;
+
    }
+
    interp->exitCode = exitCode;
+
    return JIM_EXIT;
+
}
+

+

+
static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int exitCode = 0;
+
    int i;
+
    int sig = 0;
+

+

+
    jim_wide ignore_mask = (1 << JIM_EXIT) | (1 << JIM_EVAL) | (1 << JIM_SIGNAL);
+
    static const int max_ignore_code = sizeof(ignore_mask) * 8;
+

+
    Jim_SetGlobalVariableStr(interp, "errorCode", Jim_NewStringObj(interp, "NONE", -1));
+

+
    for (i = 1; i < argc - 1; i++) {
+
        const char *arg = Jim_String(argv[i]);
+
        jim_wide option;
+
        int ignore;
+

+

+
        if (strcmp(arg, "--") == 0) {
+
            i++;
+
            break;
+
        }
+
        if (*arg != '-') {
+
            break;
+
        }
+

+
        if (strncmp(arg, "-no", 3) == 0) {
+
            arg += 3;
+
            ignore = 1;
+
        }
+
        else {
+
            arg++;
+
            ignore = 0;
+
        }
+

+
        if (Jim_StringToWide(arg, &option, 10) != JIM_OK) {
+
            option = -1;
+
        }
+
        if (option < 0) {
+
            option = Jim_FindByName(arg, jimReturnCodes, jimReturnCodesSize);
+
        }
+
        if (option < 0) {
+
            goto wrongargs;
+
        }
+

+
        if (ignore) {
+
            ignore_mask |= ((jim_wide)1 << option);
+
        }
+
        else {
+
            ignore_mask &= (~((jim_wide)1 << option));
+
        }
+
    }
+

+
    argc -= i;
+
    if (argc < 1 || argc > 3) {
+
      wrongargs:
+
        Jim_WrongNumArgs(interp, 1, argv,
+
            "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
+
        return JIM_ERR;
+
    }
+
    argv += i;
+

+
    if ((ignore_mask & (1 << JIM_SIGNAL)) == 0) {
+
        sig++;
+
    }
+

+
    interp->signal_level += sig;
+
    if (Jim_CheckSignal(interp)) {
+

+
        exitCode = JIM_SIGNAL;
+
    }
+
    else {
+
        exitCode = Jim_EvalObj(interp, argv[0]);
+

+
        interp->errorFlag = 0;
+
    }
+
    interp->signal_level -= sig;
+

+

+
    if (exitCode >= 0 && exitCode < max_ignore_code && (((unsigned jim_wide)1 << exitCode) & ignore_mask)) {
+

+
        return exitCode;
+
    }
+

+
    if (sig && exitCode == JIM_SIGNAL) {
+

+
        if (interp->signal_set_result) {
+
            interp->signal_set_result(interp, interp->sigmask);
+
        }
+
        else {
+
            Jim_SetResultInt(interp, interp->sigmask);
+
        }
+
        interp->sigmask = 0;
+
    }
+

+
    if (argc >= 2) {
+
        if (Jim_SetVariable(interp, argv[1], Jim_GetResult(interp)) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        if (argc == 3) {
+
            Jim_Obj *optListObj = Jim_NewListObj(interp, NULL, 0);
+

+
            Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-code", -1));
+
            Jim_ListAppendElement(interp, optListObj,
+
                Jim_NewIntObj(interp, exitCode == JIM_RETURN ? interp->returnCode : exitCode));
+
            Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-level", -1));
+
            Jim_ListAppendElement(interp, optListObj, Jim_NewIntObj(interp, interp->returnLevel));
+
            if (exitCode == JIM_ERR) {
+
                Jim_Obj *errorCode;
+
                Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorinfo",
+
                    -1));
+
                Jim_ListAppendElement(interp, optListObj, interp->stackTrace);
+

+
                errorCode = Jim_GetGlobalVariableStr(interp, "errorCode", JIM_NONE);
+
                if (errorCode) {
+
                    Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorcode", -1));
+
                    Jim_ListAppendElement(interp, optListObj, errorCode);
+
                }
+
            }
+
            if (Jim_SetVariable(interp, argv[2], optListObj) != JIM_OK) {
+
                return JIM_ERR;
+
            }
+
        }
+
    }
+
    Jim_SetResultInt(interp, exitCode);
+
    return JIM_OK;
+
}
+

+

+

+
static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
+
        return JIM_ERR;
+
    }
+

+
    if (JimValidName(interp, "new procedure", argv[2])) {
+
        return JIM_ERR;
+
    }
+

+
    return Jim_RenameCommand(interp, Jim_String(argv[1]), Jim_String(argv[2]));
+
}
+

+
#define JIM_DICTMATCH_KEYS 0x0001
+
#define JIM_DICTMATCH_VALUES 0x002
+

+
int Jim_DictMatchTypes(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj, int match_type, int return_types)
+
{
+
    Jim_HashEntry *he;
+
    Jim_Obj *listObjPtr;
+
    Jim_HashTableIterator htiter;
+

+
    if (SetDictFromAny(interp, objPtr) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+

+
    listObjPtr = Jim_NewListObj(interp, NULL, 0);
+

+
    JimInitHashTableIterator(objPtr->internalRep.ptr, &htiter);
+
    while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+
        if (patternObj) {
+
            Jim_Obj *matchObj = (match_type == JIM_DICTMATCH_KEYS) ? (Jim_Obj *)he->key : Jim_GetHashEntryVal(he);
+
            if (!JimGlobMatch(Jim_String(patternObj), Jim_String(matchObj), 0)) {
+

+
                continue;
+
            }
+
        }
+
        if (return_types & JIM_DICTMATCH_KEYS) {
+
            Jim_ListAppendElement(interp, listObjPtr, (Jim_Obj *)he->key);
+
        }
+
        if (return_types & JIM_DICTMATCH_VALUES) {
+
            Jim_ListAppendElement(interp, listObjPtr, Jim_GetHashEntryVal(he));
+
        }
+
    }
+

+
    Jim_SetResult(interp, listObjPtr);
+
    return JIM_OK;
+
}
+

+
int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    if (SetDictFromAny(interp, objPtr) != JIM_OK) {
+
        return -1;
+
    }
+
    return ((Jim_HashTable *)objPtr->internalRep.ptr)->used;
+
}
+

+
Jim_Obj *Jim_DictMerge(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+
{
+
    Jim_Obj *objPtr = Jim_NewDictObj(interp, NULL, 0);
+
    int i;
+

+
    JimPanic((objc == 0, "Jim_DictMerge called with objc=0"));
+

+

+

+
    for (i = 0; i < objc; i++) {
+
        Jim_HashTable *ht;
+
        Jim_HashTableIterator htiter;
+
        Jim_HashEntry *he;
+

+
        if (SetDictFromAny(interp, objv[i]) != JIM_OK) {
+
            Jim_FreeNewObj(interp, objPtr);
+
            return NULL;
+
        }
+
        ht = objv[i]->internalRep.ptr;
+
        JimInitHashTableIterator(ht, &htiter);
+
        while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+
            Jim_ReplaceHashEntry(objPtr->internalRep.ptr, Jim_GetHashEntryKey(he), Jim_GetHashEntryVal(he));
+
        }
+
    }
+
    return objPtr;
+
}
+

+
int Jim_DictInfo(Jim_Interp *interp, Jim_Obj *objPtr)
+
{
+
    Jim_HashTable *ht;
+
    unsigned int i;
+
    char buffer[100];
+
    int sum = 0;
+
    int nonzero_count = 0;
+
    Jim_Obj *output;
+
    int bucket_counts[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+

+
    if (SetDictFromAny(interp, objPtr) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+

+
    ht = (Jim_HashTable *)objPtr->internalRep.ptr;
+

+

+
    snprintf(buffer, sizeof(buffer), "%d entries in table, %d buckets\n", ht->used, ht->size);
+
    output = Jim_NewStringObj(interp, buffer, -1);
+

+
    for (i = 0; i < ht->size; i++) {
+
        Jim_HashEntry *he = ht->table[i];
+
        int entries = 0;
+
        while (he) {
+
            entries++;
+
            he = he->next;
+
        }
+
        if (entries > 9) {
+
            bucket_counts[10]++;
+
        }
+
        else {
+
            bucket_counts[entries]++;
+
        }
+
        if (entries) {
+
            sum += entries;
+
            nonzero_count++;
+
        }
+
    }
+
    for (i = 0; i < 10; i++) {
+
        snprintf(buffer, sizeof(buffer), "number of buckets with %d entries: %d\n", i, bucket_counts[i]);
+
        Jim_AppendString(interp, output, buffer, -1);
+
    }
+
    snprintf(buffer, sizeof(buffer), "number of buckets with 10 or more entries: %d\n", bucket_counts[10]);
+
    Jim_AppendString(interp, output, buffer, -1);
+
    snprintf(buffer, sizeof(buffer), "average search distance for entry: %.1f", nonzero_count ? (double)sum / nonzero_count : 0.0);
+
    Jim_AppendString(interp, output, buffer, -1);
+
    Jim_SetResult(interp, output);
+
    return JIM_OK;
+
}
+

+
static int Jim_EvalEnsemble(Jim_Interp *interp, const char *basecmd, const char *subcmd, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *prefixObj = Jim_NewStringObj(interp, basecmd, -1);
+

+
    Jim_AppendString(interp, prefixObj, " ", 1);
+
    Jim_AppendString(interp, prefixObj, subcmd, -1);
+

+
    return Jim_EvalObjPrefix(interp, prefixObj, argc, argv);
+
}
+

+
static int JimDictWith(Jim_Interp *interp, Jim_Obj *dictVarName, Jim_Obj *const *keyv, int keyc, Jim_Obj *scriptObj)
+
{
+
    int i;
+
    Jim_Obj *objPtr;
+
    Jim_Obj *dictObj;
+
    Jim_Obj **dictValues;
+
    int len;
+
    int ret = JIM_OK;
+

+

+
    dictObj = Jim_GetVariable(interp, dictVarName, JIM_ERRMSG);
+
    if (dictObj == NULL || Jim_DictKeysVector(interp, dictObj, keyv, keyc, &objPtr, JIM_ERRMSG) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+

+
    if (Jim_DictPairs(interp, objPtr, &dictValues, &len) == JIM_ERR) {
+
        return JIM_ERR;
+
    }
+
    for (i = 0; i < len; i += 2) {
+
        if (Jim_SetVariable(interp, dictValues[i], dictValues[i + 1]) == JIM_ERR) {
+
            Jim_Free(dictValues);
+
            return JIM_ERR;
+
        }
+
    }
+

+

+
    if (Jim_Length(scriptObj)) {
+
        ret = Jim_EvalObj(interp, scriptObj);
+

+

+
        if (ret == JIM_OK && Jim_GetVariable(interp, dictVarName, 0) != NULL) {
+

+
            Jim_Obj **newkeyv = Jim_Alloc(sizeof(*newkeyv) * (keyc + 1));
+
            for (i = 0; i < keyc; i++) {
+
                newkeyv[i] = keyv[i];
+
            }
+

+
            for (i = 0; i < len; i += 2) {
+

+
                objPtr = Jim_GetVariable(interp, dictValues[i], 0);
+
                newkeyv[keyc] = dictValues[i];
+
                Jim_SetDictKeysVector(interp, dictVarName, newkeyv, keyc + 1, objPtr, 0);
+
            }
+
            Jim_Free(newkeyv);
+
        }
+
    }
+

+
    Jim_Free(dictValues);
+

+
    return ret;
+
}
+

+

+
static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr;
+
    int types = JIM_DICTMATCH_KEYS;
+
    int option;
+
    static const char * const options[] = {
+
        "create", "get", "set", "unset", "exists", "keys", "size", "info",
+
        "merge", "with", "append", "lappend", "incr", "remove", "values", "for",
+
        "replace", "update", NULL
+
    };
+
    enum
+
    {
+
        OPT_CREATE, OPT_GET, OPT_SET, OPT_UNSET, OPT_EXISTS, OPT_KEYS, OPT_SIZE, OPT_INFO,
+
        OPT_MERGE, OPT_WITH, OPT_APPEND, OPT_LAPPEND, OPT_INCR, OPT_REMOVE, OPT_VALUES, OPT_FOR,
+
        OPT_REPLACE, OPT_UPDATE,
+
    };
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "subcommand ?arguments ...?");
+
        return JIM_ERR;
+
    }
+

+
    if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK) {
+
        return Jim_CheckShowCommands(interp, argv[1], options);
+
    }
+

+
    switch (option) {
+
        case OPT_GET:
+
            if (argc < 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "dictionary ?key ...?");
+
                return JIM_ERR;
+
            }
+
            if (Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr,
+
                    JIM_ERRMSG) != JIM_OK) {
+
                return JIM_ERR;
+
            }
+
            Jim_SetResult(interp, objPtr);
+
            return JIM_OK;
+

+
        case OPT_SET:
+
            if (argc < 5) {
+
                Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...? value");
+
                return JIM_ERR;
+
            }
+
            return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 4, argv[argc - 1], JIM_ERRMSG);
+

+
        case OPT_EXISTS:
+
            if (argc < 4) {
+
                Jim_WrongNumArgs(interp, 2, argv, "dictionary key ?key ...?");
+
                return JIM_ERR;
+
            }
+
            else {
+
                int rc = Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr, JIM_ERRMSG);
+
                if (rc < 0) {
+
                    return JIM_ERR;
+
                }
+
                Jim_SetResultBool(interp,  rc == JIM_OK);
+
                return JIM_OK;
+
            }
+

+
        case OPT_UNSET:
+
            if (argc < 4) {
+
                Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...?");
+
                return JIM_ERR;
+
            }
+
            if (Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 3, NULL, 0) != JIM_OK) {
+
                return JIM_ERR;
+
            }
+
            return JIM_OK;
+

+
        case OPT_VALUES:
+
            types = JIM_DICTMATCH_VALUES;
+

+
        case OPT_KEYS:
+
            if (argc != 3 && argc != 4) {
+
                Jim_WrongNumArgs(interp, 2, argv, "dictionary ?pattern?");
+
                return JIM_ERR;
+
            }
+
            return Jim_DictMatchTypes(interp, argv[2], argc == 4 ? argv[3] : NULL, types, types);
+

+
        case OPT_SIZE:
+
            if (argc != 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "dictionary");
+
                return JIM_ERR;
+
            }
+
            else if (Jim_DictSize(interp, argv[2]) < 0) {
+
                return JIM_ERR;
+
            }
+
            Jim_SetResultInt(interp, Jim_DictSize(interp, argv[2]));
+
            return JIM_OK;
+

+
        case OPT_MERGE:
+
            if (argc == 2) {
+
                return JIM_OK;
+
            }
+
            objPtr = Jim_DictMerge(interp, argc - 2, argv + 2);
+
            if (objPtr == NULL) {
+
                return JIM_ERR;
+
            }
+
            Jim_SetResult(interp, objPtr);
+
            return JIM_OK;
+

+
        case OPT_UPDATE:
+
            if (argc < 6 || argc % 2) {
+

+
                argc = 2;
+
            }
+
            break;
+

+
        case OPT_CREATE:
+
            if (argc % 2) {
+
                Jim_WrongNumArgs(interp, 2, argv, "?key value ...?");
+
                return JIM_ERR;
+
            }
+
            objPtr = Jim_NewDictObj(interp, argv + 2, argc - 2);
+
            Jim_SetResult(interp, objPtr);
+
            return JIM_OK;
+

+
        case OPT_INFO:
+
            if (argc != 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "dictionary");
+
                return JIM_ERR;
+
            }
+
            return Jim_DictInfo(interp, argv[2]);
+

+
        case OPT_WITH:
+
            if (argc < 4) {
+
                Jim_WrongNumArgs(interp, 2, argv, "dictVar ?key ...? script");
+
                return JIM_ERR;
+
            }
+
            return JimDictWith(interp, argv[2], argv + 3, argc - 4, argv[argc - 1]);
+
    }
+

+
    return Jim_EvalEnsemble(interp, "dict", options[option], argc - 2, argv + 2);
+
}
+

+

+
static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    static const char * const options[] = {
+
        "-nobackslashes", "-nocommands", "-novariables", NULL
+
    };
+
    enum
+
    { OPT_NOBACKSLASHES, OPT_NOCOMMANDS, OPT_NOVARIABLES };
+
    int i;
+
    int flags = JIM_SUBST_FLAG;
+
    Jim_Obj *objPtr;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "?options? string");
+
        return JIM_ERR;
+
    }
+
    for (i = 1; i < (argc - 1); i++) {
+
        int option;
+

+
        if (Jim_GetEnum(interp, argv[i], options, &option, NULL,
+
                JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        switch (option) {
+
            case OPT_NOBACKSLASHES:
+
                flags |= JIM_SUBST_NOESC;
+
                break;
+
            case OPT_NOCOMMANDS:
+
                flags |= JIM_SUBST_NOCMD;
+
                break;
+
            case OPT_NOVARIABLES:
+
                flags |= JIM_SUBST_NOVAR;
+
                break;
+
        }
+
    }
+
    if (Jim_SubstObj(interp, argv[argc - 1], &objPtr, flags) != JIM_OK) {
+
        return JIM_ERR;
+
    }
+
    Jim_SetResult(interp, objPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int cmd;
+
    Jim_Obj *objPtr;
+
    int mode = 0;
+

+
    static const char * const commands[] = {
+
        "body", "statics", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
+
        "vars", "version", "patchlevel", "complete", "args", "hostname",
+
        "script", "source", "stacktrace", "nameofexecutable", "returncodes",
+
        "references", "alias", NULL
+
    };
+
    enum
+
    { INFO_BODY, INFO_STATICS, INFO_COMMANDS, INFO_PROCS, INFO_CHANNELS, INFO_EXISTS, INFO_GLOBALS, INFO_LEVEL,
+
        INFO_FRAME, INFO_LOCALS, INFO_VARS, INFO_VERSION, INFO_PATCHLEVEL, INFO_COMPLETE, INFO_ARGS,
+
        INFO_HOSTNAME, INFO_SCRIPT, INFO_SOURCE, INFO_STACKTRACE, INFO_NAMEOFEXECUTABLE,
+
        INFO_RETURNCODES, INFO_REFERENCES, INFO_ALIAS,
+
    };
+

+
#ifdef jim_ext_namespace
+
    int nons = 0;
+

+
    if (argc > 2 && Jim_CompareStringImmediate(interp, argv[1], "-nons")) {
+

+
        argc--;
+
        argv++;
+
        nons = 1;
+
    }
+
#endif
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "subcommand ?args ...?");
+
        return JIM_ERR;
+
    }
+
    if (Jim_GetEnum(interp, argv[1], commands, &cmd, "subcommand", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+
        return Jim_CheckShowCommands(interp, argv[1], commands);
+
    }
+

+

+
    switch (cmd) {
+
        case INFO_EXISTS:
+
            if (argc != 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "varName");
+
                return JIM_ERR;
+
            }
+
            Jim_SetResultBool(interp, Jim_GetVariable(interp, argv[2], 0) != NULL);
+
            break;
+

+
        case INFO_ALIAS:{
+
            Jim_Cmd *cmdPtr;
+

+
            if (argc != 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "command");
+
                return JIM_ERR;
+
            }
+
            if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
+
                return JIM_ERR;
+
            }
+
            if (cmdPtr->isproc || cmdPtr->u.native.cmdProc != JimAliasCmd) {
+
                Jim_SetResultFormatted(interp, "command \"%#s\" is not an alias", argv[2]);
+
                return JIM_ERR;
+
            }
+
            Jim_SetResult(interp, (Jim_Obj *)cmdPtr->u.native.privData);
+
            return JIM_OK;
+
        }
+

+
        case INFO_CHANNELS:
+
            mode++;
+
#ifndef jim_ext_aio
+
            Jim_SetResultString(interp, "aio not enabled", -1);
+
            return JIM_ERR;
+
#endif
+

+
        case INFO_PROCS:
+
            mode++;
+

+
        case INFO_COMMANDS:
+

+
            if (argc != 2 && argc != 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
+
                return JIM_ERR;
+
            }
+
#ifdef jim_ext_namespace
+
            if (!nons) {
+
                if (Jim_Length(interp->framePtr->nsObj) || (argc == 3 && JimGlobMatch("::*", Jim_String(argv[2]), 0))) {
+
                    return Jim_EvalPrefix(interp, "namespace info", argc - 1, argv + 1);
+
                }
+
            }
+
#endif
+
            Jim_SetResult(interp, JimCommandsList(interp, (argc == 3) ? argv[2] : NULL, mode));
+
            break;
+

+
        case INFO_VARS:
+
            mode++;
+

+
        case INFO_LOCALS:
+
            mode++;
+

+
        case INFO_GLOBALS:
+

+
            if (argc != 2 && argc != 3) {
+
                Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
+
                return JIM_ERR;
+
            }
+
#ifdef jim_ext_namespace
+
            if (!nons) {
+
                if (Jim_Length(interp->framePtr->nsObj) || (argc == 3 && JimGlobMatch("::*", Jim_String(argv[2]), 0))) {
+
                    return Jim_EvalPrefix(interp, "namespace info", argc - 1, argv + 1);
+
                }
+
            }
+
#endif
+
            Jim_SetResult(interp, JimVariablesList(interp, argc == 3 ? argv[2] : NULL, mode));
+
            break;
+

+
        case INFO_SCRIPT:
+
            if (argc != 2) {
+
                Jim_WrongNumArgs(interp, 2, argv, "");
+
                return JIM_ERR;
+
            }
+
            Jim_SetResult(interp, JimGetScript(interp, interp->currentScriptObj)->fileNameObj);
+
            break;
+

+
        case INFO_SOURCE:{
+
                jim_wide line;
+
                Jim_Obj *resObjPtr;
+
                Jim_Obj *fileNameObj;
+

+
                if (argc != 3 && argc != 5) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "source ?filename line?");
+
                    return JIM_ERR;
+
                }
+
                if (argc == 5) {
+
                    if (Jim_GetWide(interp, argv[4], &line) != JIM_OK) {
+
                        return JIM_ERR;
+
                    }
+
                    resObjPtr = Jim_NewStringObj(interp, Jim_String(argv[2]), Jim_Length(argv[2]));
+
                    JimSetSourceInfo(interp, resObjPtr, argv[3], line);
+
                }
+
                else {
+
                    if (argv[2]->typePtr == &sourceObjType) {
+
                        fileNameObj = argv[2]->internalRep.sourceValue.fileNameObj;
+
                        line = argv[2]->internalRep.sourceValue.lineNumber;
+
                    }
+
                    else if (argv[2]->typePtr == &scriptObjType) {
+
                        ScriptObj *script = JimGetScript(interp, argv[2]);
+
                        fileNameObj = script->fileNameObj;
+
                        line = script->firstline;
+
                    }
+
                    else {
+
                        fileNameObj = interp->emptyObj;
+
                        line = 1;
+
                    }
+
                    resObjPtr = Jim_NewListObj(interp, NULL, 0);
+
                    Jim_ListAppendElement(interp, resObjPtr, fileNameObj);
+
                    Jim_ListAppendElement(interp, resObjPtr, Jim_NewIntObj(interp, line));
+
                }
+
                Jim_SetResult(interp, resObjPtr);
+
                break;
+
            }
+

+
        case INFO_STACKTRACE:
+
            Jim_SetResult(interp, interp->stackTrace);
+
            break;
+

+
        case INFO_LEVEL:
+
        case INFO_FRAME:
+
            switch (argc) {
+
                case 2:
+
                    Jim_SetResultInt(interp, interp->framePtr->level);
+
                    break;
+

+
                case 3:
+
                    if (JimInfoLevel(interp, argv[2], &objPtr, cmd == INFO_LEVEL) != JIM_OK) {
+
                        return JIM_ERR;
+
                    }
+
                    Jim_SetResult(interp, objPtr);
+
                    break;
+

+
                default:
+
                    Jim_WrongNumArgs(interp, 2, argv, "?levelNum?");
+
                    return JIM_ERR;
+
            }
+
            break;
+

+
        case INFO_BODY:
+
        case INFO_STATICS:
+
        case INFO_ARGS:{
+
                Jim_Cmd *cmdPtr;
+

+
                if (argc != 3) {
+
                    Jim_WrongNumArgs(interp, 2, argv, "procname");
+
                    return JIM_ERR;
+
                }
+
                if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
+
                    return JIM_ERR;
+
                }
+
                if (!cmdPtr->isproc) {
+
                    Jim_SetResultFormatted(interp, "command \"%#s\" is not a procedure", argv[2]);
+
                    return JIM_ERR;
+
                }
+
                switch (cmd) {
+
                    case INFO_BODY:
+
                        Jim_SetResult(interp, cmdPtr->u.proc.bodyObjPtr);
+
                        break;
+
                    case INFO_ARGS:
+
                        Jim_SetResult(interp, cmdPtr->u.proc.argListObjPtr);
+
                        break;
+
                    case INFO_STATICS:
+
                        if (cmdPtr->u.proc.staticVars) {
+
                            Jim_SetResult(interp, JimHashtablePatternMatch(interp, cmdPtr->u.proc.staticVars,
+
                                NULL, JimVariablesMatch, JIM_VARLIST_LOCALS | JIM_VARLIST_VALUES));
+
                        }
+
                        break;
+
                }
+
                break;
+
            }
+

+
        case INFO_VERSION:
+
        case INFO_PATCHLEVEL:{
+
                char buf[(JIM_INTEGER_SPACE * 2) + 1];
+

+
                sprintf(buf, "%d.%d", JIM_VERSION / 100, JIM_VERSION % 100);
+
                Jim_SetResultString(interp, buf, -1);
+
                break;
+
            }
+

+
        case INFO_COMPLETE:
+
            if (argc != 3 && argc != 4) {
+
                Jim_WrongNumArgs(interp, 2, argv, "script ?missing?");
+
                return JIM_ERR;
+
            }
+
            else {
+
                char missing;
+

+
                Jim_SetResultBool(interp, Jim_ScriptIsComplete(interp, argv[2], &missing));
+
                if (missing != ' ' && argc == 4) {
+
                    Jim_SetVariable(interp, argv[3], Jim_NewStringObj(interp, &missing, 1));
+
                }
+
            }
+
            break;
+

+
        case INFO_HOSTNAME:
+

+
            return Jim_Eval(interp, "os.gethostname");
+

+
        case INFO_NAMEOFEXECUTABLE:
+

+
            return Jim_Eval(interp, "{info nameofexecutable}");
+

+
        case INFO_RETURNCODES:
+
            if (argc == 2) {
+
                int i;
+
                Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
+

+
                for (i = 0; jimReturnCodes[i]; i++) {
+
                    Jim_ListAppendElement(interp, listObjPtr, Jim_NewIntObj(interp, i));
+
                    Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp,
+
                            jimReturnCodes[i], -1));
+
                }
+

+
                Jim_SetResult(interp, listObjPtr);
+
            }
+
            else if (argc == 3) {
+
                long code;
+
                const char *name;
+

+
                if (Jim_GetLong(interp, argv[2], &code) != JIM_OK) {
+
                    return JIM_ERR;
+
                }
+
                name = Jim_ReturnCode(code);
+
                if (*name == '?') {
+
                    Jim_SetResultInt(interp, code);
+
                }
+
                else {
+
                    Jim_SetResultString(interp, name, -1);
+
                }
+
            }
+
            else {
+
                Jim_WrongNumArgs(interp, 2, argv, "?code?");
+
                return JIM_ERR;
+
            }
+
            break;
+
        case INFO_REFERENCES:
+
#ifdef JIM_REFERENCES
+
            return JimInfoReferences(interp, argc, argv);
+
#else
+
            Jim_SetResultString(interp, "not supported", -1);
+
            return JIM_ERR;
+
#endif
+
    }
+
    return JIM_OK;
+
}
+

+

+
static int Jim_ExistsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr;
+
    int result = 0;
+

+
    static const char * const options[] = {
+
        "-command", "-proc", "-alias", "-var", NULL
+
    };
+
    enum
+
    {
+
        OPT_COMMAND, OPT_PROC, OPT_ALIAS, OPT_VAR
+
    };
+
    int option;
+

+
    if (argc == 2) {
+
        option = OPT_VAR;
+
        objPtr = argv[1];
+
    }
+
    else if (argc == 3) {
+
        if (Jim_GetEnum(interp, argv[1], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+
            return JIM_ERR;
+
        }
+
        objPtr = argv[2];
+
    }
+
    else {
+
        Jim_WrongNumArgs(interp, 1, argv, "?option? name");
+
        return JIM_ERR;
+
    }
+

+
    if (option == OPT_VAR) {
+
        result = Jim_GetVariable(interp, objPtr, 0) != NULL;
+
    }
+
    else {
+

+
        Jim_Cmd *cmd = Jim_GetCommand(interp, objPtr, JIM_NONE);
+

+
        if (cmd) {
+
            switch (option) {
+
            case OPT_COMMAND:
+
                result = 1;
+
                break;
+

+
            case OPT_ALIAS:
+
                result = cmd->isproc == 0 && cmd->u.native.cmdProc == JimAliasCmd;
+
                break;
+

+
            case OPT_PROC:
+
                result = cmd->isproc;
+
                break;
+
            }
+
        }
+
    }
+
    Jim_SetResultBool(interp, result);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *str, *splitChars, *noMatchStart;
+
    int splitLen, strLen;
+
    Jim_Obj *resObjPtr;
+
    int c;
+
    int len;
+

+
    if (argc != 2 && argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
+
        return JIM_ERR;
+
    }
+

+
    str = Jim_GetString(argv[1], &len);
+
    if (len == 0) {
+
        return JIM_OK;
+
    }
+
    strLen = Jim_Utf8Length(interp, argv[1]);
+

+

+
    if (argc == 2) {
+
        splitChars = " \n\t\r";
+
        splitLen = 4;
+
    }
+
    else {
+
        splitChars = Jim_String(argv[2]);
+
        splitLen = Jim_Utf8Length(interp, argv[2]);
+
    }
+

+
    noMatchStart = str;
+
    resObjPtr = Jim_NewListObj(interp, NULL, 0);
+

+

+
    if (splitLen) {
+
        Jim_Obj *objPtr;
+
        while (strLen--) {
+
            const char *sc = splitChars;
+
            int scLen = splitLen;
+
            int sl = utf8_tounicode(str, &c);
+
            while (scLen--) {
+
                int pc;
+
                sc += utf8_tounicode(sc, &pc);
+
                if (c == pc) {
+
                    objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
+
                    Jim_ListAppendElement(interp, resObjPtr, objPtr);
+
                    noMatchStart = str + sl;
+
                    break;
+
                }
+
            }
+
            str += sl;
+
        }
+
        objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
+
        Jim_ListAppendElement(interp, resObjPtr, objPtr);
+
    }
+
    else {
+
        Jim_Obj **commonObj = NULL;
+
#define NUM_COMMON (128 - 9)
+
        while (strLen--) {
+
            int n = utf8_tounicode(str, &c);
+
#ifdef JIM_OPTIMIZATION
+
            if (c >= 9 && c < 128) {
+

+
                c -= 9;
+
                if (!commonObj) {
+
                    commonObj = Jim_Alloc(sizeof(*commonObj) * NUM_COMMON);
+
                    memset(commonObj, 0, sizeof(*commonObj) * NUM_COMMON);
+
                }
+
                if (!commonObj[c]) {
+
                    commonObj[c] = Jim_NewStringObj(interp, str, 1);
+
                }
+
                Jim_ListAppendElement(interp, resObjPtr, commonObj[c]);
+
                str++;
+
                continue;
+
            }
+
#endif
+
            Jim_ListAppendElement(interp, resObjPtr, Jim_NewStringObjUtf8(interp, str, 1));
+
            str += n;
+
        }
+
        Jim_Free(commonObj);
+
    }
+

+
    Jim_SetResult(interp, resObjPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *joinStr;
+
    int joinStrLen;
+

+
    if (argc != 2 && argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
+
        return JIM_ERR;
+
    }
+

+
    if (argc == 2) {
+
        joinStr = " ";
+
        joinStrLen = 1;
+
    }
+
    else {
+
        joinStr = Jim_GetString(argv[2], &joinStrLen);
+
    }
+
    Jim_SetResult(interp, Jim_ListJoin(interp, argv[1], joinStr, joinStrLen));
+
    return JIM_OK;
+
}
+

+

+
static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr;
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
+
        return JIM_ERR;
+
    }
+
    objPtr = Jim_FormatString(interp, argv[1], argc - 2, argv + 2);
+
    if (objPtr == NULL)
+
        return JIM_ERR;
+
    Jim_SetResult(interp, objPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *listPtr, **outVec;
+
    int outc, i;
+

+
    if (argc < 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "string format ?varName varName ...?");
+
        return JIM_ERR;
+
    }
+
    if (argv[2]->typePtr != &scanFmtStringObjType)
+
        SetScanFmtFromAny(interp, argv[2]);
+
    if (FormatGetError(argv[2]) != 0) {
+
        Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
+
        return JIM_ERR;
+
    }
+
    if (argc > 3) {
+
        int maxPos = FormatGetMaxPos(argv[2]);
+
        int count = FormatGetCnvCount(argv[2]);
+

+
        if (maxPos > argc - 3) {
+
            Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
+
            return JIM_ERR;
+
        }
+
        else if (count > argc - 3) {
+
            Jim_SetResultString(interp, "different numbers of variable names and "
+
                "field specifiers", -1);
+
            return JIM_ERR;
+
        }
+
        else if (count < argc - 3) {
+
            Jim_SetResultString(interp, "variable is not assigned by any "
+
                "conversion specifiers", -1);
+
            return JIM_ERR;
+
        }
+
    }
+
    listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
+
    if (listPtr == 0)
+
        return JIM_ERR;
+
    if (argc > 3) {
+
        int rc = JIM_OK;
+
        int count = 0;
+

+
        if (listPtr != 0 && listPtr != (Jim_Obj *)EOF) {
+
            int len = Jim_ListLength(interp, listPtr);
+

+
            if (len != 0) {
+
                JimListGetElements(interp, listPtr, &outc, &outVec);
+
                for (i = 0; i < outc; ++i) {
+
                    if (Jim_Length(outVec[i]) > 0) {
+
                        ++count;
+
                        if (Jim_SetVariable(interp, argv[3 + i], outVec[i]) != JIM_OK) {
+
                            rc = JIM_ERR;
+
                        }
+
                    }
+
                }
+
            }
+
            Jim_FreeNewObj(interp, listPtr);
+
        }
+
        else {
+
            count = -1;
+
        }
+
        if (rc == JIM_OK) {
+
            Jim_SetResultInt(interp, count);
+
        }
+
        return rc;
+
    }
+
    else {
+
        if (listPtr == (Jim_Obj *)EOF) {
+
            Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
+
            return JIM_OK;
+
        }
+
        Jim_SetResult(interp, listPtr);
+
    }
+
    return JIM_OK;
+
}
+

+

+
static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    if (argc != 2 && argc != 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "message ?stacktrace?");
+
        return JIM_ERR;
+
    }
+
    Jim_SetResult(interp, argv[1]);
+
    if (argc == 3) {
+
        JimSetStackTrace(interp, argv[2]);
+
        return JIM_ERR;
+
    }
+
    interp->addStackTrace++;
+
    return JIM_ERR;
+
}
+

+

+
static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr;
+

+
    if (argc != 4) {
+
        Jim_WrongNumArgs(interp, 1, argv, "list first last");
+
        return JIM_ERR;
+
    }
+
    if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
+
        return JIM_ERR;
+
    Jim_SetResult(interp, objPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_LrepeatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *objPtr;
+
    long count;
+

+
    if (argc < 2 || Jim_GetLong(interp, argv[1], &count) != JIM_OK || count < 0) {
+
        Jim_WrongNumArgs(interp, 1, argv, "count ?value ...?");
+
        return JIM_ERR;
+
    }
+

+
    if (count == 0 || argc == 2) {
+
        return JIM_OK;
+
    }
+

+
    argc -= 2;
+
    argv += 2;
+

+
    objPtr = Jim_NewListObj(interp, argv, argc);
+
    while (--count) {
+
        ListInsertElements(objPtr, -1, argc, argv);
+
    }
+

+
    Jim_SetResult(interp, objPtr);
+
    return JIM_OK;
+
}
+

+
char **Jim_GetEnviron(void)
+
{
+
#if defined(HAVE__NSGETENVIRON)
+
    return *_NSGetEnviron();
+
#else
+
    #if !defined(NO_ENVIRON_EXTERN)
+
    extern char **environ;
+
    #endif
+

+
    return environ;
+
#endif
+
}
+

+
void Jim_SetEnviron(char **env)
+
{
+
#if defined(HAVE__NSGETENVIRON)
+
    *_NSGetEnviron() = env;
+
#else
+
    #if !defined(NO_ENVIRON_EXTERN)
+
    extern char **environ;
+
    #endif
+

+
    environ = env;
+
#endif
+
}
+

+

+
static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const char *key;
+
    const char *val;
+

+
    if (argc == 1) {
+
        char **e = Jim_GetEnviron();
+

+
        int i;
+
        Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
+

+
        for (i = 0; e[i]; i++) {
+
            const char *equals = strchr(e[i], '=');
+

+
            if (equals) {
+
                Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, e[i],
+
                        equals - e[i]));
+
                Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, equals + 1, -1));
+
            }
+
        }
+

+
        Jim_SetResult(interp, listObjPtr);
+
        return JIM_OK;
+
    }
+

+
    if (argc < 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "varName ?default?");
+
        return JIM_ERR;
+
    }
+
    key = Jim_String(argv[1]);
+
    val = getenv(key);
+
    if (val == NULL) {
+
        if (argc < 3) {
+
            Jim_SetResultFormatted(interp, "environment variable \"%#s\" does not exist", argv[1]);
+
            return JIM_ERR;
+
        }
+
        val = Jim_String(argv[2]);
+
    }
+
    Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
+
    return JIM_OK;
+
}
+

+

+
static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    int retval;
+

+
    if (argc != 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "fileName");
+
        return JIM_ERR;
+
    }
+
    retval = Jim_EvalFile(interp, Jim_String(argv[1]));
+
    if (retval == JIM_RETURN)
+
        return JIM_OK;
+
    return retval;
+
}
+

+

+
static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    Jim_Obj *revObjPtr, **ele;
+
    int len;
+

+
    if (argc != 2) {
+
        Jim_WrongNumArgs(interp, 1, argv, "list");
+
        return JIM_ERR;
+
    }
+
    JimListGetElements(interp, argv[1], &len, &ele);
+
    len--;
+
    revObjPtr = Jim_NewListObj(interp, NULL, 0);
+
    while (len >= 0)
+
        ListAppendElement(revObjPtr, ele[len--]);
+
    Jim_SetResult(interp, revObjPtr);
+
    return JIM_OK;
+
}
+

+
static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
+
{
+
    jim_wide len;
+

+
    if (step == 0)
+
        return -1;
+
    if (start == end)
+
        return 0;
+
    else if (step > 0 && start > end)
+
        return -1;
+
    else if (step < 0 && end > start)
+
        return -1;
+
    len = end - start;
+
    if (len < 0)
+
        len = -len;
+
    if (step < 0)
+
        step = -step;
+
    len = 1 + ((len - 1) / step);
+
    if (len > INT_MAX)
+
        len = INT_MAX;
+
    return (int)((len < 0) ? -1 : len);
+
}
+

+

+
static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    jim_wide start = 0, end, step = 1;
+
    int len, i;
+
    Jim_Obj *objPtr;
+

+
    if (argc < 2 || argc > 4) {
+
        Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
+
        return JIM_ERR;
+
    }
+
    if (argc == 2) {
+
        if (Jim_GetWide(interp, argv[1], &end) != JIM_OK)
+
            return JIM_ERR;
+
    }
+
    else {
+
        if (Jim_GetWide(interp, argv[1], &start) != JIM_OK ||
+
            Jim_GetWide(interp, argv[2], &end) != JIM_OK)
+
            return JIM_ERR;
+
        if (argc == 4 && Jim_GetWide(interp, argv[3], &step) != JIM_OK)
+
            return JIM_ERR;
+
    }
+
    if ((len = JimRangeLen(start, end, step)) == -1) {
+
        Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
+
        return JIM_ERR;
+
    }
+
    objPtr = Jim_NewListObj(interp, NULL, 0);
+
    for (i = 0; i < len; i++)
+
        ListAppendElement(objPtr, Jim_NewIntObj(interp, start + i * step));
+
    Jim_SetResult(interp, objPtr);
+
    return JIM_OK;
+
}
+

+

+
static int Jim_RandCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    jim_wide min = 0, max = 0, len, maxMul;
+

+
    if (argc < 1 || argc > 3) {
+
        Jim_WrongNumArgs(interp, 1, argv, "?min? max");
+
        return JIM_ERR;
+
    }
+
    if (argc == 1) {
+
        max = JIM_WIDE_MAX;
+
    } else if (argc == 2) {
+
        if (Jim_GetWide(interp, argv[1], &max) != JIM_OK)
+
            return JIM_ERR;
+
    } else if (argc == 3) {
+
        if (Jim_GetWide(interp, argv[1], &min) != JIM_OK ||
+
            Jim_GetWide(interp, argv[2], &max) != JIM_OK)
+
            return JIM_ERR;
+
    }
+
    len = max-min;
+
    if (len < 0) {
+
        Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
+
        return JIM_ERR;
+
    }
+
    maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
+
    while (1) {
+
        jim_wide r;
+

+
        JimRandomBytes(interp, &r, sizeof(jim_wide));
+
        if (r < 0 || r >= maxMul) continue;
+
        r = (len == 0) ? 0 : r%len;
+
        Jim_SetResultInt(interp, min+r);
+
        return JIM_OK;
+
    }
+
}
+

+
static const struct {
+
    const char *name;
+
    Jim_CmdProc *cmdProc;
+
} Jim_CoreCommandsTable[] = {
+
    {"alias", Jim_AliasCoreCommand},
+
    {"set", Jim_SetCoreCommand},
+
    {"unset", Jim_UnsetCoreCommand},
+
    {"puts", Jim_PutsCoreCommand},
+
    {"+", Jim_AddCoreCommand},
+
    {"*", Jim_MulCoreCommand},
+
    {"-", Jim_SubCoreCommand},
+
    {"/", Jim_DivCoreCommand},
+
    {"incr", Jim_IncrCoreCommand},
+
    {"while", Jim_WhileCoreCommand},
+
    {"loop", Jim_LoopCoreCommand},
+
    {"for", Jim_ForCoreCommand},
+
    {"foreach", Jim_ForeachCoreCommand},
+
    {"lmap", Jim_LmapCoreCommand},
+
    {"lassign", Jim_LassignCoreCommand},
+
    {"if", Jim_IfCoreCommand},
+
    {"switch", Jim_SwitchCoreCommand},
+
    {"list", Jim_ListCoreCommand},
+
    {"lindex", Jim_LindexCoreCommand},
+
    {"lset", Jim_LsetCoreCommand},
+
    {"lsearch", Jim_LsearchCoreCommand},
+
    {"llength", Jim_LlengthCoreCommand},
+
    {"lappend", Jim_LappendCoreCommand},
+
    {"linsert", Jim_LinsertCoreCommand},
+
    {"lreplace", Jim_LreplaceCoreCommand},
+
    {"lsort", Jim_LsortCoreCommand},
+
    {"append", Jim_AppendCoreCommand},
+
    {"debug", Jim_DebugCoreCommand},
+
    {"eval", Jim_EvalCoreCommand},
+
    {"uplevel", Jim_UplevelCoreCommand},
+
    {"expr", Jim_ExprCoreCommand},
+
    {"break", Jim_BreakCoreCommand},
+
    {"continue", Jim_ContinueCoreCommand},
+
    {"proc", Jim_ProcCoreCommand},
+
    {"concat", Jim_ConcatCoreCommand},
+
    {"return", Jim_ReturnCoreCommand},
+
    {"upvar", Jim_UpvarCoreCommand},
+
    {"global", Jim_GlobalCoreCommand},
+
    {"string", Jim_StringCoreCommand},
+
    {"time", Jim_TimeCoreCommand},
+
    {"exit", Jim_ExitCoreCommand},
+
    {"catch", Jim_CatchCoreCommand},
+
#ifdef JIM_REFERENCES
+
    {"ref", Jim_RefCoreCommand},
+
    {"getref", Jim_GetrefCoreCommand},
+
    {"setref", Jim_SetrefCoreCommand},
+
    {"finalize", Jim_FinalizeCoreCommand},
+
    {"collect", Jim_CollectCoreCommand},
+
#endif
+
    {"rename", Jim_RenameCoreCommand},
+
    {"dict", Jim_DictCoreCommand},
+
    {"subst", Jim_SubstCoreCommand},
+
    {"info", Jim_InfoCoreCommand},
+
    {"exists", Jim_ExistsCoreCommand},
+
    {"split", Jim_SplitCoreCommand},
+
    {"join", Jim_JoinCoreCommand},
+
    {"format", Jim_FormatCoreCommand},
+
    {"scan", Jim_ScanCoreCommand},
+
    {"error", Jim_ErrorCoreCommand},
+
    {"lrange", Jim_LrangeCoreCommand},
+
    {"lrepeat", Jim_LrepeatCoreCommand},
+
    {"env", Jim_EnvCoreCommand},
+
    {"source", Jim_SourceCoreCommand},
+
    {"lreverse", Jim_LreverseCoreCommand},
+
    {"range", Jim_RangeCoreCommand},
+
    {"rand", Jim_RandCoreCommand},
+
    {"tailcall", Jim_TailcallCoreCommand},
+
    {"local", Jim_LocalCoreCommand},
+
    {"upcall", Jim_UpcallCoreCommand},
+
    {"apply", Jim_ApplyCoreCommand},
+
    {NULL, NULL},
+
};
+

+
void Jim_RegisterCoreCommands(Jim_Interp *interp)
+
{
+
    int i = 0;
+

+
    while (Jim_CoreCommandsTable[i].name != NULL) {
+
        Jim_CreateCommand(interp,
+
            Jim_CoreCommandsTable[i].name, Jim_CoreCommandsTable[i].cmdProc, NULL, NULL);
+
        i++;
+
    }
+
}
+

+
void Jim_MakeErrorMessage(Jim_Interp *interp)
+
{
+
    Jim_Obj *argv[2];
+

+
    argv[0] = Jim_NewStringObj(interp, "errorInfo", -1);
+
    argv[1] = interp->result;
+

+
    Jim_EvalObjVector(interp, 2, argv);
+
}
+

+
static char **JimSortStringTable(const char *const *tablePtr)
+
{
+
    int count;
+
    char **tablePtrSorted;
+

+

+
    for (count = 0; tablePtr[count]; count++) {
+
    }
+

+

+
    tablePtrSorted = Jim_Alloc(sizeof(char *) * (count + 1));
+
    memcpy(tablePtrSorted, tablePtr, sizeof(char *) * count);
+
    qsort(tablePtrSorted, count, sizeof(char *), qsortCompareStringPointers);
+
    tablePtrSorted[count] = NULL;
+

+
    return tablePtrSorted;
+
}
+

+
static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
+
    const char *prefix, const char *const *tablePtr, const char *name)
+
{
+
    char **tablePtrSorted;
+
    int i;
+

+
    if (name == NULL) {
+
        name = "option";
+
    }
+

+
    Jim_SetResultFormatted(interp, "%s%s \"%s\": must be ", badtype, name, arg);
+
    tablePtrSorted = JimSortStringTable(tablePtr);
+
    for (i = 0; tablePtrSorted[i]; i++) {
+
        if (tablePtrSorted[i + 1] == NULL && i > 0) {
+
            Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
+
        }
+
        Jim_AppendStrings(interp, Jim_GetResult(interp), prefix, tablePtrSorted[i], NULL);
+
        if (tablePtrSorted[i + 1]) {
+
            Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
+
        }
+
    }
+
    Jim_Free(tablePtrSorted);
+
}
+

+

+
int Jim_CheckShowCommands(Jim_Interp *interp, Jim_Obj *objPtr, const char *const *tablePtr)
+
{
+
    if (Jim_CompareStringImmediate(interp, objPtr, "-commands")) {
+
        int i;
+
        char **tablePtrSorted = JimSortStringTable(tablePtr);
+
        Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
+
        for (i = 0; tablePtrSorted[i]; i++) {
+
            Jim_ListAppendElement(interp, Jim_GetResult(interp), Jim_NewStringObj(interp, tablePtrSorted[i], -1));
+
        }
+
        Jim_Free(tablePtrSorted);
+
        return JIM_OK;
+
    }
+
    return JIM_ERR;
+
}
+

+
int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
+
    const char *const *tablePtr, int *indexPtr, const char *name, int flags)
+
{
+
    const char *bad = "bad ";
+
    const char *const *entryPtr = NULL;
+
    int i;
+
    int match = -1;
+
    int arglen;
+
    const char *arg = Jim_GetString(objPtr, &arglen);
+

+
    *indexPtr = -1;
+

+
    for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
+
        if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
+

+
            *indexPtr = i;
+
            return JIM_OK;
+
        }
+
        if (flags & JIM_ENUM_ABBREV) {
+
            if (strncmp(arg, *entryPtr, arglen) == 0) {
+
                if (*arg == '-' && arglen == 1) {
+
                    break;
+
                }
+
                if (match >= 0) {
+
                    bad = "ambiguous ";
+
                    goto ambiguous;
+
                }
+
                match = i;
+
            }
+
        }
+
    }
+

+

+
    if (match >= 0) {
+
        *indexPtr = match;
+
        return JIM_OK;
+
    }
+

+
  ambiguous:
+
    if (flags & JIM_ERRMSG) {
+
        JimSetFailedEnumResult(interp, arg, bad, "", tablePtr, name);
+
    }
+
    return JIM_ERR;
+
}
+

+
int Jim_FindByName(const char *name, const char * const array[], size_t len)
+
{
+
    int i;
+

+
    for (i = 0; i < (int)len; i++) {
+
        if (array[i] && strcmp(array[i], name) == 0) {
+
            return i;
+
        }
+
    }
+
    return -1;
+
}
+

+
int Jim_IsDict(Jim_Obj *objPtr)
+
{
+
    return objPtr->typePtr == &dictObjType;
+
}
+

+
int Jim_IsList(Jim_Obj *objPtr)
+
{
+
    return objPtr->typePtr == &listObjType;
+
}
+

+
void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...)
+
{
+

+
    int len = strlen(format);
+
    int extra = 0;
+
    int n = 0;
+
    const char *params[5];
+
    int nobjparam = 0;
+
    Jim_Obj *objparam[5];
+
    char *buf;
+
    va_list args;
+
    int i;
+

+
    va_start(args, format);
+

+
    for (i = 0; i < len && n < 5; i++) {
+
        int l;
+

+
        if (strncmp(format + i, "%s", 2) == 0) {
+
            params[n] = va_arg(args, char *);
+

+
            l = strlen(params[n]);
+
        }
+
        else if (strncmp(format + i, "%#s", 3) == 0) {
+
            Jim_Obj *objPtr = va_arg(args, Jim_Obj *);
+

+
            params[n] = Jim_GetString(objPtr, &l);
+
            objparam[nobjparam++] = objPtr;
+
            Jim_IncrRefCount(objPtr);
+
        }
+
        else {
+
            if (format[i] == '%') {
+
                i++;
+
            }
+
            continue;
+
        }
+
        n++;
+
        extra += l;
+
    }
+

+
    len += extra;
+
    buf = Jim_Alloc(len + 1);
+
    len = snprintf(buf, len + 1, format, params[0], params[1], params[2], params[3], params[4]);
+

+
    va_end(args);
+

+
    Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
+

+
    for (i = 0; i < nobjparam; i++) {
+
        Jim_DecrRefCount(interp, objparam[i]);
+
    }
+
}
+

+

+
#ifndef jim_ext_package
+
int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver, int flags)
+
{
+
    return JIM_OK;
+
}
+
#endif
+
#ifndef jim_ext_aio
+
FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *fhObj)
+
{
+
    Jim_SetResultString(interp, "aio not enabled", -1);
+
    return NULL;
+
}
+
#endif
+

+

+
#include <stdio.h>
+
#include <string.h>
+

+

+
static int subcmd_null(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+

+
    return JIM_OK;
+
}
+

+
static const jim_subcmd_type dummy_subcmd = {
+
    "dummy", NULL, subcmd_null, 0, 0, JIM_MODFLAG_HIDDEN
+
};
+

+
static void add_commands(Jim_Interp *interp, const jim_subcmd_type * ct, const char *sep)
+
{
+
    const char *s = "";
+

+
    for (; ct->cmd; ct++) {
+
        if (!(ct->flags & JIM_MODFLAG_HIDDEN)) {
+
            Jim_AppendStrings(interp, Jim_GetResult(interp), s, ct->cmd, NULL);
+
            s = sep;
+
        }
+
    }
+
}
+

+
static void bad_subcmd(Jim_Interp *interp, const jim_subcmd_type * command_table, const char *type,
+
    Jim_Obj *cmd, Jim_Obj *subcmd)
+
{
+
    Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+
    Jim_AppendStrings(interp, Jim_GetResult(interp), Jim_String(cmd), ", ", type,
+
        " command \"", Jim_String(subcmd), "\": should be ", NULL);
+
    add_commands(interp, command_table, ", ");
+
}
+

+
static void show_cmd_usage(Jim_Interp *interp, const jim_subcmd_type * command_table, int argc,
+
    Jim_Obj *const *argv)
+
{
+
    Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+
    Jim_AppendStrings(interp, Jim_GetResult(interp), "Usage: \"", Jim_String(argv[0]),
+
        " command ... \", where command is one of: ", NULL);
+
    add_commands(interp, command_table, ", ");
+
}
+

+
static void add_cmd_usage(Jim_Interp *interp, const jim_subcmd_type * ct, Jim_Obj *cmd)
+
{
+
    if (cmd) {
+
        Jim_AppendStrings(interp, Jim_GetResult(interp), Jim_String(cmd), " ", NULL);
+
    }
+
    Jim_AppendStrings(interp, Jim_GetResult(interp), ct->cmd, NULL);
+
    if (ct->args && *ct->args) {
+
        Jim_AppendStrings(interp, Jim_GetResult(interp), " ", ct->args, NULL);
+
    }
+
}
+

+
static void set_wrong_args(Jim_Interp *interp, const jim_subcmd_type * command_table, Jim_Obj *subcmd)
+
{
+
    Jim_SetResultString(interp, "wrong # args: should be \"", -1);
+
    add_cmd_usage(interp, command_table, subcmd);
+
    Jim_AppendStrings(interp, Jim_GetResult(interp), "\"", NULL);
+
}
+

+
const jim_subcmd_type *Jim_ParseSubCmd(Jim_Interp *interp, const jim_subcmd_type * command_table,
+
    int argc, Jim_Obj *const *argv)
+
{
+
    const jim_subcmd_type *ct;
+
    const jim_subcmd_type *partial = 0;
+
    int cmdlen;
+
    Jim_Obj *cmd;
+
    const char *cmdstr;
+
    const char *cmdname;
+
    int help = 0;
+

+
    cmdname = Jim_String(argv[0]);
+

+
    if (argc < 2) {
+
        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+
        Jim_AppendStrings(interp, Jim_GetResult(interp), "wrong # args: should be \"", cmdname,
+
            " command ...\"\n", NULL);
+
        Jim_AppendStrings(interp, Jim_GetResult(interp), "Use \"", cmdname, " -help ?command?\" for help", NULL);
+
        return 0;
+
    }
+

+
    cmd = argv[1];
+

+

+
    if (Jim_CompareStringImmediate(interp, cmd, "-help")) {
+
        if (argc == 2) {
+

+
            show_cmd_usage(interp, command_table, argc, argv);
+
            return &dummy_subcmd;
+
        }
+
        help = 1;
+

+

+
        cmd = argv[2];
+
    }
+

+

+
    if (Jim_CompareStringImmediate(interp, cmd, "-commands")) {
+

+
        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+
        add_commands(interp, command_table, " ");
+
        return &dummy_subcmd;
+
    }
+

+
    cmdstr = Jim_GetString(cmd, &cmdlen);
+

+
    for (ct = command_table; ct->cmd; ct++) {
+
        if (Jim_CompareStringImmediate(interp, cmd, ct->cmd)) {
+

+
            break;
+
        }
+
        if (strncmp(cmdstr, ct->cmd, cmdlen) == 0) {
+
            if (partial) {
+

+
                if (help) {
+

+
                    show_cmd_usage(interp, command_table, argc, argv);
+
                    return &dummy_subcmd;
+
                }
+
                bad_subcmd(interp, command_table, "ambiguous", argv[0], argv[1 + help]);
+
                return 0;
+
            }
+
            partial = ct;
+
        }
+
        continue;
+
    }
+

+

+
    if (partial && !ct->cmd) {
+
        ct = partial;
+
    }
+

+
    if (!ct->cmd) {
+

+
        if (help) {
+

+
            show_cmd_usage(interp, command_table, argc, argv);
+
            return &dummy_subcmd;
+
        }
+
        bad_subcmd(interp, command_table, "unknown", argv[0], argv[1 + help]);
+
        return 0;
+
    }
+

+
    if (help) {
+
        Jim_SetResultString(interp, "Usage: ", -1);
+

+
        add_cmd_usage(interp, ct, argv[0]);
+
        return &dummy_subcmd;
+
    }
+

+

+
    if (argc - 2 < ct->minargs || (ct->maxargs >= 0 && argc - 2 > ct->maxargs)) {
+
        Jim_SetResultString(interp, "wrong # args: should be \"", -1);
+

+
        add_cmd_usage(interp, ct, argv[0]);
+
        Jim_AppendStrings(interp, Jim_GetResult(interp), "\"", NULL);
+

+
        return 0;
+
    }
+

+

+
    return ct;
+
}
+

+
int Jim_CallSubCmd(Jim_Interp *interp, const jim_subcmd_type * ct, int argc, Jim_Obj *const *argv)
+
{
+
    int ret = JIM_ERR;
+

+
    if (ct) {
+
        if (ct->flags & JIM_MODFLAG_FULLARGV) {
+
            ret = ct->function(interp, argc, argv);
+
        }
+
        else {
+
            ret = ct->function(interp, argc - 2, argv + 2);
+
        }
+
        if (ret < 0) {
+
            set_wrong_args(interp, ct, argv[0]);
+
            ret = JIM_ERR;
+
        }
+
    }
+
    return ret;
+
}
+

+
int Jim_SubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+
{
+
    const jim_subcmd_type *ct =
+
        Jim_ParseSubCmd(interp, (const jim_subcmd_type *)Jim_CmdPrivData(interp), argc, argv);
+

+
    return Jim_CallSubCmd(interp, ct, argc, argv);
+
}
+

+
#include <ctype.h>
+
#include <stdlib.h>
+
#include <string.h>
+
#include <stdio.h>
+
#include <assert.h>
+

+

+
int utf8_fromunicode(char *p, unsigned uc)
+
{
+
    if (uc <= 0x7f) {
+
        *p = uc;
+
        return 1;
+
    }
+
    else if (uc <= 0x7ff) {
+
        *p++ = 0xc0 | ((uc & 0x7c0) >> 6);
+
        *p = 0x80 | (uc & 0x3f);
+
        return 2;
+
    }
+
    else if (uc <= 0xffff) {
+
        *p++ = 0xe0 | ((uc & 0xf000) >> 12);
+
        *p++ = 0x80 | ((uc & 0xfc0) >> 6);
+
        *p = 0x80 | (uc & 0x3f);
+
        return 3;
+
    }
+

+
    else {
+
        *p++ = 0xf0 | ((uc & 0x1c0000) >> 18);
+
        *p++ = 0x80 | ((uc & 0x3f000) >> 12);
+
        *p++ = 0x80 | ((uc & 0xfc0) >> 6);
+
        *p = 0x80 | (uc & 0x3f);
+
        return 4;
+
    }
+
}
+

+
#include <ctype.h>
+
#include <string.h>
+

+

+
#define JIM_INTEGER_SPACE 24
+
#define MAX_FLOAT_WIDTH 320
+

+
Jim_Obj *Jim_FormatString(Jim_Interp *interp, Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv)
+
{
+
    const char *span, *format, *formatEnd, *msg;
+
    int numBytes = 0, objIndex = 0, gotXpg = 0, gotSequential = 0;
+
    static const char * const mixedXPG =
+
            "cannot mix \"%\" and \"%n$\" conversion specifiers";
+
    static const char * const badIndex[2] = {
+
        "not enough arguments for all format specifiers",
+
        "\"%n$\" argument index out of range"
+
    };
+
    int formatLen;
+
    Jim_Obj *resultPtr;
+

+
    char *num_buffer = NULL;
+
    int num_buffer_size = 0;
+

+
    span = format = Jim_GetString(fmtObjPtr, &formatLen);
+
    formatEnd = format + formatLen;
+
    resultPtr = Jim_NewEmptyStringObj(interp);
+

+
    while (format != formatEnd) {
+
        char *end;
+
        int gotMinus, sawFlag;
+
        int gotPrecision, useShort;
+
        long width, precision;
+
        int newXpg;
+
        int ch;
+
        int step;
+
        int doubleType;
+
        char pad = ' ';
+
        char spec[2*JIM_INTEGER_SPACE + 12];
+
        char *p;
+

+
        int formatted_chars;
+
        int formatted_bytes;
+
        const char *formatted_buf;
+

+
        step = utf8_tounicode(format, &ch);
+
        format += step;
+
        if (ch != '%') {
+
            numBytes += step;
+
            continue;
+
        }
+
        if (numBytes) {
+
            Jim_AppendString(interp, resultPtr, span, numBytes);
+
            numBytes = 0;
+
        }
+

+

+
        step = utf8_tounicode(format, &ch);
+
        if (ch == '%') {
+
            span = format;
+
            numBytes = step;
+
            format += step;
+
            continue;
+
        }
+

+

+
        newXpg = 0;
+
        if (isdigit(ch)) {
+
            int position = strtoul(format, &end, 10);
+
            if (*end == '$') {
+
                newXpg = 1;
+
                objIndex = position - 1;
+
                format = end + 1;
+
                step = utf8_tounicode(format, &ch);
+
            }
+
        }
+
        if (newXpg) {
+
            if (gotSequential) {
+
                msg = mixedXPG;
+
                goto errorMsg;
+
            }
+
            gotXpg = 1;
+
        } else {
+
            if (gotXpg) {
+
                msg = mixedXPG;
+
                goto errorMsg;
+
            }
+
            gotSequential = 1;
+
        }
+
        if ((objIndex < 0) || (objIndex >= objc)) {
+
            msg = badIndex[gotXpg];
+
            goto errorMsg;
+
        }
+

+
        p = spec;
+
        *p++ = '%';
+

+
        gotMinus = 0;
+
        sawFlag = 1;
+
        do {
+
            switch (ch) {
+
            case '-':
+
                gotMinus = 1;
+
                break;
+
            case '0':
+
                pad = ch;
+
                break;
+
            case ' ':
+
            case '+':
+
            case '#':
+
                break;
+
            default:
+
                sawFlag = 0;
+
                continue;
+
            }
+
            *p++ = ch;
+
            format += step;
+
            step = utf8_tounicode(format, &ch);
+
        } while (sawFlag);
+

+

+
        width = 0;
+
        if (isdigit(ch)) {
+
            width = strtoul(format, &end, 10);
+
            format = end;
+
            step = utf8_tounicode(format, &ch);
+
        } else if (ch == '*') {
+
            if (objIndex >= objc - 1) {
+
                msg = badIndex[gotXpg];
+
                goto errorMsg;
+
            }
+
            if (Jim_GetLong(interp, objv[objIndex], &width) != JIM_OK) {
+
                goto error;
+
            }
+
            if (width < 0) {
+
                width = -width;
+
                if (!gotMinus) {
+
                    *p++ = '-';
+
                    gotMinus = 1;
+
                }
+
            }
+
            objIndex++;
+
            format += step;
+
            step = utf8_tounicode(format, &ch);
+
        }
+

+

+
        gotPrecision = precision = 0;
+
        if (ch == '.') {
+
            gotPrecision = 1;
+
            format += step;
+
            step = utf8_tounicode(format, &ch);
+
        }
+
        if (isdigit(ch)) {
+
            precision = strtoul(format, &end, 10);
+
            format = end;
+
            step = utf8_tounicode(format, &ch);
+
        } else if (ch == '*') {
+
            if (objIndex >= objc - 1) {
+
                msg = badIndex[gotXpg];
+
                goto errorMsg;
+
            }
+
            if (Jim_GetLong(interp, objv[objIndex], &precision) != JIM_OK) {
+
                goto error;
+
            }
+

+

+
            if (precision < 0) {
+
                precision = 0;
+
            }
+
            objIndex++;
+
            format += step;
+
            step = utf8_tounicode(format, &ch);
+
        }
+

+

+
        useShort = 0;
+
        if (ch == 'h') {
+
            useShort = 1;
+
            format += step;
+
            step = utf8_tounicode(format, &ch);
+
        } else if (ch == 'l') {
+

+
            format += step;
+
            step = utf8_tounicode(format, &ch);
+
            if (ch == 'l') {
+
                format += step;
+
                step = utf8_tounicode(format, &ch);
+
            }
+
        }
+

+
        format += step;
+
        span = format;
+

+

+
        if (ch == 'i') {
+
            ch = 'd';
+
        }
+

+
        doubleType = 0;
+

+
        switch (ch) {
+
        case '\0':
+
            msg = "format string ended in middle of field specifier";
+
            goto errorMsg;
+
        case 's': {
+
            formatted_buf = Jim_GetString(objv[objIndex], &formatted_bytes);
+
            formatted_chars = Jim_Utf8Length(interp, objv[objIndex]);
+
            if (gotPrecision && (precision < formatted_chars)) {
+

+
                formatted_chars = precision;
+
                formatted_bytes = utf8_index(formatted_buf, precision);
+
            }
+
            break;
+
        }
+
        case 'c': {
+
            jim_wide code;
+

+
            if (Jim_GetWide(interp, objv[objIndex], &code) != JIM_OK) {
+
                goto error;
+
            }
+

+
            formatted_bytes = utf8_getchars(spec, code);
+
            formatted_buf = spec;
+
            formatted_chars = 1;
+
            break;
+
        }
+
        case 'b': {
+
                unsigned jim_wide w;
+
                int length;
+
                int i;
+
                int j;
+

+
                if (Jim_GetWide(interp, objv[objIndex], (jim_wide *)&w) != JIM_OK) {
+
                    goto error;
+
                }
+
                length = sizeof(w) * 8;
+

+

+

+
                if (num_buffer_size < length + 1) {
+
                    num_buffer_size = length + 1;
+
                    num_buffer = Jim_Realloc(num_buffer, num_buffer_size);
+
                }
+

+
                j = 0;
+
                for (i = length; i > 0; ) {
+
                        i--;
+
                    if (w & ((unsigned jim_wide)1 << i)) {
+
                                num_buffer[j++] = '1';
+
                        }
+
                        else if (j || i == 0) {
+
                                num_buffer[j++] = '0';
+
                        }
+
                }
+
                num_buffer[j] = 0;
+
                formatted_chars = formatted_bytes = j;
+
                formatted_buf = num_buffer;
+
                break;
+
        }
+

+
        case 'e':
+
        case 'E':
+
        case 'f':
+
        case 'g':
+
        case 'G':
+
            doubleType = 1;
+

+
        case 'd':
+
        case 'u':
+
        case 'o':
+
        case 'x':
+
        case 'X': {
+
            jim_wide w;
+
            double d;
+
            int length;
+

+

+
            if (width) {
+
                p += sprintf(p, "%ld", width);
+
            }
+
            if (gotPrecision) {
+
                p += sprintf(p, ".%ld", precision);
+
            }
+

+

+
            if (doubleType) {
+
                if (Jim_GetDouble(interp, objv[objIndex], &d) != JIM_OK) {
+
                    goto error;
+
                }
+
                length = MAX_FLOAT_WIDTH;
+
            }
+
            else {
+
                if (Jim_GetWide(interp, objv[objIndex], &w) != JIM_OK) {
+
                    goto error;
+
                }
+
                length = JIM_INTEGER_SPACE;
+
                if (useShort) {
+
                    if (ch == 'd') {
+
                        w = (short)w;
+
                    }
+
                    else {
+
                        w = (unsigned short)w;
+
                    }
+
                }
+
                *p++ = 'l';
+
#ifdef HAVE_LONG_LONG
+
                if (sizeof(long long) == sizeof(jim_wide)) {
+
                    *p++ = 'l';
+
                }
+
#endif
+
            }
+

+
            *p++ = (char) ch;
+
            *p = '\0';
+

+

+
            if (width > length) {
+
                length = width;
+
            }
+
            if (gotPrecision) {
+
                length += precision;
+
            }
+

+

+
            if (num_buffer_size < length + 1) {
+
                num_buffer_size = length + 1;
+
                num_buffer = Jim_Realloc(num_buffer, num_buffer_size);
+
            }
+

+
            if (doubleType) {
+
                snprintf(num_buffer, length + 1, spec, d);
+
            }
+
            else {
+
                formatted_bytes = snprintf(num_buffer, length + 1, spec, w);
+
            }
+
            formatted_chars = formatted_bytes = strlen(num_buffer);
+
            formatted_buf = num_buffer;
+
            break;
+
        }
+

+
        default: {
+

+
            spec[0] = ch;
+
            spec[1] = '\0';
+
            Jim_SetResultFormatted(interp, "bad field specifier \"%s\"", spec);
+
            goto error;
+
        }
+
        }
+

+
        if (!gotMinus) {
+
            while (formatted_chars < width) {
+
                Jim_AppendString(interp, resultPtr, &pad, 1);
+
                formatted_chars++;
+
            }
+
        }
+

+
        Jim_AppendString(interp, resultPtr, formatted_buf, formatted_bytes);
+

+
        while (formatted_chars < width) {
+
            Jim_AppendString(interp, resultPtr, &pad, 1);
+
            formatted_chars++;
+
        }
+

+
        objIndex += gotSequential;
+
    }
+
    if (numBytes) {
+
        Jim_AppendString(interp, resultPtr, span, numBytes);
+
    }
+

+
    Jim_Free(num_buffer);
+
    return resultPtr;
+

+
  errorMsg:
+
    Jim_SetResultString(interp, msg, -1);
+
  error:
+
    Jim_FreeNewObj(interp, resultPtr);
+
    Jim_Free(num_buffer);
+
    return NULL;
+
}
+

+

+
#if defined(JIM_REGEXP)
+
#include <stdio.h>
+
#include <ctype.h>
+
#include <stdlib.h>
+
#include <string.h>
+

+

+

+
#define REG_MAX_PAREN 100
+

+

+

+
#define	END	0
+
#define	BOL	1
+
#define	EOL	2
+
#define	ANY	3
+
#define	ANYOF	4
+
#define	ANYBUT	5
+
#define	BRANCH	6
+
#define	BACK	7
+
#define	EXACTLY	8
+
#define	NOTHING	9
+
#define	REP	10
+
#define	REPMIN	11
+
#define	REPX	12
+
#define	REPXMIN	13
+
#define	BOLX	14
+
#define	EOLX	15
+
#define	WORDA	16
+
#define	WORDZ	17
+

+
#define	OPENNC 	1000
+
#define	OPEN   	1001
+

+

+

+

+
#define	CLOSENC	2000
+
#define	CLOSE	2001
+
#define	CLOSE_END	(CLOSE+REG_MAX_PAREN)
+

+
#define	REG_MAGIC	0xFADED00D
+

+

+
#define	OP(preg, p)	(preg->program[p])
+
#define	NEXT(preg, p)	(preg->program[p + 1])
+
#define	OPERAND(p)	((p) + 2)
+

+

+

+

+
#define	FAIL(R,M)	{ (R)->err = (M); return (M); }
+
#define	ISMULT(c)	((c) == '*' || (c) == '+' || (c) == '?' || (c) == '{')
+
#define	META		"^$.[()|?{+*"
+

+
#define	HASWIDTH	1
+
#define	SIMPLE		2
+
#define	SPSTART		4
+
#define	WORST		0
+

+
#define MAX_REP_COUNT 1000000
+

+
static int reg(regex_t *preg, int paren, int *flagp );
+
static int regpiece(regex_t *preg, int *flagp );
+
static int regbranch(regex_t *preg, int *flagp );
+
static int regatom(regex_t *preg, int *flagp );
+
static int regnode(regex_t *preg, int op );
+
static int regnext(regex_t *preg, int p );
+
static void regc(regex_t *preg, int b );
+
static int reginsert(regex_t *preg, int op, int size, int opnd );
+
static void regtail(regex_t *preg, int p, int val);
+
static void regoptail(regex_t *preg, int p, int val );
+
static int regopsize(regex_t *preg, int p );
+

+
static int reg_range_find(const int *string, int c);
+
static const char *str_find(const char *string, int c, int nocase);
+
static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase);
+

+

+
#ifdef DEBUG
+
static int regnarrate = 0;
+
static void regdump(regex_t *preg);
+
static const char *regprop( int op );
+
#endif
+

+

+
static int str_int_len(const int *seq)
+
{
+
	int n = 0;
+
	while (*seq++) {
+
		n++;
+
	}
+
	return n;
+
}
+

+
int regcomp(regex_t *preg, const char *exp, int cflags)
+
{
+
	int scan;
+
	int longest;
+
	unsigned len;
+
	int flags;
+

+
#ifdef DEBUG
+
	fprintf(stderr, "Compiling: '%s'\n", exp);
+
#endif
+
	memset(preg, 0, sizeof(*preg));
+

+
	if (exp == NULL)
+
		FAIL(preg, REG_ERR_NULL_ARGUMENT);
+

+

+
	preg->cflags = cflags;
+
	preg->regparse = exp;
+

+

+
	preg->proglen = (strlen(exp) + 1) * 5;
+
	preg->program = malloc(preg->proglen * sizeof(int));
+
	if (preg->program == NULL)
+
		FAIL(preg, REG_ERR_NOMEM);
+

+
	regc(preg, REG_MAGIC);
+
	if (reg(preg, 0, &flags) == 0) {
+
		return preg->err;
+
	}
+

+

+
	if (preg->re_nsub >= REG_MAX_PAREN)
+
		FAIL(preg,REG_ERR_TOO_BIG);
+

+

+
	preg->regstart = 0;
+
	preg->reganch = 0;
+
	preg->regmust = 0;
+
	preg->regmlen = 0;
+
	scan = 1;
+
	if (OP(preg, regnext(preg, scan)) == END) {
+
		scan = OPERAND(scan);
+

+

+
		if (OP(preg, scan) == EXACTLY) {
+
			preg->regstart = preg->program[OPERAND(scan)];
+
		}
+
		else if (OP(preg, scan) == BOL)
+
			preg->reganch++;
+

+
		if (flags&SPSTART) {
+
			longest = 0;
+
			len = 0;
+
			for (; scan != 0; scan = regnext(preg, scan)) {
+
				if (OP(preg, scan) == EXACTLY) {
+
					int plen = str_int_len(preg->program + OPERAND(scan));
+
					if (plen >= len) {
+
						longest = OPERAND(scan);
+
						len = plen;
+
					}
+
				}
+
			}
+
			preg->regmust = longest;
+
			preg->regmlen = len;
+
		}
+
	}
+

+
#ifdef DEBUG
+
	regdump(preg);
+
#endif
+

+
	return 0;
+
}
+

+
static int reg(regex_t *preg, int paren, int *flagp )
+
{
+
	int ret;
+
	int br;
+
	int ender;
+
	int parno = 0;
+
	int flags;
+

+
	*flagp = HASWIDTH;
+

+

+
	if (paren) {
+
		if (preg->regparse[0] == '?' && preg->regparse[1] == ':') {
+

+
			preg->regparse += 2;
+
			parno = -1;
+
		}
+
		else {
+
			parno = ++preg->re_nsub;
+
		}
+
		ret = regnode(preg, OPEN+parno);
+
	} else
+
		ret = 0;
+

+

+
	br = regbranch(preg, &flags);
+
	if (br == 0)
+
		return 0;
+
	if (ret != 0)
+
		regtail(preg, ret, br);
+
	else
+
		ret = br;
+
	if (!(flags&HASWIDTH))
+
		*flagp &= ~HASWIDTH;
+
	*flagp |= flags&SPSTART;
+
	while (*preg->regparse == '|') {
+
		preg->regparse++;
+
		br = regbranch(preg, &flags);
+
		if (br == 0)
+
			return 0;
+
		regtail(preg, ret, br);
+
		if (!(flags&HASWIDTH))
+
			*flagp &= ~HASWIDTH;
+
		*flagp |= flags&SPSTART;
+
	}
+

+

+
	ender = regnode(preg, (paren) ? CLOSE+parno : END);
+
	regtail(preg, ret, ender);
+

+

+
	for (br = ret; br != 0; br = regnext(preg, br))
+
		regoptail(preg, br, ender);
+

+

+
	if (paren && *preg->regparse++ != ')') {
+
		preg->err = REG_ERR_UNMATCHED_PAREN;
+
		return 0;
+
	} else if (!paren && *preg->regparse != '\0') {
+
		if (*preg->regparse == ')') {
+
			preg->err = REG_ERR_UNMATCHED_PAREN;
+
			return 0;
+
		} else {
+
			preg->err = REG_ERR_JUNK_ON_END;
+
			return 0;
+
		}
+
	}
+

+
	return(ret);
+
}
+

+
static int regbranch(regex_t *preg, int *flagp )
+
{
+
	int ret;
+
	int chain;
+
	int latest;
+
	int flags;
+

+
	*flagp = WORST;
+

+
	ret = regnode(preg, BRANCH);
+
	chain = 0;
+
	while (*preg->regparse != '\0' && *preg->regparse != ')' &&
+
	       *preg->regparse != '|') {
+
		latest = regpiece(preg, &flags);
+
		if (latest == 0)
+
			return 0;
+
		*flagp |= flags&HASWIDTH;
+
		if (chain == 0) {
+
			*flagp |= flags&SPSTART;
+
		}
+
		else {
+
			regtail(preg, chain, latest);
+
		}
+
		chain = latest;
+
	}
+
	if (chain == 0)
+
		(void) regnode(preg, NOTHING);
+

+
	return(ret);
+
}
+

+
static int regpiece(regex_t *preg, int *flagp)
+
{
+
	int ret;
+
	char op;
+
	int next;
+
	int flags;
+
	int min;
+
	int max;
+

+
	ret = regatom(preg, &flags);
+
	if (ret == 0)
+
		return 0;
+

+
	op = *preg->regparse;
+
	if (!ISMULT(op)) {
+
		*flagp = flags;
+
		return(ret);
+
	}
+

+
	if (!(flags&HASWIDTH) && op != '?') {
+
		preg->err = REG_ERR_OPERAND_COULD_BE_EMPTY;
+
		return 0;
+
	}
+

+

+
	if (op == '{') {
+
		char *end;
+

+
		min = strtoul(preg->regparse + 1, &end, 10);
+
		if (end == preg->regparse + 1) {
+
			preg->err = REG_ERR_BAD_COUNT;
+
			return 0;
+
		}
+
		if (*end == '}') {
+
			max = min;
+
		}
+
		else {
+
			preg->regparse = end;
+
			max = strtoul(preg->regparse + 1, &end, 10);
+
			if (*end != '}') {
+
				preg->err = REG_ERR_UNMATCHED_BRACES;
+
				return 0;
+
			}
+
		}
+
		if (end == preg->regparse + 1) {
+
			max = MAX_REP_COUNT;
+
		}
+
		else if (max < min || max >= 100) {
+
			preg->err = REG_ERR_BAD_COUNT;
+
			return 0;
+
		}
+
		if (min >= 100) {
+
			preg->err = REG_ERR_BAD_COUNT;
+
			return 0;
+
		}
+

+
		preg->regparse = strchr(preg->regparse, '}');
+
	}
+
	else {
+
		min = (op == '+');
+
		max = (op == '?' ? 1 : MAX_REP_COUNT);
+
	}
+

+
	if (preg->regparse[1] == '?') {
+
		preg->regparse++;
+
		next = reginsert(preg, flags & SIMPLE ? REPMIN : REPXMIN, 5, ret);
+
	}
+
	else {
+
		next = reginsert(preg, flags & SIMPLE ? REP: REPX, 5, ret);
+
	}
+
	preg->program[ret + 2] = max;
+
	preg->program[ret + 3] = min;
+
	preg->program[ret + 4] = 0;
+

+
	*flagp = (min) ? (WORST|HASWIDTH) : (WORST|SPSTART);
+

+
	if (!(flags & SIMPLE)) {
+
		int back = regnode(preg, BACK);
+
		regtail(preg, back, ret);
+
		regtail(preg, next, back);
+
	}
+

+
	preg->regparse++;
+
	if (ISMULT(*preg->regparse)) {
+
		preg->err = REG_ERR_NESTED_COUNT;
+
		return 0;
+
	}
+

+
	return ret;
+
}
+

+
static void reg_addrange(regex_t *preg, int lower, int upper)
+
{
+
	if (lower > upper) {
+
		reg_addrange(preg, upper, lower);
+
	}
+

+
	regc(preg, upper - lower + 1);
+
	regc(preg, lower);
+
}
+

+
static void reg_addrange_str(regex_t *preg, const char *str)
+
{
+
	while (*str) {
+
		reg_addrange(preg, *str, *str);
+
		str++;
+
	}
+
}
+

+
static int reg_utf8_tounicode_case(const char *s, int *uc, int upper)
+
{
+
	int l = utf8_tounicode(s, uc);
+
	if (upper) {
+
		*uc = utf8_upper(*uc);
+
	}
+
	return l;
+
}
+

+
static int hexdigitval(int c)
+
{
+
	if (c >= '0' && c <= '9')
+
		return c - '0';
+
	if (c >= 'a' && c <= 'f')
+
		return c - 'a' + 10;
+
	if (c >= 'A' && c <= 'F')
+
		return c - 'A' + 10;
+
	return -1;
+
}
+

+
static int parse_hex(const char *s, int n, int *uc)
+
{
+
	int val = 0;
+
	int k;
+

+
	for (k = 0; k < n; k++) {
+
		int c = hexdigitval(*s++);
+
		if (c == -1) {
+
			break;
+
		}
+
		val = (val << 4) | c;
+
	}
+
	if (k) {
+
		*uc = val;
+
	}
+
	return k;
+
}
+

+
static int reg_decode_escape(const char *s, int *ch)
+
{
+
	int n;
+
	const char *s0 = s;
+

+
	*ch = *s++;
+

+
	switch (*ch) {
+
		case 'b': *ch = '\b'; break;
+
		case 'e': *ch = 27; break;
+
		case 'f': *ch = '\f'; break;
+
		case 'n': *ch = '\n'; break;
+
		case 'r': *ch = '\r'; break;
+
		case 't': *ch = '\t'; break;
+
		case 'v': *ch = '\v'; break;
+
		case 'u':
+
			if (*s == '{') {
+

+
				n = parse_hex(s + 1, 6, ch);
+
				if (n > 0 && s[n + 1] == '}' && *ch >= 0 && *ch <= 0x1fffff) {
+
					s += n + 2;
+
				}
+
				else {
+

+
					*ch = 'u';
+
				}
+
			}
+
			else if ((n = parse_hex(s, 4, ch)) > 0) {
+
				s += n;
+
			}
+
			break;
+
		case 'U':
+
			if ((n = parse_hex(s, 8, ch)) > 0) {
+
				s += n;
+
			}
+
			break;
+
		case 'x':
+
			if ((n = parse_hex(s, 2, ch)) > 0) {
+
				s += n;
+
			}
+
			break;
+
		case '\0':
+
			s--;
+
			*ch = '\\';
+
			break;
+
	}
+
	return s - s0;
+
}
+

+
static int regatom(regex_t *preg, int *flagp)
+
{
+
	int ret;
+
	int flags;
+
	int nocase = (preg->cflags & REG_ICASE);
+

+
	int ch;
+
	int n = reg_utf8_tounicode_case(preg->regparse, &ch, nocase);
+

+
	*flagp = WORST;
+

+
	preg->regparse += n;
+
	switch (ch) {
+

+
	case '^':
+
		ret = regnode(preg, BOL);
+
		break;
+
	case '$':
+
		ret = regnode(preg, EOL);
+
		break;
+
	case '.':
+
		ret = regnode(preg, ANY);
+
		*flagp |= HASWIDTH|SIMPLE;
+
		break;
+
	case '[': {
+
			const char *pattern = preg->regparse;
+

+
			if (*pattern == '^') {
+
				ret = regnode(preg, ANYBUT);
+
				pattern++;
+
			} else
+
				ret = regnode(preg, ANYOF);
+

+

+
			if (*pattern == ']' || *pattern == '-') {
+
				reg_addrange(preg, *pattern, *pattern);
+
				pattern++;
+
			}
+

+
			while (*pattern && *pattern != ']') {
+

+
				int start;
+
				int end;
+

+
				pattern += reg_utf8_tounicode_case(pattern, &start, nocase);
+
				if (start == '\\') {
+
					pattern += reg_decode_escape(pattern, &start);
+
					if (start == 0) {
+
						preg->err = REG_ERR_NULL_CHAR;
+
						return 0;
+
					}
+
				}
+
				if (pattern[0] == '-' && pattern[1] && pattern[1] != ']') {
+

+
					pattern += utf8_tounicode(pattern, &end);
+
					pattern += reg_utf8_tounicode_case(pattern, &end, nocase);
+
					if (end == '\\') {
+
						pattern += reg_decode_escape(pattern, &end);
+
						if (end == 0) {
+
							preg->err = REG_ERR_NULL_CHAR;
+
							return 0;
+
						}
+
					}
+

+
					reg_addrange(preg, start, end);
+
					continue;
+
				}
+
				if (start == '[' && pattern[0] == ':') {
+
					static const char *character_class[] = {
+
						":alpha:", ":alnum:", ":space:", ":blank:", ":upper:", ":lower:",
+
						":digit:", ":xdigit:", ":cntrl:", ":graph:", ":print:", ":punct:",
+
					};
+
					enum {
+
						CC_ALPHA, CC_ALNUM, CC_SPACE, CC_BLANK, CC_UPPER, CC_LOWER,
+
						CC_DIGIT, CC_XDIGIT, CC_CNTRL, CC_GRAPH, CC_PRINT, CC_PUNCT,
+
						CC_NUM
+
					};
+
					int i;
+

+
					for (i = 0; i < CC_NUM; i++) {
+
						n = strlen(character_class[i]);
+
						if (strncmp(pattern, character_class[i], n) == 0) {
+

+
							pattern += n + 1;
+
							break;
+
						}
+
					}
+
					if (i != CC_NUM) {
+
						switch (i) {
+
							case CC_ALNUM:
+
								reg_addrange(preg, '0', '9');
+

+
							case CC_ALPHA:
+
								if ((preg->cflags & REG_ICASE) == 0) {
+
									reg_addrange(preg, 'a', 'z');
+
								}
+
								reg_addrange(preg, 'A', 'Z');
+
								break;
+
							case CC_SPACE:
+
								reg_addrange_str(preg, " \t\r\n\f\v");
+
								break;
+
							case CC_BLANK:
+
								reg_addrange_str(preg, " \t");
+
								break;
+
							case CC_UPPER:
+
								reg_addrange(preg, 'A', 'Z');
+
								break;
+
							case CC_LOWER:
+
								reg_addrange(preg, 'a', 'z');
+
								break;
+
							case CC_XDIGIT:
+
								reg_addrange(preg, 'a', 'f');
+
								reg_addrange(preg, 'A', 'F');
+

+
							case CC_DIGIT:
+
								reg_addrange(preg, '0', '9');
+
								break;
+
							case CC_CNTRL:
+
								reg_addrange(preg, 0, 31);
+
								reg_addrange(preg, 127, 127);
+
								break;
+
							case CC_PRINT:
+
								reg_addrange(preg, ' ', '~');
+
								break;
+
							case CC_GRAPH:
+
								reg_addrange(preg, '!', '~');
+
								break;
+
							case CC_PUNCT:
+
								reg_addrange(preg, '!', '/');
+
								reg_addrange(preg, ':', '@');
+
								reg_addrange(preg, '[', '`');
+
								reg_addrange(preg, '{', '~');
+
								break;
+
						}
+
						continue;
+
					}
+
				}
+

+
				reg_addrange(preg, start, start);
+
			}
+
			regc(preg, '\0');
+

+
			if (*pattern) {
+
				pattern++;
+
			}
+
			preg->regparse = pattern;
+

+
			*flagp |= HASWIDTH|SIMPLE;
+
		}
+
		break;
+
	case '(':
+
		ret = reg(preg, 1, &flags);
+
		if (ret == 0)
+
			return 0;
+
		*flagp |= flags&(HASWIDTH|SPSTART);
+
		break;
+
	case '\0':
+
	case '|':
+
	case ')':
+
		preg->err = REG_ERR_INTERNAL;
+
		return 0;
+
	case '?':
+
	case '+':
+
	case '*':
+
	case '{':
+
		preg->err = REG_ERR_COUNT_FOLLOWS_NOTHING;
+
		return 0;
+
	case '\\':
+
		ch = *preg->regparse++;
+
		switch (ch) {
+
		case '\0':
+
			preg->err = REG_ERR_TRAILING_BACKSLASH;
+
			return 0;
+
		case 'A':
+
			ret = regnode(preg, BOLX);
+
			break;
+
		case 'Z':
+
			ret = regnode(preg, EOLX);
+
			break;
+
		case '<':
+
		case 'm':
+
			ret = regnode(preg, WORDA);
+
			break;
+
		case '>':
+
		case 'M':
+
			ret = regnode(preg, WORDZ);
+
			break;
+
		case 'd':
+
		case 'D':
+
			ret = regnode(preg, ch == 'd' ? ANYOF : ANYBUT);
+
			reg_addrange(preg, '0', '9');
+
			regc(preg, '\0');
+
			*flagp |= HASWIDTH|SIMPLE;
+
			break;
+
		case 'w':
+
		case 'W':
+
			ret = regnode(preg, ch == 'w' ? ANYOF : ANYBUT);
+
			if ((preg->cflags & REG_ICASE) == 0) {
+
				reg_addrange(preg, 'a', 'z');
+
			}
+
			reg_addrange(preg, 'A', 'Z');
+
			reg_addrange(preg, '0', '9');
+
			reg_addrange(preg, '_', '_');
+
			regc(preg, '\0');
+
			*flagp |= HASWIDTH|SIMPLE;
+
			break;
+
		case 's':
+
		case 'S':
+
			ret = regnode(preg, ch == 's' ? ANYOF : ANYBUT);
+
			reg_addrange_str(preg," \t\r\n\f\v");
+
			regc(preg, '\0');
+
			*flagp |= HASWIDTH|SIMPLE;
+
			break;
+

+
		default:
+

+

+
			preg->regparse--;
+
			goto de_fault;
+
		}
+
		break;
+
	de_fault:
+
	default: {
+
			int added = 0;
+

+

+
			preg->regparse -= n;
+

+
			ret = regnode(preg, EXACTLY);
+

+

+

+
			while (*preg->regparse && strchr(META, *preg->regparse) == NULL) {
+
				n = reg_utf8_tounicode_case(preg->regparse, &ch, (preg->cflags & REG_ICASE));
+
				if (ch == '\\' && preg->regparse[n]) {
+
					if (strchr("<>mMwWdDsSAZ", preg->regparse[n])) {
+

+
						break;
+
					}
+
					n += reg_decode_escape(preg->regparse + n, &ch);
+
					if (ch == 0) {
+
						preg->err = REG_ERR_NULL_CHAR;
+
						return 0;
+
					}
+
				}
+

+

+
				if (ISMULT(preg->regparse[n])) {
+

+
					if (added) {
+

+
						break;
+
					}
+

+
					regc(preg, ch);
+
					added++;
+
					preg->regparse += n;
+
					break;
+
				}
+

+

+
				regc(preg, ch);
+
				added++;
+
				preg->regparse += n;
+
			}
+
			regc(preg, '\0');
+

+
			*flagp |= HASWIDTH;
+
			if (added == 1)
+
				*flagp |= SIMPLE;
+
			break;
+
		}
+
		break;
+
	}
+

+
	return(ret);
+
}
+

+
static void reg_grow(regex_t *preg, int n)
+
{
+
	if (preg->p + n >= preg->proglen) {
+
		preg->proglen = (preg->p + n) * 2;
+
		preg->program = realloc(preg->program, preg->proglen * sizeof(int));
+
	}
+
}
+

+

+
static int regnode(regex_t *preg, int op)
+
{
+
	reg_grow(preg, 2);
+

+

+
	preg->program[preg->p++] = op;
+
	preg->program[preg->p++] = 0;
+

+

+
	return preg->p - 2;
+
}
+

+
static void regc(regex_t *preg, int b )
+
{
+
	reg_grow(preg, 1);
+
	preg->program[preg->p++] = b;
+
}
+

+
static int reginsert(regex_t *preg, int op, int size, int opnd )
+
{
+
	reg_grow(preg, size);
+

+

+
	memmove(preg->program + opnd + size, preg->program + opnd, sizeof(int) * (preg->p - opnd));
+

+
	memset(preg->program + opnd, 0, sizeof(int) * size);
+

+
	preg->program[opnd] = op;
+

+
	preg->p += size;
+

+
	return opnd + size;
+
}
+

+
static void regtail(regex_t *preg, int p, int val)
+
{
+
	int scan;
+
	int temp;
+
	int offset;
+

+

+
	scan = p;
+
	for (;;) {
+
		temp = regnext(preg, scan);
+
		if (temp == 0)
+
			break;
+
		scan = temp;
+
	}
+

+
	if (OP(preg, scan) == BACK)
+
		offset = scan - val;
+
	else
+
		offset = val - scan;
+

+
	preg->program[scan + 1] = offset;
+
}
+

+

+
static void regoptail(regex_t *preg, int p, int val )
+
{
+

+
	if (p != 0 && OP(preg, p) == BRANCH) {
+
		regtail(preg, OPERAND(p), val);
+
	}
+
}
+

+

+
static int regtry(regex_t *preg, const char *string );
+
static int regmatch(regex_t *preg, int prog);
+
static int regrepeat(regex_t *preg, int p, int max);
+

+
int regexec(regex_t  *preg,  const  char *string, size_t nmatch, regmatch_t pmatch[], int eflags)
+
{
+
	const char *s;
+
	int scan;
+

+

+
	if (preg == NULL || preg->program == NULL || string == NULL) {
+
		return REG_ERR_NULL_ARGUMENT;
+
	}
+

+

+
	if (*preg->program != REG_MAGIC) {
+
		return REG_ERR_CORRUPTED;
+
	}
+

+
#ifdef DEBUG
+
	fprintf(stderr, "regexec: %s\n", string);
+
	regdump(preg);
+
#endif
+

+
	preg->eflags = eflags;
+
	preg->pmatch = pmatch;
+
	preg->nmatch = nmatch;
+
	preg->start = string;
+

+

+
	for (scan = OPERAND(1); scan != 0; scan += regopsize(preg, scan)) {
+
		int op = OP(preg, scan);
+
		if (op == END)
+
			break;
+
		if (op == REPX || op == REPXMIN)
+
			preg->program[scan + 4] = 0;
+
	}
+

+

+
	if (preg->regmust != 0) {
+
		s = string;
+
		while ((s = str_find(s, preg->program[preg->regmust], preg->cflags & REG_ICASE)) != NULL) {
+
			if (prefix_cmp(preg->program + preg->regmust, preg->regmlen, s, preg->cflags & REG_ICASE) >= 0) {
+
				break;
+
			}
+
			s++;
+
		}
+
		if (s == NULL)
+
			return REG_NOMATCH;
+
	}
+

+

+
	preg->regbol = string;
+

+

+
	if (preg->reganch) {
+
		if (eflags & REG_NOTBOL) {
+

+
			goto nextline;
+
		}
+
		while (1) {
+
			if (regtry(preg, string)) {
+
				return REG_NOERROR;
+
			}
+
			if (*string) {
+
nextline:
+
				if (preg->cflags & REG_NEWLINE) {
+

+
					string = strchr(string, '\n');
+
					if (string) {
+
						preg->regbol = ++string;
+
						continue;
+
					}
+
				}
+
			}
+
			return REG_NOMATCH;
+
		}
+
	}
+

+

+
	s = string;
+
	if (preg->regstart != '\0') {
+

+
		while ((s = str_find(s, preg->regstart, preg->cflags & REG_ICASE)) != NULL) {
+
			if (regtry(preg, s))
+
				return REG_NOERROR;
+
			s++;
+
		}
+
	}
+
	else
+

+
		while (1) {
+
			if (regtry(preg, s))
+
				return REG_NOERROR;
+
			if (*s == '\0') {
+
				break;
+
			}
+
			else {
+
				int c;
+
				s += utf8_tounicode(s, &c);
+
			}
+
		}
+

+

+
	return REG_NOMATCH;
+
}
+

+

+
static int regtry( regex_t *preg, const char *string )
+
{
+
	int i;
+

+
	preg->reginput = string;
+

+
	for (i = 0; i < preg->nmatch; i++) {
+
		preg->pmatch[i].rm_so = -1;
+
		preg->pmatch[i].rm_eo = -1;
+
	}
+
	if (regmatch(preg, 1)) {
+
		preg->pmatch[0].rm_so = string - preg->start;
+
		preg->pmatch[0].rm_eo = preg->reginput - preg->start;
+
		return(1);
+
	} else
+
		return(0);
+
}
+

+
static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase)
+
{
+
	const char *s = string;
+
	while (proglen && *s) {
+
		int ch;
+
		int n = reg_utf8_tounicode_case(s, &ch, nocase);
+
		if (ch != *prog) {
+
			return -1;
+
		}
+
		prog++;
+
		s += n;
+
		proglen--;
+
	}
+
	if (proglen == 0) {
+
		return s - string;
+
	}
+
	return -1;
+
}
+

+
static int reg_range_find(const int *range, int c)
+
{
+
	while (*range) {
+

+
		if (c >= range[1] && c <= (range[0] + range[1] - 1)) {
+
			return 1;
+
		}
+
		range += 2;
+
	}
+
	return 0;
+
}
+

+
static const char *str_find(const char *string, int c, int nocase)
+
{
+
	if (nocase) {
+

+
		c = utf8_upper(c);
+
	}
+
	while (*string) {
+
		int ch;
+
		int n = reg_utf8_tounicode_case(string, &ch, nocase);
+
		if (c == ch) {
+
			return string;
+
		}
+
		string += n;
+
	}
+
	return NULL;
+
}
+

+
static int reg_iseol(regex_t *preg, int ch)
+
{
+
	if (preg->cflags & REG_NEWLINE) {
+
		return ch == '\0' || ch == '\n';
+
	}
+
	else {
+
		return ch == '\0';
+
	}
+
}
+

+
static int regmatchsimplerepeat(regex_t *preg, int scan, int matchmin)
+
{
+
	int nextch = '\0';
+
	const char *save;
+
	int no;
+
	int c;
+

+
	int max = preg->program[scan + 2];
+
	int min = preg->program[scan + 3];
+
	int next = regnext(preg, scan);
+

+
	if (OP(preg, next) == EXACTLY) {
+
		nextch = preg->program[OPERAND(next)];
+
	}
+
	save = preg->reginput;
+
	no = regrepeat(preg, scan + 5, max);
+
	if (no < min) {
+
		return 0;
+
	}
+
	if (matchmin) {
+

+
		max = no;
+
		no = min;
+
	}
+

+
	while (1) {
+
		if (matchmin) {
+
			if (no > max) {
+
				break;
+
			}
+
		}
+
		else {
+
			if (no < min) {
+
				break;
+
			}
+
		}
+
		preg->reginput = save + utf8_index(save, no);
+
		reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE));
+

+
		if (reg_iseol(preg, nextch) || c == nextch) {
+
			if (regmatch(preg, next)) {
+
				return(1);
+
			}
+
		}
+
		if (matchmin) {
+

+
			no++;
+
		}
+
		else {
+

+
			no--;
+
		}
+
	}
+
	return(0);
+
}
+

+
static int regmatchrepeat(regex_t *preg, int scan, int matchmin)
+
{
+
	int *scanpt = preg->program + scan;
+

+
	int max = scanpt[2];
+
	int min = scanpt[3];
+

+

+
	if (scanpt[4] < min) {
+

+
		scanpt[4]++;
+
		if (regmatch(preg, scan + 5)) {
+
			return 1;
+
		}
+
		scanpt[4]--;
+
		return 0;
+
	}
+
	if (scanpt[4] > max) {
+
		return 0;
+
	}
+

+
	if (matchmin) {
+

+
		if (regmatch(preg, regnext(preg, scan))) {
+
			return 1;
+
		}
+

+
		scanpt[4]++;
+
		if (regmatch(preg, scan + 5)) {
+
			return 1;
+
		}
+
		scanpt[4]--;
+
		return 0;
+
	}
+

+
	if (scanpt[4] < max) {
+
		scanpt[4]++;
+
		if (regmatch(preg, scan + 5)) {
+
			return 1;
+
		}
+
		scanpt[4]--;
+
	}
+

+
	return regmatch(preg, regnext(preg, scan));
+
}
+

+

+
static int regmatch(regex_t *preg, int prog)
+
{
+
	int scan;
+
	int next;
+
	const char *save;
+

+
	scan = prog;
+

+
#ifdef DEBUG
+
	if (scan != 0 && regnarrate)
+
		fprintf(stderr, "%s(\n", regprop(scan));
+
#endif
+
	while (scan != 0) {
+
		int n;
+
		int c;
+
#ifdef DEBUG
+
		if (regnarrate) {
+
			fprintf(stderr, "%3d: %s...\n", scan, regprop(OP(preg, scan)));
+
		}
+
#endif
+
		next = regnext(preg, scan);
+
		n = reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE));
+

+
		switch (OP(preg, scan)) {
+
		case BOLX:
+
			if ((preg->eflags & REG_NOTBOL)) {
+
				return(0);
+
			}
+

+
		case BOL:
+
			if (preg->reginput != preg->regbol) {
+
				return(0);
+
			}
+
			break;
+
		case EOLX:
+
			if (c != 0) {
+

+
				return 0;
+
			}
+
			break;
+
		case EOL:
+
			if (!reg_iseol(preg, c)) {
+
				return(0);
+
			}
+
			break;
+
		case WORDA:
+

+
			if ((!isalnum(UCHAR(c))) && c != '_')
+
				return(0);
+

+
			if (preg->reginput > preg->regbol &&
+
				(isalnum(UCHAR(preg->reginput[-1])) || preg->reginput[-1] == '_'))
+
				return(0);
+
			break;
+
		case WORDZ:
+

+
			if (preg->reginput > preg->regbol) {
+

+
				if (reg_iseol(preg, c) || !isalnum(UCHAR(c)) || c != '_') {
+
					c = preg->reginput[-1];
+

+
					if (isalnum(UCHAR(c)) || c == '_') {
+
						break;
+
					}
+
				}
+
			}
+

+
			return(0);
+

+
		case ANY:
+
			if (reg_iseol(preg, c))
+
				return 0;
+
			preg->reginput += n;
+
			break;
+
		case EXACTLY: {
+
				int opnd;
+
				int len;
+
				int slen;
+

+
				opnd = OPERAND(scan);
+
				len = str_int_len(preg->program + opnd);
+

+
				slen = prefix_cmp(preg->program + opnd, len, preg->reginput, preg->cflags & REG_ICASE);
+
				if (slen < 0) {
+
					return(0);
+
				}
+
				preg->reginput += slen;
+
			}
+
			break;
+
		case ANYOF:
+
			if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) == 0) {
+
				return(0);
+
			}
+
			preg->reginput += n;
+
			break;
+
		case ANYBUT:
+
			if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) != 0) {
+
				return(0);
+
			}
+
			preg->reginput += n;
+
			break;
+
		case NOTHING:
+
			break;
+
		case BACK:
+
			break;
+
		case BRANCH:
+
			if (OP(preg, next) != BRANCH)
+
				next = OPERAND(scan);
+
			else {
+
				do {
+
					save = preg->reginput;
+
					if (regmatch(preg, OPERAND(scan))) {
+
						return(1);
+
					}
+
					preg->reginput = save;
+
					scan = regnext(preg, scan);
+
				} while (scan != 0 && OP(preg, scan) == BRANCH);
+
				return(0);
+

+
			}
+
			break;
+
		case REP:
+
		case REPMIN:
+
			return regmatchsimplerepeat(preg, scan, OP(preg, scan) == REPMIN);
+

+
		case REPX:
+
		case REPXMIN:
+
			return regmatchrepeat(preg, scan, OP(preg, scan) == REPXMIN);
+

+
		case END:
+
			return 1;
+

+
		case OPENNC:
+
		case CLOSENC:
+
			return regmatch(preg, next);
+

+
		default:
+
			if (OP(preg, scan) >= OPEN+1 && OP(preg, scan) < CLOSE_END) {
+
				save = preg->reginput;
+
				if (regmatch(preg, next)) {
+
					if (OP(preg, scan) < CLOSE) {
+
						int no = OP(preg, scan) - OPEN;
+
						if (no < preg->nmatch && preg->pmatch[no].rm_so == -1) {
+
							preg->pmatch[no].rm_so = save - preg->start;
+
						}
+
					}
+
					else {
+
						int no = OP(preg, scan) - CLOSE;
+
						if (no < preg->nmatch && preg->pmatch[no].rm_eo == -1) {
+
							preg->pmatch[no].rm_eo = save - preg->start;
+
						}
+
					}
+
					return(1);
+
				}
+
				return(0);
+
			}
+
			return REG_ERR_INTERNAL;
+
		}
+

+
		scan = next;
+
	}
+

+
	return REG_ERR_INTERNAL;
+
}
+

+
static int regrepeat(regex_t *preg, int p, int max)
+
{
+
	int count = 0;
+
	const char *scan;
+
	int opnd;
+
	int ch;
+
	int n;
+

+
	scan = preg->reginput;
+
	opnd = OPERAND(p);
+
	switch (OP(preg, p)) {
+
	case ANY:
+

+
		while (!reg_iseol(preg, *scan) && count < max) {
+
			count++;
+
			scan++;
+
		}
+
		break;
+
	case EXACTLY:
+
		while (count < max) {
+
			n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
+
			if (preg->program[opnd] != ch) {
+
				break;
+
			}
+
			count++;
+
			scan += n;
+
		}
+
		break;
+
	case ANYOF:
+
		while (count < max) {
+
			n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
+
			if (reg_iseol(preg, ch) || reg_range_find(preg->program + opnd, ch) == 0) {
+
				break;
+
			}
+
			count++;
+
			scan += n;
+
		}
+
		break;
+
	case ANYBUT:
+
		while (count < max) {
+
			n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
+
			if (reg_iseol(preg, ch) || reg_range_find(preg->program + opnd, ch) != 0) {
+
				break;
+
			}
+
			count++;
+
			scan += n;
+
		}
+
		break;
+
	default:
+
		preg->err = REG_ERR_INTERNAL;
+
		count = 0;
+
		break;
+
	}
+
	preg->reginput = scan;
+

+
	return(count);
+
}
+

+
static int regnext(regex_t *preg, int p )
+
{
+
	int offset;
+

+
	offset = NEXT(preg, p);
+

+
	if (offset == 0)
+
		return 0;
+

+
	if (OP(preg, p) == BACK)
+
		return(p-offset);
+
	else
+
		return(p+offset);
+
}
+

+
static int regopsize(regex_t *preg, int p )
+
{
+

+
	switch (OP(preg, p)) {
+
		case REP:
+
		case REPMIN:
+
		case REPX:
+
		case REPXMIN:
+
			return 5;
+

+
		case ANYOF:
+
		case ANYBUT:
+
		case EXACTLY: {
+
			int s = p + 2;
+
			while (preg->program[s++]) {
+
			}
+
			return s - p;
+
		}
+
	}
+
	return 2;
+
}
+

+

+
size_t regerror(int errcode, const regex_t *preg, char *errbuf,  size_t errbuf_size)
+
{
+
	static const char *error_strings[] = {
+
		"success",
+
		"no match",
+
		"bad pattern",
+
		"null argument",
+
		"unknown error",
+
		"too big",
+
		"out of memory",
+
		"too many ()",
+
		"parentheses () not balanced",
+
		"braces {} not balanced",
+
		"invalid repetition count(s)",
+
		"extra characters",
+
		"*+ of empty atom",
+
		"nested count",
+
		"internal error",
+
		"count follows nothing",
+
		"trailing backslash",
+
		"corrupted program",
+
		"contains null char",
+
	};
+
	const char *err;
+

+
	if (errcode < 0 || errcode >= REG_ERR_NUM) {
+
		err = "Bad error code";
+
	}
+
	else {
+
		err = error_strings[errcode];
+
	}
+

+
	return snprintf(errbuf, errbuf_size, "%s", err);
+
}
+

+
void regfree(regex_t *preg)
+
{
+
	free(preg->program);
+
}
+

+
#endif
+

+
#if defined(_WIN32) || defined(WIN32)
+
#ifndef STRICT
+
#define STRICT
+
#endif
+
#define WIN32_LEAN_AND_MEAN
+
#include <windows.h>
+

+
#if defined(HAVE_DLOPEN_COMPAT)
+
void *dlopen(const char *path, int mode)
+
{
+
    JIM_NOTUSED(mode);
+

+
    return (void *)LoadLibraryA(path);
+
}
+

+
int dlclose(void *handle)
+
{
+
    FreeLibrary((HANDLE)handle);
+
    return 0;
+
}
+

+
void *dlsym(void *handle, const char *symbol)
+
{
+
    return GetProcAddress((HMODULE)handle, symbol);
+
}
+

+
char *dlerror(void)
+
{
+
    static char msg[121];
+
    FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
+
                   LANG_NEUTRAL, msg, sizeof(msg) - 1, NULL);
+
    return msg;
+
}
+
#endif
+

+
#ifdef _MSC_VER
+

+
#include <sys/timeb.h>
+

+

+
int gettimeofday(struct timeval *tv, void *unused)
+
{
+
    struct _timeb tb;
+

+
    _ftime(&tb);
+
    tv->tv_sec = tb.time;
+
    tv->tv_usec = tb.millitm * 1000;
+

+
    return 0;
+
}
+

+

+
DIR *opendir(const char *name)
+
{
+
    DIR *dir = 0;
+

+
    if (name && name[0]) {
+
        size_t base_length = strlen(name);
+
        const char *all =
+
            strchr("/\\", name[base_length - 1]) ? "*" : "/*";
+

+
        if ((dir = (DIR *) Jim_Alloc(sizeof *dir)) != 0 &&
+
            (dir->name = (char *)Jim_Alloc(base_length + strlen(all) + 1)) != 0) {
+
            strcat(strcpy(dir->name, name), all);
+

+
            if ((dir->handle = (long)_findfirst(dir->name, &dir->info)) != -1)
+
                dir->result.d_name = 0;
+
            else {
+
                Jim_Free(dir->name);
+
                Jim_Free(dir);
+
                dir = 0;
+
            }
+
        }
+
        else {
+
            Jim_Free(dir);
+
            dir = 0;
+
            errno = ENOMEM;
+
        }
+
    }
+
    else {
+
        errno = EINVAL;
+
    }
+
    return dir;
+
}
+

+
int closedir(DIR * dir)
+
{
+
    int result = -1;
+

+
    if (dir) {
+
        if (dir->handle != -1)
+
            result = _findclose(dir->handle);
+
        Jim_Free(dir->name);
+
        Jim_Free(dir);
+
    }
+
    if (result == -1)
+
        errno = EBADF;
+
    return result;
+
}
+

+
struct dirent *readdir(DIR * dir)
+
{
+
    struct dirent *result = 0;
+

+
    if (dir && dir->handle != -1) {
+
        if (!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1) {
+
            result = &dir->result;
+
            result->d_name = dir->info.name;
+
        }
+
    }
+
    else {
+
        errno = EBADF;
+
    }
+
    return result;
+
}
+
#endif
+
#endif
+
#ifndef JIM_BOOTSTRAP_LIB_ONLY
+
#include <errno.h>
+
#include <string.h>
+

+

+
#ifdef USE_LINENOISE
+
#ifdef HAVE_UNISTD_H
+
    #include <unistd.h>
+
#endif
+
#ifdef HAVE_SYS_STAT_H
+
    #include <sys/stat.h>
+
#endif
+
#include "linenoise.h"
+
#else
+
#define MAX_LINE_LEN 512
+
#endif
+

+
char *Jim_HistoryGetline(const char *prompt)
+
{
+
#ifdef USE_LINENOISE
+
    return linenoise(prompt);
+
#else
+
    int len;
+
    char *line = malloc(MAX_LINE_LEN);
+

+
    fputs(prompt, stdout);
+
    fflush(stdout);
+

+
    if (fgets(line, MAX_LINE_LEN, stdin) == NULL) {
+
        free(line);
+
        return NULL;
+
    }
+
    len = strlen(line);
+
    if (len && line[len - 1] == '\n') {
+
        line[len - 1] = '\0';
+
    }
+
    return line;
+
#endif
+
}
+

+
void Jim_HistoryLoad(const char *filename)
+
{
+
#ifdef USE_LINENOISE
+
    linenoiseHistoryLoad(filename);
+
#endif
+
}
+

+
void Jim_HistoryAdd(const char *line)
+
{
+
#ifdef USE_LINENOISE
+
    linenoiseHistoryAdd(line);
+
#endif
+
}
+

+
void Jim_HistorySave(const char *filename)
+
{
+
#ifdef USE_LINENOISE
+
#ifdef HAVE_UMASK
+
    mode_t mask;
+

+
    mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
+
#endif
+
    linenoiseHistorySave(filename);
+
#ifdef HAVE_UMASK
+
    mask = umask(mask);
+
#endif
+
#endif
+
}
+

+
void Jim_HistoryShow(void)
+
{
+
#ifdef USE_LINENOISE
+

+
    int i;
+
    int len;
+
    char **history = linenoiseHistory(&len);
+
    for (i = 0; i < len; i++) {
+
        printf("%4d %s\n", i + 1, history[i]);
+
    }
+
#endif
+
}
+

+
#ifdef USE_LINENOISE
+
struct JimCompletionInfo {
+
    Jim_Interp *interp;
+
    Jim_Obj *command;
+
};
+

+
void JimCompletionCallback(const char *prefix, linenoiseCompletions *comp, void *userdata)
+
{
+
    struct JimCompletionInfo *info = (struct JimCompletionInfo *)userdata;
+
    Jim_Obj *objv[2];
+
    int ret;
+

+
    objv[0] = info->command;
+
    objv[1] = Jim_NewStringObj(info->interp, prefix, -1);
+

+
    ret = Jim_EvalObjVector(info->interp, 2, objv);
+

+

+
    if (ret == JIM_OK) {
+
        int i;
+
        Jim_Obj *listObj = Jim_GetResult(info->interp);
+
        int len = Jim_ListLength(info->interp, listObj);
+
        for (i = 0; i < len; i++) {
+
            linenoiseAddCompletion(comp, Jim_String(Jim_ListGetIndex(info->interp, listObj, i)));
+
        }
+
    }
+
}
+
#endif
+

+
int Jim_InteractivePrompt(Jim_Interp *interp)
+
{
+
    int retcode = JIM_OK;
+
    char *history_file = NULL;
+
#ifdef USE_LINENOISE
+
    const char *home;
+
    struct JimCompletionInfo compinfo;
+

+
    home = getenv("HOME");
+
    if (home && isatty(STDIN_FILENO)) {
+
        int history_len = strlen(home) + sizeof("/.jim_history");
+
        history_file = Jim_Alloc(history_len);
+
        snprintf(history_file, history_len, "%s/.jim_history", home);
+
        Jim_HistoryLoad(history_file);
+
    }
+

+
    compinfo.interp = interp;
+
    compinfo.command = Jim_NewStringObj(interp, "tcl::autocomplete", -1);
+
    Jim_IncrRefCount(compinfo.command);
+

+

+
    linenoiseSetCompletionCallback(JimCompletionCallback, &compinfo);
+
#endif
+

+
    printf("Welcome to Jim version %d.%d\n",
+
        JIM_VERSION / 100, JIM_VERSION % 100);
+
    Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, "1");
+

+
    while (1) {
+
        Jim_Obj *scriptObjPtr;
+
        const char *result;
+
        int reslen;
+
        char prompt[20];
+

+
        if (retcode != JIM_OK) {
+
            const char *retcodestr = Jim_ReturnCode(retcode);
+

+
            if (*retcodestr == '?') {
+
                snprintf(prompt, sizeof(prompt) - 3, "[%d] . ", retcode);
+
            }
+
            else {
+
                snprintf(prompt, sizeof(prompt) - 3, "[%s] . ", retcodestr);
+
            }
+
        }
+
        else {
+
            strcpy(prompt, ". ");
+
        }
+

+
        scriptObjPtr = Jim_NewStringObj(interp, "", 0);
+
        Jim_IncrRefCount(scriptObjPtr);
+
        while (1) {
+
            char state;
+
            char *line;
+

+
            line = Jim_HistoryGetline(prompt);
+
            if (line == NULL) {
+
                if (errno == EINTR) {
+
                    continue;
+
                }
+
                Jim_DecrRefCount(interp, scriptObjPtr);
+
                retcode = JIM_OK;
+
                goto out;
+
            }
+
            if (Jim_Length(scriptObjPtr) != 0) {
+

+
                Jim_AppendString(interp, scriptObjPtr, "\n", 1);
+
            }
+
            Jim_AppendString(interp, scriptObjPtr, line, -1);
+
            free(line);
+
            if (Jim_ScriptIsComplete(interp, scriptObjPtr, &state))
+
                break;
+

+
            snprintf(prompt, sizeof(prompt), "%c> ", state);
+
        }
+
#ifdef USE_LINENOISE
+
        if (strcmp(Jim_String(scriptObjPtr), "h") == 0) {
+

+
            Jim_HistoryShow();
+
            Jim_DecrRefCount(interp, scriptObjPtr);
+
            continue;
+
        }
+

+
        Jim_HistoryAdd(Jim_String(scriptObjPtr));
+
        if (history_file) {
+
            Jim_HistorySave(history_file);
+
        }
+
#endif
+
        retcode = Jim_EvalObj(interp, scriptObjPtr);
+
        Jim_DecrRefCount(interp, scriptObjPtr);
+

+
        if (retcode == JIM_EXIT) {
+
            break;
+
        }
+
        if (retcode == JIM_ERR) {
+
            Jim_MakeErrorMessage(interp);
+
        }
+
        result = Jim_GetString(Jim_GetResult(interp), &reslen);
+
        if (reslen) {
+
            printf("%s\n", result);
+
        }
+
    }
+
  out:
+
    Jim_Free(history_file);
+

+
#ifdef USE_LINENOISE
+
    Jim_DecrRefCount(interp, compinfo.command);
+
    linenoiseSetCompletionCallback(NULL, NULL);
+
#endif
+

+
    return retcode;
+
}
+

+
#include <stdio.h>
+
#include <stdlib.h>
+
#include <string.h>
+

+

+

+
extern int Jim_initjimshInit(Jim_Interp *interp);
+

+
static void JimSetArgv(Jim_Interp *interp, int argc, char *const argv[])
+
{
+
    int n;
+
    Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
+

+

+
    for (n = 0; n < argc; n++) {
+
        Jim_Obj *obj = Jim_NewStringObj(interp, argv[n], -1);
+

+
        Jim_ListAppendElement(interp, listObj, obj);
+
    }
+

+
    Jim_SetVariableStr(interp, "argv", listObj);
+
    Jim_SetVariableStr(interp, "argc", Jim_NewIntObj(interp, argc));
+
}
+

+
static void JimPrintErrorMessage(Jim_Interp *interp)
+
{
+
    Jim_MakeErrorMessage(interp);
+
    fprintf(stderr, "%s\n", Jim_String(Jim_GetResult(interp)));
+
}
+

+
void usage(const char* executable_name)
+
{
+
    printf("jimsh version %d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
+
    printf("Usage: %s\n", executable_name);
+
    printf("or   : %s [options] [filename]\n", executable_name);
+
    printf("\n");
+
    printf("Without options: Interactive mode\n");
+
    printf("\n");
+
    printf("Options:\n");
+
    printf("      --version  : prints the version string\n");
+
    printf("      --help     : prints this text\n");
+
    printf("      -e CMD     : executes command CMD\n");
+
    printf("                   NOTE: all subsequent options will be passed as arguments to the command\n");
+
    printf("    [filename|-] : executes the script contained in the named file, or from stdin if \"-\"\n");
+
    printf("                   NOTE: all subsequent options will be passed to the script\n\n");
+
}
+

+
int main(int argc, char *const argv[])
+
{
+
    int retcode;
+
    Jim_Interp *interp;
+
    char *const orig_argv0 = argv[0];
+

+

+
    if (argc > 1 && strcmp(argv[1], "--version") == 0) {
+
        printf("%d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
+
        return 0;
+
    }
+
    else if (argc > 1 && strcmp(argv[1], "--help") == 0) {
+
        usage(argv[0]);
+
        return 0;
+
    }
+

+

+
    interp = Jim_CreateInterp();
+
    Jim_RegisterCoreCommands(interp);
+

+

+
    if (Jim_InitStaticExtensions(interp) != JIM_OK) {
+
        JimPrintErrorMessage(interp);
+
    }
+

+
    Jim_SetVariableStrWithStr(interp, "jim::argv0", orig_argv0);
+
    Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, argc == 1 ? "1" : "0");
+
    retcode = Jim_initjimshInit(interp);
+

+
    if (argc == 1) {
+

+
        if (retcode == JIM_ERR) {
+
            JimPrintErrorMessage(interp);
+
        }
+
        if (retcode != JIM_EXIT) {
+
            JimSetArgv(interp, 0, NULL);
+
            retcode = Jim_InteractivePrompt(interp);
+
        }
+
    }
+
    else {
+

+
        if (argc > 2 && strcmp(argv[1], "-e") == 0) {
+

+
            JimSetArgv(interp, argc - 3, argv + 3);
+
            retcode = Jim_Eval(interp, argv[2]);
+
            if (retcode != JIM_ERR) {
+
                printf("%s\n", Jim_String(Jim_GetResult(interp)));
+
            }
+
        }
+
        else {
+
            Jim_SetVariableStr(interp, "argv0", Jim_NewStringObj(interp, argv[1], -1));
+
            JimSetArgv(interp, argc - 2, argv + 2);
+
            if (strcmp(argv[1], "-") == 0) {
+
                retcode = Jim_Eval(interp, "eval [info source [stdin read] stdin 1]");
+
            } else {
+
                retcode = Jim_EvalFile(interp, argv[1]);
+
            }
+
        }
+
        if (retcode == JIM_ERR) {
+
            JimPrintErrorMessage(interp);
+
        }
+
    }
+
    if (retcode == JIM_EXIT) {
+
        retcode = Jim_GetExitCode(interp);
+
    }
+
    else if (retcode == JIM_ERR) {
+
        retcode = 1;
+
    }
+
    else {
+
        retcode = 0;
+
    }
+
    Jim_FreeInterp(interp);
+
    return retcode;
+
}
+
#endif
added autosetup/pkg-config.tcl
@@ -0,0 +1,186 @@
+
# Copyright (c) 2016 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# @synopsis:
+
#
+
# The 'pkg-config' module allows package information to be found via 'pkg-config'.
+
#
+
# If not cross-compiling, the package path should be determined automatically
+
# by 'pkg-config'.
+
# If cross-compiling, the default package path is the compiler sysroot.
+
# If the C compiler doesn't support '-print-sysroot', the path can be supplied
+
# by the '--sysroot' option or by defining 'SYSROOT'.
+
#
+
# 'PKG_CONFIG' may be set to use an alternative to 'pkg-config'.
+

+
use cc
+

+
module-options {
+
	sysroot:dir => "Override compiler sysroot for pkg-config search path"
+
}
+

+
# @pkg-config-init ?required?
+
#
+
# Initialises the 'pkg-config' system. Unless '$required' is set to 0,
+
# it is a fatal error if a usable 'pkg-config' is not found .
+
#
+
# This command will normally be called automatically as required,
+
# but it may be invoked explicitly if lack of 'pkg-config' is acceptable.
+
#
+
# Returns 1 if ok, or 0 if 'pkg-config' not found/usable (only if '$required' is 0).
+
#
+
proc pkg-config-init {{required 1}} {
+
	if {[is-defined HAVE_PKG_CONFIG]} {
+
		return [get-define HAVE_PKG_CONFIG]
+
	}
+
	set found 0
+

+
	define PKG_CONFIG [get-env PKG_CONFIG pkg-config]
+
	msg-checking "Checking for pkg-config..."
+

+
	if {[catch {exec [get-define PKG_CONFIG] --version} version]} {
+
		msg-result "[get-define PKG_CONFIG] (not found)"
+
		if {$required} {
+
			user-error "No usable pkg-config"
+
		}
+
	} else {
+
		msg-result $version
+
		define PKG_CONFIG_VERSION $version
+

+
		set found 1
+

+
		if {[opt-str sysroot o]} {
+
			define SYSROOT [file-normalize $o]
+
			msg-result "Using specified sysroot [get-define SYSROOT]"
+
		} elseif {[get-define build] ne [get-define host]} {
+
			if {[catch {exec-with-stderr [get-define CC] -print-sysroot} result errinfo] == 0} {
+
				# Use the compiler sysroot, if there is one
+
				define SYSROOT $result
+
				msg-result "Found compiler sysroot $result"
+
			} else {
+
				set msg "pkg-config: Cross compiling, but no compiler sysroot and no --sysroot supplied"
+
				if {$required} {
+
					user-error $msg
+
				} else {
+
					msg-result $msg
+
				}
+
				set found 0
+
			}
+
		}
+
		if {[is-defined SYSROOT]} {
+
			set sysroot [get-define SYSROOT]
+

+
			# XXX: It's possible that these should be set only when invoking pkg-config
+
			global env
+
			set env(PKG_CONFIG_DIR) ""
+
			# Do we need to try /usr/local as well or instead?
+
			set env(PKG_CONFIG_LIBDIR) $sysroot/usr/lib/pkgconfig:$sysroot/usr/share/pkgconfig
+
			set env(PKG_CONFIG_SYSROOT_DIR) $sysroot
+
		}
+
	}
+
	define HAVE_PKG_CONFIG $found
+
	return $found
+
}
+

+
# @pkg-config module ?requirements?
+
#
+
# Use 'pkg-config' to find the given module meeting the given requirements.
+
# e.g.
+
#
+
## pkg-config pango >= 1.37.0
+
#
+
# If found, returns 1 and sets 'HAVE_PKG_PANGO' to 1 along with:
+
#
+
## PKG_PANGO_VERSION to the found version
+
## PKG_PANGO_LIBS    to the required libs (--libs-only-l)
+
## PKG_PANGO_LDFLAGS to the required linker flags (--libs-only-L)
+
## PKG_PANGO_CFLAGS  to the required compiler flags (--cflags)
+
## PKG_PANGO_LIBS_STATIC to the required libs (--libs-only-l -static)
+
#
+
# If not found, returns 0.
+
#
+
proc pkg-config {module args} {
+
	set ok [pkg-config-init]
+

+
	msg-checking "Checking for $module $args..."
+

+
	if {!$ok} {
+
		msg-result "no pkg-config"
+
		return 0
+
	}
+

+
	if {[catch {exec [get-define PKG_CONFIG] --modversion "$module $args"} version]} {
+
		msg-result "not found"
+
		configlog "pkg-config --modversion $module $args: $version"
+
		return 0
+
	}
+
	msg-result $version
+
	set prefix [feature-define-name $module PKG_]
+
	define HAVE_${prefix}
+
	define ${prefix}_VERSION $version
+
	define ${prefix}_LIBS [exec pkg-config --libs-only-l $module]
+

+
# Please enter the commit message for your changes. Lines starting
+
# with '#' will be ignored, and an empty message aborts the commit.
+
#
+
# On branch autosetup
+
# Your branch is up to date with 'origin/autosetup'.
+
#
+
# Changes to be committed:
+
#	modified:   auto.def
+
#
+
# Untracked files:
+
#	..travis.yml.un~
+
#	.Makefile.autosetup.un~
+
#	.auto.def.un~
+
#	autosetup/.pkg-config.tcl.un~
+
#	config.h
+
#	docs/.Makefile.autosetup.un~
+
#	docs/.Makefile.un~
+
#	external/libfetch/.Makefile.autosetup.un~
+
#	external/libfetch/Makefile
+
#	libpkg/.Makefile.autosetup.un~
+
#	libpkg/.Makefile.un~
+
#	mk/.common.mk.un~
+
#	mk/.defs.mk.in.un~
+
#	mk/.defs.mk.un~
+
#	mk/.doc.mk.un~
+
#	mk/doc.mk
+
#	plop.tar.xz
+
#	scripts/.Makefile.autosetup.un~
+
#	scripts/.Makefile.un~
+
#	src/.Makefile.autosetup.un~
+
#	src/.Makefile.un~
+
#	tests/.Makefile.autosetup.un~
+
#	tests/Kyuafile
+
#	tests/checksum
+
#	tests/deps_formula
+
#	tests/frontend/Kyuafile
+
#	tests/frontend/add
+
#	tests/frontend/alias
+
#	tests/frontend/annotate
+
#	tests/frontend/autoremove
+
#	tests/frontend/autoupgrade
+
#	tests/frontend/config
+
#	tests/frontend/configmerge
+
#	tests/frontend/conflicts
+
#	tests/frontend/conflicts-multirepo
+
#	tests/frontend/create
+
#	tests/frontend/delete
+
#	tests/frontend/extract
+
#	tests/frontend/fingerprint
+
	define ${prefix}_LDFLAGS [exec pkg-config --libs-only-L $module]
+
	define ${prefix}_CFLAGS [exec pkg-config --cflags $module]
+
	return 1
+
}
+

+
# @pkg-config-get module setting
+
#
+
# Convenience access to the results of 'pkg-config'.
+
#
+
# For example, '[pkg-config-get pango CFLAGS]' returns
+
# the value of 'PKG_PANGO_CFLAGS', or '""' if not defined.
+
proc pkg-config-get {module name} {
+
	set prefix [feature-define-name $module PKG_]
+
	get-define ${prefix}_${name} ""
+
}
added autosetup/system.tcl
@@ -0,0 +1,325 @@
+
# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# @synopsis:
+
#
+
# This module supports common system interrogation and options
+
# such as '--host', '--build', '--prefix', and setting 'srcdir', 'builddir', and 'EXEEXT'.
+
#
+
# It also support the "feature" naming convention, where searching
+
# for a feature such as 'sys/type.h' defines 'HAVE_SYS_TYPES_H'.
+
#
+
# It defines the following variables, based on '--prefix' unless overridden by the user:
+
#
+
## datadir
+
## sysconfdir
+
## sharedstatedir
+
## localstatedir
+
## infodir
+
## mandir
+
## includedir
+
#
+
# If '--prefix' is not supplied, it defaults to '/usr/local' unless 'defaultprefix' is defined *before*
+
# including the 'system' module.
+

+
if {[is-defined defaultprefix]} {
+
	user-notice "Note: defaultprefix is deprecated. Use options-defaults to set default options"
+
	options-defaults [list prefix [get-define defaultprefix]]
+
}
+

+
module-options [subst -noc -nob {
+
	host:host-alias =>		{a complete or partial cpu-vendor-opsys for the system where
+
							the application will run (defaults to the same value as --build)}
+
	build:build-alias =>	{a complete or partial cpu-vendor-opsys for the system
+
							where the application will be built (defaults to the
+
							result of running config.guess)}
+
	prefix:dir=/usr/local => {the target directory for the build (default: '@default@')}
+

+
	# These (hidden) options are supported for autoconf/automake compatibility
+
	exec-prefix:
+
	bindir:
+
	sbindir:
+
	includedir:
+
	mandir:
+
	infodir:
+
	libexecdir:
+
	datadir:
+
	libdir:
+
	sysconfdir:
+
	sharedstatedir:
+
	localstatedir:
+
	maintainer-mode=0
+
	dependency-tracking=0
+
	silent-rules=0
+
}]
+

+
# @check-feature name { script }
+
#
+
# defines feature '$name' to the return value of '$script',
+
# which should be 1 if found or 0 if not found.
+
#
+
# e.g. the following will define 'HAVE_CONST' to 0 or 1.
+
#
+
## check-feature const {
+
##     cctest -code {const int _x = 0;}
+
## }
+
proc check-feature {name code} {
+
	msg-checking "Checking for $name..."
+
	set r [uplevel 1 $code]
+
	define-feature $name $r
+
	if {$r} {
+
		msg-result "ok"
+
	} else {
+
		msg-result "not found"
+
	}
+
	return $r
+
}
+

+
# @have-feature name ?default=0?
+
#
+
# Returns the value of feature '$name' if defined, or '$default' if not.
+
#
+
# See 'feature-define-name' for how the "feature" name
+
# is translated into the "define" name.
+
#
+
proc have-feature {name {default 0}} {
+
	get-define [feature-define-name $name] $default
+
}
+

+
# @define-feature name ?value=1?
+
#
+
# Sets the feature 'define' to '$value'.
+
#
+
# See 'feature-define-name' for how the "feature" name
+
# is translated into the "define" name.
+
#
+
proc define-feature {name {value 1}} {
+
	define [feature-define-name $name] $value
+
}
+

+
# @feature-checked name
+
#
+
# Returns 1 if feature '$name' has been checked, whether true or not.
+
#
+
proc feature-checked {name} {
+
	is-defined [feature-define-name $name]
+
}
+

+
# @feature-define-name name ?prefix=HAVE_?
+
#
+
# Converts a "feature" name to the corresponding "define",
+
# e.g. 'sys/stat.h' becomes 'HAVE_SYS_STAT_H'.
+
#
+
# Converts '*' to 'P' and all non-alphanumeric to underscore.
+
#
+
proc feature-define-name {name {prefix HAVE_}} {
+
	string toupper $prefix[regsub -all {[^a-zA-Z0-9]} [regsub -all {[*]} $name p] _]
+
}
+

+
# @write-if-changed filename contents ?script?
+
#
+
# If '$filename' doesn't exist, or it's contents are different to '$contents',
+
# the file is written and '$script' is evaluated.
+
#
+
# Otherwise a "file is unchanged" message is displayed.
+
proc write-if-changed {file buf {script {}}} {
+
	set old [readfile $file ""]
+
	if {$old eq $buf && [file exists $file]} {
+
		msg-result "$file is unchanged"
+
	} else {
+
		writefile $file $buf\n
+
		uplevel 1 $script
+
	}
+
}
+

+
# @make-template template ?outfile?
+
#
+
# Reads the input file '<srcdir>/$template' and writes the output file '$outfile'
+
# (unless unchanged).
+
# If '$outfile' is blank/omitted, '$template' should end with '.in' which
+
# is removed to create the output file name.
+
#
+
# Each pattern of the form '@define@' is replaced with the corresponding
+
# "define", if it exists, or left unchanged if not.
+
# 
+
# The special value '@srcdir@' is substituted with the relative
+
# path to the source directory from the directory where the output
+
# file is created, while the special value '@top_srcdir@' is substituted
+
# with the relative path to the top level source directory.
+
#
+
# Conditional sections may be specified as follows:
+
## @if name == value
+
## lines
+
## @else
+
## lines
+
## @endif
+
#
+
# Where 'name' is a defined variable name and '@else' is optional.
+
# If the expression does not match, all lines through '@endif' are ignored.
+
#
+
# The alternative forms may also be used:
+
## @if name
+
## @if name != value
+
#
+
# Where the first form is true if the variable is defined, but not empty nor 0.
+
#
+
# Currently these expressions can't be nested.
+
#
+
proc make-template {template {out {}}} {
+
	set infile [file join $::autosetup(srcdir) $template]
+

+
	if {![file exists $infile]} {
+
		user-error "Template $template is missing"
+
	}
+

+
	# Define this as late as possible
+
	define AUTODEPS $::autosetup(deps)
+

+
	if {$out eq ""} {
+
		if {[file ext $template] ne ".in"} {
+
			autosetup-error "make_template $template has no target file and can't guess"
+
		}
+
		set out [file rootname $template]
+
	}
+

+
	set outdir [file dirname $out]
+

+
	# Make sure the directory exists
+
	file mkdir $outdir
+

+
	# Set up srcdir and top_srcdir to be relative to the target dir
+
	define srcdir [relative-path [file join $::autosetup(srcdir) $outdir] $outdir]
+
	define top_srcdir [relative-path $::autosetup(srcdir) $outdir]
+

+
	set mapping {}
+
	foreach {n v} [array get ::define] {
+
		lappend mapping @$n@ $v
+
	}
+
	set result {}
+
	foreach line [split [readfile $infile] \n] {
+
		if {[info exists cond]} {
+
			set l [string trimright $line]
+
			if {$l eq "@endif"} {
+
				unset cond
+
				continue
+
			}
+
			if {$l eq "@else"} {
+
				set cond [expr {!$cond}]
+
				continue
+
			}
+
			if {$cond} {
+
				lappend result $line
+
			}
+
			continue
+
		}
+
		if {[regexp {^@if\s+(\w+)(.*)} $line -> name expression]} {
+
			lassign $expression equal value
+
			set varval [get-define $name ""]
+
			if {$equal eq ""} {
+
				set cond [expr {$varval ni {"" 0}}]
+
			} else {
+
				set cond [expr {$varval eq $value}]
+
				if {$equal ne "=="} {
+
					set cond [expr {!$cond}]
+
				}
+
			}
+
			continue
+
		}
+
		lappend result $line
+
	}
+
	write-if-changed $out [string map $mapping [join $result \n]] {
+
		msg-result "Created [relative-path $out] from [relative-path $template]"
+
	}
+
}
+

+
# build/host tuples and cross-compilation prefix
+
opt-str build build ""
+
define build_alias $build
+
if {$build eq ""} {
+
	define build [config_guess]
+
} else {
+
	define build [config_sub $build]
+
}
+

+
opt-str host host ""
+
define host_alias $host
+
if {$host eq ""} {
+
	define host [get-define build]
+
	set cross ""
+
} else {
+
	define host [config_sub $host]
+
	set cross $host-
+
}
+
define cross [get-env CROSS $cross]
+

+
# build/host _cpu, _vendor and _os
+
foreach type {build host} {
+
	set v [get-define $type]
+
	if {![regexp {^([^-]+)-([^-]+)-(.*)$} $v -> cpu vendor os]} {
+
		user-error "Invalid canonical $type: $v"
+
	}
+
	define ${type}_cpu $cpu
+
	define ${type}_vendor $vendor
+
	define ${type}_os $os
+
}
+

+
opt-str prefix prefix /usr/local
+

+
# These are for compatibility with autoconf
+
define target [get-define host]
+
define prefix $prefix
+
define builddir $autosetup(builddir)
+
define srcdir $autosetup(srcdir)
+
define top_srcdir $autosetup(srcdir)
+
define abs_top_srcdir [file-normalize $autosetup(srcdir)]
+
define abs_top_builddir [file-normalize $autosetup(builddir)]
+

+
# autoconf supports all of these
+
define exec_prefix [opt-str exec-prefix exec_prefix $prefix]
+
foreach {name defpath} {
+
	bindir /bin
+
	sbindir /sbin
+
	libexecdir /libexec
+
	libdir /lib
+
} {
+
	define $name [opt-str $name o $exec_prefix$defpath]
+
}
+
foreach {name defpath} {
+
	datadir /share
+
	sharedstatedir /com
+
	infodir /share/info
+
	mandir /share/man
+
	includedir /include
+
} {
+
	define $name [opt-str $name o $prefix$defpath]
+
}
+
if {$prefix ne {/usr}} {
+
	opt-str sysconfdir sysconfdir $prefix/etc
+
} else {
+
	opt-str sysconfdir sysconfdir /etc
+
}
+
define sysconfdir $sysconfdir
+

+
define localstatedir [opt-str localstatedir o /var]
+

+
define SHELL [get-env SHELL [find-an-executable sh bash ksh]]
+

+
# These could be used to generate Makefiles following some automake conventions
+
define AM_SILENT_RULES [opt-bool silent-rules]
+
define AM_MAINTAINER_MODE [opt-bool maintainer-mode]
+
define AM_DEPENDENCY_TRACKING [opt-bool dependency-tracking]
+

+
# Windows vs. non-Windows
+
switch -glob -- [get-define host] {
+
	*-*-ming* - *-*-cygwin - *-*-msys {
+
		define-feature windows
+
		define EXEEXT .exe
+
	}
+
	default {
+
		define EXEEXT ""
+
	}
+
}
+

+
# Display
+
msg-result "Host System...[get-define host]"
+
msg-result "Build System...[get-define build]"
added autosetup/tmake.auto
@@ -0,0 +1,55 @@
+
# Copyright (c) 2016 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# Auto-load module for 'tmake' build system integration
+

+
use init
+

+
autosetup_add_init_type tmake "Tcl-based tmake build system" {
+
	autosetup_check_create auto.def \
+
{# Initial auto.def created by 'autosetup --init=tmake'
+
# vim:set syntax=tcl:
+

+
use cc cc-lib cc-db cc-shared
+
use tmake
+

+
# Add any user options here
+
# Really want a --configure that takes over the rest of the command line
+
options {
+
}
+

+
cc-check-tools ar ranlib
+

+
set objdir [get-env BUILDDIR objdir]
+

+
make-config-header $objdir/include/autoconf.h
+
make-tmake-settings $objdir/settings.conf {[A-Z]*} *dir lib_*
+
}
+

+
	autosetup_check_create project.spec \
+
{# Initial project.spec created by 'autosetup --init=tmake'
+

+
tmake-require-version 0.7.3
+

+
# vim:set syntax=tcl:
+
define? DESTDIR _install
+

+
# XXX If configure creates additional/different files than include/autoconf.h
+
#     that should be reflected here
+
Autosetup include/autoconf.h
+

+
# e.g. for autoconf.h
+
IncludePaths include
+

+
ifconfig !CONFIGURED {
+
	# Not configured, so don't process subdirs
+
	AutoSubDirs off
+
	# And don't process this file any further
+
	ifconfig false
+
}
+
}
+

+
	if {![file exists build.spec]} {
+
		puts "Note: I don't see build.spec. Try running: tmake --genie"
+
	}
+
}
added autosetup/tmake.tcl
@@ -0,0 +1,52 @@
+
# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
+
# All rights reserved
+

+
# @synopsis:
+
#
+
# The 'tmake' module makes it easy to support the tmake build system.
+
#
+
# The following variables are set:
+
#
+
## CONFIGURED  - to indicate that the project is configured
+

+
use system
+

+
module-options {}
+

+
define CONFIGURED
+

+
# @make-tmake-settings outfile patterns ...
+
#
+
# Examines all defined variables which match the given patterns (defaults to '*')
+
# and writes a tmake-compatible .conf file defining those variables.
+
# For example, if 'ABC' is '"3 monkeys"' and 'ABC' matches a pattern, then the file will include:
+
#
+
## define ABC {3 monkeys}
+
#
+
# If the file would be unchanged, it is not written.
+
#
+
# Typical usage is:
+
#
+
## make-tmake-settings [get-env BUILDDIR objdir]/settings.conf {[A-Z]*}
+
proc make-tmake-settings {file args} {
+
	file mkdir [file dirname $file]
+
	set lines {}
+

+
	if {[llength $args] == 0} {
+
		set args *
+
	}
+

+
	foreach n [lsort [dict keys [all-defines]]] {
+
		foreach p $args {
+
			if {[string match $p $n]} {
+
				set value [get-define $n]
+
				lappend lines "define $n [list $value]"
+
				break
+
			}
+
		}
+
	}
+
	set buf [join $lines \n]
+
	write-if-changed $file $buf {
+
		msg-result "Created $file"
+
	}
+
}
deleted compat/Makefile.am
@@ -1,14 +0,0 @@
-
noinst_LTLIBRARIES=	libbsd_compat.la
-
noinst_HEADERS=		bsd_compat.h endian_util.h \
-
			humanize_number.h
-

-
libbsd_compat_la_SOURCES=	basename.c \
-
				closefrom.c \
-
				dirname.c \
-
				file_at.c \
-
				humanize_number.c \
-
				strtonum.c \
-
				strnstr.c \
-
				funopen.c
-

-
libbsd_compat_la_CFLAGS=	$(pkg_common_cflags) -shared
added compat/Makefile.autosetup
@@ -0,0 +1,16 @@
+
include @builddir@/mk/defs.mk
+
LIB=	bsd_compat
+
SRCS=	basename.c \
+
	closefrom.c \
+
	dirname.c \
+
	file_at.c \
+
	humanize_number.c \
+
	strtonum.c \
+
	strnstr.c \
+
	funopen.c
+

+
LOCAL_CFLAGS=	-I$(top_srcdir)/compat \
+
		-I$(top_srcdir)
+

+
include $(MK)/static-lib.mk
+

modified compat/bsd_compat.h
@@ -102,23 +102,23 @@ void closefrom(int lowfd);
#define	AT_SYMLINK_NOFOLLOW	0x200
#endif

-
#if !HAVE_DECL_FACCESSAT
+
#if !HAVE_FACCESSAT
int faccessat(int fd, const char *path, int mode, int flag);
#endif

-
#if !HAVE_DECL_FSTATAT
+
#if !HAVE_FSTATAT
int fstatat(int fd, const char *path, struct stat *buf, int flag);
#endif

-
#if !HAVE_DECL_OPENAT
+
#if !HAVE_OPENAT
int openat(int fd, const char *path, int flags, ...);
#endif

-
#if !HAVE_DECL_READLINKAT
+
#if !HAVE_READLINKAT
ssize_t readlinkat(int fd, const char *restrict path, char *restrict buf, size_t bufsize);
#endif

-
#if !HAVE_DECL_UNLINKAT
+
#if !HAVE_UNLINKAT
# ifndef AT_REMOVEDIR
#  define AT_REMOVEDIR	0x800
# endif
modified compat/closefrom.c
@@ -58,7 +58,7 @@ __unused static const char rcsid[] = "$Sudo: closefrom.c,v 1.11 2006/08/17 15:26
/*
 * Close all file descriptors greater than or equal to lowfd.
 */
-
#ifdef HAVE_FCNTL_CLOSEM
+
#if HAVE_DECL_F_CLOSEM
void
closefrom(int lowfd)
{
@@ -105,5 +105,5 @@ closefrom(int lowfd)
	    (void) close((int) fd);
    }
}
-
#endif /* !HAVE_FCNTL_CLOSEM */
+
#endif /* !HAVE_DECL_F_CLOSEM */
#endif /* HAVE_CLOSEFROM */
modified compat/file_at.c
@@ -1,4 +1,4 @@
-
/*-
+
/*
 * Copyright (c) 2014 Landon Fuller <landon@landonf.org>
 * All rights reserved.
 * 
@@ -33,7 +33,7 @@
#include <stdarg.h>
#include <unistd.h>

-
#if !HAVE_DECL_UNLINKAT || !HAVE_DECL_FSTATAT
+
#if !HAVE_UNLINKAT || !HAVE_FSTATAT

static pthread_mutex_t file_at_lock = PTHREAD_MUTEX_INITIALIZER;
static int file_at_dfd = -1;
@@ -92,7 +92,7 @@ file_chdir_unlock(int dfd)
}
#endif

-
#if !HAVE_DECL_FACCESSAT
+
#if !HAVE_FACCESSAT
int
faccessat(int fd, const char *path, int mode, int flag)
{
@@ -117,7 +117,7 @@ faccessat(int fd, const char *path, int mode, int flag)
}
#endif

-
#if !HAVE_DECL_READLINKAT
+
#if !HAVE_READLINKAT
ssize_t
readlinkat(int fd, const char *restrict path, char *restrict buf,
	   size_t bufsize)
@@ -134,7 +134,7 @@ readlinkat(int fd, const char *restrict path, char *restrict buf,
}
#endif

-
#if !HAVE_DECL_FSTATAT
+
#if !HAVE_FSTATAT
int
fstatat(int fd, const char *path, struct stat *buf, int flag)
{
@@ -154,7 +154,7 @@ fstatat(int fd, const char *path, struct stat *buf, int flag)
}
#endif

-
#if !HAVE_DECL_OPENAT
+
#if !HAVE_OPENAT
int
openat(int fd, const char *path, int flags, ...)
{
@@ -177,7 +177,7 @@ openat(int fd, const char *path, int flags, ...)
}
#endif

-
#if !HAVE_DECL_UNLINKAT
+
#if !HAVE_UNLINKAT
int
unlinkat(int fd, const char *path, int flag)
{
added configure
@@ -0,0 +1,3 @@
+
#!/bin/sh
+
dir="`dirname "$0"`/autosetup"
+
WRAPPER="$0"; export WRAPPER; exec "`$dir/autosetup-find-tclsh`" "$dir/autosetup" "$@"
deleted configure.ac
@@ -1,552 +0,0 @@
-
m4_define([maj_ver], [1])
-
m4_define([med_ver], [10])
-
m4_define([min_ver], [99])
-
m4_define([api_ver], [m4_eval(maj_ver * 1000000 + med_ver * 1000 + min_ver)])
-
m4_define([dev_ver], m4_expand([m4_normalize(m4_sinclude([dev_version.m4]))]))
-
m4_ifset([dev_ver],
-
       [m4_define([pkg_version], [maj_ver.med_ver.min_ver.dev_ver])],
-
       [m4_define([pkg_version], [maj_ver.med_ver.min_ver])])
-

-
AC_INIT([pkg],m4_expand([pkg_version]),[https://github.com/freebsd/pkg],[pkg])
-
AC_CONFIG_SRCDIR([configure.ac])
-
AM_INIT_AUTOMAKE([1.11 foreign -Wno-portability no-dist-gzip dist-xz])
-
AM_SILENT_RULES([yes])
-

-
# Silence warning: ar: 'u' modifier ignored since 'D' is the default
-
AC_SUBST(AR_FLAGS, [cr])
-

-
AM_MAINTAINER_MODE([enable])
-

-
dnl Here are rules for setting version-info for libpkg
-
dnl we use 3 integers: current, revision and age:
-
dnl - if you change ABI (meaning add/remove/modify), then always update `current`
-
dnl - if you modify lib (that means ALL modifies), then increase `revision`
-
dnl - if you want backward compatibility, then use `age`
-
LIBPKG_CURRENT=4
-
LIBPKG_REVISION=0
-
LIBPKG_AGE=0
-
LIBPKG_SO_VERSION="$LIBPKG_CURRENT:$LIBPKG_REVISION:$LIBPKG_AGE"
-
AC_SUBST(LIBPKG_SO_VERSION)
-

-
AC_GNU_SOURCE
-
AC_PROG_CC_C99
-
LT_INIT()
-
AC_CONFIG_MACRO_DIR([m4])
-
AX_CFLAGS_WARN_ALL
-

-
AC_C_CONST
-
AC_TYPE_SIZE_T
-
AC_CHECK_FUNCS(memmove bcopy)
-
AC_PROG_LN_S
-

-
AC_CHECK_HEADERS_ONCE([fcntl.h unistd.h elf-hints.h])
-
AC_TYPE_OFF_T
-
AC_FUNC_MMAP
-

-
if test "$ac_cv_func_mmap_fixed_mapped" = "yes"; then
-
    FILEMAP=unixfilemap
-
else
-
    FILEMAP=readfilemap
-
fi
-
AC_SUBST(FILEMAP)
-

-
AC_MSG_CHECKING(for GCC atomic builtins)
-
AC_LINK_IFELSE([
-
	AC_LANG_SOURCE([[
-
		int main() {
-
			volatile unsigned long val = 1;
-
			__sync_synchronize();
-
			__sync_val_compare_and_swap(&val, 1, 0);
-
			__sync_add_and_fetch(&val, 1);
-
			__sync_sub_and_fetch(&val, 1);
-
			return 0;
-
		}
-
	]])
-
],
-
[
-
 	AC_MSG_RESULT([yes])
-
	AC_DEFINE([HAVE_ATOMIC_BUILTINS], [1], [Has gcc/MSVC atomic intrinsics])
-
],
-
[
-
 	AC_MSG_RESULT([no])
-
])
-

-
gl_LD_VERSION_SCRIPT
-

-
AC_CANONICAL_HOST
-
case $host_os in
-
  linux*)
-
        OS_CFLAGS="-D_XOPEN_SOURCE -D_GNU_SOURCE -pthread"
-
        OS_LDFLAGS="-pthread"
-
        OS_LIBS="-ldl -lrt"
-
        OS_STATIC="false"
-
        ;;
-
  openbsd*|bitrig*)
-
        OS_CFLAGS="-D_BSD_SOURCE -I/usr/local/include"
-
        OS_LDFLAGS="-L/usr/local/lib"
-
        OS_LIBS=
-
        OS_STATIC="true"
-
        ;;
-
  *)
-
        OS_CFLAGS="-D_BSD_SOURCE"
-
        OS_LDFLAGS=
-
        OS_LIBS=
-
        OS_STATIC="true"
-
        ;;
-
esac
-

-
AC_SUBST(OS_CFLAGS)
-
AC_SUBST(OS_LDFLAGS)
-
AC_SUBST(OS_LIBS)
-
AC_SUBST(OS_STATIC)
-
AM_CONDITIONAL([BUILD_STATIC], [test x$OS_STATIC = xtrue])
-

-
CFLAGS="$CFLAGS $OS_CFLAGS"
-
LDFLAGS="$LDFLAGS $OS_LDFLAGS"
-

-
AC_CHECK_HEADERS_ONCE([machine/endian.h])
-
AC_CHECK_HEADERS_ONCE([endian.h])
-
AC_CHECK_HEADERS_ONCE([sys/endian.h])
-
AC_CHECK_HEADERS_ONCE([dlfcn.h])
-
AC_CHECK_HEADERS_ONCE([stdlib.h])
-
AC_CHECK_HEADERS_ONCE([string.h])
-
AC_CHECK_HEADERS_ONCE([memory.h])
-
AC_CHECK_HEADERS_ONCE([inttypes.h])
-

-
AC_CHECK_HEADERS_ONCE([sys/types.h])
-
AC_CHECK_HEADERS_ONCE([sys/stat.h])
-
AC_CHECK_HEADERS_ONCE([sys/param.h])
-
AC_CHECK_HEADERS_ONCE([sys/mman.h])
-
AC_CHECK_HEADERS_ONCE([sys/elf_common.h])
-
AC_CHECK_HEADERS_ONCE([link.h])
-
AC_CHECK_HEADERS_ONCE([stddef.h])
-
AC_CHECK_HEADERS_ONCE([stdarg.h])
-
AC_CHECK_HEADERS_ONCE([stdbool.h])
-
AC_CHECK_HEADERS_ONCE([stdint.h])
-
AC_CHECK_HEADERS_ONCE([ctype.h])
-
AC_CHECK_HEADERS_ONCE([errno.h])
-
AC_CHECK_HEADERS_ONCE([limits.h])
-
AC_CHECK_HEADERS_ONCE([libgen.h])
-
AC_CHECK_HEADERS_ONCE([stdio.h])
-
AC_CHECK_HEADERS_ONCE([float.h])
-
AC_CHECK_HEADERS_ONCE([math.h])
-
AC_CHECK_HEADERS_ONCE([readpassphrase.h])
-
AC_CHECK_HEADERS_ONCE([osreldate.h])
-
AC_CHECK_HEADERS_ONCE([sys/socket.h])
-
AC_CHECK_HEADERS_ONCE([netinet/in.h])
-
AC_CHECK_HEADERS_ONCE([netinet/in6.h])
-
AC_CHECK_HEADERS_ONCE([sys/statfs.h])
-
AC_CHECK_HEADERS_ONCE([sys/statvfs.h])
-
AC_CHECK_HEADERS_ONCE([dirent.h], [sys/ndir.h], [sys/dir.h], [ndir.h])
-
AC_CHECK_HEADERS_ONCE([sys/capsicum.h])
-
AC_CHECK_HEADERS_ONCE([bsd/stdlib.h])
-
AC_CHECK_HEADERS_ONCE([bsd/string.h])
-
AC_CHECK_HEADERS_ONCE([bsd/stdio.h])
-
AC_CHECK_HEADERS_ONCE([bsd/readpassphrase.h])
-
AC_CHECK_HEADERS_ONCE([bsd/libutil.h])
-
AC_CHECK_HEADERS_ONCE([bsd/err.h])
-
AC_CHECK_HEADERS_ONCE([bsd/unistd.h])
-
AC_CHECK_HEADERS_ONCE([bsd/sys/cdefs.h])
-
AC_CHECK_HEADERS_ONCE([sys/procctl.h])
-

-
AC_CHECK_HEADER([regex.h], [
-
	AC_DEFINE(HAVE_REGEX_H, 1, [Define to 1 if you have the <regex.h> header file.])
-
	],
-
	[AC_MSG_ERROR([unable to find the regex.h header])],
-
	[#include <sys/types.h>])
-

-
AC_CHECK_FUNCS_ONCE([strtofflags])
-
AC_CHECK_FUNCS_ONCE([fflagstostr])
-
AC_CHECK_FUNCS_ONCE([posix_fallocate])
-
AC_CHECK_FUNCS_ONCE([usleep])
-
AC_CHECK_FUNCS_ONCE([localtime_r])
-
AC_CHECK_FUNCS_ONCE([gmtime_r])
-
AC_CHECK_FUNCS_ONCE([strerror_r])
-
AC_CHECK_FUNCS_ONCE([strtonum])
-
AC_CHECK_FUNCS_ONCE([strnstr])
-
AC_CHECK_FUNCS_ONCE([funopen])
-
AC_CHECK_FUNCS_ONCE([fopencookie])
-
AC_CHECK_FUNCS_ONCE([sysctlbyname])
-
AC_CHECK_FUNCS_ONCE([__res_setservers])
-
AC_CHECK_MEMBERS([struct stat.st_mtim])
-

-
AC_CHECK_DECLS(
-
	[[fstatat], [openat], [unlinkat], [readlinkat], [faccessat]],
-
	[], [], [
-
		#include <sys/types.h>
-
		#include <fcntl.h>
-
		#include <sys/stat.h>
-
		#include <unistd.h>
-
	])
-
AC_CHECK_DECLS(
-
	[[be16dec], [be32dec], [be64dec], [le16dec], [le32dec], [le64dec],
-
	 [be16enc], [be32enc], [be64enc], [le16enc], [le32enc], [le64enc]],
-
	[], [], [#include <sys/endian.h>]
-
)
-
AC_CHECK_FUNCS_ONCE([eaccess])
-
AC_CHECK_FUNCS_ONCE([closefrom])
-
AC_CHECK_FUNCS_ONCE([dirfd])
-
AC_CHECK_FUNCS_ONCE([sysconf])
-

-
AC_CHECK_MEMBERS([struct in6_addr.s6_addr32, 
-
	struct in6_addr.s6_addr16, 
-
	struct sockaddr_in.sin_len, 
-
	struct sockaddr_in6.sin6_len, 
-
	struct sockaddr_storage.ss_len,
-
	struct sockaddr_storage.ss_family,
-
	struct sockaddr_storage.__ss_family], [], [],
-
[#include <sys/types.h>
-
#ifdef HAVE_NETINET_IN_H
-
#include <netinet/in.h>
-
#endif
-
#ifdef HAVE_NETINET_IN6_H
-
#include <netinet/in6.h>
-
#endif
-
#ifdef HAVE_SYS_SOCKET_H
-
#include <sys/socket.h>
-
#endif
-
])
-

-
AC_MSG_CHECKING(for IPv6 support)
-
AC_CACHE_VAL(ac_cv_ipv6,
-
	AC_TRY_COMPILE([
-
#include <sys/types.h>
-
#include <sys/socket.h>
-
#include <netinet/in.h>],
-
	[ int domain = AF_INET6; ],
-
	ac_cv_ipv6=yes,
-
	ac_cv_ipv6=no,
-
	ac_cv_ipv6=no))
-
AC_MSG_RESULT($ac_cv_ipv6)
-
if test $ac_cv_ipv6 = yes ; then
-
	CFLAGS="${CFLAGS} -DINET6=1"
-
	AC_DEFINE(INET6,1,"check if system supports IPV6")
-
fi
-

-
PKG_PROG_PKG_CONFIG
-

-
AC_DEFUN([AC_PROG_GIT], [AC_CHECK_PROG(GITBIN,git,yes)])
-
AC_PROG_GIT
-
if test x"${GITBIN}" = x"yes" ; then
-
	AC_MSG_CHECKING([for git head])
-
	if test -d "${GIT_DIR:-${ac_top_srcdir:-./}/.git}" ; then
-
		GIT_HEAD=`git rev-parse --short HEAD`
-
		if test -n "`git diff-index -m --name-only HEAD`" ; then
-
			GIT_HEAD=${GIT_HEAD}-dirty
-
		fi
-
		if test -n "${GIT_HEAD}" ; then
-
			GIT_HEAD="-${GIT_HEAD}"
-
		fi
-
	fi
-
fi
-
AH_TEMPLATE(GIT_HEAD, "Git revision")
-
AH_TEMPLATE(PKG_API, "Api version")
-
AC_MSG_RESULT([$GIT_HEAD])
-
AC_SUBST([GIT_HEAD])
-
AC_DEFINE_UNQUOTED([GIT_HEAD], $GIT_HEAD)
-
AC_DEFINE([PKG_API], [api_ver])
-

-
AC_CACHE_VAL(ac_cv_seqpacket,
-
      AC_TRY_RUN([
-
#include <sys/types.h>
-
#include <sys/socket.h>
-
int main() { return socket(AF_LOCAL, SOCK_SEQPACKET, 0) == -1 ? -1 : 0; }
-
	],
-
	ac_cv_seqpacket=yes,
-
	ac_cv_seqpacket=no,
-
	ac_cv_seqpacket=no))
-
AC_MSG_RESULT($ac_cv_seqpacket)
-
if test $ac_cv_seqpacket = yes ; then
-
	AC_DEFINE([HAVE_SEQPACKET], 1,Define [Define to 1 if you have SOCK_SEQPACKET working])
-
fi
-
AC_SUBST([HAVE_SEQPACKET])
-

-
AC_SEARCH_LIBS([lzma_version_string], [lzma], [], [
-
  AC_MSG_ERROR([unable to find the liblzma])
-
])
-
AC_SEARCH_LIBS([BZ2_bzReadOpen], [bz2], [], [
-
  AC_MSG_ERROR([unable to find the libbz2])
-
])
-
AC_SEARCH_LIBS([zlibVersion], [z], [], [
-
  AC_MSG_ERROR([unable to find the zlib])
-
])
-
AC_SEARCH_LIBS([archive_read_open], [archive], [], [
-
  AC_MSG_ERROR([unable to find the archive_read() function])
-
])
-
AC_SEARCH_LIBS([__res_query], [resolv], [], [])
-

-
AC_CHECK_HEADER([archive.h],
-
	[pkg_found_archive_headers=yes])
-
AS_IF([test "x$pkg_found_archive_headers" != "xyes"],
-
	[AC_MSG_ERROR([Unable to find the libarchive headers])])
-

-
AC_SEARCH_LIBS([jail_getid], [jail], [
-
	AC_DEFINE(HAVE_LIBJAIL, 1, [Define to 1 if you have the 'jail' library (-ljail).])
-
	LIBJAIL_LIB="-ljail"
-
	], [])
-
	
-
AC_SEARCH_LIBS([getprogname], [bsd], [
-
	AC_DEFINE(HAVE_LIBBSD, 1, [Define to 1 if you have the 'bsd' library (-lbsd).])
-
	LIBBSD_LIB="-lbsd"
-
  ], [
-
    case $host_os in
-
      linux*)
-
        AC_MSG_ERROR([Unable to find the libbsd])
-
        ;;
-
    esac
-
  ])
-

-
AC_CHECK_HEADERS([gelf.h libelf.h], [
-
	AC_CHECK_TYPES([Elf_Note], [
-
		AC_DEFINE(HAVE_GELF_H, 1, [Define to 1 if you have the <gelf.h> header file.])
-
		AC_CHECK_LIB(elf, gelf_getehdr, [
-
			AC_DEFINE(HAVE_LIBELF, 1, [Define to 1 if you have the 'elf' library (-lelf).])
-
			libelf_bundled=no
-
		]) dnl AC_CHECK_LIB
-
	], dnl AC_CHECK_TYPES
-
	[], AC_LANG_SOURCE(
-
	[[
-
#include "gelf.h"
-
#include "libelf.h"
-
	]])
-
	)])
-

-
AC_ARG_WITH([ldns], AS_HELP_STRING([--with-ldns], [Build with ldns for name resolving]))
-

-
AS_IF([test "x$with_ldns" = "xyes"], [
-
   PKG_CHECK_MODULES([LDNS], [libldns], [
-
   	AC_DEFINE([HAVE_LDNS], [1], [Use ldns])
-
   	AC_SUBST([HAVE_LDNS], [1], [Use ldns])
-
   ],
-
   [
-
   	AC_CHECK_HEADER([ldns/ldns.h], [
-
   		AC_CHECK_LIB(ldns, ldns_resolver_new_frm_file, [
-
   			AC_DEFINE([HAVE_LDNS], [1], [Use ldns])
-
   			AC_SUBST([HAVE_LDNS], [1], [Use ldns])
-
   			AC_SUBST([LDNS_LIBS], [-lldns], [LDNS library])
-
   		])
-
   	])
-
   ])
-
   AS_IF([test "x$HAVE_LDNS" != "x1"],
-
	[AC_MSG_ERROR([Unable to find the libdns])])
-
])
-

-
AC_CHECK_FUNCS(cap_sandboxed, [
-
   AC_DEFINE(HAVE_CAPSICUM, 1, [Define 1 if you have 'capsicum'.])
-
])
-

-

-
AC_CACHE_CHECK(for arc4random_uniform,
-
               ac_cv_func_arc4random_uniform,
-
               [ac_save_CFLAGS="$CFLAGS"
-
                CFLAGS="$CFLAGS -Werror"
-
                AC_TRY_COMPILE([#include <stdlib.h>],
-
                               [arc4random_uniform(255);],
-
                               [ac_cv_func_arc4random_uniform=yes],
-
                               [ac_cv_func_arc4random_uniform=no])
-
		CFLAGS="$ac_save_CFLAGS"])
-
if test "$ac_cv_func_arc4random_uniform" = yes ; then
-
	AC_DEFINE(HAVE_ARC4RANDOM, 1, [Define 1 if you have 'arc4random_uniform' function.])
-
fi
-

-
AC_CACHE_CHECK(for arc4random_stir,
-
               ac_cv_func_arc4random_stir,
-
               [ac_save_CFLAGS="$CFLAGS"
-
                CFLAGS="$CFLAGS -Werror"
-
                AC_TRY_COMPILE([#include <stdlib.h>],
-
                               [arc4random_stir();],
-
                               [ac_cv_func_arc4random_stir=yes],
-
                               [ac_cv_func_arc4random_stir=no])
-
		CFLAGS="$ac_save_CFLAGS"])
-
if test "$ac_cv_func_arc4random_stir" = yes ; then
-
   AC_DEFINE(HAVE_ARC4RANDOM_STIR, 1, [Define 1 if you have 'arc4random_stir' function.])
-
fi
-

-
AC_CACHE_CHECK(for humanize_number,
-
               ac_cv_func_humanize_number,
-
               [ac_save_CFLAGS="$CFLAGS"
-
                CFLAGS="$CFLAGS -Werror"
-
                AC_TRY_COMPILE([#include <libutil.h>],
-
                               [humanize_number(NULL, 0, 0, NULL, 0, 0);],
-
                               [ac_cv_func_humanize_number=yes],
-
                               [ac_cv_func_humanize_number=no])
-
		CFLAGS="$ac_save_CFLAGS"])
-
if test "$ac_cv_func_humanize_number" = yes ; then
-
   AC_DEFINE(HAVE_HUMANIZE_NUMBER, 1, [Define 1 if you have 'humanize_number' function.])
-
fi
-

-
AC_CACHE_CHECK(for BSD dirname(const char *),
-
               ac_cv_func_bsd_dirname,
-
               [ac_save_CFLAGS="$CFLAGS"
-
		CFLAGS="$CFLAGS -Werror"
-
		AC_TRY_COMPILE([#include <libgen.h>],
-
                               [static char *(*ac_test_dirname)(const char *) = dirname; ac_test_dirname("");],
-
                               [ac_cv_func_bsd_dirname=yes],
-
                               [ac_cv_func_bsd_dirname=no])
-
		CFLAGS="$ac_save_CFLAGS"])
-
if test "$ac_cv_func_bsd_dirname" = yes ; then
-
	AC_DEFINE(HAVE_BSD_DIRNAME, 1, [Define 1 if you have 'dirname(const char *)' function.])
-
fi
-

-
AC_CACHE_CHECK(for BSD fstatfs(int, struct statfs *buf),
-
               ac_cv_func_fstatfs,
-
               [ac_save_CFLAGS="$CFLAGS"
-
		CFLAGS="$CFLAGS -Werror"
-
		AC_TRY_COMPILE([#include <sys/param.h>
-
     					#include <sys/mount.h>],
-
                               [struct statfs stfs; static int (*ac_test_fstatfs)(int fd, struct statfs *buf) = fstatfs; ac_test_fstatfs(0, &stfs);],
-
                               [ac_cv_func_fstatfs=yes],
-
                               [ac_cv_func_fstatfs=no])
-
		CFLAGS="$ac_save_CFLAGS"])
-
if test "$ac_cv_func_fstatfs" = yes ; then
-
	AC_DEFINE(HAVE_FSTATFS, 1, [Define 1 if you have 'fstatfs(int fd, struct statfs *buf)' function.])
-
fi
-

-
AC_CHECK_FUNCS(chflags chflagsat)
-
AC_CHECK_FUNCS(utimensat futimesat)
-

-
AC_CHECK_FUNCS(basename_r)
-
AC_CACHE_CHECK(for BSD basename(const char *),
-
               ac_cv_func_bsd_basename,
-
               [ac_save_CFLAGS="$CFLAGS"
-
		CFLAGS="$CFLAGS -Werror"
-
		AC_TRY_COMPILE([#include <libgen.h>],
-
                               [static char *(*ac_test_basename)(const char *) = basename; ac_test_basename("");],
-
                               [ac_cv_func_bsd_basename=yes],
-
                               [ac_cv_func_bsd_basename=no])
-
		CFLAGS="$ac_save_CFLAGS"])
-
if test "$ac_cv_func_bsd_basename" = yes ; then
-
	AC_DEFINE(HAVE_BSD_BASENAME, 1, [Define 1 if you have 'basename(const char *)' function.])
-
fi
-

-
AC_MSG_CHECKING([for /proc/pid/fd directory])
-
if test -d "/proc/$$/fd" ; then
-
        AC_DEFINE([HAVE_PROC_PID], [1], [Define if you have /proc/$pid/fd])
-
        AC_MSG_RESULT([yes])
-
else
-
        AC_MSG_RESULT([no])
-
fi
-

-
AC_CHECK_DECL([F_CLOSEM],
-
        AC_DEFINE([HAVE_FCNTL_CLOSEM], [1], [Use F_CLOSEM fcntl for closefrom]),
-
        [],
-
        [ #include <limits.h>
-
          #include <fcntl.h> ]
-
)
-

-
AC_MSG_CHECKING([whether we should only build the static version of pkg])
-
AC_ARG_WITH([staticonly],
-
	      [AS_HELP_STRING([--with-staticonly],
-
			      [Only build the static version (default is no)])])
-

-
if test "$with_staticonly" = "yes"; then
-
	AC_MSG_RESULT([yes])
-
else
-
	AC_MSG_RESULT([no])
-
fi
-

-
AM_CONDITIONAL(DYNAMIC, test "$with_staticonly" != "no")
-

-
dnl Select appropriate ABI
-
AS_CASE(
-
	[$host_os],
-
	[darwin*],
-
	[ac_cv_binary_abi=macho],
-
	[ac_cv_binary_abi=elf]
-
)
-
AM_CONDITIONAL(HAVE_MACHO_ABI, test "$ac_cv_binary_abi" = "macho")
-
AM_CONDITIONAL(HAVE_ELF_ABI, test "$ac_cv_binary_abi" = "elf")
-
AM_CONDITIONAL(LIBELF_BUNDLED, test "$ac_cv_binary_abi" = "elf" -a "$libelf_bundled" != "no")
-

-
AC_SUBST([LIBJAIL_LIB])
-
AC_SUBST([LIBBSD_LIB])
-
AC_SUBST([TESTS])
-
AC_SUBST([LDNS_LIBS])
-
AC_SUBST([LDNS_CFLAGS])
-

-
dnl We now support merely binary repos
-
m4_define([repos], [binary])
-
m4_define([repos_ldadd], [])
-
m4_define([repos_list], [])
-
m4_define([repos_makefiles], [])
-
m4_define([repos_ldadd_static], [])
-

-
dnl Add ldadd for repo
-
m4_define([repos_add_ldadd], [
-
	m4_append([$1], [m4_join([], [$(top_builddir)/libpkg/repo/], 
-
		[$3], [/librepo_], 
-
		[$3], [$2.la ])])
-
])
-
dnl Create makefile definition for repo
-
m4_define([repos_add_makefile], [
-
	m4_append([$1], [m4_join([], [\], m4_newline(), [libpkg/repo/], 
-
		[$2], [/Makefile ])])
-
])
-
m4_define([repos_add_list], [ m4_append([$1], [m4_join([],[ ],[$2])]) ])
-
dnl Apply macros to repos list
-
m4_map([m4_curry([repos_add_ldadd], [repos_ldadd], [])], [repos])
-
m4_map([m4_curry([repos_add_ldadd], [repos_ldadd_static], [_static])], [repos])
-
m4_map([m4_curry([repos_add_makefile], [repos_makefiles])], [repos])
-
m4_map([m4_curry([repos_add_list], [repos_list])], [repos])
-

-
REPOS='m4_normalize(m4_expand([repos_list]))'
-
REPOS_LDADD='m4_normalize(m4_expand([repos_ldadd]))'
-
REPOS_LDADD_STATIC='m4_normalize(m4_expand([repos_ldadd_static]))'
-
AC_SUBST([REPOS])
-
AC_SUBST([REPOS_LDADD])
-
AC_SUBST([REPOS_LDADD_STATIC])
-

-
AC_CONFIG_FILES(Makefile \
-
		Kyuafile \
-
		src/Makefile \
-
		external/Makefile \
-
		external/blake2/Makefile \
-
		scripts/Makefile \
-
		docs/Makefile \
-
		tests/Makefile \
-
		tests/Kyuafile \
-
		tests/frontend/Kyuafile \
-
		tests/frontend/test_environment.sh \
-
		compat/Makefile \
-
		libpkg/Makefile \
-
		libpkg/repo/Makefile \
-
		libpkg/pkg.h \
-
		libpkg/pkg.pc
-
		scripts/periodic/400.status-pkg
-
		scripts/periodic/410.pkg-audit
-
		scripts/periodic/411.pkg-backup
-
		scripts/periodic/460.pkg-checksum
-
		scripts/periodic/490.status-pkg-changes
-
		scripts/completion/_pkg.bash
-
		scripts/completion/_pkg)
-
AC_CONFIG_FILES(m4_expand([repos_makefiles]))
-

-
AC_CONFIG_HEADERS(pkg_config.h)
-
AC_CONFIG_COMMANDS([pkg_repos.h], [[
-
	NMODULES=pkg_repos.h.new
-
	echo "#ifndef PKG_REPOS_H" > $NMODULES
-
	echo "#define PKG_REPOS_H" >> $NMODULES
-
	for rt in $REPOS ; do
-
		echo "extern struct pkg_repo_ops pkg_repo_${rt}_ops;" >> $NMODULES;
-
	done
-
	echo "struct pkg_repo_ops* repos_ops[] = {" >> $NMODULES
-
	for rt in $REPOS ; do
-
		echo "&pkg_repo_${rt}_ops," >> $NMODULES
-
	done
-
	echo "NULL" >> $NMODULES
-
	echo "};" >> $NMODULES
-
	echo "#endif /* PKG_REPOS_H */" >> $NMODULES
-
	if [ -f pkg_repos.h ] ; then
-
		diff $NMODULES pkg_repos.h > /dev/null 2>&1
-
		if [ $? -ne 0 ] ; then
-
			cp $NMODULES pkg_repos.h
-
		fi
-
	else
-
		cp $NMODULES pkg_repos.h
-
	fi
-
	rm $NMODULES
-
]], [REPOS="$REPOS"])
-

-
AC_CONFIG_COMMANDS([mkdir], [$MKDIR_P tests/frontend])
-

-
AC_OUTPUT
deleted dev_version.m4
@@ -1 +0,0 @@
-
7
deleted docs/Makefile.am
@@ -1,52 +0,0 @@
-
dist_man_MANS=	pkg-add.8 \
-
		pkg-alias.8 \
-
		pkg-annotate.8 \
-
		pkg-audit.8 \
-
		pkg-autoremove.8 \
-
		pkg-backup.8 \
-
		pkg-check.8 \
-
		pkg-clean.8 \
-
		pkg-config.8 \
-
		pkg-create.8 \
-
		pkg-delete.8 \
-
		pkg-fetch.8 \
-
		pkg-info.8 \
-
		pkg-install.8 \
-
		pkg-lock.8 \
-
		pkg-query.8 \
-
		pkg-register.8 \
-
		pkg-repo.8 \
-
		pkg-repository.5 \
-
		pkg-rquery.8 \
-
		pkg-search.8 \
-
		pkg-set.8 \
-
		pkg-shell.8 \
-
		pkg-shlib.8 \
-
		pkg-ssh.8 \
-
		pkg-stats.8 \
-
		pkg-update.8 \
-
		pkg-updating.8 \
-
		pkg-upgrade.8 \
-
		pkg-version.8 \
-
		pkg-which.8 \
-
		pkg.8 \
-
		pkg.conf.5 \
-
		pkg_printf.3 \
-
		pkg_repos.3
-

-
mandir=	$(prefix)/man
-

-
EXTRA_DIST=	fix-xrefs
-
.PHONY: run-fix-xrefs
-

-
run-fix-xrefs:
-
	@$(srcdir)/fix-xrefs ${dist_man_MANS}
-

-
install-data-hook:
-
	$(LN_S) -f pkg-delete.8 \
-
	$(DESTDIR)$(man8dir)/pkg-remove.8
-
	$(LN_S) -f pkg-lock.8 \
-
	$(DESTDIR)$(man8dir)/pkg-unlock.8
-
	$(LN_S) -f pkg.8 \
-
	$(DESTDIR)$(man8dir)/pkg-static.8
-

added docs/Makefile.autosetup
@@ -0,0 +1,68 @@
+
include @builddir@/mk/defs.mk
+

+
MAN3=	pkg_printf.3 \
+
	pkg_repos.3
+
MAN5=	pkg-repository.5 \
+
	pkg.conf.5
+
MAN8=	pkg-add.8 \
+
	pkg-alias.8 \
+
	pkg-annotate.8 \
+
	pkg-audit.8 \
+
	pkg-autoremove.8 \
+
	pkg-backup.8 \
+
	pkg-check.8 \
+
	pkg-clean.8 \
+
	pkg-config.8 \
+
	pkg-create.8 \
+
	pkg-delete.8 \
+
	pkg-fetch.8 \
+
	pkg-info.8 \
+
	pkg-install.8 \
+
	pkg-lock.8 \
+
	pkg-query.8 \
+
	pkg-register.8 \
+
	pkg-repo.8 \
+
	pkg-rquery.8 \
+
	pkg-search.8 \
+
	pkg-set.8 \
+
	pkg-shell.8 \
+
	pkg-shlib.8 \
+
	pkg-ssh.8 \
+
	pkg-stats.8 \
+
	pkg-update.8 \
+
	pkg-updating.8 \
+
	pkg-upgrade.8 \
+
	pkg-version.8 \
+
	pkg-which.8 \
+
	pkg.8
+

+
MAN3GZ=	$(MAN3:.3=.3.gz)
+
MAN5GZ=	$(MAN5:.5=.5.gz)
+
MAN8GZ=	$(MAN8:.8=.8.gz)
+

+
.SUFFIXES: .3.gz .5.gz .8.gz .3 .5 .8
+

+
all: $(MAN3GZ) $(MAN5GZ) $(MAN8GZ)
+

+
.3.3.gz:
+
	gzip -kfn $< > $@
+

+
.5.5.gz:
+
	gzip -kfn $< > $@
+

+
.8.8.gz:
+
	gzip -kfn $< > $@
+

+
clean:
+
	rm -f *.gz
+

+
run-fix-xrefs:
+
	./fix-xrefs $(MAN3) $(MAN5) $(MAN8)
+

+
install:
+
	install -d $(DESTDIR)$(mandir)/man3
+
	install -d $(DESTDIR)$(mandir)/man5
+
	install -d $(DESTDIR)$(mandir)/man8
+
	install -m 644 *.3.gz $(DESTDIR)$(mandir)/man3
+
	install -m 644 *.5.gz $(DESTDIR)$(mandir)/man5
+
	install -m 644 *.8.gz $(DESTDIR)$(mandir)/man8
deleted external/Makefile.am
@@ -1,289 +0,0 @@
-
AUTOMAKE_OPTIONS=	subdir-objects
-

-
dist_check_SCRIPTS=	libelf/native-elf-format \
-
			libelf/elf_types.m4 \
-
			libelf/libelf_convert.m4 \
-
			libelf/libelf_fsize.m4 \
-
			libelf/libelf_msize.m4
-
noinst_HEADERS= expat/amiga/expat_68k.h \
-
		expat/amiga/expat_base.h \
-
		expat/amiga/include/inline4/expat.h \
-
		expat/amiga/include/interfaces/expat.h \
-
		expat/amiga/include/libraries/expat.h \
-
		expat/amiga/include/proto/expat.h \
-
		expat/expat_config.h \
-
		expat/lib/amigaconfig.h \
-
		expat/lib/ascii.h \
-
		expat/lib/asciitab.h \
-
		expat/lib/expat.h \
-
		expat/lib/expat_external.h \
-
		expat/lib/iasciitab.h \
-
		expat/lib/internal.h \
-
		expat/lib/latin1tab.h \
-
		expat/lib/macconfig.h \
-
		expat/lib/nametab.h \
-
		expat/lib/utf8tab.h \
-
		expat/lib/winconfig.h \
-
		expat/lib/xmlrole.h \
-
		expat/lib/xmltok.h \
-
		expat/lib/xmltok_impl.h \
-
		expat/tests/chardata.h \
-
		expat/tests/minicheck.h \
-
		expat/vms/expat_config.h \
-
		expat/xmlwf/codepage.h \
-
		expat/xmlwf/filemap.h \
-
		expat/xmlwf/xmlfile.h \
-
		expat/xmlwf/xmlmime.h \
-
		expat/xmlwf/xmltchar.h \
-
		expat/xmlwf/xmlurl.h \
-
		expat/lib/xmltok_impl.c \
-
		expat/lib/xmltok_ns.c \
-
		libelf/_elftc.h \
-
		libelf/_libelf.h \
-
		libelf/_libelf_ar.h \
-
		libelf/_libelf_config.h \
-
		libelf/elfdefinitions.h \
-
		libelf/gelf.h \
-
		libelf/libelf.h \
-
		libmachista/hashmap.h \
-
		libmachista/libmachista.h \
-
		libucl/klib/kvec.h \
-
		libucl/klib/khash.h \
-
		libucl/include/ucl.h \
-
		libucl/src/mum.h \
-
		libucl/src/ucl_internal.h \
-
		libucl/src/ucl_hash.h \
-
		libucl/src/ucl_chartable.h \
-
		libucl/src/tree.h \
-
		libucl/uthash/uthash.h \
-
		libucl/uthash/utlist.h \
-
		libucl/uthash/utstring.h \
-
		picosat/picosat.h \
-
		sqlite/sqlite3.h \
-
		uthash/uthash.h \
-
		uthash/utlist.h \
-
		uthash/utstring.h \
-
		include/tree.h \
-
		include/siphash.h \
-
		config.h \
-
		libfetch/common.h \
-
		libfetch/fetch.h \
-
		libfetch/httperr.h \
-
		libfetch/ftperr.h \
-
		linenoise/linenoise.h
-

-
DYNLIBS=		libucl.la \
-
			libsqlite.la \
-
			libexpat.la \
-
			libpicosat.la \
-
			libfetch.la \
-
			liblinenoise.la
-
noinst_LTLIBRARIES=	libucl_static.la \
-
			libsqlite_static.la \
-
			libexpat_static.la \
-
			libpicosat_static.la \
-
			libfetch_static.la \
-
			liblinenoise_static.la
-
if LIBELF_BUNDLED
-
DYNLIBS+=		libelf.la
-
noinst_LTLIBRARIES+=	libelf_static.la
-
endif
-

-
if HAVE_MACHO_ABI
-
noinst_LTLIBRARIES+=	libmachista_static.la
-
endif
-

-
if DYNAMIC
-
noinst_LTLIBRARIES+=	$(DYNLIBS)
-
endif
-

-
libelf_la_SOURCES=	libelf/elf.c \
-
			libelf/elf_begin.c \
-
			libelf/elf_cntl.c \
-
			libelf/elf_data.c \
-
			libelf/elf_end.c \
-
			libelf/elf_errmsg.c \
-
			libelf/elf_errno.c \
-
			libelf/elf_fill.c \
-
			libelf/elf_flag.c \
-
			libelf/elf_getarhdr.c \
-
			libelf/elf_getarsym.c \
-
			libelf/elf_getbase.c \
-
			libelf/elf_getident.c \
-
			libelf/elf_hash.c \
-
			libelf/elf_kind.c \
-
			libelf/elf_memory.c \
-
			libelf/elf_next.c \
-
			libelf/elf_open.c \
-
			libelf/elf_phnum.c \
-
			libelf/elf_rand.c \
-
			libelf/elf_rawfile.c \
-
			libelf/elf_scn.c \
-
			libelf/elf_shnum.c \
-
			libelf/elf_shstrndx.c \
-
			libelf/elf_strptr.c \
-
			libelf/elf_update.c \
-
			libelf/elf_version.c \
-
			libelf/gelf_cap.c \
-
			libelf/gelf_checksum.c \
-
			libelf/gelf_dyn.c \
-
			libelf/gelf_ehdr.c \
-
			libelf/gelf_fsize.c \
-
			libelf/gelf_getclass.c \
-
			libelf/gelf_move.c \
-
			libelf/gelf_phdr.c \
-
			libelf/gelf_rel.c \
-
			libelf/gelf_rela.c \
-
			libelf/gelf_shdr.c \
-
			libelf/gelf_sym.c \
-
			libelf/gelf_syminfo.c \
-
			libelf/gelf_symshndx.c \
-
			libelf/gelf_xlate.c \
-
			libelf/libelf_align.c \
-
			libelf/libelf_allocate.c \
-
			libelf/libelf_ar.c \
-
			libelf/libelf_ar_util.c \
-
			libelf/libelf_checksum.c \
-
			libelf/libelf_data.c \
-
			libelf/libelf_ehdr.c \
-
			libelf/libelf_extended.c \
-
			libelf/libelf_memory.c \
-
			libelf/libelf_open.c \
-
			libelf/libelf_phdr.c \
-
			libelf/libelf_shdr.c \
-
			libelf/libelf_xlate.c
-
nodist_libelf_la_SOURCES=	libelf/libelf_fsize.c \
-
				libelf/libelf_msize.c \
-
				libelf/libelf_convert.c
-
libelf_la_CFLAGS=	-I$(top_srcdir)/external/libelf -I$(top_builddir)/external/libelf
-
libelf_static_la_SOURCES=	${libelf_la_SOURCES}
-
nodist_libelf_static_la_SOURCES=	$(nodist_libelf_la_SOURCES)
-
libelf_static_la_CFLAGS=	$(libelf_la_CFLAGS) -static
-
libelf_static_la_LDFLAGS=	-all-static
-

-
libmachista_static_la_SOURCES=	libmachista/libmachista.c \
-
				libmachista/hashmap.c
-
libmachista_static_la_CFLAGS=	-I$(tip_srcdir)/external/libmachista -static
-
libmachista_static_la_LDFLAGS=	-all-static
-

-
liblinenoise_la_SOURCES=	linenoise/linenoise.c
-
liblinenoise_la_CFLAGS=	-shared
-
liblinenoise_static_la_SOURCES=	$(liblinenoise_la_SOURCES)
-
liblinenoise_static_CFLAGS=	-static
-
liblinenoise_static_la_LDFLAGS=	-all-static
-

-
ucl_common_cflags=	-I$(top_srcdir)/external/libucl/uthash \
-
			-I$(top_srcdir)/external/libucl/klib \
-
			-I$(top_srcdir)/external/libucl/include  \
-
			-I$(top_srcdir)/external/libucl/src \
-
			-Wno-unused-parameter -Wno-pointer-sign
-
libucl_la_SOURCES=	libucl/src/ucl_emitter.c \
-
			libucl/src/ucl_emitter_utils.c \
-
			libucl/src/ucl_emitter_streamline.c \
-
			libucl/src/ucl_hash.c \
-
			libucl/src/ucl_parser.c \
-
			libucl/src/ucl_schema.c \
-
			libucl/src/ucl_util.c \
-
			libucl/src/ucl_msgpack.c \
-
			libucl/src/ucl_sexp.c
-
libucl_la_CFLAGS=	$(ucl_common_cflags) -shared
-
libucl_static_la_SOURCES=	$(libucl_la_SOURCES)
-
libucl_static_la_CFLAGS=	$(ucl_common_cflags) -static
-
libucl_static_la_LDFLAGS=	-all-static
-

-
expat_common_cflags=	-I$(top_srcdir)/external/expat \
-
			-I$(top_srcdir)/external/expat/lib \
-
			-DHAVE_EXPAT_CONFIG_H
-
libexpat_la_SOURCES=	expat/lib/xmlparse.c \
-
			expat/lib/xmlrole.c \
-
			expat/lib/xmltok.c
-
libexpat_la_CFLAGS=	$(expat_common_cflags) -shared
-
libexpat_static_la_SOURCES=	$(libexpat_la_SOURCES)
-
libexpat_static_la_CFLAGS=	$(expat_common_cflags) -static
-
libexpat_static_la_LDFLAGS=	-all-static
-

-
picosat_common_cflags=	-I$(top_srcdir)/external/picosat \
-
			-Wno-strict-aliasing \
-
			-Wno-unused	
-
libpicosat_la_SOURCES=	picosat/picosat.c \
-
			picosat/version.c
-
libpicosat_la_CFLAGS=	$(picosat_common_cflags) -shared
-
libpicosat_static_la_SOURCES=	$(libpicosat_la_SOURCES)
-
libpicosat_static_la_CFLAGS= $(picosat_common_cflags) -static
-
libpicosat_static_la_LDFLAGS=	-all-static
-

-
sqlite_common_cflags=	-I$(top_srcdir)/external/linenoise \
-
			-DHAVE_SQLITE_CONFIG_H \
-
			-DHAVE_LINENOISE \
-
			-Wno-unused-variable \
-
			-Wno-unused-function \
-
			-Wno-strict-aliasing \
-
			-DHAVE_USLEEP=1 \
-
			-DSQLITE_OMIT_AUTOVACUUM \
-
			-DSQLITE_OMIT_BLOB_LITERAL \
-
			-DSQLITE_OMIT_DECLTYPE \
-
			-DSQLITE_OMIT_EXPLAIN \
-
			-DSQLITE_OMIT_DEPRECATED \
-
			-DSQLITE_OMIT_LOAD_EXTENSION \
-
			-DSQLITE_OMIT_PROGRESS_CALLBACK \
-
			-DSQLITE_OMIT_TCL_VARIABLE \
-
			-DSQLITE_OMIT_UTF16 \
-
			-DSQLITE_OMIT_CAT \
-
			-DSQLITE_OMIT_CHECK \
-
			-DSQLITE_OMIT_AUTOINIT \
-
			-DSQLITE_OMIT_COMPILEOPTION_DIAGS \
-
			-DSQLITE_OMIT_INTEGRITY_CHECK \
-
			-DSQLITE_OMIT_BUILTIN_TEST \
-
			-DSQLITE_OMIT_SHARED_CACHE \
-
			-DSQLITE_ENABLE_UNLOCK_NOTIFY=1 \
-
			-DUSE_PREAD \
-
			-DUSE_PWRITE \
-
			-DSQLITE_THREADSAFE=0 \
-
			-DSQLITE_TEMP_STORE=3 \
-
			-DSQLITE_ENABLE_FTS4 \
-
			-DSQLITE_SHELL_DBNAME_PROC=pkgshell_open \
-
			-DNDEBUG
-
libsqlite_la_SOURCES=	sqlite/sqlite3.c \
-
			sqlite/shell.c
-
libsqlite_la_CFLAGS=	$(sqlite_common_cflags) -shared
-
libsqlite_static_la_SOURCES=	$(libsqlite_la_SOURCES)
-
libsqlite_static_la_CFLAGS=	$(sqlite_common_cflags) -static
-
libsqlite_static_la_LDFLAGS=	-all-static
-

-
libfetch_common_cflags=	-I$(top_srcdir)/compat -DWITH_SSL -Wno-pointer-sign
-
libfetch_la_CFLAGS=	$(libfetch_common_cflags) -shared
-
libfetch_la_SOURCES=	libfetch/common.c \
-
			libfetch/fetch.c \
-
			libfetch/file.c \
-
			libfetch/ftp.c \
-
			libfetch/http.c
-
libfetch_static_la_CFLAGS=	$(libfetch_common_cflags) -static
-
libfetch_static_la_SOURCES=	${libfetch_la_SOURCES}
-

-
if HAVE_ELF_ABI
-
CLEANFILES=	libelf/libelf_fsize.c \
-
		libelf/libelf_msize.c \
-
		libelf/libelf_convert.c \
-
		libelf/native-elf-format.h
-
BUILT_SOURCES = libelf/native-elf-format.h \
-
		libelf/libelf_convert.c \
-
		libelf/libelf_fsize.c \
-
		libelf/libelf_msize.c
-

-
libelf/libelf_convert.c:
-
	@echo "    M4    " $@;
-
	@m4 -D SRCDIR=$(srcdir)/libelf $(srcdir)/libelf/elf_types.m4 $(srcdir)/libelf/libelf_convert.m4 > $@
-

-
libelf/libelf_fsize.c:
-
	@echo "    M4    " $@;
-
	@m4 -D SRCDIR=$(srcdir)/libelf $(srcdir)/libelf/elf_types.m4 $(srcdir)/libelf/libelf_fsize.m4 > $@
-

-
libelf/libelf_msize.c:
-
	@echo "    M4    " $@;
-
	@m4 -D SRCDIR=$(srcdir)/libelf $(srcdir)/libelf/elf_types.m4 $(srcdir)/libelf/libelf_msize.m4 > $@
-
libelf/native-elf-format.h:
-
	$(srcdir)/libelf/native-elf-format > libelf/native-elf-format.h
-

-
endif
-

-
SUBDIRS=	blake2
added external/Makefile.autosetup
@@ -0,0 +1,3 @@
+
include @builddir@/mk/defs.mk
+
DIRS=	expat blake2 picosat linenoise libfetch sqlite libucl @libabidir@
+
include $(MK)/dir.mk
deleted external/blake2/Makefile.am
@@ -1,11 +0,0 @@
-
noinst_HEADERS=	blake2.h \
-
				blake2-impl.h
-

-
noinst_LTLIBRARIES=	libblake2.la libblake2_static.la
-

-
blake2_common_cflags=	-I$(top_srcdir)/compat -O3
-
libblake2_la_SOURCES=	blake2b-ref.c blake2s-ref.c
-
libblake2_la_CFLAGS=	$(blake2_common_cflags) -shared
-
libblake2_static_la_SOURCES=	$(libblake2_la_SOURCES)
-
libblake2_static_la_CFLAGS=	$(blake2_common_cflags) -static
-
libblake2_static_la_LDFLAGS=	-all-static
added external/blake2/Makefile.autosetup
@@ -0,0 +1,6 @@
+
include @builddir@/mk/defs.mk
+
LIB=	blake2
+
SRCS=	blake2b-ref.c blake2s-ref.c
+
LOCAL_CFLAGS=	-I$(top_srcdir)/compat -O3
+

+
include $(MK)/static-lib.mk
added external/expat/Makefile.autosetup
@@ -0,0 +1,12 @@
+
include @builddir@/mk/defs.mk
+

+
LIB=	expat
+
SRCS=	lib/xmlparse.c \
+
	lib/xmlrole.c \
+
	lib/xmltok.c
+
LOCAL_CFLAGS=	-I$(top_srcdir)/external/expat \
+
		-I$(top_srcdir)/external/expat/lib \
+
		-DHAVE_MEMMOVE=1 \
+
		-Wno-unused-parameter
+

+
include $(MK)/static-lib.mk
added external/libelf/Makefile.autosetup
@@ -0,0 +1,79 @@
+
include @builddir@/mk/defs.mk
+
LIB=	elf
+
SRCS=	elf_begin.c \
+
	elf_cntl.c \
+
	elf_data.c \
+
	elf_end.c \
+
	elf_errmsg.c \
+
	elf_errno.c \
+
	elf_fill.c \
+
	elf_flag.c \
+
	elf_getarhdr.c \
+
	elf_getarsym.c \
+
	elf_getbase.c \
+
	elf_getident.c \
+
	elf_hash.c \
+
	elf_kind.c \
+
	elf_memory.c \
+
	elf_next.c \
+
	elf_open.c \
+
	elf_phnum.c \
+
	elf_rand.c \
+
	elf_rawfile.c \
+
	elf_scn.c \
+
	elf_shnum.c \
+
	elf_shstrndx.c \
+
	elf_strptr.c \
+
	elf_update.c \
+
	elf_version.c \
+
	elf.c \
+
	gelf_cap.c \
+
	gelf_checksum.c \
+
	gelf_dyn.c \
+
	gelf_ehdr.c \
+
	gelf_fsize.c \
+
	gelf_getclass.c \
+
	gelf_move.c \
+
	gelf_phdr.c \
+
	gelf_rel.c \
+
	gelf_rela.c \
+
	gelf_shdr.c \
+
	gelf_sym.c \
+
	gelf_syminfo.c \
+
	gelf_symshndx.c \
+
	gelf_xlate.c \
+
	libelf_align.c \
+
	libelf_allocate.c \
+
	libelf_ar_util.c \
+
	libelf_ar.c \
+
	libelf_checksum.c \
+
	libelf_convert.c \
+
	libelf_data.c \
+
	libelf_ehdr.c \
+
	libelf_extended.c \
+
	libelf_fsize.c \
+
	libelf_memory.c \
+
	libelf_msize.c \
+
	libelf_open.c \
+
	libelf_phdr.c \
+
	libelf_shdr.c \
+
	libelf_xlate.c
+

+
LOCAL_CFLAGS=	-I$(top_srcdir)/external/libelf -I$(top_builddir)/external/libelf
+

+
$(SRCS): native-elf-format.h
+

+
libelf_fsize.c: libelf_fsize.m4 elf_types.m4
+
	m4 -D SRCDIR=$(top_srcdir)/external/libelf $(top_srcdir)/external/libelf/elf_types.m4 $(top_srcdir)/external/libelf/libelf_fsize.m4 > $@
+

+
libelf_convert.c: libelf_convert.m4 elf_types.m4
+
	m4 -D SRCDIR=$(top_srcdir)/external/libelf $(top_srcdir)/external/libelf/elf_types.m4 $(top_srcdir)/external/libelf/libelf_convert.m4 > $@
+

+
libelf_msize.c: libelf_msize.m4 elf_types.m4
+
	@m4 -D SRCDIR=$(top_srcdir)/external/libelf $(top_srcdir)/external/libelf/elf_types.m4 $(top_srcdir)/external/libelf/libelf_msize.m4 > $@
+

+
native-elf-format.h:
+
	$(top_srcdir)/external/libelf/native-elf-format > $@
+

+

+
include $(MK)/static-lib.mk
deleted external/libfetch/Makefile
@@ -1,81 +0,0 @@
-
# $FreeBSD: head/lib/libfetch/Makefile 275024 2014-11-25 11:07:26Z bapt $
-

-
.include <src.opts.mk>
-

-
LIB=		fetch
-
CFLAGS+=	-I.
-
SRCS=		fetch.c common.c ftp.c http.c file.c \
-
		ftperr.h httperr.h
-
INCS=		fetch.h
-
MAN=		fetch.3
-
CLEANFILES=	ftperr.h httperr.h
-

-
.if ${MK_INET6_SUPPORT} != "no"
-
CFLAGS+=	-DINET6
-
.endif
-

-
.if ${MK_OPENSSL} != "no"
-
CFLAGS+=	-DWITH_SSL
-
LIBADD+=	ssl crypto
-
.else
-
LIBADD+=	md
-
.endif
-

-
CFLAGS+=	-DFTP_COMBINE_CWDS
-

-
CSTD?=		c99
-

-
SHLIB_MAJOR=    6
-

-
ftperr.h: ftp.errors ${.CURDIR}/Makefile
-
	@echo "static struct fetcherr ftp_errlist[] = {" > ${.TARGET}
-
	@cat ${.CURDIR}/ftp.errors \
-
	  | grep -v ^# \
-
	  | sort \
-
	  | while read NUM CAT STRING; do \
-
	    echo "    { $${NUM}, FETCH_$${CAT}, \"$${STRING}\" },"; \
-
	  done >> ${.TARGET}
-
	@echo "    { -1, FETCH_UNKNOWN, \"Unknown FTP error\" }" >> ${.TARGET}
-
	@echo "};" >> ${.TARGET}
-

-
httperr.h: http.errors ${.CURDIR}/Makefile
-
	@echo "static struct fetcherr http_errlist[] = {" > ${.TARGET}
-
	@cat ${.CURDIR}/http.errors \
-
	  | grep -v ^# \
-
	  | sort \
-
	  | while read NUM CAT STRING; do \
-
	    echo "    { $${NUM}, FETCH_$${CAT}, \"$${STRING}\" },"; \
-
	  done >> ${.TARGET}
-
	@echo "    { -1, FETCH_UNKNOWN, \"Unknown HTTP error\" }" >> ${.TARGET}
-
	@echo "};" >> ${.TARGET}
-

-
MLINKS+= fetch.3 fetchFreeURL.3
-
MLINKS+= fetch.3 fetchGet.3
-
MLINKS+= fetch.3 fetchGetFTP.3
-
MLINKS+= fetch.3 fetchGetFile.3
-
MLINKS+= fetch.3 fetchGetHTTP.3
-
MLINKS+= fetch.3 fetchGetURL.3
-
MLINKS+= fetch.3 fetchList.3
-
MLINKS+= fetch.3 fetchListFTP.3
-
MLINKS+= fetch.3 fetchListFile.3
-
MLINKS+= fetch.3 fetchListHTTP.3
-
MLINKS+= fetch.3 fetchListURL.3
-
MLINKS+= fetch.3 fetchMakeURL.3
-
MLINKS+= fetch.3 fetchParseURL.3
-
MLINKS+= fetch.3 fetchPut.3
-
MLINKS+= fetch.3 fetchPutFTP.3
-
MLINKS+= fetch.3 fetchPutFile.3
-
MLINKS+= fetch.3 fetchPutHTTP.3
-
MLINKS+= fetch.3 fetchPutURL.3
-
MLINKS+= fetch.3 fetchStat.3
-
MLINKS+= fetch.3 fetchStatFTP.3
-
MLINKS+= fetch.3 fetchStatFile.3
-
MLINKS+= fetch.3 fetchStatHTTP.3
-
MLINKS+= fetch.3 fetchStatURL.3
-
MLINKS+= fetch.3 fetchXGet.3
-
MLINKS+= fetch.3 fetchXGetFTP.3
-
MLINKS+= fetch.3 fetchXGetFile.3
-
MLINKS+= fetch.3 fetchXGetHTTP.3
-
MLINKS+= fetch.3 fetchXGetURL.3
-

-
.include <bsd.lib.mk>
added external/libfetch/Makefile.autosetup
@@ -0,0 +1,15 @@
+
include @builddir@/mk/defs.mk
+
LIB=	fetch
+
SRCS=	common.c \
+
	fetch.c \
+
	file.c \
+
	ftp.c \
+
	http.c
+

+
LOCAL_CFLAGS=	-I$(top_srcdir)/compat \
+
		-I$(top_srcdir) \
+
		-Wno-unused-parameter \
+
		-Wno-pointer-sign \
+
		-DWITH_SSL
+

+
include $(MK)/static-lib.mk
added external/libmachista/Makefile.autosetup
@@ -0,0 +1,6 @@
+
include @builddir@/mk/defs.mk
+
LIB=	machista
+
SRCS=	libmachista.c \
+
	hashmap.c
+

+
include $(MK)/static-lib.mk
deleted external/libucl/Makefile.am
@@ -1,81 +0,0 @@
-
ACLOCAL_AMFLAGS = -I m4
-
EXTRA_DIST = uthash klib README.md
-

-
pkgconfigdir = $(libdir)/pkgconfig
-
pkgconfig_DATA = libucl.pc
-

-
if LUA_SUB
-
  LUA_SUBDIR = lua
-
endif
-

-
COVERAGE_INFO_FILE = $(top_builddir)/coverage.info
-
COVERAGE_REPORT_DIR = $(top_builddir)/coverage
-

-
.PHONY = coverage-requirement-check clean-coverage-report
-

-
coverage-requirement-check:
-
	@if test ! -e $(GCOV); then \
-
		echo "Cannot find $(GCOV). Please install gcov."; \
-
		exit 1; \
-
	fi
-

-
coverage: coverage-requirement-check clean-coverage coverage-build coverage-check coverage-report
-
	@echo "Please execute 'make clean' before 'make' or 'make check' to remove instrumented object files(compiled with -O0 etc.). Note that 'make clean' also remove coverage data."
-

-
coverage-build: coverage-requirement-check
-
	@if test `find $(top_builddir) -name "*.gcno" | wc -l` -eq 0; then \
-
		echo "Start to remove old non-instrumented object files..."; \
-
		$(MAKE) $(AM_MAKEFLAGS) clean; \
-
		echo "Successfully removed old non-instrumented object files."; \
-
	fi
-
	@echo "Start to build libraries with coverage options..."
-
	$(MAKE) $(AM_MAKEFLAGS) \
-
		CFLAGS="$(CFLAGS) $(COVERAGE_CFLAGS) $(COVERAGE_OPTFLAGS)" \
-
		CXXFLAGS="$(CXXFLAGS) $(COVERAGE_CXXFLAGS) $(COVERAGE_OPTFLAGS)" \
-
		LDFLAGS="$(LDFLAGS) $(COVERAGE_LDFLAGS)" \
-
		LIBS="$(LIBS) $(COVERAGE_LIBS)"
-
	@echo "Successfully built libraries with coverage options."
-

-
coverage-check: coverage-requirement-check
-
	@echo "Start to run tests with instrumented libraries..."
-
	$(MAKE) $(AM_MAKEFLAGS) check \
-
		CFLAGS="$(CFLAGS) $(COVERAGE_CFLAGS) $(COVERAGE_OPTFLAGS)" \
-
		CXXFLAGS="$(CXXFLAGS) $(COVERAGE_CXXFLAGS) $(COVERAGE_OPTFLAGS)" \
-
		LDFLAGS="$(LDFLAGS) $(COVERAGE_LDFLAGS)" \
-
		LIBS="$(LIBS) $(COVERAGE_LIBS)"
-
	@echo "Successfully run tests with instrumented libraries."
-

-
coverage-lcov: coverage-check coverage-requirement-check
-
	$(LCOV) --capture \
-
		--directory "$(top_builddir)/" \
-
		--output-file $(COVERAGE_INFO_FILE) \
-
		--gcov-tool $(GCOV) \
-
		--compat-libtool --checksum
-
	$(LCOV) --extract $(COVERAGE_INFO_FILE) `pwd`/src/ucl_\* \
-
		--output-file $(COVERAGE_INFO_FILE)
-

-
coverage-report: coverage-lcov
-
	@echo "Start to create coverage reports..."
-
	$(GENHTML) --prefix "$(top_srcdir)" \
-
		--output-directory $(COVERAGE_REPORT_DIR) \
-
		--title $(PACKAGE_NAME) \
-
		--legend --show-details \
-
		$(GENHTML_OPTIONS) \
-
		$(COVERAGE_INFO_FILE)
-
	@echo "Successfully created coverage reports into $(COVERAGE_REPORT_DIR) directory."
-

-
clean-coverage-report:
-
	-rm -rf $(COVERAGE_INFO_FILE)
-
	-rm -rf $(COVERAGE_REPORT_DIR)
-

-
clean-coverage: clean-coverage-report
-
	-$(LCOV) --gcov-tool $(GCOV) --zerocounters --directory $(top_builddir)
-
	@if xargs --version 2>/dev/null; then \
-
		find $(top_builddir) -name "*.gcno" | xargs --no-run-if-empty rm; \
-
	else \
-
		find $(top_builddir) -name "*.gcno" | xargs rm; \
-
	fi
-

-
clean-local: clean-coverage
-

-
SUBDIRS = src tests utils doc $(LUA_SUBDIR)
added external/libucl/Makefile.autosetup
@@ -0,0 +1,19 @@
+
include @builddir@/mk/defs.mk
+
LIB=	ucl
+
SRCS=	src/ucl_emitter_streamline.c \
+
	src/ucl_emitter_utils.c \
+
	src/ucl_emitter.c \
+
	src/ucl_hash.c \
+
	src/ucl_msgpack.c \
+
	src/ucl_parser.c \
+
	src/ucl_schema.c \
+
	src/ucl_sexp.c \
+
	src/ucl_util.c
+

+
LOCAL_CFLAGS=	-I$(top_srcdir)/external/libucl/include \
+
		-I$(top_srcdir)/external/libucl/uthash \
+
		-I$(top_srcdir)/external/libucl/klib \
+
		-I$(top_srcdir)/external/libucl/src/ \
+
		-Wno-unused-parameter
+

+
include $(MK)/static-lib.mk
deleted external/libucl/doc/Makefile.am
@@ -1,9 +0,0 @@
-
EXTRA_DIST = api.md
-

-
dist_man_MANS = libucl.3
-

-
gen-man: @PANDOC@
-
	tail -n +$$(grep -n '# Synopsis' api.md | cut -d':' -f1) api.md | \
-
	cat pandoc.template - | sed -e 's/^# \(.*\)/# \U\1/' \
-
	-e "s/%%date%%/$$(LANG=C date +'%d %B, %Y')/" | \
-
	@PANDOC@ -s -f markdown -t man -o libucl.3
deleted external/libucl/lua/Makefile.am
@@ -1,26 +0,0 @@
-
ucl_common_cflags=	-I$(top_srcdir)/src \
-
			-I$(top_srcdir)/include \
-
			-I$(top_srcdir)/uthash \
-
			-Wall -W -Wno-unused-parameter -Wno-pointer-sign
-
luaexec_LTLIBRARIES=	ucl.la
-
ucl_la_SOURCES=	lua_ucl.c
-
ucl_la_CFLAGS=	$(ucl_common_cflags) \
-
					@LUA_INCLUDE@
-
ucl_la_LDFLAGS = -module -export-dynamic -avoid-version
-
ucl_la_LIBADD=	$(top_srcdir)/src/libucl.la \
-
					@LIBFETCH_LIBS@ \
-
					@LIBCRYPTO_LIB@ \
-
					@LIBREGEX_LIB@ \
-
					@CURL_LIBS@ \
-
					@LUA_LIB@
-

-
include_HEADERS=	$(top_srcdir)/include/lua_ucl.h
-

-
ROCKSPEC = $(PACKAGE)-$(VERSION)-1.rockspec
-
EXTRA_DIST = $(PACKAGE).rockspec.in \
-
			test.lua
-
DISTCLEANFILES = $(PACKAGE).rockspec
-

-
$(ROCKSPEC): $(PACKAGE).rockspec dist
-
	sed -e 's/@MD5@/'`$(MD5SUM) $(distdir).tar.gz | \
-
	cut -d " " -f 1`'/g' < $(PACKAGE).rockspec > $@

\ No newline at end of file
deleted external/libucl/src/Makefile.am
@@ -1,30 +0,0 @@
-
libucl_common_cflags=	-I$(top_srcdir)/src \
-
			-I$(top_srcdir)/include \
-
			-I$(top_srcdir)/uthash \
-
			-I$(top_srcdir)/klib \
-
			-Wall -W -Wno-unused-parameter -Wno-pointer-sign
-
lib_LTLIBRARIES=	libucl.la
-
libucl_la_SOURCES=	ucl_emitter.c \
-
					ucl_emitter_streamline.c \
-
					ucl_emitter_utils.c \
-
					ucl_hash.c \
-
					ucl_parser.c \
-
					ucl_schema.c \
-
					ucl_util.c \
-
					ucl_msgpack.c \
-
					ucl_sexp.c
-
libucl_la_CFLAGS=	$(libucl_common_cflags) \
-
					@CURL_CFLAGS@
-
libucl_la_LDFLAGS = -version-info @SO_VERSION@
-
libucl_la_LIBADD=	@LIBFETCH_LIBS@ \
-
					@LIBCRYPTO_LIB@ \
-
					@LIBREGEX_LIB@ \
-
					@CURL_LIBS@
-

-
include_HEADERS=	$(top_srcdir)/include/ucl.h \
-
					$(top_srcdir)/include/ucl++.h
-
noinst_HEADERS=	ucl_internal.h \
-
				mum.h \
-
				ucl_hash.h \
-
				ucl_chartable.h \
-
				tree.h
deleted external/libucl/tests/Makefile.am
@@ -1,45 +0,0 @@
-
EXTRA_DIST = $(TESTS) basic schema generate.res \
-
	streamline.res rcl_test.json.xz
-

-
TESTS = basic.test \
-
		generate.test \
-
		schema.test \
-
		msgpack.test \
-
		speed.test \
-
		msgpack.test
-
TESTS_ENVIRONMENT = $(SH) \
-
			TEST_DIR=$(top_srcdir)/tests \
-
			TEST_OUT_DIR=$(top_builddir)/tests \
-
			TEST_BINARY_DIR=$(top_builddir)/tests
-

-
common_test_cflags = -I$(top_srcdir)/include \
-
					-I$(top_srcdir)/src \
-
					-I$(top_srcdir)/uthash
-
common_test_ldadd = $(top_builddir)/src/libucl.la
-

-
test_basic_SOURCES = test_basic.c
-
test_basic_LDADD = $(common_test_ldadd)
-
test_basic_CFLAGS = $(common_test_cflags)
-

-
test_speed_SOURCES = test_speed.c
-
test_speed_LDADD = $(common_test_ldadd)
-
test_speed_CFLAGS = $(common_test_cflags)
-

-
test_generate_SOURCES = test_generate.c
-
test_generate_LDADD = $(common_test_ldadd)
-
test_generate_CFLAGS = $(common_test_cflags)
-

-
test_schema_SOURCES = test_schema.c
-
test_schema_LDADD = $(common_test_ldadd)
-
test_schema_CFLAGS = $(common_test_cflags)
-

-
test_streamline_SOURCES = test_streamline.c
-
test_streamline_LDADD = $(common_test_ldadd)
-
test_streamline_CFLAGS = $(common_test_cflags)
-

-
test_msgpack_SOURCES = test_msgpack.c
-
test_msgpack_LDADD = $(common_test_ldadd)
-
test_msgpack_CFLAGS = $(common_test_cflags)
-

-
check_PROGRAMS = test_basic test_speed test_generate test_schema test_streamline \
-
	test_msgpack

\ No newline at end of file
deleted external/libucl/utils/Makefile.am
@@ -1,23 +0,0 @@
-
common_utils_cflags = -I$(top_srcdir)/include \
-
					-I$(top_srcdir)/src \
-
					-I$(top_srcdir)/uthash
-
common_utils_ldadd = $(top_builddir)/src/libucl.la
-

-
ucl_chargen_SOURCES = chargen.c
-
ucl_chargen_LDADD = $(common_utils_ldadd)
-
ucl_chargen_CFLAGS = $(common_utils_cflags)
-

-
ucl_objdump_SOURCES = objdump.c
-
ucl_objdump_LDADD = $(common_utils_ldadd)
-
ucl_objdump_CFLAGS = $(common_utils_cflags)
-

-
ucl_tool_SOURCES = ucl-tool.c
-
ucl_tool_LDADD = $(common_utils_ldadd)
-
ucl_tool_CFLAGS = $(common_utils_cflags)
-

-
if UTILS
-
UTL = ucl_chargen ucl_objdump ucl_tool
-
else
-
UTL =
-
endif
-
bin_PROGRAMS = $(UTL)

\ No newline at end of file
added external/linenoise/Makefile.autosetup
@@ -0,0 +1,5 @@
+
include @builddir@/mk/defs.mk
+
LIB=	linenoise
+
SRCS=	linenoise.c
+

+
include $(MK)/static-lib.mk
added external/picosat/Makefile.autosetup
@@ -0,0 +1,7 @@
+
include @builddir@/mk/defs.mk
+
LIB=	picosat
+
SRCS=	picosat.c \
+
	version.c
+
LOCAL_CFLAGS=	-Wno-strict-aliasing \
+
		-Wno-unused
+
include $(MK)/static-lib.mk
added external/sqlite/Makefile.autosetup
@@ -0,0 +1,39 @@
+
include @builddir@/mk/defs.mk
+
LIB=	sqlite
+
SRCS=	sqlite3.c \
+
	shell.c
+

+
LOCAL_CFLAGS=	-I$(top_srcdir)/external/linenoise \
+
		-D_HAVE_SQLITE_CONFIG_H \
+
		-DHAVE_LINENOISE \
+
		-Wno-unused-variable \
+
		-Wno-unused-function \
+
		-Wno-strict-aliasing \
+
		-Wno-unused-parameter \
+
		-DHAVE_USLEEP=1 \
+
		-DSQLITE_OMIT_AUTOVACUUM \
+
		-DSQLITE_OMIT_BLOB_LITERAL \
+
		-DSQLITE_OMIT_DECLTYPE \
+
		-DSQLITE_OMIT_EXPLAIN \
+
		-DSQLITE_OMIT_DEPRECATED \
+
		-DSQLITE_OMIT_LOAD_EXTENSION \
+
		-DSQLITE_OMIT_PROGRESS_CALLBACK \
+
		-DSQLITE_OMIT_TCL_VARIABLE \
+
		-DSQLITE_OMIT_UTF16 \
+
		-DSQLITE_OMIT_CAT \
+
		-DSQLITE_OMIT_CHECK \
+
		-DSQLITE_OMIT_AUTOINIT \
+
		-DSQLITE_OMIT_COMPILEOPTION_DIAGS \
+
		-DSQLITE_OMIT_INTEGRITY_CHECK \
+
		-DSQLITE_OMIT_BUILTIN_TEST \
+
		-DSQLITE_OMIT_SHARED_CACHE \
+
		-DSQLITE_ENABLE_UNLOCK_NOTIFY=1 \
+
		-DUSE_PREAD \
+
		-DUSE_PWRITE \
+
		-DSQLITE_THREADSAFE=0 \
+
		-DSQLITE_TEMP_STORE=3 \
+
		-DSQLITE_ENABLE_FTS4 \
+
		-DSQLITE_SHELL_DBNAME_PROC=pkgshell_open \
+
		-DNDEBUG
+

+
include $(MK)/static-lib.mk
deleted libpkg/Makefile.am
@@ -1,150 +0,0 @@
-
EXTRA_DIST=		libpkg.ver
-

-
pkg_common_cflags=	-I$(top_srcdir)/libpkg -I$(top_builddir)/libpkg \
-
			@LDNS_CFLAGS@ \
-
			-I$(top_srcdir)/external/libfetch \
-
			-I$(top_srcdir)/compat \
-
			-I$(top_srcdir)/external/expat/lib \
-
			-I$(top_srcdir)/external/libucl/include \
-
			-I$(top_srcdir)/external/libucl/klib \
-
			-I$(top_srcdir)/external/libucl/src \
-
			-I$(top_srcdir)/external/picosat \
-
			-I$(top_srcdir)/external/uthash \
-
			-I$(top_srcdir)/external/sqlite \
-
			-I$(top_srcdir)/external/include \
-
			-I$(top_srcdir)/external/blake2 \
-
			-DPREFIX=\"$(prefix)\" \
-
			-Wno-pointer-sign
-

-
if LIBELF_BUNDLED
-
pkg_common_cflags+=	-I$(top_srcdir)/external/libelf
-
endif
-

-
libpkg_la_SOURCES=	pkg.c \
-
			backup.c \
-
			clean_cache.c \
-
			dns_utils.c \
-
			fetch.c \
-
			packing.c \
-
			metalog.c \
-
			pkg_add.c \
-
			pkg_arch.c \
-
			pkg_attributes.c \
-
			pkg_audit.c \
-
			pkg_checksum.c \
-
			pkg_config.c \
-
			pkg_cudf.c \
-
			pkg_create.c \
-
			pkg_delete.c \
-
			pkg_deps.c \
-
			pkg_event.c \
-
			pkg_jobs.c \
-
			pkg_jobs_conflicts.c \
-
			pkg_jobs_universe.c \
-
			pkg_manifest.c \
-
			pkg_object.c \
-
			pkg_ports.c \
-
			pkg_printf.c \
-
			pkg_repo.c \
-
			pkg_repo_create.c \
-
			pkg_repo_update.c \
-
			pkg_repo_meta.c \
-
			pkg_solve.c \
-
			pkg_status.c \
-
			pkg_version.c \
-
			pkgdb.c \
-
			pkgdb_iterator.c \
-
			pkgdb_query.c \
-
			rcscripts.c \
-
			rsa.c \
-
			ssh.c \
-
			scripts.c \
-
			utils.c \
-
			plugins.c \
-
			merge3.c \
-
			diff.c \
-
			sha256.c
-

-
if HAVE_ELF_ABI
-
libpkg_la_SOURCES+=	elfhints.c \
-
			pkg_elf.c
-
endif
-

-
if HAVE_MACHO_ABI
-
libpkg_la_SOURCES+=	pkg_macho.c
-
pkg_common_cflags+=	-I$(top_srcdir)/external/libmachista
-
endif
-

-
libpkg_la_CFLAGS=	@OS_CFLAGS@ $(pkg_common_cflags) -shared
-
libpkg_la_LIBADD=	$(top_builddir)/compat/libbsd_compat.la \
-
			$(top_builddir)/external/libucl.la \
-
			$(top_builddir)/external/libsqlite.la \
-
			$(top_builddir)/external/libexpat.la \
-
			$(top_builddir)/external/libpicosat.la \
-
			$(top_builddir)/external/libfetch.la \
-
			$(top_builddir)/external/liblinenoise.la \
-
			$(top_builddir)/external/blake2/libblake2.la \
-
			@REPOS_LDADD@ \
-
			@LDNS_LIBS@ \
-
			-larchive \
-
			-lutil \
-
			-lssl \
-
			-lcrypto \
-
			-lm
-

-
if HAVE_ELF_ABI
-
if LIBELF_BUNDLED
-
libpkg_la_LIBADD+=	$(top_builddir)/external/libelf.la
-
else
-
libpkg_la_LIBADD+=	-lelf
-
endif
-
endif
-

-
if HAVE_MACHO_ABI
-
libpkg_la_LIBADD+=	$(top_builddir)/external/libmachista_static.la
-
endif
-

-
libpkg_la_LDFLAGS=	-version-info @LIBPKG_SO_VERSION@
-
EXTRA_libpkg_la_DEPENDENCIES=	@REPOS_LDADD@
-

-
if HAVE_LD_VERSION_SCRIPT
-
libpkg_la_LDFLAGS+=	-version-info @LIBPKG_SO_VERSION@ -Wl,--version-script=$(srcdir)/libpkg.ver
-
EXTRA_libpkg_la_DEPENDENCIES+=	libpkg.ver
-
endif
-

-
DYNLIBS=		libpkg.la
-
lib_LTLIBRARIES=	libpkg_static.la
-
if DYNAMIC
-
lib_LTLIBRARIES+=	$(DYNLIBS)
-
endif
-
include_HEADERS=	pkg.h
-

-
libpkg_static_la_SOURCES=	$(libpkg_la_SOURCES)
-
libpkg_static_la_CFLAGS=	$(pkg_common_cflags) -static
-
libpkg_static_la_LIBADD=	$(top_builddir)/external/libucl_static.la \
-
			$(top_builddir)/external/libsqlite_static.la \
-
			$(top_builddir)/external/libexpat_static.la \
-
			$(top_builddir)/external/libpicosat_static.la \
-
			$(top_builddir)/external/libfetch_static.la \
-
			$(top_builddir)/external/liblinenoise_static.la \
-
			$(top_builddir)/external/blake2/libblake2_static.la \
-
			@REPOS_LDADD_STATIC@
-

-
EXTRA_libpkg_static_la_DEPENDENCIES=	@REPOS_LDADD_STATIC@ libpkg.ver
-

-
libpkg_static_la_LDFLAGS=	-all-static
-

-
noinst_HEADERS=		private/db_upgrades.h \
-
			private/elf_tables.h \
-
			private/event.h \
-
			private/ldconfig.h \
-
			private/pkg.h \
-
			private/pkg_printf.h \
-
			private/pkgdb.h \
-
			private/utils.h \
-
			private/pkg_jobs.h \
-
			private/pkg_deps.h \
-
			xmalloc.h \
-
			sha256.h
-

-
SUBDIRS = repo .
added libpkg/Makefile.autosetup
@@ -0,0 +1,142 @@
+
include @builddir@/mk/defs.mk
+
LIB=	pkg
+
SRCS=	backup.c \
+
	merge3.c \
+
	pkg_audit.c \
+
	pkg_deps.c \
+
	pkg_repo_meta.c \
+
	pkg.c \
+
	rsa.c \
+
	clean_cache.c \
+
	metalog.c \
+
	pkg_checksum.c \
+
	pkg_elf.c \
+
	pkg_manifest.c \
+
	pkg_repo_update.c \
+
	pkgdb_iterator.c \
+
	scripts.c diff.c \
+
	packing.c \
+
	pkg_config.c \
+
	pkg_event.c \
+
	pkg_object.c \
+
	pkg_repo.c \
+
	pkgdb_query.c \
+
	sha256.c dns_utils.c \
+
	pkg_add.c \
+
	pkg_create.c \
+
	pkg_jobs_conflicts.c pkg_ports.c \
+
	pkg_solve.c \
+
	pkgdb.c \
+
	ssh.c elfhints.c \
+
	pkg_arch.c \
+
	pkg_cudf.c \
+
	pkg_jobs_universe.c  pkg_printf.c \
+
	pkg_status.c \
+
	plugins.c \
+
	utils.c fetch.c \
+
	pkg_attributes.c \
+
	pkg_delete.c \
+
	pkg_jobs.c \
+
	pkg_repo_create.c \
+
	pkg_version.c \
+
	rcscripts.c
+

+
LOCAL_CFLAGS=	-I$(top_srcdir)/compat \
+
		-I$(top_srcdir)/external/blake2 \
+
		-I$(top_srcdir)/external/sqlite \
+
		-I$(top_srcdir)/external/uthash \
+
		-I$(top_srcdir)/external/picosat \
+
		-I$(top_srcdir)/external/expat/lib \
+
		-I$(top_srcdir)/external/include \
+
		-I$(top_srcdir)/external/libucl/include \
+
		-I$(top_srcdir)/external/libucl/klib \
+
		-I$(top_srcdir)/external/libfetch \
+
		-I$(top_srcdir)/libpkg/repo \
+
		-I$(top_srcdir)/libpkg \
+
		-I$(top_srcdir) \
+
		-Wno-pointer-sign \
+
		-Wno-missing-field-initializers \
+
		-Wno-sign-compare \
+
		-DPREFIX=\"$(PREFIX)\" \
+
		-DHAVE_CONFIG_H
+

+
LOCAL_LDFLAGS=	@REPOS_LDFLAGS@ \
+
		-L$(top_builddir)/external/sqlite -lsqlite_pic \
+
		-L$(top_builddir)/external/libucl -lucl_pic \
+
		-L$(top_builddir)/external/picosat -lpicosat_pic \
+
		-L$(top_builddir)/external/linenoise -llinenoise_pic \
+
		-L$(top_builddir)/external/expat -lexpat_pic \
+
		-L$(top_builddir)/external/blake2 -lblake2_pic \
+
		-L$(top_builddir)/compat -lbsd_compat_pic \
+
		-L$(top_builddir)/external/libfetch -lfetch_pic \
+
		-lssl \
+
		-lcrypto \
+
		-lm \
+
		-Wl,--version-script=$(top_builddir)/libpkg/libpkg.ver
+

+
STATIC_LIBS=	@REPOS_STATIC_LIBS@ \
+
		$(top_builddir)/external/sqlite/libsqlite.a \
+
		$(top_builddir)/external/libucl/libucl.a \
+
		$(top_builddir)/external/picosat/libpicosat.a \
+
		$(top_builddir)/external/linenoise/liblinenoise.a \
+
		$(top_builddir)/external/expat/libexpat.a \
+
		$(top_builddir)/external/blake2/libblake2.a \
+
		$(top_builddir)/compat/libbsd_compat.a \
+
		$(top_builddir)/external/libfetch/libfetch.a \
+
		lib$(LIB).a
+

+
@if HAVE_LIBUTIL
+
LOCAL_LDFLAGS+=	-lutil
+
@endif
+

+
@if libabidir == libmachista
+
LOCAL_CFLAGS+= -I$(top_srcdir)/external/libmachista
+
STATIC_LIBS+=	$(top_builddir)/external/libmachista/libmachista.a
+
LOCAL_LDFLAGS+=	-L$(top_builddir)/external/libmachista -lmachista_pic -Lresolv
+
@endif
+

+
@if libabidir == libelf
+
LOCAL_CFLAGS+= -I$(top_srcdir)/external/libelf
+
STATIC_LIBS+=	$(top_builddir)/external/libelf/libelf.a
+
LOCAL_LDFLAGS+=	-L$(top_builddir)/external/libelf -lelf
+
@endif
+

+
@if libabidir
+
@else
+
LOCAL_LDFLAGS+=	-lelf
+
@endif
+

+
@if PKG_LIBARCHIVE_LIBS
+
LOCAL_CFLAGS+=	@PKG_LIBARCHIVE_CFLAGS@
+
LOCAL_LDFLAGS+=	@PKG_LIBARCHIVE_LDFLAGS@ @PKG_LIBARCHIVE_LIBS@
+
@endif
+

+
@if PKG_LIBLDNS_LIBS
+
LOCAL_CFLAGS+=	@PKG_LIBLDNS_CFLAGS@
+
LOCAL_LDFLAGS+=	@PKG_LIBLDNS_LDFLAGS@ @PKG_LIBLDNS_LIBS@
+
@endif
+

+
include $(MK)/lib.mk
+

+
all: lib$(LIB)_flat.a
+

+
lib$(LIB)_flat.a: mergelib_script
+
	ar -M < mergelib_script
+

+
mergelib_script: $(STATIC_LIBS)
+
	@echo "CREATE lib$(LIB)_flat.a" > $@
+
	@for l in $(STATIC_LIBS); do \
+
		echo "ADDLIB $$l"; \
+
	done >> $@
+
	@echo "SAVE" >> $@
+
	@echo "END" >> $@
+

+
install: all pkg.h lib$(LIB)$(LIBSOEXT) lib$(LIB).a
+
	install -d -m 755 $(DESTDIR)$(libdir)
+
	install -d -m 755 $(DESTDIR)$(includedir)
+
	install -d -m 755 $(DESTDIR)$(pkgconfigdir)
+
	install -s -m 644 lib$(LIB)$(LIBSOEXT) $(DESTDIR)$(libdir)/
+
	ln -sf lib$(LIB)$(LIBSOEXT) $(DESTDIR)$(libdir)/lib$(LIB)$(SH_SOEXT)
+
	install -s -m 644 lib$(LIB).a $(DESTDIR)$(libdir)/
+
	install -m 644 pkg.h $(DESTDIR)$(includedir)/
+
	install -m 644 pkg.pc $(DESTDIR)$(pkgconfigdir)
modified libpkg/pkg_checksum.c
@@ -330,7 +330,7 @@ pkg_checksum_is_valid(const char *cksum, size_t clen)

/* <hashtype>$<hash> */
pkg_checksum_type_t
-
pkg_checksum_file_get_type(const char *cksum, size_t clen)
+
pkg_checksum_file_get_type(const char *cksum, size_t clen __unused)
{
	unsigned int value;

@@ -346,7 +346,7 @@ pkg_checksum_file_get_type(const char *cksum, size_t clen)

/* <version>$<hashtype>$<hash> */
pkg_checksum_type_t
-
pkg_checksum_get_type(const char *cksum, size_t clen)
+
pkg_checksum_get_type(const char *cksum, size_t clen __unused)
{
	const char *sep;
	unsigned int value;
modified libpkg/pkg_delete.c
@@ -191,7 +191,7 @@ rmdir_p(struct pkgdb *db, struct pkg *pkg, char *dir, const char *prefix_r)
	int64_t cnt;
	char fullpath[MAXPATHLEN];
	size_t len;
-
#if defined(HAVE_CHFLAGS)
+
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
	struct stat st;
#if !defined(HAVE_CHFLAGSAT)
	int fd;
@@ -220,7 +220,7 @@ rmdir_p(struct pkgdb *db, struct pkg *pkg, char *dir, const char *prefix_r)
		return;

	pkg_debug(1, "removing directory %s", fullpath);
-
#ifdef HAVE_CHFLAGS
+
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
	if (fstatat(pkg->rootfd, dir, &st, AT_SYMLINK_NOFOLLOW) != -1) {
		if (st.st_flags & NOCHANGESFLAGS) {
#ifdef HAVE_CHFLAGSAT
@@ -283,7 +283,7 @@ pkg_delete_file(struct pkg *pkg, struct pkg_file *file, unsigned force)
	const char *path;
	const char *prefix_rel;
	size_t len;
-
#if defined(HAVE_CHFLAGS)
+
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
	struct stat st;
#if !defined(HAVE_CHFLAGSAT)
	int fd;
@@ -300,7 +300,7 @@ pkg_delete_file(struct pkg *pkg, struct pkg_file *file, unsigned force)
	while (len > 0 && prefix_rel[len - 1] == '/')
		len--;

-
#ifdef HAVE_CHFLAGS
+
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
	if (fstatat(pkg->rootfd, path, &st, AT_SYMLINK_NOFOLLOW) != -1) {
		if (st.st_flags & NOCHANGESFLAGS) {
#ifdef HAVE_CHFLAGSAT
modified libpkg/pkg_elf.c
@@ -456,7 +456,7 @@ analyse_fpath(struct pkg *pkg, const char *fpath)
}

int
-
pkg_analyse_files(struct pkgdb *db, struct pkg *pkg, const char *stage)
+
pkg_analyse_files(struct pkgdb *db __unused, struct pkg *pkg, const char *stage)
{
	struct pkg_file *file = NULL;
	char *sh;
modified libpkg/pkg_jobs.c
@@ -2303,7 +2303,7 @@ pkg_jobs_has_lockedpkgs(struct pkg_jobs *j)
}

static void
-
pkg_jobs_visit_lockedpkgs(const void * node, VISIT v, int __unused0)
+
pkg_jobs_visit_lockedpkgs(const void * node, VISIT v, int i __unused)
{

	if (v == postorder || v == leaf) {
modified libpkg/pkg_jobs_universe.c
@@ -154,7 +154,7 @@ pkg_jobs_universe_get_remote(struct pkg_jobs_universe *universe,
 */
int
pkg_jobs_universe_add_pkg(struct pkg_jobs_universe *universe, struct pkg *pkg,
-
		bool force, struct pkg_job_universe_item **found)
+
		bool force __unused, struct pkg_job_universe_item **found)
{
	struct pkg_job_universe_item *item, *seen, *tmp = NULL;

@@ -372,7 +372,7 @@ pkg_jobs_universe_process_deps(struct pkg_jobs_universe *universe,

static int
pkg_jobs_universe_handle_provide(struct pkg_jobs_universe *universe,
-
		struct pkgdb_it *it, const char *name, bool is_shlib, struct pkg *parent)
+
    struct pkgdb_it *it, const char *name, bool is_shlib, struct pkg *parent __unused)
{
	struct pkg_job_universe_item *unit;
	struct pkg_job_provide *pr, *prhead;
modified libpkg/pkg_manifest.c
@@ -602,7 +602,7 @@ pkg_obj(struct pkg *pkg, const ucl_object_t *obj, uint32_t attr)
}

static int
-
pkg_message(struct pkg *pkg, const ucl_object_t *obj, uint32_t attr)
+
pkg_message(struct pkg *pkg, const ucl_object_t *obj, uint32_t attr __unused)
{
	return pkg_message_from_ucl(pkg, obj);
}
modified libpkg/pkg_ports.c
@@ -168,7 +168,7 @@ free_file_attr(struct file_attr *a)
}

static int
-
setprefix(struct plist *p, char *line, struct file_attr *a)
+
setprefix(struct plist *p, char *line, struct file_attr *a __unused)
{
	/* if no arguments then set default prefix */
	if (line[0] == '\0') {
@@ -190,7 +190,7 @@ setprefix(struct plist *p, char *line, struct file_attr *a)
}

static int
-
name_key(struct plist *p, char *line, struct file_attr *a)
+
name_key(struct plist *p, char *line, struct file_attr *a __unused)
{
	char *tmp;

@@ -207,7 +207,7 @@ name_key(struct plist *p, char *line, struct file_attr *a)
}

static int
-
pkgdep(struct plist *p, char *line, struct file_attr *a)
+
pkgdep(struct plist *p, char *line, struct file_attr *a __unused)
{
	if (*line != '\0') {
		free(p->pkgdep);
@@ -410,7 +410,7 @@ file(struct plist *p, char *line, struct file_attr *a)
}

static int
-
setmod(struct plist *p, char *line, struct file_attr *a)
+
setmod(struct plist *p, char *line, struct file_attr *a __unused)
{
	void *set;

@@ -428,7 +428,7 @@ setmod(struct plist *p, char *line, struct file_attr *a)
}

static int
-
setowner(struct plist *p, char *line, struct file_attr *a)
+
setowner(struct plist *p, char *line, struct file_attr *a __unused)
{
	free(p->uname);
	if (line[0] == '\0')
@@ -439,7 +439,7 @@ setowner(struct plist *p, char *line, struct file_attr *a)
}

static int
-
setgroup(struct plist *p, char *line, struct file_attr *a)
+
setgroup(struct plist *p, char *line, struct file_attr *a __unused)
{
	free(p->gname);
	if (line[0] == '\0')
@@ -450,7 +450,7 @@ setgroup(struct plist *p, char *line, struct file_attr *a)
}

static int
-
comment_key(struct plist *p, char *line, struct file_attr *a)
+
comment_key(struct plist *p, char *line, struct file_attr *a __unused)
{
	char *name, *version, *line_options, *line_options2, *option;

@@ -489,7 +489,7 @@ comment_key(struct plist *p, char *line, struct file_attr *a)
}

static int
-
ignore_next(struct plist *p, __unused char *line, struct file_attr *a)
+
ignore_next(struct plist *p, __unused char *line, struct file_attr *a __unused)
{
	p->ignore_next = true;
	if (ctx.developer_mode)
modified libpkg/pkg_repo_create.c
@@ -85,17 +85,6 @@ pkg_digest_sort_compare_func(struct digest_list_entry *d1,
	return strcmp(d1->origin, d2->origin);
}

-
static void
-
pkg_repo_new_conflict(const char *uniqueid, struct pkg_conflict_bulk *bulk)
-
{
-
	struct pkg_conflict *new;
-

-
	new = xcalloc(1, sizeof(*new));
-
	new->uid = xstrdup(uniqueid);
-

-
	kh_safe_add(pkg_conflicts, bulk->conflictshash, new, new->uid);
-
}
-

struct pkg_fts_item {
	char *fts_accpath;
	char *pkg_path;
@@ -640,7 +629,7 @@ pkg_create_repo(char *path, const char *output_dir, bool filelist,
			int ofl;
			int st = SOCK_DGRAM;

-
#ifdef HAVE_SEQPACKET
+
#ifdef HAVE_DECL_SOCK_SEQPACKET
			st = SOCK_SEQPACKET;
#endif
			if (socketpair(AF_UNIX, st, 0, cur_pipe) == -1) {
modified libpkg/pkg_solve.c
@@ -891,7 +891,7 @@ err:
}

static int
-
pkg_solve_picosat_iter(struct pkg_solve_problem *problem, int iter)
+
pkg_solve_picosat_iter(struct pkg_solve_problem *problem, int iter __unused)
{
	int res, i;
	struct pkg_solve_variable *var, *cur;
deleted libpkg/repo/Makefile.am
@@ -1 +0,0 @@
-
SUBDIRS = @REPOS@

\ No newline at end of file
added libpkg/repo/Makefile.autosetup
@@ -0,0 +1,21 @@
+
include @builddir@/mk/defs.mk
+
DIRS=	@REPOS@
+

+
all: pkg_repos.h
+

+
pkg_repos.h: $(DIRS)
+
	@echo "#ifndef PKG_REPOS_H" > $@
+
	@echo "#define PKG_REPOS_H" >> $@
+
	@for b in $(DIRS); do \
+
		echo "extern struct pkg_repo_ops pkg_repo_$${b}_ops;" ; \
+
	done >> $@
+
	@echo "struct pkg_repo_ops *repos_ops[] = {" >> $@
+
	@for b in $(DIRS); do \
+
		echo "&pkg_repo_$${b}_ops," ; \
+
	done >> $@
+
	@echo "NULL" >> $@
+
	@echo "};" >> $@
+
	@echo "#endif /* PKG_REPOS_H */" >> $@
+

+
include $(MK)/dir.mk
+

deleted libpkg/repo/binary/Makefile.am
@@ -1,29 +0,0 @@
-
pkg_common_cflags=	-I$(top_srcdir)/libpkg -I$(top_builddir)/libpkg \
-
			-I$(top_srcdir)/compat \
-
			@LDNS_CFLAGS@ \
-
			-I$(top_srcdir)/external/expat/lib \
-
			-I$(top_srcdir)/external/libucl/include \
-
			-I$(top_srcdir)/external/libucl/klib \
-
			-I$(top_srcdir)/external/uthash \
-
			-I$(top_srcdir)/external/sqlite \
-
			-Wno-pointer-sign
-

-
librepo_binary_la_SOURCES=	binary.c \
-
							common.c \
-
							fetch.c \
-
							init.c \
-
							query.c \
-
							update.c
-
librepo_binary_la_CFLAGS=	$(pkg_common_cflags) -shared
-

-
librepo_binary_static_la_LDFLAGS=	-all-static
-
librepo_binary_static_la_SOURCES=	$(librepo_binary_la_SOURCES)
-
librepo_binary_static_la_CFLAGS=	$(pkg_common_cflags) -static
-

-
DYNLIBS=		librepo_binary.la
-
noinst_LTLIBRARIES= librepo_binary_static.la
-
if DYNAMIC
-
noinst_LTLIBRARIES+=	$(DYNLIBS)
-
endif
-

-
noinst_HEADERS=		binary.h binary_private.h
added libpkg/repo/binary/Makefile.autosetup
@@ -0,0 +1,17 @@
+
include @builddir@/mk/defs.mk
+
LIB=	repo-binary
+
SRCS=	binary.c \
+
	common.c \
+
	fetch.c \
+
	init.c \
+
	query.c \
+
	update.c
+
LOCAL_CFLAGS=	-I$(top_srcdir)/libpkg \
+
		-I$(top_srcdir)/external/uthash \
+
		-I$(top_srcdir)/external/sqlite \
+
		-I$(top_srcdir)/external/libucl/include \
+
		-I$(top_srcdir)/external/libucl/klib \
+
		-I$(top_srcdir)/compat \
+
		-I$(top_srcdir)/ \
+

+
include $(MK)/static-lib.mk
modified libpkg/xmalloc.h
@@ -1,6 +1,8 @@
#ifndef XMALLOC_H
#define XMALLOC_H

+
#include <stdio.h>
+

static inline void *xmalloc(size_t size)
{
	void *ptr = malloc(size);
deleted m4/.gitignore
@@ -1,5 +0,0 @@
-
# Ignore everything in this directory
-
*
-
# Except this file
-
!.gitignore
-
!ax_*.m4
deleted m4/ax_append_flag.m4
@@ -1,70 +0,0 @@
-
# ===========================================================================
-
#      http://www.gnu.org/software/autoconf-archive/ax_append_flag.html
-
# ===========================================================================
-
#
-
# SYNOPSIS
-
#
-
#   AX_APPEND_FLAG(FLAG, [FLAGS-VARIABLE])
-
#
-
# DESCRIPTION
-
#
-
#   FLAG is appended to the FLAGS-VARIABLE shell variable, with a space
-
#   added in between.
-
#
-
#   If FLAGS-VARIABLE is not specified, the current language's flags (e.g.
-
#   CFLAGS) is used.  FLAGS-VARIABLE is not changed if it already contains
-
#   FLAG.  If FLAGS-VARIABLE is unset in the shell, it is set to exactly
-
#   FLAG.
-
#
-
#   NOTE: Implementation based on AX_CFLAGS_GCC_OPTION.
-
#
-
# LICENSE
-
#
-
#   Copyright (c) 2008 Guido U. Draheim <guidod@gmx.de>
-
#   Copyright (c) 2011 Maarten Bosmans <mkbosmans@gmail.com>
-
#
-
#   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 the
-
#   Free Software Foundation, either version 3 of the License, or (at your
-
#   option) any later version.
-
#
-
#   This program is distributed in the hope that it will be useful, but
-
#   WITHOUT ANY WARRANTY; without even the implied warranty of
-
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
-
#   Public License for more details.
-
#
-
#   You should have received a copy of the GNU General Public License along
-
#   with this program. If not, see <http://www.gnu.org/licenses/>.
-
#
-
#   As a special exception, the respective Autoconf Macro's copyright owner
-
#   gives unlimited permission to copy, distribute and modify the configure
-
#   scripts that are the output of Autoconf when processing the Macro. You
-
#   need not follow the terms of the GNU General Public License when using
-
#   or distributing such scripts, even though portions of the text of the
-
#   Macro appear in them. The GNU General Public License (GPL) does govern
-
#   all other use of the material that constitutes the Autoconf Macro.
-
#
-
#   This special exception to the GPL applies to versions of the Autoconf
-
#   Macro released by the Autoconf Archive. When you make and distribute a
-
#   modified version of the Autoconf Macro, you may extend this special
-
#   exception to the GPL to apply to your modified version as well.
-

-
#serial 2
-

-
AC_DEFUN([AX_APPEND_FLAG],
-
[AC_PREREQ(2.59)dnl for _AC_LANG_PREFIX
-
AS_VAR_PUSHDEF([FLAGS], [m4_default($2,_AC_LANG_PREFIX[FLAGS])])dnl
-
AS_VAR_SET_IF(FLAGS,
-
  [case " AS_VAR_GET(FLAGS) " in
-
    *" $1 "*)
-
      AC_RUN_LOG([: FLAGS already contains $1])
-
      ;;
-
    *)
-
      AC_RUN_LOG([: FLAGS="$FLAGS $1"])
-
      AS_VAR_SET(FLAGS, ["AS_VAR_GET(FLAGS) $1"])
-
      ;;
-
   esac],
-
  [AS_VAR_SET(FLAGS,["$1"])])
-
AS_VAR_POPDEF([FLAGS])dnl
-
])dnl AX_APPEND_FLAG
-

deleted m4/ax_cflags_warn_all.m4
@@ -1,124 +0,0 @@
-
# ===========================================================================
-
#    http://www.gnu.org/software/autoconf-archive/ax_cflags_warn_all.html
-
# ===========================================================================
-
#
-
# SYNOPSIS
-
#
-
#   AX_CFLAGS_WARN_ALL   [(shellvar [,default, [A/NA]])]
-
#   AX_CXXFLAGS_WARN_ALL [(shellvar [,default, [A/NA]])]
-
#   AX_FCFLAGS_WARN_ALL  [(shellvar [,default, [A/NA]])]
-
#
-
# DESCRIPTION
-
#
-
#   Try to find a compiler option that enables most reasonable warnings.
-
#
-
#   For the GNU compiler it will be -Wall (and -ansi -pedantic) The result
-
#   is added to the shellvar being CFLAGS, CXXFLAGS, or FCFLAGS by default.
-
#
-
#   Currently this macro knows about the GCC, Solaris, Digital Unix, AIX,
-
#   HP-UX, IRIX, NEC SX-5 (Super-UX 10), Cray J90 (Unicos 10.0.0.8), and
-
#   Intel compilers.  For a given compiler, the Fortran flags are much more
-
#   experimental than their C equivalents.
-
#
-
#    - $1 shell-variable-to-add-to : CFLAGS, CXXFLAGS, or FCFLAGS
-
#    - $2 add-value-if-not-found : nothing
-
#    - $3 action-if-found : add value to shellvariable
-
#    - $4 action-if-not-found : nothing
-
#
-
#   NOTE: These macros depend on AX_APPEND_FLAG.
-
#
-
# LICENSE
-
#
-
#   Copyright (c) 2008 Guido U. Draheim <guidod@gmx.de>
-
#   Copyright (c) 2010 Rhys Ulerich <rhys.ulerich@gmail.com>
-
#
-
#   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 the
-
#   Free Software Foundation; either version 3 of the License, or (at your
-
#   option) any later version.
-
#
-
#   This program is distributed in the hope that it will be useful, but
-
#   WITHOUT ANY WARRANTY; without even the implied warranty of
-
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
-
#   Public License for more details.
-
#
-
#   You should have received a copy of the GNU General Public License along
-
#   with this program. If not, see <http://www.gnu.org/licenses/>.
-
#
-
#   As a special exception, the respective Autoconf Macro's copyright owner
-
#   gives unlimited permission to copy, distribute and modify the configure
-
#   scripts that are the output of Autoconf when processing the Macro. You
-
#   need not follow the terms of the GNU General Public License when using
-
#   or distributing such scripts, even though portions of the text of the
-
#   Macro appear in them. The GNU General Public License (GPL) does govern
-
#   all other use of the material that constitutes the Autoconf Macro.
-
#
-
#   This special exception to the GPL applies to versions of the Autoconf
-
#   Macro released by the Autoconf Archive. When you make and distribute a
-
#   modified version of the Autoconf Macro, you may extend this special
-
#   exception to the GPL to apply to your modified version as well.
-

-
#serial 15
-

-
AC_DEFUN([AX_FLAGS_WARN_ALL],[dnl
-
AS_VAR_PUSHDEF([FLAGS],[_AC_LANG_PREFIX[]FLAGS])dnl
-
AS_VAR_PUSHDEF([VAR],[ac_cv_[]_AC_LANG_ABBREV[]flags_warn_all])dnl
-
AC_CACHE_CHECK([m4_ifval($1,$1,FLAGS) for maximum warnings],
-
VAR,[VAR="no, unknown"
-
ac_save_[]FLAGS="$[]FLAGS"
-
for ac_arg dnl
-
in "-warn all  % -warn all"   dnl Intel
-
   "-pedantic  % -Wall -Wno-unused-function" dnl clang
-
   "-pedantic  % -Wall -Wno-unused-function"       dnl GCC
-
   "-xstrconst % -v"          dnl Solaris C
-
   "-std1      % -verbose -w0 -warnprotos" dnl Digital Unix
-
   "-qlanglvl=ansi % -qsrcmsg -qinfo=all:noppt:noppc:noobs:nocnd" dnl AIX
-
   "-ansi -ansiE % -fullwarn" dnl IRIX
-
   "+ESlit     % +w1"         dnl HP-UX C
-
   "-Xc        % -pvctl[,]fullmsg" dnl NEC SX-5 (Super-UX 10)
-
   "-h conform % -h msglevel 2" dnl Cray C (Unicos)
-
   #
-
do FLAGS="$ac_save_[]FLAGS "`echo $ac_arg | sed -e 's,%%.*,,' -e 's,%,,'`
-
   AC_COMPILE_IFELSE([AC_LANG_PROGRAM],
-
                     [VAR=`echo $ac_arg | sed -e 's,.*% *,,'` ; break])
-
done
-
FLAGS="$ac_save_[]FLAGS"
-
])
-
AS_VAR_POPDEF([FLAGS])dnl
-
AX_REQUIRE_DEFINED([AX_APPEND_FLAG])
-
case ".$VAR" in
-
     .ok|.ok,*) m4_ifvaln($3,$3) ;;
-
   .|.no|.no,*) m4_default($4,[m4_ifval($2,[AX_APPEND_FLAG([$2], [$1])])]) ;;
-
   *) m4_default($3,[AX_APPEND_FLAG([$VAR], [$1])]) ;;
-
esac
-
AS_VAR_POPDEF([VAR])dnl
-
])dnl AX_FLAGS_WARN_ALL
-
dnl  implementation tactics:
-
dnl   the for-argument contains a list of options. The first part of
-
dnl   these does only exist to detect the compiler - usually it is
-
dnl   a global option to enable -ansi or -extrawarnings. All other
-
dnl   compilers will fail about it. That was needed since a lot of
-
dnl   compilers will give false positives for some option-syntax
-
dnl   like -Woption or -Xoption as they think of it is a pass-through
-
dnl   to later compile stages or something. The "%" is used as a
-
dnl   delimiter. A non-option comment can be given after "%%" marks
-
dnl   which will be shown but not added to the respective C/CXXFLAGS.
-

-
AC_DEFUN([AX_CFLAGS_WARN_ALL],[dnl
-
AC_LANG_PUSH([C])
-
AX_FLAGS_WARN_ALL([$1], [$2], [$3], [$4])
-
AC_LANG_POP([C])
-
])
-

-
AC_DEFUN([AX_CXXFLAGS_WARN_ALL],[dnl
-
AC_LANG_PUSH([C++])
-
AX_FLAGS_WARN_ALL([$1], [$2], [$3], [$4])
-
AC_LANG_POP([C++])
-
])
-

-
AC_DEFUN([AX_FCFLAGS_WARN_ALL],[dnl
-
AC_LANG_PUSH([Fortran])
-
AX_FLAGS_WARN_ALL([$1], [$2], [$3], [$4])
-
AC_LANG_POP([Fortran])
-
])
-

deleted m4/ax_require_defined.m4
@@ -1,37 +0,0 @@
-
# ===========================================================================
-
#    http://www.gnu.org/software/autoconf-archive/ax_require_defined.html
-
# ===========================================================================
-
#
-
# SYNOPSIS
-
#
-
#   AX_REQUIRE_DEFINED(MACRO)
-
#
-
# DESCRIPTION
-
#
-
#   AX_REQUIRE_DEFINED is a simple helper for making sure other macros have
-
#   been defined and thus are available for use.  This avoids random issues
-
#   where a macro isn't expanded.  Instead the configure script emits a
-
#   non-fatal:
-
#
-
#     ./configure: line 1673: AX_CFLAGS_WARN_ALL: command not found
-
#
-
#   It's like AC_REQUIRE except it doesn't expand the required macro.
-
#
-
#   Here's an example:
-
#
-
#     AX_REQUIRE_DEFINED([AX_CHECK_LINK_FLAG])
-
#
-
# LICENSE
-
#
-
#   Copyright (c) 2014 Mike Frysinger <vapier@gentoo.org>
-
#
-
#   Copying and distribution of this file, with or without modification, are
-
#   permitted in any medium without royalty provided the copyright notice
-
#   and this notice are preserved. This file is offered as-is, without any
-
#   warranty.
-

-
#serial 1
-

-
AC_DEFUN([AX_REQUIRE_DEFINED], [dnl
-
  m4_ifndef([$1], [m4_fatal([macro ]$1[ is not defined; is a m4 file missing?])])
-
])dnl AX_REQUIRE_DEFINED
deleted m4/ld-version-script.m4
@@ -1,53 +0,0 @@
-
# ld-version-script.m4 serial 3
-
dnl Copyright (C) 2008-2014 Free Software Foundation, Inc.
-
dnl This file is free software; the Free Software Foundation
-
dnl gives unlimited permission to copy and/or distribute it,
-
dnl with or without modifications, as long as this notice is preserved.
-

-
dnl From Simon Josefsson
-

-
# FIXME: The test below returns a false positive for mingw
-
# cross-compiles, 'local:' statements does not reduce number of
-
# exported symbols in a DLL.  Use --disable-ld-version-script to work
-
# around the problem.
-

-
# gl_LD_VERSION_SCRIPT
-
# --------------------
-
# Check if LD supports linker scripts, and define automake conditional
-
# HAVE_LD_VERSION_SCRIPT if so.
-
AC_DEFUN([gl_LD_VERSION_SCRIPT],
-
[
-
  AC_ARG_ENABLE([ld-version-script],
-
    AS_HELP_STRING([--enable-ld-version-script],
-
      [enable linker version script (default is enabled when possible)]),
-
      [have_ld_version_script=$enableval], [])
-
  if test -z "$have_ld_version_script"; then
-
    AC_MSG_CHECKING([if LD -Wl,--version-script works])
-
    save_LDFLAGS="$LDFLAGS"
-
    LDFLAGS="$LDFLAGS -Wl,--version-script=conftest.map"
-
    cat > conftest.map <<EOF
-
foo
-
EOF
-
    AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],
-
                   [accepts_syntax_errors=yes], [accepts_syntax_errors=no])
-
    if test "$accepts_syntax_errors" = no; then
-
      cat > conftest.map <<EOF
-
VERS_1 {
-
        global: sym;
-
};
-

-
VERS_2 {
-
        global: sym;
-
} VERS_1;
-
EOF
-
      AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],
-
                     [have_ld_version_script=yes], [have_ld_version_script=no])
-
    else
-
      have_ld_version_script=no
-
    fi
-
    rm -f conftest.map
-
    LDFLAGS="$save_LDFLAGS"
-
    AC_MSG_RESULT($have_ld_version_script)
-
  fi
-
  AM_CONDITIONAL(HAVE_LD_VERSION_SCRIPT, test "$have_ld_version_script" = "yes")
-
])
deleted m4/pkg.m4
@@ -1,159 +0,0 @@
-
# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
-
# serial 1 (pkg-config-0.24)
-
# 
-
# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
-
#
-
# 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
-
# the Free Software Foundation; either version 2 of the License, or
-
# (at your option) any later version.
-
#
-
# This program is distributed in the hope that it will be useful, but
-
# WITHOUT ANY WARRANTY; without even the implied warranty of
-
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-
# General Public License for more details.
-
#
-
# You should have received a copy of the GNU General Public License
-
# along with this program; if not, write to the Free Software
-
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-
#
-
# As a special exception to the GNU General Public License, if you
-
# distribute this file as part of a program that contains a
-
# configuration script generated by Autoconf, you may include it under
-
# the same distribution terms that you use for the rest of that program.
-

-
# PKG_PROG_PKG_CONFIG([MIN-VERSION])
-
# ----------------------------------
-
AC_DEFUN([PKG_PROG_PKG_CONFIG],
-
[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
-
m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
-
m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$])
-
AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
-
AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
-
AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
-

-
if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
-
	AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
-
fi
-
if test -n "$PKG_CONFIG"; then
-
	_pkg_min_version=m4_default([$1], [0.9.0])
-
	AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
-
	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
-
		AC_MSG_RESULT([yes])
-
	else
-
		AC_MSG_RESULT([no])
-
		PKG_CONFIG=""
-
	fi
-
fi[]dnl
-
])# PKG_PROG_PKG_CONFIG
-

-
# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
-
#
-
# Check to see whether a particular set of modules exists.  Similar
-
# to PKG_CHECK_MODULES(), but does not set variables or print errors.
-
#
-
# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
-
# only at the first occurence in configure.ac, so if the first place
-
# it's called might be skipped (such as if it is within an "if", you
-
# have to call PKG_CHECK_EXISTS manually
-
# --------------------------------------------------------------
-
AC_DEFUN([PKG_CHECK_EXISTS],
-
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
-
if test -n "$PKG_CONFIG" && \
-
    AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
-
  m4_default([$2], [:])
-
m4_ifvaln([$3], [else
-
  $3])dnl
-
fi])
-

-
# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
-
# ---------------------------------------------
-
m4_define([_PKG_CONFIG],
-
[if test -n "$$1"; then
-
    pkg_cv_[]$1="$$1"
-
 elif test -n "$PKG_CONFIG"; then
-
    PKG_CHECK_EXISTS([$3],
-
                     [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`
-
		      test "x$?" != "x0" && pkg_failed=yes ],
-
		     [pkg_failed=yes])
-
 else
-
    pkg_failed=untried
-
fi[]dnl
-
])# _PKG_CONFIG
-

-
# _PKG_SHORT_ERRORS_SUPPORTED
-
# -----------------------------
-
AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
-
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
-
if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-
        _pkg_short_errors_supported=yes
-
else
-
        _pkg_short_errors_supported=no
-
fi[]dnl
-
])# _PKG_SHORT_ERRORS_SUPPORTED
-

-

-
# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
-
# [ACTION-IF-NOT-FOUND])
-
#
-
#
-
# Note that if there is a possibility the first call to
-
# PKG_CHECK_MODULES might not happen, you should be sure to include an
-
# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
-
#
-
#
-
# --------------------------------------------------------------
-
AC_DEFUN([PKG_CHECK_MODULES],
-
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
-
AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
-
AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
-

-
pkg_failed=no
-
AC_MSG_CHECKING([for $1])
-

-
_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
-
_PKG_CONFIG([$1][_LIBS], [libs], [$2])
-

-
m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
-
and $1[]_LIBS to avoid the need to call pkg-config.
-
See the pkg-config man page for more details.])
-

-
if test $pkg_failed = yes; then
-
   	AC_MSG_RESULT([no])
-
        _PKG_SHORT_ERRORS_SUPPORTED
-
        if test $_pkg_short_errors_supported = yes; then
-
	        $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1`
-
        else 
-
	        $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1`
-
        fi
-
	# Put the nasty error message in config.log where it belongs
-
	echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
-

-
	m4_default([$4], [AC_MSG_ERROR(
-
[Package requirements ($2) were not met:
-

-
$$1_PKG_ERRORS
-

-
Consider adjusting the PKG_CONFIG_PATH environment variable if you
-
installed software in a non-standard prefix.
-

-
_PKG_TEXT])[]dnl
-
        ])
-
elif test $pkg_failed = untried; then
-
     	AC_MSG_RESULT([no])
-
	m4_default([$4], [AC_MSG_FAILURE(
-
[The pkg-config script could not be found or is too old.  Make sure it
-
is in your PATH or set the PKG_CONFIG environment variable to the full
-
path to pkg-config.
-

-
_PKG_TEXT
-

-
To get pkg-config, see <http://pkg-config.freedesktop.org/>.])[]dnl
-
        ])
-
else
-
	$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
-
	$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
-
        AC_MSG_RESULT([yes])
-
	$3
-
fi[]dnl
-
])# PKG_CHECK_MODULES
added mk/common.mk
@@ -0,0 +1,15 @@
+
CFLAGS?=	-O2 -pipe
+
OBJS=	${SRCS:.c=.o}
+
SHOBJS?=	${SRCS:.c=.pico}
+

+
.SUFFIXES: .pico .in
+

+
.c.o:
+
	$(CC) -Wall -Wextra -std=gnu99 -D_GNU_SOURCE=1 -o $@ -c $(CFLAGS) $(LOCAL_CFLAGS) $<
+

+
.c.pico:
+
	$(CC) -Wall -Wextra -std=gnu99 -D_GNU_SOURCE=1 -o $@ -c $(CFLAGS) $(LOCAL_CFLAGS) $(SHOBJ_CFLAGS) $<
+

+
.in:
+
	sed -e 's|@prefix@|$(PREFIX)|g; s|@abs_top_srcdir@|$(top_srcdir)|g' \
+
		-e 's|@VERSION@|$(version)|g' $< > $@
added mk/common.mk.in
@@ -0,0 +1,3 @@
+
RANLIB=	@RANLIB@
+
AR=	@AR@
+
OBJS=	${SRCS:.c=.o}
added mk/defs.mk.in
@@ -0,0 +1,26 @@
+
RANLIB=	@RANLIB@
+
AR=	@AR@
+
CC=	@CC@
+
SHOBJ_CFLAGS=	@SHOBJ_CFLAGS@
+
LIBSOEXT=	@LIBSOEXT@
+
SH_SOEXT=	@SH_SOEXT@
+
SH_PREFIX=	@SH_SOPREFIX@
+
SH_LDFLAGS=	@SH_LDFLAGS@
+
PREFIX=		@prefix@
+
top_srcdir=	@abs_top_srcdir@
+
top_builddir=	@abs_top_builddir@
+
libdir=		$(PREFIX)/lib
+
sbindir=	$(PREFIX)/sbin
+
includedir=	$(PREFIX)/include
+
mandir=		@mandir@
+
sysconfdir=	@sysconfdir@
+
pkgconfigdir=	@pkgconfigdir@
+
MK=	$(top_srcdir)/mk
+

+
all:
+

+
clean:
+

+
install:
+

+
check:
added mk/dir.mk
@@ -0,0 +1,14 @@
+
all:
+
	@for d in $(DIRS); do \
+
		$(MAKE) -C $$d ; \
+
	done
+

+
install:
+
	@for d in $(DIRS); do \
+
		$(MAKE) -C $$d install ; \
+
	done
+

+
clean:
+
	@for d in $(DIRS); do \
+
		$(MAKE) -C $$d clean ; \
+
	done
added mk/lib.mk
@@ -0,0 +1,18 @@
+
include $(MK)/common.mk
+

+
all: lib$(LIB)$(LIBSOEXT) lib$(LIB)$(SH_SOEXT) lib$(LIB).a
+

+
lib$(LIB)$(SH_SOEXT): lib$(LIB)$(LIBSOEXT)
+
	ln -sf $> $@
+

+
lib$(LIB)$(LIBSOEXT): $(SHOBJS)
+
	$(CC) $(SH_LDFLAGS) $(LDFLAGS) $(LOCAL_LDFLAGS) $(SH_PREFIX)$@ -o $@ $(SHOBJS)
+

+
lib$(LIB).a: $(OBJS)
+
	$(AR) cr $@ $(OBJS) $(EXTRA_DEPS)
+
	$(RANLIB) $@
+

+
clean:
+
	rm -f lib$(LIB).a lib$(LIB)$(SH_SOEXT) lib$(LIB)$(LIBSOEXT) $(OBJS) $(SHOBJS)
+

+
install:
added mk/prog.mk
@@ -0,0 +1,13 @@
+
include $(MK)/common.mk
+

+
PROGNAME=	$(PROG)$(EXEEXT)
+

+
all: $(PROGNAME)
+

+
$(PROGNAME): $(OBJS)
+
	$(CC) -o $@ $(OBJS) $(LDFLAGS) $(LOCAL_LDFLAGS)
+

+
clean:
+
	rm -f $(PROGNAME) $(OBJS)
+

+
install:
added mk/static-lib.mk
@@ -0,0 +1,16 @@
+
include $(MK)/common.mk
+

+
all: lib$(LIB).a lib$(LIB)_pic.a
+

+
lib$(LIB).a: $(OBJS)
+
	$(AR) cr $@ $(OBJS)
+
	$(RANLIB) $@
+

+
lib$(LIB)_pic.a: $(SHOBJS)
+
	$(AR) cr $@ $(SHOBJS)
+
	$(RANLIB) $@
+

+
clean:
+
	rm -f lib$(LIB).a lib$(LIB)_pic.a $(OBJS) $(SHOBJS)
+

+
install:
deleted scripts/Makefile.am
@@ -1,13 +0,0 @@
-
pdailydir=		${sysconfdir}/periodic/daily
-
psecuritydir=		${sysconfdir}/periodic/security
-
pweeklydir=		${sysconfdir}/periodic/weekly
-
bashcompdir=		${sysconfdir}/bash_completion.d
-
zshcompdir=		${prefix}/share/zsh/site-functions
-

-
dist_pdaily_SCRIPTS=	periodic/411.pkg-backup \
-
			periodic/490.status-pkg-changes
-
dist_psecurity_SCRIPTS=	periodic/410.pkg-audit \
-
			periodic/460.pkg-checksum
-
dist_pweekly_SCRIPTS=	periodic/400.status-pkg
-
dist_bashcomp_DATA=	completion/_pkg.bash
-
dist_zshcomp_DATA=	completion/_pkg
added scripts/Makefile.autosetup
@@ -0,0 +1,39 @@
+
include @builddir@/mk/defs.mk
+
include $(MK)/common.mk
+

+
pdailydir=		$(sysconfdir)/periodic/daily
+
psecuritydir=		$(sysconfdir)/periodic/security
+
pweeklydir=		$(sysconfdir)/periodic/weekly
+
bashcompdir=		$(sysconfdir)/bash_completion.d
+
zshcompdir=		$(prefix)/share/zsh/site-functions
+

+
PDAILY=	periodic/411.pkg-backup \
+
	periodic/490.status-pkg-changes
+
PSECURITY=	periodic/410.pkg-audit \
+
		periodic/460.pkg-checksum
+
PWEEKLY=	periodic/400.status-pkg
+
COMPLETION=	completion/_pkg \
+
		completion/_pkg.bash
+

+
all: $(PDAILY) $(PSECURITY) $(PWEEKLY) $(COMPLETION)
+

+
clean:
+
	rm -f $(PDAILY) $(PSECURITY) $(PWEEKLY)
+

+
install: $(PDAILY) $(PSECURITY) $(PWEEKLY) $(COMPLETION)
+
	install -d -m 755 $(DESTDIR)$(pdailydir)
+
	install -d -m 755 $(DESTDIR)$(pweeklydir)
+
	install -d -m 755 $(DESTDIR)$(psecuritydir)
+
	install -d -m 755 $(DESTDIR)$(bashcompdir)
+
	install -d -m 755 $(DESTDIR)$(zshcompdir)
+
	for script in $(PDAILY); do \
+
		install -m 755 $$script $(DESTDIR)$(pdailydir) ; \
+
	done
+
	for script in $(PSECURITY); do \
+
		install -m 755 $$script $(DESTDIR)$(psecuritydir) ; \
+
	done
+
	for script in $(PWEEKLY); do \
+
		install -m 755 $$script $(DESTDIR)$(pweeklydir) ; \
+
	done
+
	install -m 644 completion/_pkg.bash $(DESTDIR)$(bashcompdir)/
+
	install -m 644 completion/_pkg  $(DESTDIR)$(zshcompdir)/
modified scripts/travis_build.sh
@@ -41,7 +41,7 @@ if [ $(uname -s) = "Darwin" ]; then
    LDFLAGS="-L/usr/local/opt/libarchive/lib" \
    ./configure
elif [ $(uname -s) = "Linux" ]; then
-
  CFLAGS="-Wno-strict-aliasing -Wno-unused-result -Wno-unused-value" ./configure
+
  CFLAGS="-Wno-strict-aliasing -Wno-unused-result -Wno-unused-value" ./configure --with-libarchive.pc
fi

# Build quietly and in parallel first.  If the build fails re-run
deleted src/Makefile.am
@@ -1,105 +0,0 @@
-
noinst_HEADERS=	pkgcli.h \
-
		readpassphrase_compat.h
-

-
if HAVE_ELF_ABI
-
LDFLAGS+=	-Wl,--enable-new-dtags
-
endif
-

-
pkg_SOURCES=		add.c \
-
			alias.c \
-
			annotate.c \
-
			audit.c \
-
			autoremove.c \
-
			backup.c \
-
			check.c \
-
			clean.c \
-
			config.c \
-
			create.c \
-
			delete.c \
-
			event.c \
-
			fetch.c \
-
			globals.c \
-
			info.c \
-
			install.c \
-
			lock.c \
-
			main.c \
-
			plugins.c \
-
			query.c \
-
			register.c \
-
			repo.c \
-
			rquery.c \
-
			search.c \
-
			set.c \
-
			shell.c \
-
			shlib.c \
-
			ssh.c \
-
			stats.c \
-
			update.c \
-
			updating.c \
-
			upgrade.c \
-
			utils.c \
-
			version.c \
-
			which.c
-
			
-
pkg_LDADD=	@OS_LDFLAGS@ \
-
			$(top_builddir)/libpkg/libpkg.la \
-
			$(top_builddir)/compat/libbsd_compat.la \
-
			@LIBJAIL_LIB@ \
-
			-lutil \
-
			-lcrypto
-
pkg_CFLAGS=	 @OS_CFLAGS@ \
-
			-I$(top_srcdir)/libpkg \
-
			-I$(top_builddir)/libpkg \
-
			-I$(top_srcdir)/compat \
-
			-I$(top_srcdir)/external/libucl/klib \
-
			-I$(top_srcdir)/external/uthash \
-
			-I$(top_srcdir)/external/expat/lib \
-
			-DGITHASH=\"$(GIT_HEAD)\" 
-
pkg_static_SOURCES=
-
pkg_static_LDADD= @OS_LDFLAGS@ \
-
			$(pkg_OBJECTS) \
-
			$(top_builddir)/libpkg/libpkg_static.la \
-
			$(top_builddir)/compat/libbsd_compat.la \
-
			@LIBJAIL_LIB@ \
-
			@LDNS_LIBS@ \
-
			@OS_LIBS@ \
-
			-larchive \
-
			-lz \
-
			-lutil \
-
			-lbz2 \
-
			-llzma \
-
			-lssl \
-
			-lcrypto \
-
			-lm
-

-
if HAVE_ELF_ABI
-
if LIBELF_BUNDLED
-
pkg_static_LDADD+=	$(top_builddir)/external/libelf_static.la
-
else
-
pkg_static_LDADD+=	-lelf
-
endif
-
endif
-

-
if HAVE_MACHO_ABI
-
pkg_static_LDADD+=	$(top_builddir)/external/libmachista_static.la \
-
			-lresolv
-
pkg_LDADD+=		-lresolv
-
endif
-

-
DYNPROG=		pkg
-

-
if BUILD_STATIC
-

-
pkg_static_LDFLAGS=	-all-static
-
sbin_PROGRAMS=		pkg-static
-

-
if DYNAMIC
-
sbin_PROGRAMS+=		$(DYNPROG)
-
endif
-

-
else
-

-
sbin_PROGRAMS=	$(DYNPROG)
-
endif
-

-
dist_sysconf_DATA=	pkg.conf.sample
added src/Makefile.autosetup
@@ -0,0 +1,77 @@
+
include @builddir@/mk/defs.mk
+
PROG=	pkg
+
SRCS=	add.c \
+
	alias.c \
+
	annotate.c \
+
	audit.c \
+
	autoremove.c \
+
	backup.c \
+
	check.c \
+
	clean.c \
+
	config.c \
+
	create.c \
+
	delete.c \
+
	event.c \
+
	fetch.c \
+
	globals.c \
+
	info.c \
+
	install.c \
+
	lock.c \
+
	main.c \
+
	plugins.c \
+
	query.c \
+
	register.c \
+
	repo.c \
+
	rquery.c \
+
	search.c \
+
	set.c \
+
	shell.c \
+
	shlib.c \
+
	ssh.c \
+
	stats.c \
+
	update.c \
+
	updating.c \
+
	upgrade.c \
+
	utils.c \
+
	version.c \
+
	which.c
+

+
LOCAL_CFLAGS=	-I$(top_srcdir)/external/uthash \
+
		-I$(top_srcdir)/compat \
+
		-I$(top_srcdir)/external/libucl/klib \
+
		-I$(top_builddir)/ \
+
		-I$(top_builddir)/libpkg \
+
		-DGITHASH=\"@GITHASH@\" \
+
		-DHAVE_CONFIG_H
+
LIBS=	\
+
	-L$(top_builddir)/libpkg -lpkg_flat \
+
	-lm \
+
	@EXTRA_LIBS@
+

+
@if HAVE_PKG_LIBARCHIVE
+
LIBS+=	@PKG_LIBARCHIVE_LDFLAGS@ @PKG_LIBARCHIVE_LIBS_STATIC@
+
@else
+
LIBS+=	-larchive -lbz2 -lz -llzma
+
@endif
+
OTHER_LIBS=	-lssl -lcrypto -pthread
+
@if HAVE_LIBUTIL
+
OTHER_LIBS+=	-lutil
+
@endif
+

+
LOCAL_LDFLAGS=	-Wl,-Bstatic $(LIBS) -Wl,-Bdynamic $(OTHER_LIBS)
+
STATIC_LDFLAGS=	$(LIBS) $(OTHER_LIBS)
+

+
include $(MK)/prog.mk
+

+
all: pkg-static
+

+
pkg-static: $(OBJS)
+
	$(CC) -o $@ $(OBJS) -static $(LDFLAGS) $(STATIC_LDFLAGS)
+

+
install: $(PROG) pkg-static
+
	install -d -m 755 $(DESTDIR)$(sbindir)
+
	install -s -m 755 pkg $(DESTDIR)$(sbindir)/pkg
+

+
clean: clean-pkg-static
+
clean-pkg-static:
+
	rm -f pkg-static
deleted tests/Makefile.am
@@ -1,138 +0,0 @@
-
AUTOMAKE_OPTIONS=	subdir-objects
-

-
GENERIC_LDADD=	$(top_builddir)/libpkg/libpkg_static.la \
-
		$(top_builddir)/compat/libbsd_compat.la \
-
		$(top_builddir)/external/libfetch_static.la \
-
		@LDNS_LIBS@ \
-
		@LIBJAIL_LIB@ \
-
		@OS_LIBS@ \
-
		-larchive \
-
		-lutil \
-
		-lm \
-
		-lssl \
-
		-lcrypto \
-
		-L/usr/local/lib \
-
		-latf-c
-

-
if HAVE_ELF_ABI
-
if LIBELF_BUNDLED
-
GENERIC_LDADD+=	$(top_builddir)/external/libelf_static.la
-
else
-
GENERIC_LDADD+=	-lelf
-
endif
-
endif
-

-
if HAVE_MACHO_ABI
-
GENERIC_LDADD+=	$(top_builddir)/external/libmachista_static.la \
-
		-lresolv
-
endif
-

-
PUBLIC_INCS=	-DTESTING \
-
		-I$(top_srcdir)/compat \
-
		-I$(top_srcdir)/libpkg \
-
		-I/usr/local/include
-
PRIVATE_INCS=	-I$(top_srcdir)/external/sqlite \
-
		-I$(top_srcdir)/external/uthash \
-
		-I$(top_srcdir)/external/libucl/include \
-
		-I$(top_srcdir)/external/libucl/klib \
-
		$(PUBLIC_INCS)
-

-
pkg_printf_SOURCES=	lib/pkg_printf_test.c
-
nodist_pkg_printf_SOURCES=	lib/pkg_printf.c
-
CLEANFILES=		lib/pkg_printf.c
-
BUILT_SOURCES=		lib/pkg_printf.c
-
pkg_printf_CFLAGS=	$(PRIVATE_INCS)
-
pkg_printf_LDADD=	$(GENERIC_LDADD)
-

-
pkg_validation_SOURCES=	lib/pkg_validation.c
-
pkg_validation_CFLAGS=	$(PRIVATE_INCS)
-
pkg_validation_LDADD=	$(GENERIC_LDADD)
-

-
plist_SOURCES=		lib/plist.c
-
plist_CFLAGS=		$(PRIVATE_INCS)
-
plist_LDADD=		$(GENERIC_LDADD)
-

-
checksum_SOURCES=	lib/checksum.c
-
checksum_CFLAGS=	$(PRIVATE_INCS)
-
checksum_LDADD=		$(GENERIC_LDADD)
-

-
deps_formula_SOURCES=	lib/deps_formula.c
-
deps_formula_CFLAGS=	$(PRIVATE_INCS)
-
deps_formula_LDADD=		$(GENERIC_LDADD)
-

-
pkg_add_dir_to_del_SOURCES=	lib/pkg_add_dir_to_del.c
-
pkg_add_dir_to_del_CFLAGS=	$(PRIVATE_INCS)
-
pkg_add_dir_to_del_LDADD=	$(GENERIC_LDADD)
-
merge_SOURCES=	lib/merge.c
-
merge_CFLAGS=	$(PRIVATE_INCS)
-
merge_LDADD=	$(GENERIC_LDADD)
-

-
EXTRA_DIST=	frontend/png.ucl \
-
		frontend/sqlite3.ucl \
-
		frontend/test_subr.sh \
-
		$(tests_scripts)
-

-
tests_scripts=	\
-
		frontend/pkg.sh \
-
		frontend/add.sh \
-
		frontend/alias.sh \
-
		frontend/annotate.sh \
-
		frontend/autoremove.sh \
-
		frontend/autoupgrade.sh \
-
		frontend/config.sh \
-
		frontend/configmerge.sh \
-
		frontend/conflicts.sh \
-
		frontend/conflicts-multirepo.sh \
-
		frontend/create.sh \
-
		frontend/delete.sh \
-
		frontend/extract.sh \
-
		frontend/install.sh \
-
		frontend/jpeg.sh \
-
		frontend/lock.sh \
-
		frontend/messages.sh \
-
		frontend/multipleprovider.sh \
-
		frontend/packagesplit.sh \
-
		frontend/packagemerge.sh \
-
		frontend/php-pr.sh \
-
		frontend/pubkey.sh \
-
		frontend/query.sh \
-
		frontend/register.sh \
-
		frontend/repo.sh \
-
		frontend/requires.sh \
-
		frontend/rootdir.sh \
-
		frontend/rubypuppet.sh \
-
		frontend/search.sh \
-
		frontend/set.sh \
-
		frontend/version.sh \
-
		frontend/vital.sh \
-
		frontend/update.sh \
-
		frontend/test_environment.sh \
-
		frontend/issue1374.sh \
-
		frontend/issue1425.sh \
-
		frontend/issue1440.sh \
-
		frontend/issue1445.sh \
-
		frontend/fingerprint.sh
-

-
check_SCRIPTS=	$(tests_scripts:.sh=)
-
CLEANFILES+=	$(check_SCRIPTS)
-

-
TESTS =
-
tests_programs=	pkg_printf \
-
		pkg_validation \
-
		plist \
-
		checksum \
-
		deps_formula \
-
		pkg_add_dir_to_del \
-
		merge
-
EXTRA_PROGRAMS=	$(tests_programs)
-
check_PROGRAMS=	$(tests_programs)
-

-
SUFFIXES= .sh
-

-
lib/pkg_printf.c: $(top_srcdir)/libpkg/pkg_printf.c
-
	@echo "    CP    " $@;
-
	@cp $(top_srcdir)/libpkg/pkg_printf.c $@
-

-
.sh:
-
	@echo "    CP    " $@:
-
	@install -m 755 $< $@
added tests/Makefile.autosetup
@@ -0,0 +1,131 @@
+
include @builddir@/mk/defs.mk
+

+
TESTS=	\
+
	checksum \
+
	deps_formula \
+
	merge \
+
	pkg_add_dir_to_del \
+
	pkg_printf \
+
	pkg_validation \
+
	plist \
+

+
TESTS_SH= \
+
	frontend/pkg.sh \
+
	frontend/add.sh \
+
	frontend/alias.sh \
+
	frontend/annotate.sh \
+
	frontend/autoremove.sh \
+
	frontend/autoupgrade.sh \
+
	frontend/config.sh \
+
	frontend/configmerge.sh \
+
	frontend/conflicts.sh \
+
	frontend/conflicts-multirepo.sh \
+
	frontend/create.sh \
+
	frontend/delete.sh \
+
	frontend/extract.sh \
+
	frontend/install.sh \
+
	frontend/jpeg.sh \
+
	frontend/lock.sh \
+
	frontend/messages.sh \
+
	frontend/multipleprovider.sh \
+
	frontend/packagesplit.sh \
+
	frontend/packagemerge.sh \
+
	frontend/php-pr.sh \
+
	frontend/pubkey.sh \
+
	frontend/query.sh \
+
	frontend/register.sh \
+
	frontend/repo.sh \
+
	frontend/requires.sh \
+
	frontend/rootdir.sh \
+
	frontend/rubypuppet.sh \
+
	frontend/search.sh \
+
	frontend/set.sh \
+
	frontend/version.sh \
+
	frontend/vital.sh \
+
	frontend/update.sh \
+
	frontend/issue1374.sh \
+
	frontend/issue1425.sh \
+
	frontend/issue1440.sh \
+
	frontend/issue1445.sh \
+
	frontend/fingerprint.sh
+

+
merge_OBJS=	lib/merge.o
+
plist_OBJS=	lib/plist.o
+
checksum_OBJS=	lib/checksum.o
+
pkg_printf_OBJS=	lib/pkg_printf_test.o \
+
			lib/pkg_printf.o
+
deps_formula_OBJS=	lib/deps_formula.o
+
pkg_add_dir_to_del_OBJS=	lib/pkg_add_dir_to_del.o
+
pkg_validation_OBJS=	lib/pkg_validation.o
+

+
SRCS=	\
+
	$(merge_OBJS:.o=.c) \
+
	$(plist_OBJS:.o=.c) \
+
	$(checksum_OBJS:.o=.c) \
+
	$(pkg_printf_OBJS:.o=.c) \
+
	$(deps_formula_OBJS:.o=.c) \
+
	$(pkg_add_dir_to_del_OBJS:.o=.c) \
+
	$(pkg_validation_OBJS:.o=.c)
+

+
include $(MK)/common.mk
+

+
TESTS_SHELL=	$(TESTS_SH:.sh=)
+

+
LOCAL_CFLAGS=	-I$(top_srcdir)/external/uthash \
+
		-I$(top_srcdir)/compat \
+
		-I$(top_srcdir)/external/libucl/include \
+
		-I$(top_srcdir)/external/libucl/klib \
+
		-I$(top_srcdir)/external/uthash \
+
		-I$(top_builddir)/ \
+
		-I$(top_builddir)/libpkg \
+
		@PKG_ATF_C_CFLAGS@ \
+
		-DTESTING
+

+
LIBS=	\
+
	-L$(top_builddir)/libpkg -lpkg_flat \
+
	-lm \
+
	@EXTRA_LIBS@
+

+
@if HAVE_PKG_LIBARCHIVE
+
LIBS+=	@PKG_LIBARCHIVE_LDFLAGS@ @PKG_LIBARCHIVE_LIBS_STATIC@
+
@else
+
LIBS+=	-L/usr/lib -larchive -lbz2 -lz -llzma
+
@endif
+
OTHER_LIBS=	-lssl -lcrypto -pthread
+
@if HAVE_LIBUTIL
+
OTHER_LIBS+=	-lutil
+
@endif
+

+
LOCAL_LDFLAGS=	-Wl,-Bstatic $(LIBS) -Wl,-Bdynamic $(OTHER_LIBS) \
+
	@PKG_ATF_C_LDFLAGS@ @PKG_ATF_C_LIBS@
+

+
all: $(TESTS) Kyuafile ${TESTS_SHELL} frontend/Kyuafile
+

+
$(TESTS): $(OBJS)
+
	$(CC) -o $@ $($@_OBJS) $(LOCAL_LDFLAGS)
+

+
lib/pkg_printf.c:
+
	cp $(top_srcdir)/libpkg/pkg_printf.c $@
+

+
.sh:
+
	install -m 755 $< $@
+

+
clean:
+
	rm -f lib/pkg_printf.c $(OBJS) $(TESTS) $(TESTS_SHELL) Kyuafile frontend/Kyuafile
+

+
Kyuafile: $(TESTS)
+
	@echo "Generating $@"
+
	@echo 'syntax(2)' > $@
+
	@echo 'test_suite("pkg")' >> $@
+
	@for p in $(TESTS); do \
+
		echo "atf_test_program{name='$$p'}" >> $@ ; \
+
	done
+
	@echo 'include("frontend/Kyuafile")' >> $@
+

+
frontend/Kyuafile: $(TESTS_SHELL)
+
	@echo "Generating $@"
+
	@echo 'syntax(2)' > $@
+
	@echo 'test_suite("pkg")' >> $@
+
	@for p in $(TESTS_SHELL); do \
+
		echo "atf_test_program{name='$${p##*/}'}" >> $@ ; \
+
	done
modified tests/frontend/test_environment.sh.in
@@ -1,4 +1,4 @@
-
export RESOURCEDIR=@abs_srcdir@
+
export RESOURCEDIR=@abs_top_srcdir@/tests/frontend
export OS=`uname -s`
export PATH=$(atf_get_srcdir)/../../src/:${PATH}
#export LD_LIBRARY_PATH=$(atf_get_srcdir)/../../libpkg/.libs/
modified tests/lib/deps_formula.c
@@ -52,7 +52,7 @@ ATF_TC_BODY(check_parsing, tc)
		"name1 = 1.0 | name2 != 1.0, name3 > 1.0 < 2.0 != 1.5, name4 +opt1 -opt2"
	};
	char *r;
-
	int i;
+
	unsigned int i;

	for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i ++) {
		f = pkg_deps_parse_formula(cases[i]);
@@ -80,7 +80,7 @@ ATF_TC_BODY(check_sql, tc)
		"name1 = 1.0 | name2 != 1.0", "(name='name1' AND vercmp('=',version,'1.0')) OR (name='name2' AND vercmp('!=',version,'1.0'))"
	};
	char *r;
-
	int i;
+
	unsigned int i;

	for (i = 0; i < sizeof(cases) / sizeof(cases[0]) / 2; i ++) {
		f = pkg_deps_parse_formula(cases[i * 2]);
@@ -115,8 +115,8 @@ ATF_TC_BODY(check_op_parsing, tc)
		{ "=>", VERSION_ANY },
	};

-
	for (int i = 0; i < sizeof(cases) / sizeof(cases[0]); i ++) {
-
		ATF_REQUIRE_EQ(pkg_deps_string_toop(cases[i].val), cases[i].expect);
+
	for (unsigned int i = 0; i < sizeof(cases) / sizeof(cases[0]); i ++) {
+
		ATF_REQUIRE_EQ((int)pkg_deps_string_toop(cases[i].val), cases[i].expect);
	}
}

modified tests/lib/pkg_validation.c
@@ -32,6 +32,14 @@
#include <utstring.h>
#include <pkg.h>

+
#ifndef __unused
+
# ifdef __GNUC__
+
# define __unused __attribute__ ((__unused__))
+
# else
+
# define __unused
+
# endif
+
#endif
+

UT_string *msg;

ATF_TC(valid_installed);
@@ -43,7 +51,7 @@ ATF_TC_HEAD(valid_installed, tc)
}

int
-
event_callback(void *data, struct pkg_event *ev)
+
event_callback(void *data __unused, struct pkg_event *ev)
{
	switch (ev->type) {
	case PKG_EVENT_ERROR: