Import new 2-clause BSD licenced implementation of the bc and dc commands

These implementations of the bc and dc programs offer a number of advantages
compared to the current implementations in the FreeBSD base system:

- They do not depend on external large number functions (i.e. no dependency
  on OpenSSL or any other large number library)

- They implements all features found in GNU bc/dc (with the exception of
  the forking of sub-processes, which the author of this version considers
  as a security issue).

- They are significantly faster than the current code in base (more than
  2 orders of magnitude in some of my tests, e.g. for 12345^100000).

- They should be fully compatible with all features and the behavior of the
  current implementations in FreeBSD (not formally verified).

- They support POSIX message catalogs and come with localized messages in
  Chinese, Dutch, English, French, German, Japanese, Polish, Portugueze,
  and Russian.

- They offer very detailed man-pages that provide far more information than
  the current ones.

The upstream sources contain a large number of tests, which are not
imported with this commit. They could be integrated into our test
framework at a latter time.

Installation of this version is controlled by the option "MK_GH_BC=yes".
This option will be set to yes by default in 13-CURRENT, but will be off
by default in 12-STABLE.

Approved by:	imp
Obtained from:	https://git.yzena.com/gavin/bc
MFC after:	4 weeks
Relnotes:	yes
Differential Revision:	https://reviews.freebsd.org/D19982
This commit is contained in:
Stefan Eßer 2020-06-27 12:02:01 +00:00
parent 136bdd990b
commit 252884ae7e
Notes: svn2git 2020-12-20 02:59:44 +00:00
svn path=/head/; revision=362681
85 changed files with 27670 additions and 2 deletions

59
contrib/bc/LICENSE.md Normal file
View File

@ -0,0 +1,59 @@
# License
Copyright (c) 2018-2020 Gavin D. Howard <yzena.tech@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
## History
The files `src/history.c` and `include/history.h` are under the following
copyrights and license:
Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com><br>
Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com><br>
Copyright (c) 2018 rain-1 <rain1@openmailbox.org><br>
Copyright (c) 2018-2020, Gavin D. Howard <yzena.tech@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.

362
contrib/bc/Makefile.in Normal file
View File

@ -0,0 +1,362 @@
#
# Copyright (c) 2018-2020 Gavin D. Howard and contributors.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
#
# %%WARNING%%
#
.POSIX:
VERSION = 3.0.2
SRC = %%SRC%%
OBJ = %%OBJ%%
GCDA = %%GCDA%%
GCNO = %%GCNO%%
BC_SRC = %%BC_SRC%%
BC_OBJ = %%BC_OBJ%%
BC_GCDA = %%BC_GCDA%%
BC_GCNO = %%BC_GCNO%%
DC_SRC = %%DC_SRC%%
DC_OBJ = %%DC_OBJ%%
DC_GCDA = %%DC_GCDA%%
DC_GCNO = %%DC_GCNO%%
HISTORY_SRC = %%HISTORY_SRC%%
HISTORY_OBJ = %%HISTORY_OBJ%%
HISTORY_GCDA = %%HISTORY_GCDA%%
HISTORY_GCNO = %%HISTORY_GCNO%%
RAND_SRC = %%RAND_SRC%%
RAND_OBJ = %%RAND_OBJ%%
RAND_GCDA = %%RAND_GCDA%%
RAND_GCNO = %%RAND_GCNO%%
BC_ENABLED_NAME = BC_ENABLED
BC_ENABLED = %%BC_ENABLED%%
DC_ENABLED_NAME = DC_ENABLED
DC_ENABLED = %%DC_ENABLED%%
GEN_DIR = gen
GEN = %%GEN%%
GEN_EXEC = $(GEN_DIR)/$(GEN)
GEN_C = $(GEN_DIR)/$(GEN).c
GEN_EMU = %%GEN_EMU%%
BC_LIB = $(GEN_DIR)/lib.bc
BC_LIB_C = $(GEN_DIR)/lib.c
BC_LIB_O = %%BC_LIB_O%%
BC_LIB_GCDA = $(GEN_DIR)/lib.gcda
BC_LIB_GCNO = $(GEN_DIR)/lib.gcno
BC_LIB2 = $(GEN_DIR)/lib2.bc
BC_LIB2_C = $(GEN_DIR)/lib2.c
BC_LIB2_O = %%BC_LIB2_O%%
BC_LIB2_GCDA = $(GEN_DIR)/lib2.gcda
BC_LIB2_GCNO = $(GEN_DIR)/lib2.gcno
BC_HELP = $(GEN_DIR)/bc_help.txt
BC_HELP_C = $(GEN_DIR)/bc_help.c
BC_HELP_O = %%BC_HELP_O%%
BC_HELP_GCDA = $(GEN_DIR)/bc_help.gcda
BC_HELP_GCNO = $(GEN_DIR)/bc_help.gcno
DC_HELP = $(GEN_DIR)/dc_help.txt
DC_HELP_C = $(GEN_DIR)/dc_help.c
DC_HELP_O = %%DC_HELP_O%%
DC_HELP_GCDA = $(GEN_DIR)/dc_help.gcda
DC_HELP_GCNO = $(GEN_DIR)/dc_help.gcno
BIN = bin
LOCALES = locales
EXEC_SUFFIX = %%EXECSUFFIX%%
EXEC_PREFIX = %%EXECPREFIX%%
BC = bc
DC = dc
BC_EXEC = $(BIN)/$(EXEC_PREFIX)$(BC)
DC_EXEC = $(BIN)/$(EXEC_PREFIX)$(DC)
MANUALS = manuals
BC_MANPAGE_NAME = $(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX).1
BC_MANPAGE = $(MANUALS)/$(BC).1
BC_RONN = $(BC_MANPAGE).ronn
DC_MANPAGE_NAME = $(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX).1
DC_MANPAGE = $(MANUALS)/$(DC).1
DC_RONN = $(DC_MANPAGE).ronn
MANPAGE_INSTALL_ARGS = -Dm644
%%DESTDIR%%
BINDIR = %%BINDIR%%
MAN1DIR = %%MAN1DIR%%
MAIN_EXEC = $(EXEC_PREFIX)$(%%MAIN_EXEC%%)$(EXEC_SUFFIX)
EXEC = $(%%EXEC%%)
NLSPATH = %%NLSPATH%%
BC_ENABLE_HISTORY = %%HISTORY%%
BC_ENABLE_EXTRA_MATH_NAME = BC_ENABLE_EXTRA_MATH
BC_ENABLE_EXTRA_MATH = %%EXTRA_MATH%%
BC_ENABLE_NLS = %%NLS%%
BC_ENABLE_PROMPT = %%PROMPT%%
BC_LONG_BIT = %%LONG_BIT%%
RM = rm
MKDIR = mkdir
INSTALL = ./install.sh
SAFE_INSTALL = ./safe-install.sh
LINK = ./link.sh
MANPAGE = ./manpage.sh
KARATSUBA = ./karatsuba.py
LOCALE_INSTALL = ./locale_install.sh
LOCALE_UNINSTALL = ./locale_uninstall.sh
VALGRIND_ARGS = --error-exitcode=100 --leak-check=full --show-leak-kinds=all --errors-for-leak-kinds=all
BC_NUM_KARATSUBA_LEN = %%KARATSUBA_LEN%%
CPPFLAGS1 = -D$(BC_ENABLED_NAME)=$(BC_ENABLED) -D$(DC_ENABLED_NAME)=$(DC_ENABLED)
CPPFLAGS2 = $(CPPFLAGS1) -I./include/ -DVERSION=$(VERSION) %%LONG_BIT_DEFINE%%
CPPFLAGS3 = $(CPPFLAGS2) -DEXECPREFIX=$(EXEC_PREFIX) -DMAINEXEC=$(MAIN_EXEC)
CPPFLAGS4 = $(CPPFLAGS3) -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700
CPPFLAGS5 = $(CPPFLAGS4) -DBC_NUM_KARATSUBA_LEN=$(BC_NUM_KARATSUBA_LEN)
CPPFLAGS6 = $(CPPFLAGS5) -DBC_ENABLE_NLS=$(BC_ENABLE_NLS) -DBC_ENABLE_PROMPT=$(BC_ENABLE_PROMPT)
CPPFLAGS7 = $(CPPFLAGS6) -D$(BC_ENABLE_EXTRA_MATH_NAME)=$(BC_ENABLE_EXTRA_MATH)
CPPFLAGS = $(CPPFLAGS7) -DBC_ENABLE_HISTORY=$(BC_ENABLE_HISTORY)
CFLAGS = $(CPPFLAGS) %%CPPFLAGS%% %%CFLAGS%%
LDFLAGS = %%LDFLAGS%%
HOSTCFLAGS = %%HOSTCFLAGS%%
CC = %%CC%%
HOSTCC = %%HOSTCC%%
BC_LIB_C_ARGS = bc_lib bc.h bc_lib_name $(BC_ENABLED_NAME) 1
BC_LIB2_C_ARGS = bc_lib2 bc.h bc_lib2_name "$(BC_ENABLED_NAME) && $(BC_ENABLE_EXTRA_MATH_NAME)" 1
OBJS1 = $(OBJ) $(DC_OBJ) $(BC_OBJ) $(HISTORY_OBJ) $(RAND_OBJ) $(BC_HELP_O) $(DC_HELP_O)
OBJS = $(OBJS1) $(BC_LIB_O) $(BC_LIB2_O) $(BC_LIB3_O)
OBJ_TARGETS1 = $(DC_HELP_O) $(BC_HELP_O) $(BC_LIB_O) $(BC_LIB2_O) $(BC_LIB3_O)
OBJ_TARGETS = $(OBJ_TARGETS1) $(BC_OBJ) $(DC_OBJ) $(HISTORY_OBJ) $(RAND_OBJ) $(OBJ)
.c.o:
$(CC) $(CFLAGS) -o $@ -c $<
all: make_bin $(OBJ_TARGETS)
$(CC) $(CFLAGS) $(OBJS) $(LDFLAGS) -o $(EXEC)
%%LINK%%
$(GEN_EXEC):
%%GEN_EXEC_TARGET%%
$(BC_LIB_C): $(GEN_EXEC) $(BC_LIB)
$(GEN_EMU) $(GEN_EXEC) $(BC_LIB) $(BC_LIB_C) $(BC_LIB_C_ARGS)
$(BC_LIB2_C): $(GEN_EXEC) $(BC_LIB2)
$(GEN_EMU) $(GEN_EXEC) $(BC_LIB2) $(BC_LIB2_C) $(BC_LIB2_C_ARGS)
$(BC_HELP_C): $(GEN_EXEC) $(BC_HELP)
$(GEN_EMU) $(GEN_EXEC) $(BC_HELP) $(BC_HELP_C) bc_help bc.h "" $(BC_ENABLED_NAME)
$(DC_HELP_C): $(GEN_EXEC) $(DC_HELP)
$(GEN_EMU) $(GEN_EXEC) $(DC_HELP) $(DC_HELP_C) dc_help dc.h "" $(DC_ENABLED_NAME)
make_bin:
$(MKDIR) -p $(BIN)
help:
@printf 'available targets:\n'
@printf '\n'
@printf ' all (default) builds %%EXECUTABLES%%\n'
@printf ' check alias for `make test`\n'
@printf ' clean removes all build files\n'
@printf ' clean_config removes all build files as well as the generated Makefile\n'
@printf ' clean_tests removes all build files, the generated Makefile,\n'
@printf ' and generated tests\n'
@printf ' install installs binaries to "%s%s"\n' "$(DESTDIR)" "$(BINDIR)"
@printf ' and (if enabled) manpages to "%s%s"\n' "$(DESTDIR)" "$(MAN1DIR)"
@printf ' karatsuba runs the karatsuba script (requires Python 3)\n'
@printf ' karatsuba_test runs the karatsuba script while running tests\n'
@printf ' (requires Python 3)\n'
@printf ' uninstall uninstalls binaries from "%s%s"\n' "$(DESTDIR)" "$(BINDIR)"
@printf ' and (if enabled) manpages from "%s%s"\n' "$(DESTDIR)" "$(MAN1DIR)"
@printf ' test runs the test suite\n'
@printf ' test_bc runs the bc test suite, if bc has been built\n'
@printf ' test_dc runs the dc test suite, if dc has been built\n'
@printf ' time_test runs the test suite, displaying times for some things\n'
@printf ' time_test_bc runs the bc test suite, displaying times for some things\n'
@printf ' time_test_dc runs the dc test suite, displaying times for some things\n'
@printf ' timeconst runs the test on the Linux timeconst.bc script,\n'
@printf ' if it exists and bc has been built\n'
@printf ' valgrind runs the test suite through valgrind\n'
@printf ' valgrind_bc runs the bc test suite, if bc has been built,\n'
@printf ' through valgrind\n'
@printf ' valgrind_dc runs the dc test suite, if dc has been built,\n'
@printf ' through valgrind\n'
check: test
test: test_bc timeconst test_dc
test_bc:
%%BC_TEST%%
test_dc:
%%DC_TEST%%
time_test: time_test_bc timeconst time_test_dc
time_test_bc:
%%BC_TIME_TEST%%
time_test_dc:
%%DC_TIME_TEST%%
timeconst:
%%TIMECONST%%
valgrind: valgrind_bc valgrind_dc
valgrind_bc:
%%VG_BC_TEST%%
valgrind_dc:
%%VG_DC_TEST%%
karatsuba:
%%KARATSUBA%%
karatsuba_test:
%%KARATSUBA_TEST%%
coverage_output:
%%COVERAGE_OUTPUT%%
coverage:%%COVERAGE_PREREQS%%
version:
@printf '%s' "$(VERSION)"
libcname:
@printf '%s' "$(BC_LIB_C)"
extra_math:
@printf '%s' "$(BC_ENABLE_EXTRA_MATH)"
manpages:
$(MANPAGE) $(BC_RONN) $(BC_MANPAGE)
$(MANPAGE) $(DC_RONN) $(DC_MANPAGE)
clean_gen:
@$(RM) -f $(GEN_EXEC)
clean:%%CLEAN_PREREQS%%
@printf 'Cleaning files...\n'
@$(RM) -f $(OBJ)
@$(RM) -f $(BC_OBJ)
@$(RM) -f $(DC_OBJ)
@$(RM) -f $(HISTORY_OBJ)
@$(RM) -f $(RAND_OBJ)
@$(RM) -f $(BC_EXEC)
@$(RM) -f $(DC_EXEC)
@$(RM) -fr $(BIN)
@$(RM) -f $(LOCALES)/*.cat
@$(RM) -f $(BC_LIB_C) $(BC_LIB_O)
@$(RM) -f $(BC_LIB2_C) $(BC_LIB2_O)
@$(RM) -f $(BC_HELP_C) $(BC_HELP_O)
@$(RM) -f $(DC_HELP_C) $(DC_HELP_O)
clean_config: clean
@printf 'Cleaning config...\n'
@$(RM) -f Makefile
clean_coverage:
@printf 'Cleaning coverage files...\n'
@$(RM) -f *.gcov
@$(RM) -f *.html
@$(RM) -f *.gcda *.gcno
@$(RM) -f *.profraw
@$(RM) -f $(GCDA) $(GCNO)
@$(RM) -f $(BC_GCDA) $(BC_GCNO)
@$(RM) -f $(DC_GCDA) $(DC_GCNO)
@$(RM) -f $(HISTORY_GCDA) $(HISTORY_GCNO)
@$(RM) -f $(RAND_GCDA) $(RAND_GCNO)
@$(RM) -f $(BC_LIB_GCDA) $(BC_LIB_GCNO)
@$(RM) -f $(BC_LIB2_GCDA) $(BC_LIB2_GCNO)
@$(RM) -f $(BC_HELP_GCDA) $(BC_HELP_GCNO)
@$(RM) -f $(DC_HELP_GCDA) $(DC_HELP_GCNO)
clean_tests: clean clean_config clean_coverage
@printf 'Cleaning test files...\n'
@$(RM) -f tests/bc/parse.txt tests/bc/parse_results.txt
@$(RM) -f tests/bc/print.txt tests/bc/print_results.txt
@$(RM) -f tests/bc/bessel.txt tests/bc/bessel_results.txt
@$(RM) -f tests/bc/scripts/bessel.txt
@$(RM) -f tests/bc/scripts/parse.txt
@$(RM) -f tests/bc/scripts/print.txt
@$(RM) -f tests/bc/scripts/add.txt
@$(RM) -f tests/bc/scripts/divide.txt
@$(RM) -f tests/bc/scripts/multiply.txt
@$(RM) -f tests/bc/scripts/subtract.txt
@$(RM) -f tests/dc/scripts/prime.txt tests/dc/scripts/stream.txt
@$(RM) -f .log_*.txt
@$(RM) -f .math.txt .results.txt .ops.txt
@$(RM) -f .test.txt
@$(RM) -f tags .gdbbreakpoints .gdb_history .gdbsetup
@$(RM) -f cscope.*
@$(RM) -f bc.old
install_locales:
$(LOCALE_INSTALL) $(NLSPATH) $(MAIN_EXEC) $(DESTDIR)
install_bc_manpage:
$(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BC_MANPAGE) $(DESTDIR)$(MAN1DIR)/$(BC_MANPAGE_NAME)
install_dc_manpage:
$(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(DC_MANPAGE) $(DESTDIR)$(MAN1DIR)/$(DC_MANPAGE_NAME)
install:%%INSTALL_LOCALES_PREREQS%%%%INSTALL_PREREQS%%
$(INSTALL) $(DESTDIR)$(BINDIR) "$(EXEC_SUFFIX)"
uninstall_locales:
$(LOCALE_UNINSTALL) $(NLSPATH) $(MAIN_EXEC) $(DESTDIR)
uninstall_bc_manpage:
$(RM) -f $(DESTDIR)$(MAN1DIR)/$(BC_MANPAGE_NAME)
uninstall_bc:
$(RM) -f $(DESTDIR)$(BINDIR)/$(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX)
uninstall_dc_manpage:
$(RM) -f $(DESTDIR)$(MAN1DIR)/$(DC_MANPAGE_NAME)
uninstall_dc:
$(RM) -f $(DESTDIR)$(BINDIR)/$(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX)
uninstall:%%UNINSTALL_LOCALES_PREREQS%%%%UNINSTALL_MAN_PREREQS%%%%UNINSTALL_PREREQS%%

824
contrib/bc/NEWS.md Normal file
View File

@ -0,0 +1,824 @@
# News
## 3.0.2
This is a production release that adds `utf8` locale symlinks and removes an
unused `auto` variable from the `ceil()` function in the [extended math
library][16].
Users do ***NOT*** need to update unless they want the locales.
## 3.0.1
This is a production release with two small changes. Users do ***NOT*** need to
upgrade to this release; however, if they haven't upgraded to `3.0.0` yet, it
may be worthwhile to upgrade to this release.
The first change is fixing a compiler warning on FreeBSD with strict warnings
on.
The second change is to make the new implementation of `ceil()` in `lib2.bc`
much more efficient.
## 3.0.0
*Notes for package maintainers:*
*First, the `2.7.0` release series saw a change in the option parsing. This made
me change one error message and add a few others. The error message that was
changed removed one format specifier. This means that `printf()` will seqfault
on old locale files. Unfortunately, `bc` cannot use any locale files except the
global ones that are already installed, so it will use the previous ones while
running tests during install. **If `bc` segfaults while running arg tests when
updating, it is because the global locale files have not been replaced. Make
sure to either prevent the test suite from running on update or remove the old
locale files before updating.** Once this is done, `bc` should install without
problems.*
*Second, **the option to build without signal support has been removed**. See
below for the reasons why.*
This is a production release with some small bug fixes, a few improvements,
three major bug fixes, and a complete redesign of `bc`'s error and signal
handling. **Users and package maintainers should update to this version as soon
as possible.**
The first major bug fix was in how `bc` executed files. Previously, a whole file
was parsed before it was executed, but if a function is defined *after* code,
especially if the function definition was actually a redefinition, and the code
before the definition referred to the previous function, this `bc` would replace
the function before executing any code. The fix was to make sure that all code
that existed before a function definition was executed.
The second major bug fix was in `bc`'s `lib2.bc`. The `ceil()` function had a
bug where a `0` in the decimal place after the truncation position, caused it to
output the wrong numbers if there was any non-zero digit after.
The third major bug is that when passing parameters to functions, if an
expression included an array (not an array element) as a parameter, it was
accepted, when it should have been rejected. It is now correctly rejected.
Beyond that, this `bc` got several improvements that both sped it up, improved
the handling of signals, and improved the error handling.
First, the requirements for `bc` were pushed back to POSIX 2008. `bc` uses one
function, `strdup()`, which is not in POSIX 2001, and it is in the X/Open System
Interfaces group 2001. It is, however, in POSIX 2008, and since POSIX 2008 is
old enough to be supported anywhere that I care, that should be the requirement.
Second, the BcVm global variable was put into `bss`. This actually slightly
reduces the size of the executable from a massive code shrink, and it will stop
`bc` from allocating a large set of memory when `bc` starts.
Third, the default Karatsuba length was updated from 64 to 32 after making the
optimization changes below, since 32 is going to be better than 64 after the
changes.
Fourth, Spanish translations were added.
Fifth, the interpreter received a speedup to make performance on non-math-heavy
scripts more competitive with GNU `bc`. While improvements did, in fact, get it
much closer (see the [benchmarks][19]), it isn't quite there.
There were several things done to speed up the interpreter:
First, several small inefficiencies were removed. These inefficiencies included
calling the function `bc_vec_pop(v)` twice instead of calling
`bc_vec_npop(v, 2)`. They also included an extra function call for checking the
size of the stack and checking the size of the stack more than once on several
operations.
Second, since the current `bc` function is the one that stores constants and
strings, the program caches pointers to the current function's vectors of
constants and strings to prevent needing to grab the current function in order
to grab a constant or a string.
Third, `bc` tries to reuse `BcNum`'s (the internal representation of
arbitary-precision numbers). If a `BcNum` has the default capacity of
`BC_NUM_DEF_SIZE` (32 on 64-bit and 16 on 32-bit) when it is freed, it is added
to a list of available `BcNum`'s. And then, when a `BcNum` is allocated with a
capacity of `BC_NUM_DEF_SIZE` and any `BcNum`'s exist on the list of reusable
ones, one of those ones is grabbed instead.
In order to support these changes, the `BC_NUM_DEF_SIZE` was changed. It used to
be 16 bytes on all systems, but it was changed to more closely align with the
minimum allocation size on Linux, which is either 32 bytes (64-bit musl), 24
bytes (64-bit glibc), 16 bytes (32-bit musl), or 12 bytes (32-bit glibc). Since
these are the minimum allocation sizes, these are the sizes that would be
allocated anyway, making it worth it to just use the whole space, so the value
of `BC_NUM_DEF_SIZE` on 64-bit systems was changed to 32 bytes.
On top of that, at least on 64-bit, `BC_NUM_DEF_SIZE` supports numbers with
either 72 integer digits or 45 integer digits and 27 fractional digits. This
should be more than enough for most cases since `bc`'s default `scale` values
are 0 or 20, meaning that, by default, it has at most 20 fractional digits. And
45 integer digits are *a lot*; it's enough to calculate the amount of mass in
the Milky Way galaxy in kilograms. Also, 72 digits is enough to calculate the
diameter of the universe in Planck lengths.
(For 32-bit, these numbers are either 32 integer digits or 12 integer digits and
20 fractional digits. These are also quite big, and going much bigger on a
32-bit system seems a little pointless since 12 digits in just under a trillion
and 20 fractional digits is still enough for about any use since `10^-20` light
years is just under a millimeter.)
All of this together means that for ordinary uses, and even uses in scientific
work, the default number size will be all that is needed, which means that
nearly all, if not all, numbers will be reused, relieving pressure on the system
allocator.
I did several experiments to find the changes that had the most impact,
especially with regard to reusing `BcNum`'s. One was putting `BcNum`'s into
buckets according to their capacity in powers of 2 up to 512. That performed
worse than `bc` did in `2.7.2`. Another was putting any `BcNum` on the reuse
list that had a capacity of `BC_NUM_DEF_SIZE * 2` and reusing them for `BcNum`'s
that requested `BC_NUM_DEF_SIZE`. This did reduce the amount of time spent, but
it also spent a lot of time in the system allocator for an unknown reason. (When
using `strace`, a bunch more `brk` calls showed up.) Just reusing `BcNum`'s that
had exactly `BC_NUM_DEF_SIZE` capacity spent the smallest amount of time in both
user and system time. This makes sense, especially with the changes to make
`BC_NUM_DEF_SIZE` bigger on 64-bit systems, since the vast majority of numbers
will only ever use numbers with a size less than or equal to `BC_NUM_DEF_SIZE`.
Last of all, `bc`'s signal handling underwent a complete redesign. (This is the
reason that this version is `3.0.0` and not `2.8.0`.) The change was to move
from a polling approach to signal handling to an interrupt-based approach.
Previously, every single loop condition had a check for signals. I suspect that
this could be expensive when in tight loops.
Now, the signal handler just uses `longjmp()` (actually `siglongjmp()`) to start
an unwinding of the stack until it is stopped or the stack is unwound to
`main()`, which just returns. If `bc` is currently executing code that cannot be
safely interrupted (according to POSIX), then signals are "locked." The signal
handler checks if the lock is taken, and if it is, it just sets the status to
indicate that a signal arrived. Later, when the signal lock is released, the
status is checked to see if a signal came in. If so, the stack unwinding starts.
This design eliminates polling in favor of maintaining a stack of `jmp_buf`'s.
This has its own performance implications, but it gives better interaction. And
the cost of pushing and popping a `jmp_buf` in a function is paid at most twice.
Most functions do not pay that price, and most of the rest only pay it once.
(There are only some 3 functions in `bc` that push and pop a `jmp_buf` twice.)
As a side effect of this change, I had to eliminate the use of `stdio.h` in `bc`
because `stdio` does not play nice with signals and `longjmp()`. I implemented
custom I/O buffer code that takes a fraction of the size. This means that static
builds will be smaller, but non-static builds will be bigger, though they will
have less linking time.
This change is also good because my history implementation was already bypassing
`stdio` for good reasons, and unifying the architecture was a win.
Another reason for this change is that my `bc` should *always* behave correctly
in the presence of signals like `SIGINT`, `SIGTERM`, and `SIGQUIT`. With the
addition of my own I/O buffering, I needed to also make sure that the buffers
were correctly flushed even when such signals happened.
For this reason, I **removed the option to build without signal support**.
As a nice side effect of this change, the error handling code could be changed
to take advantage of the stack unwinding that signals used. This means that
signals and error handling use the same code paths, which means that the stack
unwinding is well-tested. (Errors are tested heavily in the test suite.)
It also means that functions do not need to return a status code that
***every*** caller needs to check. This eliminated over 100 branches that simply
checked return codes and then passed that return code up the stack if necessary.
The code bloat savings from this is at least 1700 bytes on `x86_64`, *before*
taking into account the extra code from removing `stdio.h`.
## 2.7.2
This is a production release with one major bug fix.
The `length()` built-in function can take either a number or an array. If it
takes an array, it returns the length of the array. Arrays can be passed by
reference. The bug is that the `length()` function would not properly
dereference arrays that were references. This is a bug that affects all users.
**ALL USERS SHOULD UPDATE `bc`**.
## 2.7.1
This is a production release with fixes for new locales and fixes for compiler
warnings on FreeBSD.
## 2.7.0
This is a production release with a bug fix for Linux, new translations, and new
features.
Bug fixes:
* Option parsing in `BC_ENV_ARGS` was broken on Linux in 2.6.1 because `glibc`'s
`getopt_long()` is broken. To get around that, and to support long options on
every platform, an adapted version of [`optparse`][17] was added. Now, `bc`
does not even use `getopt()`.
* Parsing `BC_ENV_ARGS` with quotes now works. It isn't the smartest, but it
does the job if there are spaces in file names.
The following new languages are supported:
* Dutch
* Polish
* Russian
* Japanes
* Simplified Chinese
All of these translations were generated using [DeepL][18], so improvements are
welcome.
There is only one new feature: **`bc` now has a built-in pseudo-random number
generator** (PRNG).
The PRNG is seeded, making it useful for applications where
`/dev/urandom` does not work because output needs to be reproducible. However,
it also uses `/dev/urandom` to seed itself by default, so it will start with a
good seed by default.
It also outputs 32 bits on 32-bit platforms and 64 bits on 64-bit platforms, far
better than the 15 bits of C's `rand()` and `bash`'s `$RANDOM`.
In addition, the PRNG can take a bound, and when it gets a bound, it
automatically adjusts to remove bias. It can also generate numbers of arbitrary
size. (As of the time of release, the largest pseudo-random number generated by
this `bc` was generated with a bound of `2^(2^20)`.)
***IMPORTANT: read the [`bc` manual][9] and the [`dc` manual][10] to find out
exactly what guarantees the PRNG provides. The underlying implementation is not
guaranteed to stay the same, but the guarantees that it provides are guaranteed
to stay the same regardless of the implementation.***
On top of that, four functions were added to `bc`'s [extended math library][16]
to make using the PRNG easier:
* `frand(p)`: Generates a number between `[0,1)` to `p` decimal places.
* `ifrand(i, p)`: Generates an integer with bound `i` and adds it to `frand(p)`.
* `srand(x)`: Randomizes the sign of `x`. In other words, it flips the sign of
`x` with probability `0.5`.
* `brand()`: Returns a random boolean value (either `0` or `1`).
## 2.6.1
This is a production release with a bug fix for FreeBSD.
The bug was that when `bc` was built without long options, it would give a fatal
error on every run. This was caused by a mishandling of `optind`.
## 2.6.0
This release is a production release ***with no bugfixes***. If you do not want
to upgrade, you don't have to.
No source code changed; the only thing that changed was `lib2.bc`.
This release adds one function to the [extended math library][16]: `p(x, y)`,
which calculates `x` to the power of `y`, whether or not `y` is an integer. (The
`^` operator can only accept integer powers.)
This release also includes a couple of small tweaks to the [extended math
library][16], mostly to fix returning numbers with too high of `scale`.
## 2.5.3
This release is a production release which addresses inconsistencies in the
Portuguese locales. No `bc` code was changed.
The issues were that the ISO files used different naming, and also that the
files that should have been symlinks were not. I did not catch that because
GitHub rendered them the exact same way.
## 2.5.2
This release is a production release.
No code was changed, but the build system was changed to allow `CFLAGS` to be
given to `CC`, like this:
```
CC="gcc -O3 -march=native" ./configure.sh
```
If this happens, the flags are automatically put into `CFLAGS`, and the compiler
is set appropriately. In the example above this means that `CC` will be "gcc"
and `CFLAGS` will be "-O3 -march=native".
This behavior was added to conform to GNU autotools practices.
## 2.5.1
This is a production release which addresses portability concerns discovered
in the `bc` build system. No `bc` code was changed.
* Support for Solaris SPARC and AIX were added.
* Minor documentations edits were performed.
* An option for `configure.sh` was added to disable long options if
`getopt_long()` is missing.
## 2.5.0
This is a production release with new translations. No code changed.
The translations were contributed by [bugcrazy][15], and they are for
Portuguese, both Portugal and Brazil locales.
## 2.4.0
This is a production release primarily aimed at improving `dc`.
* A couple of copy and paste errors in the [`dc` manual][10] were fixed.
* `dc` startup was optimized by making sure it didn't have to set up `bc`-only
things.
* The `bc` `&&` and `||` operators were made available to `dc` through the `M`
and `m` commands, respectively.
* `dc` macros were changed to be tail call-optimized.
The last item, tail call optimization, means that if the last thing in a macro
is a call to another macro, then the old macro is popped before executing the
new macro. This change was made to stop `dc` from consuming more and more memory
as macros are executed in a loop.
The `q` and `Q` commands still respect the "hidden" macros by way of recording
how many macros were removed by tail call optimization.
## 2.3.2
This is a production release meant to fix warnings in the Gentoo `ebuild` by
making it possible to disable binary stripping. Other users do *not* need to
upgrade.
## 2.3.1
This is a production release. It fixes a bug that caused `-1000000000 < -1` to
return `0`. This only happened with negative numbers and only if the value on
the left was more negative by a certain amount. That said, this bug *is* a bad
bug, and needs to be fixed.
**ALL USERS SHOULD UPDATE `bc`**.
## 2.3.0
This is a production release with changes to the build system.
## 2.2.0
This release is a production release. It only has new features and performance
improvements.
1. The performance of `sqrt(x)` was improved.
2. The new function `root(x, n)` was added to the extended math library to
calculate `n`th roots.
3. The new function `cbrt(x)` was added to the extended math library to
calculate cube roots.
## 2.1.3
This is a non-critical release; it just changes the build system, and in
non-breaking ways:
1. Linked locale files were changed to link to their sources with a relative
link.
2. A bug in `configure.sh` that caused long option parsing to fail under `bash`
was fixed.
## 2.1.2
This release is not a critical release.
1. A few codes were added to history.
2. Multiplication was optimized a bit more.
3. Addition and subtraction were both optimized a bit more.
## 2.1.1
This release contains a fix for the test suite made for Linux from Scratch: now
the test suite prints `pass` when a test is passed.
Other than that, there is no change in this release, so distros and other users
do not need to upgrade.
## 2.1.0
This release is a production release.
The following bugs were fixed:
1. A `dc` bug that caused stack mishandling was fixed.
2. A warning on OpenBSD was fixed.
3. Bugs in `ctrl+arrow` operations in history were fixed.
4. The ability to paste multiple lines in history was added.
5. A `bc` bug, mishandling of array arguments to functions, was fixed.
6. A crash caused by freeing the wrong pointer was fixed.
7. A `dc` bug where strings, in a rare case, were mishandled in parsing was
fixed.
In addition, the following changes were made:
1. Division was slightly optimized.
2. An option was added to the build to disable printing of prompts.
3. The special case of empty arguments is now handled. This is to prevent
errors in scripts that end up passing empty arguments.
4. A harmless bug was fixed. This bug was that, with the pop instructions
(mostly) removed (see below), `bc` would leave extra values on its stack for
`void` functions and in a few other cases. These extra items would not
affect anything put on the stack and would not cause any sort of crash or
even buggy behavior, but they would cause `bc` to take more memory than it
needed.
On top of the above changes, the following optimizations were added:
1. The need for pop instructions in `bc` was removed.
2. Extra tests on every iteration of the interpreter loop were removed.
3. Updating function and code pointers on every iteration of the interpreter
loop was changed to only updating them when necessary.
4. Extra assignments to pointers were removed.
Altogether, these changes sped up the interpreter by around 2x.
***NOTE***: This is the last release with new features because this `bc` is now
considered complete. From now on, only bug fixes and new translations will be
added to this `bc`.
## 2.0.3
This is a production, bug-fix release.
Two bugs were fixed in this release:
1. A rare and subtle signal handling bug was fixed.
2. A misbehavior on `0` to a negative power was fixed.
The last bug bears some mentioning.
When I originally wrote power, I did not thoroughly check its error cases;
instead, I had it check if the first number was `0` and then if so, just return
`0`. However, `0` to a negative power means that `1` will be divided by `0`,
which is an error.
I caught this, but only after I stopped being cocky. You see, sometime later, I
had noticed that GNU `bc` returned an error, correctly, but I thought it was
wrong simply because that's not what my `bc` did. I saw it again later and had a
double take. I checked for real, finally, and found out that my `bc` was wrong
all along.
That was bad on me. But the bug was easy to fix, so it is fixed now.
There are two other things in this release:
1. Subtraction was optimized by [Stefan Eßer][14].
2. Division was also optimized, also by Stefan Eßer.
## 2.0.2
This release contains a fix for a possible overflow in the signal handling. I
would be surprised if any users ran into it because it would only happen after 2
billion (`2^31-1`) `SIGINT`'s, but I saw it and had to fix it.
## 2.0.1
This release contains very few things that will apply to any users.
1. A slight bug in `dc`'s interactive mode was fixed.
2. A bug in the test suite that was only triggered on NetBSD was fixed.
3. **The `-P`/`--no-prompt` option** was added for users that do not want a
prompt.
4. A `make check` target was added as an alias for `make test`.
5. `dc` got its own read prompt: `?> `.
## 2.0.0
This release is a production release.
This release is also a little different from previous releases. From here on
out, I do not plan on adding any more features to this `bc`; I believe that it
is complete. However, there may be bug fix releases in the future, if I or any
others manage to find bugs.
This release has only a few new features:
1. `atan2(y, x)` was added to the extended math library as both `a2(y, x)` and
`atan2(y, x)`.
2. Locales were fixed.
3. A **POSIX shell-compatible script was added as an alternative to compiling
`gen/strgen.c`** on a host machine. More details about making the choice
between the two can be found by running `./configure.sh --help` or reading
the [build manual][13].
4. Multiplication was optimized by using **diagonal multiplication**, rather
than straight brute force.
5. The `locale_install.sh` script was fixed.
6. `dc` was given the ability to **use the environment variable
`DC_ENV_ARGS`**.
7. `dc` was also given the ability to **use the `-i` or `--interactive`**
options.
8. Printing the prompt was fixed so that it did not print when it shouldn't.
9. Signal handling was fixed.
10. **Handling of `SIGTERM` and `SIGQUIT`** was fixed.
11. The **built-in functions `maxibase()`, `maxobase()`, and `maxscale()`** (the
commands `T`, `U`, `V` in `dc`, respectively) were added to allow scripts to
query for the max allowable values of those globals.
12. Some incompatibilities with POSIX were fixed.
In addition, this release is `2.0.0` for a big reason: the internal format for
numbers changed. They used to be a `char` array. Now, they are an array of
larger integers, packing more decimal digits into each integer. This has
delivered ***HUGE*** performance improvements, especially for multiplication,
division, and power.
This `bc` should now be the fastest `bc` available, but I may be wrong.
## 1.2.8
This release contains a fix for a harmless bug (it is harmless in that it still
works, but it just copies extra data) in the [`locale_install.sh`][12] script.
## 1.2.7
This version contains fixes for the build on Arch Linux.
## 1.2.6
This release removes the use of `local` in shell scripts because it's not POSIX
shell-compatible, and also updates a man page that should have been updated a
long time ago but was missed.
## 1.2.5
This release contains some missing locale `*.msg` files.
## 1.2.4
This release contains a few bug fixes and new French translations.
## 1.2.3
This release contains a fix for a bug: use of uninitialized data. Such data was
only used when outputting an error message, but I am striving for perfection. As
Michelangelo said, "Trifles make perfection, and perfection is no trifle."
## 1.2.2
This release contains fixes for OpenBSD.
## 1.2.1
This release contains bug fixes for some rare bugs.
## 1.2.0
This is a production release.
There have been several changes since `1.1.0`:
1. The build system had some changes.
2. Locale support has been added. (Patches welcome for translations.)
3. **The ability to turn `ibase`, `obase`, and `scale` into stacks** was added
with the `-g` command-line option. (See the [`bc` manual][9] for more
details.)
4. Support for compiling on Mac OSX out of the box was added.
5. The extended math library got `t(x)`, `ceil(x)`, and some aliases.
6. The extended math library also got `r2d(x)` (for converting from radians to
degrees) and `d2r(x)` (for converting from degrees to radians). This is to
allow using degrees with the standard library.
7. Both calculators now accept numbers in **scientific notation**. See the
[`bc` manual][9] and the [`dc` manual][10] for details.
8. Both calculators can **output in either scientific or engineering
notation**. See the [`bc` manual][9] and the [`dc` manual][10] for details.
9. Some inefficiencies were removed.
10. Some bugs were fixed.
11. Some bugs in the extended library were fixed.
12. Some defects from [Coverity Scan][11] were fixed.
## 1.1.4
This release contains a fix to the build system that allows it to build on older
versions of `glibc`.
## 1.1.3
This release contains a fix for a bug in the test suite where `bc` tests and
`dc` tests could not be run in parallel.
## 1.1.2
This release has a fix for a history bug; the down arrow did not work.
## 1.1.1
This release fixes a bug in the `1.1.0` build system. The source is exactly the
same.
The bug that was fixed was a failure to install if no `EXECSUFFIX` was used.
## 1.1.0
This is a production release. However, many new features were added since `1.0`.
1. **The build system has been changed** to use a custom, POSIX
shell-compatible configure script ([`configure.sh`][6]) to generate a POSIX
make-compatible `Makefile`, which means that `bc` and `dc` now build out of
the box on any POSIX-compatible system.
2. Out-of-memory and output errors now cause the `bc` to report the error,
clean up, and die, rather than just reporting and trying to continue.
3. **Strings and constants are now garbage collected** when possible.
4. Signal handling and checking has been made more simple and more thorough.
5. `BcGlobals` was refactored into `BcVm` and `BcVm` was made global. Some
procedure names were changed to reflect its difference to everything else.
6. Addition got a speed improvement.
7. Some common code for addition and multiplication was refactored into its own
procedure.
8. A bug was removed where `dc` could have been selected, but the internal
`#define` that returned `true` for a query about `dc` would not have
returned `true`.
9. Useless calls to `bc_num_zero()` were removed.
10. **History support was added.** The history support is based off of a
[UTF-8 aware fork][7] of [`linenoise`][8], which has been customized with
`bc`'s own data structures and signal handling.
11. Generating C source from the math library now removes tabs from the library,
shrinking the size of the executable.
12. The math library was shrunk.
13. Error handling and reporting was improved.
14. Reallocations were reduced by giving access to the request size for each
operation.
15. **`abs()` (`b` command for `dc`) was added as a builtin.**
16. Both calculators were tested on FreeBSD.
17. Many obscure parse bugs were fixed.
18. Markdown and man page manuals were added, and the man pages are installed by
`make install`.
19. Executable size was reduced, though the added features probably made the
executable end up bigger.
20. **GNU-style array references were added as a supported feature.**
21. Allocations were reduced.
22. **New operators were added**: `$` (`$` for `dc`), `@` (`@` for `dc`), `@=`,
`<<` (`H` for `dc`), `<<=`, `>>` (`h` for `dc`), and `>>=`. See the
[`bc` manual][9] and the [`dc` manual][10] for more details.
23. **An extended math library was added.** This library contains code that
makes it so I can replace my desktop calculator with this `bc`. See the
[`bc` manual][3] for more details.
24. Support for all capital letters as numbers was added.
25. **Support for GNU-style void functions was added.**
26. A bug fix for improper handling of function parameters was added.
27. Precedence for the or (`||`) operator was changed to match GNU `bc`.
28. `dc` was given an explicit negation command.
29. `dc` was changed to be able to handle strings in arrays.
## 1.1 Release Candidate 3
This release is the eighth release candidate for 1.1, though it is the third
release candidate meant as a general release candidate. The new code has not
been tested as thoroughly as it should for release.
## 1.1 Release Candidate 2
This release is the seventh release candidate for 1.1, though it is the second
release candidate meant as a general release candidate. The new code has not
been tested as thoroughly as it should for release.
## 1.1 FreeBSD Beta 5
This release is the sixth release candidate for 1.1, though it is the fifth
release candidate meant specifically to test if `bc` works on FreeBSD. The new
code has not been tested as thoroughly as it should for release.
## 1.1 FreeBSD Beta 4
This release is the fifth release candidate for 1.1, though it is the fourth
release candidate meant specifically to test if `bc` works on FreeBSD. The new
code has not been tested as thoroughly as it should for release.
## 1.1 FreeBSD Beta 3
This release is the fourth release candidate for 1.1, though it is the third
release candidate meant specifically to test if `bc` works on FreeBSD. The new
code has not been tested as thoroughly as it should for release.
## 1.1 FreeBSD Beta 2
This release is the third release candidate for 1.1, though it is the second
release candidate meant specifically to test if `bc` works on FreeBSD. The new
code has not been tested as thoroughly as it should for release.
## 1.1 FreeBSD Beta 1
This release is the second release candidate for 1.1, though it is meant
specifically to test if `bc` works on FreeBSD. The new code has not been tested as
thoroughly as it should for release.
## 1.1 Release Candidate 1
This is the first release candidate for 1.1. The new code has not been tested as
thoroughly as it should for release.
## 1.0
This is the first non-beta release. `bc` is ready for production use.
As such, a lot has changed since 0.5.
1. `dc` has been added. It has been tested even more thoroughly than `bc` was
for `0.5`. It does not have the `!` command, and for security reasons, it
never will, so it is complete.
2. `bc` has been more thoroughly tested. An entire section of the test suite
(for both programs) has been added to test for errors.
3. A prompt (`>>> `) has been added for interactive mode, making it easier to
see inputs and outputs.
4. Interrupt handling has been improved, including elimination of race
conditions (as much as possible).
5. MinGW and [Windows Subsystem for Linux][1] support has been added (see
[xstatic][2] for binaries).
6. Memory leaks and errors have been eliminated (as far as ASan and Valgrind
can tell).
7. Crashes have been eliminated (as far as [afl][3] can tell).
8. Karatsuba multiplication was added (and thoroughly) tested, speeding up
multiplication and power by orders of magnitude.
9. Performance was further enhanced by using a "divmod" function to reduce
redundant divisions and by removing superfluous `memset()` calls.
10. To switch between Karatsuba and `O(n^2)` multiplication, the config variable
`BC_NUM_KARATSUBA_LEN` was added. It is set to a sane default, but the
optimal number can be found with [`karatsuba.py`][4] (requires Python 3)
and then configured through `make`.
11. The random math test generator script was changed to Python 3 and improved.
`bc` and `dc` have together been run through 30+ million random tests.
12. All known math bugs have been fixed, including out of control memory
allocations in `sine` and `cosine` (that was actually a parse bug), certain
cases of infinite loop on square root, and slight inaccuracies (as much as
possible; see the [README][5]) in transcendental functions.
13. Parsing has been fixed as much as possible.
14. Test coverage was improved to 94.8%. The only paths not covered are ones
that happen when `malloc()` or `realloc()` fails.
15. An extension to get the length of an array was added.
16. The boolean not (`!`) had its precedence change to match negation.
17. Data input was hardened.
18. `bc` was made fully compliant with POSIX when the `-s` flag is used or
`POSIXLY_CORRECT` is defined.
19. Error handling was improved.
20. `bc` now checks that files it is given are not directories.
## 1.0 Release Candidate 7
This is the seventh release candidate for 1.0. It fixes a few bugs in 1.0
Release Candidate 6.
## 1.0 Release Candidate 6
This is the sixth release candidate for 1.0. It fixes a few bugs in 1.0 Release
Candidate 5.
## 1.0 Release Candidate 5
This is the fifth release candidate for 1.0. It fixes a few bugs in 1.0 Release
Candidate 4.
## 1.0 Release Candidate 4
This is the fourth release candidate for 1.0. It fixes a few bugs in 1.0 Release
Candidate 3.
## 1.0 Release Candidate 3
This is the third release candidate for 1.0. It fixes a few bugs in 1.0 Release
Candidate 2.
## 1.0 Release Candidate 2
This is the second release candidate for 1.0. It fixes a few bugs in 1.0 Release
Candidate 1.
## 1.0 Release Candidate 1
This is the first Release Candidate for 1.0. `bc` is complete, with `dc`, but it
is not tested.
## 0.5
This beta release completes more features, but it is still not complete nor
tested as thoroughly as necessary.
## 0.4.1
This beta release fixes a few bugs in 0.4.
## 0.4
This is a beta release. It does not have the complete set of features, and it is
not thoroughly tested.
[1]: https://docs.microsoft.com/en-us/windows/wsl/install-win10
[2]: https://pkg.musl.cc/bc/
[3]: http://lcamtuf.coredump.cx/afl/
[4]: ./karatsuba.py
[5]: ./README.md
[6]: ./configure.sh
[7]: https://github.com/rain-1/linenoise-mob
[8]: https://github.com/antirez/linenoise
[9]: ./manuals/bc.1.ronn
[10]: ./manuals/dc.1.ronn
[11]: https://scan.coverity.com/projects/gavinhoward-bc
[12]: ./locale_install.sh
[13]: ./manuals/build.md
[14]: https://github.com/stesser
[15]: https://github.com/bugcrazy
[16]: ./manuals/bc.1.ronn#extended-library
[17]: https://github.com/skeeto/optparse
[18]: https://www.deepl.com/translator
[19]: ./manuals/benchmarks.md

14
contrib/bc/NOTICE.md Normal file
View File

@ -0,0 +1,14 @@
# Notice
Copyright 2018-2020 Gavin D. Howard and contributors.
## Contributors
The contributors to `bc` (besides Gavin) are listed below in alphabetical order.
* Laurent Bercot (skarnet)
* Stefan Eßer (stesser)
* Michael Forney (michaelforney)
* John Regan (jprjr)
* rofl0r
* Zach van Rijn (me@zv.io)

332
contrib/bc/README.md Normal file
View File

@ -0,0 +1,332 @@
# `bc`
[![Build Status][13]][14]
[![codecov][15]][16]
[![Coverity Scan Build Status][17]][18]
***WARNING: This project has moved to [https://git.yzena.com/][20] for [these
reasons][21], though GitHub will remain a mirror.***
This is an implementation of the [POSIX `bc` calculator][12] that implements
[GNU `bc`][1] extensions, as well as the period (`.`) extension for the BSD
flavor of `bc`.
For more information, see this `bc`'s [full manual][2].
This `bc` also includes an implementation of `dc` in the same binary, accessible
via a symbolic link, which implements all FreeBSD and GNU extensions. (If a
standalone `dc` binary is desired, `bc` can be copied and renamed to `dc`.) The
`!` command is omitted; I believe this poses security concerns and that such
functionality is unnecessary.
For more information, see the `dc`'s [full manual][3].
This `bc` is Free and Open Source Software (FOSS). It is offered under the BSD
2-clause License. Full license text may be found in the [`LICENSE.md`][4] file.
## Prerequisites
This `bc` only requires a C99-compatible compiler and a (mostly) POSIX
2008-compatible system with the XSI (X/Open System Interfaces) option group.
Since POSIX 2008 with XSI requires the existence of a C99 compiler as `c99`, any
POSIX and XSI-compatible system will have everything needed.
Systems that are known to work:
* Linux
* FreeBSD
* OpenBSD
* NetBSD
* Mac OSX
* Solaris
* AIX
Please submit bug reports if this `bc` does not build out of the box on any
system besides Windows. If Windows binaries are needed, they can be found at
[xstatic][6].
## Build
This `bc` should build unmodified on any POSIX-compliant system.
For more complex build requirements than the ones below, see the
[build manual][5].
### Pre-built Binaries
It is possible to download pre-compiled binaries for a wide list of platforms,
including Linux- and Windows-based systems, from [xstatic][6]. This link always
points to the latest release of `bc`.
### Default
For the default build with optimization, use the following commands in the root
directory:
```
./configure.sh -O3
make
```
### One Calculator
To only build `bc`, use the following commands:
```
./configure.sh --disable-dc
make
```
To only build `dc`, use the following commands:
```
./configure.sh --disable-bc
make
```
### Debug
For debug builds, use the following commands in the root directory:
```
./configure.sh -g
make
```
### Install
To install, use the following command:
```
make install
```
By default, `bc` and `dc` will be installed in `/usr/local`. For installing in
other locations, use the `PREFIX` environment variable when running
`configure.sh` or pass the `--prefix=<prefix>` option to `configure.sh`. See the
[build manual][5], or run `./configure.sh --help`, for more details.
### Package and Distro Maintainers
#### Recommended Compiler
When I ran benchmarks with my `bc` compiled under `clang`, it performed much
better than when compiled under `gcc`. I recommend compiling this `bc` with
`clang`.
I also recommend building this `bc` with C11 if you can because `bc` will detect
a C11 compiler and add `_Noreturn` to any relevant function(s).
#### Recommended Optimizations
I wrote this `bc` with Separation of Concerns, which means that there are many
small functions that could be inlined. However, they are often called across
file boundaries, and the default optimizer can only look at the current file,
which means that they are not inlined.
Thus, because of the way this `bc` is built, it will automatically be slower
than other `bc` implementations when running scripts with no math. (My `bc`'s
math is *much* faster, so any non-trivial script should run faster in my `bc`.)
Some, or all, of the difference can be made up with the right optimizations. The
optimizations I recommend are:
1. `-O3`
2. `-flto` (link-time optimization)
in that order.
Link-time optimization, in particular, speeds up the `bc` a lot. This is because
when link-time optimization is turned on, the optimizer can look across files
and inline *much* more heavily.
However, I recommend ***NOT*** using `-march=native`. Doing so will reduce this
`bc`'s performance, at least when building with link-time optimization. See the
[benchmarks][19] for more details.
#### Stripping Binaries
By default, non-debug binaries are stripped, but stripping can be disabled with
the `-T` option to `configure.sh`.
#### Using This `bc` as an Alternative
If this `bc` is packaged as an alternative to an already existing `bc` package,
it is possible to rename it in the build to prevent name collision. To prepend
to the name, just run the following:
```
EXECPREFIX=<some_prefix> ./configure.sh
```
To append to the name, just run the following:
```
EXECSUFFIX=<some_suffix> ./configure.sh
```
If a package maintainer wishes to add both a prefix and a suffix, that is
allowed.
**Note**: The suggested name (and package name) when `bc` is not available is
`bc-gh`.
#### Karatsuba Number
Package and distro maintainers have one tool at their disposal to build this
`bc` in the optimal configuration: `karatsuba.py`.
This script is not a compile-time or runtime prerequisite; it is for package and
distro maintainers to run once when a package is being created. It finds the
optimal Karatsuba number (see the [algorithms manual][7] for more information)
for the machine that it is running on.
The easiest way to run this script is with `make karatsuba`.
If desired, maintainers can also skip running this script because there is a
sane default for the Karatsuba number.
## Status
This `bc` is robust.
It is well-tested, fuzzed, and fully standards-compliant (though not certified)
with POSIX `bc`. The math has been tested with 40+ million random problems, so
it is as correct as I can make it.
This `bc` can be used as a drop-in replacement for any existing `bc`. This `bc`
is also compatible with MinGW toolchains, though history is not supported on
Windows.
In addition, this `bc` is considered complete; i.e., there will be no more
releases with additional features. However, it *is* actively maintained, so if
any bugs are found, they will be fixed in new releases. Also, additional
translations will also be added as they are provided.
## Comparison to GNU `bc`
This `bc` compares favorably to GNU `bc`.
* It has more extensions, which make this `bc` more useful for scripting.
* This `bc` is a bit more POSIX compliant.
* It has a much less buggy parser. The GNU `bc` will give parse errors for what
is actually valid `bc` code, or should be. For example, putting an `else` on
a new line after a brace can cause GNU `bc` to give a parse error.
* This `bc` has fewer crashes.
* GNU `bc` calculates the wrong number of significant digits for `length(x)`.
* GNU `bc` will sometimes print numbers incorrectly. For example, when running
it on the file `tests/bc/power.txt` in this repo, GNU `bc` gets all the right
answers, but it fails to wrap the numbers at the proper place when outputting
to a file.
* This `bc` is faster. (See [Performance](#performance).)
### Performance
Because this `bc` packs more than `1` decimal digit per hardware integer, this
`bc` is faster than GNU `bc` and can be *much* faster. Full benchmarks can be
found at [manuals/benchmarks.md][19].
There is one instance where this `bc` is slower: if scripts are light on math.
This is because this `bc`'s intepreter is slightly slower than GNU `bc`, but
that is because it is more robust. See the [benchmarks][19].
## Algorithms
To see what algorithms this `bc` uses, see the [algorithms manual][7].
## Locales
Currently, this `bc` only has support for English (and US English), French,
German, Portuguese, Dutch, Polish, Russian, Japanese, and Chinese locales.
Patches are welcome for translations; use the existing `*.msg` files in
`locales/` as a starting point.
In addition, patches for improvements are welcome; the last two messages in
Portuguese were made with Google Translate, and the Dutch, Polish, Russian,
Japanese, and Chinese locales were all generated with [DeepL][22].
The message files provided assume that locales apply to all regions where a
language is used, but this might not be true for, e.g., `fr_CA` and `fr_CH`.
Any corrections or a confirmation that the current texts are acceptable for
those regions would be appreciated, too.
## Other Projects
Other projects based on this bc are:
* [busybox `bc`][8]. The busybox maintainers have made their own changes, so any
bugs in the busybox `bc` should be reported to them.
* [toybox `bc`][9]. The maintainer has also made his own changes, so bugs in the
toybox `bc` should be reported there.
## Language
This `bc` is written in pure ISO C99, using POSIX 2008 APIs.
## Commit Messages
This `bc` uses the commit message guidelines laid out in [this blog post][10].
## Semantic Versioning
This `bc` uses [semantic versioning][11].
## Contents
Items labeled with `(maintainer use only)` are not included in release source
tarballs.
Files:
.gitignore The git ignore file (maintainer use only).
.travis.yml The Travis CI file (maintainer use only).
codecov.yml The Codecov file (maintainer use only).
configure A symlink to configure.sh to make packaging easier.
configure.sh The configure script.
functions.sh A script with functions used by other scripts.
install.sh Install script.
karatsuba.py Script to find the optimal Karatsuba number.
LICENSE.md A Markdown form of the BSD 2-clause License.
link.sh A script to link dc to bc.
locale_install.sh A script to install locales, if desired.
locale_uninstall.sh A script to uninstall locales.
Makefile.in The Makefile template.
manpage.sh Script to generate man pages from ronn files.
NOTICE.md List of contributors and copyright owners.
RELEASE.md A checklist for making a release (maintainer use only).
release.sh A script to test for release (maintainer use only).
safe-install.sh Safe install script from musl libc.
Folders:
gen The bc math library, help texts, and code to generate C source.
include All header files.
locales Locale files, in .msg format. Patches welcome for translations.
manuals Manuals for both programs.
src All source code.
tests All tests.
[1]: https://www.gnu.org/software/bc/
[2]: ./manuals/bc.md
[3]: ./manuals/dc.md
[4]: ./LICENSE.md
[5]: ./manuals/build.md
[6]: https://pkg.musl.cc/bc/
[7]: ./manuals/algorithms.md
[8]: https://git.busybox.net/busybox/tree/miscutils/bc.c
[9]: https://github.com/landley/toybox/blob/master/toys/pending/bc.c
[10]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
[11]: http://semver.org/
[12]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[13]: https://travis-ci.com/gavinhoward/bc.svg?branch=master
[14]: https://travis-ci.com/gavinhoward/bc
[15]: https://codecov.io/gh/gavinhoward/bc/branch/master/graph/badge.svg
[16]: https://codecov.io/gh/gavinhoward/bc
[17]: https://img.shields.io/coverity/scan/16609.svg
[18]: https://scan.coverity.com/projects/gavinhoward-bc
[19]: ./manuals/benchmarks.md
[20]: https://git.yzena.com/gavin/bc
[21]: https://gavinhoward.com/2020/04/i-am-moving-away-from-github/
[22]: https://www.deepl.com/translator

54
contrib/bc/RELEASE.md Normal file
View File

@ -0,0 +1,54 @@
# Release Checklist
This is the checklist for cutting a release.
1. Update the README.
2. Update the manuals.
3. Test history manually.
4. Test with POSIX test suite.
5. Run the randmath.py script an excessive amount and add failing tests to
test suite.
* debug
* release
* minrelease
6. Fuzz with AFL.
* reldebug
7. Fix AFL crashes.
8. Find ASan crashes on AFL test cases.
9. Fix ASan crashes.
10. Build with xstatic.
11. Run and pass the `release.sh` script on my own machine.
12. Run and pass the `release.sh` script, without generated tests and
sanitizers, on FreeBSD.
13. Run and pass the `release.sh` script, without generated tests, sanitizers,
and 64-bit, on Thalheim's ARM server.
14. Run and pass the release script, with no generated tests, no clang, no
sanitizers, and no valgrind, on NetBSD.
15. Run and pass the release script, with no generated tests, no clang, no
sanitizers, and no valgrind, on OpenBSD.
16. Run Coverity Scan and eliminate warnings, if possible (both only).
* debug
17. Run `scan-build make`.
18. Repeat steps 3-14 again and repeat until nothing is found.
19. Update the benchmarks.
20. Change the version (remove "-dev") and commit.
21. Run `make clean_tests`.
22. Run the release script.
23. Upload the custom tarball to GitHub.
24. Add sha's to release notes.
25. Edit release notes for the changelog.
26. Increment to the next version (with "-dev").
27. Notify the following:
* FreeBSD
* Adelie Linux
* Ataraxia Linux
* Sabotage
* xstatic
* OpenBSD
* NetBSD
28. Submit new packages for the following:
* Alpine Linux
* Void Linux
* Gentoo Linux
* Linux from Scratch
* Arch Linux

115
contrib/bc/gen/bc_help.txt Normal file
View File

@ -0,0 +1,115 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 bc help text.
*
*/
usage: %s [options] [file...]
bc is a command-line, arbitrary-precision calculator with a Turing-complete
language. For details, use `man %s`.
This bc is compatible with both the GNU bc and the POSIX bc spec. See the GNU bc
manual (https://www.gnu.org/software/bc/manual/bc.html) and bc spec
(http://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
for details.
This bc has three differences to the GNU bc:
1) Arrays can be passed to the builtin "length" function to get the number of
elements currently in the array. The following example prints "1":
a[0] = 0
length(a[])
2) The precedence of the boolean "not" operator (!) is equal to that of the
unary minus (-), or negation, operator. This still allows POSIX-compliant
scripts to work while somewhat preserving expected behavior (versus C) and
making parsing easier.
3) This bc has many more extensions than the GNU bc does. For details, see the
man page.
Options:
-e expr --expression=expr
Run "expr" and quit. If multiple expressions or files (see below) are
given, they are all run before executing from stdin.
-f file --file=file
Run the bc code in "file" and exit. See above as well.
-g --global-stacks
Turn scale, ibase, and obase into stacks. This makes the value of each be
be restored on returning from functions. See the man page for more
details.
-h --help
Print this usage message and exit.
-i --interactive
Force interactive mode.
-l --mathlib
Use predefined math routines:
s(expr) = sine of expr in radians
c(expr) = cosine of expr in radians
a(expr) = arctangent of expr, returning radians
l(expr) = natural log of expr
e(expr) = raises e to the power of expr
j(n, x) = Bessel function of integer order n of x
-P --no-prompt
Disable the prompt in interactive mode.
-q --quiet
Don't print version and copyright.
-s --standard
Error if any non-POSIX extensions are used.
-w --warn
Warn if any non-POSIX extensions are used.
-v --version
Print version information and copyright and exit.

101
contrib/bc/gen/dc_help.txt Normal file
View File

@ -0,0 +1,101 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 dc help text.
*
*/
usage: %s [options] [file...]
dc is a reverse-polish notation command-line calculator which supports unlimited
precision arithmetic. For details, use `man %s`.
This dc is (mostly) compatible with the FreeBSD dc and the GNU dc. See the
FreeBSD man page (https://www.unix.com/man-page/FreeBSD/1/dc/) and the GNU dc
manual (https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html) for
details.
This dc has a few differences from the two above:
1) When printing a byte stream (command "P"), this bc follows what the FreeBSD
dc does.
2) This dc implements the GNU extensions for divmod ("~") and modular
exponentiation ("|").
3) This dc implements all FreeBSD extensions, except for "J" and "M".
4) This dc does not implement the run command ("!"), for security reasons.
5) Like the FreeBSD dc, this dc supports extended registers. However, they are
implemented differently. When it encounters whitespace where a register
should be, it skips the whitespace. If the character following is not
a lowercase letter, an error is issued. Otherwise, the register name is
parsed by the following regex:
[a-z][a-z0-9_]*
This generally means that register names will be surrounded by whitespace.
Examples:
l idx s temp L index S temp2 < do_thing
Also note that, unlike the FreeBSD dc, extended registers are not even
parsed unless the "-x" option is given. Instead, the space after a command
that requires a register name is taken as the register name.
Options:
-e expr --expression=expr
Run "expr" and quit. If multiple expressions or files (see below) are
given, they are all run. After running, dc will exit.
-f file --file=file
Run the dc code in "file" and exit. See above.
-h --help
Print this usage message and exit.
-i --interactive
Put dc into interactive mode. See the man page for more details.
-P --no-prompt
Disable the prompt in interactive mode.
-V --version
Print version and copyright and exit.
-x --extended-register
Enable extended register mode.

201
contrib/bc/gen/lib.bc Normal file
View File

@ -0,0 +1,201 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 bc math library.
*
*/
scale=20
define e(x){
auto b,s,n,r,d,i,p,f,v
b=ibase
ibase=A
if(x<0){
n=1
x=-x
}
s=scale
r=6+s+.44*x
scale=scale(x)+1
while(x>1){
d+=1
x/=2
scale+=1
}
scale=r
r=x+1
p=x
f=v=1
for(i=2;v;++i){
p*=x
f*=i
v=p/f
r+=v
}
while(d--)r*=r
scale=s
ibase=b
if(n)return(1/r)
return(r/1)
}
define l(x){
auto b,s,r,p,a,q,i,v
if(x<=0)return((1-A^scale)/1)
b=ibase
ibase=A
s=scale
scale+=6
p=2
while(x>=2){
p*=2
x=sqrt(x)
}
while(x<=.5){
p*=2
x=sqrt(x)
}
r=a=(x-1)/(x+1)
q=a*a
v=1
for(i=3;v;i+=2){
a*=q
v=a/i
r+=v
}
r*=p
scale=s
ibase=b
return(r/1)
}
define s(x){
auto b,s,r,a,q,i
if(x<0)return(-s(-x))
b=ibase
ibase=A
s=scale
scale=1.1*s+2
a=a(1)
scale=0
q=(x/a+2)/4
x-=4*q*a
if(q%2)x=-x
scale=s+2
r=a=x
q=-x*x
for(i=3;a;i+=2){
a*=q/(i*(i-1))
r+=a
}
scale=s
ibase=b
return(r/1)
}
define c(x){
auto b,s
b=ibase
ibase=A
s=scale
scale*=1.2
x=s(2*a(1)+x)
scale=s
ibase=b
return(x/1)
}
define a(x){
auto b,s,r,n,a,m,t,f,i,u
b=ibase
ibase=A
n=1
if(x<0){
n=-1
x=-x
}
if(scale<65){
if(x==1){
r=.7853981633974483096156608458198757210492923498437764552437361480/n
ibase=b
return(r)
}
if(x==.2){
r=.1973955598498807583700497651947902934475851037878521015176889402/n
ibase=b
return(r)
}
}
s=scale
if(x>.2){
scale+=5
a=a(.2)
}
scale=s+3
while(x>.2){
m+=1
x=(x-.2)/(1+.2*x)
}
r=u=x
f=-x*x
t=1
for(i=3;t;i+=2){
u*=f
t=u/i
r+=t
}
scale=s
ibase=b
return((m*a+r)/n)
}
define j(n,x){
auto b,s,o,a,i,v,f
b=ibase
ibase=A
s=scale
scale=0
n/=1
if(n<0){
n=-n
o=n%2
}
a=1
for(i=2;i<=n;++i)a*=i
scale=1.5*s
a=(x^n)/2^n/a
r=v=1
f=-x*x/4
scale+=length(a)-scale(a)
for(i=1;v;++i){
v=v*f/i/(n+i)
r+=v
}
scale=s
ibase=b
if(o)a=-a
return(a*r/1)
}

317
contrib/bc/gen/lib2.bc Normal file
View File

@ -0,0 +1,317 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 second bc math library.
*
*/
define p(x,y){
auto a
a=y$
if(y==a)return (x^a)@scale
return e(y*l(x))
}
define r(x,p){
auto t,n
if(x==0)return x
p=abs(p)$
n=(x<0)
x=abs(x)
t=x@p
if(p<scale(x)&&x-t>=5>>p+1)t+=1>>p
if(n)t=-t
return t
}
define ceil(x,p){
auto t,n
if(x==0)return x
p=abs(p)$
n=(x<0)
x=abs(x)
t=(x+((x@p<x)>>p))@p
if(n)t=-t
return t
}
define f(n){
auto r
n=abs(n)$
for(r=1;n>1;--n)r*=n
return r
}
define perm(n,k){
auto f,g,s
if(k>n)return 0
n=abs(n)$
k=abs(k)$
f=f(n)
g=f(n-k)
s=scale
scale=0
f/=g
scale=s
return f
}
define comb(n,r){
auto s,f,g,h
if(r>n)return 0
n=abs(n)$
r=abs(r)$
s=scale
scale=0
f=f(n)
h=f(r)
g=f(n-r)
f/=h*g
scale=s
return f
}
define log(x,b){
auto p,s
s=scale
if(scale<K)scale=K
if(scale(x)>scale)scale=scale(x)
scale*=2
p=l(x)/l(b)
scale=s
return p@s
}
define l2(x){return log(x,2)}
define l10(x){return log(x,A)}
define root(x,n){
auto s,m,r,q,p
if(n<0)sqrt(n)
n=n$
if(n==0)x/n
if(n==1)return x
if(n==2)return sqrt(x)
s=scale
scale=0
if(x<0&&n%2==0)sqrt(x)
scale=s+2
m=(x<0)
x=abs(x)
p=n-1
q=10^ceil((length(x$)/n)$,0)
while(r!=q){
r=q
q=(p*r+x/r^p)/n
}
if(m)r=-r
scale=s
return r@s
}
define cbrt(x){return root(x,3)}
define pi(s){
auto t,v
if(s==0)return 3
s=abs(s)$
t=scale
scale=s+1
v=4*a(1)
scale=t
return v@s
}
define t(x){
auto s,c,l
l=scale
scale+=2
s=s(x)
c=c(x)
scale=l
return s/c
}
define a2(y,x){
auto a,p
if(!x&&!y)y/x
if(x<=0){
p=pi(scale+2)
if(y<0)p=-p
}
if(x==0)a=p/2
else{
scale+=2
a=a(y/x)+p
scale-=2
}
return a@scale
}
define sin(x){return s(x)}
define cos(x){return c(x)}
define atan(x){return a(x)}
define tan(x){return t(x)}
define atan2(y,x){return a2(y,x)}
define r2d(x){
auto r,i,s
s=scale
scale+=5
i=ibase
ibase=A
r=x*180/pi(scale)
ibase=i
scale=s
return r@s
}
define d2r(x){
auto r,i,s
s=scale
scale+=5
i=ibase
ibase=A
r=x*pi(scale)/180
ibase=i
scale=s
return r@s
}
define frand(p){
p=abs(p)$
return irand(10^p)>>p
}
define ifrand(i,p){return irand(abs(i)$)+frand(p)}
define srand(x){
if(irand(2))return -x
return x
}
define brand(){return irand(2)}
define void output(x,b){
auto c
c=obase
obase=b
x
obase=c
}
define void hex(x){output(x,G)}
define void binary(x){output(x,2)}
define ubytes(x){
auto p,b,i
b=ibase
ibase=A
x=abs(x)$
i=2^8
for(p=1;i-1<x;p*=2){i*=i}
ibase=b
return p
}
define sbytes(x){
auto p,b,n,z
z=(x<0)
x=abs(x)
x=x$
n=ubytes(x)
b=ibase
ibase=A
p=2^(n*8-1)
if(x>p||(!z&&x==p))n*=2
ibase=b
return n
}
define void output_byte(x,i){
auto j,p,y,b
j=ibase
ibase=A
s=scale
scale=0
x=abs(x)$
b=x/(2^(i*8))
b%=2^8
y=log(256,obase)
if(b>1)p=log(b,obase)+1
else p=b
for(i=y-p;i>0;--i)print 0
if(b)print b
scale=s
ibase=j
}
define void output_uint(x,n){
auto i,b
b=ibase
ibase=A
for(i=n-1;i>=0;--i){
output_byte(x,i)
if(i)print" "
else print"\n"
}
ibase=b
}
define void hex_uint(x,n){
auto o
o=obase
obase=G
output_uint(x,n)
obase=o
}
define void binary_uint(x,n){
auto o
o=obase
obase=2
output_uint(x,n)
obase=o
}
define void uintn(x,n){
if(scale(x)){
print"Error: ",x," is not an integer.\n"
return
}
if(x<0){
print"Error: ",x," is negative.\n"
return
}
if(x>=2^(n*8)){
print"Error: ",x," cannot fit into ",n," unsigned byte(s).\n"
return
}
binary_uint(x,n)
hex_uint(x,n)
}
define void intn(x,n){
auto t
if(scale(x)){
print"Error: ",x," is not an integer.\n"
return
}
t=2^(n*8-1)
if(abs(x)>=t&&(x>0||x!=-t)){
print "Error: ",x," cannot fit into ",n," signed byte(s).\n"
return
}
if(x<0)x=2^(n*8)-(-x)
binary_uint(x,n)
hex_uint(x,n)
}
define void uint8(x){uintn(x,1)}
define void int8(x){intn(x,1)}
define void uint16(x){uintn(x,2)}
define void int16(x){intn(x,2)}
define void uint32(x){uintn(x,4)}
define void int32(x){intn(x,4)}
define void uint64(x){uintn(x,8)}
define void int64(x){intn(x,8)}
define void uint(x){uintn(x,ubytes(x))}
define void int(x){intn(x,sbytes(x))}

79
contrib/bc/gen/strgen.sh Executable file
View File

@ -0,0 +1,79 @@
#! /bin/sh
#
# Copyright (c) 2018-2020 Gavin D. Howard and contributors.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
#
export LANG=C
export LC_CTYPE=C
progname=${0##*/}
if [ $# -lt 4 ]; then
echo "usage: $progname input output name header [label [define [remove_tabs]]]"
exit 1
fi
input="$1"
output="$2"
name="$3"
header="$4"
label="$5"
define="$6"
remove_tabs="$7"
exec < "$input"
exec > "$output"
if [ -n "$label" ]; then
nameline="const char *${label} = \"${input}\";"
fi
if [ -n "$define" ]; then
condstart="#if ${define}"
condend="#endif"
fi
if [ -n "$remove_tabs" ]; then
if [ "$remove_tabs" -ne 0 ]; then
remtabsexpr='s: ::g;'
fi
fi
cat<<EOF
// Licensed under the 2-clause BSD license.
// *** AUTOMATICALLY GENERATED FROM ${input}. DO NOT MODIFY. ***
${condstart}
#include <${header}>
$nameline
const char ${name}[] =
$(sed -e "$remtabsexpr " -e '1,/^$/d; s:\\n:\\\\n:g; s:":\\":g; s:^:":; s:$:\\n":')
;
${condend}
EOF

46
contrib/bc/include/args.h Normal file
View File

@ -0,0 +1,46 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for processing command-line arguments.
*
*/
#ifndef BC_ARGS_H
#define BC_ARGS_H
#include <status.h>
#include <vm.h>
void bc_args(int argc, char *argv[]);
extern const char* const bc_args_env_name;
#endif // BC_ARGS_H

181
contrib/bc/include/bc.h Normal file
View File

@ -0,0 +1,181 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for bc.
*
*/
#ifndef BC_BC_H
#define BC_BC_H
#if BC_ENABLED
#include <limits.h>
#include <stdbool.h>
#include <status.h>
#include <lex.h>
#include <parse.h>
void bc_main(int argc, char **argv);
extern const char bc_help[];
extern const char bc_lib[];
extern const char* bc_lib_name;
#if BC_ENABLE_EXTRA_MATH
extern const char bc_lib2[];
extern const char* bc_lib2_name;
#endif // BC_ENABLE_EXTRA_MATH
typedef struct BcLexKeyword {
uchar data;
const char name[9];
} BcLexKeyword;
#define BC_LEX_CHAR_MSB(bit) ((bit) << (CHAR_BIT - 1))
#define BC_LEX_KW_POSIX(kw) ((kw)->data & (BC_LEX_CHAR_MSB(1)))
#define BC_LEX_KW_LEN(kw) ((size_t) ((kw)->data & ~(BC_LEX_CHAR_MSB(1))))
#define BC_LEX_KW_ENTRY(a, b, c) \
{ .data = ((b) & ~(BC_LEX_CHAR_MSB(1))) | BC_LEX_CHAR_MSB(c), .name = a }
extern const BcLexKeyword bc_lex_kws[];
extern const size_t bc_lex_kws_len;
void bc_lex_token(BcLex *l);
#define BC_PARSE_TOP_FLAG_PTR(p) ((uint16_t*) bc_vec_top(&(p)->flags))
#define BC_PARSE_TOP_FLAG(p) (*(BC_PARSE_TOP_FLAG_PTR(p)))
#define BC_PARSE_FLAG_BRACE (UINTMAX_C(1)<<0)
#define BC_PARSE_BRACE(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_BRACE)
#define BC_PARSE_FLAG_FUNC_INNER (UINTMAX_C(1)<<1)
#define BC_PARSE_FUNC_INNER(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_FUNC_INNER)
#define BC_PARSE_FLAG_FUNC (UINTMAX_C(1)<<2)
#define BC_PARSE_FUNC(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_FUNC)
#define BC_PARSE_FLAG_BODY (UINTMAX_C(1)<<3)
#define BC_PARSE_BODY(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_BODY)
#define BC_PARSE_FLAG_LOOP (UINTMAX_C(1)<<4)
#define BC_PARSE_LOOP(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_LOOP)
#define BC_PARSE_FLAG_LOOP_INNER (UINTMAX_C(1)<<5)
#define BC_PARSE_LOOP_INNER(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_LOOP_INNER)
#define BC_PARSE_FLAG_IF (UINTMAX_C(1)<<6)
#define BC_PARSE_IF(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_IF)
#define BC_PARSE_FLAG_ELSE (UINTMAX_C(1)<<7)
#define BC_PARSE_ELSE(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_ELSE)
#define BC_PARSE_FLAG_IF_END (UINTMAX_C(1)<<8)
#define BC_PARSE_IF_END(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_IF_END)
#define BC_PARSE_NO_EXEC(p) ((p)->flags.len != 1 || BC_PARSE_TOP_FLAG(p) != 0)
#define BC_PARSE_DELIMITER(t) \
((t) == BC_LEX_SCOLON || (t) == BC_LEX_NLINE || (t) == BC_LEX_EOF)
#define BC_PARSE_BLOCK_STMT(f) \
((f) & (BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_LOOP_INNER))
#define BC_PARSE_OP(p, l) (((p) & ~(BC_LEX_CHAR_MSB(1))) | (BC_LEX_CHAR_MSB(l)))
#define BC_PARSE_OP_DATA(t) bc_parse_ops[((t) - BC_LEX_OP_INC)]
#define BC_PARSE_OP_LEFT(op) (BC_PARSE_OP_DATA(op) & BC_LEX_CHAR_MSB(1))
#define BC_PARSE_OP_PREC(op) (BC_PARSE_OP_DATA(op) & ~(BC_LEX_CHAR_MSB(1)))
#define BC_PARSE_EXPR_ENTRY(e1, e2, e3, e4, e5, e6, e7, e8) \
((UINTMAX_C(e1) << 7) | (UINTMAX_C(e2) << 6) | (UINTMAX_C(e3) << 5) | \
(UINTMAX_C(e4) << 4) | (UINTMAX_C(e5) << 3) | (UINTMAX_C(e6) << 2) | \
(UINTMAX_C(e7) << 1) | (UINTMAX_C(e8) << 0))
#define BC_PARSE_EXPR(i) \
(bc_parse_exprs[(((i) & (uchar) ~(0x07)) >> 3)] & (1 << (7 - ((i) & 0x07))))
#define BC_PARSE_TOP_OP(p) (*((BcLexType*) bc_vec_top(&(p)->ops)))
#define BC_PARSE_LEAF(prev, bin_last, rparen) \
(!(bin_last) && ((rparen) || bc_parse_inst_isLeaf(prev)))
#if BC_ENABLE_EXTRA_MATH
#define BC_PARSE_INST_VAR(t) \
((t) >= BC_INST_VAR && (t) <= BC_INST_SEED && (t) != BC_INST_ARRAY)
#else // BC_ENABLE_EXTRA_MATH
#define BC_PARSE_INST_VAR(t) \
((t) >= BC_INST_VAR && (t) <= BC_INST_SCALE && (t) != BC_INST_ARRAY)
#endif // BC_ENABLE_EXTRA_MATH
#define BC_PARSE_PREV_PREFIX(p) \
((p) >= BC_INST_NEG && (p) <= BC_INST_BOOL_NOT)
#define BC_PARSE_OP_PREFIX(t) ((t) == BC_LEX_OP_BOOL_NOT || (t) == BC_LEX_NEG)
// We can calculate the conversion between tokens and exprs by subtracting the
// position of the first operator in the lex enum and adding the position of
// the first in the expr enum. Note: This only works for binary operators.
#define BC_PARSE_TOKEN_INST(t) ((uchar) ((t) - BC_LEX_NEG + BC_INST_NEG))
typedef enum BcParseStatus {
BC_PARSE_STATUS_SUCCESS,
BC_PARSE_STATUS_EMPTY_EXPR,
} BcParseStatus;
void bc_parse_expr(BcParse *p, uint8_t flags);
void bc_parse_parse(BcParse *p);
void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next);
// This is necessary to clear up for if statements at the end of files.
void bc_parse_noElse(BcParse *p);
extern const char bc_sig_msg[];
extern const uchar bc_sig_msg_len;
extern const char* const bc_parse_const1;
extern const uint8_t bc_parse_exprs[];
extern const uchar bc_parse_ops[];
extern const BcParseNext bc_parse_next_expr;
extern const BcParseNext bc_parse_next_param;
extern const BcParseNext bc_parse_next_print;
extern const BcParseNext bc_parse_next_rel;
extern const BcParseNext bc_parse_next_elem;
extern const BcParseNext bc_parse_next_for;
extern const BcParseNext bc_parse_next_read;
#endif // BC_ENABLED
#endif // BC_BC_H

70
contrib/bc/include/dc.h Normal file
View File

@ -0,0 +1,70 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for bc.
*
*/
#ifndef BC_DC_H
#define BC_DC_H
#ifndef DC_ENABLE_RAND
#define DC_ENABLE_RAND (1)
#endif // DC_ENABLE_RAND
#if DC_ENABLED
#include <status.h>
#include <lex.h>
#include <parse.h>
void dc_main(int argc, char **argv);
extern const char dc_help[];
void dc_lex_token(BcLex *l);
bool dc_lex_negCommand(BcLex *l);
extern const char dc_sig_msg[];
extern const uchar dc_sig_msg_len;
extern const uint8_t dc_lex_regs[];
extern const size_t dc_lex_regs_len;
extern const uint8_t dc_lex_tokens[];
extern const uint8_t dc_parse_insts[];
void dc_parse_parse(BcParse *p);
void dc_parse_expr(BcParse *p, uint8_t flags);
#endif // DC_ENABLED
#endif // BC_DC_H

67
contrib/bc/include/file.h Normal file
View File

@ -0,0 +1,67 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for implementing buffered I/O on my own terms.
*
*/
#ifndef BC_FILE_H
#define BC_FILE_H
#include <stdarg.h>
#include <vector.h>
#define BC_FILE_ULL_LENGTH (21)
typedef struct BcFile {
int fd;
char *buf;
size_t len;
size_t cap;
} BcFile;
void bc_file_init(BcFile *f, int fd, char *buf, size_t cap);
void bc_file_free(BcFile *f);
void bc_file_putchar(BcFile *restrict f, uchar c);
BcStatus bc_file_flushErr(BcFile *restrict f);
void bc_file_flush(BcFile *restrict f);
void bc_file_write(BcFile *restrict f, const char *buf, size_t n);
void bc_file_printf(BcFile *restrict f, const char *fmt, ...);
void bc_file_vprintf(BcFile *restrict f, const char *fmt, va_list args);
void bc_file_puts(BcFile *restrict f, const char *str);
void bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH]);
#endif // BC_FILE_H

View File

@ -0,0 +1,260 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Adapted from the following:
*
* linenoise.c -- guerrilla line editing library against the idea that a
* line editing lib needs to be 20,000 lines of C code.
*
* You can find the original source code at:
* http://github.com/antirez/linenoise
*
* You can find the fork that this code is based on at:
* https://github.com/rain-1/linenoise-mob
*
* ------------------------------------------------------------------------
*
* This code is also under the following license:
*
* Copyright (c) 2010-2016, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE COPYRIGHT
* HOLDER 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.
*
* *****************************************************************************
*
* Definitions for line history.
*
*/
#ifndef BC_HISTORY_H
#define BC_HISTORY_H
#ifndef BC_ENABLE_HISTORY
#define BC_ENABLE_HISTORY (1)
#endif // BC_ENABLE_HISTORY
#if BC_ENABLE_HISTORY
#ifdef _WIN32
#error History is not supported on Windows.
#endif // _WIN32
#include <stdbool.h>
#include <stddef.h>
#include <signal.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <sys/select.h>
#include <status.h>
#include <vector.h>
#include <read.h>
#if BC_DEBUG_CODE
#include <file.h>
#endif // BC_DEBUG_CODE
#define BC_HIST_DEF_COLS (80)
#define BC_HIST_MAX_LEN (128)
#define BC_HIST_MAX_LINE (4095)
#define BC_HIST_SEQ_SIZE (64)
#define BC_HIST_BUF_LEN(h) ((h)->buf.len - 1)
#define BC_HIST_READ(s, n) (bc_history_read((s), (n)) == -1)
#define BC_HIST_NEXT (false)
#define BC_HIST_PREV (true)
#if BC_DEBUG_CODE
#define BC_HISTORY_DEBUG_BUF_SIZE (1024)
#define lndebug(...) \
do { \
if (bc_history_debug_fp.fd == 0) { \
bc_history_debug_buf = bc_vm_malloc(BC_HISTORY_DEBUG_BUF_SIZE); \
bc_file_init(&bc_history_debug_fp, \
open("/tmp/lndebug.txt", O_APPEND), \
BC_HISTORY_DEBUG_BUF_SIZE); \
bc_file_printf(&bc_history_debug_fp, \
"[%zu %zu %zu] p: %d, rows: %d, " \
"rpos: %d, max: %zu, oldmax: %d\n", \
l->len, l->pos, l->oldcolpos, plen, rows, rpos, \
l->maxrows, old_rows); \
} \
bc_file_printf(&bc_history_debug_fp, ", " __VA_ARGS__); \
bc_file_flush(&bc_history_debug_fp); \
} while (0)
#else // BC_DEBUG_CODE
#define lndebug(fmt, ...)
#endif // BC_DEBUG_CODE
#if !BC_ENABLE_PROMPT
#define bc_history_line(h, vec, prompt) bc_history_line(h, vec)
#define bc_history_raw(h, prompt) bc_history_raw(h)
#define bc_history_edit(h, prompt) bc_history_edit(h)
#endif // BC_ENABLE_PROMPT
typedef enum BcHistoryAction {
BC_ACTION_NULL = 0,
BC_ACTION_CTRL_A = 1,
BC_ACTION_CTRL_B = 2,
BC_ACTION_CTRL_C = 3,
BC_ACTION_CTRL_D = 4,
BC_ACTION_CTRL_E = 5,
BC_ACTION_CTRL_F = 6,
BC_ACTION_CTRL_H = 8,
BC_ACTION_TAB = 9,
BC_ACTION_LINE_FEED = 10,
BC_ACTION_CTRL_K = 11,
BC_ACTION_CTRL_L = 12,
BC_ACTION_ENTER = 13,
BC_ACTION_CTRL_N = 14,
BC_ACTION_CTRL_P = 16,
BC_ACTION_CTRL_T = 20,
BC_ACTION_CTRL_U = 21,
BC_ACTION_CTRL_W = 23,
BC_ACTION_CTRL_Z = 26,
BC_ACTION_ESC = 27,
BC_ACTION_BACKSPACE = 127
} BcHistoryAction;
/**
* This represents the state during line editing. We pass this state
* to functions implementing specific editing functionalities.
*/
typedef struct BcHistory {
/// Edited line buffer.
BcVec buf;
/// The history.
BcVec history;
#if BC_ENABLE_PROMPT
/// Prompt to display.
const char *prompt;
/// Prompt length.
size_t plen;
#endif // BC_ENABLE_PROMPT
/// Prompt column length.
size_t pcol;
/// Current cursor position.
size_t pos;
/// Previous refresh cursor column position.
size_t oldcolpos;
/// Number of columns in terminal.
size_t cols;
/// The history index we are currently editing.
size_t idx;
/// The original terminal state.
struct termios orig_termios;
/// These next three are here because pahole found a 4 byte hole here.
/// This is to signal that there is more, so we don't process yet.
bool stdin_has_data;
/// Whether we are in rawmode.
bool rawMode;
/// Whether the terminal is bad.
bool badTerm;
/// This is to check if stdin has more data.
fd_set rdset;
/// This is to check if stdin has more data.
struct timespec ts;
/// This is to check if stdin has more data.
sigset_t sigmask;
} BcHistory;
BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt);
void bc_history_init(BcHistory *h);
void bc_history_free(BcHistory *h);
extern const char *bc_history_bad_terms[];
extern const char bc_history_tab[];
extern const size_t bc_history_tab_len;
extern const char bc_history_ctrlc[];
extern const uint32_t bc_history_wchars[][2];
extern const size_t bc_history_wchars_len;
extern const uint32_t bc_history_combo_chars[];
extern const size_t bc_history_combo_chars_len;
#if BC_DEBUG_CODE
extern BcFile bc_history_debug_fp;
extern char *bc_history_debug_buf;
void bc_history_printKeyCodes(BcHistory* l);
#endif // BC_DEBUG_CODE
#endif // BC_ENABLE_HISTORY
#endif // BC_HISTORY_H

326
contrib/bc/include/lang.h Normal file
View File

@ -0,0 +1,326 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for program data.
*
*/
#ifndef BC_LANG_H
#define BC_LANG_H
#include <stdbool.h>
#include <status.h>
#include <vector.h>
#include <num.h>
#if BC_ENABLED
#define BC_INST_IS_ASSIGN(i) \
((i) == BC_INST_ASSIGN || (i) == BC_INST_ASSIGN_NO_VAL)
#define BC_INST_USE_VAL(i) ((i) <= BC_INST_ASSIGN)
#else // BC_ENABLED
#define BC_INST_IS_ASSIGN(i) ((i) == BC_INST_ASSIGN_NO_VAL)
#define BC_INST_USE_VAL(i) (false)
#endif // BC_ENABLED
#ifndef NDEBUG
#define BC_ENABLE_FUNC_FREE (1)
#else // NDEBUG
#define BC_ENABLE_FUNC_FREE DC_ENABLED
#endif // NDEBUG
typedef enum BcInst {
#if BC_ENABLED
BC_INST_INC = 0,
BC_INST_DEC,
#endif // BC_ENABLED
BC_INST_NEG,
BC_INST_BOOL_NOT,
#if BC_ENABLE_EXTRA_MATH
BC_INST_TRUNC,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_POWER,
BC_INST_MULTIPLY,
BC_INST_DIVIDE,
BC_INST_MODULUS,
BC_INST_PLUS,
BC_INST_MINUS,
#if BC_ENABLE_EXTRA_MATH
BC_INST_PLACES,
BC_INST_LSHIFT,
BC_INST_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_REL_EQ,
BC_INST_REL_LE,
BC_INST_REL_GE,
BC_INST_REL_NE,
BC_INST_REL_LT,
BC_INST_REL_GT,
BC_INST_BOOL_OR,
BC_INST_BOOL_AND,
#if BC_ENABLED
BC_INST_ASSIGN_POWER,
BC_INST_ASSIGN_MULTIPLY,
BC_INST_ASSIGN_DIVIDE,
BC_INST_ASSIGN_MODULUS,
BC_INST_ASSIGN_PLUS,
BC_INST_ASSIGN_MINUS,
#if BC_ENABLE_EXTRA_MATH
BC_INST_ASSIGN_PLACES,
BC_INST_ASSIGN_LSHIFT,
BC_INST_ASSIGN_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_ASSIGN,
BC_INST_ASSIGN_POWER_NO_VAL,
BC_INST_ASSIGN_MULTIPLY_NO_VAL,
BC_INST_ASSIGN_DIVIDE_NO_VAL,
BC_INST_ASSIGN_MODULUS_NO_VAL,
BC_INST_ASSIGN_PLUS_NO_VAL,
BC_INST_ASSIGN_MINUS_NO_VAL,
#if BC_ENABLE_EXTRA_MATH
BC_INST_ASSIGN_PLACES_NO_VAL,
BC_INST_ASSIGN_LSHIFT_NO_VAL,
BC_INST_ASSIGN_RSHIFT_NO_VAL,
#endif // BC_ENABLE_EXTRA_MATH
#endif // BC_ENABLED
BC_INST_ASSIGN_NO_VAL,
BC_INST_NUM,
BC_INST_VAR,
BC_INST_ARRAY_ELEM,
#if BC_ENABLED
BC_INST_ARRAY,
#endif // BC_ENABLED
BC_INST_ONE,
#if BC_ENABLED
BC_INST_LAST,
#endif // BC_ENABLED
BC_INST_IBASE,
BC_INST_OBASE,
BC_INST_SCALE,
#if BC_ENABLE_EXTRA_MATH
BC_INST_SEED,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_LENGTH,
BC_INST_SCALE_FUNC,
BC_INST_SQRT,
BC_INST_ABS,
#if BC_ENABLE_EXTRA_MATH
BC_INST_IRAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_READ,
#if BC_ENABLE_EXTRA_MATH
BC_INST_RAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_MAXIBASE,
BC_INST_MAXOBASE,
BC_INST_MAXSCALE,
#if BC_ENABLE_EXTRA_MATH
BC_INST_MAXRAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_PRINT,
BC_INST_PRINT_POP,
BC_INST_STR,
BC_INST_PRINT_STR,
#if BC_ENABLED
BC_INST_JUMP,
BC_INST_JUMP_ZERO,
BC_INST_CALL,
BC_INST_RET,
BC_INST_RET0,
BC_INST_RET_VOID,
BC_INST_HALT,
#endif // BC_ENABLED
BC_INST_POP,
#if DC_ENABLED
BC_INST_POP_EXEC,
BC_INST_MODEXP,
BC_INST_DIVMOD,
BC_INST_EXECUTE,
BC_INST_EXEC_COND,
BC_INST_ASCIIFY,
BC_INST_PRINT_STREAM,
BC_INST_PRINT_STACK,
BC_INST_CLEAR_STACK,
BC_INST_STACK_LEN,
BC_INST_DUPLICATE,
BC_INST_SWAP,
BC_INST_LOAD,
BC_INST_PUSH_VAR,
BC_INST_PUSH_TO_VAR,
BC_INST_QUIT,
BC_INST_NQUIT,
#endif // DC_ENABLED
BC_INST_INVALID = UCHAR_MAX,
} BcInst;
typedef struct BcId {
char *name;
size_t idx;
} BcId;
typedef struct BcLoc {
size_t loc;
size_t idx;
} BcLoc;
typedef struct BcConst {
char *val;
BcBigDig base;
BcNum num;
} BcConst;
typedef struct BcFunc {
BcVec code;
#if BC_ENABLED
BcVec labels;
BcVec autos;
size_t nparams;
#endif // BC_ENABLED
BcVec strs;
BcVec consts;
const char *name;
#if BC_ENABLED
bool voidfn;
#endif // BC_ENABLED
} BcFunc;
typedef enum BcResultType {
BC_RESULT_VAR,
BC_RESULT_ARRAY_ELEM,
#if BC_ENABLED
BC_RESULT_ARRAY,
#endif // BC_ENABLED
BC_RESULT_STR,
BC_RESULT_CONSTANT,
BC_RESULT_TEMP,
BC_RESULT_ONE,
#if BC_ENABLED
BC_RESULT_LAST,
BC_RESULT_VOID,
#endif // BC_ENABLED
BC_RESULT_IBASE,
BC_RESULT_OBASE,
BC_RESULT_SCALE,
#if BC_ENABLE_EXTRA_MATH
BC_RESULT_SEED,
#endif // BC_ENABLE_EXTRA_MATH
} BcResultType;
typedef union BcResultData {
BcNum n;
BcVec v;
BcLoc loc;
} BcResultData;
typedef struct BcResult {
BcResultType t;
BcResultData d;
} BcResult;
typedef struct BcInstPtr {
size_t func;
size_t idx;
size_t len;
} BcInstPtr;
typedef enum BcType {
BC_TYPE_VAR,
BC_TYPE_ARRAY,
#if BC_ENABLED
BC_TYPE_REF,
#endif // BC_ENABLED
} BcType;
struct BcProgram;
void bc_func_init(BcFunc *f, const char* name);
void bc_func_insert(BcFunc *f, struct BcProgram* p, char* name,
BcType type, size_t line);
void bc_func_reset(BcFunc *f);
void bc_func_free(void *func);
void bc_array_init(BcVec *a, bool nums);
void bc_array_copy(BcVec *d, const BcVec *s);
void bc_string_free(void *string);
void bc_const_free(void *constant);
void bc_id_free(void *id);
void bc_result_clear(BcResult *r);
void bc_result_copy(BcResult *d, BcResult *src);
void bc_result_free(void *result);
void bc_array_expand(BcVec *a, size_t len);
int bc_id_cmp(const BcId *e1, const BcId *e2);
#if BC_DEBUG_CODE
extern const char* bc_inst_names[];
#endif // BC_DEBUG_CODE
extern const char bc_func_main[];
extern const char bc_func_read[];
#endif // BC_LANG_H

232
contrib/bc/include/lex.h Normal file
View File

@ -0,0 +1,232 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for bc's lexer.
*
*/
#ifndef BC_LEX_H
#define BC_LEX_H
#include <stdbool.h>
#include <stddef.h>
#include <status.h>
#include <vector.h>
#include <lang.h>
#define bc_lex_err(l, e) (bc_vm_error((e), (l)->line))
#define bc_lex_verr(l, e, ...) (bc_vm_error((e), (l)->line, __VA_ARGS__))
#define BC_LEX_NEG_CHAR (BC_IS_BC ? '-' : '_')
#define BC_LEX_LAST_NUM_CHAR (BC_IS_BC ? 'Z' : 'F')
#define BC_LEX_NUM_CHAR(c, pt, int_only) \
(isdigit(c) || ((c) >= 'A' && (c) <= BC_LEX_LAST_NUM_CHAR) || \
((c) == '.' && !(pt) && !(int_only)))
// BC_LEX_NEG is not used in lexing; it is only for parsing.
typedef enum BcLexType {
BC_LEX_EOF,
BC_LEX_INVALID,
#if BC_ENABLED
BC_LEX_OP_INC,
BC_LEX_OP_DEC,
#endif // BC_ENABLED
BC_LEX_NEG,
BC_LEX_OP_BOOL_NOT,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_OP_TRUNC,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_OP_POWER,
BC_LEX_OP_MULTIPLY,
BC_LEX_OP_DIVIDE,
BC_LEX_OP_MODULUS,
BC_LEX_OP_PLUS,
BC_LEX_OP_MINUS,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_OP_PLACES,
BC_LEX_OP_LSHIFT,
BC_LEX_OP_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_OP_REL_EQ,
BC_LEX_OP_REL_LE,
BC_LEX_OP_REL_GE,
BC_LEX_OP_REL_NE,
BC_LEX_OP_REL_LT,
BC_LEX_OP_REL_GT,
BC_LEX_OP_BOOL_OR,
BC_LEX_OP_BOOL_AND,
#if BC_ENABLED
BC_LEX_OP_ASSIGN_POWER,
BC_LEX_OP_ASSIGN_MULTIPLY,
BC_LEX_OP_ASSIGN_DIVIDE,
BC_LEX_OP_ASSIGN_MODULUS,
BC_LEX_OP_ASSIGN_PLUS,
BC_LEX_OP_ASSIGN_MINUS,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_OP_ASSIGN_PLACES,
BC_LEX_OP_ASSIGN_LSHIFT,
BC_LEX_OP_ASSIGN_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
#endif // BC_ENABLED
BC_LEX_OP_ASSIGN,
BC_LEX_NLINE,
BC_LEX_WHITESPACE,
BC_LEX_LPAREN,
BC_LEX_RPAREN,
BC_LEX_LBRACKET,
BC_LEX_COMMA,
BC_LEX_RBRACKET,
BC_LEX_LBRACE,
BC_LEX_SCOLON,
BC_LEX_RBRACE,
BC_LEX_STR,
BC_LEX_NAME,
BC_LEX_NUMBER,
#if BC_ENABLED
BC_LEX_KW_AUTO,
BC_LEX_KW_BREAK,
BC_LEX_KW_CONTINUE,
BC_LEX_KW_DEFINE,
BC_LEX_KW_FOR,
BC_LEX_KW_IF,
BC_LEX_KW_LIMITS,
BC_LEX_KW_RETURN,
BC_LEX_KW_WHILE,
BC_LEX_KW_HALT,
BC_LEX_KW_LAST,
#endif // BC_ENABLED
BC_LEX_KW_IBASE,
BC_LEX_KW_OBASE,
BC_LEX_KW_SCALE,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_SEED,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_LENGTH,
BC_LEX_KW_PRINT,
BC_LEX_KW_SQRT,
BC_LEX_KW_ABS,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_IRAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_QUIT,
BC_LEX_KW_READ,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_RAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_MAXIBASE,
BC_LEX_KW_MAXOBASE,
BC_LEX_KW_MAXSCALE,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_MAXRAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ELSE,
#if DC_ENABLED
BC_LEX_EQ_NO_REG,
BC_LEX_OP_MODEXP,
BC_LEX_OP_DIVMOD,
BC_LEX_COLON,
BC_LEX_EXECUTE,
BC_LEX_PRINT_STACK,
BC_LEX_CLEAR_STACK,
BC_LEX_STACK_LEVEL,
BC_LEX_DUPLICATE,
BC_LEX_SWAP,
BC_LEX_POP,
BC_LEX_ASCIIFY,
BC_LEX_PRINT_STREAM,
BC_LEX_STORE_IBASE,
BC_LEX_STORE_OBASE,
BC_LEX_STORE_SCALE,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_STORE_SEED,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_LOAD,
BC_LEX_LOAD_POP,
BC_LEX_STORE_PUSH,
BC_LEX_PRINT_POP,
BC_LEX_NQUIT,
BC_LEX_SCALE_FACTOR,
#endif // DC_ENABLED
} BcLexType;
struct BcLex;
typedef void (*BcLexNext)(struct BcLex*);
typedef struct BcLex {
const char *buf;
size_t i;
size_t line;
size_t len;
BcLexType t;
BcLexType last;
BcVec str;
} BcLex;
void bc_lex_init(BcLex *l);
void bc_lex_free(BcLex *l);
void bc_lex_file(BcLex *l, const char *file);
void bc_lex_text(BcLex *l, const char *text);
void bc_lex_next(BcLex *l);
void bc_lex_lineComment(BcLex *l);
void bc_lex_comment(BcLex *l);
void bc_lex_whitespace(BcLex *l);
void bc_lex_number(BcLex *l, char start);
void bc_lex_name(BcLex *l);
void bc_lex_commonTokens(BcLex *l, char c);
void bc_lex_invalidChar(BcLex *l, char c);
#endif // BC_LEX_H

235
contrib/bc/include/num.h Normal file
View File

@ -0,0 +1,235 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for the num type.
*
*/
#ifndef BC_NUM_H
#define BC_NUM_H
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include <status.h>
#include <vector.h>
#ifndef BC_ENABLE_EXTRA_MATH
#define BC_ENABLE_EXTRA_MATH (1)
#endif // BC_ENABLE_EXTRA_MATH
#define BC_BASE (10)
typedef unsigned long ulong;
// For some reason, LONG_BIT is not defined in some versions of gcc.
// I define it here to the minimum accepted value in the POSIX standard.
#ifndef LONG_BIT
#define LONG_BIT (32)
#endif // LONG_BIT
#ifndef BC_LONG_BIT
#define BC_LONG_BIT LONG_BIT
#endif // BC_LONG_BIT
#if BC_LONG_BIT > LONG_BIT
#error BC_LONG_BIT cannot be greater than LONG_BIT
#endif // BC_LONG_BIT > LONG_BIT
#if BC_LONG_BIT >= 64
typedef int_least32_t BcDig;
typedef uint64_t BcBigDig;
#define BC_NUM_BIGDIG_MAX ((BcBigDig) UINT64_MAX)
#define BC_BASE_DIGS (9)
#define BC_BASE_POW (1000000000)
#define BC_NUM_BIGDIG_C UINT64_C
#elif BC_LONG_BIT >= 32
typedef int_least16_t BcDig;
typedef uint32_t BcBigDig;
#define BC_NUM_BIGDIG_MAX ((BcBigDig) UINT32_MAX)
#define BC_BASE_DIGS (4)
#define BC_BASE_POW (10000)
#define BC_NUM_BIGDIG_C UINT32_C
#else
#error BC_LONG_BIT must be at least 32
#endif // BC_LONG_BIT >= 64
#define BC_NUM_DEF_SIZE (8)
typedef struct BcNum {
BcDig *restrict num;
size_t rdx;
size_t scale;
size_t len;
size_t cap;
bool neg;
} BcNum;
#if BC_ENABLE_EXTRA_MATH
// Forward declaration
struct BcRNG;
#endif // BC_ENABLE_EXTRA_MATH
#define BC_NUM_MIN_BASE (BC_NUM_BIGDIG_C(2))
#define BC_NUM_MAX_POSIX_IBASE (BC_NUM_BIGDIG_C(16))
#define BC_NUM_MAX_IBASE (BC_NUM_BIGDIG_C(36))
// This is the max base allowed by bc_num_parseChar().
#define BC_NUM_MAX_LBASE (BC_NUM_BIGDIG_C('Z' + BC_BASE + 1))
#define BC_NUM_PRINT_WIDTH (BC_NUM_BIGDIG_C(69))
#ifndef BC_NUM_KARATSUBA_LEN
#define BC_NUM_KARATSUBA_LEN (BC_NUM_BIGDIG_C(32))
#elif BC_NUM_KARATSUBA_LEN < 16
#error BC_NUM_KARATSUBA_LEN must be at least 16.
#endif // BC_NUM_KARATSUBA_LEN
// A crude, but always big enough, calculation of
// the size required for ibase and obase BcNum's.
#define BC_NUM_BIGDIG_LOG10 (BC_NUM_DEF_SIZE)
#define BC_NUM_NONZERO(n) ((n)->len)
#define BC_NUM_ZERO(n) (!BC_NUM_NONZERO(n))
#define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1)
#define BC_NUM_NUM_LETTER(c) ((c) - 'A' + BC_BASE)
#define BC_NUM_KARATSUBA_ALLOCS (6)
#define BC_NUM_ROUND_POW(s) (bc_vm_growSize((s), BC_BASE_DIGS - 1))
#define BC_NUM_RDX(s) (BC_NUM_ROUND_POW(s) / BC_BASE_DIGS)
#define BC_NUM_SIZE(n) ((n) * sizeof(BcDig))
#if BC_DEBUG_CODE
#define BC_NUM_PRINT(x) fprintf(stderr, "%s = %lu\n", #x, (unsigned long)(x))
#define DUMP_NUM bc_num_dump
#else // BC_DEBUG_CODE
#undef DUMP_NUM
#define DUMP_NUM(x,y)
#define BC_NUM_PRINT(x)
#endif // BC_DEBUG_CODE
typedef void (*BcNumBinaryOp)(BcNum*, BcNum*, BcNum*, size_t);
typedef size_t (*BcNumBinaryOpReq)(const BcNum*, const BcNum*, size_t);
typedef void (*BcNumDigitOp)(size_t, size_t, bool);
typedef void (*BcNumShiftAddOp)(BcDig*, const BcDig*, size_t);
void bc_num_init(BcNum *restrict n, size_t req);
void bc_num_setup(BcNum *restrict n, BcDig *restrict num, size_t cap);
void bc_num_copy(BcNum *d, const BcNum *s);
void bc_num_createCopy(BcNum *d, const BcNum *s);
void bc_num_createFromBigdig(BcNum *n, BcBigDig val);
void bc_num_clear(BcNum *restrict n);
void bc_num_free(void *num);
size_t bc_num_scale(const BcNum *restrict n);
size_t bc_num_len(const BcNum *restrict n);
void bc_num_bigdig(const BcNum *restrict n, BcBigDig *result);
void bc_num_bigdig2(const BcNum *restrict n, BcBigDig *result);
void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val);
#if BC_ENABLE_EXTRA_MATH
void bc_num_irand(const BcNum *restrict a, BcNum *restrict b,
struct BcRNG *restrict rng);
void bc_num_rng(const BcNum *restrict n, struct BcRNG *rng);
void bc_num_createFromRNG(BcNum *restrict n, struct BcRNG *rng);
#endif // BC_ENABLE_EXTRA_MATH
void bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale);
void bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale);
void bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale);
void bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale);
void bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale);
void bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale);
#if BC_ENABLE_EXTRA_MATH
void bc_num_places(BcNum *a, BcNum *b, BcNum *c, size_t scale);
void bc_num_lshift(BcNum *a, BcNum *b, BcNum *c, size_t scale);
void bc_num_rshift(BcNum *a, BcNum *b, BcNum *c, size_t scale);
#endif // BC_ENABLE_EXTRA_MATH
void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale);
void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale);
size_t bc_num_addReq(const BcNum* a, const BcNum* b, size_t scale);
size_t bc_num_mulReq(const BcNum *a, const BcNum *b, size_t scale);
size_t bc_num_powReq(const BcNum *a, const BcNum *b, size_t scale);
#if BC_ENABLE_EXTRA_MATH
size_t bc_num_placesReq(const BcNum *a, const BcNum *b, size_t scale);
#endif // BC_ENABLE_EXTRA_MATH
void bc_num_truncate(BcNum *restrict n, size_t places);
ssize_t bc_num_cmp(const BcNum *a, const BcNum *b);
#if DC_ENABLED
void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d);
#endif // DC_ENABLED
void bc_num_one(BcNum *restrict n);
ssize_t bc_num_cmpZero(const BcNum *n);
void bc_num_parse(BcNum *restrict n, const char *restrict val,
BcBigDig base, bool letter);
void bc_num_print(BcNum *restrict n, BcBigDig base, bool newline);
#if DC_ENABLED
void bc_num_stream(BcNum *restrict n, BcBigDig base);
#endif // DC_ENABLED
#if BC_DEBUG_CODE
void bc_num_printDebug(const BcNum *n, const char *name, bool emptyline);
void bc_num_printDigs(const BcDig* n, size_t len, bool emptyline);
void bc_num_printWithDigs(const BcNum *n, const char *name, bool emptyline);
void bc_num_dump(const char *varname, const BcNum *n);
#endif // BC_DEBUG_CODE
extern const char bc_num_hex_digits[];
extern const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1];
extern const BcDig bc_num_bigdigMax[];
extern const size_t bc_num_bigdigMax_size;
#endif // BC_NUM_H

79
contrib/bc/include/opt.h Normal file
View File

@ -0,0 +1,79 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Adapted from https://github.com/skeeto/optparse
*
* *****************************************************************************
*
* Definitions for getopt_long() replacement.
*
*/
#ifndef BC_OPT_H
#define BC_OPT_H
#include <stdbool.h>
typedef struct BcOpt {
char **argv;
size_t optind;
int optopt;
int subopt;
char *optarg;
} BcOpt;
typedef enum BcOptType {
BC_OPT_NONE,
BC_OPT_REQUIRED,
BC_OPT_BC_ONLY,
BC_OPT_DC_ONLY,
} BcOptType;
typedef struct BcOptLong {
const char *name;
BcOptType type;
int val;
} BcOptLong;
void bc_opt_init(BcOpt *o, char **argv);
int bc_opt_parse(BcOpt *o, const BcOptLong *longopts);
#define BC_OPT_ISDASHDASH(a) \
((a) != NULL && (a)[0] == '-' && (a)[1] == '-' && (a)[2] == '\0')
#define BC_OPT_ISSHORTOPT(a) \
((a) != NULL && (a)[0] == '-' && (a)[1] != '-' && (a)[1] != '\0')
#define BC_OPT_ISLONGOPT(a) \
((a) != NULL && (a)[0] == '-' && (a)[1] == '-' && (a)[2] != '\0')
#endif // BC_OPT_H

115
contrib/bc/include/parse.h Normal file
View File

@ -0,0 +1,115 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for bc's parser.
*
*/
#ifndef BC_PARSE_H
#define BC_PARSE_H
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <status.h>
#include <vector.h>
#include <lex.h>
#include <lang.h>
#define BC_PARSE_REL (UINTMAX_C(1)<<0)
#define BC_PARSE_PRINT (UINTMAX_C(1)<<1)
#define BC_PARSE_NOCALL (UINTMAX_C(1)<<2)
#define BC_PARSE_NOREAD (UINTMAX_C(1)<<3)
#define BC_PARSE_ARRAY (UINTMAX_C(1)<<4)
#define BC_PARSE_NEEDVAL (UINTMAX_C(1)<<5)
#if BC_ENABLED
#define BC_PARSE_CAN_PARSE(p) \
((p).l.t != BC_LEX_EOF && (p).l.t != BC_LEX_KW_DEFINE)
#else // BC_ENABLED
#define BC_PARSE_CAN_PARSE(p) ((p).l.t != BC_LEX_EOF)
#endif // BC_ENABLED
#define bc_parse_push(p, i) (bc_vec_pushByte(&(p)->func->code, (uchar) (i)))
#define bc_parse_pushIndex(p, idx) (bc_vec_pushIndex(&(p)->func->code, (idx)))
#define bc_parse_err(p, e) (bc_vm_error((e), (p)->l.line))
#define bc_parse_verr(p, e, ...) (bc_vm_error((e), (p)->l.line, __VA_ARGS__))
typedef struct BcParseNext {
uchar len;
uchar tokens[4];
} BcParseNext;
#define BC_PARSE_NEXT_TOKENS(...) .tokens = { __VA_ARGS__ }
#define BC_PARSE_NEXT(a, ...) \
{ .len = (uchar) (a), BC_PARSE_NEXT_TOKENS(__VA_ARGS__) }
struct BcParse;
struct BcProgram;
typedef void (*BcParseParse)(struct BcParse*);
typedef void (*BcParseExpr)(struct BcParse*, uint8_t);
typedef struct BcParse {
BcLex l;
#if BC_ENABLED
BcVec flags;
BcVec exits;
BcVec conds;
BcVec ops;
BcVec buf;
#endif // BC_ENABLED
struct BcProgram *prog;
BcFunc *func;
size_t fidx;
bool auto_part;
} BcParse;
void bc_parse_init(BcParse *p, struct BcProgram *prog, size_t func);
void bc_parse_free(BcParse *p);
void bc_parse_reset(BcParse *p);
void bc_parse_addString(BcParse *p);
void bc_parse_number(BcParse *p);
void bc_parse_updateFunc(BcParse *p, size_t fidx);
void bc_parse_pushName(const BcParse* p, char *name, bool var);
void bc_parse_text(BcParse *p, const char *text);
extern const char bc_parse_one[];
#endif // BC_PARSE_H

View File

@ -0,0 +1,183 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for bc programs.
*
*/
#ifndef BC_PROGRAM_H
#define BC_PROGRAM_H
#include <stddef.h>
#include <status.h>
#include <parse.h>
#include <lang.h>
#include <num.h>
#include <rand.h>
#define BC_PROG_GLOBALS_IBASE (0)
#define BC_PROG_GLOBALS_OBASE (1)
#define BC_PROG_GLOBALS_SCALE (2)
#if BC_ENABLE_EXTRA_MATH
#define BC_PROG_MAX_RAND (3)
#endif // BC_ENABLE_EXTRA_MATH
#define BC_PROG_GLOBALS_LEN (3 + BC_ENABLE_EXTRA_MATH)
#define BC_PROG_ONE_CAP (1)
typedef struct BcProgram {
BcBigDig globals[BC_PROG_GLOBALS_LEN];
BcVec globals_v[BC_PROG_GLOBALS_LEN];
#if BC_ENABLE_EXTRA_MATH
BcRNG rng;
#endif // BC_ENABLE_EXTRA_MATH
BcVec results;
BcVec stack;
BcVec *consts;
BcVec *strs;
BcVec fns;
BcVec fn_map;
BcVec vars;
BcVec var_map;
BcVec arrs;
BcVec arr_map;
#if DC_ENABLED
BcVec tail_calls;
BcBigDig strm;
BcNum strmb;
#endif // DC_ENABLED
BcNum one;
#if BC_ENABLED
BcNum last;
#endif // BC_ENABLED
#if DC_ENABLED
// This uses BC_NUM_LONG_LOG10 because it is used in bc_num_ulong2num(),
// which attempts to realloc, unless it is big enough. This is big enough.
BcDig strmb_num[BC_NUM_BIGDIG_LOG10];
#endif // DC_ENABLED
BcDig one_num[BC_PROG_ONE_CAP];
} BcProgram;
#define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) (n)))
#define BC_PROG_GLOBAL_PTR(v) (bc_vec_top(v))
#define BC_PROG_GLOBAL(v) (*((BcBigDig*) BC_PROG_GLOBAL_PTR(v)))
#define BC_PROG_IBASE(p) ((p)->globals[BC_PROG_GLOBALS_IBASE])
#define BC_PROG_OBASE(p) ((p)->globals[BC_PROG_GLOBALS_OBASE])
#define BC_PROG_SCALE(p) ((p)->globals[BC_PROG_GLOBALS_SCALE])
#define BC_PROG_MAIN (0)
#define BC_PROG_READ (1)
#define bc_program_retire(p, nres, nops) \
(bc_vec_npopAt(&(p)->results, (nops), (p)->results.len - (nres + nops)))
#if DC_ENABLED
#define BC_PROG_REQ_FUNCS (2)
#if !BC_ENABLED
// For dc only, last is always true.
#define bc_program_copyToVar(p, name, t, last) \
bc_program_copyToVar(p, name, t)
#endif // !BC_ENABLED
#else // DC_ENABLED
// For bc, 'pop' and 'copy' are always false.
#define bc_program_pushVar(p, code, bgn, pop, copy) \
bc_program_pushVar(p, code, bgn)
#ifdef NDEBUG
#define BC_PROG_NO_STACK_CHECK
#endif // NDEBUG
#endif // DC_ENABLED
#define BC_PROG_STR(n) ((n)->num == NULL && !(n)->cap)
#if BC_ENABLED
#define BC_PROG_NUM(r, n) \
((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
#else // BC_ENABLED
#define BC_PROG_NUM(r, n) ((r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
// For dc, inst is always BC_INST_ARRAY_ELEM.
#define bc_program_pushArray(p, code, bgn, inst) \
bc_program_pushArray(p, code, bgn)
#endif // BC_ENABLED
typedef void (*BcProgramUnary)(BcResult*, BcNum*);
void bc_program_init(BcProgram *p);
void bc_program_free(BcProgram *p);
#if BC_DEBUG_CODE
#if BC_ENABLED && DC_ENABLED
void bc_program_code(const BcProgram *p);
void bc_program_printInst(const BcProgram *p, const char *code,
size_t *restrict bgn);
void bc_program_printStackDebug(BcProgram* p);
#endif // BC_ENABLED && DC_ENABLED
#endif // BC_DEBUG_CODE
size_t bc_program_search(BcProgram *p, const char* id, bool var);
size_t bc_program_insertFunc(BcProgram *p, const char *name);
void bc_program_reset(BcProgram *p);
void bc_program_exec(BcProgram *p);
void bc_program_negate(BcResult *r, BcNum *n);
void bc_program_not(BcResult *r, BcNum *n);
#if BC_ENABLE_EXTRA_MATH
void bc_program_trunc(BcResult *r, BcNum *n);
#endif // BC_ENABLE_EXTRA_MATH
extern const BcNumBinaryOp bc_program_ops[];
extern const BcNumBinaryOpReq bc_program_opReqs[];
extern const BcProgramUnary bc_program_unarys[];
extern const char bc_program_exprs_name[];
extern const char bc_program_stdin_name[];
extern const char bc_program_ready_msg[];
extern const size_t bc_program_ready_msg_len;
extern const char bc_program_esc_chars[];
extern const char bc_program_esc_seqs[];
#endif // BC_PROGRAM_H

229
contrib/bc/include/rand.h Normal file
View File

@ -0,0 +1,229 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2019 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Parts of this code are adapted from the following:
*
* PCG, A Family of Better Random Number Generators.
*
* You can find the original source code at:
* https://github.com/imneme/pcg-c
*
* -----------------------------------------------------------------------------
*
* Parts of this code are also under the following license:
*
* Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* *****************************************************************************
*
* Definitions for the RNG.
*
*/
#ifndef BC_RAND_H
#define BC_RAND_H
#if BC_ENABLE_EXTRA_MATH
#include <stdint.h>
#include <inttypes.h>
#include <vector.h>
#include <num.h>
typedef ulong (*BcRandUlong)(void*);
#if BC_LONG_BIT >= 64
#ifdef BC_RAND_BUILTIN
#if BC_RAND_BUILTIN
#ifndef __SIZEOF_INT128__
#undef BC_RAND_BUILTIN
#define BC_RAND_BUILTIN (0)
#endif // __SIZEOF_INT128__
#endif // BC_RAND_BUILTIN
#endif // BC_RAND_BUILTIN
#ifndef BC_RAND_BUILTIN
#ifdef __SIZEOF_INT128__
#define BC_RAND_BUILTIN (1)
#else // __SIZEOF_INT128__
#define BC_RAND_BUILTIN (0)
#endif // __SIZEOF_INT128__
#endif // BC_RAND_BUILTIN
typedef uint64_t BcRand;
#define BC_RAND_ROTC (63)
#if BC_RAND_BUILTIN
typedef __uint128_t BcRandState;
#define bc_rand_mul(a, b) (((BcRandState) (a)) * ((BcRandState) (b)))
#define bc_rand_add(a, b) (((BcRandState) (a)) + ((BcRandState) (b)))
#define bc_rand_mul2(a, b) (((BcRandState) (a)) * ((BcRandState) (b)))
#define bc_rand_add2(a, b) (((BcRandState) (a)) + ((BcRandState) (b)))
#define BC_RAND_NOTMODIFIED(r) (((r)->inc & 1UL) == 0)
#define BC_RAND_ZERO(r) (!(r)->state)
#define BC_RAND_CONSTANT(h, l) ((((BcRandState) (h)) << 64) + (BcRandState) (l))
#define BC_RAND_TRUNC(s) ((uint64_t) (s))
#define BC_RAND_CHOP(s) ((uint64_t) ((s) >> 64UL))
#define BC_RAND_ROTAMT(s) ((unsigned int) ((s) >> 122UL))
#else // BC_RAND_BUILTIN
typedef struct BcRandState {
uint_fast64_t lo;
uint_fast64_t hi;
} BcRandState;
#define bc_rand_mul(a, b) (bc_rand_multiply((a), (b)))
#define bc_rand_add(a, b) (bc_rand_addition((a), (b)))
#define bc_rand_mul2(a, b) (bc_rand_multiply2((a), (b)))
#define bc_rand_add2(a, b) (bc_rand_addition2((a), (b)))
#define BC_RAND_NOTMODIFIED(r) (((r)->inc.lo & 1) == 0)
#define BC_RAND_ZERO(r) (!(r)->state.lo && !(r)->state.hi)
#define BC_RAND_CONSTANT(h, l) { .lo = (l), .hi = (h) }
#define BC_RAND_TRUNC(s) ((s).lo)
#define BC_RAND_CHOP(s) ((s).hi)
#define BC_RAND_ROTAMT(s) ((unsigned int) ((s).hi >> 58UL))
#define BC_RAND_BOTTOM32 (((uint_fast64_t) 0xffffffffULL))
#define BC_RAND_TRUNC32(n) ((n) & BC_RAND_BOTTOM32)
#define BC_RAND_CHOP32(n) ((n) >> 32)
#endif // BC_RAND_BUILTIN
#define BC_RAND_MULTIPLIER \
BC_RAND_CONSTANT(2549297995355413924ULL, 4865540595714422341ULL)
#define BC_RAND_FOLD(s) ((BcRand) (BC_RAND_CHOP(s) ^ BC_RAND_TRUNC(s)))
#else // BC_LONG_BIT >= 64
#undef BC_RAND_BUILTIN
#define BC_RAND_BUILTIN (1)
typedef uint32_t BcRand;
#define BC_RAND_ROTC (31)
typedef uint_fast64_t BcRandState;
#define bc_rand_mul(a, b) (((BcRandState) (a)) * ((BcRandState) (b)))
#define bc_rand_add(a, b) (((BcRandState) (a)) + ((BcRandState) (b)))
#define bc_rand_mul2(a, b) (((BcRandState) (a)) * ((BcRandState) (b)))
#define bc_rand_add2(a, b) (((BcRandState) (a)) + ((BcRandState) (b)))
#define BC_RAND_NOTMODIFIED(r) (((r)->inc & 1UL) == 0)
#define BC_RAND_ZERO(r) (!(r)->state)
#define BC_RAND_CONSTANT UINT64_C
#define BC_RAND_MULTIPLIER BC_RAND_CONSTANT(6364136223846793005)
#define BC_RAND_TRUNC(s) ((uint32_t) (s))
#define BC_RAND_CHOP(s) ((uint32_t) ((s) >> 32UL))
#define BC_RAND_ROTAMT(s) ((unsigned int) ((s) >> 59UL))
#define BC_RAND_FOLD(s) ((BcRand) ((((s) >> 18U) ^ (s)) >> 27U))
#endif // BC_LONG_BIT >= 64
#define BC_RAND_ROT(v, r) \
((BcRand) (((v) >> (r)) | ((v) << ((0 - (r)) & BC_RAND_ROTC))))
#define BC_RAND_BITS (sizeof(BcRand) * CHAR_BIT)
#define BC_RAND_STATE_BITS (sizeof(BcRandState) * CHAR_BIT)
#define BC_RAND_NUM_SIZE (BC_NUM_BIGDIG_LOG10 * 2 + 2)
#define BC_RAND_SRAND_BITS ((1 << CHAR_BIT) - 1)
typedef struct BcRNGData {
BcRandState state;
BcRandState inc;
} BcRNGData;
typedef struct BcRNG {
BcVec v;
} BcRNG;
void bc_rand_init(BcRNG *r);
#ifndef NDEBUG
void bc_rand_free(BcRNG *r);
#endif // NDEBUG
BcRand bc_rand_int(BcRNG *r);
BcRand bc_rand_bounded(BcRNG *r, BcRand bound);
void bc_rand_seed(BcRNG *r, ulong state1, ulong state2, ulong inc1, ulong inc2);
void bc_rand_push(BcRNG *r);
void bc_rand_pop(BcRNG *r, bool reset);
void bc_rand_getRands(BcRNG *r, BcRand *s1, BcRand *s2, BcRand *i1, BcRand *i2);
extern const BcRandState bc_rand_multiplier;
#endif // BC_ENABLE_EXTRA_MATH
#endif // BC_RAND_H

59
contrib/bc/include/read.h Normal file
View File

@ -0,0 +1,59 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Code to handle special I/O for bc.
*
*/
#ifndef BC_IO_H
#define BC_IO_H
#include <stdlib.h>
#include <status.h>
#include <vector.h>
#ifndef BC_ENABLE_PROMPT
#define BC_ENABLE_PROMPT (1)
#endif // BC_ENABLE_PROMPT
#if !BC_ENABLE_PROMPT
#define bc_read_line(vec, prompt) bc_read_line(vec)
#define bc_read_chars(vec, prompt) bc_read_chars(vec)
#endif // BC_ENABLE_PROMPT
#define BC_READ_BIN_CHAR(c) (((c) < ' ' && !isspace((c))) || ((uchar) c) > '~')
BcStatus bc_read_line(BcVec *vec, const char *prompt);
void bc_read_file(const char *path, char **buf);
BcStatus bc_read_chars(BcVec *vec, const char *prompt);
#endif // BC_IO_H

186
contrib/bc/include/status.h Normal file
View File

@ -0,0 +1,186 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* All bc status codes.
*
*/
#ifndef BC_STATUS_H
#define BC_STATUS_H
#include <stdint.h>
#ifndef BC_ENABLED
#define BC_ENABLED (1)
#endif // BC_ENABLED
#ifndef DC_ENABLED
#define DC_ENABLED (1)
#endif // DC_ENABLED
typedef enum BcStatus {
BC_STATUS_SUCCESS = 0,
BC_STATUS_ERROR_MATH,
BC_STATUS_ERROR_PARSE,
BC_STATUS_ERROR_EXEC,
BC_STATUS_ERROR_FATAL,
BC_STATUS_EOF,
BC_STATUS_QUIT,
} BcStatus;
typedef enum BcError {
BC_ERROR_MATH_NEGATIVE,
BC_ERROR_MATH_NON_INTEGER,
BC_ERROR_MATH_OVERFLOW,
BC_ERROR_MATH_DIVIDE_BY_ZERO,
BC_ERROR_FATAL_ALLOC_ERR,
BC_ERROR_FATAL_IO_ERR,
BC_ERROR_FATAL_FILE_ERR,
BC_ERROR_FATAL_BIN_FILE,
BC_ERROR_FATAL_PATH_DIR,
BC_ERROR_FATAL_OPTION,
BC_ERROR_FATAL_OPTION_NO_ARG,
BC_ERROR_FATAL_OPTION_ARG,
BC_ERROR_EXEC_IBASE,
BC_ERROR_EXEC_OBASE,
BC_ERROR_EXEC_SCALE,
BC_ERROR_EXEC_READ_EXPR,
BC_ERROR_EXEC_REC_READ,
BC_ERROR_EXEC_TYPE,
BC_ERROR_EXEC_STACK,
BC_ERROR_EXEC_PARAMS,
BC_ERROR_EXEC_UNDEF_FUNC,
BC_ERROR_EXEC_VOID_VAL,
BC_ERROR_PARSE_EOF,
BC_ERROR_PARSE_CHAR,
BC_ERROR_PARSE_STRING,
BC_ERROR_PARSE_COMMENT,
BC_ERROR_PARSE_TOKEN,
#if BC_ENABLED
BC_ERROR_PARSE_EXPR,
BC_ERROR_PARSE_EMPTY_EXPR,
BC_ERROR_PARSE_PRINT,
BC_ERROR_PARSE_FUNC,
BC_ERROR_PARSE_ASSIGN,
BC_ERROR_PARSE_NO_AUTO,
BC_ERROR_PARSE_DUP_LOCAL,
BC_ERROR_PARSE_BLOCK,
BC_ERROR_PARSE_RET_VOID,
BC_ERROR_PARSE_REF_VAR,
BC_ERROR_POSIX_NAME_LEN,
BC_ERROR_POSIX_COMMENT,
BC_ERROR_POSIX_KW,
BC_ERROR_POSIX_DOT,
BC_ERROR_POSIX_RET,
BC_ERROR_POSIX_BOOL,
BC_ERROR_POSIX_REL_POS,
BC_ERROR_POSIX_MULTIREL,
BC_ERROR_POSIX_FOR,
BC_ERROR_POSIX_EXP_NUM,
BC_ERROR_POSIX_REF,
BC_ERROR_POSIX_VOID,
BC_ERROR_POSIX_BRACE,
#endif // BC_ENABLED
BC_ERROR_NELEMS,
#if BC_ENABLED
BC_ERROR_POSIX_START = BC_ERROR_POSIX_NAME_LEN,
BC_ERROR_POSIX_END = BC_ERROR_POSIX_BRACE,
#endif // BC_ENABLED
} BcError;
#define BC_ERR_IDX_MATH (0)
#define BC_ERR_IDX_PARSE (1)
#define BC_ERR_IDX_EXEC (2)
#define BC_ERR_IDX_FATAL (3)
#define BC_ERR_IDX_NELEMS (4)
#if BC_ENABLED
#define BC_ERR_IDX_WARN (BC_ERR_IDX_NELEMS)
#endif // BC_ENABLED
#define BC_UNUSED(e) ((void) (e))
#ifndef BC_LIKELY
#define BC_LIKELY(e) (e)
#endif // BC_LIKELY
#ifndef BC_UNLIKELY
#define BC_UNLIKELY(e) (e)
#endif // BC_UNLIKELY
#define BC_ERR(e) BC_UNLIKELY(e)
#define BC_NO_ERR(s) BC_LIKELY(s)
#ifndef BC_DEBUG_CODE
#define BC_DEBUG_CODE (0)
#endif // BC_DEBUG_CODE
#if __STDC_VERSION__ >= 201100L
#include <stdnoreturn.h>
#define BC_NORETURN _Noreturn
#else // __STDC_VERSION__
#define BC_NORETURN
#define BC_MUST_RETURN
#endif // __STDC_VERSION__
// Workarounds for AIX's POSIX incompatibility.
#ifndef SIZE_MAX
#define SIZE_MAX __SIZE_MAX__
#endif // SIZE_MAX
#ifndef UINTMAX_C
#define UINTMAX_C __UINTMAX_C
#endif // UINTMAX_C
#ifndef UINT32_C
#define UINT32_C __UINT32_C
#endif // UINT32_C
#ifndef UINT_FAST32_MAX
#define UINT_FAST32_MAX __UINT_FAST32_MAX__
#endif // UINT_FAST32_MAX
#ifndef UINT16_MAX
#define UINT16_MAX __UINT16_MAX__
#endif // UINT16_MAX
#ifndef SIG_ATOMIC_MAX
#define SIG_ATOMIC_MAX __SIG_ATOMIC_MAX__
#endif // SIG_ATOMIC_MAX
#endif // BC_STATUS_H

101
contrib/bc/include/vector.h Normal file
View File

@ -0,0 +1,101 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for bc vectors (resizable arrays).
*
*/
#ifndef BC_VECTOR_H
#define BC_VECTOR_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <status.h>
#define BC_VEC_INVALID_IDX (SIZE_MAX)
#define BC_VEC_START_CAP (UINTMAX_C(1)<<5)
typedef unsigned char uchar;
typedef void (*BcVecFree)(void*);
// Forward declaration.
struct BcId;
typedef struct BcVec {
char *v;
size_t len;
size_t cap;
size_t size;
BcVecFree dtor;
} BcVec;
void bc_vec_init(BcVec *restrict v, size_t esize, BcVecFree dtor);
void bc_vec_expand(BcVec *restrict v, size_t req);
void bc_vec_npop(BcVec *restrict v, size_t n);
void bc_vec_npopAt(BcVec *restrict v, size_t n, size_t idx);
void bc_vec_push(BcVec *restrict v, const void *data);
void bc_vec_npush(BcVec *restrict v, size_t n, const void *data);
void bc_vec_pushByte(BcVec *restrict v, uchar data);
void bc_vec_pushIndex(BcVec *restrict v, size_t idx);
void bc_vec_string(BcVec *restrict v, size_t len, const char *restrict str);
void bc_vec_concat(BcVec *restrict v, const char *restrict str);
void bc_vec_empty(BcVec *restrict v);
#if BC_ENABLE_HISTORY
void bc_vec_replaceAt(BcVec *restrict v, size_t idx, const void *data);
#endif // BC_ENABLE_HISTORY
void* bc_vec_item(const BcVec *restrict v, size_t idx);
void* bc_vec_item_rev(const BcVec *restrict v, size_t idx);
void bc_vec_clear(BcVec *restrict v);
void bc_vec_free(void *vec);
bool bc_map_insert(BcVec *restrict v, const char *name,
size_t idx, size_t *restrict i);
size_t bc_map_index(const BcVec *restrict v, const char *name);
#define bc_vec_pop(v) (bc_vec_npop((v), 1))
#define bc_vec_top(v) (bc_vec_item_rev((v), 0))
#ifndef NDEBUG
#define bc_map_init(v) (bc_vec_init((v), sizeof(BcId), bc_id_free))
#else // NDEBUG
#define bc_map_init(v) (bc_vec_init((v), sizeof(BcId), NULL))
#endif // NDEBUG
#endif // BC_VECTOR_H

357
contrib/bc/include/vm.h Normal file
View File

@ -0,0 +1,357 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Definitions for bc's VM.
*
*/
#ifndef BC_VM_H
#define BC_VM_H
#include <stddef.h>
#include <limits.h>
#include <signal.h>
#if BC_ENABLE_NLS
# ifdef _WIN32
# error NLS is not supported on Windows.
# endif // _WIN32
#include <nl_types.h>
#endif // BC_ENABLE_NLS
#include <status.h>
#include <num.h>
#include <parse.h>
#include <program.h>
#include <history.h>
#include <file.h>
#if !BC_ENABLED && !DC_ENABLED
#error Must define BC_ENABLED, DC_ENABLED, or both
#endif
// CHAR_BIT must be at least 6.
#if CHAR_BIT < 6
#error CHAR_BIT must be at least 6.
#endif
#ifndef BC_ENABLE_NLS
#define BC_ENABLE_NLS (0)
#endif // BC_ENABLE_NLS
#ifndef MAINEXEC
#define MAINEXEC bc
#endif
#ifndef EXECPREFIX
#define EXECPREFIX
#endif
#define GEN_STR(V) #V
#define GEN_STR2(V) GEN_STR(V)
#define BC_VERSION GEN_STR2(VERSION)
#define BC_EXECPREFIX GEN_STR2(EXECPREFIX)
#define BC_MAINEXEC GEN_STR2(MAINEXEC)
// Windows has deprecated isatty().
#ifdef _WIN32
#define isatty _isatty
#endif // _WIN32
#define DC_FLAG_X (UINTMAX_C(1)<<0)
#define BC_FLAG_W (UINTMAX_C(1)<<1)
#define BC_FLAG_S (UINTMAX_C(1)<<2)
#define BC_FLAG_Q (UINTMAX_C(1)<<3)
#define BC_FLAG_L (UINTMAX_C(1)<<4)
#define BC_FLAG_I (UINTMAX_C(1)<<5)
#define BC_FLAG_G (UINTMAX_C(1)<<6)
#define BC_FLAG_P (UINTMAX_C(1)<<7)
#define BC_FLAG_TTYIN (UINTMAX_C(1)<<8)
#define BC_FLAG_TTY (UINTMAX_C(1)<<9)
#define BC_TTYIN (vm.flags & BC_FLAG_TTYIN)
#define BC_TTY (vm.flags & BC_FLAG_TTY)
#define BC_S (BC_ENABLED && (vm.flags & BC_FLAG_S))
#define BC_W (BC_ENABLED && (vm.flags & BC_FLAG_W))
#define BC_L (BC_ENABLED && (vm.flags & BC_FLAG_L))
#define BC_I (vm.flags & BC_FLAG_I)
#define BC_G (BC_ENABLED && (vm.flags & BC_FLAG_G))
#define DC_X (DC_ENABLED && (vm.flags & DC_FLAG_X))
#define BC_P (vm.flags & BC_FLAG_P)
#define BC_USE_PROMPT (!BC_P && BC_TTY && !BC_IS_POSIX)
#define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
#define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
#define BC_MAX_OBASE ((BcBigDig) (BC_BASE_POW))
#define BC_MAX_DIM ((BcBigDig) (SIZE_MAX - 1))
#define BC_MAX_SCALE ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1))
#define BC_MAX_STRING ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1))
#define BC_MAX_NAME BC_MAX_STRING
#define BC_MAX_NUM BC_MAX_SCALE
#if BC_ENABLE_EXTRA_MATH
#define BC_MAX_RAND ((BcBigDig) (((BcRand) 0) - 1))
#endif // BC_ENABLE_EXTRA_MATH
#define BC_MAX_EXP ((ulong) (BC_NUM_BIGDIG_MAX))
#define BC_MAX_VARS ((ulong) (SIZE_MAX - 1))
#define BC_IS_BC (BC_ENABLED && (!DC_ENABLED || vm.name[0] != 'd'))
#define BC_IS_POSIX (BC_S || BC_W)
#if BC_DEBUG_CODE
#define BC_VM_JMP bc_vm_jmp(__func__)
#else // BC_DEBUG_CODE
#define BC_VM_JMP bc_vm_jmp()
#endif // BC_DEBUG_CODE
#define BC_SIG_EXC \
BC_UNLIKELY(vm.status != (sig_atomic_t) BC_STATUS_SUCCESS || vm.sig)
#define BC_NO_SIG_EXC \
BC_LIKELY(vm.status == (sig_atomic_t) BC_STATUS_SUCCESS && !vm.sig)
#ifndef NDEBUG
#define BC_SIG_ASSERT_LOCKED do { assert(vm.sig_lock); } while (0)
#define BC_SIG_ASSERT_NOT_LOCKED do { assert(vm.sig_lock == 0); } while (0)
#else // NDEBUG
#define BC_SIG_ASSERT_LOCKED
#define BC_SIG_ASSERT_NOT_LOCKED
#endif // NDEBUG
#define BC_SIG_LOCK \
do { \
BC_SIG_ASSERT_NOT_LOCKED; \
vm.sig_lock = 1; \
} while (0)
#define BC_SIG_UNLOCK \
do { \
BC_SIG_ASSERT_LOCKED; \
vm.sig_lock = 0; \
if (BC_SIG_EXC) BC_VM_JMP; \
} while (0)
#define BC_SIG_MAYLOCK \
do { \
vm.sig_lock = 1; \
} while (0)
#define BC_SIG_MAYUNLOCK \
do { \
vm.sig_lock = 0; \
if (BC_SIG_EXC) BC_VM_JMP; \
} while (0)
#define BC_SIG_TRYLOCK(v) \
do { \
v = vm.sig_lock; \
vm.sig_lock = 1; \
} while (0)
#define BC_SIG_TRYUNLOCK(v) \
do { \
vm.sig_lock = (v); \
if (!(v) && BC_SIG_EXC) BC_VM_JMP; \
} while (0)
#define BC_SETJMP(l) \
do { \
sigjmp_buf sjb; \
BC_SIG_LOCK; \
if (sigsetjmp(sjb, 0)) { \
assert(BC_SIG_EXC); \
goto l; \
} \
bc_vec_push(&vm.jmp_bufs, &sjb); \
BC_SIG_UNLOCK; \
} while (0)
#define BC_SETJMP_LOCKED(l) \
do { \
sigjmp_buf sjb; \
BC_SIG_ASSERT_LOCKED; \
if (sigsetjmp(sjb, 0)) { \
assert(BC_SIG_EXC); \
goto l; \
} \
bc_vec_push(&vm.jmp_bufs, &sjb); \
} while (0)
#define BC_LONGJMP_CONT \
do { \
BC_SIG_ASSERT_LOCKED; \
if (!vm.sig_pop) bc_vec_pop(&vm.jmp_bufs); \
BC_SIG_UNLOCK; \
} while (0)
#define BC_UNSETJMP \
do { \
BC_SIG_ASSERT_LOCKED; \
bc_vec_pop(&vm.jmp_bufs); \
} while (0)
#define BC_LONGJMP_STOP \
do { \
vm.sig_pop = 0; \
vm.sig = 0; \
} while (0)
#define BC_VM_BUF_SIZE (1<<12)
#define BC_VM_STDOUT_BUF_SIZE (1<<11)
#define BC_VM_STDERR_BUF_SIZE (1<<10)
#define BC_VM_STDIN_BUF_SIZE BC_VM_STDERR_BUF_SIZE
#define bc_vm_err(e) (bc_vm_error((e), 0))
#define bc_vm_verr(e, ...) (bc_vm_error((e), 0, __VA_ARGS__))
#define BC_STATUS_IS_ERROR(s) \
((s) >= BC_STATUS_ERROR_MATH && (s) <= BC_STATUS_ERROR_FATAL)
#define BC_VM_INVALID_CATALOG ((nl_catd) -1)
// dc does not use is_stdin.
#if !BC_ENABLED
#define bc_vm_process(text, is_stdin) bc_vm_process(text)
#else // BC_ENABLED
#endif // BC_ENABLED
typedef struct BcVm {
volatile sig_atomic_t status;
volatile sig_atomic_t sig_pop;
BcParse prs;
BcProgram prog;
BcVec jmp_bufs;
BcVec temps;
const char* file;
const char *sigmsg;
volatile sig_atomic_t sig_lock;
volatile sig_atomic_t sig;
uchar siglen;
uchar read_ret;
uint16_t flags;
uint16_t nchars;
uint16_t line_len;
bool eof;
BcBigDig maxes[BC_PROG_GLOBALS_LEN + BC_ENABLE_EXTRA_MATH];
BcVec files;
BcVec exprs;
const char *name;
const char *help;
#if BC_ENABLE_HISTORY
BcHistory history;
#endif // BC_ENABLE_HISTORY
BcLexNext next;
BcParseParse parse;
BcParseExpr expr;
const char *func_header;
const char *err_ids[BC_ERR_IDX_NELEMS + BC_ENABLED];
const char *err_msgs[BC_ERROR_NELEMS];
const char *locale;
BcBigDig last_base;
BcBigDig last_pow;
BcBigDig last_exp;
BcBigDig last_rem;
char *env_args_buffer;
BcVec env_args;
BcNum max;
BcDig max_num[BC_NUM_BIGDIG_LOG10];
BcFile fout;
BcFile ferr;
#if BC_ENABLE_NLS
nl_catd catalog;
#endif // BC_ENABLE_NLS
char *buf;
size_t buf_len;
} BcVm;
void bc_vm_info(const char* const help);
void bc_vm_boot(int argc, char *argv[], const char *env_len,
const char* const env_args, const char* env_exp_quit);
void bc_vm_shutdown(void);
void bc_vm_printf(const char *fmt, ...);
void bc_vm_putchar(int c);
size_t bc_vm_arraySize(size_t n, size_t size);
size_t bc_vm_growSize(size_t a, size_t b);
void* bc_vm_malloc(size_t n);
void* bc_vm_realloc(void *ptr, size_t n);
char* bc_vm_strdup(const char *str);
#if BC_DEBUG_CODE
void bc_vm_jmp(const char *f);
#else // BC_DEBUG_CODE
void bc_vm_jmp(void);
#endif // BC_DEBUG_CODE
void bc_vm_error(BcError e, size_t line, ...);
extern const char bc_copyright[];
extern const char* const bc_err_line;
extern const char* const bc_err_func_header;
extern const char *bc_errs[];
extern const uchar bc_err_ids[];
extern const char* const bc_err_msgs[];
extern BcVm vm;
extern char output_bufs[BC_VM_BUF_SIZE];
#endif // BC_VM_H

View File

@ -0,0 +1,80 @@
$quote "
$ Headers for printing errors/warnings.
$set 1
1 "Funktion:"
$ Error types.
$set 2
1 "Rechenfehler:"
2 "Analysefehler:"
3 "Laufzeitfehler:"
4 "Fataler Fehler:"
5 "Warnung:"
$ Math errors.
$set 3
1 "negative Zahl"
2 "Nicht-Ganzzahl-Wert"
3 "Überlauf: Zahl passt nicht in Register"
4 "Division durch 0"
$ Parse errors.
$set 4
1 "Ende der Datei"
2 "ungültiges Zeichen: '%c'"
3 "Zeichenketten-Ende konnte nicht gefunden werden"
4 "Kommentar-Ende konnte nicht gefunden werden"
5 "ungültiges Token"
6 "ungültiger Ausdruck"
7 "leerer Ausdruck"
8 "Ungültige Druckanweisung"
9 "Ungültige Funktionsdefinition"
10 "Ungültige Zuweisung: Die linke Seite muss \"scale\", \"ibase\", \"obase\", \"seed\", \"last\", \"var\" oder \"array element\" sein"
11 "keine automatische Variable gefunden"
12 "Funktionsparameter oder Variable \"%s%s\" existiert bereits"
13 "Blockende konnte nicht gefunden werden"
14 "eine \"void-Funktion\" kann keinen Wert zurückgeben: %s()"
15 "Variable kann keine Referenz sein: %s"
16 "POSIX erlaubt keine Namen mit mehr als 1 Zeichen Länge: %s"
17 "POSIX erlaubt keine '#'-Skriptkommentare"
18 "POSIX erlaubt das Schlüsselwort \"%s\" nicht"
19 "POSIX erlaubt keinen Punkt ('.') als Abkürzung für das letzte Ergebnis"
20 "POSIX benötigt Klammern um Rückgabeausdrücke"
21 "POSIX erlaubt den Operator \"%s\" nicht"
22 "POSIX erlaubt keine Vergleichsoperatoren außerhalb von if-Anweisungen oder Schleifen"
23 "POSIX benötigt 0 oder 1 Vergleichsoperatoren pro Bedingung"
24 "POSIX erlaubt keinen leeren Ausdruck in einer for-Schleife"
25 "POSIX erlaubt keine exponentielle Notation"
26 "POSIX erlaubt keine Feld-Referenzen als Funktionsparameter"
27 "POSIX erfordert, dass die linke Klammer auf der gleichen Linie wie der Funktionskopf steht"
$ Runtime errors.
$set 5
1 "ungültige \"ibase\": muss im Intervall [%lu, %lu] liegen"
2 "ungültige \"obase\": muss im Intervall [%lu, %lu] liegen"
3 "ungültige \"scale\": muss im Intervall [%lu, %lu] liegen"
4 "ungültiger read()-Ausdruck"
5 "rekursiver read()-Aufruf"
6 "Variable oder Feld-Element hat den falschen Typ"
7 "Stapel hat zu wenig Elemente"
8 "falsche Anzahl der Parameter: benötigt %zu, hat %zu"
9 "undefinierte Funktion: %s()"
10 "kann keinen ungültigen Wert in einem Ausdruck verwenden"
$ Fatal errors.
$set 6
1 "Speicherzuweisung fehlgeschlagen"
2 "Ein-Ausgabe-Fehler"
3 "konnte die Datei nicht öffnen: %s"
4 "Datei ist nicht ASCII: %s"
5 "Pfad ist ein Verzeichnis: %s"
6 "ungültige Befehlszeilenoption: \"%s\""
7 "Option erfordert ein Argument: '%c' (\"%s\")"
8 "Option benutzt keine Argumente: '%c' (\"%s\")"

View File

@ -0,0 +1,80 @@
$quote "
$ Headers for printing errors/warnings.
$set 1
1 "Funktion:"
$ Error types.
$set 2
1 "Rechenfehler:"
2 "Analysefehler:"
3 "Laufzeitfehler:"
4 "Fataler Fehler:"
5 "Warnung:"
$ Math errors.
$set 3
1 "negative Zahl"
2 "Nicht-Ganzzahl-Wert"
3 "Überlauf: Zahl passt nicht in Register"
4 "Division durch 0"
$ Parse errors.
$set 4
1 "Ende der Datei"
2 "ungültiges Zeichen: '%c'"
3 "Zeichenketten-Ende konnte nicht gefunden werden"
4 "Kommentar-Ende konnte nicht gefunden werden"
5 "ungültiges Token"
6 "ungültiger Ausdruck"
7 "leerer Ausdruck"
8 "Ungültige Druckanweisung"
9 "Ungültige Funktionsdefinition"
10 "Ungültige Zuweisung: Die linke Seite muss \"scale\", \"ibase\", \"obase\", \"seed\", \"last\", \"var\" oder \"array element\" sein"
11 "keine automatische Variable gefunden"
12 "Funktionsparameter oder Variable \"%s%s\" existiert bereits"
13 "Blockende konnte nicht gefunden werden"
14 "eine \"void-Funktion\" kann keinen Wert zurückgeben: %s()"
15 "Variable kann keine Referenz sein: %s"
16 "POSIX erlaubt keine Namen mit mehr als 1 Zeichen Länge: %s"
17 "POSIX erlaubt keine '#'-Skriptkommentare"
18 "POSIX erlaubt das Schlüsselwort \"%s\" nicht"
19 "POSIX erlaubt keinen Punkt ('.') als Abkürzung für das letzte Ergebnis"
20 "POSIX benötigt Klammern um Rückgabeausdrücke"
21 "POSIX erlaubt den Operator \"%s\" nicht"
22 "POSIX erlaubt keine Vergleichsoperatoren außerhalb von if-Anweisungen oder Schleifen"
23 "POSIX benötigt 0 oder 1 Vergleichsoperatoren pro Bedingung"
24 "POSIX erlaubt keinen leeren Ausdruck in einer for-Schleife"
25 "POSIX erlaubt keine exponentielle Notation"
26 "POSIX erlaubt keine Feld-Referenzen als Funktionsparameter"
27 "POSIX erfordert, dass die linke Klammer auf der gleichen Linie wie der Funktionskopf steht"
$ Runtime errors.
$set 5
1 "ungültige \"ibase\": muss im Intervall [%lu, %lu] liegen"
2 "ungültige \"obase\": muss im Intervall [%lu, %lu] liegen"
3 "ungültige \"scale\"; muss im Intervall [%lu, %lu] liegen"
4 "ungültiger read()-Ausdruck"
5 "rekursiver read()-Aufruf"
6 "Variable oder Feld-Element hat den falschen Typ"
7 "Stapel hat zu wenig Elemente"
8 "falsche Anzahl der Parameter: benötigt %zu, hat %zu"
9 "undefinierte Funktion: %s()"
10 "kann keinen ungültigen Wert in einem Ausdruck verwenden"
$ Fatal errors.
$set 6
1 "Speicherzuweisung fehlgeschlagen"
2 "Ein-Ausgabe-Fehler"
3 "konnte die Datei nicht öffnen: %s"
4 "Datei ist nicht ASCII: %s"
5 "Pfad ist ein Verzeichnis: %s"
6 "ungültige Befehlszeilenoption: \"%s\""
7 "Option erfordert ein Argument: '%c' (\"%s\")"
8 "Option benutzt keine Argumente: '%c' (\"%s\")"

View File

@ -0,0 +1 @@
en_US.msg

View File

@ -0,0 +1,108 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ Miscellaneous messages.
$set 1
1 "Function:"
$ Error types.
$set 2
1 "Math error:"
2 "Parse error:"
3 "Runtime error:"
4 "Fatal error:"
5 "Warning:"
$ Math errors.
$set 3
1 "negative number"
2 "non-integer number"
3 "overflow: number does not fit into a hardware number"
4 "divide by 0"
$ Parse errors.
$set 4
1 "end of file"
2 "invalid character '%c'"
3 "string end cannot be found"
4 "comment end cannot be found"
5 "invalid token"
6 "invalid expression"
7 "empty expression"
8 "invalid print statement"
9 "invalid function definition"
10 "invalid assignment: left side must be scale, ibase, obase, seed, last, var, or array element"
11 "no auto variable found"
12 "function parameter or auto \"%s%s\" already exists"
13 "block end cannot be found"
14 "cannot return a value from void function: %s()"
15 "var cannot be a reference: %s"
16 "POSIX does not allow names longer than 1 character: %s"
17 "POSIX does not allow '#' script comments"
18 "POSIX does not allow the following keyword: %s"
19 "POSIX does not allow a period ('.') as a shortcut for the last result"
20 "POSIX requires parentheses around return expressions"
21 "POSIX does not allow the following operator: %s"
22 "POSIX does not allow comparison operators outside if statements or loops"
23 "POSIX requires 0 or 1 comparison operators per condition"
24 "POSIX requires all 3 parts of a for loop to be non-empty"
25 "POSIX does not allow exponential notation"
26 "POSIX does not allow array references as function parameters"
27 "POSIX requires the left brace be on the same line as the function header"
$ Runtime errors.
$set 5
1 "invalid ibase: must be [%lu, %lu]"
2 "invalid obase: must be [%lu, %lu]"
3 "invalid scale: must be [%lu, %lu]"
4 "invalid read() expression"
5 "recursive read() call"
6 "variable or array element is the wrong type"
7 "stack has too few elements"
8 "wrong number of parameters; need %zu, have %zu"
9 "undefined function: %s()"
10 "cannot use a void value in an expression"
$ Fatal errors.
$set 6
1 "memory allocation failed"
2 "I/O error"
3 "cannot open file: %s"
4 "file is not ASCII: %s"
5 "path is a directory: %s"
6 "invalid command-line option: \"%s\""
7 "option requires an argument: '%c' (\"%s\")"
8 "option takes no arguments: '%c' (\"%s\")"

View File

@ -0,0 +1,108 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ Miscellaneous messages.
$set 1
1 "Función:"
$ Error types.
$set 2
1 "Error de matemática:"
2 "Error de syntaxis:"
3 "Error de ejecución:"
4 "Error fatal:"
5 "Advertencia:"
$ Math errors.
$set 3
1 "número negativo"
2 "número no es entero"
3 "desbordamiento de enteros: no se puede encajar el el hardware"
4 "división por cero"
$ Parse errors.
$set 4
1 "fin de archivo"
2 "no válido '%c'"
3 "no puede encontrar el fine de la cadena"
4 "no puede encontrar el fine del comentario"
5 "el token no es válido"
6 "la expresión no es válida"
7 "la expresión es vacía"
8 "la expresión de print no es válida"
9 "la definición de función no es válida"
10 "la asignación no es valida: en la izquierda debe ser scale, ibase, obase, last, var, o un elemento de matriz"
11 "no se encontró ninguna variable automática"
12 "ya hay un parámetro de función o variable automatica que se llama \"%s%s\""
13 "no se puede encontrar el final de del bloque de código"
14 "no puede haber un valor de retorno de una función \"void\": %s()"
15 "var no puede ser una referencia: %s"
16 "POSIX no permite nombres de más de 1 carácter: %s"
17 "POSIX no permite '#' script comentarios"
18 "POSIX no permite este palabra clave %s"
19 "POSIX no permite un punto ('.') como un atajo del resultado previoso"
20 "POSIX requieres paréntesis en el expresión del \"return\""
21 "POSIX no permite este operador: %s"
22 "POSIX no permite operadores de comparación aparte de \"if\" expresión o bucles"
23 "POSIX requiere 0 o 1 operadores de comparisón para cada condición"
24 "POSIX requiere todos 3 partes de una bucla que no esta vacío"
25 "POSIX no permite una notación exponencial"
26 "POSIX no permite una referencia a una matriz como un parámetro de función"
27 "POSIX requiere el llave de la izquierda que sea en la misma línea que los parámetros de la función"
$ Runtime errors.
$set 5
1 "\"ibase\" no es válido: debe ser [%lu, %lu]"
2 "\"obase\" no es válido: debe ser [%lu, %lu]"
3 "\"scale\" no es válido: debe ser [%lu, %lu]"
4 "read() expresión no es válido"
5 "recursion en la invocación de read()"
6 "variable o elemento del matriz de tipo equivocado"
7 "la pila no ha demaciado elementos"
8 "la función no tiene un número de argumentos correcto; necessita %zu, tiene %zu"
9 "la función no esta definida: %s()"
10 "no puede utilizar un valor vacío en una expresión"
$ Fatal errors.
$set 6
1 "error en la asignación de memoria"
2 "error de I/O"
3 "no puede abrir el archivo: %s"
4 "el archivo no es ASCII: %s"
5 "el ruta es un directorio: %s"
6 "una opción de línea de comandos no es válida: \"%s\""
7 "una opción requiere un argumento: '%c' (\"%s\")"
8 "una opción no tiene argumento: '%c' (\"%s\")"

View File

@ -0,0 +1,108 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ Miscellaneous messages.
$set 1
1 "Fonction :"
$ Error types.
$set 2
1 "Erreur de calcul :"
2 "Erreur d'analyse syntaxique :"
3 "Erreur d'exécution :"
4 "Erreur fatale :"
5 "Avertissement :"
$ Math errors.
$set 3
1 "nombre strictement négatif"
2 "nombre non entier"
3 "dépassement : le nombre ne tient pas dans un type traité par le processeur"
4 "division par 0"
$ Parse errors.
$set 4
1 "fin de fichier"
2 "caractère invalide '%c'"
3 "fin de chaîne non trouvée"
4 "fin de commentaire non trouvée"
5 "symbole invalide"
6 "expression invalide"
7 "expression vide"
8 "instruction d'écriture invalide"
9 "définition de fonction invalide"
10 "affectation invalide : la partie gauche doit être 'scale', 'ibase', 'obase', 'seed', 'last', une variable ou une case de tableau"
11 "aucune variable auto trouvée"
12 "Le paramètre de fonction ou variable auto \"%s%s\" existe déjà"
13 "fin de bloc non trouvée"
14 "une fonction 'void' ne peut pas retourner de valeur : %s()"
15 "Une variable ne peut pas être une référence : %s"
16 "POSIX interdit les noms de plus d'un caractère : %s"
17 "POSIX interdit les commentaires dans les scripts (pas de '#')"
18 "POSIX interdit le mot-clé '%s'"
19 "POSIX interdit l'utilisation du point ('.') comme raccourci pour le dernier résultat"
20 "POSIX impose des parenthèses autour des expressions de retour"
21 "POSIX interdit l'opérateur '%s'"
22 "POSIX interdit les opérateurs de comparaison en dehors des expressions 'if' ou des boucles"
23 "POSIX impose 0 ou 1 opérateur de comparaison par condition"
24 "POSIX interdit une expression vide dans une boucle 'for'"
25 "POSIX interdit la notation exponentielle"
26 "POSIX interdit les références à un tableau dans les paramètres d'une fonction"
27 "POSIX impose que l'en-tête de la fonction et le '{' soient sur la même ligne"
$ Runtime errors.
$set 5
1 "ibase invalide : doit être [%lu, %lu]"
2 "obase invalide : doit être [%lu, %lu]"
3 "scale invalide : doit être [%lu, %lu]"
4 "expression read() invalide"
5 "appel read() récursif"
6 "mauvais type de variable ou d'élément de tableau"
7 "pile sous-remplie"
8 "nombre incorrect de paramètres - attendus : %zu, obtenus : %zu"
9 "fonction non définie : %s()"
10 "une valeur 'void' est inutilisable dans une expression"
$ Fatal errors.
$set 6
1 "échec d'allocation mémoire"
2 "erreur d'entrée-sortie"
3 "impossible d'ouvrir le fichier : %s"
4 "fichier non ASCII : %s"
5 "le chemin est un répertoire : %s"
6 "option de ligne de commande invalide : \"%s\""
7 "l'option '%c' (\"%s\") requiert un argument"
8 "l'option '%c' (\"%s\") ne prend pas d'argument"

View File

@ -0,0 +1,108 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ Miscellaneous messages.
$set 1
1 "Fonction :"
$ Error types.
$set 2
1 "Erreur de calcul :"
2 "Erreur d'analyse syntaxique :"
3 "Erreur d'exécution :"
4 "Erreur fatale :"
5 "Avertissement :"
$ Math errors.
$set 3
1 "nombre strictement négatif"
2 "nombre non entier"
3 "dépassement : le nombre ne tient pas dans un type traité par le processeur"
4 "division par 0"
$ Parse errors.
$set 4
1 "fin de fichier"
2 "caractère invalide '%c'"
3 "fin de chaîne non trouvée"
4 "fin de commentaire non trouvée"
5 "symbole invalide"
6 "expression invalide"
7 "expression vide"
8 "instruction d'écriture invalide"
9 "définition de fonction invalide"
10 "affectation invalide : la partie gauche doit être 'scale', 'ibase', 'obase', 'seed', 'last', une variable ou une case de tableau"
11 "aucune variable auto trouvée"
12 "Le paramètre de fonction ou variable auto \"%s%s\" existe déjà"
13 "fin de bloc non trouvée"
14 "une fonction 'void' ne peut pas retourner de valeur : %s()"
15 "Une variable ne peut pas être une référence : %s"
16 "POSIX interdit les noms de plus d'un caractère : %s"
17 "POSIX interdit les commentaires dans les scripts (pas de '#')"
18 "POSIX interdit le mot-clé '%s'"
19 "POSIX interdit l'utilisation du point ('.') comme raccourci pour le dernier résultat"
20 "POSIX impose des parenthèses autour des expressions de retour"
21 "POSIX interdit l'opérateur '%s'"
22 "POSIX interdit les opérateurs de comparaison en dehors des expressions 'if' ou des boucles"
23 "POSIX impose 0 ou 1 opérateur de comparaison par condition"
24 "POSIX interdit une expression vide dans une boucle 'for'"
25 "POSIX interdit la notation exponentielle"
26 "POSIX interdit les références à un tableau dans les paramètres d'une fonction"
27 "POSIX impose que l'en-tête de la fonction et le '{' soient sur la même ligne"
$ Runtime errors.
$set 5
1 "ibase invalide : doit être [%lu, %lu]"
2 "obase invalide : doit être [%lu, %lu]"
3 "scale invalide : doit être [%lu, %lu]"
4 "expression read() invalide"
5 "appel read() récursif"
6 "mauvais type de variable ou d'élément de tableau"
7 "pile sous-remplie"
8 "nombre incorrect de paramètres - attendus : %zu, obtenus : %zu"
9 "fonction non définie : %s()"
10 "une valeur 'void' est inutilisable dans une expression"
$ Fatal errors.
$set 6
1 "échec d'allocation mémoire"
2 "erreur d'entrée-sortie"
3 "impossible d'ouvrir le fichier : %s"
4 "fichier non ASCII : %s"
5 "le chemin est un répertoire : %s"
6 "option de ligne de commande invalide : \"%s\""
7 "l'option '%c' (\"%s\") requiert un argument"
8 "l'option '%c' (\"%s\") ne prend pas d'argument"

View File

@ -0,0 +1,83 @@
$quote "
$ その他のメッセージ。
$set 1
1 "関数:"
$ エラーの種類。
$set 2
1 "数学のエラー:"
2 "パースエラー:"
3 "ランタイムエラー:"
4 "致命的なエラー:"
5 "警告:"
$ 数学のエラーです。
$set 3
1 "負の数"
2 "非整数"
3 "オーバーフロー:数字がハードウェア番号に収まらない"
4 "0で割る"
$ 構文解析のエラー。
$set 4
1 "ファイルの終了"
2 "無効な文字 '%c'"
3 "文字列の終端が見つかりませんでした"
4 "コメントエンドが見つかりませんでした"
5 "無効なトークン"
6 "無効な式"
7 "空の式"
8 "無効な印刷文"
9 "無効な関数定義"
10 "無効な代入:左側は scale, ibase, obase, last, var, または配列要素でなければなりません"
11 "自動変数が見つかりませんでした"
12 "関数パラメータまたは自動\"ss\"はすでに存在します"
13 "ブロックエンドが見つかりませんでした"
14 "void 関数から値を返すことはできません:%s()"
15 "varは参照にできませんs"
16 "POSIX は 1 文字より長い名前を許可しません:%s"
17 "POSIX は '#' スクリプトのコメントを許可しません。"
18 "POSIX は以下のキーワードを許可しません:%s"
19 "POSIX は最後の結果のショートカットとしてピリオド ('.') を許可しません。"
20 "POSIX は戻り値式の周りに括弧を必要とします。"
21 "POSIX は次の演算子を許可しません:%s"
22 "POSIX は if 文やループの外の比較演算子を許可しません。"
23 "POSIXは条件ごとに0または1の比較演算子を必要とします。"
24 "POSIXはforループの3つの部分がすべて空でないことを要求します。"
25 "POSIXは指数表記を許可しません。"
26 "POSIX は関数パラメータとして配列参照を許可しません。"
27 "POSIXでは、関数ヘッダと同じ行に左中括弧があることが必要です。"
$ ランタイムエラー。
$set 5
1 "無効なibaseは[lu、lu]でなければなりません"
2 "無効なobaseは[lu、lu]でなければなりません"
3 "無効なscaleは[lu、lu]でなければなりません"
4 "式が無効read()"
5 "再帰的読み込み()呼び出し"
6 "変数または配列要素の型が間違っている"
7 "スタックの要素が少なすぎる"
8 "パラメータの数が間違っています。"
9 "定義されていない関数:%s()"
10 "式では void 値を使用できません"
$ 致命的なエラーが発生しました。
$set 6
1 "メモリの割り当てに失敗しました"
2 "I/Oエラー"
3 "ファイルを開けませんでした。%s"
4 "ファイルがASCIIではありません%s"
5 "パスはディレクトリです:%s"
6 "無効なコマンドラインオプション:'c'\"s\")"
$set 7
1 "オプションには引数が必要です:'%c' (\"%s\")"
2 "オプションは引数を取りません:'%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ その他のメッセージ。
$set 1
1 "関数:"
$ エラーの種類。
$set 2
1 "数学のエラー:"
2 "パースエラー:"
3 "ランタイムエラー:"
4 "致命的なエラー:"
5 "警告:"
$ 数学のエラーです。
$set 3
1 "負の数"
2 "非整数"
3 "オーバーフロー:数字がハードウェア番号に収まらない"
4 "0で割る"
$ 構文解析のエラー。
$set 4
1 "ファイルの終了"
2 "無効な文字 '%c'"
3 "文字列の終端が見つかりませんでした"
4 "コメントエンドが見つかりませんでした"
5 "無効なトークン"
6 "無効な式"
7 "空の式"
8 "無効な印刷文"
9 "無効な関数定義"
10 "無効な代入:左側は scale, ibase, obase, last, var, または配列要素でなければなりません"
11 "自動変数が見つかりませんでした"
12 "関数パラメータまたは自動\"ss\"はすでに存在します"
13 "ブロックエンドが見つかりませんでした"
14 "void 関数から値を返すことはできません:%s()"
15 "varは参照にできませんs"
16 "POSIX は 1 文字より長い名前を許可しません:%s"
17 "POSIX は '#' スクリプトのコメントを許可しません。"
18 "POSIX は以下のキーワードを許可しません:%s"
19 "POSIX は最後の結果のショートカットとしてピリオド ('.') を許可しません。"
20 "POSIX は戻り値式の周りに括弧を必要とします。"
21 "POSIX は次の演算子を許可しません:%s"
22 "POSIX は if 文やループの外の比較演算子を許可しません。"
23 "POSIXは条件ごとに0または1の比較演算子を必要とします。"
24 "POSIXはforループの3つの部分がすべて空でないことを要求します。"
25 "POSIXは指数表記を許可しません。"
26 "POSIX は関数パラメータとして配列参照を許可しません。"
27 "POSIXでは、関数ヘッダと同じ行に左中括弧があることが必要です。"
$ ランタイムエラー。
$set 5
1 "無効なibaseは[lu、lu]でなければなりません"
2 "無効なobaseは[lu、lu]でなければなりません"
3 "無効なscaleは[lu、lu]でなければなりません"
4 "式が無効read()"
5 "再帰的読み込み()呼び出し"
6 "変数または配列要素の型が間違っている"
7 "スタックの要素が少なすぎる"
8 "パラメータの数が間違っています。"
9 "定義されていない関数:%s()"
10 "式では void 値を使用できません"
$ 致命的なエラーが発生しました。
$set 6
1 "メモリの割り当てに失敗しました"
2 "I/Oエラー"
3 "ファイルを開けませんでした。%s"
4 "ファイルがASCIIではありません%s"
5 "パスはディレクトリです:%s"
6 "無効なコマンドラインオプション:'c'\"s\")"
$set 7
1 "オプションには引数が必要です:'%c' (\"%s\")"
2 "オプションは引数を取りません:'%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ Diversen berichten.
$set 1
1 "Functie:"
$ Fouttypes.
$set 2
1 "Rekenfout:"
2 "Parse error:"
3 "Runtime error:"
4 "Fatale fout:"
5 "Waarschuwing:"
$ Math error.
$set 3
1 "negatief getal"
2 "niet-integraal getal"
3 "overloop: nummer past niet in een hardware-nummer"
4 "delen door 0"
$ Parsefouten.
$set 4
1 "einde van het file"
2 "ongeldig teken '%c'"
3 "string einde kon niet worden gevonden"
4 "commentaar einde kon niet worden gevonden"
5 "ongeldige token"
6 "ongeldige uitdrukking"
7 "lege uitdrukking"
8 "ongeldige afdruk"
9 "ongeldige functiedefinitie"
10 "ongeldige toewijzing: linkerzijde moet scale, ibase, obase, last, var of array element zijn"
11 "geen autovariabele gevonden"
12 "Functieparameter of automatisch bestaat al"
13 "blokuiteinde kon niet worden gevonden"
14 "kan geen waarde uit de nietige functie teruggeven: %s()"
15 "var kan geen referentie zijn: %s"
16 "POSIX staat geen namen toe die langer zijn dan 1 teken: %s"
17 "POSIX staat geen '#'-scriptcommentaar toe"
18 "POSIX laat het volgende sleutelwoord niet toe: %s"
19 "POSIX staat geen periode ('.') toe als een kortere weg voor het laatste resultaat"
20 "POSIX vereist haakjes rond de terugkeeruitdrukkingen"
21 "POSIX laat de volgende operator niet toe: %s"
22 "POSIX laat geen vergelijking toe tussen operatoren buiten als verklaringen of lussen"
23 "POSIX vereist 0 of 1 vergelijkingsoperator per conditie"
24 "POSIX vereist dat alle 3 de delen van een lus niet leeg zijn"
25 "POSIX laat geen exponentiële notatie toe"
26 "POSIX staat geen arrayreferenties toe als functieparameters"
27 "POSIX vereist dat de linkse beugel op dezelfde regel staat als de functiehoofding"
$ Runtime fouten.
$set 5
1 "ongeldige ibase: moet [%lu, %lu] zijn"
2 "ongeldige obase: moet [%lu, %lu] zijn"
3 "ongeldige schaal: moet [%lu, %lu] zijn"
4 "ongeldige read() expressie"
5 "recursieve read() call"
6 "Variabele of matrix-element is het verkeerde type"
7 "Stapel heeft te weinig elementen"
8 "Verkeerd aantal parameters; hebben %zu nodig, hebben %zu"
9 "ongedefinieerde functie: %s()"
10 "kan geen nietige waarde in een uitdrukking gebruiken"
$ Fatale fouten.
$set 6
1 "geheugentoewijzing mislukt"
2 "I/O-fout"
3 "kon geen file openen: %s"
4 "bestand is niet ASCII: %s"
5 "pad is een directory: %s"
6 "ongeldige opdrachtregeloptie: '%c' (%s)"
$set 7
1 "optie vereist een argument: '%c' (\"%s\")"
2 "optie neemt geen argumenten aan: '%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ Diversen berichten.
$set 1
1 "Functie:"
$ Fouttypes.
$set 2
1 "Rekenfout:"
2 "Parse error:"
3 "Runtime error:"
4 "Fatale fout:"
5 "Waarschuwing:"
$ Math error.
$set 3
1 "negatief getal"
2 "niet-integraal getal"
3 "overloop: nummer past niet in een hardware-nummer"
4 "delen door 0"
$ Parsefouten.
$set 4
1 "einde van het file"
2 "ongeldig teken '%c'"
3 "string einde kon niet worden gevonden"
4 "commentaar einde kon niet worden gevonden"
5 "ongeldige token"
6 "ongeldige uitdrukking"
7 "lege uitdrukking"
8 "ongeldige afdruk"
9 "ongeldige functiedefinitie"
10 "ongeldige toewijzing: linkerzijde moet scale, ibase, obase, last, var of array element zijn"
11 "geen autovariabele gevonden"
12 "Functieparameter of automatisch bestaat al"
13 "blokuiteinde kon niet worden gevonden"
14 "kan geen waarde uit de nietige functie teruggeven: %s()"
15 "var kan geen referentie zijn: %s"
16 "POSIX staat geen namen toe die langer zijn dan 1 teken: %s"
17 "POSIX staat geen '#'-scriptcommentaar toe"
18 "POSIX laat het volgende sleutelwoord niet toe: %s"
19 "POSIX staat geen periode ('.') toe als een kortere weg voor het laatste resultaat"
20 "POSIX vereist haakjes rond de terugkeeruitdrukkingen"
21 "POSIX laat de volgende operator niet toe: %s"
22 "POSIX laat geen vergelijking toe tussen operatoren buiten als verklaringen of lussen"
23 "POSIX vereist 0 of 1 vergelijkingsoperator per conditie"
24 "POSIX vereist dat alle 3 de delen van een lus niet leeg zijn"
25 "POSIX laat geen exponentiële notatie toe"
26 "POSIX staat geen arrayreferenties toe als functieparameters"
27 "POSIX vereist dat de linkse beugel op dezelfde regel staat als de functiehoofding"
$ Runtime fouten.
$set 5
1 "ongeldige ibase: moet [%lu, %lu] zijn"
2 "ongeldige obase: moet [%lu, %lu] zijn"
3 "ongeldige schaal: moet [%lu, %lu] zijn"
4 "ongeldige read() expressie"
5 "recursieve read() call"
6 "Variabele of matrix-element is het verkeerde type"
7 "Stapel heeft te weinig elementen"
8 "Verkeerd aantal parameters; hebben %zu nodig, hebben %zu"
9 "ongedefinieerde functie: %s()"
10 "kan geen nietige waarde in een uitdrukking gebruiken"
$ Fatale fouten.
$set 6
1 "geheugentoewijzing mislukt"
2 "I/O-fout"
3 "kon geen file openen: %s"
4 "bestand is niet ASCII: %s"
5 "pad is een directory: %s"
6 "ongeldige opdrachtregeloptie: '%c' (%s)"
$set 7
1 "optie vereist een argument: '%c' (\"%s\")"
2 "optie neemt geen argumenten aan: '%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ Różne wiadomości.
$set 1
1 "Funkcja:"
$ Typy błędów.
$set 2
1 "Błąd matematyczny:"
2 "Błąd parse'a:"
3 "Błąd biegu:"
4 "Błąd śmiertelny:"
5 "Ostrzeżenie:"
$ Błędy matematyczne.
$set 3
1 "liczba ujemna"
2 "numer nieintegracyjny"
3 "przelewanie: liczba nie mieści się w numerze sprzętowym"
4 "dzielenie przez 0"
$ Błędy Parse'a.
$set 4
1 "koniec akt"
2 "nieważny znak '%c'"
3 "koniec sznurka nie mógł być znaleziony"
4 "koniec komentarza nie mógł być znaleziony"
5 "nieważny token"
6 "nieważne wyrażenie"
7 "puste wyrażenie"
8 "nieważny wyciąg z wydruku"
9 "nieprawidłowa definicja funkcji"
10 "nieprawidłowe przyporządkowanie: lewa strona musi być elementem scale, ibase, obase, last, var lub element array"
11 "nie znaleziono zmiennej automatycznej"
12 "parametr funkcji lub auto \"%s%s\" już istnieje"
13 "końca bloku nie można było znaleźć"
14 "nie może zwrócić wartości z funkcji void: %s()"
15 "var nie może być odniesieniem: %s"
16 "POSIX nie zezwala na nazwy dłuższe niż 1 znak: %s"
17 "POSIX nie pozwala na komentarze skryptu '#'"
18 "POSIX nie pozwala na użycie następującego słowa kluczowego: %s"
19 "POSIX nie dopuszcza kropki ('.') jako skrótu do ostatniego wyniku"
20 "POSIX wymaga nawiasów wokół wyrażeń zwrotnych"
21 "POSIX nie pozwala następującemu operatorowi: %s"
22 "POSIX nie pozwala na porównywanie operatorów na zewnątrz, jeśli deklaracje lub pętle"
23 "POSIX wymaga 0 lub 1 operatora porównawczego na jeden warunek"
24 "POSIX wymaga, aby wszystkie 3 części pętli nie były puste"
25 "POSIX nie pozwala na notację wykładniczą"
26 "POSIX nie zezwala na odniesienia do tablicy jako parametrów funkcji"
27 "POSIX wymaga, aby lewe usztywnienie znajdowało się na tej samej linii co nagłówek funkcji"
$ Błędy Runtime'u.
$set 5
1 "nieprawidłowa ibase: musi być [%lu, %lu]"
2 "nieprawidłowa obase: musi być [%lu, %lu]"
3 "nieprawidłowa scale: musi być [%lu, %lu]"
4 "nieprawidłowe wyrażenie read()"
5 "powtarzalne wywołanie read()"
6 "element zmienny lub tablicowy jest niewłaściwym typem"
7 "stos ma zbyt mało elementów"
8 "niewłaściwa liczba parametrów; potrzeba %zu, mają %zu"
9 "niezdefiniowana funkcja: %s()"
10 "nie może użyć wartości pustej w wyrażeniu"
$ Fatalne błędy.
$set 6
1 "Alokacja pamięci nie powiodła się"
2 "Błąd we/wy"
3 "nie mógł otworzyć pliku: %s"
4 "plik nie jest ASCII: %s"
5 "ścieżka to katalog: %s"
6 "nieprawidłowa opcja wiersza poleceń: '%c' (\"%s\")"
$set 7
1 "opcja wymaga argumentu: '%c' (\"%s\")"
2 "opcja nie wymaga żadnych argumentów: '%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ Różne wiadomości.
$set 1
1 "Funkcja:"
$ Typy błędów.
$set 2
1 "Błąd matematyczny:"
2 "Błąd parse'a:"
3 "Błąd biegu:"
4 "Błąd śmiertelny:"
5 "Ostrzeżenie:"
$ Błędy matematyczne.
$set 3
1 "liczba ujemna"
2 "numer nieintegracyjny"
3 "przelewanie: liczba nie mieści się w numerze sprzętowym"
4 "dzielenie przez 0"
$ Błędy Parse'a.
$set 4
1 "koniec akt"
2 "nieważny znak '%c'"
3 "koniec sznurka nie mógł być znaleziony"
4 "koniec komentarza nie mógł być znaleziony"
5 "nieważny token"
6 "nieważne wyrażenie"
7 "puste wyrażenie"
8 "nieważny wyciąg z wydruku"
9 "nieprawidłowa definicja funkcji"
10 "nieprawidłowe przyporządkowanie: lewa strona musi być elementem scale, ibase, obase, last, var lub element array"
11 "nie znaleziono zmiennej automatycznej"
12 "parametr funkcji lub auto \"%s%s\" już istnieje"
13 "końca bloku nie można było znaleźć"
14 "nie może zwrócić wartości z funkcji void: %s()"
15 "var nie może być odniesieniem: %s"
16 "POSIX nie zezwala na nazwy dłuższe niż 1 znak: %s"
17 "POSIX nie pozwala na komentarze skryptu '#'"
18 "POSIX nie pozwala na użycie następującego słowa kluczowego: %s"
19 "POSIX nie dopuszcza kropki ('.') jako skrótu do ostatniego wyniku"
20 "POSIX wymaga nawiasów wokół wyrażeń zwrotnych"
21 "POSIX nie pozwala następującemu operatorowi: %s"
22 "POSIX nie pozwala na porównywanie operatorów na zewnątrz, jeśli deklaracje lub pętle"
23 "POSIX wymaga 0 lub 1 operatora porównawczego na jeden warunek"
24 "POSIX wymaga, aby wszystkie 3 części pętli nie były puste"
25 "POSIX nie pozwala na notację wykładniczą"
26 "POSIX nie zezwala na odniesienia do tablicy jako parametrów funkcji"
27 "POSIX wymaga, aby lewe usztywnienie znajdowało się na tej samej linii co nagłówek funkcji"
$ Błędy Runtime'u.
$set 5
1 "nieprawidłowa ibase: musi być [%lu, %lu]"
2 "nieprawidłowa obase: musi być [%lu, %lu]"
3 "nieprawidłowa scale: musi być [%lu, %lu]"
4 "nieprawidłowe wyrażenie read()"
5 "powtarzalne wywołanie read()"
6 "element zmienny lub tablicowy jest niewłaściwym typem"
7 "stos ma zbyt mało elementów"
8 "niewłaściwa liczba parametrów; potrzeba %zu, mają %zu"
9 "niezdefiniowana funkcja: %s()"
10 "nie może użyć wartości pustej w wyrażeniu"
$ Fatalne błędy.
$set 6
1 "Alokacja pamięci nie powiodła się"
2 "Błąd we/wy"
3 "nie mógł otworzyć pliku: %s"
4 "plik nie jest ASCII: %s"
5 "ścieżka to katalog: %s"
6 "nieprawidłowa opcja wiersza poleceń: '%c' (\"%s\")"
$set 7
1 "opcja wymaga argumentu: '%c' (\"%s\")"
2 "opcja nie wymaga żadnych argumentów: '%c' (\"%s\")"

View File

@ -0,0 +1,108 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ Miscellaneous messages.
$set 1
1 "Função:"
$ Error types.
$set 2
1 "Erro de cálculo:"
2 "Erro de análise de sintaxe:"
3 "Erro de execução:"
4 "Erro fatal:"
5 "Aviso:"
$ Math errors.
$set 3
1 "número negativo"
2 "número não inteiro"
3 "Estouro: número não cabe no registro"
4 "dividir por 0"
$ Parse errors.
$set 4
1 "fim do arquivo"
2 "caractere inválido '%c'"
3 "Não foi possível encontrar o final da string"
4 "Não foi possível encontrar o final do comentário"
5 "token inválido"
6 "expressão inválida"
7 "expressão vazia"
8 "instrução de gravação inválida"
9 "definição de função inválida"
10 "atribuição inválida: a parte esquerda deve ser 'scale', 'ibase', 'obase', 'last', uma variável ou um elemento da matriz"
11 "nenhuma variável automática encontrada"
12 "parâmetro de função ou variável automática \"%s%s\" já existe"
13 "fim do bloco não encontrado"
14 "uma função 'void' não pode retornar um valor: %s()"
15 "Uma variável não pode ser uma referência: %s"
16 "POSIX não permite nomes com mais de 1 caractere: %s"
17 "POSIX não permite comentários de script '#'"
18 "POSIX não permite a seguinte palavra-chave: %s"
19 "POSIX não permite um ponto ('.') como um atalho para o último resultado"
20 "POSIX requer parênteses em torno de expressões de retorno"
21 "POSIX não permite o seguinte operador: %s"
22 "POSIX não permite operadores de comparação fora das expressões 'if' ou loops"
23 "POSIX requer operadores 0 ou 1 de comparação por condição"
24 "POSIX não permite uma expressão vazia em um loop 'for'"
25 "POSIX não permite notação exponencial"
26 "POSIX não permite referências de matriz como parâmetros de função"
27 "POSIX requer que o cabeçalho da função '{' estejam na mesma linha"
$ Runtime errors.
$set 5
1 "ibase inválido: deve ser [%lu, %lu]"
2 "obase inválido: deve ser [%lu, %lu]"
3 "scale inválida: deve ser [%lu, %lu]"
4 "expressão read() inválida"
5 "chamada read() recursiva"
6 "tipo errado de variável ou elemento de matriz"
7 "pilha tem poucos elementos"
8 "número incorreto de parâmetros - esperado: %zu, obtido: %zu"
9 "função indefinida: %s()"
10 "um valor 'void' não pode ser usado em uma expressão"
$ Fatal errors.
$set 6
1 "falha na alocação de memória"
2 "erro de entrada-saída"
3 "impossível abrir o arquivo: %s"
4 "arquivo não é ASCII: %s"
5 "caminho é um diretório: %s"
6 "opção de linha de comando inválida: \"%s\""
7 "opção requer um argumento: '%c' (\"%s\")"
8 "a opção não aceita argumentos: '%c' (\"%s\")"

View File

@ -0,0 +1,108 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ Miscellaneous messages.
$set 1
1 "Função:"
$ Error types.
$set 2
1 "Erro de cálculo:"
2 "Erro de análise de sintaxe:"
3 "Erro de execução:"
4 "Erro fatal:"
5 "Aviso:"
$ Math errors.
$set 3
1 "número negativo"
2 "número não inteiro"
3 "Estouro: número não cabe no registro"
4 "dividir por 0"
$ Parse errors.
$set 4
1 "fim do arquivo"
2 "caractere inválido '%c'"
3 "Não foi possível encontrar o final da string"
4 "Não foi possível encontrar o final do comentário"
5 "token inválido"
6 "expressão inválida"
7 "expressão vazia"
8 "instrução de gravação inválida"
9 "definição de função inválida"
10 "atribuição inválida: a parte esquerda deve ser 'scale', 'ibase', 'obase', 'last', uma variável ou um elemento da matriz"
11 "nenhuma variável automática encontrada"
12 "parâmetro de função ou variável automática \"%s%s\" já existe"
13 "fim do bloco não encontrado"
14 "uma função 'void' não pode retornar um valor: %s()"
15 "Uma variável não pode ser uma referência: %s"
16 "POSIX não permite nomes com mais de 1 caractere: %s"
17 "POSIX não permite comentários de script '#'"
18 "POSIX não permite a seguinte palavra-chave: %s"
19 "POSIX não permite um ponto ('.') como um atalho para o último resultado"
20 "POSIX requer parênteses em torno de expressões de retorno"
21 "POSIX não permite o seguinte operador: %s"
22 "POSIX não permite operadores de comparação fora das expressões 'if' ou loops"
23 "POSIX requer operadores 0 ou 1 de comparação por condição"
24 "POSIX não permite uma expressão vazia em um loop 'for'"
25 "POSIX não permite notação exponencial"
26 "POSIX não permite referências de matriz como parâmetros de função"
27 "POSIX requer que o cabeçalho da função '{' estejam na mesma linha"
$ Runtime errors.
$set 5
1 "ibase inválido: deve ser [%lu, %lu]"
2 "obase inválido: deve ser [%lu, %lu]"
3 "scale inválida: deve ser [%lu, %lu]"
4 "expressão read() inválida"
5 "chamada read() recursiva"
6 "tipo errado de variável ou elemento de matriz"
7 "pilha tem poucos elementos"
8 "número incorreto de parâmetros - esperado: %zu, obtido: %zu"
9 "função indefinida: %s()"
10 "um valor 'void' não pode ser usado em uma expressão"
$ Fatal errors.
$set 6
1 "falha na alocação de memória"
2 "erro de entrada-saída"
3 "impossível abrir o arquivo: %s"
4 "arquivo não é ASCII: %s"
5 "caminho é um diretório: %s"
6 "opção de linha de comando inválida: \"%s\""
7 "opção requer um argumento: '%c' (\"%s\")"
8 "a opção não aceita argumentos: '%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ Разные сообщения.
$set 1
1 "Функция:"
$ Типы ошибок.
$set 2
1 "Математическая ошибка:"
2 "Ошибка при разборе:"
3 "Ошибка выполнения:"
4 "Фатальная ошибка:"
5 "Предупреждение:"
$ Математические ошибки.
$set 3
1 "отрицательное число"
2 "неинтегрированное число"
3 "переполнение: номер не помещается в аппаратный номер"
4 "делить на 0"
$ Ошибки при разборе.
$set 4
1 "конец файла"
2 "недопустимый символ '%c'"
3 "конец строки не найден"
4 "конец комментария не найден"
5 "недействительный жетон"
6 "неправильное выражение"
7 "пустое выражение"
8 "заявление о недействительности печати"
9 "определение недействительной функции"
10 "неверное присвоение: левая сторона должна быть scale, ibase, obase, last, варом или элементом массива"
11 "автоматическая переменная не найдена"
12 "параметр функции или auto \"%s%s\" уже существует"
13 "конец блока не найден"
14 "не может вернуть значение из функции void: %s()"
15 "var не может быть ссылкой: %s"
16 "POSIX не допускает имен длиннее 1 символа: %s"
17 "POSIX не допускает комментариев к сценарию '#'"
18 "POSIX не допускает следующее ключевое слово: %s"
19 "POSIX не допускает точку ('.') в качестве ярлыка для последнего результата"
20 "POSIX требует скобок вокруг выражений возврата"
21 "POSIX не разрешает использовать следующий оператор: %s"
22 "POSIX не разрешает операторам сравнения выходить за пределы, если утверждения или циклы"
23 "POSIX требует 0 или 1 оператора сравнения на условие"
24 "POSIX требует, чтобы все 3 части петли были непустыми"
25 "POSIX не допускает экспоненциальной нотации"
26 "POSIX не допускает ссылки на массив в качестве параметров функции"
27 "POSIX требует, чтобы левая скобка была на той же линии, что и заголовок функции"
$ Ошибки выполнения.
$set 5
1 "Недействительный ibase: должен быть [%lu, %lu]"
2 "Недействительный obase: должен быть [%lu, %lu]"
3 "недействительная scale: должна быть [%lu, %lu]"
4 "недействительное выражение read()"
5 "рекурсивный вызов read()"
6 "переменная или элемент массива является неправильным типом"
7 "стопка имеет слишком мало элементов"
8 "неправильное количество параметров; нужно %zu, нужно %zu"
9 "неопределенная функция: %s()"
10 "не может использовать пустое значение в выражении"
$ Фатальные ошибки.
$set 6
1 "Не удалось выделить память"
2 "Ошибка ввода/вывода"
3 "не смог открыть файл: %s"
4 "файл не ASCII: %s"
5 "путь - это каталог: %s"
6 "неверная опция командной строки: '%c' (\"%s\")"
$set 7
1 "опция требует аргумента: '%c' (\"%s\")"
2 "опция не принимает аргументов: '%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ <20> §­ë¥ á®®¡é¥­¨ï.
$set 1
1 "”ã­ªæ¨ï:"
$ ’¨¯ë ®è¨¡®ª.
$set 2
1 "Œ â¥¬ â¨ç¥áª ï ®è¨¡ª :"
2 "Žè¨¡ª  ¯à¨ à §¡®à¥:"
3 "Žè¨¡ª  ¢ë¯®«­¥­¨ï:"
4 "” â «ì­ ï ®è¨¡ª :"
5 "<22>।ã¯à¥¦¤¥­¨¥:"
$ Œ â¥¬ â¨ç¥áª¨¥ ®è¨¡ª¨.
$set 3
1 "®âà¨æ â¥«ì­®¥ ç¨á«®"
2 "­¥¨­â¥£à¨à®¢ ­­®¥ ç¨á«®"
3 "¯¥à¥¯®«­¥­¨¥: ­®¬¥à ­¥ ¯®¬¥é ¥âáï ¢  ¯¯ à â­ë© ­®¬¥à"
4 "¤¥«¨âì ­  0"
$ Žè¨¡ª¨ ¯à¨ à §¡®à¥.
$set 4
1 "ª®­¥æ ä ©« "
2 "­¥¤®¯ãáâ¨¬ë© á¨¬¢®« '%c'"
3 "ª®­¥æ áâப¨ ­¥ ­ ©¤¥­"
4 "ª®­¥æ ª®¬¬¥­â à¨ï ­¥ ­ ©¤¥­"
5 "­¥¤¥©á⢨⥫ì­ë© ¦¥â®­"
6 "­¥¯à ¢¨«ì­®¥ ¢ëà ¦¥­¨¥"
7 "¯ãá⮥ ¢ëà ¦¥­¨¥"
8 "§ ï¢«¥­¨¥ ® ­¥¤¥©á⢨⥫쭮á⨠¯¥ç â¨"
9 "®¯à¥¤¥«¥­¨¥ ­¥¤¥©á⢨⥫쭮© ä㭪樨"
10 "­¥¢¥à­®¥ ¯à¨á¢®¥­¨¥: «¥¢ ï áâ®à®­  ¤®«¦­  ¡ëâì scale, ibase, obase, last, ¢ à®¬ ¨«¨ í«¥¬¥­â®¬ ¬ áᨢ "
11 " ¢â®¬ â¨ç¥áª ï ¯¥à¥¬¥­­ ï ­¥ ­ ©¤¥­ "
12 "¯ à ¬¥âà ä㭪樨 ¨«¨ auto \"%s%s\" 㦥 áãé¥áâ¢ã¥â"
13 "ª®­¥æ ¡«®ª  ­¥ ­ ©¤¥­"
14 "­¥ ¬®¦¥â ¢¥à­ãâì §­ ç¥­¨¥ ¨§ ä㭪樨 void: %s()"
15 "var ­¥ ¬®¦¥â ¡ëâì áá뫪®©: %s"
16 "POSIX ­¥ ¤®¯ã᪠¥â ¨¬¥­ ¤«¨­­¥¥ 1 ᨬ¢®« : %s"
17 "POSIX ­¥ ¤®¯ã᪠¥â ª®¬¬¥­â à¨¥¢ ª á業 à¨î '#'"
18 "POSIX ­¥ ¤®¯ã᪠¥â á«¥¤ãî饥 ª«î祢®¥ á«®¢®: %s"
19 "POSIX ­¥ ¤®¯ã᪠¥â â®çªã ('.') ¢ ª ç¥á⢥ ïà«ëª  ¤«ï ¯®á«¥¤­¥£® १ã«ìâ â "
20 "POSIX âॡã¥â ᪮¡®ª ¢®ªà㣠¢ëà ¦¥­¨© ¢®§¢à â "
21 "POSIX ­¥ à §à¥è ¥â ¨á¯®«ì§®¢ âì á«¥¤ãî騩 ®¯¥à â®à: %s"
22 "POSIX ­¥ à §à¥è ¥â ®¯¥à â®à ¬ áà ¢­¥­¨ï ¢ë室¨âì §  ¯à¥¤¥«ë, ¥á«¨ ã⢥ত¥­¨ï ¨«¨ 横«ë"
23 "POSIX âॡã¥â 0 ¨«¨ 1 ®¯¥à â®à  áà ¢­¥­¨ï ­  ãá«®¢¨¥"
24 "POSIX âॡã¥â, çâ®¡ë ¢á¥ 3 ç á⨠¯¥â«¨ ¡ë«¨ ­¥¯ãáâ묨"
25 "POSIX ­¥ ¤®¯ã᪠¥â íªá¯®­¥­æ¨ «ì­®© ­®â æ¨¨"
26 "POSIX ­¥ ¤®¯ã᪠¥â áá뫪¨ ­  ¬ áᨢ ¢ ª ç¥á⢥ ¯ à ¬¥â஢ ä㭪樨"
27 "POSIX âॡã¥â, çâ®¡ë «¥¢ ï ᪮¡ª  ¡ë«  ­  ⮩ ¦¥ «¨­¨¨, çâ® ¨ § £®«®¢®ª ä㭪樨"
$ Žè¨¡ª¨ ¢ë¯®«­¥­¨ï.
$set 5
1 "<22>¥¤¥©á⢨⥫ì­ë© ibase: ¤®«¦¥­ ¡ëâì [%lu, %lu]"
2 "<22>¥¤¥©á⢨⥫ì­ë© obase: ¤®«¦¥­ ¡ëâì [%lu, %lu]"
3 "­¥¤¥©á⢨⥫쭠ï scale: ¤®«¦­  ¡ëâì [%lu, %lu]"
4 "­¥¤¥©á⢨⥫쭮¥ ¢ëà ¦¥­¨¥ read()"
5 "४ãàᨢ­ë© ¢ë§®¢ read()"
6 "¯¥à¥¬¥­­ ï ¨«¨ í«¥¬¥­â ¬ áᨢ  ï¥âáï ­¥¯à ¢¨«ì­ë¬ ⨯®¬"
7 "á⮯ª  ¨¬¥¥â ᫨誮¬ ¬ «® í«¥¬¥­â®¢"
8 "­¥¯à ¢¨«ì­®¥ ª®«¨ç¥á⢮ ¯ à ¬¥â஢; ­ã¦­® %zu, ­ã¦­® %zu"
9 "­¥®¯à¥¤¥«¥­­ ï äã­ªæ¨ï: %s()"
10 "­¥ ¬®¦¥â ¨á¯®«ì§®¢ âì ¯ãá⮥ §­ ç¥­¨¥ ¢ ¢ëà ¦¥­¨¨"
$ ” â «ì­ë¥ ®è¨¡ª¨.
$set 6
1 "<22>¥ 㤠«®áì ¢ë¤¥«¨âì ¯ ¬ïâì"
2 "Žè¨¡ª  ¢¢®¤ /¢ë¢®¤ "
3 "­¥ ᬮ£ ®âªàëâì ä ©«: %s"
4 "ä ©« ­¥ ASCII: %s"
5 "¯ãâì - íâ® ª â «®£: %s"
6 "­¥¢¥à­ ï ®¯æ¨ï ª®¬ ­¤­®© áâப¨: '%c' (\"%s\")"
$set 7
1 "®¯æ¨ï âॡã¥â  à£ã¬¥­â : '%c' (\"%s\")"
2 "®¯æ¨ï ­¥ ¯à¨­¨¬ ¥â  à£ã¬¥­â®¢: '%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ Разные сообщения.
$set 1
1 "Функция:"
$ Типы ошибок.
$set 2
1 "Математическая ошибка:"
2 "Ошибка при разборе:"
3 "Ошибка выполнения:"
4 "Фатальная ошибка:"
5 "Предупреждение:"
$ Математические ошибки.
$set 3
1 "отрицательное число"
2 "неинтегрированное число"
3 "переполнение: номер не помещается в аппаратный номер"
4 "делить на 0"
$ Ошибки при разборе.
$set 4
1 "конец файла"
2 "недопустимый символ '%c'"
3 "конец строки не найден"
4 "конец комментария не найден"
5 "недействительный жетон"
6 "неправильное выражение"
7 "пустое выражение"
8 "заявление о недействительности печати"
9 "определение недействительной функции"
10 "неверное присвоение: левая сторона должна быть scale, ibase, obase, last, варом или элементом массива"
11 "автоматическая переменная не найдена"
12 "параметр функции или auto \"%s%s\" уже существует"
13 "конец блока не найден"
14 "не может вернуть значение из функции void: %s()"
15 "var не может быть ссылкой: %s"
16 "POSIX не допускает имен длиннее 1 символа: %s"
17 "POSIX не допускает комментариев к сценарию '#'"
18 "POSIX не допускает следующее ключевое слово: %s"
19 "POSIX не допускает точку ('.') в качестве ярлыка для последнего результата"
20 "POSIX требует скобок вокруг выражений возврата"
21 "POSIX не разрешает использовать следующий оператор: %s"
22 "POSIX не разрешает операторам сравнения выходить за пределы, если утверждения или циклы"
23 "POSIX требует 0 или 1 оператора сравнения на условие"
24 "POSIX требует, чтобы все 3 части петли были непустыми"
25 "POSIX не допускает экспоненциальной нотации"
26 "POSIX не допускает ссылки на массив в качестве параметров функции"
27 "POSIX требует, чтобы левая скобка была на той же линии, что и заголовок функции"
$ Ошибки выполнения.
$set 5
1 "Недействительный ibase: должен быть [%lu, %lu]"
2 "Недействительный obase: должен быть [%lu, %lu]"
3 "недействительная scale: должна быть [%lu, %lu]"
4 "недействительное выражение read()"
5 "рекурсивный вызов read()"
6 "переменная или элемент массива является неправильным типом"
7 "стопка имеет слишком мало элементов"
8 "неправильное количество параметров; нужно %zu, нужно %zu"
9 "неопределенная функция: %s()"
10 "не может использовать пустое значение в выражении"
$ Фатальные ошибки.
$set 6
1 "Не удалось выделить память"
2 "Ошибка ввода/вывода"
3 "не смог открыть файл: %s"
4 "файл не ASCII: %s"
5 "путь - это каталог: %s"
6 "неверная опция командной строки: '%c' (\"%s\")"
$set 7
1 "опция требует аргумента: '%c' (\"%s\")"
2 "опция не принимает аргументов: '%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ Разные сообщения.
$set 1
1 "Функция:"
$ Типы ошибок.
$set 2
1 "Математическая ошибка:"
2 "Ошибка при разборе:"
3 "Ошибка выполнения:"
4 "Фатальная ошибка:"
5 "Предупреждение:"
$ Математические ошибки.
$set 3
1 "отрицательное число"
2 "неинтегрированное число"
3 "переполнение: номер не помещается в аппаратный номер"
4 "делить на 0"
$ Ошибки при разборе.
$set 4
1 "конец файла"
2 "недопустимый символ '%c'"
3 "конец строки не найден"
4 "конец комментария не найден"
5 "недействительный жетон"
6 "неправильное выражение"
7 "пустое выражение"
8 "заявление о недействительности печати"
9 "определение недействительной функции"
10 "неверное присвоение: левая сторона должна быть scale, ibase, obase, last, варом или элементом массива"
11 "автоматическая переменная не найдена"
12 "параметр функции или auto \"%s%s\" уже существует"
13 "конец блока не найден"
14 "не может вернуть значение из функции void: %s()"
15 "var не может быть ссылкой: %s"
16 "POSIX не допускает имен длиннее 1 символа: %s"
17 "POSIX не допускает комментариев к сценарию '#'"
18 "POSIX не допускает следующее ключевое слово: %s"
19 "POSIX не допускает точку ('.') в качестве ярлыка для последнего результата"
20 "POSIX требует скобок вокруг выражений возврата"
21 "POSIX не разрешает использовать следующий оператор: %s"
22 "POSIX не разрешает операторам сравнения выходить за пределы, если утверждения или циклы"
23 "POSIX требует 0 или 1 оператора сравнения на условие"
24 "POSIX требует, чтобы все 3 части петли были непустыми"
25 "POSIX не допускает экспоненциальной нотации"
26 "POSIX не допускает ссылки на массив в качестве параметров функции"
27 "POSIX требует, чтобы левая скобка была на той же линии, что и заголовок функции"
$ Ошибки выполнения.
$set 5
1 "Недействительный ibase: должен быть [%lu, %lu]"
2 "Недействительный obase: должен быть [%lu, %lu]"
3 "недействительная scale: должна быть [%lu, %lu]"
4 "недействительное выражение read()"
5 "рекурсивный вызов read()"
6 "переменная или элемент массива является неправильным типом"
7 "стопка имеет слишком мало элементов"
8 "неправильное количество параметров; нужно %zu, нужно %zu"
9 "неопределенная функция: %s()"
10 "не может использовать пустое значение в выражении"
$ Фатальные ошибки.
$set 6
1 "Не удалось выделить память"
2 "Ошибка ввода/вывода"
3 "не смог открыть файл: %s"
4 "файл не ASCII: %s"
5 "путь - это каталог: %s"
6 "неверная опция командной строки: '%c' (\"%s\")"
$set 7
1 "опция требует аргумента: '%c' (\"%s\")"
2 "опция не принимает аргументов: '%c' (\"%s\")"

View File

@ -0,0 +1,83 @@
$quote "
$ Разные сообщения.
$set 1
1 "Функция:"
$ Типы ошибок.
$set 2
1 "Математическая ошибка:"
2 "Ошибка при разборе:"
3 "Ошибка выполнения:"
4 "Фатальная ошибка:"
5 "Предупреждение:"
$ Математические ошибки.
$set 3
1 "отрицательное число"
2 "неинтегрированное число"
3 "переполнение: номер не помещается в аппаратный номер"
4 "делить на 0"
$ Ошибки при разборе.
$set 4
1 "конец файла"
2 "недопустимый символ '%c'"
3 "конец строки не найден"
4 "конец комментария не найден"
5 "недействительный жетон"
6 "неправильное выражение"
7 "пустое выражение"
8 "заявление о недействительности печати"
9 "определение недействительной функции"
10 "неверное присвоение: левая сторона должна быть scale, ibase, obase, last, варом или элементом массива"
11 "автоматическая переменная не найдена"
12 "параметр функции или auto \"%s%s\" уже существует"
13 "конец блока не найден"
14 "не может вернуть значение из функции void: %s()"
15 "var не может быть ссылкой: %s"
16 "POSIX не допускает имен длиннее 1 символа: %s"
17 "POSIX не допускает комментариев к сценарию '#'"
18 "POSIX не допускает следующее ключевое слово: %s"
19 "POSIX не допускает точку ('.') в качестве ярлыка для последнего результата"
20 "POSIX требует скобок вокруг выражений возврата"
21 "POSIX не разрешает использовать следующий оператор: %s"
22 "POSIX не разрешает операторам сравнения выходить за пределы, если утверждения или циклы"
23 "POSIX требует 0 или 1 оператора сравнения на условие"
24 "POSIX требует, чтобы все 3 части петли были непустыми"
25 "POSIX не допускает экспоненциальной нотации"
26 "POSIX не допускает ссылки на массив в качестве параметров функции"
27 "POSIX требует, чтобы левая скобка была на той же линии, что и заголовок функции"
$ Ошибки выполнения.
$set 5
1 "Недействительный ibase: должен быть [%lu, %lu]"
2 "Недействительный obase: должен быть [%lu, %lu]"
3 "недействительная scale: должна быть [%lu, %lu]"
4 "недействительное выражение read()"
5 "рекурсивный вызов read()"
6 "переменная или элемент массива является неправильным типом"
7 "стопка имеет слишком мало элементов"
8 "неправильное количество параметров; нужно %zu, нужно %zu"
9 "неопределенная функция: %s()"
10 "не может использовать пустое значение в выражении"
$ Фатальные ошибки.
$set 6
1 "Не удалось выделить память"
2 "Ошибка ввода/вывода"
3 "не смог открыть файл: %s"
4 "файл не ASCII: %s"
5 "путь - это каталог: %s"
6 "неверная опция командной строки: '%c' (\"%s\")"
$set 7
1 "опция требует аргумента: '%c' (\"%s\")"
2 "опция не принимает аргументов: '%c' (\"%s\")"

View File

@ -0,0 +1,111 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ 杂项信息。
$set 1
1 "函数:"
$ 错误类型。
$set 2
1 "数学错误:"
2 "解析错误:"
3 "运行时错误:"
4 "致命错误:"
5 "警告:"
$ 数学错误。
$set 3
1 "负数"
2 "非整数"
3 "溢出:数字不符合硬件号码"
4 "除以0"
$ 解析错误。
$set 4
1 "文件结束"
2 "无效字符'%c'"
3 "找不到字符串尾部"
4 "无法找到评论的结尾"
5 "无效令牌"
6 "无效表达"
7 “空表达”
8 "无效打印声明"
9 "无效的功能定义"
10 "无效分配左侧必须是scale、ibase、obase、last、var或数组元素"
11 "没有找到自动变量"
12 "函数参数或自动参数 \"%s%s\" 已经存在"
13 "找不到区块末端"
14 "不能从void函数中返回一个值%s()"
15 "var不能作为参考%s"
16 "POSIX不允许名字超过1个字符%s"
17 "POSIX不允许'#'脚本注释"
18 "POSIX不允许使用以下关键字%s"
19 "POSIX不允许用句号('.')作为最后结果的快捷方式"
20 "POSIX要求在返回表达式周围加括号"
21 "POSIX不允许以下操作符%s"
22 "POSIX不允许在if语句或循环之外的比较运算符"
23 "POSIX要求每个条件的比较运算符为0或1个"
24 "POSIX要求for循环的所有3个部分必须是非空的"
25 "POSIX不允许使用指数符号"
26 "POSIX不允许数组引用作为函数参数"
27 "POSIX要求左边的括号和函数头在同一行上"
$ 运行时错误。
$set 5
1 "无效的ibase: 必须是[%lu, %lu]"
2 "无效的obase必须是[%lu%lu]"
3 "无效的scale必须是[%lu%lu]"
4 "无效的read()表达式"
5 "递归读取()调用"
6 "变量或数组元素是错误的类型"
7 "堆栈的元素太少"
8 "参数数量错误;需要%zu有%zu"
9 "未定义的函数:%s()"
10 “不能在表达式中使用空值”
$ 致命错误。
$set 6
1 "内存分配失败"
2 "I/O错误"
3 "无法打开文件。%s"
4 "文件不是ASCII: %s"
5 "路径是一个目录:%s"
6 "无效的命令行选项:'%c'(\"%s\")"
$set 7
1 "选项需要一个参数:'%c'(\"%s\")"
2 "选项不需要参数。'%c'(\"%s\")"

View File

@ -0,0 +1,111 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ 杂项信息。
$set 1
1 "函数:"
$ 错误类型。
$set 2
1 "数学错误:"
2 "解析错误:"
3 "运行时错误:"
4 "致命错误:"
5 "警告:"
$ 数学错误。
$set 3
1 "负数"
2 "非整数"
3 "溢出:数字不符合硬件号码"
4 "除以0"
$ 解析错误。
$set 4
1 "文件结束"
2 "无效字符'%c'"
3 "找不到字符串尾部"
4 "无法找到评论的结尾"
5 "无效令牌"
6 "无效表达"
7 “空表达”
8 "无效打印声明"
9 "无效的功能定义"
10 "无效分配左侧必须是scale、ibase、obase、last、var或数组元素"
11 "没有找到自动变量"
12 "函数参数或自动参数 \"%s%s\" 已经存在"
13 "找不到区块末端"
14 "不能从void函数中返回一个值%s()"
15 "var不能作为参考%s"
16 "POSIX不允许名字超过1个字符%s"
17 "POSIX不允许'#'脚本注释"
18 "POSIX不允许使用以下关键字%s"
19 "POSIX不允许用句号('.')作为最后结果的快捷方式"
20 "POSIX要求在返回表达式周围加括号"
21 "POSIX不允许以下操作符%s"
22 "POSIX不允许在if语句或循环之外的比较运算符"
23 "POSIX要求每个条件的比较运算符为0或1个"
24 "POSIX要求for循环的所有3个部分必须是非空的"
25 "POSIX不允许使用指数符号"
26 "POSIX不允许数组引用作为函数参数"
27 "POSIX要求左边的括号和函数头在同一行上"
$ 运行时错误。
$set 5
1 "无效的ibase: 必须是[%lu, %lu]"
2 "无效的obase必须是[%lu%lu]"
3 "无效的scale必须是[%lu%lu]"
4 "无效的read()表达式"
5 "递归读取()调用"
6 "变量或数组元素是错误的类型"
7 "堆栈的元素太少"
8 "参数数量错误;需要%zu有%zu"
9 "未定义的函数:%s()"
10 “不能在表达式中使用空值”
$ 致命错误。
$set 6
1 "内存分配失败"
2 "I/O错误"
3 "无法打开文件。%s"
4 "文件不是ASCII: %s"
5 "路径是一个目录:%s"
6 "无效的命令行选项:'%c'(\"%s\")"
$set 7
1 "选项需要一个参数:'%c'(\"%s\")"
2 "选项不需要参数。'%c'(\"%s\")"

View File

@ -0,0 +1,111 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ 杂项信息。
$set 1
1 "函数:"
$ 错误类型。
$set 2
1 "数学错误:"
2 "解析错误:"
3 "运行时错误:"
4 "致命错误:"
5 "警告:"
$ 数学错误。
$set 3
1 "负数"
2 "非整数"
3 "溢出:数字不符合硬件号码"
4 "除以0"
$ 解析错误。
$set 4
1 "文件结束"
2 "无效字符'%c'"
3 "找不到字符串尾部"
4 "无法找到评论的结尾"
5 "无效令牌"
6 "无效表达"
7 “空表达”
8 "无效打印声明"
9 "无效的功能定义"
10 "无效分配左侧必须是scale、ibase、obase、last、var或数组元素"
11 "没有找到自动变量"
12 "函数参数或自动参数 \"%s%s\" 已经存在"
13 "找不到区块末端"
14 "不能从void函数中返回一个值%s()"
15 "var不能作为参考%s"
16 "POSIX不允许名字超过1个字符%s"
17 "POSIX不允许'#'脚本注释"
18 "POSIX不允许使用以下关键字%s"
19 "POSIX不允许用句号('.')作为最后结果的快捷方式"
20 "POSIX要求在返回表达式周围加括号"
21 "POSIX不允许以下操作符%s"
22 "POSIX不允许在if语句或循环之外的比较运算符"
23 "POSIX要求每个条件的比较运算符为0或1个"
24 "POSIX要求for循环的所有3个部分必须是非空的"
25 "POSIX不允许使用指数符号"
26 "POSIX不允许数组引用作为函数参数"
27 "POSIX要求左边的括号和函数头在同一行上"
$ 运行时错误。
$set 5
1 "无效的ibase: 必须是[%lu, %lu]"
2 "无效的obase必须是[%lu%lu]"
3 "无效的scale必须是[%lu%lu]"
4 "无效的read()表达式"
5 "递归读取()调用"
6 "变量或数组元素是错误的类型"
7 "堆栈的元素太少"
8 "参数数量错误;需要%zu有%zu"
9 "未定义的函数:%s()"
10 “不能在表达式中使用空值”
$ 致命错误。
$set 6
1 "内存分配失败"
2 "I/O错误"
3 "无法打开文件。%s"
4 "文件不是ASCII: %s"
5 "路径是一个目录:%s"
6 "无效的命令行选项:'%c'(\"%s\")"
$set 7
1 "选项需要一个参数:'%c'(\"%s\")"
2 "选项不需要参数。'%c'(\"%s\")"

View File

@ -0,0 +1,111 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ 杂项信息。
$set 1
1 "函数:"
$ 错误类型。
$set 2
1 "数学错误:"
2 "解析错误:"
3 "运行时错误:"
4 "致命错误:"
5 "警告:"
$ 数学错误。
$set 3
1 "负数"
2 "非整数"
3 "溢出:数字不符合硬件号码"
4 "除以0"
$ 解析错误。
$set 4
1 "文件结束"
2 "无效字符'%c'"
3 "找不到字符串尾部"
4 "无法找到评论的结尾"
5 "无效令牌"
6 "无效表达"
7 “空表达”
8 "无效打印声明"
9 "无效的功能定义"
10 "无效分配左侧必须是scale、ibase、obase、last、var或数组元素"
11 "没有找到自动变量"
12 "函数参数或自动参数 \"%s%s\" 已经存在"
13 "找不到区块末端"
14 "不能从void函数中返回一个值%s()"
15 "var不能作为参考%s"
16 "POSIX不允许名字超过1个字符%s"
17 "POSIX不允许'#'脚本注释"
18 "POSIX不允许使用以下关键字%s"
19 "POSIX不允许用句号('.')作为最后结果的快捷方式"
20 "POSIX要求在返回表达式周围加括号"
21 "POSIX不允许以下操作符%s"
22 "POSIX不允许在if语句或循环之外的比较运算符"
23 "POSIX要求每个条件的比较运算符为0或1个"
24 "POSIX要求for循环的所有3个部分必须是非空的"
25 "POSIX不允许使用指数符号"
26 "POSIX不允许数组引用作为函数参数"
27 "POSIX要求左边的括号和函数头在同一行上"
$ 运行时错误。
$set 5
1 "无效的ibase: 必须是[%lu, %lu]"
2 "无效的obase必须是[%lu%lu]"
3 "无效的scale必须是[%lu%lu]"
4 "无效的read()表达式"
5 "递归读取()调用"
6 "变量或数组元素是错误的类型"
7 "堆栈的元素太少"
8 "参数数量错误;需要%zu有%zu"
9 "未定义的函数:%s()"
10 “不能在表达式中使用空值”
$ 致命错误。
$set 6
1 "内存分配失败"
2 "I/O错误"
3 "无法打开文件。%s"
4 "文件不是ASCII: %s"
5 "路径是一个目录:%s"
6 "无效的命令行选项:'%c'(\"%s\")"
$set 7
1 "选项需要一个参数:'%c'(\"%s\")"
2 "选项不需要参数。'%c'(\"%s\")"

View File

@ -0,0 +1,111 @@
$ $
$ Copyright (c) 2018-2020 Gavin D. Howard and contributors.
$ $
$ All rights reserved.
$ $
$ Redistribution and use in source and binary forms, with or without
$ modification, are permitted provided that the following conditions are met:
$ $
$ * Redistributions of source code must retain the above copyright notice, this
$ list of conditions and the following disclaimer.
$ $
$ * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
$ $
$quote "
$ 杂项信息。
$set 1
1 "函数:"
$ 错误类型。
$set 2
1 "数学错误:"
2 "解析错误:"
3 "运行时错误:"
4 "致命错误:"
5 "警告:"
$ 数学错误。
$set 3
1 "负数"
2 "非整数"
3 "溢出:数字不符合硬件号码"
4 "除以0"
$ 解析错误。
$set 4
1 "文件结束"
2 "无效字符'%c'"
3 "找不到字符串尾部"
4 "无法找到评论的结尾"
5 "无效令牌"
6 "无效表达"
7 “空表达”
8 "无效打印声明"
9 "无效的功能定义"
10 "无效分配左侧必须是scale、ibase、obase、last、var或数组元素"
11 "没有找到自动变量"
12 "函数参数或自动参数 \"%s%s\" 已经存在"
13 "找不到区块末端"
14 "不能从void函数中返回一个值%s()"
15 "var不能作为参考%s"
16 "POSIX不允许名字超过1个字符%s"
17 "POSIX不允许'#'脚本注释"
18 "POSIX不允许使用以下关键字%s"
19 "POSIX不允许用句号('.')作为最后结果的快捷方式"
20 "POSIX要求在返回表达式周围加括号"
21 "POSIX不允许以下操作符%s"
22 "POSIX不允许在if语句或循环之外的比较运算符"
23 "POSIX要求每个条件的比较运算符为0或1个"
24 "POSIX要求for循环的所有3个部分必须是非空的"
25 "POSIX不允许使用指数符号"
26 "POSIX不允许数组引用作为函数参数"
27 "POSIX要求左边的括号和函数头在同一行上"
$ 运行时错误。
$set 5
1 "无效的ibase: 必须是[%lu, %lu]"
2 "无效的obase必须是[%lu%lu]"
3 "无效的scale必须是[%lu%lu]"
4 "无效的read()表达式"
5 "递归读取()调用"
6 "变量或数组元素是错误的类型"
7 "堆栈的元素太少"
8 "参数数量错误;需要%zu有%zu"
9 "未定义的函数:%s()"
10 “不能在表达式中使用空值”
$ 致命错误。
$set 6
1 "内存分配失败"
2 "I/O错误"
3 "无法打开文件。%s"
4 "文件不是ASCII: %s"
5 "路径是一个目录:%s"
6 "无效的命令行选项:'%c'(\"%s\")"
$set 7
1 "选项需要一个参数:'%c'(\"%s\")"
2 "选项不需要参数。'%c'(\"%s\")"

View File

@ -0,0 +1,189 @@
# Algorithms
This `bc` uses the math algorithms below:
### Addition
This `bc` uses brute force addition, which is linear (`O(n)`) in the number of
digits.
### Subtraction
This `bc` uses brute force subtraction, which is linear (`O(n)`) in the number
of digits.
### Multiplication
This `bc` uses two algorithms: [Karatsuba][1] and brute force.
Karatsuba is used for "large" numbers. ("Large" numbers are defined as any
number with `BC_NUM_KARATSUBA_LEN` digits or larger. `BC_NUM_KARATSUBA_LEN` has
a sane default, but may be configured by the user.) Karatsuba, as implemented in
this `bc`, is superlinear but subpolynomial (bounded by `O(n^log_2(3))`).
Brute force multiplication is used below `BC_NUM_KARATSUBA_LEN` digits. It is
polynomial (`O(n^2)`), but since Karatsuba requires both more intermediate
values (which translate to memory allocations) and a few more additions, there
is a "break even" point in the number of digits where brute force multiplication
is faster than Karatsuba. There is a script (`$ROOT/karatsuba.py`) that will
find the break even point on a particular machine.
***WARNING: The Karatsuba script requires Python 3.***
### Division
This `bc` uses Algorithm D ([long division][2]). Long division is polynomial
(`O(n^2)`), but unlike Karatsuba, any division "divide and conquer" algorithm
reaches its "break even" point with significantly larger numbers. "Fast"
algorithms become less attractive with division as this operation typically
reduces the problem size.
While the implementation of long division may appear to use the subtractive
chunking method, it only uses subtraction to find a quotient digit. It avoids
unnecessary work by aligning digits prior to performing subtraction and finding
a starting guess for the quotient.
Subtraction was used instead of multiplication for two reasons:
1. Division and subtraction can share code (one of the less important goals of
this `bc` is small code).
2. It minimizes algorithmic complexity.
Using multiplication would make division have the even worse algorithmic
complexity of `O(n^(2*log_2(3)))` (best case) and `O(n^3)` (worst case).
### Power
This `bc` implements [Exponentiation by Squaring][3], which (via Karatsuba) has
a complexity of `O((n*log(n))^log_2(3))` which is favorable to the
`O((n*log(n))^2)` without Karatsuba.
### Square Root
This `bc` implements the fast algorithm [Newton's Method][4] (also known as the
Newton-Raphson Method, or the [Babylonian Method][5]) to perform the square root
operation. Its complexity is `O(log(n)*n^2)` as it requires one division per
iteration.
### Sine and Cosine (`bc` Only)
This `bc` uses the series
```
x - x^3/3! + x^5/5! - x^7/7! + ...
```
to calculate `sin(x)` and `cos(x)`. It also uses the relation
```
cos(x) = sin(x + pi/2)
```
to calculate `cos(x)`. It has a complexity of `O(n^3)`.
**Note**: this series has a tendency to *occasionally* produce an error of 1
[ULP][6]. (It is an unfortunate side effect of the algorithm, and there isn't
any way around it; [this article][7] explains why calculating sine and cosine,
and the other transcendental functions below, within less than 1 ULP is nearly
impossible and unnecessary.) Therefore, I recommend that users do their
calculations with the precision (`scale`) set to at least 1 greater than is
needed.
### Exponentiation (`bc` Only)
This `bc` uses the series
```
1 + x + x^2/2! + x^3/3! + ...
```
to calculate `e^x`. Since this only works when `x` is small, it uses
```
e^x = (e^(x/2))^2
```
to reduce `x`. It has a complexity of `O(n^3)`.
**Note**: this series can also produce errors of 1 ULP, so I recommend users do
their calculations with the precision (`scale`) set to at least 1 greater than
is needed.
### Natural Logarithm (`bc` Only)
This `bc` uses the series
```
a + a^3/3 + a^5/5 + ...
```
(where `a` is equal to `(x - 1)/(x + 1)`) to calculate `ln(x)` when `x` is small
and uses the relation
```
ln(x^2) = 2 * ln(x)
```
to sufficiently reduce `x`. It has a complexity of `O(n^3)`.
**Note**: this series can also produce errors of 1 ULP, so I recommend users do
their calculations with the precision (`scale`) set to at least 1 greater than
is needed.
### Arctangent (`bc` Only)
This `bc` uses the series
```
x - x^3/3 + x^5/5 - x^7/7 + ...
```
to calculate `atan(x)` for small `x` and the relation
```
atan(x) = atan(c) + atan((x - c)/(1 + x * c))
```
to reduce `x` to small enough. It has a complexity of `O(n^3)`.
**Note**: this series can also produce errors of 1 ULP, so I recommend users do
their calculations with the precision (`scale`) set to at least 1 greater than
is needed.
### Bessel (`bc` Only)
This `bc` uses the series
```
x^n/(2^n * n!) * (1 - x^2 * 2 * 1! * (n + 1)) + x^4/(2^4 * 2! * (n + 1) * (n + 2)) - ...
```
to calculate the bessel function (integer order only).
It also uses the relation
```
j(-n,x) = (-1)^n * j(n,x)
```
to calculate the bessel when `x < 0`, It has a complexity of `O(n^3)`.
**Note**: this series can also produce errors of 1 ULP, so I recommend users do
their calculations with the precision (`scale`) set to at least 1 greater than
is needed.
### Modular Exponentiation (`dc` Only)
This `dc` uses the [Memory-efficient method][8] to compute modular
exponentiation. The complexity is `O(e*n^2)`, which may initially seem
inefficient, but `n` is kept small by maintaining small numbers. In practice, it
is extremely fast.
[1]: https://en.wikipedia.org/wiki/Karatsuba_algorithm
[2]: https://en.wikipedia.org/wiki/Long_division
[3]: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
[4]: https://en.wikipedia.org/wiki/Newton%27s_method#Square_root_of_a_number
[5]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
[6]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[7]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[8]: https://en.wikipedia.org/wiki/Modular_exponentiation#Memory-efficient_method

1566
contrib/bc/manuals/bc.1 Normal file

File diff suppressed because it is too large Load Diff

1556
contrib/bc/manuals/bc.1.ronn Normal file

File diff suppressed because it is too large Load Diff

1
contrib/bc/manuals/bc.md Symbolic link
View File

@ -0,0 +1 @@
bc.1.ronn

View File

@ -0,0 +1,673 @@
# Benchmarks
The results of these benchmarks suggest that building this `bc` with
optimization at `-O3` with link-time optimization (`-flto`) will result in the
best performance. However, using `-march=native` can result in **WORSE**
performance.
*Note*: all benchmarks were run four times, and the fastest run is the one
shown. Also, `[bc]` means whichever `bc` was being run, and the assumed working
directory is the root directory of this repository. Also, this `bc` was at
version `3.0.0` while GNU `bc` was at version `1.07.1`, and all tests were
conducted on an `x86_64` machine running Gentoo Linux with `clang` `9.0.1` as
the compiler.
## Typical Optimization Level
These benchmarks were run with both `bc`'s compiled with the typical `-O2`
optimizations and no link-time optimization.
### Addition
The command used was:
```
tests/script.sh bc add.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 2.54
user 1.21
sys 1.32
```
For this `bc`:
```
real 0.88
user 0.85
sys 0.02
```
### Subtraction
The command used was:
```
tests/script.sh bc subtract.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 2.51
user 1.05
sys 1.45
```
For this `bc`:
```
real 0.91
user 0.85
sys 0.05
```
### Multiplication
The command used was:
```
tests/script.sh bc multiply.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 7.15
user 4.69
sys 2.46
```
For this `bc`:
```
real 2.20
user 2.10
sys 0.09
```
### Division
The command used was:
```
tests/script.sh bc divide.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 3.36
user 1.87
sys 1.48
```
For this `bc`:
```
real 1.61
user 1.57
sys 0.03
```
### Power
The command used was:
```
printf '1234567890^100000; halt\n' | time -p [bc] -q > /dev/null
```
For GNU `bc`:
```
real 11.30
user 11.30
sys 0.00
```
For this `bc`:
```
real 0.73
user 0.72
sys 0.00
```
### Scripts
[This file][1] was downloaded, saved at `../timeconst.bc` and the following
patch was applied:
```
--- ../timeconst.bc 2018-09-28 11:32:22.808669000 -0600
+++ ../timeconst.bc 2019-06-07 07:26:36.359913078 -0600
@@ -110,8 +110,10 @@
print "#endif /* KERNEL_TIMECONST_H */\n"
}
- halt
}
-hz = read();
-timeconst(hz)
+for (i = 0; i <= 50000; ++i) {
+ timeconst(i)
+}
+
+halt
```
The command used was:
```
time -p [bc] ../timeconst.bc > /dev/null
```
For GNU `bc`:
```
real 16.71
user 16.06
sys 0.65
```
For this `bc`:
```
real 13.16
user 13.15
sys 0.00
```
Because this `bc` is faster when doing math, it might be a better comparison to
run a script that is not running any math. As such, I put the following into
`../test.bc`:
```
for (i = 0; i < 100000000; ++i) {
y = i
}
i
y
halt
```
The command used was:
```
time -p [bc] ../test.bc > /dev/null
```
For GNU `bc`:
```
real 16.60
user 16.59
sys 0.00
```
For this `bc`:
```
real 22.76
user 22.75
sys 0.00
```
I also put the following into `../test2.bc`:
```
i = 0
while (i < 100000000) {
i += 1
}
i
halt
```
The command used was:
```
time -p [bc] ../test2.bc > /dev/null
```
For GNU `bc`:
```
real 17.32
user 17.30
sys 0.00
```
For this `bc`:
```
real 16.98
user 16.96
sys 0.01
```
It seems that the improvements to the interpreter helped a lot in certain cases.
Also, I have no idea why GNU `bc` did worse when it is technically doing less
work.
## Recommended Optimizations from `2.7.0`
Note that, when running the benchmarks, the optimizations used are not the ones
I recommended for version `2.7.0`, which are `-O3 -flto -march=native`.
This `bc` separates its code into modules that, when optimized at link time,
removes a lot of the inefficiency that comes from function overhead. This is
most keenly felt with one function: `bc_vec_item()`, which should turn into just
one instruction (on `x86_64`) when optimized at link time and inlined. There are
other functions that matter as well.
I also recommended `-march=native` on the grounds that newer instructions would
increase performance on math-heavy code. We will see if that assumption was
correct. (Spoiler: **NO**.)
When compiling both `bc`'s with the optimizations I recommended for this `bc`
for version `2.7.0`, the results are as follows.
### Addition
The command used was:
```
tests/script.sh bc add.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 2.44
user 1.11
sys 1.32
```
For this `bc`:
```
real 0.59
user 0.54
sys 0.05
```
### Subtraction
The command used was:
```
tests/script.sh bc subtract.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 2.42
user 1.02
sys 1.40
```
For this `bc`:
```
real 0.64
user 0.57
sys 0.06
```
### Multiplication
The command used was:
```
tests/script.sh bc multiply.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 7.01
user 4.50
sys 2.50
```
For this `bc`:
```
real 1.59
user 1.53
sys 0.05
```
### Division
The command used was:
```
tests/script.sh bc divide.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 3.26
user 1.82
sys 1.44
```
For this `bc`:
```
real 1.24
user 1.20
sys 0.03
```
### Power
The command used was:
```
printf '1234567890^100000; halt\n' | time -p [bc] -q > /dev/null
```
For GNU `bc`:
```
real 11.08
user 11.07
sys 0.00
```
For this `bc`:
```
real 0.71
user 0.70
sys 0.00
```
### Scripts
The command for the `../timeconst.bc` script was:
```
time -p [bc] ../timeconst.bc > /dev/null
```
For GNU `bc`:
```
real 15.62
user 15.08
sys 0.53
```
For this `bc`:
```
real 10.09
user 10.08
sys 0.01
```
The command for the next script, the `for` loop script, was:
```
time -p [bc] ../test.bc > /dev/null
```
For GNU `bc`:
```
real 14.76
user 14.75
sys 0.00
```
For this `bc`:
```
real 17.95
user 17.94
sys 0.00
```
The command for the next script, the `while` loop script, was:
```
time -p [bc] ../test2.bc > /dev/null
```
For GNU `bc`:
```
real 14.84
user 14.83
sys 0.00
```
For this `bc`:
```
real 13.53
user 13.52
sys 0.00
```
## Link-Time Optimization Only
Just for kicks, let's see if `-march=native` is even useful.
The optimizations I used for both `bc`'s were `-O3 -flto`.
### Addition
The command used was:
```
tests/script.sh bc add.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 2.41
user 1.05
sys 1.35
```
For this `bc`:
```
real 0.58
user 0.52
sys 0.05
```
### Subtraction
The command used was:
```
tests/script.sh bc subtract.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 2.39
user 1.10
sys 1.28
```
For this `bc`:
```
real 0.65
user 0.57
sys 0.07
```
### Multiplication
The command used was:
```
tests/script.sh bc multiply.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 6.82
user 4.30
sys 2.51
```
For this `bc`:
```
real 1.57
user 1.49
sys 0.08
```
### Division
The command used was:
```
tests/script.sh bc divide.bc 1 0 1 1 [bc]
```
For GNU `bc`:
```
real 3.25
user 1.81
sys 1.43
```
For this `bc`:
```
real 1.27
user 1.23
sys 0.04
```
### Power
The command used was:
```
printf '1234567890^100000; halt\n' | time -p [bc] -q > /dev/null
```
For GNU `bc`:
```
real 10.50
user 10.49
sys 0.00
```
For this `bc`:
```
real 0.72
user 0.71
sys 0.00
```
### Scripts
The command for the `../timeconst.bc` script was:
```
time -p [bc] ../timeconst.bc > /dev/null
```
For GNU `bc`:
```
real 15.50
user 14.81
sys 0.68
```
For this `bc`:
```
real 10.17
user 10.15
sys 0.01
```
The command for the next script, the `for` loop script, was:
```
time -p [bc] ../test.bc > /dev/null
```
For GNU `bc`:
```
real 14.99
user 14.99
sys 0.00
```
For this `bc`:
```
real 16.85
user 16.84
sys 0.00
```
The command for the next script, the `while` loop script, was:
```
time -p [bc] ../test2.bc > /dev/null
```
For GNU `bc`:
```
real 14.92
user 14.91
sys 0.00
```
For this `bc`:
```
real 12.75
user 12.75
sys 0.00
```
It turns out that `-march=native` can be a problem. As such, I have removed the
recommendation to build with `-march=native`.
## Recommended Compiler
When I ran these benchmarks with my `bc` compiled under `clang` vs. `gcc`, it
performed much better under `clang`. I recommend compiling this `bc` with
`clang`.
[1]: https://github.com/torvalds/linux/blob/master/kernel/time/timeconst.bc

672
contrib/bc/manuals/build.md Normal file
View File

@ -0,0 +1,672 @@
# Build
This `bc` attempts to be as portable as possible. It can be built on any
POSIX-compliant system.
To accomplish that, a POSIX-compatible, custom `configure.sh` script is used to
select build options, compiler, and compiler flags and generate a `Makefile`.
The general form of configuring, building, and installing this `bc` is as
follows:
```
[ENVIRONMENT_VARIABLE=<value>...] ./configure.sh [build_options...]
make
make install
```
To get all of the options, including any useful environment variables, use
either one of the following commands:
```
./configure.sh -h
./configure.sh --help
```
***WARNING***: even though `configure.sh` supports both option types, short and
long, it does not support handling both at the same time. Use only one type.
To learn the available `make` targets run the following command after running
the `configure.sh` script:
```
make help
```
See [Build Environment Variables][4] for a more detailed description of all
accepted environment variables and [Build Options][5] for more detail about all
accepted build options.
<a name="cross-compiling"/>
## Cross Compiling
To cross-compile this `bc`, an appropriate compiler must be present and assigned
to the environment variable `HOSTCC` or `HOST_CC` (the two are equivalent,
though `HOSTCC` is prioritized). This is in order to bootstrap core file(s), if
the architectures are not compatible (i.e., unlike i686 on x86_64). Thus, the
approach is:
```
HOSTCC="/path/to/native/compiler" ./configure.sh
make
make install
```
`HOST_CC` will work in exactly the same way.
`HOSTCFLAGS` and `HOST_CFLAGS` can be used to set compiler flags for `HOSTCC`.
(The two are equivalent, as `HOSTCC` and `HOST_CC` are.) `HOSTCFLAGS` is
prioritized over `HOST_CFLAGS`. If neither are present, `HOSTCC` (or `HOST_CC`)
uses `CFLAGS` (see [Build Environment Variables][4] for more details).
It is expected that `CC` produces code for the target system and `HOSTCC`
produces code for the host system. See [Build Environment Variables][4] for more
details.
If an emulator is necessary to run the bootstrap binaries, it can be set with
the environment variable `GEN_EMU`.
<a name="build-environment-variables"/>
## Build Environment Variables
This `bc` supports `CC`, `HOSTCC`, `HOST_CC`, `CFLAGS`, `HOSTCFLAGS`,
`HOST_CFLAGS`, `CPPFLAGS`, `LDFLAGS`, `LDLIBS`, `PREFIX`, `DESTDIR`, `BINDIR`,
`DATAROOTDIR`, `DATADIR`, `MANDIR`, `MAN1DIR`, `LOCALEDIR` `EXECSUFFIX`,
`EXECPREFIX`, `LONG_BIT`, `GEN_HOST`, and `GEN_EMU` environment variables in
`configure.sh`. Any values of those variables given to `configure.sh` will be
put into the generated Makefile.
More detail on what those environment variables do can be found in the following
sections.
### `CC`
C compiler for the target system. `CC` must be compatible with POSIX `c99`
behavior and options. However, **I encourage users to use any C99 or C11
compatible compiler they wish.**
If there is a space in the basename of the compiler, the items after the first
space are assumed to be compiler flags, and in that case, the flags are
automatically moved into CFLAGS.
Defaults to `c99`.
### `HOSTCC` or `HOST_CC`
C compiler for the host system, used only in [cross compiling][6]. Must be
compatible with POSIX `c99` behavior and options.
If there is a space in the basename of the compiler, the items after the first
space are assumed to be compiler flags, and in that case, the flags are
automatically moved into HOSTCFLAGS.
Defaults to `$CC`.
### `CFLAGS`
Command-line flags that will be passed verbatim to `CC`.
Defaults to empty.
### `HOSTCFLAGS` or `HOST_CFLAGS`
Command-line flags that will be passed verbatim to `HOSTCC` or `HOST_CC`.
Defaults to `$CFLAGS`.
### `CPPFLAGS`
Command-line flags for the C preprocessor. These are also passed verbatim to
both compilers (`CC` and `HOSTCC`); they are supported just for legacy reasons.
Defaults to empty.
### `LDFLAGS`
Command-line flags for the linker. These are also passed verbatim to both
compilers (`CC` and `HOSTCC`); they are supported just for legacy reasons.
Defaults to empty.
### `LDLIBS`
Libraries to link to. These are also passed verbatim to both compilers (`CC` and
`HOSTCC`); they are supported just for legacy reasons and for cross compiling
with different C standard libraries (like [musl][3]).
Defaults to empty.
### `PREFIX`
The prefix to install to.
Can be overridden by passing the `--prefix` option to `configure.sh`.
Defaults to `/usr/local`.
### `DESTDIR`
Path to prepend onto `PREFIX`. This is mostly for distro and package
maintainers.
This can be passed either to `configure.sh` or `make install`. If it is passed
to both, the one given to `configure.sh` takes precedence.
Defaults to empty.
### `BINDIR`
The directory to install binaries in.
Can be overridden by passing the `--bindir` option to `configure.sh`.
Defaults to `$PREFIX/bin`.
### `DATAROOTDIR`
The root directory to install data files in.
Can be overridden by passing the `--datarootdir` option to `configure.sh`.
Defaults to `$PREFIX/share`.
### `DATADIR`
The directory to install data files in.
Can be overridden by passing the `--datadir` option to `configure.sh`.
Defaults to `$DATAROOTDIR`.
### `MANDIR`
The directory to install manpages in.
Can be overridden by passing the `--mandir` option to `configure.sh`.
Defaults to `$DATADIR/man`
### `MAN1DIR`
The directory to install Section 1 manpages in. Because both `bc` and `dc` are
Section 1 commands, this is the only relevant section directory.
Can be overridden by passing the `--man1dir` option to `configure.sh`.
Defaults to `$MANDIR/man1`.
### `LOCALEDIR`
The directory to install locales in.
Can be overridden by passing the `--localedir` option to `configure.sh`.
Defaults to `$DATAROOTDIR/locale`.
### `EXECSUFFIX`
The suffix to append onto the executable names *when installing*. This is for
packagers and distro maintainers who want this `bc` as an option, but do not
want to replace the default `bc`.
Defaults to empty.
### `EXECPREFIX`
The prefix to append onto the executable names *when building and installing*.
This is for packagers and distro maintainers who want this `bc` as an option,
but do not want to replace the default `bc`.
Defaults to empty.
### `LONG_BIT`
The number of bits in a C `long` type. This is mostly for the embedded space.
This `bc` uses `long`s internally for overflow checking. In C99, a `long` is
required to be 32 bits. For this reason, on 8-bit and 16-bit microcontrollers,
the generated code to do math with `long` types may be inefficient.
For most normal desktop systems, setting this is unnecessary, except that 32-bit
platforms with 64-bit longs may want to set it to `32`.
Defaults to the default value of `LONG_BIT` for the target platform. For
compliance with the `bc` spec, the minimum allowed value is `32`.
It is an error if the specified value is greater than the default value of
`LONG_BIT` for the target platform.
### `GEN_HOST`
Whether to use `gen/strgen.c`, instead of `gen/strgen.sh`, to produce the C
files that contain the help texts as well as the math libraries. By default,
`gen/strgen.c` is used, compiled by `$HOSTCC` and run on the host machine. Using
`gen/strgen.sh` removes the need to compile and run an executable on the host
machine since `gen/strgen.sh` is a POSIX shell script. However, `gen/lib2.bc` is
perilously close to 4095 characters, the max supported length of a string
literal in C99 (and it could be added to in the future), and `gen/strgen.sh`
generates a string literal instead of an array, as `gen/strgen.c` does. For most
production-ready compilers, this limit probably is not enforced, but it could
be. Both options are still available for this reason.
If you are sure your compiler does not have the limit and do not want to compile
and run a binary on the host machine, set this variable to "0". Any other value,
or a non-existent value, will cause the build system to compile and run
`gen/strgen.c`.
Default is "".
### `GEN_EMU`
The emulator to run bootstrap binaries under. This is only if the binaries
produced by `HOSTCC` (or `HOST_CC`) need to be run under an emulator to work.
Defaults to empty.
<a name="build-options"/>
## Build Options
This `bc` comes with several build options, all of which are enabled by default.
All options can be used with each other, with a few exceptions that will be
noted below.
**NOTE**: All long options with mandatory argumenst accept either one of the
following forms:
```
--option arg
--option=arg
```
### `bc` Only
To build `bc` only (no `dc`), use any one of the following commands for the
configure step:
```
./configure.sh -b
./configure.sh --bc-only
./configure.sh -D
./configure.sh --disable-dc
```
Those commands are all equivalent.
***Warning***: It is an error to use those options if `bc` has also been
disabled (see below).
### `dc` Only
To build `dc` only (no `bc`), use either one of the following commands for the
configure step:
```
./configure.sh -d
./configure.sh --dc-only
./configure.sh -B
./configure.sh --disable-bc
```
Those commands are all equivalent.
***Warning***: It is an error to use those options if `dc` has also been
disabled (see above).
<a name="build-history"/>
### History
To disable signal handling, pass either the `-H` flag or the `--disable-history`
option to `configure.sh`, as follows:
```
./configure.sh -H
./configure.sh --disable-history
```
Both commands are equivalent.
History is automatically disabled when building for Windows or on another
platform that does not support the terminal handling that is required.
***WARNING***: Of all of the code in the `bc`, this is the only code that is not
completely portable. If the `bc` does not work on your platform, your first step
should be to retry with history disabled.
### NLS (Locale Support)
To disable locale support (use only English), pass either the `-N` flag or the
`--disable-nls` option to `configure.sh`, as follows:
```
./configure.sh -N
./configure.sh --disable-nls
```
Both commands are equivalent.
NLS (locale support) is automatically disabled when building for Windows or on
another platform that does not support the POSIX locale API or utilities.
### Prompt
By default, `bc` and `dc` print a prompt when in interactive mode. They both
have the command-line option `-P`/`--no-prompt`, which turns that off, but it
can be disabled permanently in the build by passing the `-P` flag or the
`--disable-prompt` option to `configure.sh`, as follows:
```
./configure.sh -P
./configure.sh --disable-prompt
```
Both commands are equivalent.
### Long Options
By default, `bc` and `dc` support long options like `--mathlib` and
`--interactive`. However, support for these options requires `getopt_long()`
which is not in the POSIX standard. For those platforms that do *not* have
`getopt_long()` it will be disabled automatically, or if you wish to disable
them regardless, you can pass the `-L` flag or the `--disable-long-options`
option to `configure.sh`, as follows:
```
./configure.sh -L
./configure.sh --disable-long-options
```
Both commands are equivalent.
### Extra Math
This `bc` has 7 extra operators:
* `$` (truncation to integer)
* `@` (set precision)
* `@=` (set precision and assign)
* `<<` (shift number left, shifts radix right)
* `<<=` (shift number left and assign)
* `>>` (shift number right, shifts radix left)
* `>>=` (shift number right and assign)
There is no assignment version of `$` because it is a unary operator.
The assignment versions of the above operators are not available in `dc`, but
the others are, as the operators `$`, `@`, `H`, and `h`, respectively.
In addition, this `bc` has the option of outputting in scientific notation or
engineering notation. It can also take input in scientific or engineering
notation. On top of that, it has a pseudo-random number generator. (See the
[full manual](./bc.md) for more details.)
Extra operators, scientific notation, engineering notation, and the
pseudo-random number generator can be disabled by passing either the `-E` flag
or the `--disable-extra-math` option to `configure.sh`, as follows:
```
./configure.sh -E
./configure.sh --disable-extra-math
```
Both commands are equivalent.
This `bc` also has a larger library that is only enabled if extra operators and
the pseudo-random number generator are. More information about the functions can
be found in the [Extended Library](./bc.md#extended-library) section of the
[full manual](./bc.md).
### Manpages
To disable installing manpages, pass either the `-M` flag or the
`--disable-man-pages` option to `configure.sh` as follows:
```
./configure.sh -M
./configure.sh --disable-man-pages
```
Both commands are equivalent.
### Karatsuba Length
The Karatsuba length is the point at which `bc` and `dc` switch from Karatsuba
multiplication to brute force, `O(n^2)` multiplication. It can be set by passing
the `-k` flag or the `--karatsuba-len` option to `configure.sh` as follows:
```
./configure.sh -k64
./configure.sh --karatsuba-len 64
```
Both commands are equivalent.
Default is `64`.
***WARNING***: The Karatsuba Length must be a **integer** greater than or equal
to `16` (to prevent stack overflow). If it is not, `configure.sh` will give an
error.
### Install Options
The relevant `autotools`-style install options are supported in `configure.sh`:
* `--prefix`
* `--bindir`
* `--datarootdir`
* `--datadir`
* `--mandir`
* `--man1dir`
* `--localedir`
An example is:
```
./configure.sh --prefix=/usr --localedir /usr/share/nls
make
make install
```
They correspond to the environment variables `$PREFIX`, `$BINDIR`,
`$DATAROOTDIR`, `$DATADIR`, `$MANDIR`, `$MAN1DIR`, and `$LOCALEDIR`,
respectively.
***WARNING***: If the option is given, the value of the corresponding
environment variable is overridden.
***WARNING***: If any long command-line options are used, the long form of all
other command-line options must be used. Mixing long and short options is not
supported.
## Optimization
The `configure.sh` script will accept an optimization level to pass to the
compiler. Because `bc` is orders of magnitude faster with optimization, I
***highly*** recommend package and distro maintainers pass the highest
optimization level available in `CC` to `configure.sh` with the `-O` flag or
`--opt` option, as follows:
```
./configure.sh -O3
./configure.sh --opt 3
```
Both commands are equivalent.
The build and install can then be run as normal:
```
make
make install
```
As usual, `configure.sh` will also accept additional `CFLAGS` on the command
line, so for SSE4 architectures, the following can add a bit more speed:
```
CFLAGS="-march=native -msse4" ./configure.sh -O3
make
make install
```
Building with link-time optimization (`-flto` in clang) can further increase the
performance. I ***highly*** recommend doing so.
I do **NOT*** recommend building with `-march=native`; doing so reduces this
`bc`'s performance.
Manual stripping is not necessary; non-debug builds are automatically stripped
in the link stage.
## Debug Builds
Debug builds (which also disable optimization if no optimization level is given
and if no extra `CFLAGS` are given) can be enabled with either the `-g` flag or
the `--debug` option, as follows:
```
./configure.sh -g
./configure.sh --debug
```
Both commands are equivalent.
The build and install can then be run as normal:
```
make
make install
```
## Stripping Binaries
By default, when `bc` and `dc` are not built in debug mode, the binaries are
stripped. Stripping can be disabled with either the `-T` or the
`--disable-strip` option, as follows:
```
./configure.sh -T
./configure.sh --disable-strip
```
Both commands are equivalent.
The build and install can then be run as normal:
```
make
make install
```
## Binary Size
When built with both calculators, all available features, and `-Os` using
`clang` and `musl`, the executable is 140.4 kb (140,386 bytes) on `x86_64`. That
isn't much for what is contained in the binary, but if necessary, it can be
reduced.
The single largest user of space is the `bc` calculator. If just `dc` is needed,
the size can be reduced to 107.6 kb (107,584 bytes).
The next largest user of space is history support. If that is not needed, size
can be reduced (for a build with both calculators) to 119.9 kb (119,866 bytes).
There are several reasons that history is a bigger user of space than `dc`
itself:
* `dc`'s lexer and parser are *tiny* compared to `bc`'s because `dc` code is
almost already in the form that it is executed in, while `bc` has to not only
adjust the form to be executable, it has to parse functions, loops, `if`
statements, and other extra features.
* `dc` does not have much extra code in the interpreter.
* History has a lot of const data for supporting `UTF-8` terminals.
* History pulls in a bunch of more code from the `libc`.
The next biggest user is extra math support. Without it, the size is reduced to
124.0 kb (123,986 bytes) with history and 107.6 kb (107,560 bytes) without
history.
The reasons why extra math support is bigger than `dc`, besides the fact that
`dc` is small already, are:
* Extra math supports adds an extra math library that takes several kilobytes of
constant data space.
* Extra math support includes support for a pseudo-random number generator,
including the code to convert a series of pseudo-random numbers into a number
of arbitrary size.
* Extra math support adds several operators.
The next biggest user is `dc`, so if just `bc` is needed, the size can be
reduced to 128.1 kb (128,096 bytes) with history and extra math support, 107.6
kb (107,576 bytes) without history and with extra math support, and 95.3 kb
(95,272 bytes) without history and without extra math support.
*Note*: all of these binary sizes were compiled using `musl` `1.2.0` as the
`libc`, making a fully static executable, with `clang` `9.0.1` (well,
`musl-clang` using `clang` `9.0.1`) as the compiler and using `-Os`
optimizations. These builds were done on an `x86_64` machine running Gentoo
Linux.
## Testing
The default test suite can be run with the following command:
```
make test
```
To test `bc` only, run the following command:
```
make test_bc
```
To test `dc` only, run the following command:
```
make test_dc
```
This `bc`, if built, assumes a working, GNU-compatible `bc`, installed on the
system and in the `PATH`, to generate some tests, unless the `-G` flag or
`--disable-generated-tests` option is given to `configure.sh`, as follows:
```
./configure.sh -G
./configure.sh --disable-generated-tests
```
After running `configure.sh`, build and run tests as follows:
```
make
make test
```
This `dc` also assumes a working, GNU-compatible `dc`, installed on the system
and in the `PATH`, to generate some tests, unless one of the above options is
given to `configure.sh`.
To generate test coverage, pass the `-c` flag or the `--coverage` option to
`configure.sh` as follows:
```
./configure.sh -c
./configure.sh --coverage
```
Both commands are equivalent.
***WARNING***: Both `bc` and `dc` must be built for test coverage. Otherwise,
`configure.sh` will give an error.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://www.musl-libc.org/
[4]: #build-environment-variables
[5]: #build-options
[6]: #cross-compiling

951
contrib/bc/manuals/dc.1 Normal file
View File

@ -0,0 +1,951 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "DC" "1" "June 2020" "Gavin D. Howard" "General Commands Manual"
.
.SH "NAME"
\fBdc\fR \- arbitrary\-precision reverse\-Polish notation calculator
.
.SH "SYNOPSIS"
\fBdc\fR [\fB\-hiPvVx\fR] [\fB\-\-version\fR] [\fB\-\-help\fR] [\fB\-\-interactive\fR] [\fB\-\-no\-prompt\fR] [\fB\-\-extended\-register\fR] [\fB\-e\fR \fIexpr\fR] [\fB\-\-expression=\fR\fIexpr\fR\.\.\.] [\fB\-f\fR \fIfile\fR\.\.\.] [\fB\-file=\fR\fIfile\fR\.\.\.] [\fIfile\fR\.\.\.]
.
.SH "DESCRIPTION"
dc(1) is an arbitrary\-precision calculator\. It uses a stack (reverse Polish notation) to store numbers and results of computations\. Arithmetic operations pop arguments off of the stack and push the results\.
.
.P
If no files are given on the command\-line as extra arguments (i\.e\., not as \fB\-f\fR or \fB\-\-file\fR arguments), then dc(1) reads from \fBstdin\fR\. Otherwise, those files are processed, and dc(1) will then exit\.
.
.P
This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \fB\-e\fR (\fB\-\-expression\fR) and \fB\-f\fR (\fB\-\-file\fR) arguments cause dc(1) to execute them and exit\. The reason for this is that this dc(1) allows users to set arguments in the environment variable \fBDC_ENV_ARGS\fR (see the ENVIRONMENT VARIABLES section)\. Any expressions given on the command\-line should be used to set up a standard environment\. For example, if a user wants the \fBscale\fR always set to \fB10\fR, they can set \fBDC_ENV_ARGS\fR to "\-e 10k", and this dc(1) will always start with a \fBscale\fR of \fB10\fR\.
.
.P
If users want to have dc(1) exit after processing all input from \fB\-e\fR and \fB\-f\fR arguments (and their equivalents), then they can just simply add "\-e q" as the last command\-line argument or define the environment variable \fBDC_EXPR_EXIT\fR\.
.
.SH "OPTIONS"
The following are the options that dc(1) accepts\.
.
.TP
\fB\-h\fR, \fB\-\-help\fR
Prints a usage message and quits\.
.
.TP
\fB\-v\fR, \fB\-V\fR, \fB\-\-version\fR
Print the version information (copyright header) and exit\.
.
.TP
\fB\-i\fR, \fB\-\-interactive\fR
Forces interactive mode\. (See the INTERACTIVE MODE section\.)
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB\-P\fR, \fB\-\-no\-prompt\fR
Disables the prompt in interactive mode\. This is mostly for those users that do not want a prompt or are not used to having them in \fBdc\fR\. Most of those users would want to put this option in \fBDC_ENV_ARGS\fR\.
.
.IP
If the prompt has been disabled while building dc(1), this option is a no\-op\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB\-x\fR \fB\-\-extended\-register\fR
Enables extended register mode\. See the REGISTERS section for more information\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB\-e\fR \fIexpr\fR, \fB\-\-expression\fR=\fIexpr\fR
Evaluates \fBexpr\fR\. If multiple expressions are given, they are evaluated in order\. If files are given as well (see below), the expressions and files are evaluated in the order given\. This means that if a file is given before an expression, the file is read in and evaluated first\.
.
.IP
In other dc(1) implementations, this option causes the program to execute the expressions and then exit\. This dc(1) does not, unless the \fBDC_EXPR_EXIT\fR is defined (see the ENVIRONMENT VARIABLES section)\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB\-f\fR \fIfile\fR, \fB\-\-file\fR=\fIfile\fR
Reads in \fBfile\fR and evaluates it\. If expressions are also given (see above), the expressions are evaluated in the order given\.
.
.IP
In other dc(1) implementations, this option causes the program to execute the files and then exit\. This dc(1) does not, unless the \fBDC_EXPR_EXIT\fR is defined (see the ENVIRONMENT VARIABLES section)\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.P
\fBNote\fR: long options are only accepted if dc(1) is built with them enabled\.
.
.SH "STDOUT"
Any non\-error output is written to \fBstdout\fR\.
.
.P
\fBNote\fR: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the EXIT STATUS section) if it cannot write to \fBstdout\fR, so if \fBstdout\fR is closed, as in \fBdc <file> >&\-\fR, it will quit with an error\. This is done so that dc(1) can report problems when \fBstdout\fR is redirected to a file\.
.
.P
If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \fBstdout\fR to \fB/dev/null\fR\.
.
.SH "STDERR"
Any error output is written to \fBstderr\fR\.
.
.P
\fBNote\fR: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the EXIT STATUS section) if it cannot write to \fBstderr\fR, so if \fBstderr\fR is closed, as in \fBdc <file> 2>&\-\fR, it will quit with an error\. This is done so that dc(1) can report problems when \fBstderr\fR is redirected to a file\.
.
.P
If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \fBstderr\fR to \fB/dev/null\fR\.
.
.SH "SYNTAX"
\fBibase\fR is a register (see the REGISTERS section) determining how to interpret constant numbers\. It is the "input" base, or the number base used for interpreting input numbers\. \fBibase\fR is initially \fB10\fR\. The max allowable value for \fBibase\fR is \fB16\fR\. The min allowable value for \fBibase\fR is \fB2\fR\. The max allowable value for \fBibase\fR can be queried in dc(1) programs with the \fBT\fR command\.
.
.P
\fBobase\fR is a register (see the REGISTERS section) determining how to output results\. It is the "output" base, or the number base used for outputting numbers\. \fBobase\fR is initially \fB10\fR\. The max allowable value for \fBobase\fR is \fBDC_BASE_MAX\fR\. The min allowable value for \fBobase\fR is \fB2\fR unless dc(1) was built with the extra math option\. If it was, then the min allowable value is \fB0\fR\. In this case, if \fBobase\fR is \fB0\fR, values are output in scientific notation, and if \fBobase\fR is \fB1\fR, values are output in engineering notation\. (Outputting in scientific or engineering notation are \fBnon\-portable extensions\fR\.) The max allowable value for \fBobase\fR can be queried in dc(1) programs with the \fBU\fR command\.
.
.P
The \fBscale\fR of an expression is the number of digits in the result of the expression right of the decimal point, and \fBscale\fR is a register (see the REGISTERS section) that sets the precision of any operations (with exceptions)\. \fBscale\fR is initially \fB0\fR\. \fBscale\fR cannot be negative\. The max allowable value for \fBscale\fR can be queried in dc(1) programs with the \fBV\fR command\.
.
.P
Each item in the input source code, either a number (see the NUMBERS section) or a command (see the COMMANDS section), is processed and executed, in order\. Input is processed immediately when entered\.
.
.P
If dc(1) was built with the extra math option, there is an additional register named \fBseed\fR\. This is the current seed used by the pseudo\-random number generator\. If the current value of \fBseed\fR is queried and stored, then if it is assigned to \fBseed\fR later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \fBseed\fR was first queried\.
.
.P
Multiple values assigned to \fBseed\fR can produce the same sequence of pseudo\-random numbers\. Likewise, when a value is assigned to \fBseed\fR, it is not guaranteed that querying \fBseed\fR immediately after will return the same value\. In addition, the value of \fBseed\fR will change after any call to the \fB'\fR or \fB"\fR commands\. The maximum integer returned by the \fB'\fR command can be queried with the \fBW\fR command\.
.
.P
\fBNote\fR: The values returned by the pseudo\-random number generator with the \fB'\fR and \fB"\fR commands are guaranteed to \fBNOT\fR be cryptographically\-secure\. This is a consequence of using a seeded pseudo\-random number generator\. However, they \fBare\fR guaranteed to be reproducible with identical \fBseed\fR values\.
.
.P
The pseudo\-random number generator, \fBseed\fR, and all associated operations are \fBnon\-portable extensions\fR\.
.
.SS "Comments"
Comments go from \fB#\fR until, and not including, the next newline\. This is a \fBnon\-portable extension\fR\.
.
.SH "NUMBERS"
Numbers are strings made up of digits, uppercase letters up to \fBF\fR, and at most \fB1\fR period for a radix\. Numbers can have up to \fBDC_NUM_MAX\fR digits\. Uppercase letters equal \fB9\fR + their position in the alphabet (i\.e\., \fBA\fR equals \fB10\fR, or \fB9 + 1\fR)\. If a digit or letter makes no sense with the current value of \fBibase\fR, they are set to the value of the highest valid digit in \fBibase\fR\.
.
.P
Single\-character numbers (i\.e\., \fBA\fR) take the value that they would have if they were valid digits, regardless of the value of \fBibase\fR\. This means that \fBA\fR always equals decimal \fB10\fR and \fBF\fR always equals decimal \fB15\fR\.
.
.P
In addition, if dc(1) was built with the extra math option, it accepts numbers in scientific notation\. For dc(1), an example is \fB1\.89237e9\fR, which is equal to \fB1892370000\fR\. Negative exponents are also allowed, so \fB4\.2890e_3\fR is equal to \fB0\.0042890\fR\.
.
.P
\fBWARNING\fR: Both the number and the exponent in scientific notation are interpreted according to the current \fBibase\fR, but the number is still multiplied by \fB10^exponent\fR regardless of the current \fBibase\fR\. For example, if \fBibase\fR is \fB16\fR and dc(1) is given the number string \fB"FFeA"\fR, the resulting decimal number will be \fB2550000000000\fR, and if dc(1) is given the number string \fB"10e_4"\fR, the resulting decimal number will be \fB0\.0016\fR\.
.
.P
Accepting input as scientific notation is a \fBnon\-portable extension\fR\.
.
.SH "COMMANDS"
The valid commands are listed below\.
.
.SS "Printing"
These commands are used for printing\.
.
.P
Note that if dc(1) has been built with the extra math option enabled, both scientific notation and engineering notation are available for printing numbers\. Scientific notation is activated by assigning \fB0\fR to \fBobase\fR using \fB0o\fR (in any other context, an \fBobase\fR of \fB0\fR is invalid), and engineering notation is activated by assigning \fB1\fR to \fBobase\fR using \fB1o\fR (which is also invalid in any other context)\. To deactivate them, just assign a different value to \fBobase\fR\.
.
.P
Printing numbers in scientific notation and/or engineering notation is a \fBnon\-portable extension\fR\.
.
.TP
\fBp\fR
Prints the value on top of the stack, whether number or string, and prints a newline after\.
.
.IP
This does not alter the stack\.
.
.TP
\fBn\fR
Prints the value on top of the stack, whether number or string, and pops it off of the stack\.
.
.TP
\fBP\fR
Pops a value off the stack\.
.
.IP
If the value is a number, it is truncated and the absolute value of the result is printed as though \fBobase\fR is \fBUCHAR_MAX + 1\fR and each digit is interpreted as an ASCII character, making it a byte stream\.
.
.IP
If the value is a string, it is printed without a trailing newline\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBf\fR
Prints the entire contents of the stack, in order from newest to oldest, without altering anything\.
.
.IP
Users should use this command when they get lost\.
.
.SS "Arithmetic"
These are the commands used for arithmetic\.
.
.TP
\fB+\fR
The top two values are popped off the stack, added, and the result is pushed onto the stack\. The \fBscale\fR of the result is equal to the max \fBscale\fR of both operands\.
.
.TP
\fB\-\fR
The top two values are popped off the stack, subtracted, and the result is pushed onto the stack\. The \fBscale\fR of the result is equal to the max \fBscale\fR of both operands\.
.
.TP
\fB*\fR
The top two values are popped off the stack, multiplied, and the result is pushed onto the stack\. If \fBa\fR is the \fBscale\fR of the first expression and \fBb\fR is the \fBscale\fR of the second expression, the \fBscale\fR of the result is equal to \fBmin(a+b,max(scale,a,b))\fR where \fBmin\fR and \fBmax\fR return the obvious values\.
.
.TP
\fB/\fR
The top two values are popped off the stack, divided, and the result is pushed onto the stack\. The \fBscale\fR of the result is equal to \fBscale\fR\.
.
.IP
The first value popped off of the stack must be non\-zero\.
.
.TP
\fB%\fR
The top two values are popped off the stack, remaindered, and the result is pushed onto the stack\.
.
.IP
Remaindering is equivalent to 1) Computing \fBa/b\fR to current \fBscale\fR, and 2) Using the result of step 1 to calculate \fBa\-(a/b)*b\fR to \fBscale\fR \fBmax(scale + scale(b), scale(a))\fR\.
.
.IP
The first value popped off of the stack must be non\-zero\.
.
.TP
\fB~\fR
The top two values are popped off the stack, divided and remaindered, and the results (divided first, remainder second) are pushed onto the stack\. This is equivalent to \fBx y / x y %\fR except that \fBx\fR and \fBy\fR are only evaluated once\.
.
.IP
The first value popped off of the stack must be non\-zero\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB^\fR
The top two values are popped off the stack, the second is raised to the power of the first, and the result is pushed onto the stack\.
.
.IP
The first value popped off of the stack must be an integer, and if that value is negative, the second value popped off of the stack must be non\-zero\.
.
.TP
\fBv\fR
The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack\. The \fBscale\fR of the result is equal to \fBscale\fR\.
.
.IP
The value popped off of the stack must be non\-negative\.
.
.TP
\fB_\fR
If this command \fIimmediately\fR precedes a number (i\.e\., no spaces or other commands), then that number is input as a negative number\.
.
.IP
Otherwise, the top value on the stack is popped and copied, and the copy is negated and pushed onto the stack\. This behavior without a number is a \fBnon\-portable extension\fR\.
.
.TP
\fBb\fR
The top value is popped off the stack, and if it is zero, it is pushed back onto the stack\. Otherwise, its absolute value is pushed onto the stack\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB|\fR
The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack\.
.
.IP
The first value popped is used as the reduction modulus and must be an integer and non\-zero\. The second value popped is used as the exponent and must be an integer and non\-negative\. The third value popped is the base and must be an integer\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB$\fR
The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB@\fR
The top two values are popped off the stack, and the precision of the second is set to the value of the first, whether by truncation or extension\.
.
.IP
The first value popped off of the stack must be an integer and non\-negative\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBH\fR
The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first\.
.
.IP
The first value popped off of the stack must be an integer and non\-negative\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBh\fR
The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first\.
.
.IP
The first value popped off of the stack must be an integer and non\-negative\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBG\fR
The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if they are equal, or \fB0\fR otherwise\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBN\fR
The top value is popped off of the stack, and if it a \fB0\fR, a \fB1\fR is pushed; otherwise, a \fB0\fR is pushed\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB(\fR
The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if the first is less than the second, or \fB0\fR otherwise\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB{\fR
The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if the first is less than or equal to the second, or \fB0\fR otherwise\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB)\fR
The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if the first is greater than the second, or \fB0\fR otherwise\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB}\fR
The top two values are popped off of the stack, they are compared, and a \fB1\fR is pushed if the first is greater than or equal to the second, or \fB0\fR otherwise\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBM\fR
The top two values are popped off of the stack\. If they are both non\-zero, a \fB1\fR is pushed onto the stack\. If either of them is zero, or both of them are, then a \fB0\fR is pushed onto the stack\.
.
.IP
This is like the \fB&&\fR operator in bc(1), and it is not a short\-circuit operator\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBm\fR
The top two values are popped off of the stack\. If at least one of them is non\-zero, a \fB1\fR is pushed onto the stack\. If both of them are zero, then a \fB0\fR is pushed onto the stack\.
.
.IP
This is like the \fB||\fR operator in bc(1), and it is not a short\-circuit operator\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.SS "Pseudo\-Random Number Generator"
If dc(1) was built with the extra math option, it has a built\-in pseudo\-random number generator\. These commands query the pseudo\-random number generator\. (See Parameters for more information about the \fBseed\fR value that controls the pseudo\-random number generator\.)
.
.P
The pseudo\-random number generator is guaranteed to \fBNOT\fR be cryptographically\-secure\.
.
.TP
\fB'\fR
Generates an integer between 0 and \fBDC_RAND_MAX\fR, inclusive (see the LIMITS section)\.
.
.IP
The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator\.
.
.IP
This command is only available if dc(1) was built with the extra math option\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB"\fR
Pops a value off of the stack, which is used as an \fBexclusive\fR upper bound on the integer that will be generated\. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the RESET section)\. If the bound is larger than \fBDC_RAND_MAX\fR, the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \fBDC_RAND_MAX + 1\fR, and adding them together\. Thus, the size of integer that can be generated with this command is unbounded\. Using this command will change the value of \fBseed\fR\.
.
.IP
If the operand is \fB0\fR or \fB1\fR, then the result pushed onto the stack is \fB0\fR, and \fBseed\fR is not changed\.
.
.IP
The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator\.
.
.IP
This command is only available if dc(1) was built with the extra math option\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.SS "Stack Control"
These commands control the stack\.
.
.TP
\fBc\fR
Removes all items from ("clears") the stack\.
.
.TP
\fBd\fR
Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack\.
.
.TP
\fBr\fR
Swaps ("reverses") the two top items on the stack\.
.
.TP
\fBR\fR
Pops ("removes") the top value from the stack\.
.
.SS "Register Control"
These commands control registers (see the REGISTERS section)\.
.
.TP
\fBs\fR\fIr\fR
Pops the value off the top of the stack and stores it into register \fBr\fR\.
.
.TP
\fBl\fR\fIr\fR
Copies the value in register \fBr\fR and pushes it onto the stack\. This does not alter the contents of \fBr\fR\.
.
.TP
\fBS\fR\fIr\fR
Pops the value off the top of the (main) stack and pushes it onto the stack of register \fBr\fR\. The previous value of the register becomes inaccessible\.
.
.TP
\fBL\fR\fIr\fR
Pops the value off the top of the stack for register \fBr\fR and push it onto the main stack\. The previous value in the stack for register \fBr\fR, if any, is now accessible via the \fBl\fR\fIr\fR command\.
.
.SS "Parameters"
These commands control the values of \fBibase\fR, \fBobase\fR, \fBscale\fR, and \fBseed\fR (if dc(1) was built with the extra math option)\. Also see the SYNTAX section\.
.
.TP
\fBi\fR
Pops the value off of the top of the stack and uses it to set \fBibase\fR, which must be between \fB2\fR and \fB16\fR, inclusive\.
.
.IP
If the value on top of the stack has any \fBscale\fR, the \fBscale\fR is ignored\.
.
.TP
\fBo\fR
Pops the value off of the top of the stack and uses it to set \fBobase\fR, which must be between \fB2\fR and \fBDC_BASE_MAX\fR, inclusive (see bc(1))\. The value can be either \fB0\fR or \fB1\fR if dc(1) was built with the extra math option\.
.
.IP
If the value on top of the stack has any \fBscale\fR, the \fBscale\fR is ignored\.
.
.TP
\fBk\fR
Pops the value off of the top of the stack and uses it to set \fBscale\fR, which must be non\-negative\.
.
.IP
If the value on top of the stack has any \fBscale\fR, the \fBscale\fR is ignored\.
.
.TP
\fBj\fR
Pops the value off of the top of the stack and uses it to set \fBseed\fR\. The meaning of \fBseed\fR is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions\.
.
.IP
The \fBscale\fR of the value may be significant\.
.
.IP
If a previously used \fBseed\fR value is used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \fBseed\fR value was previously used\.
.
.IP
The exact value assigned to \fBseed\fR is not guaranteed to be returned if the \fBJ\fR command is used\. However, if \fBseed\fR \fIdoes\fR return a different value, both values, when assigned to \fBseed\fR, are guaranteed to produce the same sequence of pseudo\-random numbers\. This means that certain values assigned to \fBseed\fR will not produce unique sequences of pseudo\-random numbers\.
.
.IP
There is no limit to the length (number of significant decimal digits) or \fIscale\fR of the value that can be assigned to \fBseed\fR\.
.
.IP
This command is only available if dc(1) was built with the extra math option\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBI\fR
Pushes the current value of \fBibase\fR onto the main stack\.
.
.TP
\fBO\fR
Pushes the current value of \fBobase\fR onto the main stack\.
.
.TP
\fBK\fR
Pushes the current value of \fBscale\fR onto the main stack\.
.
.TP
\fBJ\fR
Pushes the current value of \fBseed\fR onto the main stack\.
.
.IP
This command is only available if dc(1) was built with the extra math option\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBT\fR
Pushes the maximum allowable value of \fBibase\fR onto the main stack\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBU\fR
Pushes the maximum allowable value of \fBobase\fR onto the main stack\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBV\fR
Pushes the maximum allowable value of \fBscale\fR onto the main stack\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBW\fR
Pushes the maximum (inclusive) integer that can be generated with the \fB'\fR pseudo\-random number generator command\.
.
.IP
This command is only available if dc(1) was built with the extra math option\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.SS "Strings"
The following commands control strings\.
.
.P
dc(1) can work with both numbers and strings, and registers (see the REGISTERS section) can hold both strings and numbers\. dc(1) always knows whether the contents of a register are a string or a number\.
.
.P
While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings\.
.
.P
Strings can also be executed as macros\. For example, if the string \fB[1pR]\fR is executed as a macro, then the code \fB1pR\fR is executed, meaning that the \fB1\fR will be printed with a newline after and then popped from the stack\.
.
.TP
\fB[\fR\fIcharacters\fR\fB]\fR
Makes a string containing \fIcharacters\fR and pushes it onto the stack\.
.
.IP
If there are brackets (\fB[\fR and \fB]\fR) in the string, then they must be balanced\. Unbalanced brackets can be escaped using a backslash (\fB\e\fR) character\.
.
.IP
If there is a backslash character in the string, the character after it (even another backslash) is put into the string verbatim, but the (first) backslash is not\.
.
.TP
\fBa\fR
The value on top of the stack is popped\.
.
.IP
If it is a number, it is truncated and its absolute value is taken\. The result mod \fBUCHAR_MAX + 1\fR is calculated\. If that result is \fB0\fR, push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character\.
.
.IP
If it is a string, then a new string is made\. If the original string is empty, the new string is empty\. If it is not, then the first character of the original string is used to create the new string as a one\-character string\. The new string is then pushed onto the stack\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fBx\fR
Pops a value off of the top of the stack\.
.
.IP
If it is a number, it is pushed onto the stack\.
.
.IP
If it is a string, it is executed as a macro\.
.
.IP
This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below\.
.
.TP
\fB>\fR\fIr\fR
Pops two values off of the stack that must be numbers and compares them\. If the first value is greater than the second, then the contents of register \fBr\fR are executed\.
.
.IP
For example, \fB0 1>a\fR will execute the contents of register \fBa\fR, and \fB1 0>a\fR will not\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.TP
\fB>\fR\fIr\fR\fBe\fR\fIs\fR
Like the above, but will execute register \fBs\fR if the comparison fails\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB!>\fR\fIr\fR
Pops two values off of the stack that must be numbers and compares them\. If the first value is not greater than the second (less than or equal to), then the contents of register \fBr\fR are executed\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.TP
\fB!>\fR\fIr\fR\fBe\fR\fIs\fR
Like the above, but will execute register \fBs\fR if the comparison fails\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB<\fR\fIr\fR
Pops two values off of the stack that must be numbers and compares them\. If the first value is less than the second, then the contents of register \fBr\fR are executed\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.TP
\fB<\fR\fIr\fR\fBe\fR\fIs\fR
Like the above, but will execute register \fBs\fR if the comparison fails\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB!<\fR\fIr\fR
Pops two values off of the stack that must be numbers and compares them\. If the first value is not less than the second (greater than or equal to), then the contents of register \fBr\fR are executed\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.TP
\fB!<\fR\fIr\fR\fBe\fR\fIs\fR
Like the above, but will execute register \fBs\fR if the comparison fails\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB=\fR\fIr\fR
Pops two values off of the stack that must be numbers and compares them\. If the first value is equal to the second, then the contents of register \fBr\fR are executed\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.TP
\fB=\fR\fIr\fR\fBe\fR\fIs\fR
Like the above, but will execute register \fBs\fR if the comparison fails\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB!=\fR\fIr\fR
Pops two values off of the stack that must be numbers and compares them\. If the first value is not equal to the second, then the contents of register \fBr\fR are executed\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.TP
\fB!=\fR\fIr\fR\fBe\fR\fIs\fR
Like the above, but will execute register \fBs\fR if the comparison fails\.
.
.IP
If either or both of the values are not numbers, dc(1) will raise an error and reset (see the RESET section)\.
.
.IP
This is a \fBnon\-portable extension\fR\.
.
.TP
\fB?\fR
Reads a line from the \fBstdin\fR and executes it\. This is to allow macros to request input from users\.
.
.TP
\fBq\fR
During execution of a macro, this exits the execution of that macro and the execution of the macro that executed it\. If there are no macros, or only one macro executing, dc(1) exits\.
.
.TP
\fBQ\fR
Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack\. If the number of levels to pop is greater than the number of executing macros, dc(1) exits\.
.
.SS "Status"
These commands query status of the stack or its top value\.
.
.TP
\fBZ\fR
Pops a value off of the stack\.
.
.IP
If it is a number, calculates the number of significant decimal digits it has and pushes the result\.
.
.IP
If it is a string, pushes the number of characters the string has\.
.
.TP
\fBX\fR
Pops a value off of the stack\.
.
.IP
If it is a number, pushes the \fBscale\fR of the value onto the stack\.
.
.IP
If it is a string, pushes \fB0\fR\.
.
.TP
\fBz\fR
Pushes the current stack depth (before execution of this command)\.
.
.SS "Arrays"
These commands manipulate arrays\.
.
.TP
\fB:\fR\fIr\fR
Pops the top two values off of the stack\. The second value will be stored in the array \fBr\fR (see the REGISTERS section), indexed by the first value\.
.
.TP
\fB;\fR\fIr\fR
Pops the value on top of the stack and uses it as an index into the array \fBr\fR\. The selected value is then pushed onto the stack\.
.
.SH "REGISTERS"
Registers are names that can store strings, numbers, and arrays\. (Number/string registers do not interfere with array registers\.)
.
.P
Each register is also its own stack, so the current register value is the top of the stack for the register\. All registers, when first referenced, have one value (\fB0\fR) in their stack\.
.
.P
In non\-extended register mode, a register name is just the single character that follows any command that needs a register name\. The only exception is a newline (\fB\'\en\'\fR); it is a parse error for a newline to be used as a register name\.
.
.SS "Extended Register Mode"
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled\.
.
.P
If extended register mode is enabled (\fB\-x\fR or \fB\-\-extended\-register\fR command\-line arguments are given), then normal single character registers are used \fB\fIunless\fR\fR the character immediately following a command that needs a register name is a space (according to \fBisspace()\fR) and not a newline (\fB\'\en\'\fR)\.
.
.P
In that case, the register name is found according to the regex \fB[a\-z][a\-z0\-9_]*\fR (like bc(1)), and it is a parse error if the next non\-space characters do not match that regex\.
.
.SH "RESET"
When dc(1) encounters an error or a signal that it has a non\-default handler for, it resets\. This means that several things happen\.
.
.P
First, any macros that are executing are stopped and popped off the stack\. The behavior is not unlike that of exceptions in programming languages\. Then the execution point is set so that any code waiting to execute (after all functions returned) is skipped\.
.
.P
Thus, when dc(1) resets, it skips any remaining code waiting to be executed\. Then, if it is interactive mode, and the error was not a fatal error (see the EXIT STATUS section), it asks for more input; otherwise, it exits with the appropriate return code\.
.
.SH "PERFORMANCE"
Most dc(1) implementations use \fBchar\fR types to calculate the value of \fB1\fR decimal digit at a time, but that can be slow\. This dc(1) does something different\.
.
.P
It uses large integers to calculate more than \fB1\fR decimal digit at a time\. If built in a environment where \fBDC_LONG_BIT\fR (see the LIMITS section) is \fB64\fR, then each integer has \fB9\fR decimal digits\. If built in an environment where \fBDC_LONG_BIT\fR is \fB32\fR then each integer has \fB4\fR decimal digits\. This value (the number of decimal digits per large integer) is called \fBDC_BASE_DIGS\fR\.
.
.P
In addition, this dc(1) uses an even larger integer for overflow checking\. This integer type depends on the value of \fBDC_LONG_BIT\fR, but is always at least twice as large as the integer type used to store digits\.
.
.SH "LIMITS"
The following are the limits on dc(1):
.
.TP
\fBDC_LONG_BIT\fR
The number of bits in the \fBlong\fR type in the environment where dc(1) was built\. This determines how many decimal digits can be stored in a single large integer (see the PERFORMANCE section)\.
.
.TP
\fBDC_BASE_DIGS\fR
The number of decimal digits per large integer (see the PERFORMANCE section)\. Depends on \fBDC_LONG_BIT\fR\.
.
.TP
\fBDC_BASE_POW\fR
The max decimal number that each large integer can store (see \fBDC_BASE_DIGS\fR) plus \fB1\fR\. Depends on \fBDC_BASE_DIGS\fR\.
.
.TP
\fBDC_OVERFLOW_MAX\fR
The max number that the overflow type (see the PERFORMANCE section) can hold\. Depends on \fBDC_LONG_BIT\fR\.
.
.TP
\fBDC_BASE_DIGS\fR
The number of decimal digits per large integer (see the PERFORMANCE section)\.
.
.TP
\fBDC_BASE_MAX\fR
The maximum output base\. Set at \fBDC_BASE_POW\fR\.
.
.TP
\fBDC_DIM_MAX\fR
The maximum size of arrays\. Set at \fBSIZE_MAX\-1\fR\.
.
.TP
\fBDC_SCALE_MAX\fR
The maximum \fBscale\fR\. Set at \fBDC_OVERFLOW_MAX\-1\fR\.
.
.TP
\fBDC_STRING_MAX\fR
The maximum length of strings\. Set at \fBDC_OVERFLOW_MAX\-1\fR\.
.
.TP
\fBDC_NAME_MAX\fR
The maximum length of identifiers\. Set at \fBDC_OVERFLOW_MAX\-1\fR\.
.
.TP
\fBDC_NUM_MAX\fR
The maximum length of a number (in decimal digits), which includes digits after the decimal point\. Set at \fBDC_OVERFLOW_MAX\-1\fR\.
.
.TP
\fBDC_RAND_MAX\fR
The maximum integer (inclusive) returned by the \fB'\fR command, if dc(1) has been built with the extra math option\. Set at \fB2^DC_LONG_BIT\-1\fR\.
.
.TP
Exponent
The maximum allowable exponent (positive or negative)\. Set at \fBDC_OVERFLOW_MAX\fR\.
.
.TP
Number of vars
The maximum number of vars/arrays\. Set at \fBSIZE_MAX\-1\fR\.
.
.P
These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem\. In fact, memory should be exhausted before these limits should be hit\.
.
.SH "ENVIRONMENT VARIABLES"
dc(1) recognizes the following environment variables:
.
.TP
\fBDC_ENV_ARGS\fR
This is another way to give command\-line arguments to dc(1)\. They should be in the same format as all other command\-line arguments\. These are always processed first, so any files given in \fBDC_ENV_ARGS\fR will be processed before arguments and files given on the command\-line\. This gives the user the ability to set up "standard" options and files to be used at every invocation\. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs\. Another use would be to use the \fB\-e\fR option to set \fBscale\fR to a value other than \fB0\fR\.
.
.IP
The code that parses \fBDC_ENV_ARGS\fR will correctly handle quoted arguments, but it does not understand escape sequences\. For example, the string \fB"/home/gavin/some dc file\.dc"\fR will be correctly parsed, but the string \fB"/home/gavin/some \e"dc\e" file\.dc"\fR will include the backslashes\.
.
.IP
The quote parsing will handle either kind of quotes, \fB'\fR or \fB"\fR\. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \fB"some \'bc\' file\.bc"\fR, and vice versa if you have a file with double quotes\. However, handling a file with both kinds of quotes in \fBDC_ENV_ARGS\fR is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell\.
.
.TP
\fBDC_LINE_LENGTH\fR
If this environment variable exists and contains an integer that is greater than \fB1\fR and is less than \fBUINT16_MAX\fR (\fB2^16\-1\fR), dc(1) will output lines to that length, including the backslash newline combo\. The default line length is \fB70\fR\.
.
.TP
\fBDC_EXPR_EXIT\fR
If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \fB\-e\fR and/or \fB\-f\fR command\-line options (and any equivalents)\.
.
.SH "EXIT STATUS"
dc(1) returns the following exit statuses:
.
.TP
\fB0\fR
No error\.
.
.TP
\fB1\fR
A math error occurred\. This follows standard practice of using \fB1\fR for expected errors, since math errors will happen in the process of normal execution\.
.
.IP
Math errors include divide by \fB0\fR, taking the square root of a negative number, using a negative number as a bound for the pseudo\-random number generator, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required\.
.
.IP
Converting to a hardware integer happens for the second operand of the power (\fB^\fR), places (\fB@\fR), left shift (\fBH\fR), and right shift (\fBh\fR) operators\.
.
.TP
\fB2\fR
A parse error occurred\.
.
.IP
Parse errors include unexpected \fBEOF\fR, using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid\.
.
.TP
\fB3\fR
A runtime error occurred\.
.
.IP
Runtime errors include assigning an invalid number to \fBibase\fR, \fBobase\fR, or \fBscale\fR; give a bad expression to a \fBread()\fR call, calling \fBread()\fR inside of a \fBread()\fR call, type errors, and attempting an operation when the stack has too few elements\.
.
.TP
\fB4\fR
A fatal error occurred\.
.
.IP
Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (dc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options\.
.
.P
The exit status \fB4\fR is special; when a fatal error occurs, dc(1) always exits and returns \fB4\fR, no matter what mode dc(1) is in\.
.
.P
The other statuses will only be returned when dc(1) is not in interactive mode (see the INTERACTIVE MODE section), since dc(1) resets its state (see the RESET section) and accepts more input when one of those errors occurs in interactive mode\. This is also the case when interactive mode is forced by the \fB\-i\fR flag or \fB\-\-interactive\fR option\.
.
.P
These exit statuses allow dc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \fB\-i\fR flag or \fB\-\-interactive\fR option\.
.
.SH "INTERACTIVE MODE"
Like bc(1), dc(1) has an interactive mode and a non\-interactive mode\. Interactive mode is turned on automatically when both \fBstdin\fR and \fBstdout\fR are hooked to a terminal, but the \fB\-i\fR flag and \fB\-\-interactive\fR option can turn it on in other cases\.
.
.P
In interactive mode, dc(1) attempts to recover from errors (see the RESET section), and in normal execution, flushes \fBstdout\fR as soon as execution is done for the current input\.
.
.SH "TTY MODE"
If \fBstdin\fR, \fBstdout\fR, and \fBstderr\fR are all connected to a TTY, dc(1) turns on "TTY mode\."
.
.P
TTY mode is required for history to be enabled (see the COMMAND LINE HISTORY section)\. It is also required to enable special handling for \fBSIGINT\fR signals\.
.
.P
TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR, and interactive mode requires only \fBstdin\fR and \fBstdout\fR to be connected to a terminal\.
.
.SH "SIGNAL HANDLING"
Sending a \fBSIGINT\fR will cause dc(1) to stop execution of the current input\. If dc(1) is in TTY mode (see the TTY MODE section), it will reset (see the RESET section)\. Otherwise, it will clean up and exit\.
.
.P
Note that "current input" can mean one of two things\. If dc(1) is processing input from \fBstdin\fR in TTY mode, it will ask for more input\. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \fBstdin\fR if no other file exists\.
.
.P
This means that if a \fBSIGINT\fR is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file\. This is by design; most files that users execute when interacting with dc(1) have function definitions, which are quick to parse\. If a file takes a long time to execute, there may be a bug in that file\. The rest of the files could still be executed without problem, allowing the user to continue\.
.
.P
\fBSIGTERM\fR and \fBSIGQUIT\fR cause dc(1) to clean up and exit, and it uses the default handler for all other signals\. The one exception is \fBSIGHUP\fR, if dc(1) was built with history support; in that case, when dc(1) is in TTY mode, a \fBSIGHUP\fR will cause dc(1) to clean up and exit\.
.
.SH "COMMAND LINE HISTORY"
dc(1) supports interactive command\-line editing, if compiled with the history option enabled\. If dc(1) is in TTY mode (see the TTY MODE section), history is enabled\. Previous lines can be recalled and edited with the arrow keys\.
.
.P
\fBNote\fR: when dc(1) is built with history support, tabs are converted to 8 spaces\.
.
.SH "LOCALES"
This dc(1) ships with support for adding error messages for different locales\.
.
.SH "SEE ALSO"
bc(1)
.
.SH "STANDARDS"
The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003\.1\-2017 (“POSIX\.1\-2017”) \fIhttps://pubs\.opengroup\.org/onlinepubs/9699919799/utilities/bc\.html\fR specification\.
.
.SH "AUTHOR"
This dc(1) was made from scratch by Gavin D\. Howard\.
.
.SH "BUGS"
None are known\. Report bugs at https://git\.yzena\.com/gavin/bc\.

1103
contrib/bc/manuals/dc.1.ronn Normal file

File diff suppressed because it is too large Load Diff

1
contrib/bc/manuals/dc.md Symbolic link
View File

@ -0,0 +1 @@
dc.1.ronn

215
contrib/bc/src/args.c Normal file
View File

@ -0,0 +1,215 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Code for processing command-line arguments.
*
*/
#include <assert.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <status.h>
#include <vector.h>
#include <read.h>
#include <vm.h>
#include <args.h>
#include <opt.h>
static const BcOptLong bc_args_lopt[] = {
{ "expression", BC_OPT_REQUIRED, 'e' },
{ "file", BC_OPT_REQUIRED, 'f' },
{ "help", BC_OPT_NONE, 'h' },
{ "interactive", BC_OPT_NONE, 'i' },
{ "no-prompt", BC_OPT_NONE, 'P' },
#if BC_ENABLED
{ "global-stacks", BC_OPT_BC_ONLY, 'g' },
{ "mathlib", BC_OPT_BC_ONLY, 'l' },
{ "quiet", BC_OPT_BC_ONLY, 'q' },
{ "standard", BC_OPT_BC_ONLY, 's' },
{ "warn", BC_OPT_BC_ONLY, 'w' },
#endif // BC_ENABLED
{ "version", BC_OPT_NONE, 'v' },
{ "version", BC_OPT_NONE, 'V' },
#if DC_ENABLED
{ "extended-register", BC_OPT_DC_ONLY, 'x' },
#endif // DC_ENABLED
{ NULL, 0, 0 },
};
static void bc_args_exprs(const char *str) {
BC_SIG_ASSERT_LOCKED;
if (vm.exprs.v == NULL) bc_vec_init(&vm.exprs, sizeof(uchar), NULL);
bc_vec_concat(&vm.exprs, str);
bc_vec_concat(&vm.exprs, "\n");
}
static void bc_args_file(const char *file) {
char *buf;
BC_SIG_ASSERT_LOCKED;
vm.file = file;
bc_read_file(file, &buf);
bc_args_exprs(buf);
free(buf);
}
void bc_args(int argc, char *argv[]) {
int c;
size_t i;
bool do_exit = false, version = false;
BcOpt opts;
BC_SIG_ASSERT_LOCKED;
bc_opt_init(&opts, argv);
while ((c = bc_opt_parse(&opts, bc_args_lopt)) != -1) {
switch (c) {
case 'e':
{
bc_args_exprs(opts.optarg);
break;
}
case 'f':
{
bc_args_file(opts.optarg);
break;
}
case 'h':
{
bc_vm_info(vm.help);
do_exit = true;
break;
}
case 'i':
{
vm.flags |= BC_FLAG_I;
break;
}
case 'P':
{
vm.flags |= BC_FLAG_P;
break;
}
#if BC_ENABLED
case 'g':
{
assert(BC_IS_BC);
vm.flags |= BC_FLAG_G;
break;
}
case 'l':
{
assert(BC_IS_BC);
vm.flags |= BC_FLAG_L;
break;
}
case 'q':
{
assert(BC_IS_BC);
vm.flags |= BC_FLAG_Q;
break;
}
case 's':
{
assert(BC_IS_BC);
vm.flags |= BC_FLAG_S;
break;
}
case 'w':
{
assert(BC_IS_BC);
vm.flags |= BC_FLAG_W;
break;
}
#endif // BC_ENABLED
case 'V':
case 'v':
{
do_exit = version = true;
break;
}
#if DC_ENABLED
case 'x':
{
assert(!BC_IS_BC);
vm.flags |= DC_FLAG_X;
break;
}
#endif // DC_ENABLED
#ifndef NDEBUG
// We shouldn't get here because bc_opt_error()/bc_vm_error() should
// longjmp() out.
case '?':
case ':':
default:
{
abort();
}
#endif // NDEBUG
}
}
if (version) bc_vm_info(NULL);
if (do_exit) exit((int) vm.status);
if (vm.exprs.len > 1 || !BC_IS_BC) vm.flags |= BC_FLAG_Q;
if (opts.optind < (size_t) argc)
bc_vec_init(&vm.files, sizeof(char*), NULL);
for (i = opts.optind; i < (size_t) argc; ++i)
bc_vec_push(&vm.files, argv + i);
}

57
contrib/bc/src/bc/bc.c Normal file
View File

@ -0,0 +1,57 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 main procedure of bc.
*
*/
#if BC_ENABLED
#include <string.h>
#include <status.h>
#include <bc.h>
#include <vm.h>
void bc_main(int argc, char **argv) {
vm.read_ret = BC_INST_RET;
vm.help = bc_help;
vm.sigmsg = bc_sig_msg;
vm.siglen = bc_sig_msg_len;
vm.next = bc_lex_token;
vm.parse = bc_parse_parse;
vm.expr = bc_parse_expr;
bc_vm_boot(argc, argv, "BC_LINE_LENGTH", "BC_ENV_ARGS", "BC_EXPR_EXIT");
}
#endif // BC_ENABLED

410
contrib/bc/src/bc/lex.c Normal file
View File

@ -0,0 +1,410 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 lexer for bc.
*
*/
#if BC_ENABLED
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include <lex.h>
#include <bc.h>
#include <vm.h>
static void bc_lex_identifier(BcLex *l) {
size_t i;
const char *buf = l->buf + l->i - 1;
for (i = 0; i < bc_lex_kws_len; ++i) {
const BcLexKeyword *kw = bc_lex_kws + i;
size_t n = BC_LEX_KW_LEN(kw);
if (!strncmp(buf, kw->name, n) && !isalnum(buf[n]) && buf[n] != '_') {
l->t = BC_LEX_KW_AUTO + (BcLexType) i;
if (!BC_LEX_KW_POSIX(kw))
bc_lex_verr(l, BC_ERROR_POSIX_KW, kw->name);
// We minus 1 because the index has already been incremented.
l->i += n - 1;
return;
}
}
bc_lex_name(l);
if (BC_ERR(l->str.len - 1 > 1))
bc_lex_verr(l, BC_ERROR_POSIX_NAME_LEN, l->str.v);
}
static void bc_lex_string(BcLex *l) {
size_t len, nlines = 0, i = l->i;
const char *buf = l->buf;
char c;
l->t = BC_LEX_STR;
for (; (c = buf[i]) && c != '"'; ++i) nlines += c == '\n';
if (BC_ERR(c == '\0')) {
l->i = i;
bc_lex_err(l, BC_ERROR_PARSE_STRING);
}
len = i - l->i;
bc_vec_string(&l->str, len, l->buf + l->i);
l->i = i + 1;
l->line += nlines;
}
static void bc_lex_assign(BcLex *l, BcLexType with, BcLexType without) {
if (l->buf[l->i] == '=') {
l->i += 1;
l->t = with;
}
else l->t = without;
}
void bc_lex_token(BcLex *l) {
char c = l->buf[l->i++], c2;
// This is the workhorse of the lexer.
switch (c) {
case '\0':
case '\n':
case '\t':
case '\v':
case '\f':
case '\r':
case ' ':
{
bc_lex_commonTokens(l, c);
break;
}
case '!':
{
bc_lex_assign(l, BC_LEX_OP_REL_NE, BC_LEX_OP_BOOL_NOT);
if (l->t == BC_LEX_OP_BOOL_NOT)
bc_lex_verr(l, BC_ERROR_POSIX_BOOL, "!");
break;
}
case '"':
{
bc_lex_string(l);
break;
}
case '#':
{
bc_lex_err(l, BC_ERROR_POSIX_COMMENT);
bc_lex_lineComment(l);
break;
}
case '%':
{
bc_lex_assign(l, BC_LEX_OP_ASSIGN_MODULUS, BC_LEX_OP_MODULUS);
break;
}
case '&':
{
c2 = l->buf[l->i];
if (BC_NO_ERR(c2 == '&')) {
bc_lex_verr(l, BC_ERROR_POSIX_BOOL, "&&");
l->i += 1;
l->t = BC_LEX_OP_BOOL_AND;
}
else bc_lex_invalidChar(l, c);
break;
}
#if BC_ENABLE_EXTRA_MATH
case '$':
{
l->t = BC_LEX_OP_TRUNC;
break;
}
case '@':
{
bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLACES, BC_LEX_OP_PLACES);
break;
}
#endif // BC_ENABLE_EXTRA_MATH
case '(':
case ')':
{
l->t = (BcLexType) (c - '(' + BC_LEX_LPAREN);
break;
}
case '*':
{
bc_lex_assign(l, BC_LEX_OP_ASSIGN_MULTIPLY, BC_LEX_OP_MULTIPLY);
break;
}
case '+':
{
c2 = l->buf[l->i];
if (c2 == '+') {
l->i += 1;
l->t = BC_LEX_OP_INC;
}
else bc_lex_assign(l, BC_LEX_OP_ASSIGN_PLUS, BC_LEX_OP_PLUS);
break;
}
case ',':
{
l->t = BC_LEX_COMMA;
break;
}
case '-':
{
c2 = l->buf[l->i];
if (c2 == '-') {
l->i += 1;
l->t = BC_LEX_OP_DEC;
}
else bc_lex_assign(l, BC_LEX_OP_ASSIGN_MINUS, BC_LEX_OP_MINUS);
break;
}
case '.':
{
c2 = l->buf[l->i];
if (BC_LEX_NUM_CHAR(c2, true, false)) bc_lex_number(l, c);
else {
l->t = BC_LEX_KW_LAST;
bc_lex_err(l, BC_ERROR_POSIX_DOT);
}
break;
}
case '/':
{
c2 = l->buf[l->i];
if (c2 =='*') bc_lex_comment(l);
else bc_lex_assign(l, BC_LEX_OP_ASSIGN_DIVIDE, BC_LEX_OP_DIVIDE);
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
// Apparently, GNU bc (and maybe others) allows any uppercase letter as
// a number. When single digits, they act like the ones above. When
// multi-digit, any letter above the input base is automatically set to
// the biggest allowable digit in the input base.
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
{
bc_lex_number(l, c);
break;
}
case ';':
{
l->t = BC_LEX_SCOLON;
break;
}
case '<':
{
#if BC_ENABLE_EXTRA_MATH
c2 = l->buf[l->i];
if (c2 == '<') {
l->i += 1;
bc_lex_assign(l, BC_LEX_OP_ASSIGN_LSHIFT, BC_LEX_OP_LSHIFT);
break;
}
#endif // BC_ENABLE_EXTRA_MATH
bc_lex_assign(l, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_LT);
break;
}
case '=':
{
bc_lex_assign(l, BC_LEX_OP_REL_EQ, BC_LEX_OP_ASSIGN);
break;
}
case '>':
{
#if BC_ENABLE_EXTRA_MATH
c2 = l->buf[l->i];
if (c2 == '>') {
l->i += 1;
bc_lex_assign(l, BC_LEX_OP_ASSIGN_RSHIFT, BC_LEX_OP_RSHIFT);
break;
}
#endif // BC_ENABLE_EXTRA_MATH
bc_lex_assign(l, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_GT);
break;
}
case '[':
case ']':
{
l->t = (BcLexType) (c - '[' + BC_LEX_LBRACKET);
break;
}
case '\\':
{
if (BC_NO_ERR(l->buf[l->i] == '\n')) {
l->i += 1;
l->t = BC_LEX_WHITESPACE;
}
else bc_lex_invalidChar(l, c);
break;
}
case '^':
{
bc_lex_assign(l, BC_LEX_OP_ASSIGN_POWER, BC_LEX_OP_POWER);
break;
}
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
{
bc_lex_identifier(l);
break;
}
case '{':
case '}':
{
l->t = (BcLexType) (c - '{' + BC_LEX_LBRACE);
break;
}
case '|':
{
c2 = l->buf[l->i];
if (BC_NO_ERR(c2 == '|')) {
bc_lex_verr(l, BC_ERROR_POSIX_BOOL, "||");
l->i += 1;
l->t = BC_LEX_OP_BOOL_OR;
}
else bc_lex_invalidChar(l, c);
break;
}
default:
{
bc_lex_invalidChar(l, c);
}
}
}
#endif // BC_ENABLED

1526
contrib/bc/src/bc/parse.c Normal file

File diff suppressed because it is too large Load Diff

995
contrib/bc/src/data.c Normal file
View File

@ -0,0 +1,995 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Constant data for bc.
*
*/
#include <args.h>
#include <lex.h>
#include <parse.h>
#include <bc.h>
#include <dc.h>
#include <num.h>
#include <rand.h>
#include <program.h>
#include <vm.h>
#if BC_ENABLED
const char bc_sig_msg[] = "\ninterrupt (type \"quit\" to exit)\n";
const uchar bc_sig_msg_len = (uchar) (sizeof(bc_sig_msg) - 1);
#endif // BC_ENABLED
#if DC_ENABLED
const char dc_sig_msg[] = "\ninterrupt (type \"q\" to exit)\n";
const uchar dc_sig_msg_len = (uchar) (sizeof(dc_sig_msg) - 1);
#endif // DC_ENABLED
const char bc_copyright[] =
"Copyright (c) 2018-2020 Gavin D. Howard and contributors\n"
"Report bugs at: https://git.yzena.com/gavin/bc\n\n"
"This is free software with ABSOLUTELY NO WARRANTY.\n";
const char* const bc_err_func_header = "Function:";
const char* const bc_err_line = ":%zu";
const char *bc_errs[] = {
"Math error:",
"Parse error:",
"Runtime error:",
"Fatal error:",
#if BC_ENABLED
"Warning:",
#endif // BC_ENABLED
};
const uchar bc_err_ids[] = {
BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_MATH,
BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL,
BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL,
BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC,
BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC,
BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC,
BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE,
BC_ERR_IDX_PARSE,
#if BC_ENABLED
BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE,
BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE,
BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE,
BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE,
BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE,
BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE,
BC_ERR_IDX_PARSE,
#endif // BC_ENABLED
};
const char* const bc_err_msgs[] = {
"negative number",
"non-integer number",
"overflow: number cannot fit",
"divide by 0",
"memory allocation failed",
"I/O error",
"cannot open file: %s",
"file is not ASCII: %s",
"path is a directory: %s",
"bad command-line option: \"%s\"",
"option requires an argument: '%c' (\"%s\")",
"option takes no arguments: '%c' (\"%s\")",
"bad ibase: must be [%lu, %lu]",
"bad obase: must be [%lu, %lu]",
"bad scale: must be [%lu, %lu]",
"bad read() expression",
"read() call inside of a read() call",
"variable or array element is the wrong type",
#if DC_ENABLED
"stack has too few elements",
#else // DC_ENABLED
NULL,
#endif // DC_ENABLED
#if BC_ENABLED
"wrong number of parameters; need %zu, have %zu",
"undefined function: %s()",
"cannot use a void value in an expression",
#else
NULL, NULL, NULL,
#endif // BC_ENABLED
"end of file",
"bad character '%c'",
"string end cannot be found",
"comment end cannot be found",
"bad token",
#if BC_ENABLED
"bad expression",
"empty expression",
"bad print statement",
"bad function definition",
"bad assignment: left side must be scale, ibase, "
"obase, seed, last, var, or array element",
"no auto variable found",
"function parameter or auto \"%s%s\" already exists",
"block end cannot be found",
"cannot return a value from void function: %s()",
"var cannot be a reference: %s",
"POSIX does not allow names longer than 1 character: %s",
"POSIX does not allow '#' script comments",
"POSIX does not allow the following keyword: %s",
"POSIX does not allow a period ('.') as a shortcut for the last result",
"POSIX requires parentheses around return expressions",
"POSIX does not allow the following operator: %s",
"POSIX does not allow comparison operators outside if statements or loops",
"POSIX requires 0 or 1 comparison operators per condition",
"POSIX requires all 3 parts of a for loop to be non-empty",
#if BC_ENABLE_EXTRA_MATH
"POSIX does not allow exponential notation",
#else
NULL,
#endif // BC_ENABLE_EXTRA_MATH
"POSIX does not allow array references as function parameters",
"POSIX does not allow void functions",
"POSIX requires the left brace be on the same line as the function header",
#endif // BC_ENABLED
};
#if BC_ENABLE_HISTORY
const char *bc_history_bad_terms[] = { "dumb", "cons25", "emacs", NULL };
const char bc_history_tab[] = " ";
const size_t bc_history_tab_len = sizeof(bc_history_tab) - 1;
// These are listed in ascending order for efficiency.
const uint32_t bc_history_wchars[][2] = {
{ 0x1100, 0x115F },
{ 0x231A, 0x231B },
{ 0x2329, 0x232A },
{ 0x23E9, 0x23EC },
{ 0x23F0, 0x23F0 },
{ 0x23F3, 0x23F3 },
{ 0x25FD, 0x25FE },
{ 0x2614, 0x2615 },
{ 0x2648, 0x2653 },
{ 0x267F, 0x267F },
{ 0x2693, 0x2693 },
{ 0x26A1, 0x26A1 },
{ 0x26AA, 0x26AB },
{ 0x26BD, 0x26BE },
{ 0x26C4, 0x26C5 },
{ 0x26CE, 0x26CE },
{ 0x26D4, 0x26D4 },
{ 0x26EA, 0x26EA },
{ 0x26F2, 0x26F3 },
{ 0x26F5, 0x26F5 },
{ 0x26FA, 0x26FA },
{ 0x26FD, 0x26FD },
{ 0x2705, 0x2705 },
{ 0x270A, 0x270B },
{ 0x2728, 0x2728 },
{ 0x274C, 0x274C },
{ 0x274E, 0x274E },
{ 0x2753, 0x2755 },
{ 0x2757, 0x2757 },
{ 0x2795, 0x2797 },
{ 0x27B0, 0x27B0 },
{ 0x27BF, 0x27BF },
{ 0x2B1B, 0x2B1C },
{ 0x2B50, 0x2B50 },
{ 0x2B55, 0x2B55 },
{ 0x2E80, 0x2E99 },
{ 0x2E9B, 0x2EF3 },
{ 0x2F00, 0x2FD5 },
{ 0x2FF0, 0x2FFB },
{ 0x3001, 0x303E },
{ 0x3041, 0x3096 },
{ 0x3099, 0x30FF },
{ 0x3105, 0x312D },
{ 0x3131, 0x318E },
{ 0x3190, 0x31BA },
{ 0x31C0, 0x31E3 },
{ 0x31F0, 0x321E },
{ 0x3220, 0x3247 },
{ 0x3250, 0x32FE },
{ 0x3300, 0x4DBF },
{ 0x4E00, 0xA48C },
{ 0xA490, 0xA4C6 },
{ 0xA960, 0xA97C },
{ 0xAC00, 0xD7A3 },
{ 0xF900, 0xFAFF },
{ 0xFE10, 0xFE19 },
{ 0xFE30, 0xFE52 },
{ 0xFE54, 0xFE66 },
{ 0xFE68, 0xFE6B },
{ 0x16FE0, 0x16FE0 },
{ 0x17000, 0x187EC },
{ 0x18800, 0x18AF2 },
{ 0x1B000, 0x1B001 },
{ 0x1F004, 0x1F004 },
{ 0x1F0CF, 0x1F0CF },
{ 0x1F18E, 0x1F18E },
{ 0x1F191, 0x1F19A },
{ 0x1F200, 0x1F202 },
{ 0x1F210, 0x1F23B },
{ 0x1F240, 0x1F248 },
{ 0x1F250, 0x1F251 },
{ 0x1F300, 0x1F320 },
{ 0x1F32D, 0x1F335 },
{ 0x1F337, 0x1F37C },
{ 0x1F37E, 0x1F393 },
{ 0x1F3A0, 0x1F3CA },
{ 0x1F3CF, 0x1F3D3 },
{ 0x1F3E0, 0x1F3F0 },
{ 0x1F3F4, 0x1F3F4 },
{ 0x1F3F8, 0x1F43E },
{ 0x1F440, 0x1F440 },
{ 0x1F442, 0x1F4FC },
{ 0x1F4FF, 0x1F53D },
{ 0x1F54B, 0x1F54E },
{ 0x1F550, 0x1F567 },
{ 0x1F57A, 0x1F57A },
{ 0x1F595, 0x1F596 },
{ 0x1F5A4, 0x1F5A4 },
{ 0x1F5FB, 0x1F64F },
{ 0x1F680, 0x1F6C5 },
{ 0x1F6CC, 0x1F6CC },
{ 0x1F6D0, 0x1F6D2 },
{ 0x1F6EB, 0x1F6EC },
{ 0x1F6F4, 0x1F6F6 },
{ 0x1F910, 0x1F91E },
{ 0x1F920, 0x1F927 },
{ 0x1F930, 0x1F930 },
{ 0x1F933, 0x1F93E },
{ 0x1F940, 0x1F94B },
{ 0x1F950, 0x1F95E },
{ 0x1F980, 0x1F991 },
{ 0x1F9C0, 0x1F9C0 },
{ 0x20000, 0x2FFFD },
{ 0x30000, 0x3FFFD },
};
const size_t bc_history_wchars_len =
sizeof(bc_history_wchars) / sizeof(bc_history_wchars[0]);
// These are listed in ascending order for efficiency.
const uint32_t bc_history_combo_chars[] = {
0x0300,0x0301,0x0302,0x0303,0x0304,0x0305,0x0306,0x0307,
0x0308,0x0309,0x030A,0x030B,0x030C,0x030D,0x030E,0x030F,
0x0310,0x0311,0x0312,0x0313,0x0314,0x0315,0x0316,0x0317,
0x0318,0x0319,0x031A,0x031B,0x031C,0x031D,0x031E,0x031F,
0x0320,0x0321,0x0322,0x0323,0x0324,0x0325,0x0326,0x0327,
0x0328,0x0329,0x032A,0x032B,0x032C,0x032D,0x032E,0x032F,
0x0330,0x0331,0x0332,0x0333,0x0334,0x0335,0x0336,0x0337,
0x0338,0x0339,0x033A,0x033B,0x033C,0x033D,0x033E,0x033F,
0x0340,0x0341,0x0342,0x0343,0x0344,0x0345,0x0346,0x0347,
0x0348,0x0349,0x034A,0x034B,0x034C,0x034D,0x034E,0x034F,
0x0350,0x0351,0x0352,0x0353,0x0354,0x0355,0x0356,0x0357,
0x0358,0x0359,0x035A,0x035B,0x035C,0x035D,0x035E,0x035F,
0x0360,0x0361,0x0362,0x0363,0x0364,0x0365,0x0366,0x0367,
0x0368,0x0369,0x036A,0x036B,0x036C,0x036D,0x036E,0x036F,
0x0483,0x0484,0x0485,0x0486,0x0487,0x0591,0x0592,0x0593,
0x0594,0x0595,0x0596,0x0597,0x0598,0x0599,0x059A,0x059B,
0x059C,0x059D,0x059E,0x059F,0x05A0,0x05A1,0x05A2,0x05A3,
0x05A4,0x05A5,0x05A6,0x05A7,0x05A8,0x05A9,0x05AA,0x05AB,
0x05AC,0x05AD,0x05AE,0x05AF,0x05B0,0x05B1,0x05B2,0x05B3,
0x05B4,0x05B5,0x05B6,0x05B7,0x05B8,0x05B9,0x05BA,0x05BB,
0x05BC,0x05BD,0x05BF,0x05C1,0x05C2,0x05C4,0x05C5,0x05C7,
0x0610,0x0611,0x0612,0x0613,0x0614,0x0615,0x0616,0x0617,
0x0618,0x0619,0x061A,0x064B,0x064C,0x064D,0x064E,0x064F,
0x0650,0x0651,0x0652,0x0653,0x0654,0x0655,0x0656,0x0657,
0x0658,0x0659,0x065A,0x065B,0x065C,0x065D,0x065E,0x065F,
0x0670,0x06D6,0x06D7,0x06D8,0x06D9,0x06DA,0x06DB,0x06DC,
0x06DF,0x06E0,0x06E1,0x06E2,0x06E3,0x06E4,0x06E7,0x06E8,
0x06EA,0x06EB,0x06EC,0x06ED,0x0711,0x0730,0x0731,0x0732,
0x0733,0x0734,0x0735,0x0736,0x0737,0x0738,0x0739,0x073A,
0x073B,0x073C,0x073D,0x073E,0x073F,0x0740,0x0741,0x0742,
0x0743,0x0744,0x0745,0x0746,0x0747,0x0748,0x0749,0x074A,
0x07A6,0x07A7,0x07A8,0x07A9,0x07AA,0x07AB,0x07AC,0x07AD,
0x07AE,0x07AF,0x07B0,0x07EB,0x07EC,0x07ED,0x07EE,0x07EF,
0x07F0,0x07F1,0x07F2,0x07F3,0x0816,0x0817,0x0818,0x0819,
0x081B,0x081C,0x081D,0x081E,0x081F,0x0820,0x0821,0x0822,
0x0823,0x0825,0x0826,0x0827,0x0829,0x082A,0x082B,0x082C,
0x082D,0x0859,0x085A,0x085B,0x08D4,0x08D5,0x08D6,0x08D7,
0x08D8,0x08D9,0x08DA,0x08DB,0x08DC,0x08DD,0x08DE,0x08DF,
0x08E0,0x08E1,0x08E3,0x08E4,0x08E5,0x08E6,0x08E7,0x08E8,
0x08E9,0x08EA,0x08EB,0x08EC,0x08ED,0x08EE,0x08EF,0x08F0,
0x08F1,0x08F2,0x08F3,0x08F4,0x08F5,0x08F6,0x08F7,0x08F8,
0x08F9,0x08FA,0x08FB,0x08FC,0x08FD,0x08FE,0x08FF,0x0900,
0x0901,0x0902,0x093A,0x093C,0x0941,0x0942,0x0943,0x0944,
0x0945,0x0946,0x0947,0x0948,0x094D,0x0951,0x0952,0x0953,
0x0954,0x0955,0x0956,0x0957,0x0962,0x0963,0x0981,0x09BC,
0x09C1,0x09C2,0x09C3,0x09C4,0x09CD,0x09E2,0x09E3,0x0A01,
0x0A02,0x0A3C,0x0A41,0x0A42,0x0A47,0x0A48,0x0A4B,0x0A4C,
0x0A4D,0x0A51,0x0A70,0x0A71,0x0A75,0x0A81,0x0A82,0x0ABC,
0x0AC1,0x0AC2,0x0AC3,0x0AC4,0x0AC5,0x0AC7,0x0AC8,0x0ACD,
0x0AE2,0x0AE3,0x0B01,0x0B3C,0x0B3F,0x0B41,0x0B42,0x0B43,
0x0B44,0x0B4D,0x0B56,0x0B62,0x0B63,0x0B82,0x0BC0,0x0BCD,
0x0C00,0x0C3E,0x0C3F,0x0C40,0x0C46,0x0C47,0x0C48,0x0C4A,
0x0C4B,0x0C4C,0x0C4D,0x0C55,0x0C56,0x0C62,0x0C63,0x0C81,
0x0CBC,0x0CBF,0x0CC6,0x0CCC,0x0CCD,0x0CE2,0x0CE3,0x0D01,
0x0D41,0x0D42,0x0D43,0x0D44,0x0D4D,0x0D62,0x0D63,0x0DCA,
0x0DD2,0x0DD3,0x0DD4,0x0DD6,0x0E31,0x0E34,0x0E35,0x0E36,
0x0E37,0x0E38,0x0E39,0x0E3A,0x0E47,0x0E48,0x0E49,0x0E4A,
0x0E4B,0x0E4C,0x0E4D,0x0E4E,0x0EB1,0x0EB4,0x0EB5,0x0EB6,
0x0EB7,0x0EB8,0x0EB9,0x0EBB,0x0EBC,0x0EC8,0x0EC9,0x0ECA,
0x0ECB,0x0ECC,0x0ECD,0x0F18,0x0F19,0x0F35,0x0F37,0x0F39,
0x0F71,0x0F72,0x0F73,0x0F74,0x0F75,0x0F76,0x0F77,0x0F78,
0x0F79,0x0F7A,0x0F7B,0x0F7C,0x0F7D,0x0F7E,0x0F80,0x0F81,
0x0F82,0x0F83,0x0F84,0x0F86,0x0F87,0x0F8D,0x0F8E,0x0F8F,
0x0F90,0x0F91,0x0F92,0x0F93,0x0F94,0x0F95,0x0F96,0x0F97,
0x0F99,0x0F9A,0x0F9B,0x0F9C,0x0F9D,0x0F9E,0x0F9F,0x0FA0,
0x0FA1,0x0FA2,0x0FA3,0x0FA4,0x0FA5,0x0FA6,0x0FA7,0x0FA8,
0x0FA9,0x0FAA,0x0FAB,0x0FAC,0x0FAD,0x0FAE,0x0FAF,0x0FB0,
0x0FB1,0x0FB2,0x0FB3,0x0FB4,0x0FB5,0x0FB6,0x0FB7,0x0FB8,
0x0FB9,0x0FBA,0x0FBB,0x0FBC,0x0FC6,0x102D,0x102E,0x102F,
0x1030,0x1032,0x1033,0x1034,0x1035,0x1036,0x1037,0x1039,
0x103A,0x103D,0x103E,0x1058,0x1059,0x105E,0x105F,0x1060,
0x1071,0x1072,0x1073,0x1074,0x1082,0x1085,0x1086,0x108D,
0x109D,0x135D,0x135E,0x135F,0x1712,0x1713,0x1714,0x1732,
0x1733,0x1734,0x1752,0x1753,0x1772,0x1773,0x17B4,0x17B5,
0x17B7,0x17B8,0x17B9,0x17BA,0x17BB,0x17BC,0x17BD,0x17C6,
0x17C9,0x17CA,0x17CB,0x17CC,0x17CD,0x17CE,0x17CF,0x17D0,
0x17D1,0x17D2,0x17D3,0x17DD,0x180B,0x180C,0x180D,0x1885,
0x1886,0x18A9,0x1920,0x1921,0x1922,0x1927,0x1928,0x1932,
0x1939,0x193A,0x193B,0x1A17,0x1A18,0x1A1B,0x1A56,0x1A58,
0x1A59,0x1A5A,0x1A5B,0x1A5C,0x1A5D,0x1A5E,0x1A60,0x1A62,
0x1A65,0x1A66,0x1A67,0x1A68,0x1A69,0x1A6A,0x1A6B,0x1A6C,
0x1A73,0x1A74,0x1A75,0x1A76,0x1A77,0x1A78,0x1A79,0x1A7A,
0x1A7B,0x1A7C,0x1A7F,0x1AB0,0x1AB1,0x1AB2,0x1AB3,0x1AB4,
0x1AB5,0x1AB6,0x1AB7,0x1AB8,0x1AB9,0x1ABA,0x1ABB,0x1ABC,
0x1ABD,0x1B00,0x1B01,0x1B02,0x1B03,0x1B34,0x1B36,0x1B37,
0x1B38,0x1B39,0x1B3A,0x1B3C,0x1B42,0x1B6B,0x1B6C,0x1B6D,
0x1B6E,0x1B6F,0x1B70,0x1B71,0x1B72,0x1B73,0x1B80,0x1B81,
0x1BA2,0x1BA3,0x1BA4,0x1BA5,0x1BA8,0x1BA9,0x1BAB,0x1BAC,
0x1BAD,0x1BE6,0x1BE8,0x1BE9,0x1BED,0x1BEF,0x1BF0,0x1BF1,
0x1C2C,0x1C2D,0x1C2E,0x1C2F,0x1C30,0x1C31,0x1C32,0x1C33,
0x1C36,0x1C37,0x1CD0,0x1CD1,0x1CD2,0x1CD4,0x1CD5,0x1CD6,
0x1CD7,0x1CD8,0x1CD9,0x1CDA,0x1CDB,0x1CDC,0x1CDD,0x1CDE,
0x1CDF,0x1CE0,0x1CE2,0x1CE3,0x1CE4,0x1CE5,0x1CE6,0x1CE7,
0x1CE8,0x1CED,0x1CF4,0x1CF8,0x1CF9,0x1DC0,0x1DC1,0x1DC2,
0x1DC3,0x1DC4,0x1DC5,0x1DC6,0x1DC7,0x1DC8,0x1DC9,0x1DCA,
0x1DCB,0x1DCC,0x1DCD,0x1DCE,0x1DCF,0x1DD0,0x1DD1,0x1DD2,
0x1DD3,0x1DD4,0x1DD5,0x1DD6,0x1DD7,0x1DD8,0x1DD9,0x1DDA,
0x1DDB,0x1DDC,0x1DDD,0x1DDE,0x1DDF,0x1DE0,0x1DE1,0x1DE2,
0x1DE3,0x1DE4,0x1DE5,0x1DE6,0x1DE7,0x1DE8,0x1DE9,0x1DEA,
0x1DEB,0x1DEC,0x1DED,0x1DEE,0x1DEF,0x1DF0,0x1DF1,0x1DF2,
0x1DF3,0x1DF4,0x1DF5,0x1DFB,0x1DFC,0x1DFD,0x1DFE,0x1DFF,
0x20D0,0x20D1,0x20D2,0x20D3,0x20D4,0x20D5,0x20D6,0x20D7,
0x20D8,0x20D9,0x20DA,0x20DB,0x20DC,0x20E1,0x20E5,0x20E6,
0x20E7,0x20E8,0x20E9,0x20EA,0x20EB,0x20EC,0x20ED,0x20EE,
0x20EF,0x20F0,0x2CEF,0x2CF0,0x2CF1,0x2D7F,0x2DE0,0x2DE1,
0x2DE2,0x2DE3,0x2DE4,0x2DE5,0x2DE6,0x2DE7,0x2DE8,0x2DE9,
0x2DEA,0x2DEB,0x2DEC,0x2DED,0x2DEE,0x2DEF,0x2DF0,0x2DF1,
0x2DF2,0x2DF3,0x2DF4,0x2DF5,0x2DF6,0x2DF7,0x2DF8,0x2DF9,
0x2DFA,0x2DFB,0x2DFC,0x2DFD,0x2DFE,0x2DFF,0x302A,0x302B,
0x302C,0x302D,0x3099,0x309A,0xA66F,0xA674,0xA675,0xA676,
0xA677,0xA678,0xA679,0xA67A,0xA67B,0xA67C,0xA67D,0xA69E,
0xA69F,0xA6F0,0xA6F1,0xA802,0xA806,0xA80B,0xA825,0xA826,
0xA8C4,0xA8C5,0xA8E0,0xA8E1,0xA8E2,0xA8E3,0xA8E4,0xA8E5,
0xA8E6,0xA8E7,0xA8E8,0xA8E9,0xA8EA,0xA8EB,0xA8EC,0xA8ED,
0xA8EE,0xA8EF,0xA8F0,0xA8F1,0xA926,0xA927,0xA928,0xA929,
0xA92A,0xA92B,0xA92C,0xA92D,0xA947,0xA948,0xA949,0xA94A,
0xA94B,0xA94C,0xA94D,0xA94E,0xA94F,0xA950,0xA951,0xA980,
0xA981,0xA982,0xA9B3,0xA9B6,0xA9B7,0xA9B8,0xA9B9,0xA9BC,
0xA9E5,0xAA29,0xAA2A,0xAA2B,0xAA2C,0xAA2D,0xAA2E,0xAA31,
0xAA32,0xAA35,0xAA36,0xAA43,0xAA4C,0xAA7C,0xAAB0,0xAAB2,
0xAAB3,0xAAB4,0xAAB7,0xAAB8,0xAABE,0xAABF,0xAAC1,0xAAEC,
0xAAED,0xAAF6,0xABE5,0xABE8,0xABED,0xFB1E,0xFE00,0xFE01,
0xFE02,0xFE03,0xFE04,0xFE05,0xFE06,0xFE07,0xFE08,0xFE09,
0xFE0A,0xFE0B,0xFE0C,0xFE0D,0xFE0E,0xFE0F,0xFE20,0xFE21,
0xFE22,0xFE23,0xFE24,0xFE25,0xFE26,0xFE27,0xFE28,0xFE29,
0xFE2A,0xFE2B,0xFE2C,0xFE2D,0xFE2E,0xFE2F,
0x101FD,0x102E0,0x10376,0x10377,0x10378,0x10379,0x1037A,0x10A01,
0x10A02,0x10A03,0x10A05,0x10A06,0x10A0C,0x10A0D,0x10A0E,0x10A0F,
0x10A38,0x10A39,0x10A3A,0x10A3F,0x10AE5,0x10AE6,0x11001,0x11038,
0x11039,0x1103A,0x1103B,0x1103C,0x1103D,0x1103E,0x1103F,0x11040,
0x11041,0x11042,0x11043,0x11044,0x11045,0x11046,0x1107F,0x11080,
0x11081,0x110B3,0x110B4,0x110B5,0x110B6,0x110B9,0x110BA,0x11100,
0x11101,0x11102,0x11127,0x11128,0x11129,0x1112A,0x1112B,0x1112D,
0x1112E,0x1112F,0x11130,0x11131,0x11132,0x11133,0x11134,0x11173,
0x11180,0x11181,0x111B6,0x111B7,0x111B8,0x111B9,0x111BA,0x111BB,
0x111BC,0x111BD,0x111BE,0x111CA,0x111CB,0x111CC,0x1122F,0x11230,
0x11231,0x11234,0x11236,0x11237,0x1123E,0x112DF,0x112E3,0x112E4,
0x112E5,0x112E6,0x112E7,0x112E8,0x112E9,0x112EA,0x11300,0x11301,
0x1133C,0x11340,0x11366,0x11367,0x11368,0x11369,0x1136A,0x1136B,
0x1136C,0x11370,0x11371,0x11372,0x11373,0x11374,0x11438,0x11439,
0x1143A,0x1143B,0x1143C,0x1143D,0x1143E,0x1143F,0x11442,0x11443,
0x11444,0x11446,0x114B3,0x114B4,0x114B5,0x114B6,0x114B7,0x114B8,
0x114BA,0x114BF,0x114C0,0x114C2,0x114C3,0x115B2,0x115B3,0x115B4,
0x115B5,0x115BC,0x115BD,0x115BF,0x115C0,0x115DC,0x115DD,0x11633,
0x11634,0x11635,0x11636,0x11637,0x11638,0x11639,0x1163A,0x1163D,
0x1163F,0x11640,0x116AB,0x116AD,0x116B0,0x116B1,0x116B2,0x116B3,
0x116B4,0x116B5,0x116B7,0x1171D,0x1171E,0x1171F,0x11722,0x11723,
0x11724,0x11725,0x11727,0x11728,0x11729,0x1172A,0x1172B,0x11C30,
0x11C31,0x11C32,0x11C33,0x11C34,0x11C35,0x11C36,0x11C38,0x11C39,
0x11C3A,0x11C3B,0x11C3C,0x11C3D,0x11C3F,0x11C92,0x11C93,0x11C94,
0x11C95,0x11C96,0x11C97,0x11C98,0x11C99,0x11C9A,0x11C9B,0x11C9C,
0x11C9D,0x11C9E,0x11C9F,0x11CA0,0x11CA1,0x11CA2,0x11CA3,0x11CA4,
0x11CA5,0x11CA6,0x11CA7,0x11CAA,0x11CAB,0x11CAC,0x11CAD,0x11CAE,
0x11CAF,0x11CB0,0x11CB2,0x11CB3,0x11CB5,0x11CB6,0x16AF0,0x16AF1,
0x16AF2,0x16AF3,0x16AF4,0x16B30,0x16B31,0x16B32,0x16B33,0x16B34,
0x16B35,0x16B36,0x16F8F,0x16F90,0x16F91,0x16F92,0x1BC9D,0x1BC9E,
0x1D167,0x1D168,0x1D169,0x1D17B,0x1D17C,0x1D17D,0x1D17E,0x1D17F,
0x1D180,0x1D181,0x1D182,0x1D185,0x1D186,0x1D187,0x1D188,0x1D189,
0x1D18A,0x1D18B,0x1D1AA,0x1D1AB,0x1D1AC,0x1D1AD,0x1D242,0x1D243,
0x1D244,0x1DA00,0x1DA01,0x1DA02,0x1DA03,0x1DA04,0x1DA05,0x1DA06,
0x1DA07,0x1DA08,0x1DA09,0x1DA0A,0x1DA0B,0x1DA0C,0x1DA0D,0x1DA0E,
0x1DA0F,0x1DA10,0x1DA11,0x1DA12,0x1DA13,0x1DA14,0x1DA15,0x1DA16,
0x1DA17,0x1DA18,0x1DA19,0x1DA1A,0x1DA1B,0x1DA1C,0x1DA1D,0x1DA1E,
0x1DA1F,0x1DA20,0x1DA21,0x1DA22,0x1DA23,0x1DA24,0x1DA25,0x1DA26,
0x1DA27,0x1DA28,0x1DA29,0x1DA2A,0x1DA2B,0x1DA2C,0x1DA2D,0x1DA2E,
0x1DA2F,0x1DA30,0x1DA31,0x1DA32,0x1DA33,0x1DA34,0x1DA35,0x1DA36,
0x1DA3B,0x1DA3C,0x1DA3D,0x1DA3E,0x1DA3F,0x1DA40,0x1DA41,0x1DA42,
0x1DA43,0x1DA44,0x1DA45,0x1DA46,0x1DA47,0x1DA48,0x1DA49,0x1DA4A,
0x1DA4B,0x1DA4C,0x1DA4D,0x1DA4E,0x1DA4F,0x1DA50,0x1DA51,0x1DA52,
0x1DA53,0x1DA54,0x1DA55,0x1DA56,0x1DA57,0x1DA58,0x1DA59,0x1DA5A,
0x1DA5B,0x1DA5C,0x1DA5D,0x1DA5E,0x1DA5F,0x1DA60,0x1DA61,0x1DA62,
0x1DA63,0x1DA64,0x1DA65,0x1DA66,0x1DA67,0x1DA68,0x1DA69,0x1DA6A,
0x1DA6B,0x1DA6C,0x1DA75,0x1DA84,0x1DA9B,0x1DA9C,0x1DA9D,0x1DA9E,
0x1DA9F,0x1DAA1,0x1DAA2,0x1DAA3,0x1DAA4,0x1DAA5,0x1DAA6,0x1DAA7,
0x1DAA8,0x1DAA9,0x1DAAA,0x1DAAB,0x1DAAC,0x1DAAD,0x1DAAE,0x1DAAF,
0x1E000,0x1E001,0x1E002,0x1E003,0x1E004,0x1E005,0x1E006,0x1E008,
0x1E009,0x1E00A,0x1E00B,0x1E00C,0x1E00D,0x1E00E,0x1E00F,0x1E010,
0x1E011,0x1E012,0x1E013,0x1E014,0x1E015,0x1E016,0x1E017,0x1E018,
0x1E01B,0x1E01C,0x1E01D,0x1E01E,0x1E01F,0x1E020,0x1E021,0x1E023,
0x1E024,0x1E026,0x1E027,0x1E028,0x1E029,0x1E02A,0x1E8D0,0x1E8D1,
0x1E8D2,0x1E8D3,0x1E8D4,0x1E8D5,0x1E8D6,0x1E944,0x1E945,0x1E946,
0x1E947,0x1E948,0x1E949,0x1E94A,0xE0100,0xE0101,0xE0102,0xE0103,
0xE0104,0xE0105,0xE0106,0xE0107,0xE0108,0xE0109,0xE010A,0xE010B,
0xE010C,0xE010D,0xE010E,0xE010F,0xE0110,0xE0111,0xE0112,0xE0113,
0xE0114,0xE0115,0xE0116,0xE0117,0xE0118,0xE0119,0xE011A,0xE011B,
0xE011C,0xE011D,0xE011E,0xE011F,0xE0120,0xE0121,0xE0122,0xE0123,
0xE0124,0xE0125,0xE0126,0xE0127,0xE0128,0xE0129,0xE012A,0xE012B,
0xE012C,0xE012D,0xE012E,0xE012F,0xE0130,0xE0131,0xE0132,0xE0133,
0xE0134,0xE0135,0xE0136,0xE0137,0xE0138,0xE0139,0xE013A,0xE013B,
0xE013C,0xE013D,0xE013E,0xE013F,0xE0140,0xE0141,0xE0142,0xE0143,
0xE0144,0xE0145,0xE0146,0xE0147,0xE0148,0xE0149,0xE014A,0xE014B,
0xE014C,0xE014D,0xE014E,0xE014F,0xE0150,0xE0151,0xE0152,0xE0153,
0xE0154,0xE0155,0xE0156,0xE0157,0xE0158,0xE0159,0xE015A,0xE015B,
0xE015C,0xE015D,0xE015E,0xE015F,0xE0160,0xE0161,0xE0162,0xE0163,
0xE0164,0xE0165,0xE0166,0xE0167,0xE0168,0xE0169,0xE016A,0xE016B,
0xE016C,0xE016D,0xE016E,0xE016F,0xE0170,0xE0171,0xE0172,0xE0173,
0xE0174,0xE0175,0xE0176,0xE0177,0xE0178,0xE0179,0xE017A,0xE017B,
0xE017C,0xE017D,0xE017E,0xE017F,0xE0180,0xE0181,0xE0182,0xE0183,
0xE0184,0xE0185,0xE0186,0xE0187,0xE0188,0xE0189,0xE018A,0xE018B,
0xE018C,0xE018D,0xE018E,0xE018F,0xE0190,0xE0191,0xE0192,0xE0193,
0xE0194,0xE0195,0xE0196,0xE0197,0xE0198,0xE0199,0xE019A,0xE019B,
0xE019C,0xE019D,0xE019E,0xE019F,0xE01A0,0xE01A1,0xE01A2,0xE01A3,
0xE01A4,0xE01A5,0xE01A6,0xE01A7,0xE01A8,0xE01A9,0xE01AA,0xE01AB,
0xE01AC,0xE01AD,0xE01AE,0xE01AF,0xE01B0,0xE01B1,0xE01B2,0xE01B3,
0xE01B4,0xE01B5,0xE01B6,0xE01B7,0xE01B8,0xE01B9,0xE01BA,0xE01BB,
0xE01BC,0xE01BD,0xE01BE,0xE01BF,0xE01C0,0xE01C1,0xE01C2,0xE01C3,
0xE01C4,0xE01C5,0xE01C6,0xE01C7,0xE01C8,0xE01C9,0xE01CA,0xE01CB,
0xE01CC,0xE01CD,0xE01CE,0xE01CF,0xE01D0,0xE01D1,0xE01D2,0xE01D3,
0xE01D4,0xE01D5,0xE01D6,0xE01D7,0xE01D8,0xE01D9,0xE01DA,0xE01DB,
0xE01DC,0xE01DD,0xE01DE,0xE01DF,0xE01E0,0xE01E1,0xE01E2,0xE01E3,
0xE01E4,0xE01E5,0xE01E6,0xE01E7,0xE01E8,0xE01E9,0xE01EA,0xE01EB,
0xE01EC,0xE01ED,0xE01EE,0xE01EF,
};
const size_t bc_history_combo_chars_len =
sizeof(bc_history_combo_chars) / sizeof(bc_history_combo_chars[0]);
#if BC_DEBUG_CODE
BcFile bc_history_debug_fp;
char *bc_history_debug_buf;
#endif // BC_DEBUG_CODE
#endif // BC_ENABLE_HISTORY
const char bc_func_main[] = "(main)";
const char bc_func_read[] = "(read)";
#if BC_DEBUG_CODE
const char* bc_inst_names[] = {
#if BC_ENABLED
"BC_INST_INC",
"BC_INST_DEC",
#endif // BC_ENABLED
"BC_INST_NEG",
"BC_INST_BOOL_NOT",
#if BC_ENABLE_EXTRA_MATH
"BC_INST_TRUNC",
#endif // BC_ENABLE_EXTRA_MATH
"BC_INST_POWER",
"BC_INST_MULTIPLY",
"BC_INST_DIVIDE",
"BC_INST_MODULUS",
"BC_INST_PLUS",
"BC_INST_MINUS",
#if BC_ENABLE_EXTRA_MATH
"BC_INST_PLACES",
"BC_INST_LSHIFT",
"BC_INST_RSHIFT",
#endif // BC_ENABLE_EXTRA_MATH
"BC_INST_REL_EQ",
"BC_INST_REL_LE",
"BC_INST_REL_GE",
"BC_INST_REL_NE",
"BC_INST_REL_LT",
"BC_INST_REL_GT",
"BC_INST_BOOL_OR",
"BC_INST_BOOL_AND",
#if BC_ENABLED
"BC_INST_ASSIGN_POWER",
"BC_INST_ASSIGN_MULTIPLY",
"BC_INST_ASSIGN_DIVIDE",
"BC_INST_ASSIGN_MODULUS",
"BC_INST_ASSIGN_PLUS",
"BC_INST_ASSIGN_MINUS",
#if BC_ENABLE_EXTRA_MATH
"BC_INST_ASSIGN_PLACES",
"BC_INST_ASSIGN_LSHIFT",
"BC_INST_ASSIGN_RSHIFT",
#endif // BC_ENABLE_EXTRA_MATH
"BC_INST_ASSIGN",
"BC_INST_ASSIGN_POWER_NO_VAL",
"BC_INST_ASSIGN_MULTIPLY_NO_VAL",
"BC_INST_ASSIGN_DIVIDE_NO_VAL",
"BC_INST_ASSIGN_MODULUS_NO_VAL",
"BC_INST_ASSIGN_PLUS_NO_VAL",
"BC_INST_ASSIGN_MINUS_NO_VAL",
#if BC_ENABLE_EXTRA_MATH
"BC_INST_ASSIGN_PLACES_NO_VAL",
"BC_INST_ASSIGN_LSHIFT_NO_VAL",
"BC_INST_ASSIGN_RSHIFT_NO_VAL",
#endif // BC_ENABLE_EXTRA_MATH
#endif // BC_ENABLED
"BC_INST_ASSIGN_NO_VAL",
"BC_INST_NUM",
"BC_INST_VAR",
"BC_INST_ARRAY_ELEM",
#if BC_ENABLED
"BC_INST_ARRAY",
#endif // BC_ENABLED
"BC_INST_ONE",
#if BC_ENABLED
"BC_INST_LAST",
#endif // BC_ENABLED
"BC_INST_IBASE",
"BC_INST_OBASE",
"BC_INST_SCALE",
#if BC_ENABLE_EXTRA_MATH
"BC_INST_SEED",
#endif // BC_ENABLE_EXTRA_MATH
"BC_INST_LENGTH",
"BC_INST_SCALE_FUNC",
"BC_INST_SQRT",
"BC_INST_ABS",
#if BC_ENABLE_EXTRA_MATH
"BC_INST_IRAND",
#endif // BC_ENABLE_EXTRA_MATH
"BC_INST_READ",
#if BC_ENABLE_EXTRA_MATH
"BC_INST_RAND",
#endif // BC_ENABLE_EXTRA_MATH
"BC_INST_MAXIBASE",
"BC_INST_MAXOBASE",
"BC_INST_MAXSCALE",
#if BC_ENABLE_EXTRA_MATH
"BC_INST_MAXRAND",
#endif // BC_ENABLE_EXTRA_MATH
"BC_INST_PRINT",
"BC_INST_PRINT_POP",
"BC_INST_STR",
"BC_INST_PRINT_STR",
#if BC_ENABLED
"BC_INST_JUMP",
"BC_INST_JUMP_ZERO",
"BC_INST_CALL",
"BC_INST_RET",
"BC_INST_RET0",
"BC_INST_RET_VOID",
"BC_INST_HALT",
#endif // BC_ENABLED
#if DC_ENABLED
"BC_INST_POP",
"BC_INST_POP_EXEC",
"BC_INST_MODEXP",
"BC_INST_DIVMOD",
"BC_INST_EXECUTE",
"BC_INST_EXEC_COND",
"BC_INST_ASCIIFY",
"BC_INST_PRINT_STREAM",
"BC_INST_PRINT_STACK",
"BC_INST_CLEAR_STACK",
"BC_INST_STACK_LEN",
"BC_INST_DUPLICATE",
"BC_INST_SWAP",
"BC_INST_LOAD",
"BC_INST_PUSH_VAR",
"BC_INST_PUSH_TO_VAR",
"BC_INST_QUIT",
"BC_INST_NQUIT",
#endif // DC_ENABLED
};
#endif // BC_DEBUG_CODE
#if BC_ENABLE_EXTRA_MATH
const BcRandState bc_rand_multiplier = BC_RAND_MULTIPLIER;
#endif // BC_ENABLE_EXTRA_MATH
#if BC_ENABLED
const BcLexKeyword bc_lex_kws[] = {
BC_LEX_KW_ENTRY("auto", 4, true),
BC_LEX_KW_ENTRY("break", 5, true),
BC_LEX_KW_ENTRY("continue", 8, false),
BC_LEX_KW_ENTRY("define", 6, true),
BC_LEX_KW_ENTRY("for", 3, true),
BC_LEX_KW_ENTRY("if", 2, true),
BC_LEX_KW_ENTRY("limits", 6, false),
BC_LEX_KW_ENTRY("return", 6, true),
BC_LEX_KW_ENTRY("while", 5, true),
BC_LEX_KW_ENTRY("halt", 4, false),
BC_LEX_KW_ENTRY("last", 4, false),
BC_LEX_KW_ENTRY("ibase", 5, true),
BC_LEX_KW_ENTRY("obase", 5, true),
BC_LEX_KW_ENTRY("scale", 5, true),
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ENTRY("seed", 4, false),
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ENTRY("length", 6, true),
BC_LEX_KW_ENTRY("print", 5, false),
BC_LEX_KW_ENTRY("sqrt", 4, true),
BC_LEX_KW_ENTRY("abs", 3, false),
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ENTRY("irand", 5, false),
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ENTRY("quit", 4, true),
BC_LEX_KW_ENTRY("read", 4, false),
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ENTRY("rand", 4, false),
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ENTRY("maxibase", 8, false),
BC_LEX_KW_ENTRY("maxobase", 8, false),
BC_LEX_KW_ENTRY("maxscale", 8, false),
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ENTRY("maxrand", 7, false),
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_ENTRY("else", 4, false),
};
const size_t bc_lex_kws_len = sizeof(bc_lex_kws) / sizeof(BcLexKeyword);
const char* const bc_parse_const1 = "1";
// This is an array that corresponds to token types. An entry is
// true if the token is valid in an expression, false otherwise.
const uint8_t bc_parse_exprs[] = {
BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, true),
BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true),
BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true),
#if BC_ENABLE_EXTRA_MATH
BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true),
BC_PARSE_EXPR_ENTRY(true, true, false, false, true, true, false, false),
BC_PARSE_EXPR_ENTRY(false, false, false, false, false, true, true, false),
BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false),
BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, true, false),
BC_PARSE_EXPR_ENTRY(true, true, true, false, true, true, true, true),
BC_PARSE_EXPR_ENTRY(true, true, false, 0, 0, 0, 0, 0)
#else // BC_ENABLE_EXTRA_MATH
BC_PARSE_EXPR_ENTRY(true, true, true, false, false, true, true, false),
BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, true, true),
BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false),
BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, false),
BC_PARSE_EXPR_ENTRY(true, true, false, true, true, true, true, false)
#endif // BC_ENABLE_EXTRA_MATH
};
// This is an array of data for operators that correspond to token types.
const uchar bc_parse_ops[] = {
BC_PARSE_OP(0, false), BC_PARSE_OP(0, false),
BC_PARSE_OP(1, false), BC_PARSE_OP(1, false),
#if BC_ENABLE_EXTRA_MATH
BC_PARSE_OP(2, false),
#endif // BC_ENABLE_EXTRA_MATH
BC_PARSE_OP(4, false),
BC_PARSE_OP(5, true), BC_PARSE_OP(5, true), BC_PARSE_OP(5, true),
BC_PARSE_OP(6, true), BC_PARSE_OP(6, true),
#if BC_ENABLE_EXTRA_MATH
BC_PARSE_OP(3, false),
BC_PARSE_OP(7, true), BC_PARSE_OP(7, true),
#endif // BC_ENABLE_EXTRA_MATH
BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true),
BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true),
BC_PARSE_OP(11, true), BC_PARSE_OP(10, true),
BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false),
BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false),
#if BC_ENABLE_EXTRA_MATH
BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false),
#endif // BC_ENABLE_EXTRA_MATH
BC_PARSE_OP(8, false),
};
// These identify what tokens can come after expressions in certain cases.
const BcParseNext bc_parse_next_expr =
BC_PARSE_NEXT(4, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF);
const BcParseNext bc_parse_next_param =
BC_PARSE_NEXT(2, BC_LEX_RPAREN, BC_LEX_COMMA);
const BcParseNext bc_parse_next_print =
BC_PARSE_NEXT(4, BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF);
const BcParseNext bc_parse_next_rel = BC_PARSE_NEXT(1, BC_LEX_RPAREN);
const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET);
const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON);
const BcParseNext bc_parse_next_read =
BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF);
#endif // BC_ENABLED
#if DC_ENABLED
const uint8_t dc_lex_regs[] = {
BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE,
BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON,
BC_LEX_KW_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN,
BC_LEX_STORE_PUSH,
};
const size_t dc_lex_regs_len = sizeof(dc_lex_regs) / sizeof(uint8_t);
const uchar dc_lex_tokens[] = {
#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_KW_IRAND,
#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_INVALID,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_OP_TRUNC,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_OP_MODULUS, BC_LEX_INVALID,
#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_KW_RAND,
#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_LPAREN, BC_LEX_RPAREN, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS,
BC_LEX_INVALID, BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE,
BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
BC_LEX_INVALID, BC_LEX_INVALID,
BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ,
BC_LEX_OP_REL_LT, BC_LEX_KW_READ,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_OP_PLACES,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID,
BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_OP_LSHIFT,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_IBASE,
#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_KW_SEED,
#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_KW_SCALE, BC_LEX_LOAD_POP, BC_LEX_OP_BOOL_AND, BC_LEX_OP_BOOL_NOT,
BC_LEX_KW_OBASE, BC_LEX_PRINT_STREAM, BC_LEX_NQUIT, BC_LEX_POP,
BC_LEX_STORE_PUSH, BC_LEX_KW_MAXIBASE, BC_LEX_KW_MAXOBASE,
BC_LEX_KW_MAXSCALE,
#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_KW_MAXRAND,
#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_SCALE_FACTOR,
BC_LEX_INVALID, BC_LEX_KW_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID,
BC_LEX_INVALID, BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID,
BC_LEX_ASCIIFY, BC_LEX_KW_ABS, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE,
BC_LEX_KW_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID,
#if BC_ENABLE_EXTRA_MATH
BC_LEX_OP_RSHIFT,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_STORE_IBASE,
#if BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_STORE_SEED,
#else // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH && DC_ENABLE_RAND
BC_LEX_STORE_SCALE, BC_LEX_LOAD,
BC_LEX_OP_BOOL_OR, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KW_PRINT,
BC_LEX_KW_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID,
BC_LEX_INVALID, BC_LEX_KW_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE,
BC_LEX_INVALID, BC_LEX_STACK_LEVEL,
BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_RBRACE, BC_LEX_OP_DIVMOD,
BC_LEX_INVALID
};
const uchar dc_parse_insts[] = {
BC_INST_INVALID, BC_INST_INVALID,
#if BC_ENABLED
BC_INST_INVALID, BC_INST_INVALID,
#endif // BC_ENABLED
BC_INST_INVALID, BC_INST_BOOL_NOT,
#if BC_ENABLE_EXTRA_MATH
BC_INST_TRUNC,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE, BC_INST_MODULUS,
BC_INST_PLUS, BC_INST_MINUS,
#if BC_ENABLE_EXTRA_MATH
BC_INST_PLACES,
BC_INST_LSHIFT, BC_INST_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
BC_INST_INVALID, BC_INST_INVALID,
BC_INST_BOOL_OR, BC_INST_BOOL_AND,
#if BC_ENABLED
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
BC_INST_INVALID, BC_INST_INVALID,
#if BC_ENABLE_EXTRA_MATH
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
#endif // BC_ENABLED
BC_INST_INVALID,
BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_REL_LT,
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE,
BC_INST_INVALID, BC_INST_REL_LE,
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
#if BC_ENABLED
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
#endif // BC_ENABLED
BC_INST_IBASE, BC_INST_OBASE, BC_INST_SCALE,
#if BC_ENABLE_EXTRA_MATH
BC_INST_SEED,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_LENGTH, BC_INST_PRINT,
BC_INST_SQRT, BC_INST_ABS,
#if BC_ENABLE_EXTRA_MATH
BC_INST_IRAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_QUIT, BC_INST_INVALID,
#if BC_ENABLE_EXTRA_MATH
BC_INST_RAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_MAXIBASE,
BC_INST_MAXOBASE, BC_INST_MAXSCALE,
#if BC_ENABLE_EXTRA_MATH
BC_INST_MAXRAND,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_INVALID,
BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID,
BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP,
BC_INST_ASCIIFY, BC_INST_PRINT_STREAM,
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
#if BC_ENABLE_EXTRA_MATH
BC_INST_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID,
BC_INST_PRINT_POP, BC_INST_NQUIT, BC_INST_SCALE_FUNC,
};
#endif // DC_ENABLED
#if BC_LONG_BIT >= 64
const BcDig bc_num_bigdigMax[] = {
709551616U,
446744073U,
18U
};
#else // BC_LONG_BIT >= 64
const BcDig bc_num_bigdigMax[] = {
7296U,
9496U,
42U,
};
#endif // BC_LONG_BIT >= 64
const size_t bc_num_bigdigMax_size = sizeof(bc_num_bigdigMax) / sizeof(BcDig);
const char bc_parse_one[] = "1";
const char bc_num_hex_digits[] = "0123456789ABCDEF";
const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1] = {
1,
10,
100,
1000,
10000,
#if BC_BASE_DIGS > 4
100000,
1000000,
10000000,
100000000,
1000000000,
#endif // BC_BASE_DIGS > 4
};
const BcNumBinaryOp bc_program_ops[] = {
bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub,
#if BC_ENABLE_EXTRA_MATH
bc_num_places, bc_num_lshift, bc_num_rshift,
#endif // BC_ENABLE_EXTRA_MATH
};
const BcNumBinaryOpReq bc_program_opReqs[] = {
bc_num_powReq, bc_num_mulReq, bc_num_mulReq, bc_num_mulReq,
bc_num_addReq, bc_num_addReq,
#if BC_ENABLE_EXTRA_MATH
bc_num_placesReq, bc_num_placesReq, bc_num_placesReq,
#endif // BC_ENABLE_EXTRA_MATH
};
const BcProgramUnary bc_program_unarys[] = {
bc_program_negate, bc_program_not,
#if BC_ENABLE_EXTRA_MATH
bc_program_trunc,
#endif // BC_ENABLE_EXTRA_MATH
};
const char bc_program_exprs_name[] = "<exprs>";
const char bc_program_stdin_name[] = "<stdin>";
const char bc_program_ready_msg[] = "ready for more input\n";
const size_t bc_program_ready_msg_len = sizeof(bc_program_ready_msg) - 1;
const char bc_program_esc_chars[] = "ab\\efnqrt";
const char bc_program_esc_seqs[] = "\a\b\\\\\f\n\"\r\t";

57
contrib/bc/src/dc/dc.c Normal file
View File

@ -0,0 +1,57 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 main procedure of dc.
*
*/
#if DC_ENABLED
#include <string.h>
#include <status.h>
#include <dc.h>
#include <vm.h>
void dc_main(int argc, char **argv) {
vm.read_ret = BC_INST_POP_EXEC;
vm.help = dc_help;
vm.sigmsg = dc_sig_msg;
vm.siglen = dc_sig_msg_len;
vm.next = dc_lex_token;
vm.parse = dc_parse_parse;
vm.expr = dc_parse_expr;
bc_vm_boot(argc, argv, "DC_LINE_LENGTH", "DC_ENV_ARGS", "DC_EXPR_EXIT");
}
#endif // DC_ENABLED

202
contrib/bc/src/dc/lex.c Normal file
View File

@ -0,0 +1,202 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 lexer for dc.
*
*/
#if DC_ENABLED
#include <ctype.h>
#include <status.h>
#include <lex.h>
#include <dc.h>
#include <vm.h>
bool dc_lex_negCommand(BcLex *l) {
char c = l->buf[l->i];
return !BC_LEX_NUM_CHAR(c, false, false);
}
static void dc_lex_register(BcLex *l) {
if (DC_X && isspace(l->buf[l->i - 1])) {
char c;
bc_lex_whitespace(l);
c = l->buf[l->i];
if (!isalnum(c) && c != '_')
bc_lex_verr(l, BC_ERROR_PARSE_CHAR, c);
l->i += 1;
bc_lex_name(l);
}
else {
bc_vec_npop(&l->str, l->str.len);
bc_vec_pushByte(&l->str, (uchar) l->buf[l->i - 1]);
bc_vec_pushByte(&l->str, '\0');
l->t = BC_LEX_NAME;
}
}
static void dc_lex_string(BcLex *l) {
size_t depth = 1, nls = 0, i = l->i;
char c;
l->t = BC_LEX_STR;
bc_vec_npop(&l->str, l->str.len);
for (; (c = l->buf[i]) && depth; ++i) {
if (c == '\\') {
c = l->buf[++i];
if (!c) break;
}
else {
depth += (c == '[');
depth -= (c == ']');
}
nls += (c == '\n');
if (depth) bc_vec_push(&l->str, &c);
}
if (BC_ERR(c == '\0' && depth)) {
l->i = i;
bc_lex_err(l, BC_ERROR_PARSE_STRING);
}
bc_vec_pushByte(&l->str, '\0');
l->i = i;
l->line += nls;
}
void dc_lex_token(BcLex *l) {
char c = l->buf[l->i++], c2;
size_t i;
for (i = 0; i < dc_lex_regs_len; ++i) {
if (l->last == dc_lex_regs[i]) {
dc_lex_register(l);
return;
}
}
if (c >= '"' && c <= '~' &&
(l->t = dc_lex_tokens[(c - '"')]) != BC_LEX_INVALID)
{
return;
}
// This is the workhorse of the lexer.
switch (c) {
case '\0':
case '\n':
case '\t':
case '\v':
case '\f':
case '\r':
case ' ':
{
bc_lex_commonTokens(l, c);
break;
}
case '!':
{
c2 = l->buf[l->i];
if (c2 == '=') l->t = BC_LEX_OP_REL_NE;
else if (c2 == '<') l->t = BC_LEX_OP_REL_LE;
else if (c2 == '>') l->t = BC_LEX_OP_REL_GE;
else bc_lex_invalidChar(l, c);
l->i += 1;
break;
}
case '#':
{
bc_lex_lineComment(l);
break;
}
case '.':
{
c2 = l->buf[l->i];
if (BC_NO_ERR(BC_LEX_NUM_CHAR(c2, true, false)))
bc_lex_number(l, c);
else bc_lex_invalidChar(l, c);
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
{
bc_lex_number(l, c);
break;
}
case '[':
{
dc_lex_string(l);
break;
}
default:
{
bc_lex_invalidChar(l, c);
}
}
}
#endif // DC_ENABLED

236
contrib/bc/src/dc/parse.c Normal file
View File

@ -0,0 +1,236 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 parser for dc.
*
*/
#if DC_ENABLED
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include <status.h>
#include <parse.h>
#include <dc.h>
#include <program.h>
#include <vm.h>
static void dc_parse_register(BcParse *p, bool var) {
bc_lex_next(&p->l);
if (p->l.t != BC_LEX_NAME) bc_parse_err(p, BC_ERROR_PARSE_TOKEN);
bc_parse_pushName(p, p->l.str.v, var);
}
static inline void dc_parse_string(BcParse *p) {
bc_parse_addString(p);
bc_lex_next(&p->l);
}
static void dc_parse_mem(BcParse *p, uchar inst, bool name, bool store) {
bc_parse_push(p, inst);
if (name) dc_parse_register(p, inst != BC_INST_ARRAY_ELEM);
if (store) {
bc_parse_push(p, BC_INST_SWAP);
bc_parse_push(p, BC_INST_ASSIGN_NO_VAL);
}
bc_lex_next(&p->l);
}
static void dc_parse_cond(BcParse *p, uchar inst) {
bc_parse_push(p, inst);
bc_parse_push(p, BC_INST_EXEC_COND);
dc_parse_register(p, true);
bc_lex_next(&p->l);
if (p->l.t == BC_LEX_KW_ELSE) {
dc_parse_register(p, true);
bc_lex_next(&p->l);
}
else bc_parse_pushIndex(p, SIZE_MAX);
}
static void dc_parse_token(BcParse *p, BcLexType t, uint8_t flags) {
uchar inst;
bool assign, get_token = false;
switch (t) {
case BC_LEX_OP_REL_EQ:
case BC_LEX_OP_REL_LE:
case BC_LEX_OP_REL_GE:
case BC_LEX_OP_REL_NE:
case BC_LEX_OP_REL_LT:
case BC_LEX_OP_REL_GT:
{
inst = (uchar) (t - BC_LEX_OP_REL_EQ + BC_INST_REL_EQ);
dc_parse_cond(p, inst);
break;
}
case BC_LEX_SCOLON:
case BC_LEX_COLON:
{
dc_parse_mem(p, BC_INST_ARRAY_ELEM, true, t == BC_LEX_COLON);
break;
}
case BC_LEX_STR:
{
dc_parse_string(p);
break;
}
case BC_LEX_NEG:
{
if (dc_lex_negCommand(&p->l)) {
bc_parse_push(p, BC_INST_NEG);
get_token = true;
break;
}
bc_lex_next(&p->l);
}
// Fallthrough.
case BC_LEX_NUMBER:
{
bc_parse_number(p);
if (t == BC_LEX_NEG) bc_parse_push(p, BC_INST_NEG);
get_token = true;
break;
}
case BC_LEX_KW_READ:
{
if (BC_ERR(flags & BC_PARSE_NOREAD))
bc_parse_err(p, BC_ERROR_EXEC_REC_READ);
else bc_parse_push(p, BC_INST_READ);
get_token = true;
break;
}
case BC_LEX_OP_ASSIGN:
case BC_LEX_STORE_PUSH:
{
assign = t == BC_LEX_OP_ASSIGN;
inst = assign ? BC_INST_VAR : BC_INST_PUSH_TO_VAR;
dc_parse_mem(p, inst, true, assign);
break;
}
case BC_LEX_LOAD:
case BC_LEX_LOAD_POP:
{
inst = t == BC_LEX_LOAD_POP ? BC_INST_PUSH_VAR : BC_INST_LOAD;
dc_parse_mem(p, inst, true, false);
break;
}
case BC_LEX_STORE_IBASE:
case BC_LEX_STORE_OBASE:
case BC_LEX_STORE_SCALE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_STORE_SEED:
#endif // BC_ENABLE_EXTRA_MATH
{
inst = (uchar) (t - BC_LEX_STORE_IBASE + BC_INST_IBASE);
dc_parse_mem(p, inst, false, true);
break;
}
default:
{
bc_parse_err(p, BC_ERROR_PARSE_TOKEN);
}
}
if (get_token) bc_lex_next(&p->l);
}
void dc_parse_expr(BcParse *p, uint8_t flags) {
BcInst inst;
BcLexType t;
bool have_expr = false, need_expr = (flags & BC_PARSE_NOREAD) != 0;
while ((t = p->l.t) != BC_LEX_EOF) {
if (t == BC_LEX_NLINE) {
bc_lex_next(&p->l);
continue;
}
inst = dc_parse_insts[t];
if (inst != BC_INST_INVALID) {
bc_parse_push(p, inst);
bc_lex_next(&p->l);
}
else dc_parse_token(p, t, flags);
have_expr = true;
}
if (BC_ERR(need_expr && !have_expr))
bc_vm_err(BC_ERROR_EXEC_READ_EXPR);
else if (p->l.t == BC_LEX_EOF && (flags & BC_PARSE_NOCALL))
bc_parse_push(p, BC_INST_POP_EXEC);
}
void dc_parse_parse(BcParse *p) {
assert(p != NULL);
BC_SETJMP(exit);
if (BC_ERR(p->l.t == BC_LEX_EOF)) bc_parse_err(p, BC_ERROR_PARSE_EOF);
else dc_parse_expr(p, 0);
exit:
BC_SIG_MAYLOCK;
if (BC_ERR(vm.status)) bc_parse_reset(p);
BC_LONGJMP_CONT;
}
#endif // DC_ENABLED

225
contrib/bc/src/file.c Normal file
View File

@ -0,0 +1,225 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Code for implementing buffered I/O on my own terms.
*
*/
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <file.h>
#include <vm.h>
void bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH]) {
char buf2[BC_FILE_ULL_LENGTH];
size_t i, len;
memset(buf2, 0, BC_FILE_ULL_LENGTH);
// The i = 1 is to ensure that there is a null byte at the end.
for (i = 1; val; ++i) {
unsigned long long mod = val % 10;
buf2[i] = ((char) mod) + '0';
val /= 10;
}
len = i;
for (i = 0; i < len; ++i) buf[i] = buf2[len - i - 1];
}
static BcStatus bc_file_output(int fd, const char *buf, size_t n) {
size_t bytes = 0;
sig_atomic_t lock;
BC_SIG_TRYLOCK(lock);
while (bytes < n) {
ssize_t written = write(fd, buf + bytes, n - bytes);
if (BC_ERR(written == -1))
return errno == EPIPE ? BC_STATUS_EOF : BC_STATUS_ERROR_FATAL;
bytes += (size_t) written;
}
BC_SIG_TRYUNLOCK(lock);
return BC_STATUS_SUCCESS;
}
BcStatus bc_file_flushErr(BcFile *restrict f) {
BcStatus s;
if (f->len) {
s = bc_file_output(f->fd, f->buf, f->len);
f->len = 0;
}
else s = BC_STATUS_SUCCESS;
return s;
}
void bc_file_flush(BcFile *restrict f) {
BcStatus s = bc_file_flushErr(f);
if (BC_ERR(s)) {
if (s == BC_STATUS_EOF) {
vm.status = (sig_atomic_t) s;
BC_VM_JMP;
}
else bc_vm_err(BC_ERROR_FATAL_IO_ERR);
}
}
void bc_file_write(BcFile *restrict f, const char *buf, size_t n) {
if (n > f->cap - f->len) {
bc_file_flush(f);
assert(!f->len);
}
if (BC_UNLIKELY(n > f->cap - f->len)) bc_file_output(f->fd, buf, n);
else {
memcpy(f->buf + f->len, buf, n);
f->len += n;
}
}
void bc_file_printf(BcFile *restrict f, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
bc_file_vprintf(f, fmt, args);
va_end(args);
}
void bc_file_vprintf(BcFile *restrict f, const char *fmt, va_list args) {
char *percent;
const char *ptr = fmt;
char buf[BC_FILE_ULL_LENGTH];
while ((percent = strchr(ptr, '%')) != NULL) {
char c;
if (percent != ptr) {
size_t len = (size_t) (percent - ptr);
bc_file_write(f, ptr, len);
}
c = percent[1];
if (c == 'c') {
uchar uc = (uchar) va_arg(args, int);
bc_file_putchar(f, uc);
}
else if (c == 's') {
char *s = va_arg(args, char*);
bc_file_puts(f, s);
}
#if BC_DEBUG_CODE
else if (c == 'd') {
int d = va_arg(args, int);
if (d < 0) {
bc_file_putchar(f, '-');
d = -d;
}
if (!d) bc_file_putchar(f, '0');
else {
bc_file_ultoa((unsigned long long) d, buf);
bc_file_puts(f, buf);
}
}
#endif // BC_DEBUG_CODE
else {
unsigned long long ull;
assert((c == 'l' || c == 'z') && percent[2] == 'u');
if (c == 'z') ull = (unsigned long long) va_arg(args, size_t);
else ull = (unsigned long long) va_arg(args, unsigned long);
if (!ull) bc_file_putchar(f, '0');
else {
bc_file_ultoa(ull, buf);
bc_file_puts(f, buf);
}
}
ptr = percent + 2 + (c == 'l' || c == 'z');
}
if (ptr[0]) bc_file_puts(f, ptr);
}
void bc_file_puts(BcFile *restrict f, const char *str) {
bc_file_write(f, str, strlen(str));
}
void bc_file_putchar(BcFile *restrict f, uchar c) {
if (f->len == f->cap) bc_file_flush(f);
assert(f->len < f->cap);
f->buf[f->len] = (char) c;
f->len += 1;
}
void bc_file_init(BcFile *f, int fd, char *buf, size_t cap) {
BC_SIG_ASSERT_LOCKED;
f->fd = fd;
f->buf = buf;
f->len = 0;
f->cap = cap;
}
void bc_file_free(BcFile *f) {
BC_SIG_ASSERT_LOCKED;
bc_file_flush(f);
}

File diff suppressed because it is too large Load Diff

313
contrib/bc/src/lang.c Normal file
View File

@ -0,0 +1,313 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Code to manipulate data structures in programs.
*
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <lang.h>
#include <vm.h>
#ifndef NDEBUG
void bc_id_free(void *id) {
BC_SIG_ASSERT_LOCKED;
assert(id != NULL);
free(((BcId*) id)->name);
}
#endif // NDEBUG
void bc_string_free(void *string) {
BC_SIG_ASSERT_LOCKED;
assert(string != NULL && (*((char**) string)) != NULL);
if (BC_IS_BC) free(*((char**) string));
}
void bc_const_free(void *constant) {
BcConst *c = constant;
BC_SIG_ASSERT_LOCKED;
assert(c->val != NULL);
free(c->val);
bc_num_free(&c->num);
}
#if BC_ENABLED
void bc_func_insert(BcFunc *f, BcProgram *p, char *name,
BcType type, size_t line)
{
BcLoc a;
size_t i, idx;
assert(f != NULL);
idx = bc_program_search(p, name, type == BC_TYPE_VAR);
for (i = 0; i < f->autos.len; ++i) {
BcLoc *id = bc_vec_item(&f->autos, i);
if (BC_ERR(idx == id->loc && type == (BcType) id->idx)) {
const char *array = type == BC_TYPE_ARRAY ? "[]" : "";
bc_vm_error(BC_ERROR_PARSE_DUP_LOCAL, line, name, array);
}
}
a.loc = idx;
a.idx = type;
bc_vec_push(&f->autos, &a);
}
#endif // BC_ENABLED
void bc_func_init(BcFunc *f, const char *name) {
BC_SIG_ASSERT_LOCKED;
assert(f != NULL && name != NULL);
bc_vec_init(&f->code, sizeof(uchar), NULL);
// This is necessary for not allocating memory where it isn't used.
// dc does not use strings except in the main function. The else part
// is necessary to stop uninitiazed data errors in valgrind.
if (BC_IS_BC || !strcmp(name, bc_func_main))
bc_vec_init(&f->strs, sizeof(char*), bc_string_free);
#if BC_ENABLE_FUNC_FREE
else bc_vec_clear(&f->strs);
#endif // BC_ENABLE_FUNC_FREE
bc_vec_init(&f->consts, sizeof(BcConst), bc_const_free);
#if BC_ENABLED
if (BC_IS_BC) {
bc_vec_init(&f->autos, sizeof(BcLoc), NULL);
bc_vec_init(&f->labels, sizeof(size_t), NULL);
f->nparams = 0;
f->voidfn = false;
}
#endif // BC_ENABLED
f->name = name;
}
void bc_func_reset(BcFunc *f) {
BC_SIG_ASSERT_LOCKED;
assert(f != NULL);
bc_vec_npop(&f->code, f->code.len);
bc_vec_npop(&f->strs, f->strs.len);
bc_vec_npop(&f->consts, f->consts.len);
#if BC_ENABLED
if (BC_IS_BC) {
bc_vec_npop(&f->autos, f->autos.len);
bc_vec_npop(&f->labels, f->labels.len);
f->nparams = 0;
f->voidfn = false;
}
#endif // BC_ENABLED
}
void bc_func_free(void *func) {
#if BC_ENABLE_FUNC_FREE
BcFunc *f = (BcFunc*) func;
BC_SIG_ASSERT_LOCKED;
assert(f != NULL);
bc_vec_free(&f->code);
bc_vec_free(&f->strs);
bc_vec_free(&f->consts);
#if BC_ENABLED
#ifndef NDEBUG
if (BC_IS_BC) {
bc_vec_free(&f->autos);
bc_vec_free(&f->labels);
}
#endif // NDEBUG
#endif // BC_ENABLED
#else // BC_ENABLE_FUNC_FREE
BC_UNUSED(func);
#endif // BC_ENABLE_FUNC_FREE
}
void bc_array_init(BcVec *a, bool nums) {
BC_SIG_ASSERT_LOCKED;
if (nums) bc_vec_init(a, sizeof(BcNum), bc_num_free);
else bc_vec_init(a, sizeof(BcVec), bc_vec_free);
bc_array_expand(a, 1);
}
void bc_array_copy(BcVec *d, const BcVec *s) {
size_t i;
BC_SIG_ASSERT_LOCKED;
assert(d != NULL && s != NULL);
assert(d != s && d->size == s->size && d->dtor == s->dtor);
bc_vec_npop(d, d->len);
bc_vec_expand(d, s->cap);
d->len = s->len;
for (i = 0; i < s->len; ++i) {
BcNum *dnum = bc_vec_item(d, i), *snum = bc_vec_item(s, i);
bc_num_createCopy(dnum, snum);
}
}
void bc_array_expand(BcVec *a, size_t len) {
assert(a != NULL);
BC_SIG_ASSERT_LOCKED;
bc_vec_expand(a, len);
if (a->size == sizeof(BcNum) && a->dtor == bc_num_free) {
BcNum n;
while (len > a->len) {
bc_num_init(&n, BC_NUM_DEF_SIZE);
bc_vec_push(a, &n);
}
}
else {
BcVec v;
assert(a->size == sizeof(BcVec) && a->dtor == bc_vec_free);
while (len > a->len) {
bc_array_init(&v, true);
bc_vec_push(a, &v);
}
}
}
void bc_result_clear(BcResult *r) {
r->t = BC_RESULT_TEMP;
bc_num_clear(&r->d.n);
}
#if DC_ENABLED
void bc_result_copy(BcResult *d, BcResult *src) {
assert(d != NULL && src != NULL);
BC_SIG_ASSERT_LOCKED;
d->t = src->t;
switch (d->t) {
case BC_RESULT_TEMP:
case BC_RESULT_IBASE:
case BC_RESULT_SCALE:
case BC_RESULT_OBASE:
#if BC_ENABLE_EXTRA_MATH
case BC_RESULT_SEED:
#endif // BC_ENABLE_EXTRA_MATH
{
bc_num_createCopy(&d->d.n, &src->d.n);
break;
}
case BC_RESULT_VAR:
#if BC_ENABLED
case BC_RESULT_ARRAY:
#endif // BC_ENABLED
case BC_RESULT_ARRAY_ELEM:
{
memcpy(&d->d.loc, &src->d.loc, sizeof(BcLoc));
break;
}
case BC_RESULT_CONSTANT:
case BC_RESULT_STR:
{
memcpy(&d->d.n, &src->d.n, sizeof(BcNum));
break;
}
case BC_RESULT_ONE:
{
// Do nothing.
break;
}
#if BC_ENABLED
case BC_RESULT_VOID:
case BC_RESULT_LAST:
{
#ifndef NDEBUG
abort();
#endif // NDEBUG
}
#endif // BC_ENABLED
}
}
#endif // DC_ENABLED
void bc_result_free(void *result) {
BcResult *r = (BcResult*) result;
BC_SIG_ASSERT_LOCKED;
assert(r != NULL);
switch (r->t) {
case BC_RESULT_TEMP:
case BC_RESULT_IBASE:
case BC_RESULT_SCALE:
case BC_RESULT_OBASE:
#if BC_ENABLE_EXTRA_MATH
case BC_RESULT_SEED:
#endif // BC_ENABLE_EXTRA_MATH
{
bc_num_free(&r->d.n);
break;
}
case BC_RESULT_VAR:
#if BC_ENABLED
case BC_RESULT_ARRAY:
#endif // BC_ENABLED
case BC_RESULT_ARRAY_ELEM:
case BC_RESULT_STR:
case BC_RESULT_CONSTANT:
case BC_RESULT_ONE:
#if BC_ENABLED
case BC_RESULT_VOID:
case BC_RESULT_LAST:
#endif // BC_ENABLED
{
// Do nothing.
break;
}
}
}

231
contrib/bc/src/lex.c Normal file
View File

@ -0,0 +1,231 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Common code for the lexers.
*
*/
#include <assert.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <status.h>
#include <lex.h>
#include <vm.h>
#include <bc.h>
void bc_lex_invalidChar(BcLex *l, char c) {
l->t = BC_LEX_INVALID;
bc_lex_verr(l, BC_ERROR_PARSE_CHAR, c);
}
void bc_lex_lineComment(BcLex *l) {
l->t = BC_LEX_WHITESPACE;
while (l->i < l->len && l->buf[l->i] != '\n') l->i += 1;
}
void bc_lex_comment(BcLex *l) {
size_t i, nlines = 0;
const char *buf = l->buf;
bool end = false;
char c;
l->i += 1;
l->t = BC_LEX_WHITESPACE;
for (i = l->i; !end; i += !end) {
for (; (c = buf[i]) && c != '*'; ++i) nlines += (c == '\n');
if (BC_ERR(!c || buf[i + 1] == '\0')) {
l->i = i;
bc_lex_err(l, BC_ERROR_PARSE_COMMENT);
}
end = buf[i + 1] == '/';
}
l->i = i + 2;
l->line += nlines;
}
void bc_lex_whitespace(BcLex *l) {
char c;
l->t = BC_LEX_WHITESPACE;
for (c = l->buf[l->i]; c != '\n' && isspace(c); c = l->buf[++l->i]);
}
void bc_lex_commonTokens(BcLex *l, char c) {
if (!c) l->t = BC_LEX_EOF;
else if (c == '\n') l->t = BC_LEX_NLINE;
else bc_lex_whitespace(l);
}
static size_t bc_lex_num(BcLex *l, char start, bool int_only) {
const char *buf = l->buf + l->i;
size_t i;
char c;
bool last_pt, pt = (start == '.');
for (i = 0; (c = buf[i]) && (BC_LEX_NUM_CHAR(c, pt, int_only) ||
(c == '\\' && buf[i + 1] == '\n')); ++i)
{
if (c == '\\') {
if (buf[i + 1] == '\n') {
i += 2;
// Make sure to eat whitespace at the beginning of the line.
while(isspace(buf[i]) && buf[i] != '\n') i += 1;
c = buf[i];
if (!BC_LEX_NUM_CHAR(c, pt, int_only)) break;
}
else break;
}
last_pt = (c == '.');
if (pt && last_pt) break;
pt = pt || last_pt;
bc_vec_push(&l->str, &c);
}
return i;
}
void bc_lex_number(BcLex *l, char start) {
l->t = BC_LEX_NUMBER;
bc_vec_npop(&l->str, l->str.len);
bc_vec_push(&l->str, &start);
l->i += bc_lex_num(l, start, false);
#if BC_ENABLE_EXTRA_MATH
{
char c = l->buf[l->i];
if (c == 'e') {
#if BC_ENABLED
if (BC_IS_POSIX) bc_lex_err(l, BC_ERROR_POSIX_EXP_NUM);
#endif // BC_ENABLED
bc_vec_push(&l->str, &c);
l->i += 1;
c = l->buf[l->i];
if (c == BC_LEX_NEG_CHAR) {
bc_vec_push(&l->str, &c);
l->i += 1;
c = l->buf[l->i];
}
if (BC_ERR(!BC_LEX_NUM_CHAR(c, false, true)))
bc_lex_verr(l, BC_ERROR_PARSE_CHAR, c);
l->i += bc_lex_num(l, 0, true);
}
}
#endif // BC_ENABLE_EXTRA_MATH
bc_vec_pushByte(&l->str, '\0');
}
void bc_lex_name(BcLex *l) {
size_t i = 0;
const char *buf = l->buf + l->i - 1;
char c = buf[i];
l->t = BC_LEX_NAME;
while ((c >= 'a' && c <= 'z') || isdigit(c) || c == '_') c = buf[++i];
bc_vec_string(&l->str, i, buf);
// Increment the index. We minus 1 because it has already been incremented.
l->i += i - 1;
}
void bc_lex_init(BcLex *l) {
BC_SIG_ASSERT_LOCKED;
assert(l != NULL);
bc_vec_init(&l->str, sizeof(char), NULL);
}
void bc_lex_free(BcLex *l) {
BC_SIG_ASSERT_LOCKED;
assert(l != NULL);
bc_vec_free(&l->str);
}
void bc_lex_file(BcLex *l, const char *file) {
assert(l != NULL && file != NULL);
l->line = 1;
vm.file = file;
}
void bc_lex_next(BcLex *l) {
assert(l != NULL);
l->last = l->t;
l->line += (l->i != 0 && l->buf[l->i - 1] == '\n');
if (BC_ERR(l->last == BC_LEX_EOF)) bc_lex_err(l, BC_ERROR_PARSE_EOF);
l->t = BC_LEX_EOF;
if (l->i == l->len) return;
// Loop until failure or we don't have whitespace. This
// is so the parser doesn't get inundated with whitespace.
do {
vm.next(l);
} while (l->t == BC_LEX_WHITESPACE);
}
void bc_lex_text(BcLex *l, const char *text) {
assert(l != NULL && text != NULL);
l->buf = text;
l->i = 0;
l->len = strlen(text);
l->t = l->last = BC_LEX_INVALID;
bc_lex_next(l);
}

93
contrib/bc/src/main.c Normal file
View File

@ -0,0 +1,93 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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 entry point for bc.
*
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <libgen.h>
#include <setjmp.h>
#include <status.h>
#include <vm.h>
#include <bc.h>
#include <dc.h>
char output_bufs[BC_VM_BUF_SIZE];
BcVm vm;
int main(int argc, char *argv[]) {
int s;
char *name;
size_t len = strlen(BC_EXECPREFIX);
vm.locale = setlocale(LC_ALL, "");
name = strrchr(argv[0], '/');
vm.name = (name == NULL) ? argv[0] : name + 1;
if (strlen(vm.name) > len) vm.name += len;
BC_SIG_LOCK;
bc_vec_init(&vm.jmp_bufs, sizeof(sigjmp_buf), NULL);
BC_SETJMP_LOCKED(exit);
#if !DC_ENABLED
bc_main(argc, argv);
#elif !BC_ENABLED
dc_main(argc, argv);
#else
if (BC_IS_BC) bc_main(argc, argv);
else dc_main(argc, argv);
#endif
exit:
BC_SIG_MAYLOCK;
s = !BC_STATUS_IS_ERROR(vm.status) ? BC_STATUS_SUCCESS : (int) vm.status;
bc_vm_shutdown();
#ifndef NDEBUG
bc_vec_free(&vm.jmp_bufs);
#endif // NDEBUG
return s;
}

2837
contrib/bc/src/num.c Normal file

File diff suppressed because it is too large Load Diff

250
contrib/bc/src/opt.c Normal file
View File

@ -0,0 +1,250 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Adapted from https://github.com/skeeto/optparse
*
* *****************************************************************************
*
* Code for getopt_long() replacement. It turns out that getopt_long() has
* different behavior on different platforms.
*
*/
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <status.h>
#include <opt.h>
#include <vm.h>
static inline bool bc_opt_longoptsEnd(const BcOptLong *longopts, size_t i) {
return !longopts[i].name && !longopts[i].val;
}
static const char* bc_opt_longopt(const BcOptLong *longopts, int c) {
size_t i;
for (i = 0; !bc_opt_longoptsEnd(longopts, i); ++i) {
if (longopts[i].val == c) return longopts[i].name;
}
return "NULL";
}
static void bc_opt_error(BcError err, int c, const char *str) {
if (err == BC_ERROR_FATAL_OPTION) bc_vm_error(err, 0, str);
else bc_vm_error(err, 0, (int) c, str);
}
static int bc_opt_type(const BcOptLong *longopts, char c) {
size_t i;
if (c == ':') return -1;
for (i = 0; !bc_opt_longoptsEnd(longopts, i) && longopts[i].val != c; ++i);
if (bc_opt_longoptsEnd(longopts, i)) return -1;
return (int) longopts[i].type;
}
static int bc_opt_parseShort(BcOpt *o, const BcOptLong *longopts) {
int type;
char *next;
char *option = o->argv[o->optind];
int ret = -1;
o->optopt = 0;
o->optarg = NULL;
option += o->subopt + 1;
o->optopt = option[0];
type = bc_opt_type(longopts, option[0]);
next = o->argv[o->optind + 1];
switch (type) {
case -1:
case BC_OPT_BC_ONLY:
case BC_OPT_DC_ONLY:
{
if (type == -1 || (type == BC_OPT_BC_ONLY && !BC_IS_BC) ||
(type == BC_OPT_DC_ONLY && BC_IS_BC))
{
char str[2] = {0, 0};
str[0] = option[0];
o->optind += 1;
bc_opt_error(BC_ERROR_FATAL_OPTION, option[0], str);
}
}
// Fallthrough.
case BC_OPT_NONE:
{
if (option[1]) o->subopt += 1;
else {
o->subopt = 0;
o->optind += 1;
}
ret = (int) option[0];
break;
}
case BC_OPT_REQUIRED:
{
o->subopt = 0;
o->optind += 1;
if (option[1]) o->optarg = option + 1;
else if (next != NULL) {
o->optarg = next;
o->optind += 1;
}
else bc_opt_error(BC_ERROR_FATAL_OPTION_NO_ARG, option[0],
bc_opt_longopt(longopts, option[0]));
ret = (int) option[0];
break;
}
}
return ret;
}
static bool bc_opt_longoptsMatch(const char *name, const char *option) {
const char *a = option, *n = name;
if (name == NULL) return false;
for (; *a && *n && *a != '='; ++a, ++n) {
if (*a != *n) return false;
}
return (*n == '\0' && (*a == '\0' || *a == '='));
}
static char* bc_opt_longoptsArg(char *option) {
for (; *option && *option != '='; ++option);
if (*option == '=') return option + 1;
else return NULL;
}
int bc_opt_parse(BcOpt *o, const BcOptLong *longopts) {
size_t i;
char *option;
bool empty;
do {
option = o->argv[o->optind];
if (option == NULL) return -1;
empty = !strcmp(option, "");
o->optind += empty;
} while (empty);
if (BC_OPT_ISDASHDASH(option)) {
// Consume "--".
o->optind += 1;
return -1;
}
else if (BC_OPT_ISSHORTOPT(option)) return bc_opt_parseShort(o, longopts);
else if (!BC_OPT_ISLONGOPT(option)) return -1;
o->optopt = 0;
o->optarg = NULL;
// Skip "--" at beginning of the option.
option += 2;
o->optind += 1;
for (i = 0; !bc_opt_longoptsEnd(longopts, i); i++) {
const char *name = longopts[i].name;
if (bc_opt_longoptsMatch(name, option)) {
char *arg;
o->optopt = longopts[i].val;
arg = bc_opt_longoptsArg(option);
if ((longopts[i].type == BC_OPT_BC_ONLY && !BC_IS_BC) ||
(longopts[i].type == BC_OPT_DC_ONLY && BC_IS_BC))
{
bc_opt_error(BC_ERROR_FATAL_OPTION, o->optopt, name);
}
if (longopts[i].type == BC_OPT_NONE && arg != NULL)
{
bc_opt_error(BC_ERROR_FATAL_OPTION_ARG, o->optopt, name);
}
if (arg != NULL) o->optarg = arg;
else if (longopts[i].type == BC_OPT_REQUIRED) {
o->optarg = o->argv[o->optind];
if (o->optarg != NULL) o->optind += 1;
else bc_opt_error(BC_ERROR_FATAL_OPTION_NO_ARG,
o->optopt, name);
}
return o->optopt;
}
}
bc_opt_error(BC_ERROR_FATAL_OPTION, 0, option);
return -1;
}
void bc_opt_init(BcOpt *o, char *argv[]) {
o->argv = argv;
o->optind = 1;
o->subopt = 0;
o->optarg = NULL;
}

222
contrib/bc/src/parse.c Normal file
View File

@ -0,0 +1,222 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Code common to the parsers.
*
*/
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <status.h>
#include <vector.h>
#include <lex.h>
#include <parse.h>
#include <program.h>
#include <vm.h>
void bc_parse_updateFunc(BcParse *p, size_t fidx) {
p->fidx = fidx;
p->func = bc_vec_item(&p->prog->fns, fidx);
}
inline void bc_parse_pushName(const BcParse *p, char *name, bool var) {
bc_parse_pushIndex(p, bc_program_search(p->prog, name, var));
}
static void bc_parse_update(BcParse *p, uchar inst, size_t idx) {
bc_parse_updateFunc(p, p->fidx);
bc_parse_push(p, inst);
bc_parse_pushIndex(p, idx);
}
void bc_parse_addString(BcParse *p) {
BcFunc *f = BC_IS_BC ? p->func : bc_vec_item(&p->prog->fns, BC_PROG_MAIN);
size_t idx;
BC_SIG_LOCK;
if (BC_IS_BC) {
const char *str = bc_vm_strdup(p->l.str.v);
idx = f->strs.len;
bc_vec_push(&f->strs, &str);
}
#if DC_ENABLED
else idx = bc_program_insertFunc(p->prog, p->l.str.v) - BC_PROG_REQ_FUNCS;
#endif // DC_ENABLED
#ifndef NDEBUG
f = BC_IS_BC ? p->func : bc_vec_item(&p->prog->fns, BC_PROG_MAIN);
assert(f->strs.len > idx);
#endif // NDEBUG
bc_parse_update(p, BC_INST_STR, idx);
BC_SIG_UNLOCK;
}
static void bc_parse_addNum(BcParse *p, const char *string) {
BcFunc *f = BC_IS_BC ? p->func : bc_vec_item(&p->prog->fns, BC_PROG_MAIN);
size_t idx;
BcConst c;
if (bc_parse_one[0] == string[0] && bc_parse_one[1] == string[1]) {
bc_parse_push(p, BC_INST_ONE);
return;
}
idx = f->consts.len;
BC_SIG_LOCK;
c.val = bc_vm_strdup(string);
c.base = BC_NUM_BIGDIG_MAX;
bc_num_clear(&c.num);
bc_vec_push(&f->consts, &c);
bc_parse_update(p, BC_INST_NUM, idx);
BC_SIG_UNLOCK;
}
void bc_parse_number(BcParse *p) {
#if BC_ENABLE_EXTRA_MATH
char *exp = strchr(p->l.str.v, 'e');
size_t idx = SIZE_MAX;
if (exp != NULL) {
idx = ((size_t) (exp - p->l.str.v));
*exp = 0;
}
#endif // BC_ENABLE_EXTRA_MATH
bc_parse_addNum(p, p->l.str.v);
#if BC_ENABLE_EXTRA_MATH
if (exp != NULL) {
bool neg;
neg = (*((char*) bc_vec_item(&p->l.str, idx + 1)) == BC_LEX_NEG_CHAR);
bc_parse_addNum(p, bc_vec_item(&p->l.str, idx + 1 + neg));
bc_parse_push(p, BC_INST_LSHIFT + neg);
}
#endif // BC_ENABLE_EXTRA_MATH
}
void bc_parse_text(BcParse *p, const char *text) {
// Make sure the pointer isn't invalidated.
p->func = bc_vec_item(&p->prog->fns, p->fidx);
bc_lex_text(&p->l, text);
}
void bc_parse_reset(BcParse *p) {
BC_SIG_ASSERT_LOCKED;
if (p->fidx != BC_PROG_MAIN) {
bc_func_reset(p->func);
bc_parse_updateFunc(p, BC_PROG_MAIN);
}
p->l.i = p->l.len;
p->l.t = BC_LEX_EOF;
p->auto_part = false;
#if BC_ENABLED
if (BC_IS_BC) {
bc_vec_npop(&p->flags, p->flags.len - 1);
bc_vec_npop(&p->exits, p->exits.len);
bc_vec_npop(&p->conds, p->conds.len);
bc_vec_npop(&p->ops, p->ops.len);
}
#endif // BC_ENABLED
bc_program_reset(p->prog);
if (BC_ERR(vm.status)) BC_VM_JMP;
}
void bc_parse_free(BcParse *p) {
BC_SIG_ASSERT_LOCKED;
assert(p != NULL);
#if BC_ENABLED
if (BC_IS_BC) {
bc_vec_free(&p->flags);
bc_vec_free(&p->exits);
bc_vec_free(&p->conds);
bc_vec_free(&p->ops);
bc_vec_free(&p->buf);
}
#endif // BC_ENABLED
bc_lex_free(&p->l);
}
void bc_parse_init(BcParse *p, BcProgram *prog, size_t func) {
#if BC_ENABLED
uint16_t flag = 0;
#endif // BC_ENABLED
BC_SIG_ASSERT_LOCKED;
assert(p != NULL && prog != NULL);
#if BC_ENABLED
if (BC_IS_BC) {
bc_vec_init(&p->flags, sizeof(uint16_t), NULL);
bc_vec_push(&p->flags, &flag);
bc_vec_init(&p->exits, sizeof(BcInstPtr), NULL);
bc_vec_init(&p->conds, sizeof(size_t), NULL);
bc_vec_init(&p->ops, sizeof(BcLexType), NULL);
bc_vec_init(&p->buf, sizeof(char), NULL);
}
#endif // BC_ENABLED
bc_lex_init(&p->l);
p->prog = prog;
p->auto_part = false;
bc_parse_updateFunc(p, func);
}

2300
contrib/bc/src/program.c Normal file

File diff suppressed because it is too large Load Diff

415
contrib/bc/src/rand/rand.c Normal file
View File

@ -0,0 +1,415 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2019 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Parts of this code are adapted from the following:
*
* PCG, A Family of Better Random Number Generators.
*
* You can find the original source code at:
* https://github.com/imneme/pcg-c
*
* -----------------------------------------------------------------------------
*
* Parts of this code are also under the following license:
*
* Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* *****************************************************************************
*
* Code for the RNG.
*
*/
#if BC_ENABLE_EXTRA_MATH
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <status.h>
#include <num.h>
#include <rand.h>
#include <vm.h>
#if !BC_RAND_BUILTIN
static BcRandState bc_rand_addition(uint_fast64_t a, uint_fast64_t b) {
BcRandState res;
res.lo = a + b;
res.hi = (res.lo < a);
return res;
}
static BcRandState bc_rand_addition2(BcRandState a, BcRandState b) {
BcRandState temp, res;
res = bc_rand_addition(a.lo, b.lo);
temp = bc_rand_addition(a.hi, b.hi);
res.hi += temp.lo;
return res;
}
static BcRandState bc_rand_multiply(uint_fast64_t a, uint_fast64_t b) {
uint_fast64_t al, ah, bl, bh, c0, c1, c2, c3;
BcRandState carry, res;
al = BC_RAND_TRUNC32(a);
ah = BC_RAND_CHOP32(a);
bl = BC_RAND_TRUNC32(b);
bh = BC_RAND_CHOP32(b);
c0 = al * bl;
c1 = al * bh;
c2 = ah * bl;
c3 = ah * bh;
carry = bc_rand_addition(c1, c2);
res = bc_rand_addition(c0, (BC_RAND_TRUNC32(carry.lo)) << 32);
res.hi += BC_RAND_CHOP32(carry.lo) + c3 + (carry.hi << 32);
return res;
}
static BcRandState bc_rand_multiply2(BcRandState a, BcRandState b) {
BcRandState c0, c1, c2, carry;
c0 = bc_rand_multiply(a.lo, b.lo);
c1 = bc_rand_multiply(a.lo, b.hi);
c2 = bc_rand_multiply(a.hi, b.lo);
carry = bc_rand_addition2(c1, c2);
carry.hi = carry.lo;
carry.lo = 0;
return bc_rand_addition2(c0, carry);
}
#endif // BC_RAND_BUILTIN
static void bc_rand_setModified(BcRNGData *r) {
#if BC_RAND_BUILTIN
r->inc |= (BcRandState) 1UL;
#else // BC_RAND_BUILTIN
r->inc.lo |= (uint_fast64_t) 1UL;
#endif // BC_RAND_BUILTIN
}
static void bc_rand_clearModified(BcRNGData *r) {
#if BC_RAND_BUILTIN
r->inc &= ~((BcRandState) 1UL);
#else // BC_RAND_BUILTIN
r->inc.lo &= ~(1UL);
#endif // BC_RAND_BUILTIN
}
static void bc_rand_copy(BcRNGData *d, BcRNGData *s) {
bool unmod = BC_RAND_NOTMODIFIED(d);
memcpy(d, s, sizeof(BcRNGData));
if (!unmod) bc_rand_setModified(d);
else if (!BC_RAND_NOTMODIFIED(s)) bc_rand_clearModified(d);
}
static ulong bc_rand_frand(void *ptr) {
ulong buf[1];
int fd;
ssize_t nread;
assert(ptr != NULL);
fd = *((int*) ptr);
nread = read(fd, buf, sizeof(ulong));
if (BC_ERR(nread != sizeof(ulong))) bc_vm_err(BC_ERROR_FATAL_IO_ERR);
return *((ulong*) buf);
}
static ulong bc_rand_rand(void *ptr) {
size_t i;
ulong res = 0;
BC_UNUSED(ptr);
for (i = 0; i < sizeof(ulong); ++i)
res |= ((ulong) (rand() & BC_RAND_SRAND_BITS)) << (i * CHAR_BIT);
return res;
}
static BcRandState bc_rand_inc(BcRNGData *r) {
BcRandState inc;
#if BC_RAND_BUILTIN
inc = r->inc | 1;
#else // BC_RAND_BUILTIN
inc.lo = r->inc.lo | 1;
inc.hi = r->inc.hi;
#endif // BC_RAND_BUILTIN
return inc;
}
static void bc_rand_setInc(BcRNGData *r) {
#if BC_RAND_BUILTIN
r->inc <<= 1UL;
#else // BC_RAND_BUILTIN
r->inc.hi <<= 1UL;
r->inc.hi |= (r->inc.lo & (1UL << (BC_LONG_BIT - 1))) >> (BC_LONG_BIT - 1);
r->inc.lo <<= 1UL;
#endif // BC_RAND_BUILTIN
}
static void bc_rand_seedState(BcRandState *state, ulong val1, ulong val2) {
#if BC_RAND_BUILTIN
*state = ((BcRandState) val1) | ((BcRandState) val2) << (BC_LONG_BIT);
#else // BC_RAND_BUILTIN
state->lo = val1;
state->hi = val2;
#endif // BC_RAND_BUILTIN
}
static void bc_rand_seedRNG(BcRNGData *r, ulong state1, ulong state2,
ulong inc1, ulong inc2)
{
bc_rand_seedState(&r->state, state1, state2);
bc_rand_seedState(&r->inc, inc1, inc2);
bc_rand_setInc(r);
}
static void bc_rand_fill(BcRNGData *r, BcRandUlong fulong, void *ptr) {
ulong state1, state2, inc1, inc2;
state1 = fulong(ptr);
state2 = fulong(ptr);
inc1 = fulong(ptr);
inc2 = fulong(ptr);
bc_rand_seedRNG(r, state1, state2, inc1, inc2);
}
static void bc_rand_step(BcRNGData *r) {
BcRandState temp = bc_rand_mul2(r->state, bc_rand_multiplier);
r->state = bc_rand_add2(temp, bc_rand_inc(r));
}
static BcRand bc_rand_output(BcRNGData *r) {
return BC_RAND_ROT(BC_RAND_FOLD(r->state), BC_RAND_ROTAMT(r->state));
}
static void bc_rand_seedZeroes(BcRNG *r, BcRNGData *rng, size_t idx) {
BcRNGData *rng2;
if (r->v.len <= idx) return;
rng2 = bc_vec_item_rev(&r->v, idx);
if (BC_RAND_ZERO(rng2)) {
size_t i;
for (i = 1; i < r->v.len; ++i)
bc_rand_copy(bc_vec_item_rev(&r->v, i), rng);
}
}
static void bc_rand_srand(BcRNGData *rng) {
int fd;
BC_SIG_LOCK;
fd = open("/dev/urandom", O_RDONLY);
if (BC_NO_ERR(fd >= 0)) {
bc_rand_fill(rng, bc_rand_frand, &fd);
close(fd);
}
while (BC_ERR(BC_RAND_ZERO(rng))) bc_rand_fill(rng, bc_rand_rand, NULL);
BC_SIG_UNLOCK;
}
static void bc_rand_propagate(BcRNG *r, BcRNGData *rng) {
if (r->v.len <= 1) return;
if (BC_RAND_NOTMODIFIED(rng)) {
size_t i;
bool go = true;
for (i = 1; go && i < r->v.len; ++i) {
BcRNGData *rng2 = bc_vec_item_rev(&r->v, i);
go = BC_RAND_NOTMODIFIED(rng2);
bc_rand_copy(rng2, rng);
}
bc_rand_seedZeroes(r, rng, i);
}
else bc_rand_seedZeroes(r, rng, 1);
}
BcRand bc_rand_int(BcRNG *r) {
BcRNGData *rng = bc_vec_top(&r->v);
if (BC_ERR(BC_RAND_ZERO(rng))) bc_rand_srand(rng);
bc_rand_step(rng);
bc_rand_propagate(r, rng);
return bc_rand_output(rng);
}
BcRand bc_rand_bounded(BcRNG *r, BcRand bound) {
BcRand rand, threshold = (0 - bound) % bound;
do {
rand = bc_rand_int(r);
} while (rand < threshold);
return rand % bound;
}
void bc_rand_seed(BcRNG *r, ulong state1, ulong state2, ulong inc1, ulong inc2)
{
BcRNGData *rng = bc_vec_top(&r->v);
bc_rand_seedState(&rng->inc, inc1, inc2);
bc_rand_setInc(rng);
bc_rand_setModified(rng);
if (!state1 && !state2) {
memcpy(&rng->state, &rng->inc, sizeof(BcRandState));
bc_rand_step(rng);
}
else bc_rand_seedState(&rng->state, state1, state2);
bc_rand_propagate(r, rng);
}
static BcRandState bc_rand_getInc(BcRNGData *r) {
BcRandState res;
#if BC_RAND_BUILTIN
res = r->inc >> 1;
#else // BC_RAND_BUILTIN
res = r->inc;
res.lo >>= 1;
res.lo |= (res.hi & 1) << (BC_LONG_BIT - 1);
res.hi >>= 1;
#endif // BC_RAND_BUILTIN
return res;
}
void bc_rand_getRands(BcRNG *r, BcRand *s1, BcRand *s2, BcRand *i1, BcRand *i2)
{
BcRandState inc;
BcRNGData *rng = bc_vec_top(&r->v);
if (BC_ERR(BC_RAND_ZERO(rng))) bc_rand_srand(rng);
inc = bc_rand_getInc(rng);
*s1 = BC_RAND_TRUNC(rng->state);
*s2 = BC_RAND_CHOP(rng->state);
*i1 = BC_RAND_TRUNC(inc);
*i2 = BC_RAND_CHOP(inc);
}
void bc_rand_push(BcRNG *r) {
BcRNGData rng;
memset(&rng, 0, sizeof(BcRNGData));
if (r->v.len > 0) bc_rand_copy(&rng, bc_vec_top(&r->v));
bc_vec_push(&r->v, &rng);
}
void bc_rand_pop(BcRNG *r, bool reset) {
bc_vec_npop(&r->v, reset ? r->v.len - 1 : 1);
}
void bc_rand_init(BcRNG *r) {
BC_SIG_ASSERT_LOCKED;
bc_vec_init(&r->v, sizeof(BcRNGData), NULL);
bc_rand_push(r);
}
#ifndef NDEBUG
void bc_rand_free(BcRNG *r) {
BC_SIG_ASSERT_LOCKED;
bc_vec_free(&r->v);
}
#endif // NDEBUG
#endif // BC_ENABLE_EXTRA_MATH

226
contrib/bc/src/read.c Normal file
View File

@ -0,0 +1,226 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Code to handle special I/O for bc.
*
*/
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <read.h>
#include <history.h>
#include <program.h>
#include <vm.h>
static bool bc_read_binary(const char *buf, size_t size) {
size_t i;
for (i = 0; i < size; ++i) {
if (BC_ERR(BC_READ_BIN_CHAR(buf[i]))) return true;
}
return false;
}
static bool bc_read_buf(BcVec *vec) {
char *nl;
if (!vm.buf_len) return false;
nl = strchr(vm.buf, '\n');
if (nl != NULL) {
size_t nllen = (size_t) ((nl + 1) - vm.buf);
nllen = vm.buf_len >= nllen ? nllen : vm.buf_len;
bc_vec_npush(vec, nllen, vm.buf);
vm.buf_len -= nllen;
memmove(vm.buf, nl + 1, vm.buf_len);
return true;
}
bc_vec_npush(vec, vm.buf_len, vm.buf);
vm.buf_len = 0;
return false;
}
BcStatus bc_read_chars(BcVec *vec, const char *prompt) {
bool done = false;
assert(vec != NULL && vec->size == sizeof(char));
BC_SIG_ASSERT_NOT_LOCKED;
bc_vec_npop(vec, vec->len);
#if BC_ENABLE_PROMPT
if (BC_USE_PROMPT) {
bc_file_puts(&vm.fout, prompt);
bc_file_flush(&vm.fout);
}
#endif // BC_ENABLE_PROMPT
if (bc_read_buf(vec)) {
bc_vec_pushByte(vec, '\0');
return BC_STATUS_SUCCESS;
}
while (!done) {
ssize_t r;
BC_SIG_LOCK;
r = read(STDIN_FILENO, vm.buf + vm.buf_len,
BC_VM_STDIN_BUF_SIZE - vm.buf_len);
if (BC_UNLIKELY(r < 0)) {
if (errno == EINTR) {
if (vm.status == (sig_atomic_t) BC_STATUS_QUIT) {
BC_SIG_UNLOCK;
return BC_STATUS_QUIT;
}
assert(vm.sig);
vm.status = (sig_atomic_t) BC_STATUS_SUCCESS;
#if BC_ENABLE_PROMPT
if (BC_USE_PROMPT) bc_file_puts(&vm.fout, prompt);
#endif // BC_ENABLE_PROMPT
bc_file_flush(&vm.fout);
BC_SIG_UNLOCK;
continue;
}
BC_SIG_UNLOCK;
bc_vm_err(BC_ERROR_FATAL_IO_ERR);
}
BC_SIG_UNLOCK;
if (r == 0) {
bc_vec_pushByte(vec, '\0');
return BC_STATUS_EOF;
}
vm.buf_len += (size_t) r;
done = bc_read_buf(vec);
}
bc_vec_pushByte(vec, '\0');
return BC_STATUS_SUCCESS;
}
BcStatus bc_read_line(BcVec *vec, const char *prompt) {
BcStatus s;
#if BC_ENABLE_HISTORY
if (BC_TTY && !vm.history.badTerm)
s = bc_history_line(&vm.history, vec, prompt);
else s = bc_read_chars(vec, prompt);
#else // BC_ENABLE_HISTORY
s = bc_read_chars(vec, prompt);
#endif // BC_ENABLE_HISTORY
if (BC_ERR(bc_read_binary(vec->v, vec->len - 1)))
bc_vm_verr(BC_ERROR_FATAL_BIN_FILE, bc_program_stdin_name);
return s;
}
void bc_read_file(const char *path, char **buf) {
BcError e = BC_ERROR_FATAL_IO_ERR;
size_t size, r;
struct stat pstat;
int fd;
BC_SIG_ASSERT_LOCKED;
assert(path != NULL);
fd = open(path, O_RDONLY);
if (BC_ERR(fd < 0)) bc_vm_verr(BC_ERROR_FATAL_FILE_ERR, path);
if (BC_ERR(fstat(fd, &pstat) == -1)) goto malloc_err;
if (BC_ERR(S_ISDIR(pstat.st_mode))) {
e = BC_ERROR_FATAL_PATH_DIR;
goto malloc_err;
}
size = (size_t) pstat.st_size;
*buf = bc_vm_malloc(size + 1);
r = (size_t) read(fd, *buf, size);
if (BC_ERR(r != size)) goto read_err;
(*buf)[size] = '\0';
if (BC_ERR(bc_read_binary(*buf, size))) {
e = BC_ERROR_FATAL_BIN_FILE;
goto read_err;
}
close(fd);
return;
read_err:
free(*buf);
malloc_err:
close(fd);
bc_vm_verr(e, path);
}

311
contrib/bc/src/vector.c Normal file
View File

@ -0,0 +1,311 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Code to manipulate vectors (resizable arrays).
*
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <status.h>
#include <vector.h>
#include <lang.h>
#include <vm.h>
static void bc_vec_grow(BcVec *restrict v, size_t n) {
size_t len, cap = v->cap;
sig_atomic_t lock;
len = bc_vm_growSize(v->len, n);
while (cap < len) cap = bc_vm_growSize(cap, cap);
BC_SIG_TRYLOCK(lock);
v->v = bc_vm_realloc(v->v, bc_vm_arraySize(cap, v->size));
v->cap = cap;
BC_SIG_TRYUNLOCK(lock);
}
void bc_vec_init(BcVec *restrict v, size_t esize, BcVecFree dtor) {
BC_SIG_ASSERT_LOCKED;
assert(v != NULL && esize);
v->size = esize;
v->cap = BC_VEC_START_CAP;
v->len = 0;
v->dtor = dtor;
v->v = bc_vm_malloc(bc_vm_arraySize(BC_VEC_START_CAP, esize));
}
void bc_vec_expand(BcVec *restrict v, size_t req) {
assert(v != NULL);
if (v->cap < req) {
sig_atomic_t lock;
BC_SIG_TRYLOCK(lock);
v->v = bc_vm_realloc(v->v, bc_vm_arraySize(req, v->size));
v->cap = req;
BC_SIG_TRYUNLOCK(lock);
}
}
void bc_vec_npop(BcVec *restrict v, size_t n) {
assert(v != NULL && n <= v->len);
if (v->dtor == NULL) v->len -= n;
else {
sig_atomic_t lock;
size_t len = v->len - n;
BC_SIG_TRYLOCK(lock);
while (v->len > len) v->dtor(v->v + (v->size * --v->len));
BC_SIG_TRYUNLOCK(lock);
}
}
void bc_vec_npopAt(BcVec *restrict v, size_t n, size_t idx) {
char* ptr, *data;
assert(v != NULL);
assert(idx + n < v->len);
ptr = bc_vec_item(v, idx);
data = bc_vec_item(v, idx + n);
if (v->dtor != NULL) {
size_t i;
BC_SIG_LOCK;
for (i = 0; i < n; ++i) v->dtor(bc_vec_item(v, idx + i));
BC_SIG_UNLOCK;
}
v->len -= n;
memmove(ptr, data, (v->len - idx) * v->size);
}
void bc_vec_npush(BcVec *restrict v, size_t n, const void *data) {
assert(v != NULL && data != NULL);
if (v->len + n > v->cap) bc_vec_grow(v, n);
memcpy(v->v + (v->size * v->len), data, v->size * n);
v->len += n;
}
inline void bc_vec_push(BcVec *restrict v, const void *data) {
bc_vec_npush(v, 1, data);
}
void bc_vec_pushByte(BcVec *restrict v, uchar data) {
assert(v != NULL && v->size == sizeof(uchar));
if (v->len == v->cap) bc_vec_grow(v, 1);
v->v[v->len] = (char) data;
v->len += 1;
}
void bc_vec_pushIndex(BcVec *restrict v, size_t idx) {
uchar amt, nums[sizeof(size_t)];
assert(v != NULL);
assert(v->size == sizeof(uchar));
for (amt = 0; idx; ++amt) {
nums[amt] = (uchar) idx;
idx &= ((size_t) ~(UCHAR_MAX));
idx >>= sizeof(uchar) * CHAR_BIT;
}
bc_vec_push(v, &amt);
bc_vec_npush(v, amt, nums);
}
static void bc_vec_pushAt(BcVec *restrict v, const void *data, size_t idx) {
assert(v != NULL && data != NULL && idx <= v->len);
if (idx == v->len) bc_vec_push(v, data);
else {
char *ptr;
if (v->len == v->cap) bc_vec_grow(v, 1);
ptr = v->v + v->size * idx;
memmove(ptr + v->size, ptr, v->size * (v->len++ - idx));
memmove(ptr, data, v->size);
}
}
void bc_vec_string(BcVec *restrict v, size_t len, const char *restrict str) {
assert(v != NULL && v->size == sizeof(char));
assert(v->dtor == NULL);
assert(!v->len || !v->v[v->len - 1]);
assert(v->v != str);
bc_vec_npop(v, v->len);
bc_vec_expand(v, bc_vm_growSize(len, 1));
memcpy(v->v, str, len);
v->len = len;
bc_vec_pushByte(v, '\0');
}
void bc_vec_concat(BcVec *restrict v, const char *restrict str) {
assert(v != NULL && v->size == sizeof(char));
assert(v->dtor == NULL);
assert(!v->len || !v->v[v->len - 1]);
assert(v->v != str);
if (v->len) v->len -= 1;
bc_vec_npush(v, strlen(str) + 1, str);
}
void bc_vec_empty(BcVec *restrict v) {
assert(v != NULL && v->size == sizeof(char));
assert(v->dtor == NULL);
bc_vec_npop(v, v->len);
bc_vec_pushByte(v, '\0');
}
#if BC_ENABLE_HISTORY
void bc_vec_replaceAt(BcVec *restrict v, size_t idx, const void *data) {
char *ptr;
BC_SIG_ASSERT_LOCKED;
assert(v != NULL);
ptr = bc_vec_item(v, idx);
if (v->dtor != NULL) v->dtor(ptr);
memcpy(ptr, data, v->size);
}
#endif // BC_ENABLE_HISTORY
inline void* bc_vec_item(const BcVec *restrict v, size_t idx) {
assert(v != NULL && v->len && idx < v->len);
return v->v + v->size * idx;
}
inline void* bc_vec_item_rev(const BcVec *restrict v, size_t idx) {
assert(v != NULL && v->len && idx < v->len);
return v->v + v->size * (v->len - idx - 1);
}
inline void bc_vec_clear(BcVec *restrict v) {
v->v = NULL;
v->len = 0;
v->dtor = NULL;
}
void bc_vec_free(void *vec) {
BcVec *v = (BcVec*) vec;
BC_SIG_ASSERT_LOCKED;
bc_vec_npop(v, v->len);
free(v->v);
}
static size_t bc_map_find(const BcVec *restrict v, const char *name) {
size_t low = 0, high = v->len;
while (low < high) {
size_t mid = (low + high) / 2;
const BcId *id = bc_vec_item(v, mid);
int result = strcmp(name, id->name);
if (!result) return mid;
else if (result < 0) high = mid;
else low = mid + 1;
}
return low;
}
bool bc_map_insert(BcVec *restrict v, const char *name,
size_t idx, size_t *restrict i)
{
BcId id;
BC_SIG_ASSERT_LOCKED;
assert(v != NULL && name != NULL && i != NULL);
*i = bc_map_find(v, name);
assert(*i <= v->len);
if (*i != v->len && !strcmp(name, ((BcId*) bc_vec_item(v, *i))->name))
return false;
id.name = bc_vm_strdup(name);
id.idx = idx;
bc_vec_pushAt(v, &id, *i);
return true;
}
size_t bc_map_index(const BcVec *restrict v, const char *name) {
size_t i;
assert(v != NULL && name != NULL);
i = bc_map_find(v, name);
if (i >= v->len) return BC_VEC_INVALID_IDX;
return strcmp(name, ((BcId*) bc_vec_item(v, i))->name) ?
BC_VEC_INVALID_IDX : i;
}

819
contrib/bc/src/vm.c Normal file
View File

@ -0,0 +1,819 @@
/*
* *****************************************************************************
*
* Copyright (c) 2018-2020 Gavin D. Howard and contributors.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* Code common to all of bc and dc.
*
*/
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <string.h>
#include <signal.h>
#include <setjmp.h>
#ifndef _WIN32
#include <sys/types.h>
#include <unistd.h>
#else // _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <io.h>
#endif // _WIN32
#include <status.h>
#include <vector.h>
#include <args.h>
#include <vm.h>
#include <read.h>
#include <bc.h>
#if BC_DEBUG_CODE
BC_NORETURN void bc_vm_jmp(const char* f) {
#else // BC_DEBUG_CODE
BC_NORETURN void bc_vm_jmp(void) {
#endif
assert(vm.status != BC_STATUS_SUCCESS || vm.sig);
BC_SIG_MAYLOCK;
#if BC_DEBUG_CODE
bc_file_puts(&vm.ferr, "Longjmp: ");
bc_file_puts(&vm.ferr, f);
bc_file_putchar(&vm.ferr, '\n');
bc_file_flush(&vm.ferr);
#endif // BC_DEBUG_CODE
#ifndef NDEBUG
assert(vm.jmp_bufs.len - (size_t) vm.sig_pop);
#endif // NDEBUG
if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs);
else vm.sig_pop = 1;
siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1);
}
static void bc_vm_sig(int sig) {
// There is already a signal in flight.
if (vm.status == (sig_atomic_t) BC_STATUS_QUIT || vm.sig) {
if (!BC_TTY || sig != SIGINT) vm.status = BC_STATUS_QUIT;
return;
}
if (BC_TTY && sig == SIGINT) {
int err = errno;
if (write(STDOUT_FILENO, vm.sigmsg, vm.siglen) != (ssize_t) vm.siglen)
vm.status = BC_STATUS_ERROR_FATAL;
else vm.sig = 1;
errno = err;
}
else vm.status = BC_STATUS_QUIT;
assert(vm.jmp_bufs.len);
if (!vm.sig_lock) BC_VM_JMP;
}
void bc_vm_info(const char* const help) {
BC_SIG_ASSERT_LOCKED;
bc_file_puts(&vm.fout, vm.name);
bc_file_putchar(&vm.fout, ' ');
bc_file_puts(&vm.fout, BC_VERSION);
bc_file_putchar(&vm.fout, '\n');
bc_file_puts(&vm.fout, bc_copyright);
if (help) {
bc_file_putchar(&vm.fout, '\n');
bc_file_printf(&vm.fout, help, vm.name, vm.name);
}
bc_file_flush(&vm.fout);
}
void bc_vm_error(BcError e, size_t line, ...) {
BcStatus s;
va_list args;
uchar id = bc_err_ids[e];
const char* err_type = vm.err_ids[id];
sig_atomic_t lock;
assert(e < BC_ERROR_NELEMS);
assert(!vm.sig_pop);
#if BC_ENABLED
if (!BC_S && e >= BC_ERROR_POSIX_START) {
if (BC_W) {
// Make sure to not return an error.
id = UCHAR_MAX;
err_type = vm.err_ids[BC_ERR_IDX_WARN];
}
else return;
}
#endif // BC_ENABLED
BC_SIG_TRYLOCK(lock);
// Make sure all of stdout is written first.
s = bc_file_flushErr(&vm.fout);
if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) {
vm.status = (sig_atomic_t) s;
BC_VM_JMP;
}
va_start(args, line);
bc_file_putchar(&vm.ferr, '\n');
bc_file_puts(&vm.ferr, err_type);
bc_file_putchar(&vm.ferr, ' ');
bc_file_vprintf(&vm.ferr, vm.err_msgs[e], args);
va_end(args);
if (BC_NO_ERR(vm.file)) {
// This is the condition for parsing vs runtime.
// If line is not 0, it is parsing.
if (line) {
bc_file_puts(&vm.ferr, "\n ");
bc_file_puts(&vm.ferr, vm.file);
bc_file_printf(&vm.ferr, bc_err_line, line);
}
else {
BcInstPtr *ip = bc_vec_item_rev(&vm.prog.stack, 0);
BcFunc *f = bc_vec_item(&vm.prog.fns, ip->func);
bc_file_puts(&vm.ferr, "\n ");
bc_file_puts(&vm.ferr, vm.func_header);
bc_file_putchar(&vm.ferr, ' ');
bc_file_puts(&vm.ferr, f->name);
if (BC_IS_BC && ip->func != BC_PROG_MAIN &&
ip->func != BC_PROG_READ)
{
bc_file_puts(&vm.ferr, "()");
}
}
}
bc_file_puts(&vm.ferr, "\n\n");
s = bc_file_flushErr(&vm.ferr);
vm.status = s == BC_STATUS_ERROR_FATAL ?
(sig_atomic_t) s : (sig_atomic_t) (uchar) (id + 1);
if (BC_ERR(vm.status)) BC_VM_JMP;
BC_SIG_TRYUNLOCK(lock);
}
static void bc_vm_envArgs(const char* const env_args_name) {
char *env_args = getenv(env_args_name), *buf, *start;
char instr = '\0';
BC_SIG_ASSERT_LOCKED;
if (env_args == NULL) return;
start = buf = vm.env_args_buffer = bc_vm_strdup(env_args);
assert(buf != NULL);
bc_vec_init(&vm.env_args, sizeof(char*), NULL);
bc_vec_push(&vm.env_args, &env_args_name);
while (*buf) {
if (!isspace(*buf)) {
if (*buf == '"' || *buf == '\'') {
instr = *buf;
buf += 1;
if (*buf == instr) {
instr = '\0';
buf += 1;
continue;
}
}
bc_vec_push(&vm.env_args, &buf);
while (*buf && ((!instr && !isspace(*buf)) ||
(instr && *buf != instr)))
{
buf += 1;
}
if (*buf) {
if (instr) instr = '\0';
*buf = '\0';
buf += 1;
start = buf;
}
else if (instr) bc_vm_error(BC_ERROR_FATAL_OPTION, 0, start);
}
else buf += 1;
}
// Make sure to push a NULL pointer at the end.
buf = NULL;
bc_vec_push(&vm.env_args, &buf);
bc_args((int) vm.env_args.len - 1, bc_vec_item(&vm.env_args, 0));
}
static size_t bc_vm_envLen(const char *var) {
char *lenv = getenv(var);
size_t i, len = BC_NUM_PRINT_WIDTH;
int num;
if (lenv == NULL) return len;
len = strlen(lenv);
for (num = 1, i = 0; num && i < len; ++i) num = isdigit(lenv[i]);
if (num) {
len = (size_t) atoi(lenv) - 1;
if (len < 2 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH;
}
else len = BC_NUM_PRINT_WIDTH;
return len;
}
void bc_vm_shutdown(void) {
BC_SIG_ASSERT_LOCKED;
#if BC_ENABLE_NLS
if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog);
#endif // BC_ENABLE_NLS
#if BC_ENABLE_HISTORY
// This must always run to ensure that the terminal is back to normal.
if (BC_TTY) bc_history_free(&vm.history);
#endif // BC_ENABLE_HISTORY
#ifndef NDEBUG
bc_vec_free(&vm.env_args);
free(vm.env_args_buffer);
bc_vec_free(&vm.files);
bc_vec_free(&vm.exprs);
bc_program_free(&vm.prog);
bc_parse_free(&vm.prs);
{
size_t i;
for (i = 0; i < vm.temps.len; ++i)
free(((BcNum*) bc_vec_item(&vm.temps, i))->num);
bc_vec_free(&vm.temps);
}
#endif // NDEBUG
bc_file_free(&vm.fout);
bc_file_free(&vm.ferr);
}
size_t bc_vm_arraySize(size_t n, size_t size) {
size_t res = n * size;
if (BC_ERR(res >= SIZE_MAX || (n != 0 && res / n != size)))
bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
return res;
}
size_t bc_vm_growSize(size_t a, size_t b) {
size_t res = a + b;
if (BC_ERR(res >= SIZE_MAX || res < a || res < b))
bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
return res;
}
void* bc_vm_malloc(size_t n) {
void* ptr;
BC_SIG_ASSERT_LOCKED;
ptr = malloc(n);
if (BC_ERR(ptr == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
return ptr;
}
void* bc_vm_realloc(void *ptr, size_t n) {
void* temp;
BC_SIG_ASSERT_LOCKED;
temp = realloc(ptr, n);
if (BC_ERR(temp == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
return temp;
}
char* bc_vm_strdup(const char *str) {
char *s;
BC_SIG_ASSERT_LOCKED;
s = strdup(str);
if (BC_ERR(!s)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
return s;
}
void bc_vm_printf(const char *fmt, ...) {
va_list args;
BC_SIG_LOCK;
va_start(args, fmt);
bc_file_vprintf(&vm.fout, fmt, args);
va_end(args);
vm.nchars = 0;
BC_SIG_UNLOCK;
}
void bc_vm_putchar(int c) {
bc_file_putchar(&vm.fout, (uchar) c);
vm.nchars = (c == '\n' ? 0 : vm.nchars + 1);
}
static void bc_vm_clean(void) {
BcProgram *prog = &vm.prog;
BcVec *fns = &prog->fns;
BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN);
BcInstPtr *ip = bc_vec_item(&prog->stack, 0);
bool good = (vm.status && vm.status != BC_STATUS_QUIT);
if (good) bc_program_reset(&vm.prog);
#if BC_ENABLED
if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm.prs);
#endif // BC_ENABLED
#if DC_ENABLED
if (!BC_IS_BC) {
size_t i;
for (i = 0; i < vm.prog.vars.len; ++i) {
BcVec *arr = bc_vec_item(&vm.prog.vars, i);
BcNum *n = bc_vec_top(arr);
if (arr->len != 1 || BC_PROG_STR(n)) break;
}
if (i == vm.prog.vars.len) {
for (i = 0; i < vm.prog.arrs.len; ++i) {
BcVec *arr = bc_vec_item(&vm.prog.arrs, i);
size_t j;
assert(arr->len == 1);
arr = bc_vec_top(arr);
for (j = 0; j < arr->len; ++j) {
BcNum *n = bc_vec_item(arr, j);
if (BC_PROG_STR(n)) break;
}
if (j != arr->len) break;
}
good = (i == vm.prog.arrs.len);
}
}
#endif // DC_ENABLED
// If this condition is true, we can get rid of strings,
// constants, and code. This is an idea from busybox.
if (good && prog->stack.len == 1 && !prog->results.len &&
ip->idx == f->code.len)
{
#if BC_ENABLED
if (BC_IS_BC) {
bc_vec_npop(&f->labels, f->labels.len);
bc_vec_npop(&f->strs, f->strs.len);
}
#endif // BC_ENABLED
bc_vec_npop(&f->consts, f->consts.len);
bc_vec_npop(&f->code, f->code.len);
ip->idx = 0;
}
}
static void bc_vm_process(const char *text, bool is_stdin) {
bc_parse_text(&vm.prs, text);
do {
#if BC_ENABLED
if (vm.prs.l.t == BC_LEX_KW_DEFINE) vm.parse(&vm.prs);
#endif // BC_ENABLED
while (BC_PARSE_CAN_PARSE(vm.prs)) vm.parse(&vm.prs);
#if BC_ENABLED
if (BC_IS_BC) {
uint16_t *flags = BC_PARSE_TOP_FLAG_PTR(&vm.prs);
if (!is_stdin && vm.prs.flags.len == 1 &&
*flags == BC_PARSE_FLAG_IF_END)
{
bc_parse_noElse(&vm.prs);
}
if (BC_PARSE_NO_EXEC(&vm.prs)) return;
}
#endif // BC_ENABLED
bc_program_exec(&vm.prog);
if (BC_I) bc_file_flush(&vm.fout);
} while (vm.prs.l.t != BC_LEX_EOF);
}
static void bc_vm_file(const char *file) {
char *data = NULL;
assert(!vm.sig_pop);
bc_lex_file(&vm.prs.l, file);
BC_SIG_LOCK;
bc_read_file(file, &data);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
bc_vm_process(data, false);
#if BC_ENABLED
if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs)))
bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK);
#endif // BC_ENABLED
err:
BC_SIG_MAYLOCK;
free(data);
bc_vm_clean();
// bc_program_reset(), called by bc_vm_clean(), resets the status.
// We want it to clear the sig_pop variable in case it was set.
if (vm.status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP;
BC_LONGJMP_CONT;
}
static void bc_vm_stdin(void) {
BcStatus s;
BcVec buf, buffer;
size_t string = 0;
bool comment = false, hash = false;
bc_lex_file(&vm.prs.l, bc_program_stdin_name);
BC_SIG_LOCK;
bc_vec_init(&buffer, sizeof(uchar), NULL);
bc_vec_init(&buf, sizeof(uchar), NULL);
bc_vec_pushByte(&buffer, '\0');
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
restart:
// This loop is complex because the vm tries not to send any lines that end
// with a backslash to the parser. The reason for that is because the parser
// treats a backslash+newline combo as whitespace, per the bc spec. In that
// case, and for strings and comments, the parser will expect more stuff.
while ((!(s = bc_read_line(&buf, ">>> ")) ||
(vm.eof = (s == BC_STATUS_EOF))) && buf.len > 1)
{
char c2, *str = buf.v;
size_t i, len = buf.len - 1;
for (i = 0; i < len; ++i) {
bool notend = len > i + 1;
uchar c = (uchar) str[i];
hash = (!comment && !string && ((hash && c != '\n') ||
(!hash && c == '#')));
if (!hash && !comment && (i - 1 > len || str[i - 1] != '\\')) {
if (BC_IS_BC) string ^= (c == '"');
else if (c == ']') string -= 1;
else if (c == '[') string += 1;
}
if (BC_IS_BC && !hash && !string && notend) {
c2 = str[i + 1];
if (c == '/' && !comment && c2 == '*') {
comment = true;
i += 1;
}
else if (c == '*' && comment && c2 == '/') {
comment = false;
i += 1;
}
}
}
bc_vec_concat(&buffer, buf.v);
if (string || comment) continue;
if (len >= 2 && str[len - 2] == '\\' && str[len - 1] == '\n') continue;
#if BC_ENABLE_HISTORY
if (vm.history.stdin_has_data) continue;
#endif // BC_ENABLE_HISTORY
bc_vm_process(buffer.v, true);
bc_vec_empty(&buffer);
if (vm.eof) break;
}
if (!BC_STATUS_IS_ERROR(s)) {
if (BC_ERR(comment))
bc_parse_err(&vm.prs, BC_ERROR_PARSE_COMMENT);
else if (BC_ERR(string))
bc_parse_err(&vm.prs, BC_ERROR_PARSE_STRING);
#if BC_ENABLED
else if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs)))
bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK);
#endif // BC_ENABLED
}
err:
BC_SIG_MAYLOCK;
bc_vm_clean();
vm.status = vm.status == BC_STATUS_ERROR_FATAL ||
vm.status == BC_STATUS_QUIT || !BC_I ?
vm.status : BC_STATUS_SUCCESS;
if (!vm.status && !vm.eof) {
bc_vec_empty(&buffer);
BC_LONGJMP_STOP;
BC_SIG_UNLOCK;
goto restart;
}
bc_vec_free(&buf);
bc_vec_free(&buffer);
BC_LONGJMP_CONT;
}
#if BC_ENABLED
static void bc_vm_load(const char *name, const char *text) {
bc_lex_file(&vm.prs.l, name);
bc_parse_text(&vm.prs, text);
while (vm.prs.l.t != BC_LEX_EOF) vm.parse(&vm.prs);
}
#endif // BC_ENABLED
static void bc_vm_defaultMsgs(void) {
size_t i;
vm.func_header = bc_err_func_header;
for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i)
vm.err_ids[i] = bc_errs[i];
for (i = 0; i < BC_ERROR_NELEMS; ++i) vm.err_msgs[i] = bc_err_msgs[i];
}
static void bc_vm_gettext(void) {
#if BC_ENABLE_NLS
uchar id = 0;
int set = 1, msg = 1;
size_t i;
if (vm.locale == NULL) {
vm.catalog = BC_VM_INVALID_CATALOG;
bc_vm_defaultMsgs();
return;
}
vm.catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE);
if (vm.catalog == BC_VM_INVALID_CATALOG) {
bc_vm_defaultMsgs();
return;
}
vm.func_header = catgets(vm.catalog, set, msg, bc_err_func_header);
for (set += 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg)
vm.err_ids[msg - 1] = catgets(vm.catalog, set, msg, bc_errs[msg - 1]);
i = 0;
id = bc_err_ids[i];
for (set = id + 3, msg = 1; i < BC_ERROR_NELEMS; ++i, ++msg) {
if (id != bc_err_ids[i]) {
msg = 1;
id = bc_err_ids[i];
set = id + 3;
}
vm.err_msgs[i] = catgets(vm.catalog, set, msg, bc_err_msgs[i]);
}
#else // BC_ENABLE_NLS
bc_vm_defaultMsgs();
#endif // BC_ENABLE_NLS
}
static void bc_vm_exec(const char* env_exp_exit) {
size_t i;
bool has_file = false;
#if BC_ENABLED
if (BC_IS_BC && (vm.flags & BC_FLAG_L)) {
bc_vm_load(bc_lib_name, bc_lib);
#if BC_ENABLE_EXTRA_MATH
if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2);
#endif // BC_ENABLE_EXTRA_MATH
}
#endif // BC_ENABLED
if (vm.exprs.len) {
bc_lex_file(&vm.prs.l, bc_program_exprs_name);
bc_vm_process(vm.exprs.v, false);
if (getenv(env_exp_exit) != NULL) return;
}
for (i = 0; i < vm.files.len; ++i) {
char *path = *((char**) bc_vec_item(&vm.files, i));
if (!strcmp(path, "")) continue;
has_file = true;
bc_vm_file(path);
}
if (BC_IS_BC || !has_file) bc_vm_stdin();
}
void bc_vm_boot(int argc, char *argv[], const char *env_len,
const char* const env_args, const char* env_exp_exit)
{
int ttyin, ttyout, ttyerr;
struct sigaction sa;
BC_SIG_ASSERT_LOCKED;
ttyin = isatty(STDIN_FILENO);
ttyout = isatty(STDOUT_FILENO);
ttyerr = isatty(STDERR_FILENO);
vm.flags |= ttyin ? BC_FLAG_TTYIN : 0;
vm.flags |= (ttyin != 0 && ttyout != 0 && ttyerr != 0) ? BC_FLAG_TTY : 0;
vm.flags |= ttyin && ttyout ? BC_FLAG_I : 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = bc_vm_sig;
sa.sa_flags = SA_NODEFER;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
#if BC_ENABLE_HISTORY
if (BC_TTY) sigaction(SIGHUP, &sa, NULL);
#endif // BC_ENABLE_HISTORY
memcpy(vm.max_num, bc_num_bigdigMax,
bc_num_bigdigMax_size * sizeof(BcDig));
bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10);
vm.max.len = bc_num_bigdigMax_size;
vm.file = NULL;
bc_vm_gettext();
bc_file_init(&vm.ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE,
BC_VM_STDERR_BUF_SIZE);
bc_file_init(&vm.fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE);
vm.buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE;
vm.line_len = (uint16_t) bc_vm_envLen(env_len);
bc_vec_clear(&vm.files);
bc_vec_clear(&vm.exprs);
bc_vec_init(&vm.temps, sizeof(BcNum), NULL);
bc_program_init(&vm.prog);
bc_parse_init(&vm.prs, &vm.prog, BC_PROG_MAIN);
#if BC_ENABLE_HISTORY
if (BC_TTY) bc_history_init(&vm.history);
#endif // BC_ENABLE_HISTORY
#if BC_ENABLED
if (BC_IS_BC) vm.flags |= BC_FLAG_S * (getenv("POSIXLY_CORRECT") != NULL);
#endif // BC_ENABLED
bc_vm_envArgs(env_args);
bc_args(argc, argv);
if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G);
vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE;
vm.maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE;
vm.maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE;
#if BC_ENABLE_EXTRA_MATH
vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1;
#endif // BC_ENABLE_EXTRA_MATH
if (BC_IS_BC && !BC_IS_POSIX)
vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE;
if (BC_IS_BC && BC_I && !(vm.flags & BC_FLAG_Q)) bc_vm_info(NULL);
BC_SIG_UNLOCK;
bc_vm_exec(env_exp_exit);
}

View File

@ -105,6 +105,7 @@ __DEFAULT_YES_OPTIONS = \
FTP \
GAMES \
GDB \
GH_BC \
GNU_DIFF \
GNU_GREP \
GOOGLETEST \

View File

@ -214,6 +214,12 @@ SUBDIR.${MK_GAMES}+= random
.if ${COMPILER_FEATURES:Mc++11}
SUBDIR+= dtc
.endif
.if ${MK_GH_BC} == "yes"
SUBDIR+= gh-bc
.else
SUBDIR.${MK_OPENSSL}+= bc
SUBDIR.${MK_OPENSSL}+= dc
.endif
SUBDIR.${MK_HESIOD}+= hesinfo
SUBDIR.${MK_ICONV}+= iconv
SUBDIR.${MK_ICONV}+= mkcsmapper
@ -238,9 +244,7 @@ SUBDIR.${MK_NIS}+= ypcat
SUBDIR.${MK_NIS}+= ypmatch
SUBDIR.${MK_NIS}+= ypwhich
SUBDIR.${MK_OPENSSH}+= ssh-copy-id
SUBDIR.${MK_OPENSSL}+= bc
SUBDIR.${MK_OPENSSL}+= chkey
SUBDIR.${MK_OPENSSL}+= dc
SUBDIR.${MK_OPENSSL}+= newkey
SUBDIR.${MK_QUOTAS}+= quota
SUBDIR.${MK_SENDMAIL}+= vacation

100
usr.bin/gh-bc/Makefile Normal file
View File

@ -0,0 +1,100 @@
# $FreeBSD$
.include <src.opts.mk>
PROG= gh-bc
PROGNAME= bc
BCDIR= ${SRCTOP}/contrib/${PROGNAME}
BCVERSION!= sed -n -e '/.*VERSION *= *[0-9]/s/.*VERSION *= *//p' ${BCDIR}/Makefile.in
SRCS= args.c data.c file.c lang.c lex.c main.c num.c parse.c program.c read.c vector.c vm.c
SRCS+= bc/bc.c bc/lex.c bc/parse.c dc/dc.c dc/lex.c dc/parse.c history/history.c
SRCS+= bc_help.c dc_help.c lib.c lib2.c opt.c rand/rand.c
MAN= bc.1 dc.1
LINKS= ${BINDIR}/bc ${BINDIR}/dc
.PATH: ${BCDIR}/src ${BCDIR}/gen ${BCDIR}/manuals ${.OBJDIR}
CATALOGS= en_US.UTF-8
CATALOGS+= de_DE.UTF-8 de_DE.ISO8859-1
CATALOGS+= fr_FR.UTF-8 fr_FR.ISO8859-1
CATALOGS+= ja_JP.UTF-8 ja_JP.eucJP
CATALOGS+= nl_NL.UTF-8 nl_NL.ISO8859-1
CATALOGS+= pl_PL.UTF-8 pl_PL.ISO8859-2
CATALOGS+= pt_PT.UTF-8 pt_PT.ISO8859-1
CATALOGS+= ru_RU.UTF-8 ru_RU.ISO8859-5 ru_RU.CP1251 ru_RU.CP866 ru_RU.KOI8-R
CATALOGS+= zh_CN.UTF-8 zh_CN.eucCN zh_CN.GB18030 zh_CN.GB2312 zh_CN.GBK
NLSNAME= bc
NLSSRCDIR= ${BCDIR}/locales
CFLAGS+= -DMAINEXEC=${PROGNAME}
CFLAGS+= -DNLSPATH=/usr/share/nls/%L/%N.cat
CFLAGS+= -DBC_ENABLED
CFLAGS+= -DBC_ENABLE_PROMPT
CFLAGS+= -DBC_ENABLE_LONG_OPTIONS
CFLAGS+= -DBC_ENABLE_EXTRA_MATH
CFLAGS+= -DBC_ENABLE_HISTORY
CFLAGS+= -DBC_ENABLE_SIGNALS=0
CFLAGS+= -DBC_NUM_KARATSUBA_LEN=64
CFLAGS+= -DDC_ENABLED
CFLAGS+= -DNDEBUG
CFLAGS+= -DVERSION=${BCVERSION}
CFLAGS+= -I${BCDIR}/include
.if ${MK_NLS_CATALOGS} == "no"
CFLAGS+= -DBC_ENABLE_NLS=0
.else
CFLAGS+= -DBC_ENABLE_NLS=1
# prevent floating point incompatibilities caused by -flto on some architectures
.if ${MACHINE_ARCH} != mips && ${MACHINE_ARCH} != mips64 && ${MACHINE_ARCH} != riscv64
CFLAGS+= -flto
.endif
.for catalog in ${CATALOGS}
NLS+= ${catalog:C/.*://}
NLSSRCFILES_${catalog:C/.*://}= ${catalog:C/.*://}.msg
.endfor
NLSLINKS_en_US.UTF-8+= en_AU.UTF-8 en_CA.UTF-8 en_GB.UTF-8 en_IE.UTF-8 \
en_NZ.UTF-8 C
NLSLINKS_en_US.UTF-8+= en_AU.US-ASCII en_CA.US-ASCII en_GB.US-ASCII \
en_NZ.US-ASCII
NLSLINKS_en_US.UTF-8+= en_AU.ISO8859-1 en_CA.ISO8859-1 en_GB.ISO8859-1 \
en_NZ.ISO8859-1 en_US.ISO8859-1
NLSLINKS_en_US.UTF-8+= en_AU.ISO8859-15 en_CA.ISO8859-15 en_GB.ISO8859-15 \
en_NZ.ISO8859-15 en_US.ISO8859-15
NLSLINKS_de_DE.UTF-8+= de_AT.UTF-8 de_CH.UTF-8
NLSLINKS_de_DE.ISO8859-1+= de_AT.ISO8859-1 de_CH.ISO8859-1
NLSLINKS_de_DE.ISO8859-1+= de_AT.ISO8859-15 de_CH.ISO8859-15 de_DE.ISO8859-15
NLSLINKS_fr_FR.UTF-8+= fr_BE.UTF-8 fr_CA.UTF-8 fr_CH.UTF-8
NLSLINKS_fr_FR.ISO8859-1+= fr_BE.ISO8859-1 fr_CA.ISO8859-1 fr_CH.ISO8859-1
NLSLINKS_fr_FR.ISO8859-1+= fr_BE.ISO8859-15 fr_CA.ISO8859-15 fr_CH.ISO8859-15 \
fr_FR.ISO8859-15
NLSLINKS_nl_NL.ISO8859-1+= nl_BE.ISO8859-1
NLSLINKS_nl_NL.ISO8859-1+= nl_BE.ISO8859-15 nl_NL.ISO8859-15
NLSLINKS_pt_PT.UTF-8+= pt_BR.UTF-8
NLSLINKS_pt_PT.ISO8859-1+= pt_BR.ISO8859-1
NLSLINKS_pt_PT.ISO8859-1+= pt_PT.ISO8859-15
.endif
lib.c: lib.bc
cd ${BCDIR} && sh gen/strgen.sh gen/lib.bc ${.OBJDIR}/lib.c bc_lib bc.h bc_lib_name 1 1
lib2.c: lib2.bc
cd ${BCDIR} && sh gen/strgen.sh gen/lib2.bc ${.OBJDIR}/lib2.c bc_lib2 bc.h bc_lib2_name 1 1
bc_help.c: bc_help.txt
cd ${BCDIR} && sh gen/strgen.sh gen/bc_help.txt ${.OBJDIR}/bc_help.c bc_help bc.h
dc_help.c: dc_help.txt
cd ${BCDIR} && sh gen/strgen.sh gen/dc_help.txt ${.OBJDIR}/dc_help.c dc_help dc.h
.include <bsd.prog.mk>