diff --git a/Makefile.in b/Makefile.in
index c3a41854fe9e..3d6780d6ac95 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,603 +1,615 @@
#
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2018-2021 Gavin D. Howard and contributors.
#
# 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:
SRC = %%SRC%%
OBJ = %%OBJ%%
GCDA = %%GCDA%%
GCNO = %%GCNO%%
BC_ENABLED_NAME = BC_ENABLED
BC_ENABLED = %%BC_ENABLED%%
DC_ENABLED_NAME = DC_ENABLED
DC_ENABLED = %%DC_ENABLED%%
HEADERS = include/args.h include/file.h include/lang.h include/lex.h include/num.h include/opt.h include/parse.h include/program.h include/read.h include/status.h include/vector.h include/vm.h
BC_HEADERS = include/bc.h
DC_HEADERS = include/dc.h
HISTORY_HEADERS = include/history.h
EXTRA_MATH_HEADERS = include/rand.h
LIBRARY_HEADERS = include/bcl.h include/library.h
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)
BC_TEST_OUTPUTS = tests/bc_outputs
BC_FUZZ_OUTPUTS = tests/fuzzing/bc_outputs1 tests/fuzzing/bc_outputs2 tests/fuzzing/bc_outputs3
DC_TEST_OUTPUTS = tests/dc_outputs
DC_FUZZ_OUTPUTS = tests/fuzzing/dc_outputs
LIB = libbcl
LIB_NAME = $(LIB).a
LIBBC = $(BIN)/$(LIB_NAME)
BCL = bcl
BCL_TEST = $(BIN)/$(BCL)
BCL_TEST_C = tests/$(BCL).c
MANUALS = manuals
BC_MANPAGE_NAME = $(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX).1
BC_MANPAGE = $(MANUALS)/$(BC).1
BC_MD = $(BC_MANPAGE).md
DC_MANPAGE_NAME = $(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX).1
DC_MANPAGE = $(MANUALS)/$(DC).1
DC_MD = $(DC_MANPAGE).md
BCL_MANPAGE_NAME = bcl.3
BCL_MANPAGE = $(MANUALS)/$(BCL_MANPAGE_NAME)
BCL_MD = $(BCL_MANPAGE).md
MANPAGE_INSTALL_ARGS = -Dm644
BINARY_INSTALL_ARGS = -Dm755
BCL_HEADER_NAME = bcl.h
BCL_HEADER = include/$(BCL_HEADER_NAME)
%%DESTDIR%%
BINDIR = %%BINDIR%%
INCLUDEDIR = %%INCLUDEDIR%%
LIBDIR = %%LIBDIR%%
MAN1DIR = %%MAN1DIR%%
MAN3DIR = %%MAN3DIR%%
MAIN_EXEC = $(EXEC_PREFIX)$(%%MAIN_EXEC%%)$(EXEC_SUFFIX)
EXEC = $(%%EXEC%%)
NLSPATH = %%NLSPATH%%
BC_BUILD_TYPE = %%BUILD_TYPE%%
BC_ENABLE_LIBRARY = %%LIBRARY%%
BC_ENABLE_HISTORY = %%HISTORY%%
BC_ENABLE_EXTRA_MATH_NAME = BC_ENABLE_EXTRA_MATH
BC_ENABLE_EXTRA_MATH = %%EXTRA_MATH%%
BC_ENABLE_NLS = %%NLS%%
BC_LONG_BIT = %%LONG_BIT%%
BC_ENABLE_AFL = %%FUZZ%%
BC_ENABLE_MEMCHECK = %%MEMCHECK%%
BC_DEFAULT_BANNER = %%BC_DEFAULT_BANNER%%
BC_DEFAULT_SIGINT_RESET = %%BC_DEFAULT_SIGINT_RESET%%
DC_DEFAULT_SIGINT_RESET = %%DC_DEFAULT_SIGINT_RESET%%
BC_DEFAULT_TTY_MODE = %%BC_DEFAULT_TTY_MODE%%
DC_DEFAULT_TTY_MODE = %%DC_DEFAULT_TTY_MODE%%
BC_DEFAULT_PROMPT = %%BC_DEFAULT_PROMPT%%
DC_DEFAULT_PROMPT = %%DC_DEFAULT_PROMPT%%
RM = rm
MKDIR = mkdir
SCRIPTS = ./scripts
MINISTAT = ministat
MINISTAT_EXEC = $(SCRIPTS)/$(MINISTAT)
BITFUNCGEN = bitfuncgen
BITFUNCGEN_EXEC = $(SCRIPTS)/$(BITFUNCGEN)
INSTALL = $(SCRIPTS)/exec-install.sh
SAFE_INSTALL = $(SCRIPTS)/safe-install.sh
LINK = $(SCRIPTS)/link.sh
MANPAGE = $(SCRIPTS)/manpage.sh
KARATSUBA = $(SCRIPTS)/karatsuba.py
LOCALE_INSTALL = $(SCRIPTS)/locale_install.sh
LOCALE_UNINSTALL = $(SCRIPTS)/locale_uninstall.sh
VALGRIND_ARGS = --error-exitcode=100 --leak-check=full --show-leak-kinds=all --errors-for-leak-kinds=all
TEST_STARS = ***********************************************************************
BC_NUM_KARATSUBA_LEN = %%KARATSUBA_LEN%%
BC_DEFS0 = -DBC_DEFAULT_BANNER=$(BC_DEFAULT_BANNER)
BC_DEFS1 = -DBC_DEFAULT_SIGINT_RESET=$(BC_DEFAULT_SIGINT_RESET)
BC_DEFS2 = -DBC_DEFAULT_TTY_MODE=$(BC_DEFAULT_TTY_MODE)
BC_DEFS3 = -DBC_DEFAULT_PROMPT=$(BC_DEFAULT_PROMPT)
BC_DEFS = $(BC_DEFS0) $(BC_DEFS1) $(BC_DEFS2) $(BC_DEFS3)
DC_DEFS1 = -DDC_DEFAULT_SIGINT_RESET=$(DC_DEFAULT_SIGINT_RESET)
DC_DEFS2 = -DDC_DEFAULT_TTY_MODE=$(DC_DEFAULT_TTY_MODE)
DC_DEFS3 = -DDC_DEFAULT_PROMPT=$(DC_DEFAULT_PROMPT)
DC_DEFS = $(DC_DEFS1) $(DC_DEFS2) $(DC_DEFS3)
CPPFLAGS1 = -D$(BC_ENABLED_NAME)=$(BC_ENABLED) -D$(DC_ENABLED_NAME)=$(DC_ENABLED)
CPPFLAGS2 = $(CPPFLAGS1) -I./include/ -DBUILD_TYPE=$(BC_BUILD_TYPE) %%LONG_BIT_DEFINE%%
CPPFLAGS3 = $(CPPFLAGS2) -DEXECPREFIX=$(EXEC_PREFIX) -DMAINEXEC=$(MAIN_EXEC)
CPPFLAGS4 = $(CPPFLAGS3) -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 %%BSD%%
CPPFLAGS5 = $(CPPFLAGS4) -DBC_NUM_KARATSUBA_LEN=$(BC_NUM_KARATSUBA_LEN)
CPPFLAGS6 = $(CPPFLAGS5) -DBC_ENABLE_NLS=$(BC_ENABLE_NLS)
CPPFLAGS7 = $(CPPFLAGS6) -D$(BC_ENABLE_EXTRA_MATH_NAME)=$(BC_ENABLE_EXTRA_MATH)
CPPFLAGS8 = $(CPPFLAGS7) -DBC_ENABLE_HISTORY=$(BC_ENABLE_HISTORY) -DBC_ENABLE_LIBRARY=$(BC_ENABLE_LIBRARY)
CPPFLAGS = $(CPPFLAGS8) -DBC_ENABLE_MEMCHECK=$(BC_ENABLE_MEMCHECK) -DBC_ENABLE_AFL=$(BC_ENABLE_AFL)
CFLAGS = $(CPPFLAGS) $(BC_DEFS) $(DC_DEFS) %%CPPFLAGS%% %%CFLAGS%%
LDFLAGS = %%LDFLAGS%%
HOSTCFLAGS = %%HOSTCFLAGS%%
CC = %%CC%%
HOSTCC = %%HOSTCC%%
BC_LIB_C_ARGS = bc_lib bc_lib_name $(BC_ENABLED_NAME) 1
BC_LIB2_C_ARGS = bc_lib2 bc_lib2_name "$(BC_ENABLED_NAME) && $(BC_ENABLE_EXTRA_MATH_NAME)" 1
OBJS = $(DC_HELP_O) $(BC_HELP_O) $(BC_LIB_O) $(BC_LIB2_O) $(OBJ)
all: %%DEFAULT_TARGET%%
%%DEFAULT_TARGET%%: %%DEFAULT_TARGET_PREREQS%%
%%DEFAULT_TARGET_CMD%%
%%SECOND_TARGET%%: %%SECOND_TARGET_PREREQS%%
%%SECOND_TARGET_CMD%%
$(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_LIB_O): $(BC_LIB_C)
$(CC) $(CFLAGS) -o $@ -c $<
$(BC_LIB2_C): $(GEN_EXEC) $(BC_LIB2)
$(GEN_EMU) $(GEN_EXEC) $(BC_LIB2) $(BC_LIB2_C) $(BC_LIB2_C_ARGS)
$(BC_LIB2_O): $(BC_LIB2_C)
$(CC) $(CFLAGS) -o $@ -c $<
$(BC_HELP_C): $(GEN_EXEC) $(BC_HELP)
$(GEN_EMU) $(GEN_EXEC) $(BC_HELP) $(BC_HELP_C) bc_help "" $(BC_ENABLED_NAME)
$(BC_HELP_O): $(BC_HELP_C)
$(CC) $(CFLAGS) -o $@ -c $<
$(DC_HELP_C): $(GEN_EXEC) $(DC_HELP)
$(GEN_EMU) $(GEN_EXEC) $(DC_HELP) $(DC_HELP_C) dc_help "" $(DC_ENABLED_NAME)
$(DC_HELP_O): $(DC_HELP_C)
$(CC) $(CFLAGS) -o $@ -c $<
$(BIN):
$(MKDIR) -p $(BIN)
headers: %%HEADERS%%
$(MINISTAT):
$(HOSTCC) $(HOSTCFLAGS) -lm -o $(MINISTAT_EXEC) scripts/ministat.c
$(BITFUNCGEN):
$(HOSTCC) $(HOSTCFLAGS) -lm -o $(BITFUNCGEN_EXEC) scripts/bitfuncgen.c
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'
-run_all_tests: bc_all_tests timeconst_all_tests dc_all_tests history_all_tests
+run_all_tests: bc_all_tests timeconst_all_tests dc_all_tests
+
+run_all_tests_np: bc_all_tests_np timeconst_all_tests dc_all_tests_np
bc_all_tests:
%%BC_ALL_TESTS%%
+bc_all_tests_np:
+ %%BC_ALL_TESTS_NP%%
+
timeconst_all_tests:
%%TIMECONST_ALL_TESTS%%
dc_all_tests:
%%DC_ALL_TESTS%%
+dc_all_tests_np:
+ %%DC_ALL_TESTS_NP%%
+
history_all_tests:
%%HISTORY_TESTS%%
check: test
test: %%TESTS%%
test_bc: test_bc_header test_bc_tests test_bc_scripts test_bc_errors test_bc_stdin test_bc_read test_bc_other
@printf '\nAll bc tests passed.\n\n$(TEST_STARS)\n'
test_bc_tests:%%BC_TESTS%%
test_bc_scripts:%%BC_SCRIPT_TESTS%%
test_bc_stdin:
@sh tests/stdin.sh bc %%BC_TEST_EXEC%%
test_bc_read:
@sh tests/read.sh bc %%BC_TEST_EXEC%%
-test_bc_errors:
+test_bc_errors: test_bc_error_lines%%BC_ERROR_TESTS%%
+
+test_bc_error_lines:
@sh tests/errors.sh bc %%BC_TEST_EXEC%%
test_bc_other:
@sh tests/other.sh bc $(BC_ENABLE_EXTRA_MATH) %%BC_TEST_EXEC%%
test_bc_header:
@printf '$(TEST_STARS)\n\nRunning bc tests...\n\n'
test_dc: test_dc_header test_dc_tests test_dc_scripts test_dc_errors test_dc_stdin test_dc_read test_dc_other
@printf '\nAll dc tests passed.\n\n$(TEST_STARS)\n'
test_dc_tests:%%DC_TESTS%%
test_dc_scripts:%%DC_SCRIPT_TESTS%%
test_dc_stdin:
@sh tests/stdin.sh dc %%DC_TEST_EXEC%%
test_dc_read:
@sh tests/read.sh dc %%DC_TEST_EXEC%%
-test_dc_errors:
+test_dc_errors: test_dc_error_lines%%DC_ERROR_TESTS%%
+
+test_dc_error_lines:
@sh tests/errors.sh dc %%DC_TEST_EXEC%%
test_dc_other:
@sh tests/other.sh dc $(BC_ENABLE_EXTRA_MATH) %%DC_TEST_EXEC%%
test_dc_header:
@printf '$(TEST_STARS)\n\nRunning dc tests...\n\n'
timeconst:
%%TIMECONST%%
test_history: test_history_header test_bc_history test_dc_history
@printf '\nAll history tests passed.\n\n$(TEST_STARS)\n'
test_bc_history:%%BC_HISTORY_TEST_PREREQS%%
test_bc_history_all: test_bc_history0 test_bc_history1 test_bc_history2 test_bc_history3 test_bc_history4 test_bc_history5 test_bc_history6 test_bc_history7 test_bc_history8 test_bc_history9 test_bc_history10 test_bc_history11 test_bc_history12 test_bc_history13 test_bc_history14 test_bc_history15 test_bc_history16 test_bc_history17 test_bc_history18 test_bc_history19 test_bc_history20 test_bc_history21
test_bc_history_skip:
@printf 'No bc history tests to run\n'
test_bc_history0:
@sh tests/history.sh bc 0 %%BC_TEST_EXEC%%
test_bc_history1:
@sh tests/history.sh bc 1 %%BC_TEST_EXEC%%
test_bc_history2:
@sh tests/history.sh bc 2 %%BC_TEST_EXEC%%
test_bc_history3:
@sh tests/history.sh bc 3 %%BC_TEST_EXEC%%
test_bc_history4:
@sh tests/history.sh bc 4 %%BC_TEST_EXEC%%
test_bc_history5:
@sh tests/history.sh bc 5 %%BC_TEST_EXEC%%
test_bc_history6:
@sh tests/history.sh bc 6 %%BC_TEST_EXEC%%
test_bc_history7:
@sh tests/history.sh bc 7 %%BC_TEST_EXEC%%
test_bc_history8:
@sh tests/history.sh bc 8 %%BC_TEST_EXEC%%
test_bc_history9:
@sh tests/history.sh bc 9 %%BC_TEST_EXEC%%
test_bc_history10:
@sh tests/history.sh bc 10 %%BC_TEST_EXEC%%
test_bc_history11:
@sh tests/history.sh bc 11 %%BC_TEST_EXEC%%
test_bc_history12:
@sh tests/history.sh bc 12 %%BC_TEST_EXEC%%
test_bc_history13:
@sh tests/history.sh bc 13 %%BC_TEST_EXEC%%
test_bc_history14:
@sh tests/history.sh bc 14 %%BC_TEST_EXEC%%
test_bc_history15:
@sh tests/history.sh bc 15 %%BC_TEST_EXEC%%
test_bc_history16:
@sh tests/history.sh bc 16 %%BC_TEST_EXEC%%
test_bc_history17:
@sh tests/history.sh bc 17 %%BC_TEST_EXEC%%
test_bc_history18:
@sh tests/history.sh bc 18 %%BC_TEST_EXEC%%
test_bc_history19:
@sh tests/history.sh bc 19 %%BC_TEST_EXEC%%
test_bc_history20:
@sh tests/history.sh bc 20 %%BC_TEST_EXEC%%
test_bc_history21:
@sh tests/history.sh bc 21 %%BC_TEST_EXEC%%
test_dc_history:%%DC_HISTORY_TEST_PREREQS%%
test_dc_history_all: test_dc_history0 test_dc_history1 test_dc_history2 test_dc_history3 test_dc_history4 test_dc_history5 test_dc_history6 test_dc_history7 test_dc_history8 test_dc_history9
test_dc_history_skip:
@printf 'No dc history tests to run\n'
test_dc_history0:
@sh tests/history.sh dc 0 %%DC_TEST_EXEC%%
test_dc_history1:
@sh tests/history.sh dc 1 %%DC_TEST_EXEC%%
test_dc_history2:
@sh tests/history.sh dc 2 %%DC_TEST_EXEC%%
test_dc_history3:
@sh tests/history.sh dc 3 %%DC_TEST_EXEC%%
test_dc_history4:
@sh tests/history.sh dc 4 %%DC_TEST_EXEC%%
test_dc_history5:
@sh tests/history.sh dc 5 %%DC_TEST_EXEC%%
test_dc_history6:
@sh tests/history.sh dc 6 %%DC_TEST_EXEC%%
test_dc_history7:
@sh tests/history.sh dc 7 %%DC_TEST_EXEC%%
test_dc_history8:
@sh tests/history.sh dc 8 %%DC_TEST_EXEC%%
test_dc_history9:
@sh tests/history.sh dc 9 %%DC_TEST_EXEC%%
test_history_header:
@printf '$(TEST_STARS)\n\nRunning history tests...\n\n'
library_test: $(LIBBC)
$(CC) $(CFLAGS) $(BCL_TEST_C) $(LIBBC) -o $(BCL_TEST)
test_library: library_test
$(BCL_TEST)
karatsuba:
%%KARATSUBA%%
karatsuba_test:
%%KARATSUBA_TEST%%
coverage_output:
%%COVERAGE_OUTPUT%%
coverage:%%COVERAGE_PREREQS%%
manpages:
$(MANPAGE) bc
$(MANPAGE) dc
$(MANPAGE) bcl
clean_gen:
@$(RM) -f $(GEN_EXEC)
clean:%%CLEAN_PREREQS%%
@printf 'Cleaning files...\n'
@$(RM) -f src/*.tmp gen/*.tmp
@$(RM) -f $(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)
@$(RM) -fr Debug/ Release/
clean_benchmarks:
@printf 'Cleaning benchmarks...\n'
@$(RM) -f $(MINISTAT_EXEC)
@$(RM) -f benchmarks/bc/*.txt
@$(RM) -f benchmarks/dc/*.txt
clean_config: clean clean_benchmarks
@printf 'Cleaning config...\n'
@$(RM) -f Makefile
@$(RM) -f $(BC_MD) $(BC_MANPAGE)
@$(RM) -f $(DC_MD) $(DC_MANPAGE)
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) -fr $(BC_TEST_OUTPUTS) $(DC_TEST_OUTPUTS)
@$(RM) -fr $(BC_FUZZ_OUTPUTS) $(DC_FUZZ_OUTPUTS)
@$(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/strings2.txt tests/bc/strings2_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/bc/scripts/strings2.txt
@$(RM) -f tests/dc/scripts/prime.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
@$(RM) -f $(BITFUNCGEN_EXEC)
install_locales:
%%INSTALL_LOCALES%%
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_bcl_manpage:
$(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BCL_MANPAGE) $(DESTDIR)$(MAN3DIR)/$(BCL_MANPAGE_NAME)
install_bcl_header:
$(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BCL_HEADER) $(DESTDIR)$(INCLUDEDIR)/$(BCL_HEADER_NAME)
install_execs:
$(INSTALL) $(DESTDIR)$(BINDIR) "$(EXEC_SUFFIX)"
install_library:
$(SAFE_INSTALL) $(BINARY_INSTALL_ARGS) $(LIBBC) $(DESTDIR)$(LIBDIR)/$(LIB_NAME)
install:%%INSTALL_LOCALES_PREREQS%%%%INSTALL_MAN_PREREQS%%%%INSTALL_PREREQS%%
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_library:
$(RM) -f $(DESTDIR)$(LIBDIR)/$(LIB_NAME)
uninstall_bcl_header:
$(RM) -f $(DESTDIR)$(INCLUDEDIR)/$(BCL_HEADER_NAME)
uninstall_bcl_manpage:
$(RM) -f $(DESTDIR)$(MAN3DIR)/$(BCL_MANPAGE_NAME)
uninstall:%%UNINSTALL_LOCALES_PREREQS%%%%UNINSTALL_MAN_PREREQS%%%%UNINSTALL_PREREQS%%
diff --git a/NEWS.md b/NEWS.md
index f35d593b807a..98b52024b2e8 100644
--- a/NEWS.md
+++ b/NEWS.md
@@ -1,1185 +1,1203 @@
# News
+## 5.1.0
+
+This is a production release with some fixes and new features.
+
+* Fixed a bug where an `if` statement without an `else` before defining a
+ function caused an error.
+* Fixed a bug with the `bc` banner and `-q`.
+* Fixed a bug on Windows where files were not read correctly.
+* Added a command-line flag (`-z`) to make `bc` and `dc` print leading zeroes on
+ numbers `-1 < x < 1`.
+* Added four functions to `lib2.bc` (`plz()`, `plznl()`, `pnlz()`, and
+ `pnlznl()`) to allow printing numbers with or without leading zeros, despite
+ the use of `-z` or not.
+* Added builtin functions to query global state like line length, global stacks,
+ and leading zeroes.
+* Added a command-line flag (`-L`) to disable wrapping when printing numbers.
+* Improved builds on Windows.
+
## 5.0.2
This is a production release with one fix for a flaky test. If you have not
experienced problems with the test suite, you do ***NOT*** need to upgrade.
The test was one that tested whether `bc` fails gracefully when it can't
allocate memory. Unfortunately, there are cases when Linux and FreeBSD lie and
pretend to allocate the memory.
The reason they do this is because a lot of programs don't use all of the memory
they allocate, so those OS's usually get away with it.
However, this `bc` uses all of the memory it allocates (at least at page
granularity), so when it tries to use the memory, FreeBSD and Linux kill it.
This only happens sometimes, however. Other times (on my machine), they do, in
fact, refuse the request.
So I changed the test to not test for that because I think the graceful failure
code won't really change much.
## 5.0.1
This is a production release with two fixes:
* Fix for the build on Mac OSX.
* Fix for the build on Android.
Users that do not use those platforms do ***NOT*** need to update.
## 5.0.0
This is a major production release with several changes:
* Added support for OpenBSD's `pledge()` and `unveil()`.
* Fixed print bug where a backslash newline combo was printed even if only one
digit was left, something I blindly copied from GNU `bc`, like a fool.
* Fixed bugs in the manuals.
* Fixed a possible multiplication overflow in power.
* Temporary numbers are garbage collected if allocation fails, and the
allocation is retried. This is to make `bc` and `dc` more resilient to running
out of memory.
* Limited the number of temporary numbers and made the space for them static so
that allocating more space for them cannot fail.
* Allowed integers with non-zero `scale` to be used with power, places, and
shift operators.
* Added greatest common divisor and least common multiple to `lib2.bc`.
* Added `SIGQUIT` handling to history.
* Added a command to `dc` (`y`) to get the length of register stacks.
* Fixed multi-digit bugs in `lib2.bc`.
* Removed the no prompt build option.
* Created settings that builders can set defaults for and users can set their
preferences for. This includes the `bc` banner, resetting on `SIGINT`, TTY
mode, and prompt.
* Added history support to Windows.
* Fixed bugs with the handling of register names in `dc`.
* Fixed bugs with multi-line comments and strings in both calculators.
* Added a new error type and message for `dc` when register stacks don't have
enough items.
* Optimized string allocation.
* Made `bc` and `dc` UTF-8 capable.
* Fixed a bug with `void` functions.
* Fixed a misspelled symbol in `bcl`. This is technically a breaking change,
which requires this to be `5.0.0`.
* Added the ability for users to get the copyright banner back.
* Added the ability for users to have `bc` and `dc` quit on `SIGINT`.
* Added the ability for users to disable prompt and TTY mode by environment
variables.
* Added the ability for users to redefine keywords. This is another reason this
is `5.0.0`.
* Added `dc`'s modular exponentiation and divmod to `bc`.
* Added the ability to assign strings to variables and array elements and pass
them to functions in `bc`.
* Added `dc`'s asciify command and stream printing to `bc`.
* Added a command to `dc` (`Y`) to get the length of an array.
* Added a command to `dc` (`,`) to get the depth of the execution stack.
* Added bitwise and, or, xor, left shift, right shift, reverse, left rotate,
right rotate, and mod functions to `lib2.bc`.
* Added the functions `s2u(x)` and `s2un(x,n)`, to `lib2.bc`.
## 4.0.2
This is a production release that fixes two bugs:
1. If no files are used and the first statement on `stdin` is invalid, `scale`
would not be set to `20` even if `-l` was used.
2. When using history, `bc` failed to respond properly to `SIGSTOP` and
`SIGTSTP`.
## 4.0.1
This is a production release that only adds one thing: flushing output when it
is printed with a print statement.
## 4.0.0
This is a production release with many fixes, a new command-line option, and a
big surprise:
* A bug was fixed in `dc`'s `P` command where the item on the stack was *not*
popped.
* Various bugs in the manuals have been fixed.
* A known bug was fixed where history did not interact well with prompts printed
by user code without newlines.
* A new command-line option, `-R` and `--no-read-prompt` was added to disable
just the prompt when using `read()` (`bc`) or `?` (`dc`).
* And finally, **official support for Windows was added**.
The last item is why this is a major version bump.
Currently, only one set of build options (extra math and prompt enabled, history
and NLS/locale support disabled, both calculators enabled) is supported on
Windows. However, both debug and release builds are supported.
In addition, Windows builds are supported for the the library (`bcl`).
For more details about how to build on Windows, see the [README][5] or the
[build manual][13].
## 3.3.4
This is a production release that fixes a small bug.
The bug was that output was not flushed before a `read()` call, so prompts
without a newline on the end were not flushed before the `read()` call.
This is such a tiny bug that users only need to upgrade if they are affected.
## 3.3.3
This is a production release with one tweak and fixes for manuals.
The tweak is that `length(0)` returns `1` instead of `0`. In `3.3.1`, I changed
it so `length(0.x)`, where `x` could be any number of digits, returned the
`scale`, but `length(0)` still returned `0` because I believe that `0` has `0`
significant digits.
After request of FreeBSD and considering the arguments of a mathematician,
compatibility with other `bc`'s, and the expectations of users, I decided to
make the change.
The fixes for manuals fixed a bug where `--` was rendered as `-`.
## 3.3.2
This is a production release that fixes a divide-by-zero bug in `root()` in the
[extended math library][16]. All previous versions with `root()` have the bug.
## 3.3.1
This is a production release that fixes a bug.
The bug was in the reporting of number length when the value was 0.
## 3.3.0
This is a production release that changes one behavior and fixes documentation
bugs.
The changed behavior is the treatment of `-e` and `-f` when given through
`BC_ENV_ARGS` or `DC_ENV_ARGS`. Now `bc` and `dc` do not exit when those options
(or their equivalents) are given through those environment variables. However,
`bc` and `dc` still exit when they or their equivalents are given on the
command-line.
## 3.2.7
This is a production release that removes a small non-portable shell operation
in `configure.sh`. This problem was only noticed on OpenBSD, not FreeBSD or
Linux.
Non-OpenBSD users do ***NOT*** need to upgrade, although NetBSD users may also
need to upgrade.
## 3.2.6
This is a production release that fixes the build on FreeBSD.
There was a syntax error in `configure.sh` that the Linux shell did not catch,
and FreeBSD depends on the existence of `tests/all.sh`.
All users that already upgraded to `3.2.5` should update to this release, with
my apologies for the poor release of `3.2.5`. Other users should skip `3.2.5` in
favor of this version.
## 3.2.5
This is a production release that fixes several bugs and adds a couple small
things.
The two most important bugs were bugs that causes `dc` to access memory
out-of-bounds (crash in debug builds). This was found by upgrading to `afl++`
from `afl`. Both were caused by a failure to distinguish between the same two
cases.
Another bug was the failure to put all of the licenses in the `LICENSE.md` file.
Third, some warnings by `scan-build` were found and eliminated. This needed one
big change: `bc` and `dc` now bail out as fast as possible on fatal errors
instead of unwinding the stack.
Fourth, the pseudo-random number now attempts to seed itself with `/dev/random`
if `/dev/urandom` fails.
Finally, this release has a few quality-of-life changes to the build system. The
usage should not change at all; the only thing that changed was making sure the
`Makefile.in` was written to rebuild properly when headers changed and to not
rebuild when not necessary.
## 3.2.4
This is a production release that fixes a warning on `gcc` 6 or older, which
does not have an attribute that is used.
Users do ***NOT*** need to upgrade if they don't use `gcc` 6 or older.
## 3.2.3
This is a production release that fixes a bug in `gen/strgen.sh`. I recently
changed `gen/strgen.c`, but I did not change `gen/strgen.sh`.
Users that do not use `gen/strgen.sh` do not need to upgrade.
## 3.2.2
This is a production release that fixes a portability bug in `configure.sh`. The
bug was using the GNU `find` extension `-wholename`.
## 3.2.1
This is a production release that has one fix for `bcl(3)`. It is technically
not a bug fix since the behavior is undefined, but the `BclNumber`s that
`bcl_divmod()` returns will be set to `BCL_ERROR_INVALID_NUM` if there is an
error. Previously, they were not set.
## 3.2.0
This is a production release that has one bug fix and a major addition.
The bug fix was a missing `auto` variable in the bessel `j()` function in the
math library.
The major addition is a way to build a version of `bc`'s math code as a library.
This is done with the `-a` option to `configure.sh`. The API for the library can
be read in `./manuals/bcl.3.md` or `man bcl` once the library is installed with
`make install`.
This library was requested by developers before I even finished version 1.0, but
I could not figure out how to do it until now.
If the library has API breaking changes, the major version of `bc` will be
incremented.
## 3.1.6
This is a production release that fixes a new warning from Clang 12 for FreeBSD
and also removes some possible undefined behavior found by UBSan that compilers
did not seem to take advantage of.
Users do ***NOT*** need to upgrade, if they do not want to.
## 3.1.5
This is a production release that fixes the Chinese locales (which caused `bc`
to crash) and a crash caused by `bc` executing code when it should not have been
able to.
***ALL USERS SHOULD UPGRADE.***
## 3.1.4
This is a production release that fixes one bug, changes two behaviors, and
removes one environment variable.
The bug is like the one in the last release except it applies if files are being
executed. I also made the fix more general.
The behavior that was changed is that `bc` now exits when given `-e`, `-f`,
`--expression` or `--file`. However, if the last one of those is `-f-` (using
`stdin` as the file), `bc` does not exit. If `-f-` exists and is not the last of
the `-e` and `-f` options (and equivalents), `bc` gives a fatal error and exits.
Next, I removed the `BC_EXPR_EXIT` and `DC_EXPR_EXIT` environment variables
since their use is not needed with the behavior change.
Finally, I made it so `bc` does not print the header, though the `-q` and
`--quiet` options were kept for compatibility with GNU `bc`.
## 3.1.3
This is a production release that fixes one minor bug: if `bc` was invoked like
the following, it would error:
```
echo "if (1 < 3) 1" | bc
```
Unless users run into this bug, they do not need to upgrade, but it is suggested
that they do.
## 3.1.2
This is a production release that adds a way to install *all* locales. Users do
***NOT*** need to upgrade.
For package maintainers wishing to make use of the change, just pass `-l` to
`configure.sh`.
## 3.1.1
This is a production release that adds two Spanish locales. Users do ***NOT***
need to upgrade, unless they want those locales.
## 3.1.0
This is a production release that adjusts one behavior, fixes eight bugs, and
improves manpages for FreeBSD. Because this release fixes bugs, **users and
package maintainers should update to this version as soon as possible**.
The behavior that was adjusted was how code from the `-e` and `-f` arguments
(and equivalents) were executed. They used to be executed as one big chunk, but
in this release, they are now executed line-by-line.
The first bug fix in how output to `stdout` was handled in `SIGINT`. If a
`SIGINT` came in, the `stdout` buffer was not correctly flushed. In fact, a
clean-up function was not getting called. This release fixes that bug.
The second bug is in how `dc` handled input from `stdin`. This affected `bc` as
well since it was a mishandling of the `stdin` buffer.
The third fixed bug was that `bc` and `dc` could `abort()` (in debug mode) when
receiving a `SIGTERM`. This one was a race condition with pushing and popping
items onto and out of vectors.
The fourth bug fixed was that `bc` could leave extra items on the stack and
thus, not properly clean up some memory. (The memory would still get
`free()`'ed, but it would not be `free()`'ed when it could have been.)
The next two bugs were bugs in `bc`'s parser that caused crashes when executing
the resulting code.
The last two bugs were crashes in `dc` that resulted from mishandling of
strings.
The manpage improvement was done by switching from [ronn][20] to [Pandoc][21] to
generate manpages. Pandoc generates much cleaner manpages and doesn't leave
blank lines where they shouldn't be.
## 3.0.3
This is a production release that adds one new feature: specific manpages.
Before this release, `bc` and `dc` only used one manpage each that referred to
various build options. This release changes it so there is one manpage set per
relevant build type. Each manual only has information about its particular
build, and `configure.sh` selects the correct set for install.
## 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.** (Removing the locale files can be done with
`make uninstall` or by running the [`locale_uninstall.sh`][22] script.) 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 is 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]: ./scripts/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/A.1.md
[10]: ./manuals/dc/A.1.md
[11]: https://scan.coverity.com/projects/gavinhoward-bc
[12]: ./scripts/locale_install.sh
[13]: ./manuals/build.md
[14]: https://github.com/stesser
[15]: https://github.com/bugcrazy
[16]: ./manuals/bc/A.1.md#extended-library
[17]: https://github.com/skeeto/optparse
[18]: https://www.deepl.com/translator
[19]: ./manuals/benchmarks.md
[20]: https://github.com/apjanke/ronn-ng
[21]: https://pandoc.org/
[22]: ./scripts/locale_uninstall.sh
diff --git a/bc.vcxproj b/bc.vcxproj
deleted file mode 100644
index 8d4f34a2a0e6..000000000000
--- a/bc.vcxproj
+++ /dev/null
@@ -1,278 +0,0 @@
-
-
-
-
- Debug
- Win32
-
-
- Release
- Win32
-
-
- Debug
- x64
-
-
- Release
- x64
-
-
-
- 16.0
- {D5086CFE-052C-4742-B005-E05DB983BBA2}
- Win32Proj
-
-
-
- Application
- true
- v142
-
-
- Application
- false
- v142
-
-
- Application
- true
- v142
-
-
- Application
- false
- v142
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Building strgen
- CL /Fo:$(Configuration)\$(Platform)\$(ProjectName)\ /Fe:$(Configuration)\$(Platform)\$(ProjectName)\strgen.exe gen\strgen.c
- gen\strgen.c
- $(Configuration)\$(Platform)\$(ProjectName)\strgen.exe
-
-
- Generating $(Configuration)\$(Platform)\$(ProjectName)/lib.c
- START $(Configuration)\$(Platform)\$(ProjectName)/strgen gen\lib.bc $(Configuration)\$(Platform)\$(ProjectName)/lib.c bc_lib bc_lib_name BC_ENABLED 1
- $(Configuration)\$(Platform)\$(ProjectName)\strgen.exe;gen\lib.bc
- $(Configuration)\$(Platform)\$(ProjectName)\lib.c
-
-
- Generating $(Configuration)\$(Platform)\$(ProjectName)/lib2.c
- START $(Configuration)\$(Platform)\$(ProjectName)/strgen gen\lib2.bc $(Configuration)\$(Platform)\$(ProjectName)/lib2.c bc_lib2 bc_lib2_name BC_ENABLED 1
- $(Configuration)\$(Platform)\$(ProjectName)\strgen.exe;gen\lib2.bc
- $(Configuration)\$(Platform)\$(ProjectName)\lib2.c
-
-
- Generating $(Configuration)\$(Platform)\$(ProjectName)/bc_help.c
- START $(Configuration)\$(Platform)\$(ProjectName)/strgen gen\bc_help.txt $(Configuration)\$(Platform)\$(ProjectName)\bc_help.c bc_help "" BC_ENABLED
- $(Configuration)\$(Platform)\$(ProjectName)\strgen.exe;gen\bc_help.txt
- $(Configuration)\$(Platform)\$(ProjectName)\bc_help.c
-
-
- Generating $(Configuration)\$(Platform)\$(ProjectName)/dc_help.c
- START $(Configuration)\$(Platform)\$(ProjectName)/strgen gen\dc_help.txt $(Configuration)\$(Platform)\$(ProjectName)\dc_help.c dc_help "" DC_ENABLED
- $(Configuration)\$(Platform)\$(ProjectName)\strgen.exe;gen\dc_help.txt
- $(Configuration)\$(Platform)\$(ProjectName)\dc_help.c
-
-
-
- ClCompile
-
-
-
- true
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
-
-
- false
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
-
-
- true
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
-
-
- false
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
-
-
-
- WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions);BC_ENABLED=1;DC_ENABLED=1;BC_ENABLE_EXTRA_MATH=1;BC_ENABLE_HISTORY=1;BC_ENABLE_NLS=0;BC_DEBUG_CODE=0;BC_ENABLE_LIBRARY=0;EXECSUFFIX=.exe;BUILD_TYPE=N;BC_DEFAULT_BANNER=1;BC_DEFAULT_SIGINT_RESET=0;DC_DEFAULT_SIGINT_RESET=0;BC_DEFAULT_TTY_MODE=1;DC_DEFAULT_TTY_MODE=1;BC_DEFAULT_PROMPT=1;DC_DEFAULT_PROMPT=1
- $(SolutionDir)\include;%(AdditionalIncludeDirectories)
- MultiThreadedDebugDLL
- Level3
- ProgramDatabase
- Disabled
- false
- /W3 %(AdditionalOptions)
-
-
- MachineX86
- DebugFastLink
- Console
- kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;bcrypt.lib;ucrt.lib;%(AdditionalDependencies)
-
-
- copy /b "$(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\bc.exe" "$(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\dc.exe"
-
-
- Copying bc to dc...
-
-
-
-
- WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions);BC_ENABLED=1;DC_ENABLED=1;BC_ENABLE_EXTRA_MATH=1;BC_ENABLE_HISTORY=1;BC_ENABLE_NLS=0;BC_DEBUG_CODE=0;BC_ENABLE_LIBRARY=0;EXECSUFFIX=.exe;BUILD_TYPE=N;BC_DEFAULT_BANNER=1;BC_DEFAULT_SIGINT_RESET=0;DC_DEFAULT_SIGINT_RESET=0;BC_DEFAULT_TTY_MODE=1;DC_DEFAULT_TTY_MODE=1;BC_DEFAULT_PROMPT=1;DC_DEFAULT_PROMPT=1
- $(SolutionDir)\include;%(AdditionalIncludeDirectories)
- MultiThreadedDLL
- Level3
- ProgramDatabase
- MaxSpeed
- false
- /W3 %(AdditionalOptions)
-
-
- MachineX86
- false
- Console
- kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;bcrypt.lib;ucrt.lib;%(AdditionalDependencies)
- true
- true
-
-
- copy /b "$(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\bc.exe" "$(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\dc.exe"
-
-
- Copying bc to dc...
-
-
-
-
- WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions);BC_ENABLED=1;DC_ENABLED=1;BC_ENABLE_EXTRA_MATH=1;BC_ENABLE_HISTORY=1;BC_ENABLE_NLS=0;BC_DEBUG_CODE=0;BC_ENABLE_LIBRARY=0;EXECSUFFIX=.exe;BUILD_TYPE=N;BC_DEFAULT_BANNER=1;BC_DEFAULT_SIGINT_RESET=0;DC_DEFAULT_SIGINT_RESET=0;BC_DEFAULT_TTY_MODE=1;DC_DEFAULT_TTY_MODE=1;BC_DEFAULT_PROMPT=1;DC_DEFAULT_PROMPT=1
- $(SolutionDir)\include;%(AdditionalIncludeDirectories)
- MultiThreadedDebugDLL
- Level3
- ProgramDatabase
- Disabled
- false
- /W3 %(AdditionalOptions)
-
-
- MachineX64
- true
- Console
- kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;bcrypt.lib;ucrt.lib;%(AdditionalDependencies)
-
-
- copy /b "$(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\bc.exe" "$(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\dc.exe"
-
-
- Copying bc to dc...
-
-
-
-
- WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions);BC_ENABLED=1;DC_ENABLED=1;BC_ENABLE_EXTRA_MATH=1;BC_ENABLE_HISTORY=1;BC_ENABLE_NLS=0;BC_DEBUG_CODE=0;BC_ENABLE_LIBRARY=0;EXECSUFFIX=.exe;BUILD_TYPE=N;BC_DEFAULT_BANNER=1;BC_DEFAULT_SIGINT_RESET=0;DC_DEFAULT_SIGINT_RESET=0;BC_DEFAULT_TTY_MODE=1;DC_DEFAULT_TTY_MODE=1;BC_DEFAULT_PROMPT=1;DC_DEFAULT_PROMPT=1
- $(SolutionDir)\include;%(AdditionalIncludeDirectories)
- MultiThreadedDLL
- Level3
- ProgramDatabase
- MaxSpeed
- false
- /W3 %(AdditionalOptions)
- Default
-
-
- MachineX64
- DebugFastLink
- Console
- kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;bcrypt.lib;ucrt.lib;%(AdditionalDependencies)
-
-
- copy /b "$(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\bc.exe" "$(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\dc.exe"
-
-
- Copying bc to dc...
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/bc.vcxproj.filters b/bc.vcxproj.filters
deleted file mode 100644
index 141ecb808d08..000000000000
--- a/bc.vcxproj.filters
+++ /dev/null
@@ -1,182 +0,0 @@
-
-
-
-
- {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
- cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
-
-
- {93995380-89BD-4b04-88EB-625FBE52EBFB}
- h;hh;hpp;hxx;hm;inl;inc;xsd
-
-
- {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
- rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav
-
-
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
-
-
- Source Files
-
-
-
-
-
-
-
-
-
-
-
-
- Resource Files
-
-
- Resource Files
-
-
-
-
- Resource Files
-
-
- Resource Files
-
-
-
\ No newline at end of file
diff --git a/bcl.sln b/bcl.sln
deleted file mode 100644
index 77009a439db3..000000000000
--- a/bcl.sln
+++ /dev/null
@@ -1,31 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 16
-VisualStudioVersion = 16.0.31129.286
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bcl", "bcl.vcxproj", "{D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|x64 = Debug|x64
- Debug|x86 = Debug|x86
- Release|x64 = Release|x64
- Release|x86 = Release|x86
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}.Debug|x64.ActiveCfg = Debug|x64
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}.Debug|x64.Build.0 = Debug|x64
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}.Debug|x86.ActiveCfg = Debug|Win32
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}.Debug|x86.Build.0 = Debug|Win32
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}.Release|x64.ActiveCfg = Release|x64
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}.Release|x64.Build.0 = Release|x64
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}.Release|x86.ActiveCfg = Release|Win32
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}.Release|x86.Build.0 = Release|Win32
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {591735E0-C314-4BFF-A595-E9999B49CB25}
- EndGlobalSection
-EndGlobal
diff --git a/bcl.vcxproj b/bcl.vcxproj
deleted file mode 100644
index c1031045e34a..000000000000
--- a/bcl.vcxproj
+++ /dev/null
@@ -1,161 +0,0 @@
-
-
-
-
- Debug
- Win32
-
-
- Release
- Win32
-
-
- Debug
- x64
-
-
- Release
- x64
-
-
-
- 16.0
- {D2CC3DCF-7919-4DEF-839D-E9B897EC3E8E}
- Win32Proj
- 10.0
-
-
-
- StaticLibrary
- true
- v142
-
-
- StaticLibrary
- false
- v142
-
-
- StaticLibrary
- true
- v142
-
-
- StaticLibrary
- false
- v142
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- true
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
-
-
- true
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
-
-
- true
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
-
-
- true
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
- $(SolutionDir)\$(Configuration)\$(Platform)\$(ProjectName)\
-
-
-
- WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions);BC_ENABLED=1;DC_ENABLED=1;BC_ENABLE_EXTRA_MATH=1;BC_ENABLE_HISTORY=0;BC_ENABLE_NLS=0;BC_DEBUG_CODE=0;BC_ENABLE_LIBRARY=1
- MultiThreadedDebugDLL
- Level3
- ProgramDatabase
- Disabled
- $(SolutionDir)\include
-
-
- MachineX86
- true
- Windows
-
-
-
-
- WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions);BC_ENABLED=1;DC_ENABLED=1;BC_ENABLE_EXTRA_MATH=1;BC_ENABLE_HISTORY=0;BC_ENABLE_NLS=0;BC_DEBUG_CODE=0;BC_ENABLE_LIBRARY=1
- MultiThreadedDLL
- Level3
- ProgramDatabase
- $(SolutionDir)\include
-
-
- MachineX86
- true
- Windows
- true
- true
-
-
-
-
- WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions);BC_ENABLED=1;DC_ENABLED=1;BC_ENABLE_EXTRA_MATH=1;BC_ENABLE_HISTORY=0;BC_ENABLE_NLS=0;BC_DEBUG_CODE=0;BC_ENABLE_LIBRARY=1
- $(SolutionDir)\include
-
-
-
-
- WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions);BC_ENABLED=1;DC_ENABLED=1;BC_ENABLE_EXTRA_MATH=1;BC_ENABLE_HISTORY=0;BC_ENABLE_NLS=0;BC_DEBUG_CODE=0;BC_ENABLE_LIBRARY=1
- $(SolutionDir)\include
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/bcl.vcxproj.filters b/bcl.vcxproj.filters
deleted file mode 100644
index f75e0331cc88..000000000000
--- a/bcl.vcxproj.filters
+++ /dev/null
@@ -1,96 +0,0 @@
-
-
-
-
- {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
- cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
-
-
- {93995380-89BD-4b04-88EB-625FBE52EBFB}
- h;hh;hpp;hxx;hm;inl;inc;xsd
-
-
- {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
- rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav
-
-
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
- Source Files
-
-
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
- Header Files
-
-
-
\ No newline at end of file
diff --git a/configure.sh b/configure.sh
index bcc8688e0ec1..de1339780073 100755
--- a/configure.sh
+++ b/configure.sh
@@ -1,1608 +1,1658 @@
#! /bin/sh
#
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2018-2021 Gavin D. Howard and contributors.
#
# 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.
#
script="$0"
scriptdir=$(dirname "$script")
script=$(basename "$script")
. "$scriptdir/scripts/functions.sh"
cd "$scriptdir"
# Simply prints the help message and quits based on the argument.
# @param val The value to pass to exit. Must be an integer.
usage() {
if [ $# -gt 0 ]; then
_usage_val=1
printf "%s\n\n" "$1"
else
_usage_val=0
fi
printf 'usage:\n'
printf ' %s -h\n' "$script"
printf ' %s --help\n' "$script"
printf ' %s [-a|-bD|-dB|-c] [-CEfgGHlmMNPtTvz] [-O OPT_LEVEL] [-k KARATSUBA_LEN]\n' "$script"
printf ' %s \\\n' "$script"
printf ' [--library|--bc-only --disable-dc|--dc-only --disable-bc|--coverage] \\\n'
printf ' [--force --debug --disable-extra-math --disable-generated-tests] \\\n'
printf ' [--disable-history --disable-man-pages --disable-nls --disable-strip] \\\n'
printf ' [--install-all-locales] [--opt=OPT_LEVEL] \\\n'
printf ' [--karatsuba-len=KARATSUBA_LEN] \\\n'
printf ' [--prefix=PREFIX] [--bindir=BINDIR] [--datarootdir=DATAROOTDIR] \\\n'
printf ' [--datadir=DATADIR] [--mandir=MANDIR] [--man1dir=MAN1DIR] \\\n'
printf '\n'
printf ' -a, --library\n'
printf ' Build the libbcl instead of the programs. This is meant to be used with\n'
printf ' Other software like programming languages that want to make use of the\n'
printf ' parsing and math capabilities. This option will install headers using\n'
printf ' `make install`.\n'
printf ' -b, --bc-only\n'
printf ' Build bc only. It is an error if "-d", "--dc-only", "-B", or\n'
printf ' "--disable-bc" are specified too.\n'
printf ' -B, --disable-bc\n'
printf ' Disable bc. It is an error if "-b", "--bc-only", "-D", or "--disable-dc"\n'
printf ' are specified too.\n'
printf ' -c, --coverage\n'
printf ' Generate test coverage code. Requires gcov and gcovr.\n'
printf ' It is an error if either "-b" ("-D") or "-d" ("-B") is specified.\n'
printf ' Requires a compiler that use gcc-compatible coverage options\n'
printf ' -C, --disable-clean\n'
printf ' Disable the clean that configure.sh does before configure.\n'
printf ' -d, --dc-only\n'
printf ' Build dc only. It is an error if "-b", "--bc-only", "-D", or\n'
printf ' "--disable-dc" are specified too.\n'
printf ' -D, --disable-dc\n'
printf ' Disable dc. It is an error if "-d", "--dc-only", "-B", or "--disable-bc"\n'
printf ' are specified too.\n'
printf ' -E, --disable-extra-math\n'
printf ' Disable extra math. This includes: "$" operator (truncate to integer),\n'
printf ' "@" operator (set number of decimal places), and r(x, p) (rounding\n'
printf ' function). Additionally, this option disables the extra printing\n'
printf ' functions in the math library.\n'
printf ' -f, --force\n'
printf ' Force use of all enabled options, even if they do not work. This\n'
printf ' option is to allow the maintainer a way to test that certain options\n'
printf ' are not failing invisibly. (Development only.)'
printf ' -g, --debug\n'
printf ' Build in debug mode. Adds the "-g" flag, and if there are no\n'
printf ' other CFLAGS, and "-O" was not given, this also adds the "-O0"\n'
printf ' flag. If this flag is *not* given, "-DNDEBUG" is added to CPPFLAGS\n'
printf ' and a strip flag is added to the link stage.\n'
printf ' -G, --disable-generated-tests\n'
printf ' Disable generating tests. This is for platforms that do not have a\n'
printf ' GNU bc-compatible bc to generate tests.\n'
printf ' -h, --help\n'
printf ' Print this help message and exit.\n'
printf ' -H, --disable-history\n'
printf ' Disable history.\n'
printf ' -k KARATSUBA_LEN, --karatsuba-len KARATSUBA_LEN\n'
printf ' Set the karatsuba length to KARATSUBA_LEN (default is 64).\n'
printf ' It is an error if KARATSUBA_LEN is not a number or is less than 16.\n'
printf ' -l, --install-all-locales\n'
printf ' Installs all locales, regardless of how many are on the system. This\n'
printf ' option is useful for package maintainers who want to make sure that\n'
printf ' a package contains all of the locales that end users might need.\n'
printf ' -m, --enable-memcheck\n'
printf ' Enable memcheck mode, to ensure no memory leaks. For development only.\n'
printf ' -M, --disable-man-pages\n'
printf ' Disable installing manpages.\n'
printf ' -N, --disable-nls\n'
printf ' Disable POSIX locale (NLS) support.\n'
printf ' -O OPT_LEVEL, --opt OPT_LEVEL\n'
printf ' Set the optimization level. This can also be included in the CFLAGS,\n'
printf ' but it is provided, so maintainers can build optimized debug builds.\n'
printf ' This is passed through to the compiler, so it must be supported.\n'
printf ' -s SETTING, --set-default-on SETTING\n'
printf ' Set the default named by SETTING to on. See below for possible values\n'
printf ' for SETTING. For multiple instances of the -s or -S for the the same\n'
printf ' setting, the last one is used.\n'
printf ' -S SETTING, --set-default-off SETTING\n'
printf ' Set the default named by SETTING to off. See below for possible values\n'
printf ' for SETTING. For multiple instances of the -s or -S for the the same\n'
printf ' setting, the last one is used.\n'
printf ' -t, --enable-test-timing\n'
printf ' Enable the timing of tests. This is for development only.\n'
printf ' -T, --disable-strip\n'
printf ' Disable stripping symbols from the compiled binary or binaries.\n'
printf ' Stripping symbols only happens when debug mode is off.\n'
printf ' -v, --enable-valgrind\n'
printf ' Enable a build appropriate for valgrind. For development only.\n'
printf ' -z, --enable-fuzz-mode\n'
printf ' Enable fuzzing mode. THIS IS FOR DEVELOPMENT ONLY.\n'
printf ' --prefix PREFIX\n'
printf ' The prefix to install to. Overrides "$PREFIX" if it exists.\n'
printf ' If PREFIX is "/usr", install path will be "/usr/bin".\n'
printf ' Default is "/usr/local".\n'
printf ' --bindir BINDIR\n'
printf ' The directory to install binaries in. Overrides "$BINDIR" if it exists.\n'
printf ' Default is "$PREFIX/bin".\n'
printf ' --includedir INCLUDEDIR\n'
printf ' The directory to install headers in. Overrides "$INCLUDEDIR" if it\n'
printf ' exists. Default is "$PREFIX/include".\n'
printf ' --libdir LIBDIR\n'
printf ' The directory to install libraries in. Overrides "$LIBDIR" if it exists.\n'
printf ' Default is "$PREFIX/lib".\n'
printf ' --datarootdir DATAROOTDIR\n'
printf ' The root location for data files. Overrides "$DATAROOTDIR" if it exists.\n'
printf ' Default is "$PREFIX/share".\n'
printf ' --datadir DATADIR\n'
printf ' The location for data files. Overrides "$DATADIR" if it exists.\n'
printf ' Default is "$DATAROOTDIR".\n'
printf ' --mandir MANDIR\n'
printf ' The location to install manpages to. Overrides "$MANDIR" if it exists.\n'
printf ' Default is "$DATADIR/man".\n'
printf ' --man1dir MAN1DIR\n'
printf ' The location to install Section 1 manpages to. Overrides "$MAN1DIR" if\n'
printf ' it exists. Default is "$MANDIR/man1".\n'
printf ' --man3dir MAN3DIR\n'
printf ' The location to install Section 3 manpages to. Overrides "$MAN3DIR" if\n'
printf ' it exists. Default is "$MANDIR/man3".\n'
printf '\n'
printf 'In addition, the following environment variables are used:\n'
printf '\n'
printf ' CC C compiler. Must be compatible with POSIX c99. If there is a\n'
printf ' space in the basename of the compiler, the items after the\n'
printf ' first space are assumed to be compiler flags, and in that case,\n'
printf ' the flags are automatically moved into CFLAGS. Default is\n'
printf ' "c99".\n'
printf ' HOSTCC Host C compiler. Must be compatible with POSIX c99. If there is\n'
printf ' a space in the basename of the compiler, the items after the\n'
printf ' first space are assumed to be compiler flags, and in the case,\n'
printf ' the flags are automatically moved into HOSTCFLAGS. Default is\n'
printf ' "$CC".\n'
printf ' HOST_CC Same as HOSTCC. If HOSTCC also exists, it is used.\n'
printf ' CFLAGS C compiler flags.\n'
printf ' HOSTCFLAGS CFLAGS for HOSTCC. Default is "$CFLAGS".\n'
printf ' HOST_CFLAGS Same as HOST_CFLAGS. If HOST_CFLAGS also exists, it is used.\n'
printf ' CPPFLAGS C preprocessor flags. Default is "".\n'
printf ' LDFLAGS Linker flags. Default is "".\n'
printf ' PREFIX The prefix to install to. Default is "/usr/local".\n'
printf ' If PREFIX is "/usr", install path will be "/usr/bin".\n'
printf ' BINDIR The directory to install binaries in. Default is "$PREFIX/bin".\n'
printf ' INCLUDEDIR The directory to install header files in. Default is\n'
printf ' "$PREFIX/include".\n'
printf ' LIBDIR The directory to install libraries in. Default is\n'
printf ' "$PREFIX/lib".\n'
printf ' DATAROOTDIR The root location for data files. Default is "$PREFIX/share".\n'
printf ' DATADIR The location for data files. Default is "$DATAROOTDIR".\n'
printf ' MANDIR The location to install manpages to. Default is "$DATADIR/man".\n'
printf ' MAN1DIR The location to install Section 1 manpages to. Default is\n'
printf ' "$MANDIR/man1".\n'
printf ' MAN3DIR The location to install Section 3 manpages to. Default is\n'
printf ' "$MANDIR/man3".\n'
printf ' NLSPATH The location to install locale catalogs to. Must be an absolute\n'
printf ' path (or contain one). This is treated the same as the POSIX\n'
printf ' definition of $NLSPATH (see POSIX environment variables for\n'
printf ' more information). Default is "/usr/share/locale/%%L/%%N".\n'
printf ' EXECSUFFIX The suffix to append to the executable names, used to not\n'
printf ' interfere with other installed bc executables. Default is "".\n'
printf ' EXECPREFIX The prefix to append to the executable names, used to not\n'
printf ' interfere with other installed bc executables. Default is "".\n'
printf ' DESTDIR For package creation. Default is "". If it is empty when\n'
printf ' `%s` is run, it can also be passed to `make install`\n' "$script"
printf ' later as an environment variable. If both are specified,\n'
printf ' the one given to `%s` takes precedence.\n' "$script"
printf ' LONG_BIT The number of bits in a C `long` type. This is mostly for the\n'
printf ' embedded space since this `bc` uses `long`s internally for\n'
printf ' overflow checking. In C99, a `long` is required to be 32 bits.\n'
printf ' For most normal desktop systems, setting this is unnecessary,\n'
printf ' except that 32-bit platforms with 64-bit longs may want to set\n'
printf ' it to `32`. Default is the default of `LONG_BIT` for the target\n'
printf ' platform. Minimum allowed is `32`. It is a build time error if\n'
printf ' the specified value of `LONG_BIT` is greater than the default\n'
printf ' value of `LONG_BIT` for the target platform.\n'
printf ' GEN_HOST Whether to use `gen/strgen.c`, instead of `gen/strgen.sh`, to\n'
printf ' produce the C files that contain the help texts as well as the\n'
printf ' math libraries. By default, `gen/strgen.c` is used, compiled by\n'
printf ' "$HOSTCC" and run on the host machine. Using `gen/strgen.sh`\n'
printf ' removes the need to compile and run an executable on the host\n'
printf ' machine since `gen/strgen.sh` is a POSIX shell script. However,\n'
printf ' `gen/lib2.bc` is perilously close to 4095 characters, the max\n'
printf ' supported length of a string literal in C99 (and it could be\n'
printf ' added to in the future), and `gen/strgen.sh` generates a string\n'
printf ' literal instead of an array, as `gen/strgen.c` does. For most\n'
printf ' production-ready compilers, this limit probably is not\n'
printf ' enforced, but it could be. Both options are still available for\n'
printf ' this reason. If you are sure your compiler does not have the\n'
printf ' limit and do not want to compile and run a binary on the host\n'
printf ' machine, set this variable to "0". Any other value, or a\n'
printf ' non-existent value, will cause the build system to compile and\n'
printf ' run `gen/strgen.c`. Default is "".\n'
printf ' GEN_EMU Emulator to run string generator code under (leave empty if not\n'
printf ' necessary). This is not necessary when using `gen/strgen.sh`.\n'
printf ' Default is "".\n'
printf '\n'
printf 'WARNING: even though `configure.sh` supports both option types, short and\n'
printf 'long, it does not support handling both at the same time. Use only one type.\n'
printf '\n'
printf 'Settings\n'
printf '========\n'
printf '\n'
printf 'bc and dc have some settings that, while they cannot be removed by build time\n'
printf 'options, can have their defaults changed at build time by packagers. Users are\n'
printf 'also able to change each setting with environment variables.\n'
printf '\n'
printf 'The following is a table of settings, along with their default values and the\n'
printf 'environment variables users can use to change them. (For the defaults, non-zero\n'
printf 'means on, and zero means off.)\n'
printf '\n'
printf '| Setting | Description | Default | Env Variable |\n'
printf '| =============== | ==================== | ============ | ==================== |\n'
printf '| bc.banner | Whether to display | 0 | BC_BANNER |\n'
printf '| | the bc version | | |\n'
printf '| | banner when in | | |\n'
printf '| | interactive mode. | | |\n'
printf '| --------------- | -------------------- | ------------ | -------------------- |\n'
printf '| bc.sigint_reset | Whether SIGINT will | 1 | BC_SIGINT_RESET |\n'
printf '| | reset bc, instead of | | |\n'
printf '| | exiting, when in | | |\n'
printf '| | interactive mode. | | |\n'
printf '| --------------- | -------------------- | ------------ | -------------------- |\n'
printf '| dc.sigint_reset | Whether SIGINT will | 1 | DC_SIGINT_RESET |\n'
printf '| | reset dc, instead of | | |\n'
printf '| | exiting, when in | | |\n'
printf '| | interactive mode. | | |\n'
printf '| --------------- | -------------------- | ------------ | -------------------- |\n'
printf '| bc.tty_mode | Whether TTY mode for | 1 | BC_TTY_MODE |\n'
printf '| | bc should be on when | | |\n'
printf '| | available. | | |\n'
printf '| --------------- | -------------------- | ------------ | -------------------- |\n'
printf '| dc.tty_mode | Whether TTY mode for | 0 | BC_TTY_MODE |\n'
printf '| | dc should be on when | | |\n'
printf '| | available. | | |\n'
printf '| --------------- | -------------------- | ------------ | -------------------- |\n'
printf '| bc.prompt | Whether the prompt | $BC_TTY_MODE | BC_PROMPT |\n'
printf '| | for bc should be on | | |\n'
printf '| | in tty mode. | | |\n'
printf '| --------------- | -------------------- | ------------ | -------------------- |\n'
printf '| dc.prompt | Whether the prompt | $DC_TTY_MODE | DC_PROMPT |\n'
printf '| | for dc should be on | | |\n'
printf '| | in tty mode. | | |\n'
printf '| --------------- | -------------------- | ------------ | -------------------- |\n'
printf '\n'
printf 'These settings are not meant to be changed on a whim. They are meant to ensure\n'
printf 'that this bc and dc will conform to the expectations of the user on each\n'
printf 'platform.\n'
exit "$_usage_val"
}
# Replaces a file extension in a filename. This is used mostly to turn filenames
# like `src/num.c` into `src/num.o`. In other words, it helps to link targets to
# the files they depend on.
#
# @param file The filename.
# @param ext1 The extension to replace.
# @param ext2 The new extension.
replace_ext() {
if [ "$#" -ne 3 ]; then
err_exit "Invalid number of args to $0"
fi
_replace_ext_file="$1"
_replace_ext_ext1="$2"
_replace_ext_ext2="$3"
_replace_ext_result="${_replace_ext_file%.$_replace_ext_ext1}.$_replace_ext_ext2"
printf '%s\n' "$_replace_ext_result"
}
# Replaces a file extension in every filename given in a list. The list is just
# a space-separated list of words, so filenames are expected to *not* have
# spaces in them. See the documentation for `replace_ext()`.
#
# @param files The list of space-separated filenames to replace extensions for.
# @param ext1 The extension to replace.
# @param ext2 The new extension.
replace_exts() {
if [ "$#" -ne 3 ]; then
err_exit "Invalid number of args to $0"
fi
_replace_exts_files="$1"
_replace_exts_ext1="$2"
_replace_exts_ext2="$3"
for _replace_exts_file in $_replace_exts_files; do
_replace_exts_new_name=$(replace_ext "$_replace_exts_file" "$_replace_exts_ext1" "$_replace_exts_ext2")
_replace_exts_result="$_replace_exts_result $_replace_exts_new_name"
done
printf '%s\n' "$_replace_exts_result"
}
# Finds a placeholder in @a str and replaces it. This is the workhorse of
# configure.sh. It's what replaces placeholders in Makefile.in with the data
# needed for the chosen build. Below, you will see a lot of calls to this
# function.
#
# Note that needle can never contain an exclamation point. For more information,
# see substring_replace() in scripts/functions.sh.
#
# @param str The string to find and replace placeholders in.
# @param needle The placeholder name.
# @param replacement The string to use to replace the placeholder.
replace() {
if [ "$#" -ne 3 ]; then
err_exit "Invalid number of args to $0"
fi
_replace_str="$1"
_replace_needle="$2"
_replace_replacement="$3"
substring_replace "$_replace_str" "%%$_replace_needle%%" "$_replace_replacement"
}
# This function finds all the source files that need to be built. If there is
# only one argument and it is empty, then all source files are built. Otherwise,
# the arguments are all assumed to be source files that should *not* be built.
find_src_files() {
if [ "$#" -ge 1 ] && [ "$1" != "" ]; then
while [ "$#" -ge 1 ]; do
_find_src_files_a="${1## }"
shift
_find_src_files_args="$_find_src_files_args ! -path src/${_find_src_files_a}"
done
else
_find_src_files_args="-print"
fi
printf '%s\n' $(find src/ -depth -name "*.c" $_find_src_files_args)
}
# This function generates a list of files to go into the Makefile. It generates
# the list of object files, as well as the list of test coverage files.
#
# @param contents The contents of the Makefile template to put the list of
# files into.
gen_file_list() {
if [ "$#" -lt 1 ]; then
err_exit "Invalid number of args to $0"
fi
_gen_file_list_contents="$1"
shift
p=$(pwd)
cd "$scriptdir"
if [ "$#" -ge 1 ]; then
_gen_file_list_unneeded="$@"
else
_gen_file_list_unneeded=""
fi
_gen_file_list_needle_src="SRC"
_gen_file_list_needle_obj="OBJ"
_gen_file_list_needle_gcda="GCDA"
_gen_file_list_needle_gcno="GCNO"
_gen_file_list_replacement=$(find_src_files $_gen_file_list_unneeded | tr '\n' ' ')
_gen_file_list_contents=$(replace "$_gen_file_list_contents" \
"$_gen_file_list_needle_src" "$_gen_file_list_replacement")
_gen_file_list_replacement=$(replace_exts "$_gen_file_list_replacement" "c" "o")
_gen_file_list_contents=$(replace "$_gen_file_list_contents" \
"$_gen_file_list_needle_obj" "$_gen_file_list_replacement")
_gen_file_list_replacement=$(replace_exts "$_gen_file_list_replacement" "o" "gcda")
_gen_file_list_contents=$(replace "$_gen_file_list_contents" \
"$_gen_file_list_needle_gcda" "$_gen_file_list_replacement")
_gen_file_list_replacement=$(replace_exts "$_gen_file_list_replacement" "gcda" "gcno")
_gen_file_list_contents=$(replace "$_gen_file_list_contents" \
"$_gen_file_list_needle_gcno" "$_gen_file_list_replacement")
cd "$p"
printf '%s\n' "$_gen_file_list_contents"
}
# Generates the proper test targets for each test to have its own target. This
# allows `make test` to run in parallel.
#
# @param name Which calculator to generate tests for.
# @param extra_math An integer that, if non-zero, activates extra math tests.
# @param time_tests An integer that, if non-zero, tells the test suite to time
# the execution of each test.
-gen_tests() {
+gen_std_tests() {
- _gen_tests_name="$1"
+ _gen_std_tests_name="$1"
shift
- _gen_tests_extra_math="$1"
+ _gen_std_tests_extra_math="$1"
shift
- _gen_tests_time_tests="$1"
+ _gen_std_tests_time_tests="$1"
shift
- _gen_tests_extra_required=$(cat "$scriptdir/tests/extra_required.txt")
+ _gen_std_tests_extra_required=$(cat "$scriptdir/tests/extra_required.txt")
- for _gen_tests_t in $(cat "$scriptdir/tests/$_gen_tests_name/all.txt"); do
+ for _gen_std_tests_t in $(cat "$scriptdir/tests/$_gen_std_tests_name/all.txt"); do
- if [ "$_gen_tests_extra_math" -eq 0 ]; then
+ if [ "$_gen_std_tests_extra_math" -eq 0 ]; then
- if [ -z "${_gen_tests_extra_required##*$_gen_tests_t*}" ]; then
+ if [ -z "${_gen_std_tests_extra_required##*$_gen_std_tests_t*}" ]; then
printf 'test_%s_%s:\n\t@printf "Skipping %s %s\\n"\n\n' \
- "$_gen_tests_name" "$_gen_tests_t" "$_gen_tests_name" \
- "$_gen_tests_t" >> "$scriptdir/Makefile"
+ "$_gen_std_tests_name" "$_gen_std_tests_t" "$_gen_std_tests_name" \
+ "$_gen_std_tests_t" >> "$scriptdir/Makefile"
continue
fi
fi
printf 'test_%s_%s:\n\t@sh tests/test.sh %s %s %s %s %s\n\n' \
- "$_gen_tests_name" "$_gen_tests_t" "$_gen_tests_name" \
- "$_gen_tests_t" "$generate_tests" "$time_tests" \
+ "$_gen_std_tests_name" "$_gen_std_tests_t" "$_gen_std_tests_name" \
+ "$_gen_std_tests_t" "$generate_tests" "$time_tests" \
"$*" >> "$scriptdir/Makefile"
done
}
# Generates a list of test targets that will be used as prerequisites for other
# targets.
#
# @param name The name of the calculator to generate test targets for.
-gen_test_targets() {
+gen_std_test_targets() {
- _gen_test_targets_name="$1"
+ _gen_std_test_targets_name="$1"
shift
- _gen_test_targets_tests=$(cat "$scriptdir/tests/${_gen_test_targets_name}/all.txt")
+ _gen_std_test_targets_tests=$(cat "$scriptdir/tests/${_gen_std_test_targets_name}/all.txt")
- for _gen_test_targets_t in $_gen_test_targets_tests; do
- printf ' test_%s_%s' "$_gen_test_targets_name" "$_gen_test_targets_t"
+ for _gen_std_test_targets_t in $_gen_std_test_targets_tests; do
+ printf ' test_%s_%s' "$_gen_std_test_targets_name" "$_gen_std_test_targets_t"
+ done
+
+ printf '\n'
+}
+
+# Generates the proper test targets for each error test to have its own target.
+# This allows `make test_bc_errors` and `make test_dc_errors` to run in
+# parallel.
+#
+# @param name Which calculator to generate tests for.
+gen_err_tests() {
+
+ _gen_err_tests_name="$1"
+ shift
+
+ _gen_err_tests_fs=$(ls "$scriptdir/tests/$_gen_err_tests_name/errors/")
+
+ for _gen_err_tests_t in $_gen_err_tests_fs; do
+
+ printf 'test_%s_error_%s:\n\t@sh tests/error.sh %s %s %s\n\n' \
+ "$_gen_err_tests_name" "$_gen_err_tests_t" "$_gen_err_tests_name" \
+ "$_gen_err_tests_t" "$*" >> "$scriptdir/Makefile"
+
+ done
+
+}
+
+# Generates a list of error test targets that will be used as prerequisites for
+# other targets.
+#
+# @param name The name of the calculator to generate test targets for.
+gen_err_test_targets() {
+
+ _gen_err_test_targets_name="$1"
+ shift
+
+ _gen_err_test_targets_tests=$(ls "$scriptdir/tests/$_gen_err_test_targets_name/errors/")
+
+ for _gen_err_test_targets_t in $_gen_err_test_targets_tests; do
+ printf ' test_%s_error_%s' "$_gen_err_test_targets_name" "$_gen_err_test_targets_t"
done
printf '\n'
}
# Generates the proper script test targets for each script test to have its own
# target. This allows `make test` to run in parallel.
#
# @param name Which calculator to generate tests for.
# @param extra_math An integer that, if non-zero, activates extra math tests.
# @param generate An integer that, if non-zero, activates generated tests.
# @param time_tests An integer that, if non-zero, tells the test suite to time
# the execution of each test.
gen_script_tests() {
_gen_script_tests_name="$1"
shift
_gen_script_tests_extra_math="$1"
shift
_gen_script_tests_generate="$1"
shift
_gen_script_tests_time="$1"
shift
_gen_script_tests_tests=$(cat "$scriptdir/tests/$_gen_script_tests_name/scripts/all.txt")
for _gen_script_tests_f in $_gen_script_tests_tests; do
_gen_script_tests_b=$(basename "$_gen_script_tests_f" ".${_gen_script_tests_name}")
printf 'test_%s_script_%s:\n\t@sh tests/script.sh %s %s %s 1 %s %s %s\n\n' \
"$_gen_script_tests_name" "$_gen_script_tests_b" "$_gen_script_tests_name" \
"$_gen_script_tests_f" "$_gen_script_tests_extra_math" "$_gen_script_tests_generate" \
"$_gen_script_tests_time" "$*" >> "$scriptdir/Makefile"
done
}
set_default() {
_set_default_on="$1"
shift
_set_default_name="$1"
shift
# The reason that the variables that are being set do not have the same
# non-collision avoidance that the other variables do is that we *do* want
# the settings of these variables to leak out of the function. They adjust
# the settings outside of the function.
case "$_set_default_name" in
bc.banner) bc_default_banner="$_set_default_on" ;;
bc.sigint_reset) bc_default_sigint_reset="$_set_default_on" ;;
dc.sigint_reset) dc_default_sigint_reset="$_set_default_on" ;;
bc.tty_mode) bc_default_tty_mode="$_set_default_on" ;;
dc.tty_mode) dc_default_tty_mode="$_set_default_on" ;;
bc.prompt) bc_default_prompt="$_set_default_on" ;;
dc.prompt) dc_default_prompt="$_set_default_on" ;;
?) usage "Invalid setting: $_set_default_name" ;;
esac
}
# Generates a list of script test targets that will be used as prerequisites for
# other targets.
#
# @param name The name of the calculator to generate script test targets for.
gen_script_test_targets() {
_gen_script_test_targets_name="$1"
shift
_gen_script_test_targets_tests=$(cat "$scriptdir/tests/$_gen_script_test_targets_name/scripts/all.txt")
for _gen_script_test_targets_f in $_gen_script_test_targets_tests; do
_gen_script_test_targets_b=$(basename "$_gen_script_test_targets_f" \
".$_gen_script_test_targets_name")
printf ' test_%s_script_%s' "$_gen_script_test_targets_name" \
"$_gen_script_test_targets_b"
done
printf '\n'
}
# This is a list of defaults, but it is also the list of possible options for
# users to change.
#
# The development options are: force (force options even if they fail), valgrind
# (build in a way suitable for valgrind testing), memcheck (same as valgrind),
# and fuzzing (build in a way suitable for fuzzing).
bc_only=0
dc_only=0
coverage=0
karatsuba_len=32
debug=0
hist=1
extra_math=1
optimization=""
generate_tests=1
install_manpages=1
nls=1
force=0
strip_bin=1
all_locales=0
library=0
fuzz=0
time_tests=0
vg=0
memcheck=0
clean=1
# The empty strings are because they depend on TTY mode. If they are directly
# set, though, they will be integers. We test for empty strings later.
bc_default_banner=0
bc_default_sigint_reset=1
dc_default_sigint_reset=1
bc_default_tty_mode=1
dc_default_tty_mode=0
bc_default_prompt=""
dc_default_prompt=""
# getopts is a POSIX utility, but it cannot handle long options. Thus, the
# handling of long options is done by hand, and that's the reason that short and
# long options cannot be mixed.
while getopts "abBcdDEfgGhHk:lMmNO:S:s:tTvz-" opt; do
case "$opt" in
a) library=1 ;;
b) bc_only=1 ;;
B) dc_only=1 ;;
c) coverage=1 ;;
C) clean=0 ;;
d) dc_only=1 ;;
D) bc_only=1 ;;
E) extra_math=0 ;;
f) force=1 ;;
g) debug=1 ;;
G) generate_tests=0 ;;
h) usage ;;
H) hist=0 ;;
k) karatsuba_len="$OPTARG" ;;
l) all_locales=1 ;;
m) memcheck=1 ;;
M) install_manpages=0 ;;
N) nls=0 ;;
O) optimization="$OPTARG" ;;
S) set_default 0 "$OPTARG" ;;
s) set_default 1 "$OPTARG" ;;
t) time_tests=1 ;;
T) strip_bin=0 ;;
v) vg=1 ;;
z) fuzz=1 ;;
-)
arg="$1"
arg="${arg#--}"
LONG_OPTARG="${arg#*=}"
case $arg in
help) usage ;;
library) library=1 ;;
bc-only) bc_only=1 ;;
dc-only) dc_only=1 ;;
coverage) coverage=1 ;;
debug) debug=1 ;;
force) force=1 ;;
prefix=?*) PREFIX="$LONG_OPTARG" ;;
prefix)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
PREFIX="$2"
shift ;;
bindir=?*) BINDIR="$LONG_OPTARG" ;;
bindir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
BINDIR="$2"
shift ;;
includedir=?*) INCLUDEDIR="$LONG_OPTARG" ;;
includedir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
INCLUDEDIR="$2"
shift ;;
libdir=?*) LIBDIR="$LONG_OPTARG" ;;
libdir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
LIBDIR="$2"
shift ;;
datarootdir=?*) DATAROOTDIR="$LONG_OPTARG" ;;
datarootdir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
DATAROOTDIR="$2"
shift ;;
datadir=?*) DATADIR="$LONG_OPTARG" ;;
datadir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
DATADIR="$2"
shift ;;
mandir=?*) MANDIR="$LONG_OPTARG" ;;
mandir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
MANDIR="$2"
shift ;;
man1dir=?*) MAN1DIR="$LONG_OPTARG" ;;
man1dir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
MAN1DIR="$2"
shift ;;
man3dir=?*) MAN3DIR="$LONG_OPTARG" ;;
man3dir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
MAN3DIR="$2"
shift ;;
localedir=?*) LOCALEDIR="$LONG_OPTARG" ;;
localedir)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
LOCALEDIR="$2"
shift ;;
karatsuba-len=?*) karatsuba_len="$LONG_OPTARG" ;;
karatsuba-len)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
karatsuba_len="$1"
shift ;;
opt=?*) optimization="$LONG_OPTARG" ;;
opt)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
optimization="$1"
shift ;;
set-default-on=?*) set_default 1 "$LONG_OPTARG" ;;
set-default-on)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
set_default 1 "$1"
shift ;;
set-default-off=?*) set_default 0 "$LONG_OPTARG" ;;
set-default-off)
if [ "$#" -lt 2 ]; then
usage "No argument given for '--$arg' option"
fi
set_default 0 "$1"
shift ;;
disable-bc) dc_only=1 ;;
disable-dc) bc_only=1 ;;
disable-clean) clean=0 ;;
disable-extra-math) extra_math=0 ;;
disable-generated-tests) generate_tests=0 ;;
disable-history) hist=0 ;;
disable-man-pages) install_manpages=0 ;;
disable-nls) nls=0 ;;
disable-strip) strip_bin=0 ;;
enable-test-timing) time_tests=1 ;;
enable-valgrind) vg=1 ;;
enable-fuzz-mode) fuzz=1 ;;
enable-memcheck) memcheck=1 ;;
install-all-locales) all_locales=1 ;;
help* | bc-only* | dc-only* | coverage* | debug*)
usage "No arg allowed for --$arg option" ;;
disable-bc* | disable-dc* | disable-clean*)
usage "No arg allowed for --$arg option" ;;
disable-extra-math*)
usage "No arg allowed for --$arg option" ;;
disable-generated-tests* | disable-history*)
usage "No arg allowed for --$arg option" ;;
disable-man-pages* | disable-nls* | disable-strip*)
usage "No arg allowed for --$arg option" ;;
enable-fuzz-mode* | enable-test-timing* | enable-valgrind*)
usage "No arg allowed for --$arg option" ;;
enable-memcheck* | install-all-locales*)
usage "No arg allowed for --$arg option" ;;
'') break ;; # "--" terminates argument processing
* ) usage "Invalid option $LONG_OPTARG" ;;
esac
shift
OPTIND=1 ;;
?) usage "Invalid option: $opt" ;;
esac
done
# Sometimes, developers don't want configure.sh to do a config clean. But
# sometimes they do.
if [ "$clean" -ne 0 ]; then
if [ -f ./Makefile ]; then
make clean_config > /dev/null
fi
fi
# It is an error to say that bc only should be built and likewise for dc.
if [ "$bc_only" -eq 1 ] && [ "$dc_only" -eq 1 ]; then
usage "Can only specify one of -b(-D) or -d(-B)"
fi
# The library is mutually exclusive to the calculators, so it's an error to
# give an option for either of them.
if [ "$library" -ne 0 ]; then
if [ "$bc_only" -eq 1 ] || [ "$dc_only" -eq 1 ]; then
usage "Must not specify -b(-D) or -d(-B) when building the library"
fi
fi
# KARATSUBA_LEN must be an integer and must be 16 or greater.
case $karatsuba_len in
(*[!0-9]*|'') usage "KARATSUBA_LEN is not a number" ;;
(*) ;;
esac
if [ "$karatsuba_len" -lt 16 ]; then
usage "KARATSUBA_LEN is less than 16"
fi
set -e
if [ -z "${LONG_BIT+set}" ]; then
LONG_BIT_DEFINE=""
elif [ "$LONG_BIT" -lt 32 ]; then
usage "LONG_BIT is less than 32"
else
LONG_BIT_DEFINE="-DBC_LONG_BIT=\$(BC_LONG_BIT)"
fi
if [ -z "$CC" ]; then
CC="c99"
else
# I had users complain that, if they gave CFLAGS as part of CC, which
# autotools allows in its braindead way, the build would fail with an error.
# I don't like adjusting for autotools, but oh well. These lines puts the
# stuff after the first space into CFLAGS.
ccbase=$(basename "$CC")
suffix=" *"
prefix="* "
if [ "${ccbase%%$suffix}" != "$ccbase" ]; then
ccflags="${ccbase#$prefix}"
cc="${ccbase%%$suffix}"
ccdir=$(dirname "$CC")
if [ "$ccdir" = "." ] && [ "${CC#.}" = "$CC" ]; then
ccdir=""
else
ccdir="$ccdir/"
fi
CC="${ccdir}${cc}"
CFLAGS="$CFLAGS $ccflags"
fi
fi
if [ -z "$HOSTCC" ] && [ -z "$HOST_CC" ]; then
HOSTCC="$CC"
elif [ -z "$HOSTCC" ]; then
HOSTCC="$HOST_CC"
fi
if [ "$HOSTCC" != "$CC" ]; then
# Like above, this splits HOSTCC and HOSTCFLAGS.
ccbase=$(basename "$HOSTCC")
suffix=" *"
prefix="* "
if [ "${ccbase%%$suffix}" != "$ccbase" ]; then
ccflags="${ccbase#$prefix}"
cc="${ccbase%%$suffix}"
ccdir=$(dirname "$HOSTCC")
if [ "$ccdir" = "." ] && [ "${HOSTCC#.}" = "$HOSTCC" ]; then
ccdir=""
else
ccdir="$ccdir/"
fi
HOSTCC="${ccdir}${cc}"
HOSTCFLAGS="$HOSTCFLAGS $ccflags"
fi
fi
if [ -z "${HOSTCFLAGS+set}" ] && [ -z "${HOST_CFLAGS+set}" ]; then
HOSTCFLAGS="$CFLAGS"
elif [ -z "${HOSTCFLAGS+set}" ]; then
HOSTCFLAGS="$HOST_CFLAGS"
fi
# Store these for the cross compilation detection later.
OLDCFLAGS="$CFLAGS"
OLDHOSTCFLAGS="$HOSTCFLAGS"
link="@printf 'No link necessary\\\\n'"
main_exec="BC"
executable="BC_EXEC"
-tests="test_bc timeconst test_dc test_history"
+tests="test_bc timeconst test_dc"
bc_test="@tests/all.sh bc $extra_math 1 $generate_tests $time_tests \$(BC_EXEC)"
+bc_test_np="@tests/all.sh -n bc $extra_math 1 $generate_tests $time_tests \$(BC_EXEC)"
dc_test="@tests/all.sh dc $extra_math 1 $generate_tests $time_tests \$(DC_EXEC)"
+dc_test_np="@tests/all.sh -n dc $extra_math 1 $generate_tests $time_tests \$(DC_EXEC)"
timeconst="@tests/bc/timeconst.sh tests/bc/scripts/timeconst.bc \$(BC_EXEC)"
# In order to have cleanup at exit, we need to be in
# debug mode, so don't run valgrind without that.
if [ "$vg" -ne 0 ]; then
debug=1
bc_test_exec='valgrind $(VALGRIND_ARGS) $(BC_EXEC)'
dc_test_exec='valgrind $(VALGRIND_ARGS) $(DC_EXEC)'
else
bc_test_exec='$(BC_EXEC)'
dc_test_exec='$(DC_EXEC)'
fi
test_bc_history_prereqs="test_bc_history_all"
test_dc_history_prereqs="test_dc_history_all"
karatsuba="@printf 'karatsuba cannot be run because one of bc or dc is not built\\\\n'"
karatsuba_test="@printf 'karatsuba cannot be run because one of bc or dc is not built\\\\n'"
bc_lib="\$(GEN_DIR)/lib.o"
bc_help="\$(GEN_DIR)/bc_help.o"
dc_help="\$(GEN_DIR)/dc_help.o"
default_target_prereqs="\$(BIN) \$(OBJS)"
default_target_cmd="\$(CC) \$(CFLAGS) \$(OBJS) \$(LDFLAGS) -o \$(EXEC)"
default_target="\$(DC_EXEC)"
second_target_prereqs=""
second_target_cmd="$default_target_cmd"
second_target="\$(BC_EXEC)"
# This if/else if chain is for setting the defaults that change based on whether
# the library is being built, bc only, dc only, or both calculators.
if [ "$library" -ne 0 ]; then
extra_math=1
nls=0
hist=0
bc=1
dc=1
default_target_prereqs="\$(BIN) \$(OBJ)"
default_target_cmd="ar -r -cu \$(LIBBC) \$(OBJ)"
default_target="\$(LIBBC)"
tests="test_library"
test_bc_history_prereqs=" test_bc_history_skip"
test_dc_history_prereqs=" test_dc_history_skip"
elif [ "$bc_only" -eq 1 ]; then
bc=1
dc=0
dc_help=""
executables="bc"
dc_test="@printf 'No dc tests to run\\\\n'"
+ dc_test_np="@printf 'No dc tests to run\\\\n'"
test_dc_history_prereqs=" test_dc_history_skip"
install_prereqs=" install_execs"
install_man_prereqs=" install_bc_manpage"
uninstall_prereqs=" uninstall_bc"
uninstall_man_prereqs=" uninstall_bc_manpage"
default_target="\$(BC_EXEC)"
second_target="\$(DC_EXEC)"
- tests="test_bc timeconst test_history"
+ tests="test_bc timeconst"
elif [ "$dc_only" -eq 1 ]; then
bc=0
dc=1
bc_lib=""
bc_help=""
executables="dc"
main_exec="DC"
executable="DC_EXEC"
bc_test="@printf 'No bc tests to run\\\\n'"
+ bc_test_np="@printf 'No bc tests to run\\\\n'"
test_bc_history_prereqs=" test_bc_history_skip"
timeconst="@printf 'timeconst cannot be run because bc is not built\\\\n'"
install_prereqs=" install_execs"
install_man_prereqs=" install_dc_manpage"
uninstall_prereqs=" uninstall_dc"
uninstall_man_prereqs=" uninstall_dc_manpage"
- tests="test_dc test_history"
+ tests="test_dc"
else
bc=1
dc=1
executables="bc and dc"
karatsuba="@\$(KARATSUBA) 30 0 \$(BC_EXEC)"
karatsuba_test="@\$(KARATSUBA) 1 100 \$(BC_EXEC)"
if [ "$library" -eq 0 ]; then
install_prereqs=" install_execs"
install_man_prereqs=" install_bc_manpage install_dc_manpage"
uninstall_prereqs=" uninstall_bc uninstall_dc"
uninstall_man_prereqs=" uninstall_bc_manpage uninstall_dc_manpage"
else
install_prereqs=" install_library install_bcl_header"
install_man_prereqs=" install_bcl_manpage"
uninstall_prereqs=" uninstall_library uninstall_bcl_header"
uninstall_man_prereqs=" uninstall_bcl_manpage"
tests="test_library"
fi
second_target_prereqs="$default_target_prereqs"
default_target_prereqs="$second_target"
default_target_cmd="\$(LINK) \$(BIN) \$(EXEC_PREFIX)\$(DC)"
fi
# We need specific stuff for fuzzing.
if [ "$fuzz" -ne 0 ]; then
debug=1
hist=0
nls=0
optimization="3"
fi
# This sets some necessary things for debug mode.
if [ "$debug" -eq 1 ]; then
if [ -z "$CFLAGS" ] && [ -z "$optimization" ]; then
CFLAGS="-O0"
fi
CFLAGS="-g $CFLAGS"
else
CPPFLAGS="-DNDEBUG $CPPFLAGS"
if [ "$strip_bin" -ne 0 ]; then
LDFLAGS="-s $LDFLAGS"
fi
fi
# Set optimization CFLAGS.
if [ -n "$optimization" ]; then
CFLAGS="-O$optimization $CFLAGS"
fi
# Set test coverage defaults.
if [ "$coverage" -eq 1 ]; then
if [ "$bc_only" -eq 1 ] || [ "$dc_only" -eq 1 ]; then
usage "Can only specify -c without -b or -d"
fi
CFLAGS="-fprofile-arcs -ftest-coverage -g -O0 $CFLAGS"
CPPFLAGS="-DNDEBUG $CPPFLAGS"
COVERAGE_OUTPUT="@gcov -pabcdf \$(GCDA) \$(BC_GCDA) \$(DC_GCDA) \$(HISTORY_GCDA) \$(RAND_GCDA)"
COVERAGE_OUTPUT="$COVERAGE_OUTPUT;\$(RM) -f \$(GEN)*.gc*"
COVERAGE_OUTPUT="$COVERAGE_OUTPUT;gcovr --exclude-unreachable-branches --exclude-throw-branches --html-details --output index.html"
COVERAGE_PREREQS=" test coverage_output"
else
COVERAGE_OUTPUT="@printf 'Coverage not generated\\\\n'"
COVERAGE_PREREQS=""
fi
# Set some defaults.
if [ -z "${DESTDIR+set}" ]; then
destdir=""
else
destdir="DESTDIR = $DESTDIR"
fi
if [ -z "${PREFIX+set}" ]; then
PREFIX="/usr/local"
fi
if [ -z "${BINDIR+set}" ]; then
BINDIR="$PREFIX/bin"
fi
if [ -z "${INCLUDEDIR+set}" ]; then
INCLUDEDIR="$PREFIX/include"
fi
if [ -z "${LIBDIR+set}" ]; then
LIBDIR="$PREFIX/lib"
fi
# Set a default for the DATAROOTDIR. This is done if either manpages will be
# installed, or locales are enabled because that's probably where NLS_PATH
# points.
if [ "$install_manpages" -ne 0 ] || [ "$nls" -ne 0 ]; then
if [ -z "${DATAROOTDIR+set}" ]; then
DATAROOTDIR="$PREFIX/share"
fi
fi
# Set defaults for manpage environment variables.
if [ "$install_manpages" -ne 0 ]; then
if [ -z "${DATADIR+set}" ]; then
DATADIR="$DATAROOTDIR"
fi
if [ -z "${MANDIR+set}" ]; then
MANDIR="$DATADIR/man"
fi
if [ -z "${MAN1DIR+set}" ]; then
MAN1DIR="$MANDIR/man1"
fi
if [ -z "${MAN3DIR+set}" ]; then
MAN3DIR="$MANDIR/man3"
fi
else
install_man_prereqs=""
uninstall_man_prereqs=""
fi
# Here is where we test NLS (the locale system). This is done by trying to
# compile src/vm.c, which has the relevant code. If it fails, then it is
# disabled.
if [ "$nls" -ne 0 ]; then
set +e
printf 'Testing NLS...\n'
flags="-DBC_ENABLE_NLS=1 -DBC_ENABLED=$bc -DDC_ENABLED=$dc"
flags="$flags -DBC_ENABLE_HISTORY=$hist -DBC_ENABLE_LIBRARY=0 -DBC_ENABLE_AFL=0"
flags="$flags -DBC_ENABLE_EXTRA_MATH=$extra_math -I./include/"
flags="$flags -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700"
"$CC" $CPPFLAGS $CFLAGS $flags -c "src/vm.c" -o "$scriptdir/vm.o" > /dev/null 2>&1
err="$?"
rm -rf "$scriptdir/vm.o"
# If this errors, it is probably because of building on Windows,
# and NLS is not supported on Windows, so disable it.
if [ "$err" -ne 0 ]; then
printf 'NLS does not work.\n'
if [ $force -eq 0 ]; then
printf 'Disabling NLS...\n\n'
nls=0
else
printf 'Forcing NLS...\n\n'
fi
else
printf 'NLS works.\n\n'
printf 'Testing gencat...\n'
gencat "$scriptdir/en_US.cat" "$scriptdir/locales/en_US.msg" > /dev/null 2>&1
err="$?"
rm -rf "$scriptdir/en_US.cat"
if [ "$err" -ne 0 ]; then
printf 'gencat does not work.\n'
if [ $force -eq 0 ]; then
printf 'Disabling NLS...\n\n'
nls=0
else
printf 'Forcing NLS...\n\n'
fi
else
printf 'gencat works.\n\n'
# It turns out that POSIX locales are really terrible, and running
# gencat on one machine is not guaranteed to make those cat files
# portable to another machine, so we had better warn the user here.
if [ "$HOSTCC" != "$CC" ] || [ "$OLDHOSTCFLAGS" != "$OLDCFLAGS" ]; then
printf 'Cross-compile detected.\n\n'
printf 'WARNING: Catalog files generated with gencat may not be portable\n'
printf ' across different architectures.\n\n'
fi
if [ -z "$NLSPATH" ]; then
NLSPATH="/usr/share/locale/%L/%N"
fi
install_locales_prereqs=" install_locales"
uninstall_locales_prereqs=" uninstall_locales"
fi
fi
set -e
else
install_locales_prereqs=""
uninstall_locales_prereqs=""
all_locales=0
fi
if [ "$nls" -ne 0 ] && [ "$all_locales" -ne 0 ]; then
install_locales="\$(LOCALE_INSTALL) -l \$(NLSPATH) \$(MAIN_EXEC) \$(DESTDIR)"
else
install_locales="\$(LOCALE_INSTALL) \$(NLSPATH) \$(MAIN_EXEC) \$(DESTDIR)"
fi
# Like the above tested locale support, this tests history.
if [ "$hist" -eq 1 ]; then
set +e
printf 'Testing history...\n'
flags="-DBC_ENABLE_HISTORY=1 -DBC_ENABLED=$bc -DDC_ENABLED=$dc"
flags="$flags -DBC_ENABLE_NLS=$nls -DBC_ENABLE_LIBRARY=0 -DBC_ENABLE_AFL=0"
flags="$flags -DBC_ENABLE_EXTRA_MATH=$extra_math -I./include/"
flags="$flags -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700"
"$CC" $CPPFLAGS $CFLAGS $flags -c "src/history.c" -o "$scriptdir/history.o" > /dev/null 2>&1
err="$?"
rm -rf "$scriptdir/history.o"
# If this errors, it is probably because of building on Windows,
# and history is not supported on Windows, so disable it.
if [ "$err" -ne 0 ]; then
printf 'History does not work.\n'
if [ $force -eq 0 ]; then
printf 'Disabling history...\n\n'
hist=0
else
printf 'Forcing history...\n\n'
fi
else
printf 'History works.\n\n'
fi
set -e
fi
# We have to disable the history tests if it is disabled or valgrind is on.
if [ "$hist" -eq 0 ] || [ "$vg" -ne 0 ]; then
test_bc_history_prereqs=" test_bc_history_skip"
test_dc_history_prereqs=" test_dc_history_skip"
history_tests="@printf 'Skipping history tests...\\\\n'"
else
history_tests="@printf '\$(TEST_STARS)\\\\n\\\\nRunning history tests...\\\\n\\\\n' \&\& tests/history.sh bc -a \&\& tests/history.sh dc -a \&\& printf '\\\\nAll history tests passed.\\\\n\\\\n\$(TEST_STARS)\\\\n'"
fi
# Test OpenBSD. This is not in an if statement because regardless of whatever
# the user says, we need to know if we are on OpenBSD to activate _BSD_SOURCE.
# No, I cannot `#define _BSD_SOURCE` in a header because OpenBSD's patched GCC
# and Clang complain that that is only allowed for system headers. Sigh....So we
# have to check at configure time and set it on the compiler command-line. And
# we have to set it because we also set _POSIX_C_SOURCE, which OpenBSD headers
# detect, and when they detect it, they turn off _BSD_SOURCE unless it is
# specifically requested.
set +e
printf 'Testing for OpenBSD...\n'
flags="-DBC_TEST_OPENBSD -DBC_ENABLE_AFL=0"
"$CC" $CPPFLAGS $CFLAGS $flags -I./include -E "include/status.h" > /dev/null 2>&1
err="$?"
if [ "$err" -ne 0 ]; then
printf 'On OpenBSD. Using _BSD_SOURCE.\n\n'
bsd="-D_BSD_SOURCE"
else
printf 'Not on OpenBSD.\n\n'
bsd=""
fi
if [ "$library" -eq 1 ]; then
bc_lib=""
fi
if [ "$extra_math" -eq 1 ] && [ "$bc" -ne 0 ] && [ "$library" -eq 0 ]; then
BC_LIB2_O="\$(GEN_DIR)/lib2.o"
else
BC_LIB2_O=""
fi
# These lines set the appropriate targets based on whether `gen/strgen.c` or
# `gen/strgen.sh` is used.
GEN="strgen"
GEN_EXEC_TARGET="\$(HOSTCC) \$(HOSTCFLAGS) -o \$(GEN_EXEC) \$(GEN_C)"
CLEAN_PREREQS=" clean_gen clean_coverage"
if [ -z "${GEN_HOST+set}" ]; then
GEN_HOST=1
else
if [ "$GEN_HOST" -eq 0 ]; then
GEN="strgen.sh"
GEN_EXEC_TARGET="@printf 'Do not need to build gen/strgen.c\\\\n'"
CLEAN_PREREQS=" clean_coverage"
fi
fi
manpage_args=""
unneeded=""
headers="\$(HEADERS)"
# This series of if statements figure out what source files are *not* needed.
if [ "$extra_math" -eq 0 ]; then
manpage_args="E"
unneeded="$unneeded rand.c"
else
headers="$headers \$(EXTRA_MATH_HEADERS)"
fi
# All of these next if statements set the build type and mark certain source
# files as unneeded so that they won't have targets generated for them.
if [ "$hist" -eq 0 ]; then
manpage_args="${manpage_args}H"
unneeded="$unneeded history.c"
else
headers="$headers \$(HISTORY_HEADERS)"
fi
if [ "$nls" -eq 0 ]; then
manpage_args="${manpage_args}N"
fi
if [ "$bc" -eq 0 ]; then
unneeded="$unneeded bc.c bc_lex.c bc_parse.c"
else
headers="$headers \$(BC_HEADERS)"
fi
if [ "$dc" -eq 0 ]; then
unneeded="$unneeded dc.c dc_lex.c dc_parse.c"
else
headers="$headers \$(DC_HEADERS)"
fi
if [ "$library" -ne 0 ]; then
unneeded="$unneeded args.c opt.c read.c file.c main.c"
unneeded="$unneeded lang.c lex.c parse.c program.c"
unneeded="$unneeded bc.c bc_lex.c bc_parse.c"
unneeded="$unneeded dc.c dc_lex.c dc_parse.c"
headers="$headers \$(LIBRARY_HEADERS)"
else
unneeded="$unneeded library.c"
fi
# library.c is not needed under normal circumstances.
if [ "$unneeded" = "" ]; then
unneeded="library.c"
fi
# This sets the appropriate manpage for a full build.
if [ "$manpage_args" = "" ]; then
manpage_args="A"
fi
if [ "$vg" -ne 0 ]; then
memcheck=1
fi
if [ "$bc_default_prompt" = "" ]; then
bc_default_prompt="$bc_default_tty_mode"
fi
if [ "$dc_default_prompt" = "" ]; then
dc_default_prompt="$dc_default_tty_mode"
fi
# Generate the test targets and prerequisites.
-bc_tests=$(gen_test_targets bc)
+bc_tests=$(gen_std_test_targets bc)
bc_script_tests=$(gen_script_test_targets bc)
-dc_tests=$(gen_test_targets dc)
+bc_err_tests=$(gen_err_test_targets bc)
+dc_tests=$(gen_std_test_targets dc)
dc_script_tests=$(gen_script_test_targets dc)
+dc_err_tests=$(gen_err_test_targets dc)
# Print out the values; this is for debugging.
if [ "$bc" -ne 0 ]; then
printf 'Building bc\n'
else
printf 'Not building bc\n'
fi
if [ "$dc" -ne 0 ]; then
printf 'Building dc\n'
else
printf 'Not building dc\n'
fi
printf '\n'
printf 'BC_ENABLE_LIBRARY=%s\n\n' "$library"
printf 'BC_ENABLE_HISTORY=%s\n' "$hist"
printf 'BC_ENABLE_EXTRA_MATH=%s\n' "$extra_math"
printf 'BC_ENABLE_NLS=%s\n' "$nls"
printf 'BC_ENABLE_AFL=%s\n' "$fuzz"
printf '\n'
printf 'BC_NUM_KARATSUBA_LEN=%s\n' "$karatsuba_len"
printf '\n'
printf 'CC=%s\n' "$CC"
printf 'CFLAGS=%s\n' "$CFLAGS"
printf 'HOSTCC=%s\n' "$HOSTCC"
printf 'HOSTCFLAGS=%s\n' "$HOSTCFLAGS"
printf 'CPPFLAGS=%s\n' "$CPPFLAGS"
printf 'LDFLAGS=%s\n' "$LDFLAGS"
printf 'PREFIX=%s\n' "$PREFIX"
printf 'BINDIR=%s\n' "$BINDIR"
printf 'INCLUDEDIR=%s\n' "$INCLUDEDIR"
printf 'LIBDIR=%s\n' "$LIBDIR"
printf 'DATAROOTDIR=%s\n' "$DATAROOTDIR"
printf 'DATADIR=%s\n' "$DATADIR"
printf 'MANDIR=%s\n' "$MANDIR"
printf 'MAN1DIR=%s\n' "$MAN1DIR"
printf 'MAN3DIR=%s\n' "$MAN3DIR"
printf 'NLSPATH=%s\n' "$NLSPATH"
printf 'EXECSUFFIX=%s\n' "$EXECSUFFIX"
printf 'EXECPREFIX=%s\n' "$EXECPREFIX"
printf 'DESTDIR=%s\n' "$DESTDIR"
printf 'LONG_BIT=%s\n' "$LONG_BIT"
printf 'GEN_HOST=%s\n' "$GEN_HOST"
printf 'GEN_EMU=%s\n' "$GEN_EMU"
printf '\n'
printf 'Setting Defaults\n'
printf '================\n'
printf 'bc.banner=%s\n' "$bc_default_banner"
printf 'bc.sigint_reset=%s\n' "$bc_default_sigint_reset"
printf 'dc.sigint_reset=%s\n' "$dc_default_sigint_reset"
printf 'bc.tty_mode=%s\n' "$bc_default_tty_mode"
printf 'dc.tty_mode=%s\n' "$dc_default_tty_mode"
printf 'bc.prompt=%s\n' "$bc_default_prompt"
printf 'dc.prompt=%s\n' "$dc_default_prompt"
# This is where the real work begins. This is the point at which the Makefile.in
# template is edited and output to the Makefile.
contents=$(cat "$scriptdir/Makefile.in")
needle="WARNING"
replacement='*** WARNING: Autogenerated from Makefile.in. DO NOT MODIFY ***'
contents=$(replace "$contents" "$needle" "$replacement")
# The contents are edited to have the list of files to build.
contents=$(gen_file_list "$contents" $unneeded)
SRC_TARGETS=""
# This line and loop generates the individual targets for source files. I used
# to just use an implicit target, but that was found to be inadequate when I
# added the library.
src_files=$(find_src_files $unneeded)
for f in $src_files; do
o=$(replace_ext "$f" "c" "o")
SRC_TARGETS=$(printf '%s\n\n%s: %s %s\n\t$(CC) $(CFLAGS) -o %s -c %s\n' \
"$SRC_TARGETS" "$o" "$headers" "$f" "$o" "$f")
done
# Replace all the placeholders.
contents=$(replace "$contents" "HEADERS" "$headers")
contents=$(replace "$contents" "BC_ENABLED" "$bc")
contents=$(replace "$contents" "DC_ENABLED" "$dc")
contents=$(replace "$contents" "BC_ALL_TESTS" "$bc_test")
+contents=$(replace "$contents" "BC_ALL_TESTS_NP" "$bc_test_np")
contents=$(replace "$contents" "BC_TESTS" "$bc_tests")
contents=$(replace "$contents" "BC_SCRIPT_TESTS" "$bc_script_tests")
+contents=$(replace "$contents" "BC_ERROR_TESTS" "$bc_err_tests")
contents=$(replace "$contents" "BC_TEST_EXEC" "$bc_test_exec")
contents=$(replace "$contents" "TIMECONST_ALL_TESTS" "$timeconst")
contents=$(replace "$contents" "DC_ALL_TESTS" "$dc_test")
+contents=$(replace "$contents" "DC_ALL_TESTS_NP" "$dc_test_np")
contents=$(replace "$contents" "DC_TESTS" "$dc_tests")
contents=$(replace "$contents" "DC_SCRIPT_TESTS" "$dc_script_tests")
+contents=$(replace "$contents" "DC_ERROR_TESTS" "$dc_err_tests")
contents=$(replace "$contents" "DC_TEST_EXEC" "$dc_test_exec")
contents=$(replace "$contents" "BUILD_TYPE" "$manpage_args")
contents=$(replace "$contents" "LIBRARY" "$library")
contents=$(replace "$contents" "HISTORY" "$hist")
contents=$(replace "$contents" "EXTRA_MATH" "$extra_math")
contents=$(replace "$contents" "NLS" "$nls")
contents=$(replace "$contents" "FUZZ" "$fuzz")
contents=$(replace "$contents" "MEMCHECK" "$memcheck")
contents=$(replace "$contents" "BC_LIB_O" "$bc_lib")
contents=$(replace "$contents" "BC_HELP_O" "$bc_help")
contents=$(replace "$contents" "DC_HELP_O" "$dc_help")
contents=$(replace "$contents" "BC_LIB2_O" "$BC_LIB2_O")
contents=$(replace "$contents" "KARATSUBA_LEN" "$karatsuba_len")
contents=$(replace "$contents" "NLSPATH" "$NLSPATH")
contents=$(replace "$contents" "DESTDIR" "$destdir")
contents=$(replace "$contents" "EXECSUFFIX" "$EXECSUFFIX")
contents=$(replace "$contents" "EXECPREFIX" "$EXECPREFIX")
contents=$(replace "$contents" "BINDIR" "$BINDIR")
contents=$(replace "$contents" "INCLUDEDIR" "$INCLUDEDIR")
contents=$(replace "$contents" "LIBDIR" "$LIBDIR")
contents=$(replace "$contents" "MAN1DIR" "$MAN1DIR")
contents=$(replace "$contents" "MAN3DIR" "$MAN3DIR")
contents=$(replace "$contents" "CFLAGS" "$CFLAGS")
contents=$(replace "$contents" "HOSTCFLAGS" "$HOSTCFLAGS")
contents=$(replace "$contents" "CPPFLAGS" "$CPPFLAGS")
contents=$(replace "$contents" "LDFLAGS" "$LDFLAGS")
contents=$(replace "$contents" "CC" "$CC")
contents=$(replace "$contents" "HOSTCC" "$HOSTCC")
contents=$(replace "$contents" "COVERAGE_OUTPUT" "$COVERAGE_OUTPUT")
contents=$(replace "$contents" "COVERAGE_PREREQS" "$COVERAGE_PREREQS")
contents=$(replace "$contents" "INSTALL_PREREQS" "$install_prereqs")
contents=$(replace "$contents" "INSTALL_MAN_PREREQS" "$install_man_prereqs")
contents=$(replace "$contents" "INSTALL_LOCALES" "$install_locales")
contents=$(replace "$contents" "INSTALL_LOCALES_PREREQS" "$install_locales_prereqs")
contents=$(replace "$contents" "UNINSTALL_MAN_PREREQS" "$uninstall_man_prereqs")
contents=$(replace "$contents" "UNINSTALL_PREREQS" "$uninstall_prereqs")
contents=$(replace "$contents" "UNINSTALL_LOCALES_PREREQS" "$uninstall_locales_prereqs")
contents=$(replace "$contents" "DEFAULT_TARGET" "$default_target")
contents=$(replace "$contents" "DEFAULT_TARGET_PREREQS" "$default_target_prereqs")
contents=$(replace "$contents" "DEFAULT_TARGET_CMD" "$default_target_cmd")
contents=$(replace "$contents" "SECOND_TARGET" "$second_target")
contents=$(replace "$contents" "SECOND_TARGET_PREREQS" "$second_target_prereqs")
contents=$(replace "$contents" "SECOND_TARGET_CMD" "$second_target_cmd")
contents=$(replace "$contents" "ALL_PREREQ" "$ALL_PREREQ")
contents=$(replace "$contents" "BC_EXEC_PREREQ" "$bc_exec_prereq")
contents=$(replace "$contents" "BC_EXEC_CMD" "$bc_exec_cmd")
contents=$(replace "$contents" "DC_EXEC_PREREQ" "$dc_exec_prereq")
contents=$(replace "$contents" "DC_EXEC_CMD" "$dc_exec_cmd")
contents=$(replace "$contents" "EXECUTABLES" "$executables")
contents=$(replace "$contents" "MAIN_EXEC" "$main_exec")
contents=$(replace "$contents" "EXEC" "$executable")
contents=$(replace "$contents" "TESTS" "$tests")
-contents=$(replace "$contents" "BC_TEST" "$bc_test")
contents=$(replace "$contents" "BC_HISTORY_TEST_PREREQS" "$test_bc_history_prereqs")
-contents=$(replace "$contents" "DC_TEST" "$dc_test")
contents=$(replace "$contents" "DC_HISTORY_TEST_PREREQS" "$test_dc_history_prereqs")
contents=$(replace "$contents" "HISTORY_TESTS" "$history_tests")
contents=$(replace "$contents" "VG_BC_TEST" "$vg_bc_test")
contents=$(replace "$contents" "VG_DC_TEST" "$vg_dc_test")
contents=$(replace "$contents" "TIMECONST" "$timeconst")
contents=$(replace "$contents" "KARATSUBA" "$karatsuba")
contents=$(replace "$contents" "KARATSUBA_TEST" "$karatsuba_test")
contents=$(replace "$contents" "LONG_BIT" "$LONG_BIT")
contents=$(replace "$contents" "LONG_BIT_DEFINE" "$LONG_BIT_DEFINE")
contents=$(replace "$contents" "GEN" "$GEN")
contents=$(replace "$contents" "GEN_EXEC_TARGET" "$GEN_EXEC_TARGET")
contents=$(replace "$contents" "CLEAN_PREREQS" "$CLEAN_PREREQS")
contents=$(replace "$contents" "GEN_EMU" "$GEN_EMU")
contents=$(replace "$contents" "BSD" "$bsd")
contents=$(replace "$contents" "BC_DEFAULT_BANNER" "$bc_default_banner")
contents=$(replace "$contents" "BC_DEFAULT_SIGINT_RESET" "$bc_default_sigint_reset")
contents=$(replace "$contents" "DC_DEFAULT_SIGINT_RESET" "$dc_default_sigint_reset")
contents=$(replace "$contents" "BC_DEFAULT_TTY_MODE" "$bc_default_tty_mode")
contents=$(replace "$contents" "DC_DEFAULT_TTY_MODE" "$dc_default_tty_mode")
contents=$(replace "$contents" "BC_DEFAULT_PROMPT" "$bc_default_prompt")
contents=$(replace "$contents" "DC_DEFAULT_PROMPT" "$dc_default_prompt")
# Do the first print to the Makefile.
printf '%s\n%s\n\n' "$contents" "$SRC_TARGETS" > "$scriptdir/Makefile"
# Generate the individual test targets.
if [ "$bc" -ne 0 ]; then
- gen_tests bc "$extra_math" "$time_tests" $bc_test_exec
+ gen_std_tests bc "$extra_math" "$time_tests" $bc_test_exec
gen_script_tests bc "$extra_math" "$generate_tests" "$time_tests" $bc_test_exec
+ gen_err_tests bc $bc_test_exec
fi
if [ "$dc" -ne 0 ]; then
- gen_tests dc "$extra_math" "$time_tests" $dc_test_exec
+ gen_std_tests dc "$extra_math" "$time_tests" $dc_test_exec
gen_script_tests dc "$extra_math" "$generate_tests" "$time_tests" $dc_test_exec
+ gen_err_tests dc $dc_test_exec
fi
cd "$scriptdir"
# Copy the correct manuals to the expected places.
cp -f manuals/bc/$manpage_args.1.md manuals/bc.1.md
cp -f manuals/bc/$manpage_args.1 manuals/bc.1
cp -f manuals/dc/$manpage_args.1.md manuals/dc.1.md
cp -f manuals/dc/$manpage_args.1 manuals/dc.1
make clean > /dev/null
diff --git a/gen/bc_help.txt b/gen/bc_help.txt
index 50c38ab61314..9ba34c606481 100644
--- a/gen/bc_help.txt
+++ b/gen/bc_help.txt
@@ -1,177 +1,185 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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` or see the online documentation at
https://git.yzena.com/gavin/bc/src/tag/%s/manuals/bc/%s.1.md.
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 or online documentation.
This bc also implements the dot (.) extension of the BSD bc.
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 or online
documentation for more details.
-h --help
Print this usage message and exit.
-i --interactive
Force interactive mode.
+ -L --no-line-length
+
+ Disable line length checking.
+
-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
This bc may load more functions with these options. See the manpage or
online documentation for details.
-P --no-prompt
Disable the prompts in interactive mode.
-R --no-read-prompt
Disable the read prompt in interactive mode.
-r keyword --redefine=keyword
Redefines "keyword" and allows it to be used as a function, variable, and
array name. This is useful when this bc gives parse errors on scripts
meant for other bc implementations.
Only keywords that are not in the POSIX bc spec may be redefined.
It is a fatal error to attempt to redefine a keyword that cannot be
redefined or does not exist.
-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.
+ -z --leading-zeroes
+
+ Enable leading zeroes on numbers greater than -1 and less than 1.
+
Environment variables:
POSIXLY_CORRECT
Error if any non-POSIX extensions are used.
BC_ENV_ARGS
Command-line arguments to use on every run.
BC_LINE_LENGTH
If an integer, the number of characters to print on a line before
- wrapping.
+ wrapping. Using 0 will disable line length checking.
BC_BANNER
If an integer and non-zero, display the copyright banner in interactive
mode.
Overrides the default, which is %s print the banner.
BC_SIGINT_RESET
If an integer and non-zero, reset on SIGINT, rather than exit, when in
interactive mode.
Overrides the default, which is %s.
BC_TTY_MODE
If an integer and non-zero, enable TTY mode when it is available.
Overrides the default, which is TTY mode %s.
BC_PROMPT
If an integer and non-zero, enable prompt when TTY mode is possible.
Overrides the default, which is prompt %s.
diff --git a/gen/dc_help.txt b/gen/dc_help.txt
index c0bf34daeb46..4cf10826cd7f 100644
--- a/gen/dc_help.txt
+++ b/gen/dc_help.txt
@@ -1,136 +1,144 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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` or see the online documentation
at https://git.yzena.com/gavin/bc/src/tag/%s/manuals/bc/%s.1.md.
This dc is (mostly) compatible with the OpenBSD dc and the GNU dc. See the
OpenBSD man page (http://man.openbsd.org/OpenBSD-current/man1/dc.1) 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.
+ -L --no-line-length
+
+ Disable line length checking.
+
-P --no-prompt
Disable the prompts in interactive mode.
-R --no-read-prompt
Disable the read prompt in interactive mode.
-V --version
Print version and copyright and exit.
-x --extended-register
Enable extended register mode.
+ -z --leading-zeroes
+
+ Enable leading zeroes on numbers greater than -1 and less than 1.
+
Environment variables:
DC_ENV_ARGS
Command-line arguments to use on every run.
DC_LINE_LENGTH
If an integer, the number of characters to print on a line before
- wrapping.
+ wrapping. Using 0 will disable line length checking.
DC_SIGINT_RESET
If an integer and non-zero, reset on SIGINT, rather than exit, when in
interactive mode.
Overrides the default, which is %s.
DC_TTY_MODE
If an integer and non-zero, enable TTY mode when it is available.
Overrides the default, which is TTY mode %s.
DC_PROMPT
If an integer and non-zero, enable prompt when TTY mode is possible.
Overrides the default, which is prompt %s.
diff --git a/gen/lib2.bc b/gen/lib2.bc
index 93df1889eb63..23cbec104d02 100644
--- a/gen/lib2.bc
+++ b/gen/lib2.bc
@@ -1,528 +1,564 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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=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>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(scalescale)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(x==0||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=A^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 gcd(a,b){
auto g,s
if(!b)return a
s=scale
scale=0
a=abs(a)$
b=abs(b)$
if(a>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,i
x=abs(x)$
i=2^8
for(p=1;i-1p||(!z&&x==p))n*=2
return n
}
define s2un(x,n){
auto t,u,s
x=x$
if(x<0){
x=abs(x)
s=scale
scale=0
t=n*8
u=2^(t-1)
if(x==u)return x
else if(x>u)x%=u
scale=s
return 2^(t)-x
}
return x
}
define s2u(x){return s2un(x,sbytes(x))}
+define void plz(x){
+ if(leading_zero())print x
+ else{
+ if(x>-1&&x<1&&x!=0){
+ if(x<0)print"-"
+ print 0,abs(x)
+ }
+ else print x
+ }
+}
+define void plznl(x){
+ plz(x)
+ print"\n"
+}
+define void pnlz(x){
+ auto s,i
+ if(leading_zero()){
+ if(x>-1&&x<1&&x!=0){
+ s=scale(x)
+ if(x<0)print"-"
+ print"."
+ x=abs(x)
+ for(i=0;i1)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
for(i=n-1;i>=0;--i){
output_byte(x,i)
if(i)print" "
else print"\n"
}
}
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
}
x=s2un(x,n)
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))}
define bunrev(t){
auto a,s,m[]
s=scale
scale=0
t=abs(t)$
while(t!=1){
t=divmod(t,2,m[])
a*=2
a+=m[0]
}
scale=s
return a
}
define band(a,b){
auto s,t,m[],n[]
a=abs(a)$
b=abs(b)$
if(b>a){
t=b
b=a
a=t
}
s=scale
scale=0
t=1
while(b){
a=divmod(a,2,m[])
b=divmod(b,2,n[])
t*=2
t+=(m[0]&&n[0])
}
scale=s
return bunrev(t)
}
define bor(a,b){
auto s,t,m[],n[]
a=abs(a)$
b=abs(b)$
if(b>a){
t=b
b=a
a=t
}
s=scale
scale=0
t=1
while(b){
a=divmod(a,2,m[])
b=divmod(b,2,n[])
t*=2
t+=(m[0]||n[0])
}
while(a){
a=divmod(a,2,m[])
t*=2
t+=m[0]
}
scale=s
return bunrev(t)
}
define bxor(a,b){
auto s,t,m[],n[]
a=abs(a)$
b=abs(b)$
if(b>a){
t=b
b=a
a=t
}
s=scale
scale=0
t=1
while(b){
a=divmod(a,2,m[])
b=divmod(b,2,n[])
t*=2
t+=(m[0]+n[0]==1)
}
while(a){
a=divmod(a,2,m[])
t*=2
t+=m[0]
}
scale=s
return bunrev(t)
}
define bshl(a,b){return abs(a)$*2^abs(b)$}
define bshr(a,b){return (abs(a)$/2^abs(b)$)$}
define bnotn(x,n){
auto s,t,m[]
s=scale
scale=0
t=2^(abs(n)$*8)
x=abs(x)$%t+t
t=1
while(x!=1){
x=divmod(x,2,m[])
t*=2
t+=!m[0]
}
scale=s
return bunrev(t)
}
define bnot8(x){return bnotn(x,1)}
define bnot16(x){return bnotn(x,2)}
define bnot32(x){return bnotn(x,4)}
define bnot64(x){return bnotn(x,8)}
define bnot(x){return bnotn(x,ubytes(x))}
define brevn(x,n){
auto s,t,m[]
s=scale
scale=0
t=2^(abs(n)$*8)
x=abs(x)$%t+t
scale=s
return bunrev(x)
}
define brev8(x){return brevn(x,1)}
define brev16(x){return brevn(x,2)}
define brev32(x){return brevn(x,4)}
define brev64(x){return brevn(x,8)}
define brev(x){return brevn(x,ubytes(x))}
define broln(x,p,n){
auto s,t,m[]
s=scale
scale=0
n=abs(n)$*8
p=abs(p)$%n
t=2^n
x=abs(x)$%t
if(!p)return x
x=divmod(x,2^(n-p),m[])
x+=m[0]*2^p%t
scale=s
return x
}
define brol8(x,p){return broln(x,p,1)}
define brol16(x,p){return broln(x,p,2)}
define brol32(x,p){return broln(x,p,4)}
define brol64(x,p){return broln(x,p,8)}
define brol(x,p){return broln(x,p,ubytes(x))}
define brorn(x,p,n){
auto s,t,m[]
s=scale
scale=0
n=abs(n)$*8
p=abs(p)$%n
t=2^n
x=abs(x)$%t
if(!p)return x
x=divmod(x,2^p,m[])
x+=m[0]*2^(n-p)%t
scale=s
return x
}
define bror8(x,p){return brorn(x,p,1)}
define bror16(x,p){return brorn(x,p,2)}
define bror32(x,p){return brorn(x,p,4)}
define bror64(x,p){return brorn(x,p,8)}
define brol(x,p){return brorn(x,p,ubytes(x))}
define bmodn(x,n){
auto s
s=scale
scale=0
x=abs(x)$%2^(abs(n)$*8)
scale=s
return x
}
define bmod8(x){return bmodn(x,1)}
define bmod16(x){return bmodn(x,2)}
define bmod32(x){return bmodn(x,4)}
define bmod64(x){return bmodn(x,8)}
diff --git a/include/bc.h b/include/bc.h
index 2b47ea7b7473..3d4a11592875 100644
--- a/include/bc.h
+++ b/include/bc.h
@@ -1,458 +1,458 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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 only.
*
*/
#ifndef BC_BC_H
#define BC_BC_H
#if BC_ENABLED
#include
#include
#include
#include
#include
/**
* The main function for bc. It just sets variables and passes its arguments
* through to @a bc_vm_boot().
*/
void bc_main(int argc, char *argv[]);
// These are references to the help text, the library text, and the "filename"
// for the library.
extern const char bc_help[];
extern const char bc_lib[];
extern const char* bc_lib_name;
// These are references to the second math library and its "filename."
#if BC_ENABLE_EXTRA_MATH
extern const char bc_lib2[];
extern const char* bc_lib2_name;
#endif // BC_ENABLE_EXTRA_MATH
/**
* A struct containing information about a bc keyword.
*/
typedef struct BcLexKeyword {
/// Holds the length of the keyword along with a bit that, if set, means the
/// keyword is used in POSIX bc.
uchar data;
/// The keyword text.
- const char name[9];
+ const char name[14];
} BcLexKeyword;
/// Sets the most significant bit. Used for setting the POSIX bit in
/// BcLexKeyword's data field.
#define BC_LEX_CHAR_MSB(bit) ((bit) << (CHAR_BIT - 1))
/// Returns non-zero if the keyword is POSIX, zero otherwise.
#define BC_LEX_KW_POSIX(kw) ((kw)->data & (BC_LEX_CHAR_MSB(1)))
/// Returns the length of the keyword.
#define BC_LEX_KW_LEN(kw) ((size_t) ((kw)->data & ~(BC_LEX_CHAR_MSB(1))))
/// A macro to easily build a keyword entry. See bc_lex_kws in src/data.c.
#define BC_LEX_KW_ENTRY(a, b, c) \
{ .data = ((b) & ~(BC_LEX_CHAR_MSB(1))) | BC_LEX_CHAR_MSB(c), .name = a }
#if BC_ENABLE_EXTRA_MATH
/// A macro for the number of keywords bc has. This has to be updated if any are
/// added. This is for the redefined_kws field of the BcVm struct.
-#define BC_LEX_NKWS (32)
+#define BC_LEX_NKWS (35)
#else // BC_ENABLE_EXTRA_MATH
/// A macro for the number of keywords bc has. This has to be updated if any are
/// added. This is for the redefined_kws field of the BcVm struct.
-#define BC_LEX_NKWS (28)
+#define BC_LEX_NKWS (31)
#endif // BC_ENABLE_EXTRA_MATH
// The array of keywords and its length.
extern const BcLexKeyword bc_lex_kws[];
extern const size_t bc_lex_kws_len;
/**
* The @a BcLexNext function for bc. (See include/lex.h for a definition of
* @a BcLexNext.)
* @param l The lexer.
*/
void bc_lex_token(BcLex *l);
// The following section is for flags needed when parsing bc code. These flags
// are complicated, but necessary. Why you ask? Because bc's standard is awful.
//
// If you don't believe me, go read the bc Parsing section of the Development
// manual (manuals/development.md). Then come back.
//
// In other words, these flags are the sign declaring, "Here be dragons."
/**
* This returns a pointer to the set of flags at the top of the flag stack.
* @a p is expected to be a BcParse pointer.
* @param p The parser.
* @return A pointer to the top flag set.
*/
#define BC_PARSE_TOP_FLAG_PTR(p) ((uint16_t*) bc_vec_top(&(p)->flags))
/**
* This returns the flag set at the top of the flag stack. @a p is expected to
* be a BcParse pointer.
* @param p The parser.
* @return The top flag set.
*/
#define BC_PARSE_TOP_FLAG(p) (*(BC_PARSE_TOP_FLAG_PTR(p)))
// After this point, all flag #defines are in sets of 2: one to define the flag,
// and one to define a way to grab the flag from the flag set at the top of the
// flag stack. All `p` arguments are pointers to a BcParse.
// This flag is set if the parser has seen a left brace.
#define BC_PARSE_FLAG_BRACE (UINTMAX_C(1)<<0)
#define BC_PARSE_BRACE(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_BRACE)
// This flag is set if the parser is parsing inside of the braces of a function
// body.
#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)
// This flag is set if the parser is parsing a function. It is different from
// the one above because it is set if it is parsing a function body *or* header,
// not just if it's parsing a function body.
#define BC_PARSE_FLAG_FUNC (UINTMAX_C(1)<<2)
#define BC_PARSE_FUNC(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_FUNC)
// This flag is set if the parser is expecting to parse a body, whether of a
// function, an if statement, or a loop.
#define BC_PARSE_FLAG_BODY (UINTMAX_C(1)<<3)
#define BC_PARSE_BODY(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_BODY)
// This flag is set if bc is parsing a loop. This is important because the break
// and continue keywords are only valid inside of a loop.
#define BC_PARSE_FLAG_LOOP (UINTMAX_C(1)<<4)
#define BC_PARSE_LOOP(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_LOOP)
// This flag is set if bc is parsing the body of a loop. It is different from
// the one above the same way @a BC_PARSE_FLAG_FUNC_INNER is different from
// @a BC_PARSE_FLAG_FUNC.
#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)
// This flag is set if bc is parsing an if statement.
#define BC_PARSE_FLAG_IF (UINTMAX_C(1)<<6)
#define BC_PARSE_IF(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_IF)
// This flag is set if bc is parsing an else statement. This is important
// because of "else if" constructions, among other things.
#define BC_PARSE_FLAG_ELSE (UINTMAX_C(1)<<7)
#define BC_PARSE_ELSE(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_ELSE)
// This flag is set if bc just finished parsing an if statement and its body.
// It tells the parser that it can probably expect an else statement next. This
// flag is, thus, one of the most subtle.
#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)
/**
* This returns true if bc is in a state where it should not execute any code
* at all.
* @param p The parser.
* @return True if execution cannot proceed, false otherwise.
*/
#define BC_PARSE_NO_EXEC(p) ((p)->flags.len != 1 || BC_PARSE_TOP_FLAG(p) != 0)
/**
* This returns true if the token @a t is a statement delimiter, which is
* either a newline or a semicolon.
* @param t The token to check.
* @return True if t is a statement delimiter token; false otherwise.
*/
#define BC_PARSE_DELIMITER(t) \
((t) == BC_LEX_SCOLON || (t) == BC_LEX_NLINE || (t) == BC_LEX_EOF)
/**
* This is poorly named, but it basically returns whether or not the current
* state is valid for the end of an else statement.
* @param f The flag set to be checked.
* @return True if the state is valid for the end of an else statement.
*/
#define BC_PARSE_BLOCK_STMT(f) \
((f) & (BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_LOOP_INNER))
/**
* This returns the value of the data for an operator with precedence @a p and
* associativity @a l (true if left associative, false otherwise). This is used
* to construct an array of operators, bc_parse_ops, in src/data.c.
* @param p The precedence.
* @param l True if the operator is left associative, false otherwise.
* @return The data for the operator.
*/
#define BC_PARSE_OP(p, l) (((p) & ~(BC_LEX_CHAR_MSB(1))) | (BC_LEX_CHAR_MSB(l)))
/**
* Returns the operator data for the lex token @a t.
* @param t The token to return operator data for.
* @return The operator data for @a t.
*/
#define BC_PARSE_OP_DATA(t) bc_parse_ops[((t) - BC_LEX_OP_INC)]
/**
* Returns non-zero if operator @a op is left associative, zero otherwise.
* @param op The operator to test for associativity.
* @return Non-zero if the operator is left associative, zero otherwise.
*/
#define BC_PARSE_OP_LEFT(op) (BC_PARSE_OP_DATA(op) & BC_LEX_CHAR_MSB(1))
/**
* Returns the precedence of operator @a op. Lower number means higher
* precedence.
* @param op The operator to return the precedence of.
* @return The precedence of @a op.
*/
#define BC_PARSE_OP_PREC(op) (BC_PARSE_OP_DATA(op) & ~(BC_LEX_CHAR_MSB(1)))
/**
* A macro to easily define a series of bits for whether a lex token is an
* expression token or not. It takes 8 expression bits, corresponding to the 8
* bits in a uint8_t. You can see this in use for bc_parse_exprs in src/data.c.
* @param e1 The first bit.
* @param e2 The second bit.
* @param e3 The third bit.
* @param e4 The fourth bit.
* @param e5 The fifth bit.
* @param e6 The sixth bit.
* @param e7 The seventh bit.
* @param e8 The eighth bit.
* @return An expression entry for bc_parse_exprs[].
*/
#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))
/**
* Returns true if token @a i is a token that belongs in an expression.
* @param i The token to test.
* @return True if i is an expression token, false otherwise.
*/
#define BC_PARSE_EXPR(i) \
(bc_parse_exprs[(((i) & (uchar) ~(0x07)) >> 3)] & (1 << (7 - ((i) & 0x07))))
/**
* Returns the operator (by lex token) that is at the top of the operator
* stack.
* @param p The parser.
* @return The operator that is at the top of the operator stack, as a lex
* token.
*/
#define BC_PARSE_TOP_OP(p) (*((BcLexType*) bc_vec_top(&(p)->ops)))
/**
* Returns true if bc has a "leaf" token. A "leaf" token is one that can stand
* alone in an expression. For example, a number by itself can be an expression,
* but a binary operator, while valid for an expression, cannot be alone in the
* expression. It must have an expression to the left and right of itself. See
* the documentation for @a bc_parse_expr_err() in src/bc_parse.c.
* @param prev The previous token as an instruction.
* @param bin_last True if that last operator was a binary operator, false
* otherwise.
* @param rparen True if the last operator was a right paren.
* return True if the last token was a leaf token, false otherwise.
*/
#define BC_PARSE_LEAF(prev, bin_last, rparen) \
(!(bin_last) && ((rparen) || bc_parse_inst_isLeaf(prev)))
/**
* This returns true if the token @a t should be treated as though it's a
* variable. This goes for actual variables, array elements, and globals.
* @param t The token to test.
* @return True if @a t should be treated as though it's a variable, false
* otherwise.
*/
#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
/**
* Returns true if the previous token @a p (in the form of a bytecode
* instruction) is a prefix operator. The fact that it is for bytecode
* instructions is what makes it different from @a BC_PARSE_OP_PREFIX below.
* @param p The previous token.
* @return True if @a p is a prefix operator.
*/
#define BC_PARSE_PREV_PREFIX(p) ((p) >= BC_INST_NEG && (p) <= BC_INST_BOOL_NOT)
/**
* Returns true if token @a t is a prefix operator.
* @param t The token to test.
* @return True if @a t is a prefix operator, false otherwise.
*/
#define BC_PARSE_OP_PREFIX(t) ((t) == BC_LEX_OP_BOOL_NOT || (t) == BC_LEX_NEG)
/**
* We can calculate the conversion between tokens and bytecode instructions by
* subtracting the position of the first operator in the lex enum and adding the
* position of the first in the instruction enum. Note: This only works for
* binary operators.
* @param t The token to turn into an instruction.
* @return The token as an instruction.
*/
#define BC_PARSE_TOKEN_INST(t) ((uchar) ((t) - BC_LEX_NEG + BC_INST_NEG))
/**
* Returns true if the token is a bc keyword.
* @param t The token to check.
* @return True if @a t is a bc keyword, false otherwise.
*/
#define BC_PARSE_IS_KEYWORD(t) ((t) >= BC_LEX_KW_AUTO && (t) <= BC_LEX_KW_ELSE)
/// A struct that holds data about what tokens should be expected next. There
/// are a few instances of these, all named because they are used in specific
/// cases. Basically, in certain situations, it's useful to use the same code,
/// but have a list of valid tokens.
///
/// Obviously, @a len is the number of tokens in the @a tokens array. If more
/// than 4 is needed in the future, @a tokens will have to be changed.
typedef struct BcParseNext {
/// The number of tokens in the tokens array.
uchar len;
/// The tokens that can be expected next.
uchar tokens[4];
} BcParseNext;
/// A macro to construct an array literal of tokens from a parameter list.
#define BC_PARSE_NEXT_TOKENS(...) .tokens = { __VA_ARGS__ }
/// A macro to generate a BcParseNext literal from BcParseNext data. See
/// src/data.c for examples.
#define BC_PARSE_NEXT(a, ...) \
{ .len = (uchar) (a), BC_PARSE_NEXT_TOKENS(__VA_ARGS__) }
/// A status returned by @a bc_parse_expr_err(). It can either return success or
/// an error indicating an empty expression.
typedef enum BcParseStatus {
BC_PARSE_STATUS_SUCCESS,
BC_PARSE_STATUS_EMPTY_EXPR,
} BcParseStatus;
/**
* The @a BcParseExpr function for bc. (See include/parse.h for a definition of
* @a BcParseExpr.)
* @param p The parser.
* @param flags Flags that define the requirements that the parsed code must
* meet or an error will result. See @a BcParseExpr for more info.
*/
void bc_parse_expr(BcParse *p, uint8_t flags);
/**
* The @a BcParseParse function for bc. (See include/parse.h for a definition of
* @a BcParseParse.)
* @param p The parser.
*/
void bc_parse_parse(BcParse *p);
/// References to the signal message and its length.
extern const char bc_sig_msg[];
extern const uchar bc_sig_msg_len;
/// A reference to an array of bits that are set if the corresponding lex token
/// is valid in an expression.
extern const uint8_t bc_parse_exprs[];
/// A reference to an array of bc operators.
extern const uchar bc_parse_ops[];
// References to the various instances of BcParseNext's.
/// A reference to what tokens are valid as next tokens when parsing normal
/// expressions. More accurately. these are the tokens that are valid for
/// *ending* the expression.
extern const BcParseNext bc_parse_next_expr;
/// A reference to what tokens are valid as next tokens when parsing function
/// parameters (well, actually arguments).
extern const BcParseNext bc_parse_next_arg;
/// A reference to what tokens are valid as next tokens when parsing a print
/// statement.
extern const BcParseNext bc_parse_next_print;
/// A reference to what tokens are valid as next tokens when parsing things like
/// loop headers and builtin functions where the only thing expected is a right
/// paren.
///
/// The name is an artifact of history, and is related to @a BC_PARSE_REL (see
/// include/parse.h). It refers to how POSIX only allows some operators as part
/// of the conditional of for loops, while loops, and if statements.
extern const BcParseNext bc_parse_next_rel;
// What tokens are valid as next tokens when parsing an array element
// expression.
extern const BcParseNext bc_parse_next_elem;
/// A reference to what tokens are valid as next tokens when parsing the first
/// two parts of a for loop header.
extern const BcParseNext bc_parse_next_for;
/// A reference to what tokens are valid as next tokens when parsing a read
/// expression.
extern const BcParseNext bc_parse_next_read;
/// A reference to what tokens are valid as next tokens when parsing a builtin
/// function with multiple arguments.
extern const BcParseNext bc_parse_next_builtin;
#else // BC_ENABLED
// If bc is not enabled, execution is always possible because dc has strict
// rules that ensure execution can always proceed safely.
#define BC_PARSE_NO_EXEC(p) (0)
#endif // BC_ENABLED
#endif // BC_BC_H
diff --git a/include/bcl.h b/include/bcl.h
index 833592c4bff0..9c0e5e59cfd0 100644
--- a/include/bcl.h
+++ b/include/bcl.h
@@ -1,239 +1,242 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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 public header for the bc library.
*
*/
#ifndef BC_BCL_H
#define BC_BCL_H
#ifdef _WIN32
#include
#include
#include
#include
#endif // _WIN32
#include
#include
#include
#include
#include
// Windows has deprecated isatty() and the rest of these. Or doesn't have them.
// So these are just fixes for Windows.
#ifdef _WIN32
// This one is special. Windows did not like me defining an
// inline function that was not given a definition in a header
// file. This suppresses that by making inline functions non-inline.
#define inline
#define restrict __restrict
#define strdup _strdup
#define write(f, b, s) _write((f), (b), (unsigned int) (s))
#define read(f, b, s) _read((f), (b), (unsigned int) (s))
#define close _close
-#define open(f, n, m) _sopen_s(f, n, m, _SH_DENYNO, _S_IREAD | _S_IWRITE)
+#define open(f, n, m) \
+ _sopen_s((f), (n), (m) | _O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE)
#define sigjmp_buf jmp_buf
#define sigsetjmp(j, s) setjmp(j)
#define siglongjmp longjmp
#define isatty _isatty
#define STDIN_FILENO _fileno(stdin)
#define STDOUT_FILENO _fileno(stdout)
#define STDERR_FILENO _fileno(stderr)
#define ssize_t SSIZE_T
#define S_ISDIR(m) ((m) & _S_IFDIR)
#define O_RDONLY _O_RDONLY
#define stat _stat
#define fstat _fstat
#define BC_FILE_SEP '\\'
#else // _WIN32
#define BC_FILE_SEP '/'
#endif // _WIN32
#define BCL_SEED_ULONGS (4)
#define BCL_SEED_SIZE (sizeof(long) * BCL_SEED_ULONGS)
// 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
// For more information about the items here, see the either the
// manuals/bcl.3.md or manuals/bcl.3 manuals.
// BclBigDig is a fixed-size integer type that bcl can convert numbers to.
//
// BclRandInt is the type of fixed-size integer natively returned by the
// pseudo-random number generator.
#if BC_LONG_BIT >= 64
typedef uint64_t BclBigDig;
typedef uint64_t BclRandInt;
#elif BC_LONG_BIT >= 32
typedef uint32_t BclBigDig;
typedef uint32_t BclRandInt;
#else
#error BC_LONG_BIT must be at least 32
#endif // BC_LONG_BIT >= 64
#ifndef BC_ENABLE_LIBRARY
#define BC_ENABLE_LIBRARY (1)
#endif // BC_ENABLE_LIBRARY
#if BC_ENABLE_LIBRARY
typedef enum BclError {
BCL_ERROR_NONE,
BCL_ERROR_INVALID_NUM,
BCL_ERROR_INVALID_CONTEXT,
BCL_ERROR_SIGNAL,
BCL_ERROR_MATH_NEGATIVE,
BCL_ERROR_MATH_NON_INTEGER,
BCL_ERROR_MATH_OVERFLOW,
BCL_ERROR_MATH_DIVIDE_BY_ZERO,
BCL_ERROR_PARSE_INVALID_STR,
BCL_ERROR_FATAL_ALLOC_ERR,
BCL_ERROR_FATAL_UNKNOWN_ERR,
BCL_ERROR_NELEMS,
} BclError;
typedef struct BclNumber {
size_t i;
} BclNumber;
struct BclCtxt;
typedef struct BclCtxt* BclContext;
void bcl_handleSignal(void);
bool bcl_running(void);
BclError bcl_init(void);
void bcl_free(void);
bool bcl_abortOnFatalError(void);
void bcl_setAbortOnFatalError(bool abrt);
+bool bcl_leadingZeroes(void);
+void bcl_setLeadingZeroes(bool leadingZeroes);
void bcl_gc(void);
BclError bcl_pushContext(BclContext ctxt);
void bcl_popContext(void);
BclContext bcl_context(void);
BclContext bcl_ctxt_create(void);
void bcl_ctxt_free(BclContext ctxt);
void bcl_ctxt_freeNums(BclContext ctxt);
size_t bcl_ctxt_scale(BclContext ctxt);
void bcl_ctxt_setScale(BclContext ctxt, size_t scale);
size_t bcl_ctxt_ibase(BclContext ctxt);
void bcl_ctxt_setIbase(BclContext ctxt, size_t ibase);
size_t bcl_ctxt_obase(BclContext ctxt);
void bcl_ctxt_setObase(BclContext ctxt, size_t obase);
BclError bcl_err(BclNumber n);
BclNumber bcl_num_create(void);
void bcl_num_free(BclNumber n);
bool bcl_num_neg(BclNumber n);
void bcl_num_setNeg(BclNumber n, bool neg);
size_t bcl_num_scale(BclNumber n);
BclError bcl_num_setScale(BclNumber n, size_t scale);
size_t bcl_num_len(BclNumber n);
BclError bcl_copy(BclNumber d, BclNumber s);
BclNumber bcl_dup(BclNumber s);
BclError bcl_bigdig(BclNumber n, BclBigDig *result);
BclNumber bcl_bigdig2num(BclBigDig val);
BclNumber bcl_add(BclNumber a, BclNumber b);
BclNumber bcl_sub(BclNumber a, BclNumber b);
BclNumber bcl_mul(BclNumber a, BclNumber b);
BclNumber bcl_div(BclNumber a, BclNumber b);
BclNumber bcl_mod(BclNumber a, BclNumber b);
BclNumber bcl_pow(BclNumber a, BclNumber b);
BclNumber bcl_lshift(BclNumber a, BclNumber b);
BclNumber bcl_rshift(BclNumber a, BclNumber b);
BclNumber bcl_sqrt(BclNumber a);
BclError bcl_divmod(BclNumber a, BclNumber b, BclNumber *c, BclNumber *d);
BclNumber bcl_modexp(BclNumber a, BclNumber b, BclNumber c);
ssize_t bcl_cmp(BclNumber a, BclNumber b);
void bcl_zero(BclNumber n);
void bcl_one(BclNumber n);
BclNumber bcl_parse(const char *restrict val);
char* bcl_string(BclNumber n);
BclNumber bcl_irand(BclNumber a);
BclNumber bcl_frand(size_t places);
BclNumber bcl_ifrand(BclNumber a, size_t places);
BclError bcl_rand_seedWithNum(BclNumber n);
BclError bcl_rand_seed(unsigned char seed[BCL_SEED_SIZE]);
void bcl_rand_reseed(void);
BclNumber bcl_rand_seed2num(void);
BclRandInt bcl_rand_int(void);
BclRandInt bcl_rand_bounded(BclRandInt bound);
#endif // BC_ENABLE_LIBRARY
#endif // BC_BCL_H
diff --git a/include/history.h b/include/history.h
index 3a2cf82b7943..8d9c3417d897 100644
--- a/include/history.h
+++ b/include/history.h
@@ -1,334 +1,338 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
* Copyright (c) 2010-2013, Pieter Noordhuis
*
* 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
#include
#include
#include
#ifndef _WIN32
#include
#include
#include
#include
#else // _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include
#include
#include
#define strncasecmp _strnicmp
#define strcasecmp _stricmp
#endif // _WIN32
#include
#include
#include
#if BC_DEBUG_CODE
#include
#endif // BC_DEBUG_CODE
/// Default columns.
#define BC_HIST_DEF_COLS (80)
/// Max number of history entries.
#define BC_HIST_MAX_LEN (128)
/// Max length of a line.
#define BC_HIST_MAX_LINE (4095)
/// Max size for cursor position buffer.
#define BC_HIST_SEQ_SIZE (64)
/**
* The number of entries in the history.
* @param h The history data.
*/
#define BC_HIST_BUF_LEN(h) ((h)->buf.len - 1)
/**
* Read n characters into s and check the error.
* @param s The buffer to read into.
* @param n The number of bytes to read.
* @return True if there was an error, false otherwise.
*/
#define BC_HIST_READ(s, n) (bc_history_read((s), (n)) == -1)
/// Markers for direction when using arrow keys.
#define BC_HIST_NEXT (false)
#define BC_HIST_PREV (true)
#if BC_DEBUG_CODE
// These are just for debugging.
#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
/// An enum of useful actions. To understand what these mean, check terminal
/// emulators for their shortcuts or the VT100 codes.
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_S = 19,
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_CTRL_BSLASH = 28,
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;
/// Any material printed without a trailing newline.
BcVec extras;
/// Prompt to display.
const char *prompt;
/// Prompt length.
size_t plen;
/// 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;
#ifndef _WIN32
/// The original terminal state.
struct termios orig_termios;
#else // _WIN32
- DWORD orig_console_mode;
+ /// The original input console mode.
+ DWORD orig_in;
+
+ /// The original output console mode.
+ DWORD orig_out;
#endif // _WIN32
/// These next two are here because pahole found a 4 byte hole here.
/// Whether we are in rawmode.
bool rawMode;
/// Whether the terminal is bad.
bool badTerm;
#ifndef _WIN32
/// 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;
#endif // _WIN32
} BcHistory;
/**
* Get a line from stdin using history. This returns a status because I don't
* want to throw errors while the terminal is in raw mode.
* @param h The history data.
* @param vec A vector to put the line into.
* @param prompt The prompt to display, if desired.
* @return A status indicating an error, if any. Returning a status here
* is better because if we throw an error out of history, we
* leave the terminal in raw mode or in some other half-baked
* state.
*/
BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt);
/**
* Initialize history data.
* @param h The struct to initialize.
*/
void bc_history_init(BcHistory *h);
/**
* Free history data (and recook the terminal).
* @param h The struct to free.
*/
void bc_history_free(BcHistory *h);
/**
* Frees strings used by history.
* @param str The string to free.
*/
void bc_history_string_free(void *str);
// A list of terminals that don't work.
extern const char *bc_history_bad_terms[];
// A tab in history and its length.
extern const char bc_history_tab[];
extern const size_t bc_history_tab_len;
// A ctrl+c string.
extern const char bc_history_ctrlc[];
// UTF-8 data arrays.
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
// Debug data.
extern BcFile bc_history_debug_fp;
extern char *bc_history_debug_buf;
/**
* A function to print keycodes for debugging.
* @param h The history data.
*/
void bc_history_printKeyCodes(BcHistory* h);
#endif // BC_DEBUG_CODE
#endif // BC_ENABLE_HISTORY
#endif // BC_HISTORY_H
diff --git a/include/lang.h b/include/lang.h
index 5a678ed34a25..705aca35df1c 100644
--- a/include/lang.h
+++ b/include/lang.h
@@ -1,687 +1,700 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
#include
#include
#include
/// The instructions for bytecode.
typedef enum BcInst {
#if BC_ENABLED
/// Postfix increment and decrement. Prefix are translated into
/// BC_INST_ONE with either BC_INST_ASSIGN_PLUS or BC_INST_ASSIGN_MINUS.
BC_INST_INC = 0,
BC_INST_DEC,
#endif // BC_ENABLED
/// Unary negation.
BC_INST_NEG,
/// Boolean not.
BC_INST_BOOL_NOT,
#if BC_ENABLE_EXTRA_MATH
/// Truncation operator.
BC_INST_TRUNC,
#endif // BC_ENABLE_EXTRA_MATH
/// These should be self-explanatory.
BC_INST_POWER,
BC_INST_MULTIPLY,
BC_INST_DIVIDE,
BC_INST_MODULUS,
BC_INST_PLUS,
BC_INST_MINUS,
#if BC_ENABLE_EXTRA_MATH
/// Places operator.
BC_INST_PLACES,
/// Shift operators.
BC_INST_LSHIFT,
BC_INST_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
/// Comparison operators.
BC_INST_REL_EQ,
BC_INST_REL_LE,
BC_INST_REL_GE,
BC_INST_REL_NE,
BC_INST_REL_LT,
BC_INST_REL_GT,
/// Boolean or and and.
BC_INST_BOOL_OR,
BC_INST_BOOL_AND,
#if BC_ENABLED
/// Same as the normal operators, but assigment. So ^=, *=, /=, etc.
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
/// Places and shift assignment operators.
BC_INST_ASSIGN_PLACES,
BC_INST_ASSIGN_LSHIFT,
BC_INST_ASSIGN_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
/// Normal assignment.
BC_INST_ASSIGN,
/// bc and dc detect when the value from an assignment is not necessary.
/// For example, a plain assignment statement means the value is never used.
/// In those cases, we can get lots of performance back by not even creating
/// a copy at all. In fact, it saves a copy, a push onto the results stack,
/// a pop from the results stack, and a free. Definitely worth it to detect.
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
/// Same as above.
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
/// Normal assignment that pushes no value on the stack.
BC_INST_ASSIGN_NO_VAL,
/// Push a constant onto the results stack.
BC_INST_NUM,
/// Push a variable onto the results stack.
BC_INST_VAR,
/// Push an array element onto the results stack.
BC_INST_ARRAY_ELEM,
/// Push an array onto the results stack. This is different from pushing an
/// array *element* onto the results stack; it pushes a reference to the
/// whole array. This is needed in bc for function arguments that are
/// arrays. It is also needed for returning the length of an array.
BC_INST_ARRAY,
/// Push a zero or a one onto the stack. These are special cased because it
/// does help performance, particularly for one since inc/dec operators
/// use it.
BC_INST_ZERO,
BC_INST_ONE,
#if BC_ENABLED
/// Push the last printed value onto the stack.
BC_INST_LAST,
#endif // BC_ENABLED
/// Push the value of any of the globals onto the stack.
BC_INST_IBASE,
BC_INST_OBASE,
BC_INST_SCALE,
#if BC_ENABLE_EXTRA_MATH
/// Push the value of the seed global onto the stack.
BC_INST_SEED,
#endif // BC_ENABLE_EXTRA_MATH
/// These are builtin functions.
BC_INST_LENGTH,
BC_INST_SCALE_FUNC,
BC_INST_SQRT,
BC_INST_ABS,
#if BC_ENABLE_EXTRA_MATH
/// Another builtin function.
BC_INST_IRAND,
#endif // BC_ENABLE_EXTRA_MATH
/// Asciify.
BC_INST_ASCIIFY,
/// Another builtin function.
BC_INST_READ,
#if BC_ENABLE_EXTRA_MATH
/// Another builtin function.
BC_INST_RAND,
#endif // BC_ENABLE_EXTRA_MATH
/// Return the max for the various globals.
BC_INST_MAXIBASE,
BC_INST_MAXOBASE,
BC_INST_MAXSCALE,
#if BC_ENABLE_EXTRA_MATH
/// Return the max value returned by rand().
BC_INST_MAXRAND,
#endif // BC_ENABLE_EXTRA_MATH
+ /// bc line_length() builtin function.
+ BC_INST_LINE_LENGTH,
+
+#if BC_ENABLED
+
+ /// bc global_stacks() builtin function.
+ BC_INST_GLOBAL_STACKS,
+
+#endif // BC_ENABLED
+
+ /// bc leading_zero() builtin function.
+ BC_INST_LEADING_ZERO,
+
/// This is slightly misnamed versus BC_INST_PRINT_POP. Well, it is in bc.
/// dc uses this instruction to print, but not pop. That's valid in dc.
/// However, in bc, it is *never* valid to print without popping. In bc,
/// BC_INST_PRINT_POP is used to indicate when a string should be printed
/// because of a print statement or whether it should be printed raw. The
/// reason for this is because a print statement handles escaped characters.
/// So BC_INST_PRINT_POP is for printing a string from a print statement,
/// BC_INST_PRINT_STR is for printing a string by itself.
///
/// In dc, BC_INST_PRINT_POP prints and pops, and BC_INST_PRINT just prints.
///
/// Oh, and BC_INST_STR pushes a string onto the results stack.
BC_INST_PRINT,
BC_INST_PRINT_POP,
BC_INST_STR,
#if BC_ENABLED
BC_INST_PRINT_STR,
/// Jumps unconditionally.
BC_INST_JUMP,
/// Jumps if the top of the results stack is zero (condition failed). It
/// turns out that we only want to jump when conditions fail to "skip" code.
BC_INST_JUMP_ZERO,
/// Call a function.
BC_INST_CALL,
/// Return the top of the stack to the caller.
BC_INST_RET,
/// Return 0 to the caller.
BC_INST_RET0,
/// Special return instruction for void functions.
BC_INST_RET_VOID,
/// Special halt instruction.
BC_INST_HALT,
#endif // BC_ENABLED
/// Pop an item off of the results stack.
BC_INST_POP,
/// Swaps the top two items on the results stack.
BC_INST_SWAP,
/// Modular exponentiation.
BC_INST_MODEXP,
/// Do divide and modulus at the same time.
BC_INST_DIVMOD,
/// Turns a number into a string and prints it.
BC_INST_PRINT_STREAM,
#if DC_ENABLED
/// dc's return; it pops an executing string off of the stack.
BC_INST_POP_EXEC,
/// Unconditionally execute a string.
BC_INST_EXECUTE,
/// Conditionally execute a string.
BC_INST_EXEC_COND,
/// Prints each item on the results stack, separated by newlines.
BC_INST_PRINT_STACK,
/// Pops everything off of the results stack.
BC_INST_CLEAR_STACK,
/// Pushes the current length of a register stack onto the results stack.
BC_INST_REG_STACK_LEN,
/// Pushes the current length of the results stack onto the results stack.
BC_INST_STACK_LEN,
/// Pushes a copy of the item on the top of the results stack onto the
/// results stack.
BC_INST_DUPLICATE,
/// Copies the value in a register and pushes the copy onto the results
/// stack.
BC_INST_LOAD,
/// Pops an item off of a register stack and pushes it onto the results
/// stack.
BC_INST_PUSH_VAR,
/// Pops an item off of the results stack and pushes it onto a register's
/// stack.
BC_INST_PUSH_TO_VAR,
/// Quit.
BC_INST_QUIT,
/// Quit executing some number of strings.
BC_INST_NQUIT,
/// Push the depth of the execution stack onto the stack.
BC_INST_EXEC_STACK_LEN,
#endif // DC_ENABLED
/// Invalid instruction.
BC_INST_INVALID,
} BcInst;
/// Used by maps to identify where items are in the array.
typedef struct BcId {
/// The name of the item.
char *name;
/// The index into the array where the item is.
size_t idx;
} BcId;
/// The location of a var, array, or array element.
typedef struct BcLoc {
/// The index of the var or array.
size_t loc;
/// The index of the array element. Only used for array elements.
size_t idx;
} BcLoc;
/// An entry for a constant.
typedef struct BcConst {
/// The original string as parsed from the source code.
char *val;
/// The last base that the constant was parsed in.
BcBigDig base;
/// The parsed constant.
BcNum num;
} BcConst;
/// A function. This is also used in dc, not just bc. The reason is that strings
/// are executed in dc, and they are converted to functions in order to be
/// executed.
typedef struct BcFunc {
/// The bytecode instructions.
BcVec code;
#if BC_ENABLED
/// The labels. This is a vector of indices. The index is the index into
/// the bytecode vector where the label is.
BcVec labels;
/// The autos for the function. The first items are the parameters, and the
/// arguments to the parameters must match the types in this vector.
BcVec autos;
/// The number of parameters the function takes.
size_t nparams;
#endif // BC_ENABLED
/// The strings encountered in the function.
BcVec strs;
/// The constants encountered in the function.
BcVec consts;
/// The function's name.
const char *name;
#if BC_ENABLED
/// True if the function is a void function.
bool voidfn;
#endif // BC_ENABLED
} BcFunc;
/// Types of results that can be pushed onto the results stack.
typedef enum BcResultType {
/// Result is a variable.
BC_RESULT_VAR,
/// Result is an array element.
BC_RESULT_ARRAY_ELEM,
/// Result is an array. This is only allowed for function arguments or
/// returning the length of the array.
BC_RESULT_ARRAY,
/// Result is a string.
BC_RESULT_STR,
/// Result is a temporary. This is used for the result of almost all
/// expressions.
BC_RESULT_TEMP,
/// Special casing the two below gave performance improvements.
/// Result is a 0.
BC_RESULT_ZERO,
/// Result is a 1. Useful for inc/dec operators.
BC_RESULT_ONE,
#if BC_ENABLED
/// Result is the special "last" variable.
BC_RESULT_LAST,
/// Result is the return value of a void function.
BC_RESULT_VOID,
#endif // BC_ENABLED
/// Result is the value of ibase.
BC_RESULT_IBASE,
/// Result is the value of obase.
BC_RESULT_OBASE,
/// Result is the value of scale.
BC_RESULT_SCALE,
#if BC_ENABLE_EXTRA_MATH
/// Result is the value of seed.
BC_RESULT_SEED,
#endif // BC_ENABLE_EXTRA_MATH
} BcResultType;
/// A union to store data for various result types.
typedef union BcResultData {
/// A number. Strings are stored here too; they are numbers with
/// cap == 0 && num == NULL. The string's index into the strings vector is
/// stored in the scale field. But this is only used for strings stored in
/// variables.
BcNum n;
/// A vector.
BcVec v;
/// A variable, array, or array element reference. This could also be a
/// string if a string is not stored in a variable (dc only).
BcLoc loc;
} BcResultData;
/// A tagged union for results.
typedef struct BcResult {
/// The tag. The type of the result.
BcResultType t;
/// The data. The data for the result.
BcResultData d;
} BcResult;
/// An instruction pointer. This is how bc knows where in the bytecode vector,
/// and which function, the current execution is.
typedef struct BcInstPtr {
/// The index of the currently executing function in the fns vector.
size_t func;
/// The index into the bytecode vector of the *next* instruction.
size_t idx;
/// The length of the results vector when this function started executing.
/// This is mostly used for bc where functions should not affect the results
/// of their callers.
size_t len;
} BcInstPtr;
/// Types of identifiers.
typedef enum BcType {
/// Variable.
BC_TYPE_VAR,
/// Array.
BC_TYPE_ARRAY,
#if BC_ENABLED
/// Array reference.
BC_TYPE_REF,
#endif // BC_ENABLED
} BcType;
#if BC_ENABLED
/// An auto variable in bc.
typedef struct BcAuto {
/// The index of the variable in the vars or arrs vectors.
size_t idx;
/// The type of the variable.
BcType type;
} BcAuto;
#endif // BC_ENABLED
/// Forward declaration.
struct BcProgram;
/**
* Initializes a function.
* @param f The function to initialize.
* @param name The name of the function. The string is assumed to be owned by
* some other entity.
*/
void bc_func_init(BcFunc *f, const char* name);
/**
* Inserts an auto into the function.
* @param f The function to insert into.
* @param p The program. This is to search for the variable or array name.
* @param name The name of the auto to insert.
* @param type The type of the auto.
* @param line The line in the source code where the insert happened. This is
* solely for error reporting.
*/
void bc_func_insert(BcFunc *f, struct BcProgram* p, char* name,
BcType type, size_t line);
/**
* Resets a function in preparation for it to be reused. This can happen in bc
* because it is a dynamic language and functions can be redefined.
* @param f The functio to reset.
*/
void bc_func_reset(BcFunc *f);
#ifndef NDEBUG
/**
* Frees a function. This is a destructor. This is only used in debug builds
* because all functions are freed at exit. We free them in debug builds to
* check for memory leaks.
* @param func The function to free as a void pointer.
*/
void bc_func_free(void *func);
#endif // NDEBUG
/**
* Initializes an array, which is the array type in bc and dc source code. Since
* variables and arrays are both arrays (see the development manual,
* manuals/development.md#execution, for more information), the @a nums
* parameter tells bc whether to initialize an array of numbers or an array of
* arrays of numbers. If the latter, it does a recursive call with nums set to
* true.
* @param a The array to initialize.
* @param nums True if the array should be for numbers, false if it should be
* for vectors.
*/
void bc_array_init(BcVec *a, bool nums);
/**
* Copies an array to another array. This is used to do pass arrays to functions
* that do not take references to arrays. The arrays are passed entirely by
* value, which means that they need to be copied.
* @param d The destination array.
* @param s The source array.
*/
void bc_array_copy(BcVec *d, const BcVec *s);
/**
* Frees a string stored in a function. This is a destructor.
* @param string The string to free as a void pointer.
*/
void bc_string_free(void *string);
/**
* Frees a constant stored in a function. This is a destructor.
* @param constant The constant to free as a void pointer.
*/
void bc_const_free(void *constant);
/**
* Clears a result. It sets the type to BC_RESULT_TEMP and clears the union by
* clearing the BcNum in the union. This is to ensure that bc does not use
* uninitialized data.
* @param r The result to clear.
*/
void bc_result_clear(BcResult *r);
/**
* Copies a result into another. This is done for things like duplicating the
* top of the results stack or copying the result of an assignment to put back
* on the results stack.
* @param d The destination result.
* @param src The source result.
*/
void bc_result_copy(BcResult *d, BcResult *src);
/**
* Frees a result. This is a destructor.
* @param result The result to free as a void pointer.
*/
void bc_result_free(void *result);
/**
* Expands an array to @a len. This can happen because in bc, you do not have to
* explicitly initialize elements of an array. If you access an element that is
* not initialized, the array is expanded to fit it, and all missing elements
* are initialized to 0 if they are numbers, or arrays with one element of 0.
* This function does that expansion.
* @param a The array to expand.
* @param len The length to expand to.
*/
void bc_array_expand(BcVec *a, size_t len);
/**
* Compare two BcId's and return the result. Since they are just comparing the
* names in the BcId, I return the result from strcmp() exactly. This is used by
* maps in their binary search.
* @param e1 The first id.
* @param e2 The second id.
* @return The result of strcmp() on the BcId's names.
*/
int bc_id_cmp(const BcId *e1, const BcId *e2);
#if BC_ENABLED
/**
* Returns non-zero if the bytecode instruction i is an assignment instruction.
* @param i The instruction to test.
* @return Non-zero if i is an assignment instruction, zero otherwise.
*/
#define BC_INST_IS_ASSIGN(i) \
((i) == BC_INST_ASSIGN || (i) == BC_INST_ASSIGN_NO_VAL)
/**
* Returns true if the bytecode instruction @a i requires the value to be
* returned for use.
* @param i The instruction to test.
* @return True if @a i requires the value to be returned for use, false
* otherwise.
*/
#define BC_INST_USE_VAL(i) ((i) <= BC_INST_ASSIGN)
#else // BC_ENABLED
/**
* Returns non-zero if the bytecode instruction i is an assignment instruction.
* @param i The instruction to test.
* @return Non-zero if i is an assignment instruction, zero otherwise.
*/
#define BC_INST_IS_ASSIGN(i) ((i) == BC_INST_ASSIGN_NO_VAL)
/**
* Returns true if the bytecode instruction @a i requires the value to be
* returned for use.
* @param i The instruction to test.
* @return True if @a i requires the value to be returned for use, false
* otherwise.
*/
#define BC_INST_USE_VAL(i) (false)
#endif // BC_ENABLED
#if BC_DEBUG_CODE
/// Reference to string names for all of the instructions. For debugging.
extern const char* bc_inst_names[];
#endif // BC_DEBUG_CODE
/// References to the names of the main and read functions.
extern const char bc_func_main[];
extern const char bc_func_read[];
#endif // BC_LANG_H
diff --git a/include/lex.h b/include/lex.h
index 0b556894cec7..0e7af1742001 100644
--- a/include/lex.h
+++ b/include/lex.h
@@ -1,573 +1,586 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
#include
#include
#include
#include
// Two convencience macros for throwing errors in lex code. They take care of
// plumbing like passing in the current line the lexer is on.
#define bc_lex_err(l, e) (bc_vm_handleError((e), (l)->line))
#define bc_lex_verr(l, e, ...) (bc_vm_handleError((e), (l)->line, __VA_ARGS__))
// BC_LEX_NEG_CHAR returns the char that corresponds to negative for the
// current calculator.
//
// BC_LEX_LAST_NUM_CHAR returns the char that corresponds to the last valid
// char for numbers. In bc and dc, capital letters are part of numbers, to a
// point. (dc only goes up to hex, so its last valid char is 'F'.)
#if BC_ENABLED
#if DC_ENABLED
#define BC_LEX_NEG_CHAR (BC_IS_BC ? '-' : '_')
#define BC_LEX_LAST_NUM_CHAR (BC_IS_BC ? 'Z' : 'F')
#else // DC_ENABLED
#define BC_LEX_NEG_CHAR ('-')
#define BC_LEX_LAST_NUM_CHAR ('Z')
#endif // DC_ENABLED
#else // BC_ENABLED
#define BC_LEX_NEG_CHAR ('_')
#define BC_LEX_LAST_NUM_CHAR ('F')
#endif // BC_ENABLED
/**
* Returns true if c is a valid number character.
* @param c The char to check.
* @param pt If a decimal point has already been seen.
* @param int_only True if the number is expected to be an int only, false if
* non-integers are allowed.
* @return True if @a c is a valid number character.
*/
#define BC_LEX_NUM_CHAR(c, pt, int_only) \
(isdigit(c) != 0 || ((c) >= 'A' && (c) <= BC_LEX_LAST_NUM_CHAR) || \
((c) == '.' && !(pt) && !(int_only)))
/// An enum of lex token types.
typedef enum BcLexType {
/// End of file.
BC_LEX_EOF,
/// Marker for invalid tokens, used by bc and dc for const data.
BC_LEX_INVALID,
#if BC_ENABLED
/// Increment operator.
BC_LEX_OP_INC,
/// Decrement operator.
BC_LEX_OP_DEC,
#endif // BC_ENABLED
/// BC_LEX_NEG is not used in lexing; it is only for parsing. The lexer
/// marks all '-' characters as BC_LEX_OP_MINUS, but the parser needs to be
/// able to distinguish them.
BC_LEX_NEG,
/// Boolean not.
BC_LEX_OP_BOOL_NOT,
#if BC_ENABLE_EXTRA_MATH
/// Truncation operator.
BC_LEX_OP_TRUNC,
#endif // BC_ENABLE_EXTRA_MATH
/// Power operator.
BC_LEX_OP_POWER,
/// Multiplication operator.
BC_LEX_OP_MULTIPLY,
/// Division operator.
BC_LEX_OP_DIVIDE,
/// Modulus operator.
BC_LEX_OP_MODULUS,
/// Addition operator.
BC_LEX_OP_PLUS,
/// Subtraction operator.
BC_LEX_OP_MINUS,
#if BC_ENABLE_EXTRA_MATH
/// Places (truncate or extend) operator.
BC_LEX_OP_PLACES,
/// Left (decimal) shift operator.
BC_LEX_OP_LSHIFT,
/// Right (decimal) shift operator.
BC_LEX_OP_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
/// Equal operator.
BC_LEX_OP_REL_EQ,
/// Less than or equal operator.
BC_LEX_OP_REL_LE,
/// Greater than or equal operator.
BC_LEX_OP_REL_GE,
/// Not equal operator.
BC_LEX_OP_REL_NE,
/// Less than operator.
BC_LEX_OP_REL_LT,
/// Greater than operator.
BC_LEX_OP_REL_GT,
/// Boolean or operator.
BC_LEX_OP_BOOL_OR,
/// Boolean and operator.
BC_LEX_OP_BOOL_AND,
#if BC_ENABLED
/// Power assignment operator.
BC_LEX_OP_ASSIGN_POWER,
/// Multiplication assignment operator.
BC_LEX_OP_ASSIGN_MULTIPLY,
/// Division assignment operator.
BC_LEX_OP_ASSIGN_DIVIDE,
/// Modulus assignment operator.
BC_LEX_OP_ASSIGN_MODULUS,
/// Addition assignment operator.
BC_LEX_OP_ASSIGN_PLUS,
/// Subtraction assignment operator.
BC_LEX_OP_ASSIGN_MINUS,
#if BC_ENABLE_EXTRA_MATH
/// Places (truncate or extend) assignment operator.
BC_LEX_OP_ASSIGN_PLACES,
/// Left (decimal) shift assignment operator.
BC_LEX_OP_ASSIGN_LSHIFT,
/// Right (decimal) shift assignment operator.
BC_LEX_OP_ASSIGN_RSHIFT,
#endif // BC_ENABLE_EXTRA_MATH
#endif // BC_ENABLED
/// Assignment operator.
BC_LEX_OP_ASSIGN,
/// Newline.
BC_LEX_NLINE,
/// Whitespace.
BC_LEX_WHITESPACE,
/// Left parenthesis.
BC_LEX_LPAREN,
/// Right parenthesis.
BC_LEX_RPAREN,
/// Left bracket.
BC_LEX_LBRACKET,
/// Comma.
BC_LEX_COMMA,
/// Right bracket.
BC_LEX_RBRACKET,
/// Left brace.
BC_LEX_LBRACE,
/// Semicolon.
BC_LEX_SCOLON,
/// Right brace.
BC_LEX_RBRACE,
/// String.
BC_LEX_STR,
/// Identifier/name.
BC_LEX_NAME,
/// Constant number.
BC_LEX_NUMBER,
// These keywords are in the order they are in for a reason. Don't change
// the order unless you want a bunch of weird failures in the test suite.
// In fact, almost all of these tokens are in a specific order for a reason.
#if BC_ENABLED
/// bc auto keyword.
BC_LEX_KW_AUTO,
/// bc break keyword.
BC_LEX_KW_BREAK,
/// bc continue keyword.
BC_LEX_KW_CONTINUE,
/// bc define keyword.
BC_LEX_KW_DEFINE,
/// bc for keyword.
BC_LEX_KW_FOR,
/// bc if keyword.
BC_LEX_KW_IF,
/// bc limits keyword.
BC_LEX_KW_LIMITS,
/// bc return keyword.
BC_LEX_KW_RETURN,
/// bc while keyword.
BC_LEX_KW_WHILE,
/// bc halt keyword.
BC_LEX_KW_HALT,
/// bc last keyword.
BC_LEX_KW_LAST,
#endif // BC_ENABLED
/// bc ibase keyword.
BC_LEX_KW_IBASE,
/// bc obase keyword.
BC_LEX_KW_OBASE,
/// bc scale keyword.
BC_LEX_KW_SCALE,
#if BC_ENABLE_EXTRA_MATH
/// bc seed keyword.
BC_LEX_KW_SEED,
#endif // BC_ENABLE_EXTRA_MATH
/// bc length keyword.
BC_LEX_KW_LENGTH,
/// bc print keyword.
BC_LEX_KW_PRINT,
/// bc sqrt keyword.
BC_LEX_KW_SQRT,
/// bc abs keyword.
BC_LEX_KW_ABS,
#if BC_ENABLE_EXTRA_MATH
/// bc irand keyword.
BC_LEX_KW_IRAND,
#endif // BC_ENABLE_EXTRA_MATH
/// bc asciffy keyword.
BC_LEX_KW_ASCIIFY,
/// bc modexp keyword.
BC_LEX_KW_MODEXP,
/// bc divmod keyword.
BC_LEX_KW_DIVMOD,
/// bc quit keyword.
BC_LEX_KW_QUIT,
/// bc read keyword.
BC_LEX_KW_READ,
#if BC_ENABLE_EXTRA_MATH
/// bc rand keyword.
BC_LEX_KW_RAND,
#endif // BC_ENABLE_EXTRA_MATH
/// bc maxibase keyword.
BC_LEX_KW_MAXIBASE,
/// bc maxobase keyword.
BC_LEX_KW_MAXOBASE,
/// bc maxscale keyword.
BC_LEX_KW_MAXSCALE,
#if BC_ENABLE_EXTRA_MATH
/// bc maxrand keyword.
BC_LEX_KW_MAXRAND,
#endif // BC_ENABLE_EXTRA_MATH
+ /// bc line_length keyword.
+ BC_LEX_KW_LINE_LENGTH,
+
+#if BC_ENABLED
+
+ /// bc global_stacks keyword.
+ BC_LEX_KW_GLOBAL_STACKS,
+
+#endif // BC_ENABLED
+
+ /// bc leading_zero keyword.
+ BC_LEX_KW_LEADING_ZERO,
+
/// bc stream keyword.
BC_LEX_KW_STREAM,
/// bc else keyword.
BC_LEX_KW_ELSE,
#if DC_ENABLED
/// A special token for dc to calculate equal without a register.
BC_LEX_EQ_NO_REG,
/// Colon (array) operator.
BC_LEX_COLON,
/// Execute command.
BC_LEX_EXECUTE,
/// Print stack command.
BC_LEX_PRINT_STACK,
/// Clear stack command.
BC_LEX_CLEAR_STACK,
/// Register stack level command.
BC_LEX_REG_STACK_LEVEL,
/// Main stack level command.
BC_LEX_STACK_LEVEL,
/// Duplicate command.
BC_LEX_DUPLICATE,
/// Swap (reverse) command.
BC_LEX_SWAP,
/// Pop (remove) command.
BC_LEX_POP,
/// Store ibase command.
BC_LEX_STORE_IBASE,
/// Store obase command.
BC_LEX_STORE_OBASE,
/// Store scale command.
BC_LEX_STORE_SCALE,
#if BC_ENABLE_EXTRA_MATH
/// Store seed command.
BC_LEX_STORE_SEED,
#endif // BC_ENABLE_EXTRA_MATH
/// Load variable onto stack command.
BC_LEX_LOAD,
/// Pop off of variable stack onto results stack command.
BC_LEX_LOAD_POP,
/// Push onto variable stack command.
BC_LEX_STORE_PUSH,
/// Print with pop command.
BC_LEX_PRINT_POP,
/// Parameterized quit command.
BC_LEX_NQUIT,
/// Execution stack depth command.
BC_LEX_EXEC_STACK_LENGTH,
/// Scale of number command. This is needed specifically for dc because bc
/// parses the scale function in parts.
BC_LEX_SCALE_FACTOR,
/// Array length command. This is needed specifically for dc because bc
/// just reuses its length keyword.
BC_LEX_ARRAY_LENGTH,
#endif // DC_ENABLED
} BcLexType;
struct BcLex;
/**
* A function pointer to call when another token is needed. Mostly called by the
* parser.
* @param l The lexer.
*/
typedef void (*BcLexNext)(struct BcLex* l);
/// The lexer.
typedef struct BcLex {
/// A pointer to the text to lex.
const char *buf;
/// The current index into buf.
size_t i;
/// The current line.
size_t line;
/// The length of buf.
size_t len;
/// The current token.
BcLexType t;
/// The previous token.
BcLexType last;
/// A string to store extra data for tokens. For example, the @a BC_LEX_STR
/// token really needs to store the actual string, and numbers also need the
/// string.
BcVec str;
/// If this is true, the lexer is processing stdin and can ask for more data
/// if a string or comment are not properly terminated.
bool is_stdin;
} BcLex;
/**
* Initializes a lexer.
* @param l The lexer to initialize.
*/
void bc_lex_init(BcLex *l);
/**
* Frees a lexer. This is not guarded by #ifndef NDEBUG because a separate
* parser is created at runtime to parse read() expressions and dc strings, and
* that parser needs a lexer.
* @param l The lexer to free.
*/
void bc_lex_free(BcLex *l);
/**
* Sets the filename that the lexer will be lexing.
* @param l The lexer.
* @param file The filename that the lexer will lex.
*/
void bc_lex_file(BcLex *l, const char *file);
/**
* Sets the text the lexer will lex.
* @param l The lexer.
* @param text The text to lex.
* @param is_stdin True if the text is from stdin, false otherwise.
*/
void bc_lex_text(BcLex *l, const char *text, bool is_stdin);
/**
* Generic next function for the parser to call. It takes care of calling the
* correct @a BcLexNext function and consuming whitespace.
* @param l The lexer.
*/
void bc_lex_next(BcLex *l);
/**
* Lexes a line comment (one beginning with '#' and going to a newline).
* @param l The lexer.
*/
void bc_lex_lineComment(BcLex *l);
/**
* Lexes a general comment (C-style comment).
* @param l The lexer.
*/
void bc_lex_comment(BcLex *l);
/**
* Lexes whitespace, finding as much as possible.
* @param l The lexer.
*/
void bc_lex_whitespace(BcLex *l);
/**
* Lexes a number that begins with char @a start. This takes care of parsing
* numbers in scientific and engineering notations.
* @param l The lexer.
* @param start The starting char of the number. To detect a number and call
* this function, the lexer had to eat the first char. It fixes
* that by passing it in.
*/
void bc_lex_number(BcLex *l, char start);
/**
* Lexes a name/identifier.
* @param l The lexer.
*/
void bc_lex_name(BcLex *l);
/**
* Lexes common whitespace characters.
* @param l The lexer.
* @param c The character to lex.
*/
void bc_lex_commonTokens(BcLex *l, char c);
/**
* Throws a parse error because char @a c was invalid.
* @param l The lexer.
* @param c The problem character.
*/
void bc_lex_invalidChar(BcLex *l, char c);
/**
* Reads a line from stdin and puts it into the lexer's buffer.
* @param l The lexer.
*/
bool bc_lex_readLine(BcLex *l);
#endif // BC_LEX_H
diff --git a/include/program.h b/include/program.h
index 83c0c754b8f4..3f90f2b9f552 100644
--- a/include/program.h
+++ b/include/program.h
@@ -1,955 +1,971 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
#include
#include
#include
#include
#include
#include
/// The index of ibase in the globals array.
#define BC_PROG_GLOBALS_IBASE (0)
/// The index of obase in the globals array.
#define BC_PROG_GLOBALS_OBASE (1)
/// The index of scale in the globals array.
#define BC_PROG_GLOBALS_SCALE (2)
#if BC_ENABLE_EXTRA_MATH
/// The index of the rand max in the maxes array.
#define BC_PROG_MAX_RAND (3)
#endif // BC_ENABLE_EXTRA_MATH
/// The length of the globals array.
#define BC_PROG_GLOBALS_LEN (3 + BC_ENABLE_EXTRA_MATH)
typedef struct BcProgram {
/// The array of globals values.
BcBigDig globals[BC_PROG_GLOBALS_LEN];
/// The array of globals stacks.
BcVec globals_v[BC_PROG_GLOBALS_LEN];
#if BC_ENABLE_EXTRA_MATH
/// The pseudo-random number generator.
BcRNG rng;
#endif // BC_ENABLE_EXTRA_MATH
/// The results stack.
BcVec results;
/// The execution stack.
BcVec stack;
/// A pointer to the current function's constants.
BcVec *consts;
/// A pointer to the current function's strings.
BcVec *strs;
/// The array of functions.
BcVec fns;
/// The map of functions to go with fns.
BcVec fn_map;
/// The array of variables.
BcVec vars;
/// The map of variables to go with vars.
BcVec var_map;
/// The array of arrays.
BcVec arrs;
/// The map of arrays to go with arrs.
BcVec arr_map;
#if DC_ENABLED
/// A vector of tail calls. These are just integers, which are the number of
/// tail calls that have been executed for each function (string) on the
/// stack for dc. This is to prevent dc from constantly growing memory use
/// because of pushing more and more string executions on the stack.
BcVec tail_calls;
#endif // DC_ENABLED
/// A BcNum that has the proper base for asciify.
BcNum strmb;
#if BC_ENABLED
/// The last printed value for bc.
BcNum last;
#endif // BC_ENABLED
// The BcDig array for strmb. 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];
} BcProgram;
/**
* Returns true if the stack @a s has at least @a n items, false otherwise.
* @param s The stack to check.
* @param n The number of items the stack must have.
* @return True if @a s has at least @a n items, false otherwise.
*/
#define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) (n)))
/**
* Get a pointer to the top value in a global value stack.
* @param v The global value stack.
* @return A pointer to the top value in @a v.
*/
#define BC_PROG_GLOBAL_PTR(v) (bc_vec_top(v))
/**
* Get the top value in a global value stack.
* @param v The global value stack.
* @return The top value in @a v.
*/
#define BC_PROG_GLOBAL(v) (*((BcBigDig*) BC_PROG_GLOBAL_PTR(v)))
/**
* Returns the current value of ibase.
* @param p The program.
* @return The current ibase.
*/
#define BC_PROG_IBASE(p) ((p)->globals[BC_PROG_GLOBALS_IBASE])
/**
* Returns the current value of obase.
* @param p The program.
* @return The current obase.
*/
#define BC_PROG_OBASE(p) ((p)->globals[BC_PROG_GLOBALS_OBASE])
/**
* Returns the current value of scale.
* @param p The program.
* @return The current scale.
*/
#define BC_PROG_SCALE(p) ((p)->globals[BC_PROG_GLOBALS_SCALE])
/// The index for the main function in the functions array.//
#define BC_PROG_MAIN (0)
/// The index for the read function in the functions array.
#define BC_PROG_READ (1)
/**
* Retires (completes the execution of) an instruction. Some instructions
* require special retirement, but most can use this. This basically pops the
* operands while preserving the result (which we assumed was pushed before the
* actual operation).
* @param p The program.
* @param nres The number of results returned by the instruction.
* @param nops The number of operands used by the instruction.
*/
#define bc_program_retire(p, nres, nops) \
(bc_vec_npopAt(&(p)->results, (nops), (p)->results.len - (nres + nops)))
#if DC_ENABLED
/// A constant that tells how many functions are required in dc.
#define BC_PROG_REQ_FUNCS (2)
#if !BC_ENABLED
/// This define disappears the parameter last because 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
/// This define disappears pop and copy because for bc, 'pop' and 'copy' are
/// always false.
#define bc_program_pushVar(p, code, bgn, pop, copy) \
bc_program_pushVar(p, code, bgn)
// In debug mode, we want bc to check the stack, but otherwise, we don't because
// the bc language implicitly mandates that the stack should always have enough
// items.
#ifdef NDEBUG
#define BC_PROG_NO_STACK_CHECK
#endif // NDEBUG
#endif // DC_ENABLED
/**
* Returns true if the BcNum @a n is acting as a string.
* @param n The BcNum to test.
* @return True if @a n is acting as a string, false otherwise.
*/
#define BC_PROG_STR(n) ((n)->num == NULL && !(n)->cap)
#if BC_ENABLED
/**
* Returns true if the result @a r and @a n is a number.
* @param r The result.
* @param n The number corresponding to the result.
* @return True if the result holds a number, false otherwise.
*/
#define BC_PROG_NUM(r, n) \
((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
#else // BC_ENABLED
/**
* Returns true if the result @a r and @a n is a number.
* @param r The result.
* @param n The number corresponding to the result.
* @return True if the result holds a number, false otherwise.
*/
#define BC_PROG_NUM(r, n) ((r)->t != BC_RESULT_STR && !BC_PROG_STR(n))
#endif // BC_ENABLED
/**
* This is a function type for unary operations. Currently, these include
* boolean not, negation, and truncation with extra math.
* @param r The BcResult to store the result into.
* @param n The parameter to the unary operation.
*/
typedef void (*BcProgramUnary)(BcResult *r, BcNum *n);
/**
* Initializes the BcProgram.
* @param p The program to initialize.
*/
void bc_program_init(BcProgram *p);
#ifndef NDEBUG
/**
* Frees a BcProgram. This is only used in debug builds because a BcProgram is
* only freed on program exit, and we don't care about freeing resources on
* exit.
* @param p The program to initialize.
*/
void bc_program_free(BcProgram *p);
#endif // NDEBUG
#if BC_DEBUG_CODE
#if BC_ENABLED && DC_ENABLED
/**
* Prints the bytecode in a function. This is a debug-only function.
* @param p The program.
*/
void bc_program_code(const BcProgram *p);
/**
* Prints an instruction. This is a debug-only function.
* @param p The program.
* @param code The bytecode array.
* @param bgn A pointer to the current index. It is also updated to the next
* index.
*/
void bc_program_printInst(const BcProgram *p, const char *code,
size_t *restrict bgn);
/**
* Prints the stack. This is a debug-only function.
* @param p The program.
*/
void bc_program_printStackDebug(BcProgram* p);
#endif // BC_ENABLED && DC_ENABLED
#endif // BC_DEBUG_CODE
/**
* Returns the index of the variable or array in their respective arrays.
* @param p The program.
* @param id The BcId of the variable or array.
* @param var True if the search should be for a variable, false for an array.
* @return The index of the variable or array in the correct array.
*/
size_t bc_program_search(BcProgram *p, const char* id, bool var);
/**
* Adds a string to a function and returns the string's index in the function.
* @param p The program.
* @param str The string to add.
* @param fidx The index of the function to add to.
*/
size_t bc_program_addString(BcProgram *p, const char *str, size_t fidx);
/**
* Inserts a function into the program and returns the index of the function in
* the fns array.
* @param p The program.
* @param name The name of the function.
* @return The index of the function after insertion.
*/
size_t bc_program_insertFunc(BcProgram *p, const char *name);
/**
* Resets a program, usually because of resetting after an error.
* @param p The program to reset.
*/
void bc_program_reset(BcProgram *p);
/**
* Executes bc or dc code in the BcProgram.
* @param p The program.
*/
void bc_program_exec(BcProgram *p);
/**
* Negates a copy of a BcNum. This is a BcProgramUnary function.
* @param r The BcResult to store the result into.
* @param n The parameter to the unary operation.
*/
void bc_program_negate(BcResult *r, BcNum *n);
/**
* Returns a boolean not of a BcNum. This is a BcProgramUnary function.
* @param r The BcResult to store the result into.
* @param n The parameter to the unary operation.
*/
void bc_program_not(BcResult *r, BcNum *n);
#if BC_ENABLE_EXTRA_MATH
/**
* Truncates a copy of a BcNum. This is a BcProgramUnary function.
* @param r The BcResult to store the result into.
* @param n The parameter to the unary operation.
*/
void bc_program_trunc(BcResult *r, BcNum *n);
#endif // BC_ENABLE_EXTRA_MATH
/// A reference to an array of binary operator functions.
extern const BcNumBinaryOp bc_program_ops[];
/// A reference to an array of binary operator allocation request functions.
extern const BcNumBinaryOpReq bc_program_opReqs[];
/// A reference to an array of unary operator functions.
extern const BcProgramUnary bc_program_unarys[];
/// A reference to a filename for command-line expressions.
extern const char bc_program_exprs_name[];
/// A reference to a filename for stdin.
extern const char bc_program_stdin_name[];
/// A reference to the ready message printed on SIGINT.
extern const char bc_program_ready_msg[];
/// A reference to the length of the ready message.
extern const size_t bc_program_ready_msg_len;
/// A reference to an array of escape characters for the print statement.
extern const char bc_program_esc_chars[];
/// A reference to an array of the characters corresponding to the escape
/// characters in bc_program_esc_chars.
extern const char bc_program_esc_seqs[];
#if BC_HAS_COMPUTED_GOTO
#if BC_DEBUG_CODE
#define BC_PROG_JUMP(inst, code, ip) \
do { \
inst = (uchar) (code)[(ip)->idx++]; \
bc_file_printf(&vm.ferr, "inst: %s\n", bc_inst_names[inst]); \
bc_file_flush(&vm.ferr, bc_flush_none); \
goto *bc_program_inst_lbls[inst]; \
} while (0)
#else // BC_DEBUG_CODE
#define BC_PROG_JUMP(inst, code, ip) \
do { \
inst = (uchar) (code)[(ip)->idx++]; \
goto *bc_program_inst_lbls[inst]; \
} while (0)
#endif // BC_DEBUG_CODE
#define BC_PROG_DIRECT_JUMP(l) goto lbl_ ## l;
#define BC_PROG_LBL(l) lbl_ ## l
#define BC_PROG_FALLTHROUGH
#if BC_C11
#define BC_PROG_LBLS_SIZE (sizeof(bc_program_inst_lbls) / sizeof(void*))
#define BC_PROG_LBLS_ASSERT \
static_assert(BC_PROG_LBLS_SIZE == BC_INST_INVALID + 1,\
"bc_program_inst_lbls[] mismatches the instructions")
#else // BC_C11
#define BC_PROG_LBLS_ASSERT
#endif // BC_C11
#if BC_ENABLED
#if DC_ENABLED
#if BC_ENABLE_EXTRA_MATH
#define BC_PROG_LBLS static const void* const bc_program_inst_lbls[] = { \
&&lbl_BC_INST_INC, \
&&lbl_BC_INST_DEC, \
&&lbl_BC_INST_NEG, \
&&lbl_BC_INST_BOOL_NOT, \
&&lbl_BC_INST_TRUNC, \
&&lbl_BC_INST_POWER, \
&&lbl_BC_INST_MULTIPLY, \
&&lbl_BC_INST_DIVIDE, \
&&lbl_BC_INST_MODULUS, \
&&lbl_BC_INST_PLUS, \
&&lbl_BC_INST_MINUS, \
&&lbl_BC_INST_PLACES, \
&&lbl_BC_INST_LSHIFT, \
&&lbl_BC_INST_RSHIFT, \
&&lbl_BC_INST_REL_EQ, \
&&lbl_BC_INST_REL_LE, \
&&lbl_BC_INST_REL_GE, \
&&lbl_BC_INST_REL_NE, \
&&lbl_BC_INST_REL_LT, \
&&lbl_BC_INST_REL_GT, \
&&lbl_BC_INST_BOOL_OR, \
&&lbl_BC_INST_BOOL_AND, \
&&lbl_BC_INST_ASSIGN_POWER, \
&&lbl_BC_INST_ASSIGN_MULTIPLY, \
&&lbl_BC_INST_ASSIGN_DIVIDE, \
&&lbl_BC_INST_ASSIGN_MODULUS, \
&&lbl_BC_INST_ASSIGN_PLUS, \
&&lbl_BC_INST_ASSIGN_MINUS, \
&&lbl_BC_INST_ASSIGN_PLACES, \
&&lbl_BC_INST_ASSIGN_LSHIFT, \
&&lbl_BC_INST_ASSIGN_RSHIFT, \
&&lbl_BC_INST_ASSIGN, \
&&lbl_BC_INST_ASSIGN_POWER_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MULTIPLY_NO_VAL, \
&&lbl_BC_INST_ASSIGN_DIVIDE_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MODULUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_PLUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MINUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_PLACES_NO_VAL, \
&&lbl_BC_INST_ASSIGN_LSHIFT_NO_VAL, \
&&lbl_BC_INST_ASSIGN_RSHIFT_NO_VAL, \
&&lbl_BC_INST_ASSIGN_NO_VAL, \
&&lbl_BC_INST_NUM, \
&&lbl_BC_INST_VAR, \
&&lbl_BC_INST_ARRAY_ELEM, \
&&lbl_BC_INST_ARRAY, \
&&lbl_BC_INST_ZERO, \
&&lbl_BC_INST_ONE, \
&&lbl_BC_INST_LAST, \
&&lbl_BC_INST_IBASE, \
&&lbl_BC_INST_OBASE, \
&&lbl_BC_INST_SCALE, \
&&lbl_BC_INST_SEED, \
&&lbl_BC_INST_LENGTH, \
&&lbl_BC_INST_SCALE_FUNC, \
&&lbl_BC_INST_SQRT, \
&&lbl_BC_INST_ABS, \
&&lbl_BC_INST_IRAND, \
&&lbl_BC_INST_ASCIIFY, \
&&lbl_BC_INST_READ, \
&&lbl_BC_INST_RAND, \
&&lbl_BC_INST_MAXIBASE, \
&&lbl_BC_INST_MAXOBASE, \
&&lbl_BC_INST_MAXSCALE, \
&&lbl_BC_INST_MAXRAND, \
+ &&lbl_BC_INST_LINE_LENGTH, \
+ &&lbl_BC_INST_GLOBAL_STACKS, \
+ &&lbl_BC_INST_LEADING_ZERO, \
&&lbl_BC_INST_PRINT, \
&&lbl_BC_INST_PRINT_POP, \
&&lbl_BC_INST_STR, \
&&lbl_BC_INST_PRINT_STR, \
&&lbl_BC_INST_JUMP, \
&&lbl_BC_INST_JUMP_ZERO, \
&&lbl_BC_INST_CALL, \
&&lbl_BC_INST_RET, \
&&lbl_BC_INST_RET0, \
&&lbl_BC_INST_RET_VOID, \
&&lbl_BC_INST_HALT, \
&&lbl_BC_INST_POP, \
&&lbl_BC_INST_SWAP, \
&&lbl_BC_INST_MODEXP, \
&&lbl_BC_INST_DIVMOD, \
&&lbl_BC_INST_PRINT_STREAM, \
&&lbl_BC_INST_POP_EXEC, \
&&lbl_BC_INST_EXECUTE, \
&&lbl_BC_INST_EXEC_COND, \
&&lbl_BC_INST_PRINT_STACK, \
&&lbl_BC_INST_CLEAR_STACK, \
&&lbl_BC_INST_REG_STACK_LEN, \
&&lbl_BC_INST_STACK_LEN, \
&&lbl_BC_INST_DUPLICATE, \
&&lbl_BC_INST_LOAD, \
&&lbl_BC_INST_PUSH_VAR, \
&&lbl_BC_INST_PUSH_TO_VAR, \
&&lbl_BC_INST_QUIT, \
&&lbl_BC_INST_NQUIT, \
&&lbl_BC_INST_EXEC_STACK_LEN, \
&&lbl_BC_INST_INVALID, \
}
#else // BC_ENABLE_EXTRA_MATH
#define BC_PROG_LBLS static const void* const bc_program_inst_lbls[] = { \
&&lbl_BC_INST_INC, \
&&lbl_BC_INST_DEC, \
&&lbl_BC_INST_NEG, \
&&lbl_BC_INST_BOOL_NOT, \
&&lbl_BC_INST_POWER, \
&&lbl_BC_INST_MULTIPLY, \
&&lbl_BC_INST_DIVIDE, \
&&lbl_BC_INST_MODULUS, \
&&lbl_BC_INST_PLUS, \
&&lbl_BC_INST_MINUS, \
&&lbl_BC_INST_REL_EQ, \
&&lbl_BC_INST_REL_LE, \
&&lbl_BC_INST_REL_GE, \
&&lbl_BC_INST_REL_NE, \
&&lbl_BC_INST_REL_LT, \
&&lbl_BC_INST_REL_GT, \
&&lbl_BC_INST_BOOL_OR, \
&&lbl_BC_INST_BOOL_AND, \
&&lbl_BC_INST_ASSIGN_POWER, \
&&lbl_BC_INST_ASSIGN_MULTIPLY, \
&&lbl_BC_INST_ASSIGN_DIVIDE, \
&&lbl_BC_INST_ASSIGN_MODULUS, \
&&lbl_BC_INST_ASSIGN_PLUS, \
&&lbl_BC_INST_ASSIGN_MINUS, \
&&lbl_BC_INST_ASSIGN, \
&&lbl_BC_INST_ASSIGN_POWER_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MULTIPLY_NO_VAL, \
&&lbl_BC_INST_ASSIGN_DIVIDE_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MODULUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_PLUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MINUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_NO_VAL, \
&&lbl_BC_INST_NUM, \
&&lbl_BC_INST_VAR, \
&&lbl_BC_INST_ARRAY_ELEM, \
&&lbl_BC_INST_ARRAY, \
&&lbl_BC_INST_ZERO, \
&&lbl_BC_INST_ONE, \
&&lbl_BC_INST_LAST, \
&&lbl_BC_INST_IBASE, \
&&lbl_BC_INST_OBASE, \
&&lbl_BC_INST_SCALE, \
&&lbl_BC_INST_LENGTH, \
&&lbl_BC_INST_SCALE_FUNC, \
&&lbl_BC_INST_SQRT, \
&&lbl_BC_INST_ABS, \
&&lbl_BC_INST_ASCIIFY, \
&&lbl_BC_INST_READ, \
&&lbl_BC_INST_MAXIBASE, \
&&lbl_BC_INST_MAXOBASE, \
&&lbl_BC_INST_MAXSCALE, \
+ &&lbl_BC_INST_LINE_LENGTH, \
+ &&lbl_BC_INST_GLOBAL_STACKS, \
+ &&lbl_BC_INST_LEADING_ZERO, \
&&lbl_BC_INST_PRINT, \
&&lbl_BC_INST_PRINT_POP, \
&&lbl_BC_INST_STR, \
&&lbl_BC_INST_PRINT_STR, \
&&lbl_BC_INST_JUMP, \
&&lbl_BC_INST_JUMP_ZERO, \
&&lbl_BC_INST_CALL, \
&&lbl_BC_INST_RET, \
&&lbl_BC_INST_RET0, \
&&lbl_BC_INST_RET_VOID, \
&&lbl_BC_INST_HALT, \
&&lbl_BC_INST_POP, \
&&lbl_BC_INST_SWAP, \
&&lbl_BC_INST_MODEXP, \
&&lbl_BC_INST_DIVMOD, \
&&lbl_BC_INST_PRINT_STREAM, \
&&lbl_BC_INST_POP_EXEC, \
&&lbl_BC_INST_EXECUTE, \
&&lbl_BC_INST_EXEC_COND, \
&&lbl_BC_INST_PRINT_STACK, \
&&lbl_BC_INST_CLEAR_STACK, \
&&lbl_BC_INST_REG_STACK_LEN, \
&&lbl_BC_INST_STACK_LEN, \
&&lbl_BC_INST_DUPLICATE, \
&&lbl_BC_INST_LOAD, \
&&lbl_BC_INST_PUSH_VAR, \
&&lbl_BC_INST_PUSH_TO_VAR, \
&&lbl_BC_INST_QUIT, \
&&lbl_BC_INST_NQUIT, \
&&lbl_BC_INST_EXEC_STACK_LEN, \
&&lbl_BC_INST_INVALID, \
}
#endif // BC_ENABLE_EXTRA_MATH
#else // DC_ENABLED
#if BC_ENABLE_EXTRA_MATH
#define BC_PROG_LBLS static const void* const bc_program_inst_lbls[] = { \
&&lbl_BC_INST_INC, \
&&lbl_BC_INST_DEC, \
&&lbl_BC_INST_NEG, \
&&lbl_BC_INST_BOOL_NOT, \
&&lbl_BC_INST_TRUNC, \
&&lbl_BC_INST_POWER, \
&&lbl_BC_INST_MULTIPLY, \
&&lbl_BC_INST_DIVIDE, \
&&lbl_BC_INST_MODULUS, \
&&lbl_BC_INST_PLUS, \
&&lbl_BC_INST_MINUS, \
&&lbl_BC_INST_PLACES, \
&&lbl_BC_INST_LSHIFT, \
&&lbl_BC_INST_RSHIFT, \
&&lbl_BC_INST_REL_EQ, \
&&lbl_BC_INST_REL_LE, \
&&lbl_BC_INST_REL_GE, \
&&lbl_BC_INST_REL_NE, \
&&lbl_BC_INST_REL_LT, \
&&lbl_BC_INST_REL_GT, \
&&lbl_BC_INST_BOOL_OR, \
&&lbl_BC_INST_BOOL_AND, \
&&lbl_BC_INST_ASSIGN_POWER, \
&&lbl_BC_INST_ASSIGN_MULTIPLY, \
&&lbl_BC_INST_ASSIGN_DIVIDE, \
&&lbl_BC_INST_ASSIGN_MODULUS, \
&&lbl_BC_INST_ASSIGN_PLUS, \
&&lbl_BC_INST_ASSIGN_MINUS, \
&&lbl_BC_INST_ASSIGN_PLACES, \
&&lbl_BC_INST_ASSIGN_LSHIFT, \
&&lbl_BC_INST_ASSIGN_RSHIFT, \
&&lbl_BC_INST_ASSIGN, \
&&lbl_BC_INST_ASSIGN_POWER_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MULTIPLY_NO_VAL, \
&&lbl_BC_INST_ASSIGN_DIVIDE_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MODULUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_PLUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MINUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_PLACES_NO_VAL, \
&&lbl_BC_INST_ASSIGN_LSHIFT_NO_VAL, \
&&lbl_BC_INST_ASSIGN_RSHIFT_NO_VAL, \
&&lbl_BC_INST_ASSIGN_NO_VAL, \
&&lbl_BC_INST_NUM, \
&&lbl_BC_INST_VAR, \
&&lbl_BC_INST_ARRAY_ELEM, \
&&lbl_BC_INST_ARRAY, \
&&lbl_BC_INST_ZERO, \
&&lbl_BC_INST_ONE, \
&&lbl_BC_INST_LAST, \
&&lbl_BC_INST_IBASE, \
&&lbl_BC_INST_OBASE, \
&&lbl_BC_INST_SCALE, \
&&lbl_BC_INST_SEED, \
&&lbl_BC_INST_LENGTH, \
&&lbl_BC_INST_SCALE_FUNC, \
&&lbl_BC_INST_SQRT, \
&&lbl_BC_INST_ABS, \
&&lbl_BC_INST_IRAND, \
&&lbl_BC_INST_ASCIIFY, \
&&lbl_BC_INST_READ, \
&&lbl_BC_INST_RAND, \
&&lbl_BC_INST_MAXIBASE, \
&&lbl_BC_INST_MAXOBASE, \
&&lbl_BC_INST_MAXSCALE, \
&&lbl_BC_INST_MAXRAND, \
+ &&lbl_BC_INST_LINE_LENGTH, \
+ &&lbl_BC_INST_GLOBAL_STACKS, \
+ &&lbl_BC_INST_LEADING_ZERO, \
&&lbl_BC_INST_PRINT, \
&&lbl_BC_INST_PRINT_POP, \
&&lbl_BC_INST_STR, \
&&lbl_BC_INST_PRINT_STR, \
&&lbl_BC_INST_JUMP, \
&&lbl_BC_INST_JUMP_ZERO, \
&&lbl_BC_INST_CALL, \
&&lbl_BC_INST_RET, \
&&lbl_BC_INST_RET0, \
&&lbl_BC_INST_RET_VOID, \
&&lbl_BC_INST_HALT, \
&&lbl_BC_INST_POP, \
&&lbl_BC_INST_SWAP, \
&&lbl_BC_INST_MODEXP, \
&&lbl_BC_INST_DIVMOD, \
&&lbl_BC_INST_PRINT_STREAM, \
&&lbl_BC_INST_INVALID, \
}
#else // BC_ENABLE_EXTRA_MATH
#define BC_PROG_LBLS static const void* const bc_program_inst_lbls[] = { \
&&lbl_BC_INST_INC, \
&&lbl_BC_INST_DEC, \
&&lbl_BC_INST_NEG, \
&&lbl_BC_INST_BOOL_NOT, \
&&lbl_BC_INST_POWER, \
&&lbl_BC_INST_MULTIPLY, \
&&lbl_BC_INST_DIVIDE, \
&&lbl_BC_INST_MODULUS, \
&&lbl_BC_INST_PLUS, \
&&lbl_BC_INST_MINUS, \
&&lbl_BC_INST_REL_EQ, \
&&lbl_BC_INST_REL_LE, \
&&lbl_BC_INST_REL_GE, \
&&lbl_BC_INST_REL_NE, \
&&lbl_BC_INST_REL_LT, \
&&lbl_BC_INST_REL_GT, \
&&lbl_BC_INST_BOOL_OR, \
&&lbl_BC_INST_BOOL_AND, \
&&lbl_BC_INST_ASSIGN_POWER, \
&&lbl_BC_INST_ASSIGN_MULTIPLY, \
&&lbl_BC_INST_ASSIGN_DIVIDE, \
&&lbl_BC_INST_ASSIGN_MODULUS, \
&&lbl_BC_INST_ASSIGN_PLUS, \
&&lbl_BC_INST_ASSIGN_MINUS, \
&&lbl_BC_INST_ASSIGN, \
&&lbl_BC_INST_ASSIGN_POWER_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MULTIPLY_NO_VAL, \
&&lbl_BC_INST_ASSIGN_DIVIDE_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MODULUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_PLUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_MINUS_NO_VAL, \
&&lbl_BC_INST_ASSIGN_NO_VAL, \
&&lbl_BC_INST_NUM, \
&&lbl_BC_INST_VAR, \
&&lbl_BC_INST_ARRAY_ELEM, \
&&lbl_BC_INST_ARRAY, \
&&lbl_BC_INST_ZERO, \
&&lbl_BC_INST_ONE, \
&&lbl_BC_INST_LAST, \
&&lbl_BC_INST_IBASE, \
&&lbl_BC_INST_OBASE, \
&&lbl_BC_INST_SCALE, \
&&lbl_BC_INST_LENGTH, \
&&lbl_BC_INST_SCALE_FUNC, \
&&lbl_BC_INST_SQRT, \
&&lbl_BC_INST_ABS, \
&&lbl_BC_INST_ASCIIFY, \
&&lbl_BC_INST_READ, \
&&lbl_BC_INST_MAXIBASE, \
&&lbl_BC_INST_MAXOBASE, \
&&lbl_BC_INST_MAXSCALE, \
+ &&lbl_BC_INST_LINE_LENGTH, \
+ &&lbl_BC_INST_GLOBAL_STACKS, \
+ &&lbl_BC_INST_LEADING_ZERO, \
&&lbl_BC_INST_PRINT, \
&&lbl_BC_INST_PRINT_POP, \
&&lbl_BC_INST_STR, \
&&lbl_BC_INST_PRINT_STR, \
&&lbl_BC_INST_JUMP, \
&&lbl_BC_INST_JUMP_ZERO, \
&&lbl_BC_INST_CALL, \
&&lbl_BC_INST_RET, \
&&lbl_BC_INST_RET0, \
&&lbl_BC_INST_RET_VOID, \
&&lbl_BC_INST_HALT, \
&&lbl_BC_INST_POP, \
&&lbl_BC_INST_SWAP, \
&&lbl_BC_INST_MODEXP, \
&&lbl_BC_INST_DIVMOD, \
&&lbl_BC_INST_PRINT_STREAM, \
&&lbl_BC_INST_INVALID, \
}
#endif // BC_ENABLE_EXTRA_MATH
#endif // DC_ENABLED
#else // BC_ENABLED
#if BC_ENABLE_EXTRA_MATH
#define BC_PROG_LBLS static const void* const bc_program_inst_lbls[] = { \
&&lbl_BC_INST_NEG, \
&&lbl_BC_INST_BOOL_NOT, \
&&lbl_BC_INST_TRUNC, \
&&lbl_BC_INST_POWER, \
&&lbl_BC_INST_MULTIPLY, \
&&lbl_BC_INST_DIVIDE, \
&&lbl_BC_INST_MODULUS, \
&&lbl_BC_INST_PLUS, \
&&lbl_BC_INST_MINUS, \
&&lbl_BC_INST_PLACES, \
&&lbl_BC_INST_LSHIFT, \
&&lbl_BC_INST_RSHIFT, \
&&lbl_BC_INST_REL_EQ, \
&&lbl_BC_INST_REL_LE, \
&&lbl_BC_INST_REL_GE, \
&&lbl_BC_INST_REL_NE, \
&&lbl_BC_INST_REL_LT, \
&&lbl_BC_INST_REL_GT, \
&&lbl_BC_INST_BOOL_OR, \
&&lbl_BC_INST_BOOL_AND, \
&&lbl_BC_INST_ASSIGN_NO_VAL, \
&&lbl_BC_INST_NUM, \
&&lbl_BC_INST_VAR, \
&&lbl_BC_INST_ARRAY_ELEM, \
&&lbl_BC_INST_ARRAY, \
&&lbl_BC_INST_ZERO, \
&&lbl_BC_INST_ONE, \
&&lbl_BC_INST_IBASE, \
&&lbl_BC_INST_OBASE, \
&&lbl_BC_INST_SCALE, \
&&lbl_BC_INST_SEED, \
&&lbl_BC_INST_LENGTH, \
&&lbl_BC_INST_SCALE_FUNC, \
&&lbl_BC_INST_SQRT, \
&&lbl_BC_INST_ABS, \
&&lbl_BC_INST_IRAND, \
&&lbl_BC_INST_ASCIIFY, \
&&lbl_BC_INST_READ, \
&&lbl_BC_INST_RAND, \
&&lbl_BC_INST_MAXIBASE, \
&&lbl_BC_INST_MAXOBASE, \
&&lbl_BC_INST_MAXSCALE, \
&&lbl_BC_INST_MAXRAND, \
+ &&lbl_BC_INST_LINE_LENGTH, \
+ &&lbl_BC_INST_LEADING_ZERO, \
&&lbl_BC_INST_PRINT, \
&&lbl_BC_INST_PRINT_POP, \
&&lbl_BC_INST_STR, \
&&lbl_BC_INST_POP, \
&&lbl_BC_INST_SWAP, \
&&lbl_BC_INST_MODEXP, \
&&lbl_BC_INST_DIVMOD, \
&&lbl_BC_INST_PRINT_STREAM, \
&&lbl_BC_INST_POP_EXEC, \
&&lbl_BC_INST_EXECUTE, \
&&lbl_BC_INST_EXEC_COND, \
&&lbl_BC_INST_PRINT_STACK, \
&&lbl_BC_INST_CLEAR_STACK, \
&&lbl_BC_INST_REG_STACK_LEN, \
&&lbl_BC_INST_STACK_LEN, \
&&lbl_BC_INST_DUPLICATE, \
&&lbl_BC_INST_LOAD, \
&&lbl_BC_INST_PUSH_VAR, \
&&lbl_BC_INST_PUSH_TO_VAR, \
&&lbl_BC_INST_QUIT, \
&&lbl_BC_INST_NQUIT, \
&&lbl_BC_INST_EXEC_STACK_LEN, \
&&lbl_BC_INST_INVALID, \
}
#else // BC_ENABLE_EXTRA_MATH
#define BC_PROG_LBLS static const void* const bc_program_inst_lbls[] = { \
&&lbl_BC_INST_NEG, \
&&lbl_BC_INST_BOOL_NOT, \
&&lbl_BC_INST_POWER, \
&&lbl_BC_INST_MULTIPLY, \
&&lbl_BC_INST_DIVIDE, \
&&lbl_BC_INST_MODULUS, \
&&lbl_BC_INST_PLUS, \
&&lbl_BC_INST_MINUS, \
&&lbl_BC_INST_REL_EQ, \
&&lbl_BC_INST_REL_LE, \
&&lbl_BC_INST_REL_GE, \
&&lbl_BC_INST_REL_NE, \
&&lbl_BC_INST_REL_LT, \
&&lbl_BC_INST_REL_GT, \
&&lbl_BC_INST_BOOL_OR, \
&&lbl_BC_INST_BOOL_AND, \
&&lbl_BC_INST_ASSIGN_NO_VAL, \
&&lbl_BC_INST_NUM, \
&&lbl_BC_INST_VAR, \
&&lbl_BC_INST_ARRAY_ELEM, \
&&lbl_BC_INST_ARRAY, \
&&lbl_BC_INST_ZERO, \
&&lbl_BC_INST_ONE, \
&&lbl_BC_INST_IBASE, \
&&lbl_BC_INST_OBASE, \
&&lbl_BC_INST_SCALE, \
&&lbl_BC_INST_LENGTH, \
&&lbl_BC_INST_SCALE_FUNC, \
&&lbl_BC_INST_SQRT, \
&&lbl_BC_INST_ABS, \
&&lbl_BC_INST_ASCIIFY, \
&&lbl_BC_INST_READ, \
&&lbl_BC_INST_MAXIBASE, \
&&lbl_BC_INST_MAXOBASE, \
&&lbl_BC_INST_MAXSCALE, \
+ &&lbl_BC_INST_LINE_LENGTH, \
+ &&lbl_BC_INST_LEADING_ZERO, \
&&lbl_BC_INST_PRINT, \
&&lbl_BC_INST_PRINT_POP, \
&&lbl_BC_INST_STR, \
&&lbl_BC_INST_POP, \
&&lbl_BC_INST_SWAP, \
&&lbl_BC_INST_MODEXP, \
&&lbl_BC_INST_DIVMOD, \
&&lbl_BC_INST_PRINT_STREAM, \
&&lbl_BC_INST_POP_EXEC, \
&&lbl_BC_INST_EXECUTE, \
&&lbl_BC_INST_EXEC_COND, \
&&lbl_BC_INST_PRINT_STACK, \
&&lbl_BC_INST_CLEAR_STACK, \
&&lbl_BC_INST_REG_STACK_LEN, \
&&lbl_BC_INST_STACK_LEN, \
&&lbl_BC_INST_DUPLICATE, \
&&lbl_BC_INST_LOAD, \
&&lbl_BC_INST_PUSH_VAR, \
&&lbl_BC_INST_PUSH_TO_VAR, \
&&lbl_BC_INST_QUIT, \
&&lbl_BC_INST_NQUIT, \
&&lbl_BC_INST_EXEC_STACK_LEN, \
&&lbl_BC_INST_INVALID, \
}
#endif // BC_ENABLE_EXTRA_MATH
#endif // BC_ENABLED
#else // BC_HAS_COMPUTED_GOTO
#define BC_PROG_JUMP(inst, code, ip) break
#define BC_PROG_DIRECT_JUMP(l)
#define BC_PROG_LBL(l) case l
#define BC_PROG_FALLTHROUGH BC_FALLTHROUGH
#define BC_PROG_LBLS
#endif // BC_HAS_COMPUTED_GOTO
#endif // BC_PROGRAM_H
diff --git a/include/version.h b/include/version.h
index 071b123cccf1..3be823189b8f 100644
--- a/include/version.h
+++ b/include/version.h
@@ -1,42 +1,42 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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 version of bc.
*
*/
#ifndef BC_VERSION_H
#define BC_VERSION_H
/// The current version.
-#define VERSION 5.0.2
+#define VERSION 5.1.0
#endif // BC_VERSION_H
diff --git a/include/vm.h b/include/vm.h
index 7db5f7e3c0e9..bbc5e57e2ac8 100644
--- a/include/vm.h
+++ b/include/vm.h
@@ -1,863 +1,876 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
#include
#include
#include
#if BC_ENABLE_NLS
#ifdef _WIN32
#error NLS is not supported on Windows.
#endif // _WIN32
#include
#endif // BC_ENABLE_NLS
#include
#include
#include
#include
#include
#include
#include
#include
// We don't want to include this file for the library because it's unused.
#if !BC_ENABLE_LIBRARY
#include
#endif // !BC_ENABLE_LIBRARY
// This should be obvious. If neither calculator is enabled, barf.
#if !BC_ENABLED && !DC_ENABLED
#error Must define BC_ENABLED, DC_ENABLED, or both
#endif
// CHAR_BIT must be at least 6, for various reasons. I might want to bump this
// to 8 in the future.
#if CHAR_BIT < 6
#error CHAR_BIT must be at least 6.
#endif
// Set defaults.
//
#ifndef BC_ENABLE_NLS
#define BC_ENABLE_NLS (0)
#endif // BC_ENABLE_NLS
#ifndef MAINEXEC
#define MAINEXEC bc
#endif // MAINEXEC
#ifndef _WIN32
#ifndef EXECPREFIX
#define EXECPREFIX
#endif // EXECPREFIX
#else // _WIN32
#undef EXECPREFIX
#endif // _WIN32
/**
* Generate a string from text.
* @parm V The text to generate a string for.
*/
#define GEN_STR(V) #V
/**
* Help generate a string from text. The preprocessor requires this two-step
* process. Trust me.
* @parm V The text to generate a string for.
*/
#define GEN_STR2(V) GEN_STR(V)
/// The version as a string. VERSION must be defined previously, usually by the
/// build system.
#define BC_VERSION GEN_STR2(VERSION)
/// The main executable name as a string. MAINEXEC must be defined previously,
/// usually by the build system.
#define BC_MAINEXEC GEN_STR2(MAINEXEC)
/// The build type as a string. BUILD_TYPE must be defined previously, usually
/// by the build system.
#define BC_BUILD_TYPE GEN_STR2(BUILD_TYPE)
// We only allow an empty executable prefix on Windows.
#ifndef _WIN32
#define BC_EXECPREFIX GEN_STR2(EXECPREFIX)
#else // _WIN32
#define BC_EXECPREFIX ""
#endif // _WIN32
#if !BC_ENABLE_LIBRARY
#if DC_ENABLED
/// The flag for the extended register option.
#define DC_FLAG_X (UINTMAX_C(1)<<0)
#endif // DC_ENABLED
#if BC_ENABLED
/// The flag for the POSIX warning option.
#define BC_FLAG_W (UINTMAX_C(1)<<1)
/// The flag for the POSIX error option.
#define BC_FLAG_S (UINTMAX_C(1)<<2)
/// The flag for the math library option.
#define BC_FLAG_L (UINTMAX_C(1)<<3)
/// The flag for the global stacks option.
#define BC_FLAG_G (UINTMAX_C(1)<<4)
#endif // BC_ENABLED
/// The flag for quiet, though this one is reversed; the option clears the flag.
#define BC_FLAG_Q (UINTMAX_C(1)<<5)
/// The flag for interactive.
#define BC_FLAG_I (UINTMAX_C(1)<<6)
/// The flag for prompt. This is also reversed; the option clears the flag.
#define BC_FLAG_P (UINTMAX_C(1)<<7)
/// The flag for read prompt. This is also reversed; the option clears the flag.
#define BC_FLAG_R (UINTMAX_C(1)<<8)
+/// The flag for a leading zero.
+#define BC_FLAG_Z (UINTMAX_C(1)<<9)
+
/// The flag for stdin being a TTY.
-#define BC_FLAG_TTYIN (UINTMAX_C(1)<<9)
+#define BC_FLAG_TTYIN (UINTMAX_C(1)<<10)
/// The flag for TTY mode.
-#define BC_FLAG_TTY (UINTMAX_C(1)<<10)
+#define BC_FLAG_TTY (UINTMAX_C(1)<<11)
/// The flag for reset on SIGINT.
-#define BC_FLAG_SIGINT (UINTMAX_C(1)<<11)
+#define BC_FLAG_SIGINT (UINTMAX_C(1)<<12)
/// A convenience macro for getting the TTYIN flag.
#define BC_TTYIN (vm.flags & BC_FLAG_TTYIN)
/// A convenience macro for getting the TTY flag.
#define BC_TTY (vm.flags & BC_FLAG_TTY)
/// A convenience macro for getting the SIGINT flag.
#define BC_SIGINT (vm.flags & BC_FLAG_SIGINT)
#if BC_ENABLED
/// A convenience macro for getting the POSIX error flag.
#define BC_S (vm.flags & BC_FLAG_S)
/// A convenience macro for getting the POSIX warning flag.
#define BC_W (vm.flags & BC_FLAG_W)
/// A convenience macro for getting the math library flag.
#define BC_L (vm.flags & BC_FLAG_L)
/// A convenience macro for getting the global stacks flag.
#define BC_G (vm.flags & BC_FLAG_G)
#endif // BC_ENABLED
#if DC_ENABLED
/// A convenience macro for getting the extended register flag.
#define DC_X (vm.flags & DC_FLAG_X)
#endif // DC_ENABLED
/// A convenience macro for getting the interactive flag.
#define BC_I (vm.flags & BC_FLAG_I)
/// A convenience macro for getting the prompt flag.
#define BC_P (vm.flags & BC_FLAG_P)
/// A convenience macro for getting the read prompt flag.
#define BC_R (vm.flags & BC_FLAG_R)
+/// A convenience macro for getting the leading zero flag.
+#define BC_Z (vm.flags & BC_FLAG_Z)
+
#if BC_ENABLED
/// A convenience macro for checking if bc is in POSIX mode.
#define BC_IS_POSIX (BC_S || BC_W)
#if DC_ENABLED
/// Returns true if bc is running.
#define BC_IS_BC (vm.name[0] != 'd')
/// Returns true if dc is running.
#define BC_IS_DC (vm.name[0] == 'd')
#else // DC_ENABLED
/// Returns true if bc is running.
#define BC_IS_BC (1)
/// Returns true if dc is running.
#define BC_IS_DC (0)
#endif // DC_ENABLED
#else // BC_ENABLED
/// A convenience macro for checking if bc is in POSIX mode.
#define BC_IS_POSIX (0)
/// Returns true if bc is running.
#define BC_IS_BC (0)
/// Returns true if dc is running.
#define BC_IS_DC (1)
#endif // BC_ENABLED
/// A convenience macro for checking if the prompt is enabled.
#define BC_PROMPT (BC_P)
+#else // !BC_ENABLE_LIBRARY
+
+#define BC_Z (vm.leading_zeroes)
+
#endif // !BC_ENABLE_LIBRARY
/**
* Returns the max of its two arguments. This evaluates arguments twice, so be
* careful what args you give it.
* @param a The first argument.
* @param b The second argument.
* @return The max of the two arguments.
*/
#define BC_MAX(a, b) ((a) > (b) ? (a) : (b))
/**
* Returns the min of its two arguments. This evaluates arguments twice, so be
* careful what args you give it.
* @param a The first argument.
* @param b The second argument.
* @return The min of the two arguments.
*/
#define BC_MIN(a, b) ((a) < (b) ? (a) : (b))
/// Returns the max obase that is allowed.
#define BC_MAX_OBASE ((BcBigDig) (BC_BASE_POW))
/// Returns the max array size that is allowed.
#define BC_MAX_DIM ((BcBigDig) (SIZE_MAX - 1))
/// Returns the max scale that is allowed.
#define BC_MAX_SCALE ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1))
/// Returns the max string length that is allowed.
#define BC_MAX_STRING ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1))
/// Returns the max identifier length that is allowed.
#define BC_MAX_NAME BC_MAX_STRING
/// Returns the max number size that is allowed.
#define BC_MAX_NUM BC_MAX_SCALE
#if BC_ENABLE_EXTRA_MATH
/// Returns the max random integer that can be returned.
#define BC_MAX_RAND ((BcBigDig) (((BcRand) 0) - 1))
#endif // BC_ENABLE_EXTRA_MATH
/// Returns the max exponent that is allowed.
#define BC_MAX_EXP ((ulong) (BC_NUM_BIGDIG_MAX))
/// Returns the max number of variables that is allowed.
#define BC_MAX_VARS ((ulong) (SIZE_MAX - 1))
/// The size of the global buffer.
#define BC_VM_BUF_SIZE (1<<12)
/// The amount of the global buffer allocated to stdout.
#define BC_VM_STDOUT_BUF_SIZE (1<<11)
/// The amount of the global buffer allocated to stderr.
#define BC_VM_STDERR_BUF_SIZE (1<<10)
/// The amount of the global buffer allocated to stdin.
#define BC_VM_STDIN_BUF_SIZE (BC_VM_STDERR_BUF_SIZE - 1)
/// The max number of temporary BcNums that can be kept.
#define BC_VM_MAX_TEMPS (1 << 9)
/// The capacity of the one BcNum, which is a constant.
#define BC_VM_ONE_CAP (1)
/**
* Returns true if a BcResult is safe for garbage collection.
* @param r The BcResult to test.
* @return True if @a r is safe to garbage collect.
*/
#define BC_VM_SAFE_RESULT(r) ((r)->t >= BC_RESULT_TEMP)
/// The invalid locale catalog return value.
#define BC_VM_INVALID_CATALOG ((nl_catd) -1)
/**
* Returns true if the *unsigned* multiplication overflows.
* @param a The first operand.
* @param b The second operand.
* @param r The product.
* @return True if the multiplication of @a a and @a b overflows.
*/
#define BC_VM_MUL_OVERFLOW(a, b, r) \
((r) >= SIZE_MAX || ((a) != 0 && (r) / (a) != (b)))
/// The global vm struct. This holds all of the global data besides the file
/// buffers.
typedef struct BcVm {
/// The current status. This is volatile sig_atomic_t because it is also
/// used in the signal handler. See the development manual
/// (manuals/development.md#async-signal-safe-signal-handling) for more
/// information.
volatile sig_atomic_t status;
/// Non-zero if a jump series is in progress and items should be popped off
/// the jmp_bufs vector. This is volatile sig_atomic_t because it is also
/// used in the signal handler. See the development manual
/// (manuals/development.md#async-signal-safe-signal-handling) for more
/// information.
volatile sig_atomic_t sig_pop;
#if !BC_ENABLE_LIBRARY
/// The parser.
BcParse prs;
/// The program.
BcProgram prog;
/// A buffer for lines for stdin.
BcVec line_buf;
/// A buffer to hold a series of lines from stdin. Sometimes, multiple lines
/// are necessary for parsing, such as a comment that spans multiple lines.
BcVec buffer;
/// A parser to parse read expressions.
BcParse read_prs;
/// A buffer for read expressions.
BcVec read_buf;
#endif // !BC_ENABLE_LIBRARY
/// A vector of jmp_bufs for doing a jump series. This allows exception-type
/// error handling, while allowing me to do cleanup on the way.
BcVec jmp_bufs;
/// The number of temps in the temps array.
size_t temps_len;
#if BC_ENABLE_LIBRARY
/// The vector of contexts for the library.
BcVec ctxts;
/// The vector for creating strings to pass to the client.
BcVec out;
/// The PRNG.
BcRNG rng;
/// The current error.
BclError err;
/// Whether or not bcl should abort on fatal errors.
bool abrt;
+ /// Whether or not to print leading zeros.
+ bool leading_zeroes;
+
/// The number of "references," or times that the library was initialized.
unsigned int refs;
/// Non-zero if bcl is running. This is volatile sig_atomic_t because it is
/// also used in the signal handler. See the development manual
/// (manuals/development.md#async-signal-safe-signal-handling) for more
/// information.
volatile sig_atomic_t running;
#endif // BC_ENABLE_LIBRARY
#if !BC_ENABLE_LIBRARY
/// A pointer to the filename of the current file. This is not owned by the
/// BcVm struct.
const char* file;
/// The message printed when SIGINT happens.
const char *sigmsg;
#endif // !BC_ENABLE_LIBRARY
/// Non-zero when signals are "locked." This is volatile sig_atomic_t
/// because it is also used in the signal handler. See the development
/// manual (manuals/development.md#async-signal-safe-signal-handling) for
/// more information.
volatile sig_atomic_t sig_lock;
/// Non-zero when a signal has been received, but not acted on. This is
/// volatile sig_atomic_t because it is also used in the signal handler. See
/// the development manual
/// (manuals/development.md#async-signal-safe-signal-handling) for more
/// information.
volatile sig_atomic_t sig;
#if !BC_ENABLE_LIBRARY
/// The length of sigmsg.
uchar siglen;
/// The instruction used for returning from a read() call.
uchar read_ret;
/// The flags field used by most macros above.
uint16_t flags;
/// The number of characters printed in the current line. This is used
/// because bc has a limit of the number of characters it can print per
/// line.
uint16_t nchars;
/// The length of the line we can print. The user can set this if they wish.
uint16_t line_len;
/// True if bc should error if expressions are encountered during option
/// parsing, false otherwise.
bool no_exprs;
/// True if bc should exit if expresions are encountered.
bool exit_exprs;
/// True if EOF was encountered.
bool eof;
/// True if bc is currently reading from stdin.
bool is_stdin;
#if BC_ENABLED
/// True if keywords should not be redefined. This is only true for the
/// builtin math libraries for bc.
bool no_redefine;
#endif // BC_ENABLED
#endif // !BC_ENABLE_LIBRARY
/// An array of maxes for the globals.
BcBigDig maxes[BC_PROG_GLOBALS_LEN + BC_ENABLE_EXTRA_MATH];
#if !BC_ENABLE_LIBRARY
/// A vector of filenames to process.
BcVec files;
/// A vector of expressions to process.
BcVec exprs;
/// The name of the calculator under use. This is used by BC_IS_BC and
/// BC_IS_DC.
const char *name;
/// The help text for the calculator.
const char *help;
#if BC_ENABLE_HISTORY
/// The history data.
BcHistory history;
#endif // BC_ENABLE_HISTORY
/// The function to call to get the next lex token.
BcLexNext next;
/// The function to call to parse.
BcParseParse parse;
/// The function to call to parse expressions.
BcParseExpr expr;
/// The text to display to label functions in error messages.
const char *func_header;
/// The names of the categories of errors.
const char *err_ids[BC_ERR_IDX_NELEMS + BC_ENABLED];
/// The messages for each error.
const char *err_msgs[BC_ERR_NELEMS];
/// The locale.
const char *locale;
#endif // !BC_ENABLE_LIBRARY
/// The last base used to parse.
BcBigDig last_base;
/// The last power of last_base used to parse.
BcBigDig last_pow;
/// The last exponent of base that equals last_pow.
BcBigDig last_exp;
/// BC_BASE_POW - last_pow.
BcBigDig last_rem;
#if !BC_ENABLE_LIBRARY
/// A buffer of environment arguments. This is the actual value of the
/// environment variable.
char *env_args_buffer;
/// A vector for environment arguments after parsing.
BcVec env_args;
/// A BcNum set to constant 0.
BcNum zero;
#endif // !BC_ENABLE_LIBRARY
/// A BcNum set to constant 1.
BcNum one;
/// A BcNum holding the max number held by a BcBigDig plus 1.
BcNum max;
/// A BcNum holding the max number held by a BcBigDig times 2 plus 1.
BcNum max2;
/// The BcDig array for max.
BcDig max_num[BC_NUM_BIGDIG_LOG10];
/// The BcDig array for max2.
BcDig max2_num[BC_NUM_BIGDIG_LOG10];
// The BcDig array for the one BcNum.
BcDig one_num[BC_VM_ONE_CAP];
#if !BC_ENABLE_LIBRARY
// The BcDig array for the zero BcNum.
BcDig zero_num[BC_VM_ONE_CAP];
/// The stdout file.
BcFile fout;
/// The stderr file.
BcFile ferr;
#if BC_ENABLE_NLS
/// The locale catalog.
nl_catd catalog;
#endif // BC_ENABLE_NLS
/// A pointer to the stdin buffer.
char *buf;
/// The number of items in the input buffer.
size_t buf_len;
/// The slab for constants in the main function. This is separate for
/// garbage collection reasons.
BcVec main_const_slab;
//// The slab for all other strings for the main function.
BcVec main_slabs;
/// The slab for function names, strings in other functions, and constants
/// in other functions.
BcVec other_slabs;
#if BC_ENABLED
/// An array of booleans for which bc keywords have been redefined if
/// BC_REDEFINE_KEYWORDS is non-zero.
bool redefined_kws[BC_LEX_NKWS];
#endif // BC_ENABLED
#endif // !BC_ENABLE_LIBRARY
#if BC_DEBUG_CODE
/// The depth for BC_FUNC_ENTER and BC_FUNC_EXIT.
size_t func_depth;
#endif // BC_DEBUG_CODE
} BcVm;
/**
* Print the copyright banner and help if it's non-NULL.
* @param help The help message to print if it's non-NULL.
*/
void bc_vm_info(const char* const help);
/**
* The entrance point for bc/dc together.
* @param argc The count of arguments.
* @param argv The argument array.
*/
void bc_vm_boot(int argc, char *argv[]);
/**
* Initializes some of the BcVm global. This is separate to make things easier
* on the library code.
*/
void bc_vm_init(void);
/**
* Frees the BcVm global.
*/
void bc_vm_shutdown(void);
/**
* Add a temp to the temp array.
* @param num The BcDig array to add to the temp array.
*/
void bc_vm_addTemp(BcDig *num);
/**
* Dish out a temp, or NULL if there are none.
* @return A temp, or NULL if none exist.
*/
BcDig* bc_vm_takeTemp(void);
/**
* Frees all temporaries.
*/
void bc_vm_freeTemps(void);
#if !BC_ENABLE_HISTORY
/**
* Erases the flush argument if history does not exist because it does not
* matter if history does not exist.
*/
#define bc_vm_putchar(c, t) bc_vm_putchar(c)
#endif // !BC_ENABLE_HISTORY
/**
* Print to stdout with limited formating.
* @param fmt The format string.
*/
void bc_vm_printf(const char *fmt, ...);
/**
* Puts a char into the stdout buffer.
* @param c The character to put on the stdout buffer.
* @param type The flush type.
*/
void bc_vm_putchar(int c, BcFlushType type);
/**
* Multiplies @a n and @a size and throws an allocation error if overflow
* occurs.
* @param n The number of elements.
* @param size The size of each element.
* @return The product of @a n and @a size.
*/
size_t bc_vm_arraySize(size_t n, size_t size);
/**
* Adds @a a and @a b and throws an error if overflow occurs.
* @param a The first operand.
* @param b The second operand.
* @return The sum of @a a and @a b.
*/
size_t bc_vm_growSize(size_t a, size_t b);
/**
* Allocate @a n bytes and throw an allocation error if allocation fails.
* @param n The bytes to allocate.
* @return A pointer to the allocated memory.
*/
void* bc_vm_malloc(size_t n);
/**
* Reallocate @a ptr to be @a n bytes and throw an allocation error if
* reallocation fails.
* @param ptr The pointer to a memory allocation to reallocate.
* @param n The bytes to allocate.
* @return A pointer to the reallocated memory.
*/
void* bc_vm_realloc(void *ptr, size_t n);
/**
* Allocates space for, and duplicates, @a str.
* @param str The string to allocate.
* @return The allocated string.
*/
char* bc_vm_strdup(const char *str);
/**
* Reads a line into BcVm's buffer field.
* @param clear True if the buffer should be cleared first, false otherwise.
* @return True if a line was read, false otherwise.
*/
bool bc_vm_readLine(bool clear);
/**
* A convenience and portability function for OpenBSD's pledge().
* @param promises The promises to pledge().
* @param execpromises The exec promises to pledge().
*/
void bc_pledge(const char *promises, const char *execpromises);
/**
* Returns the value of an environment variable.
* @param var The environment variable.
* @return The value of the environment variable.
*/
char* bc_vm_getenv(const char* var);
/**
* Frees an environment variable value.
* @param val The value to free.
*/
void bc_vm_getenvFree(char* val);
#if BC_DEBUG_CODE
/**
* Start executing a jump series.
* @param f The name of the function that started the jump series.
*/
void bc_vm_jmp(const char *f);
#else // BC_DEBUG_CODE
/**
* Start executing a jump series.
*/
void bc_vm_jmp(void);
#endif // BC_DEBUG_CODE
#if BC_ENABLE_LIBRARY
/**
* Handle an error. This is the true error handler. It will start a jump series
* if an error occurred. POSIX errors will not cause jumps when warnings are on
* or no POSIX errors are enabled.
* @param e The error.
*/
void bc_vm_handleError(BcErr e);
/**
* Handle a fatal error.
* @param e The error.
*/
void bc_vm_fatalError(BcErr e);
/**
* A function to call at exit.
*/
void bc_vm_atexit(void);
#else // BC_ENABLE_LIBRARY
/**
* Handle an error. This is the true error handler. It will start a jump series
* if an error occurred. POSIX errors will not cause jumps when warnings are on
* or no POSIX errors are enabled.
* @param e The error.
* @param line The source line where the error occurred.
*/
void bc_vm_handleError(BcErr e, size_t line, ...);
/**
* Handle a fatal error.
* @param e The error.
*/
#if !BC_ENABLE_MEMCHECK
BC_NORETURN
#endif // !BC_ENABLE_MEMCHECK
void bc_vm_fatalError(BcErr e);
/**
* A function to call at exit.
* @param status The exit status.
*/
int bc_vm_atexit(int status);
#endif // BC_ENABLE_LIBRARY
/// A reference to the copyright header.
extern const char bc_copyright[];
/// A reference to the format string for source code line printing.
extern const char* const bc_err_line;
/// A reference to the format string for source code function printing.
extern const char* const bc_err_func_header;
/// A reference to the array of default error category names.
extern const char *bc_errs[];
/// A reference to the array of error category indices for each error.
extern const uchar bc_err_ids[];
/// A reference to the array of default error messages.
extern const char* const bc_err_msgs[];
/// A reference to the pledge() promises at start.
extern const char bc_pledge_start[];
#if BC_ENABLE_HISTORY
/// A reference to the end pledge() promises when using history.
extern const char bc_pledge_end_history[];
#endif // BC_ENABLE_HISTORY
/// A reference to the end pledge() promises when *not* using history.
extern const char bc_pledge_end[];
/// A reference to the global data.
extern BcVm vm;
/// A reference to the global output buffers.
extern char output_bufs[BC_VM_BUF_SIZE];
#endif // BC_VM_H
diff --git a/manuals/bc/A.1 b/manuals/bc/A.1
index ff9973e3cc8d..bf6c9108456b 100644
--- a/manuals/bc/A.1
+++ b/manuals/bc/A.1
@@ -1,2699 +1,2784 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH NAME
.PP
bc - arbitrary-precision decimal arithmetic language and calculator
.SH SYNOPSIS
.PP
\f[B]bc\f[R] [\f[B]-ghilPqRsvVw\f[R]] [\f[B]--global-stacks\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]]
[\f[B]--no-prompt\f[R]] [\f[B]--no-read-prompt\f[R]] [\f[B]--quiet\f[R]]
[\f[B]--standard\f[R]] [\f[B]--warn\f[R]] [\f[B]--version\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX.
(The current standard is
here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).)
The language provides unlimited precision decimal arithmetic and is
somewhat C-like, but there are differences.
Such differences will be noted in this document.
.PP
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from \f[B]stdin\f[R].
.PP
This bc(1) is a drop-in replacement for \f[I]any\f[R] bc(1), including
(and especially) the GNU bc(1).
It also has many extensions and extra features beyond other
implementations.
.PP
\f[B]Note\f[R]: If running this bc(1) on \f[I]any\f[R] script meant for
another bc(1) gives a parse error, it is probably because a word this
bc(1) reserves as a keyword is used as the name of a function, variable,
or array.
To fix that, use the command-line option \f[B]-r\f[R] \f[I]keyword\f[R],
where \f[I]keyword\f[R] is the keyword that is used as a name in the
script.
For more information, see the \f[B]OPTIONS\f[R] section.
.PP
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported.
See the \f[B]BUGS\f[R] section.
.SH OPTIONS
.PP
The following are the options that bc(1) accepts.
.TP
\f[B]-g\f[R], \f[B]--global-stacks\f[R]
Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and
\f[B]seed\f[R] into stacks.
.RS
.PP
This has the effect that a copy of the current value of all four are
pushed onto a stack for every function call, as well as popped when
every function returns.
This means that functions can assign to any and all of those globals
without worrying that the change will affect other functions.
Thus, a hypothetical function named \f[B]output(x,b)\f[R] that simply
printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this:
.IP
.nf
\f[C]
define void output(x, b) {
obase=b
x
}
\f[R]
.fi
.PP
instead of like this:
.IP
.nf
\f[C]
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
\f[R]
.fi
.PP
This makes writing functions much easier.
.PP
(\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the
extended math library.
See the \f[B]LIBRARY\f[R] section.)
.PP
However, since using this flag means that functions cannot set
\f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R]
globally, functions that are made to do so cannot work anymore.
There are two possible use cases for that, and each has a solution.
.PP
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases.
Examples:
.IP
.nf
\f[C]
alias d2o=\[dq]bc -e ibase=A -e obase=8\[dq]
alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq]
\f[R]
.fi
.PP
Second, if the purpose of a function is to set \f[B]ibase\f[R],
\f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] globally for any
other purpose, it could be split into one to four functions (based on
how many globals it sets) and each of those functions could return the
desired value for a global.
.PP
For functions that set \f[B]seed\f[R], the value assigned to
\f[B]seed\f[R] is not propagated to parent functions.
This means that the sequence of pseudo-random numbers that they see will
not be the same sequence of pseudo-random numbers that any parent sees.
This is only the case once \f[B]seed\f[R] has been set.
.PP
If a function desires to not affect the sequence of pseudo-random
numbers of its parents, but wants to use the same \f[B]seed\f[R], it can
use the following line:
.IP
.nf
\f[C]
seed = seed
\f[R]
.fi
.PP
If the behavior of this option is desired for every run of bc(1), then
users could make sure to define \f[B]BC_ENV_ARGS\f[R] and include this
option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more
details).
.PP
If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option
is ignored.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-l\f[R], \f[B]--mathlib\f[R]
Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R]
and loads the included math library and the extended math library before
running any code, including any expressions or files specified on the
command line.
.RS
.PP
To learn what is in the libraries, see the \f[B]LIBRARY\f[R] section.
.RE
.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.RS
.PP
These options override the \f[B]BC_PROMPT\f[R] and \f[B]BC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of bc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]read()\f[R] built-in function is called.
.PP
These options \f[I]do\f[R] override the \f[B]BC_PROMPT\f[R] and
\f[B]BC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-r\f[R] \f[I]keyword\f[R], \f[B]--redefine\f[R]=\f[I]keyword\f[R]
Redefines \f[I]keyword\f[R] in order to allow it to be used as a
function, variable, or array name.
This is useful when this bc(1) gives parse errors when parsing scripts
meant for other bc(1) implementations.
.RS
.PP
The keywords this bc(1) allows to be redefined are:
.IP \[bu] 2
\f[B]abs\f[R]
.IP \[bu] 2
\f[B]asciify\f[R]
.IP \[bu] 2
\f[B]continue\f[R]
.IP \[bu] 2
\f[B]divmod\f[R]
.IP \[bu] 2
\f[B]else\f[R]
.IP \[bu] 2
\f[B]halt\f[R]
.IP \[bu] 2
\f[B]irand\f[R]
.IP \[bu] 2
\f[B]last\f[R]
.IP \[bu] 2
\f[B]limits\f[R]
.IP \[bu] 2
\f[B]maxibase\f[R]
.IP \[bu] 2
\f[B]maxobase\f[R]
.IP \[bu] 2
\f[B]maxrand\f[R]
.IP \[bu] 2
\f[B]maxscale\f[R]
.IP \[bu] 2
\f[B]modexp\f[R]
.IP \[bu] 2
\f[B]print\f[R]
.IP \[bu] 2
\f[B]rand\f[R]
.IP \[bu] 2
\f[B]read\f[R]
.IP \[bu] 2
\f[B]seed\f[R]
.IP \[bu] 2
\f[B]stream\f[R]
.PP
If any of those keywords are used as a function, variable, or array name
in a script, use this option with the keyword as the argument.
If multiple are used, use this option for all of them; it can be used
multiple times.
.PP
Keywords are \f[I]not\f[R] redefined when parsing the builtin math
library (see the \f[B]LIBRARY\f[R] section).
.PP
It is a fatal error to redefine keywords mandated by the POSIX standard.
It is a fatal error to attempt to redefine words that this bc(1) does
not reserve as keywords.
.RE
.TP
\f[B]-q\f[R], \f[B]--quiet\f[R]
This option is for compatibility with the GNU
bc(1) (https://www.gnu.org/software/bc/); it is a no-op.
Without this option, GNU bc(1) prints a copyright header.
This bc(1) only prints the copyright header if one or more of the
\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-s\f[R], \f[B]--standard\f[R]
Process exactly the language defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
and error if any extensions are used.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-w\f[R], \f[B]--warn\f[R]
Like \f[B]-s\f[R] and \f[B]--standard\f[R], except that warnings (and
not errors) are printed for non-standard extensions and execution
continues normally.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]BC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files or expressions are given by the \f[B]-f\f[R],
\f[B]--file\f[R], \f[B]-e\f[R], or \f[B]--expression\f[R] options, then
bc(1) read from \f[B]stdin\f[R].
.PP
However, there are a few caveats to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if the parse cannot complete.
That means that starting a string without ending it or starting a
function, \f[B]if\f[R] statement, or loop without ending it will also
cause bc(1) to not execute.
.PP
Second, after an \f[B]if\f[R] statement, bc(1) doesn\[cq]t know if an
\f[B]else\f[R] statement will follow, so it will not execute until it
knows there will not be an \f[B]else\f[R] statement.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]bc >&-\f[R], it will quit with an error.
This is done so that bc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]bc 2>&-\f[R], it will quit with an error.
This is done so that bc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
which is a much more thorough resource for the language this bc(1)
accepts.
This section is meant to be a summary and a listing of all the
extensions to the standard.
.PP
In the sections below, \f[B]E\f[R] means expression, \f[B]S\f[R] means
statement, and \f[B]I\f[R] means identifier.
.PP
Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be
followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase
letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores
(\f[B]_\f[R]).
The regex is \f[B][a-z][a-z0-9_]*\f[R].
Identifiers with more than one character (letter) are a
\f[B]non-portable extension\f[R].
.PP
\f[B]ibase\f[R] is a global variable determining how to interpret
constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R]
(\f[B]--warn\f[R]) flags were not given on the command line, the max
allowable value for \f[B]ibase\f[R] is \f[B]36\f[R].
Otherwise, it is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in bc(1)
programs with the \f[B]maxibase()\f[R] built-in function.
.PP
\f[B]obase\f[R] is a global variable determining how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and
can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in
function.
The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R].
If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific
notation, and if \f[B]obase\f[R] is \f[B]1\f[R], values are output in
engineering notation.
Otherwise, values are output in the specified base.
.PP
Outputting in scientific and engineering notations are \f[B]non-portable
extensions\f[R].
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a global variable that sets the precision of any operations, with
exceptions.
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R]
and can be queried in bc(1) programs with the \f[B]maxscale()\f[R]
built-in function.
.PP
bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables.
All \f[I]local\f[R] variables are local to the function; they are
parameters or are introduced in the \f[B]auto\f[R] list of a function
(see the \f[B]FUNCTIONS\f[R] section).
If a variable is accessed which is not a parameter or in the
\f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R].
If a parent function has a \f[I]local\f[R] variable version of a
variable that a child function considers \f[I]global\f[R], the value of
that \f[I]global\f[R] variable in the child function is the value of the
variable in the parent function, not the value of the actual
\f[I]global\f[R] variable.
.PP
All of the above applies to arrays as well.
.PP
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence
operator is an assignment operator \f[I]and\f[R] the expression is
notsurrounded by parentheses.
.PP
The value that is printed is also assigned to the special variable
\f[B]last\f[R].
A single dot (\f[B].\f[R]) may also be used as a synonym for
\f[B]last\f[R].
These are \f[B]non-portable extensions\f[R].
.PP
Either semicolons or newlines may separate statements.
.SS Comments
.PP
There are two kinds of comments:
.IP "1." 3
Block comments are enclosed in \f[B]/*\f[R] and \f[B]*/\f[R].
.IP "2." 3
Line comments go from \f[B]#\f[R] until, and not including, the next
newline.
This is a \f[B]non-portable extension\f[R].
.SS Named Expressions
.PP
The following are named expressions in bc(1):
.IP "1." 3
Variables: \f[B]I\f[R]
.IP "2." 3
Array Elements: \f[B]I[E]\f[R]
.IP "3." 3
\f[B]ibase\f[R]
.IP "4." 3
\f[B]obase\f[R]
.IP "5." 3
\f[B]scale\f[R]
.IP "6." 3
\f[B]seed\f[R]
.IP "7." 3
\f[B]last\f[R] or a single dot (\f[B].\f[R])
.PP
Numbers 6 and 7 are \f[B]non-portable extensions\f[R].
.PP
The meaning of \f[B]seed\f[R] is dependent on the current pseudo-random
number generator but is guaranteed to not change except for new major
versions.
.PP
The \f[I]scale\f[R] and sign of the value may be significant.
.PP
If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R]
and used again, the pseudo-random number generator is guaranteed to
produce the same sequence of pseudo-random numbers as it did when the
\f[B]seed\f[R] value was previously used.
.PP
The exact value assigned to \f[B]seed\f[R] is not guaranteed to be
returned if \f[B]seed\f[R] is queried again immediately.
However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both
values, when assigned to \f[B]seed\f[R], are guaranteed to produce the
same sequence of pseudo-random numbers.
This means that certain values assigned to \f[B]seed\f[R] will
\f[I]not\f[R] produce unique sequences of pseudo-random numbers.
The value of \f[B]seed\f[R] will change after any use of the
\f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the
\f[I]Operands\f[R] subsection below), except if the parameter passed to
\f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative.
.PP
There is no limit to the length (number of significant decimal digits)
or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R].
.PP
Variables and arrays do not interfere; users can have arrays named the
same as variables.
This also applies to functions (see the \f[B]FUNCTIONS\f[R] section), so
a user can have a variable, array, and function that all have the same
name, and they will not shadow each other, whether inside of functions
or not.
.PP
Named expressions are required as the operand of
\f[B]increment\f[R]/\f[B]decrement\f[R] operators and as the left side
of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R]
subsection).
.SS Operands
.PP
The following are valid operands in bc(1):
.IP " 1." 4
Numbers (see the \f[I]Numbers\f[R] subsection below).
.IP " 2." 4
Array indices (\f[B]I[E]\f[R]).
.IP " 3." 4
\f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence).
.IP " 4." 4
\f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R].
\f[B]E\f[R] must be non-negative.
.IP " 5." 4
\f[B]length(E)\f[R]: The number of significant decimal digits in
\f[B]E\f[R].
Returns \f[B]1\f[R] for \f[B]0\f[R] with no decimal places.
If given a string, the length of the string is returned.
Passing a string to \f[B]length(E)\f[R] is a \f[B]non-portable
extension\f[R].
.IP " 6." 4
\f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 7." 4
\f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R].
.IP " 8." 4
\f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 9." 4
\f[B]modexp(E, E, E)\f[R]: Modular exponentiation, where the first
expression is the base, the second is the exponent, and the third is the
modulus.
All three values must be integers.
The second argument must be non-negative.
The third argument must be non-zero.
This is a \f[B]non-portable extension\f[R].
.IP "10." 4
\f[B]divmod(E, E, I[])\f[R]: Division and modulus in one operation.
This is for optimization.
The first expression is the dividend, and the second is the divisor,
which must be non-zero.
The return value is the quotient, and the modulus is stored in index
\f[B]0\f[R] of the provided array (the last argument).
This is a \f[B]non-portable extension\f[R].
.IP "11." 4
\f[B]asciify(E)\f[R]: If \f[B]E\f[R] is a string, returns a string that
is the first letter of its argument.
If it is a number, calculates the number mod \f[B]256\f[R] and returns
that number as a one-character string.
This is a \f[B]non-portable extension\f[R].
.IP "12." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.IP "13." 4
\f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an
expression.
The result of that expression is the result of the \f[B]read()\f[R]
operand.
This is a \f[B]non-portable extension\f[R].
.IP "14." 4
\f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "15." 4
\f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "16." 4
\f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "17." 4
+\f[B]line_length()\f[R]: The line length set with
+\f[B]BC_LINE_LENGTH\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
+section).
+This is a \f[B]non-portable extension\f[R].
+.IP "18." 4
+\f[B]global_stacks()\f[R]: \f[B]0\f[R] if global stacks are not enabled
+with the \f[B]-g\f[R] or \f[B]--global-stacks\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "19." 4
+\f[B]leading_zero()\f[R]: \f[B]0\f[R] if leading zeroes are not enabled
+with the \f[B]-z\f[R] or \f[B]\[en]leading-zeroes\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "20." 4
\f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R]
(inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive).
Using this operand will change the value of \f[B]seed\f[R].
This is a \f[B]non-portable extension\f[R].
-.IP "18." 4
+.IP "21." 4
\f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R]
(inclusive) and the value of \f[B]E\f[R] (exclusive).
If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s
\f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains
unchanged.
If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is
honored by generating several pseudo-random integers, multiplying them
by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], and adding them
together.
Thus, the size of integer that can be generated with this operand is
unbounded.
Using this operand will change the value of \f[B]seed\f[R], unless the
value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R].
In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is
\f[I]not\f[R] changed.
This is a \f[B]non-portable extension\f[R].
-.IP "19." 4
+.IP "22." 4
\f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R].
This is a \f[B]non-portable extension\f[R].
.PP
The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are
guaranteed to be as unbiased as possible, subject to the limitations of
the pseudo-random number generator.
.PP
\f[B]Note\f[R]: The values returned by the pseudo-random number
generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to
\f[I]NOT\f[R] be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they \f[I]are\f[R] guaranteed to be reproducible with identical
\f[B]seed\f[R] values.
This means that the pseudo-random values from bc(1) should only be used
where a reproducible stream of pseudo-random numbers is
\f[I]ESSENTIAL\f[R].
In any other case, use a non-seeded pseudo-random number generator.
.SS Numbers
.PP
Numbers are strings made up of digits, uppercase letters, and at most
\f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R].
.PP
In addition, bc(1) accepts numbers in scientific notation.
These have the form \f[B]e\f[R].
The exponent (the portion after the \f[B]e\f[R]) must be an integer.
An example is \f[B]1.89237e9\f[R], which is equal to
\f[B]1892370000\f[R].
Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to
\f[B]0.0042890\f[R].
.PP
Using scientific notation is an error or warning if the \f[B]-s\f[R] or
\f[B]-w\f[R], respectively, command-line options (or equivalents) are
given.
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if bc(1) is given the number string
\f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.PP
Accepting input as scientific notation is a \f[B]non-portable
extension\f[R].
.SS Operators
.PP
The following arithmetic and logical operators can be used.
They are listed in order of decreasing precedence.
Operators in the same group have the same precedence.
.TP
\f[B]++\f[R] \f[B]--\f[R]
Type: Prefix and Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]increment\f[R], \f[B]decrement\f[R]
.RE
.TP
\f[B]-\f[R] \f[B]!\f[R]
Type: Prefix
.RS
.PP
Associativity: None
.PP
Description: \f[B]negation\f[R], \f[B]boolean not\f[R]
.RE
.TP
\f[B]$\f[R]
Type: Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]truncation\f[R]
.RE
.TP
\f[B]\[at]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]set precision\f[R]
.RE
.TP
\f[B]\[ha]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]power\f[R]
.RE
.TP
\f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R]
.RE
.TP
\f[B]+\f[R] \f[B]-\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]add\f[R], \f[B]subtract\f[R]
.RE
.TP
\f[B]<<\f[R] \f[B]>>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]shift left\f[R], \f[B]shift right\f[R]
.RE
.TP
\f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]assignment\f[R]
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]relational\f[R]
.RE
.TP
\f[B]&&\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean and\f[R]
.RE
.TP
\f[B]||\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean or\f[R]
.RE
.PP
The operators will be described in more detail below.
.TP
\f[B]++\f[R] \f[B]--\f[R]
The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R]
operators behave exactly like they would in C.
They require a named expression (see the \f[I]Named Expressions\f[R]
subsection) as an operand.
.RS
.PP
The prefix versions of these operators are more efficient; use them
where possible.
.RE
.TP
\f[B]-\f[R]
The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts
to negate any expression with the value \f[B]0\f[R].
Otherwise, a copy of the expression with its sign flipped is returned.
.TP
\f[B]!\f[R]
The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression
is \f[B]0\f[R], or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]$\f[R]
The \f[B]truncation\f[R] operator returns a copy of the given expression
with all of its \f[I]scale\f[R] removed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[at]\f[R]
The \f[B]set precision\f[R] operator takes two expressions and returns a
copy of the first with its \f[I]scale\f[R] equal to the value of the
second expression.
That could either mean that the number is returned without change (if
the \f[I]scale\f[R] of the first expression matches the value of the
second expression), extended (if it is less), or truncated (if it is
more).
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator,
as it would be in C) takes two expressions and raises the first to the
power of the value of the second.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]), and if it
is negative, the first value must be non-zero.
.RE
.TP
\f[B]*\f[R]
The \f[B]multiply\f[R] operator takes two expressions, multiplies them,
and returns the product.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The \f[B]divide\f[R] operator takes two expressions, divides them, and
returns the quotient.
The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]%\f[R]
The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R] and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]+\f[R]
The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the
max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]-\f[R]
The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to
the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]<<\f[R]
The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its
decimal point moved \f[B]b\f[R] places to the right.
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]>>\f[R]
The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its
decimal point moved \f[B]b\f[R] places to the left.
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R]
The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and
\f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named
Expressions\f[R] subsection).
.RS
.PP
For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to
\f[B]a\f[R].
For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to
the corresponding arithmetic operator and the result is assigned to
\f[B]a\f[R].
.PP
The \f[B]assignment\f[R] operators that correspond to operators that are
extensions are themselves \f[B]non-portable extensions\f[R].
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and if the relation holds, according to C language
semantics, the result is \f[B]1\f[R].
Otherwise, it is \f[B]0\f[R].
.RS
.PP
Note that unlike in C, these operators have a lower precedence than the
\f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is
interpreted as \f[B](a=b)>c\f[R].
.PP
Also, unlike the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
requires, these operators can appear anywhere any other expressions can
be used.
This allowance is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]&&\f[R]
The \f[B]boolean and\f[R] operator takes two expressions and returns
\f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]||\f[R]
The \f[B]boolean or\f[R] operator takes two expressions and returns
\f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R]
otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Statements
.PP
The following items are statements:
.IP " 1." 4
\f[B]E\f[R]
.IP " 2." 4
\f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R]
\f[B]}\f[R]
.IP " 3." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 4." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
\f[B]else\f[R] \f[B]S\f[R]
.IP " 5." 4
\f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 6." 4
\f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R]
\f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 7." 4
An empty statement
.IP " 8." 4
\f[B]break\f[R]
.IP " 9." 4
\f[B]continue\f[R]
.IP "10." 4
\f[B]quit\f[R]
.IP "11." 4
\f[B]halt\f[R]
.IP "12." 4
\f[B]limits\f[R]
.IP "13." 4
A string of characters, enclosed in double quotes
.IP "14." 4
\f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "15." 4
\f[B]stream\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "16." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.PP
Numbers 4, 9, 11, 12, 14, 15, and 16 are \f[B]non-portable
extensions\f[R].
.PP
Also, as a \f[B]non-portable extension\f[R], any or all of the
expressions in the header of a for loop may be omitted.
If the condition (second expression) is omitted, it is assumed to be a
constant \f[B]1\f[R].
.PP
The \f[B]break\f[R] statement causes a loop to stop iterating and resume
execution immediately following a loop.
This is only allowed in loops.
.PP
The \f[B]continue\f[R] statement causes a loop iteration to stop early
and returns to the start of the loop, including testing the loop
condition.
This is only allowed in loops.
.PP
The \f[B]if\f[R] \f[B]else\f[R] statement does the same thing as in C.
.PP
The \f[B]quit\f[R] statement causes bc(1) to quit, even if it is on a
branch that will not be executed (it is a compile-time command).
.PP
The \f[B]halt\f[R] statement causes bc(1) to quit, if it is executed.
(Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement
that is not executed, bc(1) does not quit.)
.PP
The \f[B]limits\f[R] statement prints the limits that this bc(1) is
subject to.
This is like the \f[B]quit\f[R] statement in that it is a compile-time
command.
.PP
An expression by itself is evaluated and printed, followed by a newline.
.PP
Both scientific notation and engineering notation are available for
printing the results of expressions.
Scientific notation is activated by assigning \f[B]0\f[R] to
\f[B]obase\f[R], and engineering notation is activated by assigning
\f[B]1\f[R] to \f[B]obase\f[R].
To deactivate them, just assign a different value to \f[B]obase\f[R].
.PP
Scientific notation and engineering notation are disabled if bc(1) is
run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options
(or equivalents).
.PP
Printing numbers in scientific notation and/or engineering notation is a
\f[B]non-portable extension\f[R].
.SS Strings
.PP
If strings appear as a statement by themselves, they are printed without
a trailing newline.
.PP
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements.
They can also be passed to functions in variable parameters.
.PP
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
.PP
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section).
.PP
Assigning strings to variables and array elements and passing them to
functions are \f[B]non-portable extensions\f[R].
.SS Print Statement
.PP
The \[lq]expressions\[rq] in a \f[B]print\f[R] statement may also be
strings.
If they are, there are backslash escape sequences that are interpreted
specially.
What those sequences are, and what they cause to be printed, are shown
below:
.PP
\f[B]\[rs]a\f[R]: \f[B]\[rs]a\f[R]
.PP
\f[B]\[rs]b\f[R]: \f[B]\[rs]b\f[R]
.PP
\f[B]\[rs]\[rs]\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]e\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]f\f[R]: \f[B]\[rs]f\f[R]
.PP
\f[B]\[rs]n\f[R]: \f[B]\[rs]n\f[R]
.PP
\f[B]\[rs]q\f[R]: \f[B]\[lq]\f[R]
.PP
\f[B]\[rs]r\f[R]: \f[B]\[rs]r\f[R]
.PP
\f[B]\[rs]t\f[R]: \f[B]\[rs]t\f[R]
.PP
Any other character following a backslash causes the backslash and
character to be printed as-is.
.PP
Any non-string expression in a print statement shall be assigned to
\f[B]last\f[R], like any other expression that is printed.
.SS Stream Statement
.PP
The \[lq]expressions in a \f[B]stream\f[R] statement may also be
strings.
.PP
If a \f[B]stream\f[R] statement is given a string, it prints the string
as though the string had appeared as its own statement.
In other words, the \f[B]stream\f[R] statement prints strings normally,
without a newline.
.PP
If a \f[B]stream\f[R] statement is given a number, a copy of it is
truncated and its absolute value is calculated.
The result is then printed as though \f[B]obase\f[R] is \f[B]256\f[R]
and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
.SS Order of Evaluation
.PP
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations.
This means, for example, assuming that \f[B]i\f[R] is equal to
\f[B]0\f[R], in the expression
.IP
.nf
\f[C]
a[i++] = i++
\f[R]
.fi
.PP
the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and
\f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression.
.PP
This includes function arguments.
Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in
the expression
.IP
.nf
\f[C]
x(i++, i++)
\f[R]
.fi
.PP
the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the
second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to
\f[B]2\f[R] before the function starts executing.
.SH FUNCTIONS
.PP
Function definitions are as follows:
.IP
.nf
\f[C]
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
\f[R]
.fi
.PP
Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be
replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an
array, and any \f[B]I\f[R] in the parameter list may be replaced with
\f[B]*I[]\f[R] to make a parameter an array reference.
Callers of functions that take array references should not put an
asterisk in the call; they must be called with just \f[B]I[]\f[R] like
normal array parameters and will be automatically converted into
references.
.PP
As a \f[B]non-portable extension\f[R], the opening brace of a
\f[B]define\f[R] statement may appear on the next line.
.PP
As a \f[B]non-portable extension\f[R], the return statement may also be
in one of the following forms:
.IP "1." 3
\f[B]return\f[R]
.IP "2." 3
\f[B]return\f[R] \f[B](\f[R] \f[B])\f[R]
.IP "3." 3
\f[B]return\f[R] \f[B]E\f[R]
.PP
The first two, or not specifying a \f[B]return\f[R] statement, is
equivalent to \f[B]return (0)\f[R], unless the function is a
\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection
below).
.SS Void Functions
.PP
Functions can also be \f[B]void\f[R] functions, defined as follows:
.IP
.nf
\f[C]
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
\f[R]
.fi
.PP
They can only be used as standalone expressions, where such an
expression would be printed alone, except in a print statement.
.PP
Void functions can only use the first two \f[B]return\f[R] statements
listed above.
They can also omit the return statement entirely.
.PP
The word \[lq]void\[rq] is not treated as a keyword; it is still
possible to have variables, arrays, and functions named \f[B]void\f[R].
The word \[lq]void\[rq] is only treated specially right after the
\f[B]define\f[R] keyword.
.PP
This is a \f[B]non-portable extension\f[R].
.SS Array References
.PP
For any array in the parameter list, if the array is declared in the
form
.IP
.nf
\f[C]
*I[]
\f[R]
.fi
.PP
it is a \f[B]reference\f[R].
Any changes to the array in the function are reflected, when the
function returns, to the array that was passed in.
.PP
Other than this, all function arguments are passed by value.
.PP
This is a \f[B]non-portable extension\f[R].
.SH LIBRARY
.PP
All of the functions below, including the functions in the extended math
library (see the \f[I]Extended Library\f[R] subsection below), are
available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line
flags are given, except that the extended math library is not available
when the \f[B]-s\f[R] option, the \f[B]-w\f[R] option, or equivalents
are given.
.SS Standard Library
.PP
The
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
defines the following functions for the math library:
.TP
\f[B]s(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]c(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l(x)\f[R]
Returns the natural logarithm of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]e(x)\f[R]
Returns the mathematical constant \f[B]e\f[R] raised to the power of
\f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]j(x, n)\f[R]
Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.SS Extended Library
.PP
The extended library is \f[I]not\f[R] loaded when the
\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R]
options are given since they are not part of the library defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
.PP
The extended library is a \f[B]non-portable extension\f[R].
.TP
\f[B]p(x, y)\f[R]
Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R]
is not an integer, and returns the result to the current
\f[B]scale\f[R].
.RS
.PP
It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is
\f[B]0\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]r(x, p)\f[R]
Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to
the rounding mode round half away from
\f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero).
.TP
\f[B]ceil(x, p)\f[R]
Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to
the rounding mode round away from
\f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero).
.TP
\f[B]f(x)\f[R]
Returns the factorial of the truncated absolute value of \f[B]x\f[R].
.TP
\f[B]perm(n, k)\f[R]
Returns the permutation of the truncated absolute value of \f[B]n\f[R]
of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R].
If not, it returns \f[B]0\f[R].
.TP
\f[B]comb(n, k)\f[R]
Returns the combination of the truncated absolute value of \f[B]n\f[R]
of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R].
If not, it returns \f[B]0\f[R].
.TP
\f[B]l2(x)\f[R]
Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l10(x)\f[R]
Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]log(x, b)\f[R]
Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]cbrt(x)\f[R]
Returns the cube root of \f[B]x\f[R].
.TP
\f[B]root(x, n)\f[R]
Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns
the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R].
.RS
.PP
If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and
causes bc(1) to reset (see the \f[B]RESET\f[R] section).
It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even
and \f[B]x\f[R] is negative.
.RE
.TP
\f[B]gcd(a, b)\f[R]
Returns the greatest common divisor (factor) of the truncated absolute
value of \f[B]a\f[R] and the truncated absolute value of \f[B]b\f[R].
.TP
\f[B]lcm(a, b)\f[R]
Returns the least common multiple of the truncated absolute value of
\f[B]a\f[R] and the truncated absolute value of \f[B]b\f[R].
.TP
\f[B]pi(p)\f[R]
Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]t(x)\f[R]
Returns the tangent of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a2(y, x)\f[R]
Returns the arctangent of \f[B]y/x\f[R], in radians.
If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises
an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns
\f[B]a(y/x)\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than
or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than
\f[B]0\f[R], it returns \f[B]pi/2\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]-pi/2\f[R].
.RS
.PP
This function is the same as the \f[B]atan2()\f[R] function in many
programming languages.
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]sin(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is an alias of \f[B]s(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]cos(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is an alias of \f[B]c(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]tan(x)\f[R]
Returns the tangent of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an
error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
.PP
This is an alias of \f[B]t(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]atan(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is an alias of \f[B]a(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]atan2(y, x)\f[R]
Returns the arctangent of \f[B]y/x\f[R], in radians.
If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises
an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns
\f[B]a(y/x)\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than
or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than
\f[B]0\f[R], it returns \f[B]pi/2\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]-pi/2\f[R].
.RS
.PP
This function is the same as the \f[B]atan2()\f[R] function in many
programming languages.
.PP
This is an alias of \f[B]a2(y, x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]r2d(x)\f[R]
Converts \f[B]x\f[R] from radians to degrees and returns the result.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]d2r(x)\f[R]
Converts \f[B]x\f[R] from degrees to radians and returns the result.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]frand(p)\f[R]
Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and
\f[B]1\f[R] (exclusive) with the number of decimal digits after the
decimal point equal to the truncated absolute value of \f[B]p\f[R].
If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will
change the value of \f[B]seed\f[R].
If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and
\f[B]seed\f[R] is \f[I]not\f[R] changed.
.TP
\f[B]ifrand(i, p)\f[R]
Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive)
and the truncated absolute value of \f[B]i\f[R] (exclusive) with the
number of decimal digits after the decimal point equal to the truncated
absolute value of \f[B]p\f[R].
If the absolute value of \f[B]i\f[R] is greater than or equal to
\f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this
function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R]
is returned and \f[B]seed\f[R] is not changed.
.TP
\f[B]srand(x)\f[R]
Returns \f[B]x\f[R] with its sign flipped with probability
\f[B]0.5\f[R].
In other words, it randomizes the sign of \f[B]x\f[R].
.TP
\f[B]brand()\f[R]
Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]).
.TP
\f[B]band(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]and\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bor(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]or\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bxor(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]xor\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bshl(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of \f[B]a\f[R] bit-shifted left by
\f[B]b\f[R] places.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bshr(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the truncated result of \f[B]a\f[R]
bit-shifted right by \f[B]b\f[R] places.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnotn(x, n)\f[R]
Takes the truncated absolute value of \f[B]x\f[R] and does a bitwise not
as though it has the same number of bytes as the truncated absolute
value of \f[B]n\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot8(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]8\f[R] binary digits (1 unsigned byte).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot16(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]16\f[R] binary digits (2 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot32(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]32\f[R] binary digits (4 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot64(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]64\f[R] binary digits (8 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has the minimum number of power of two unsigned bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brevn(x, n)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has the same number of 8-bit bytes as the truncated absolute
value of \f[B]n\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev8(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 8 binary digits (1 unsigned byte).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev16(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 16 binary digits (2 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev32(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 32 binary digits (4 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev64(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 64 binary digits (8 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has the minimum number of power of two unsigned bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]broln(x, p, n)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the same number of unsigned 8-bit bytes as
the truncated absolute value of \f[B]n\f[R], by the number of places
equal to the truncated absolute value of \f[B]p\f[R] modded by the
\f[B]2\f[R] to the power of the number of binary digits in \f[B]n\f[R]
8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol8(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]8\f[R] binary digits (\f[B]1\f[R]
unsigned byte), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol16(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]16\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol32(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol64(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the minimum number of power of two
unsigned 8-bit bytes, by the number of places equal to the truncated
absolute value of \f[B]p\f[R] modded by 2 to the power of the number of
binary digits in the minimum number of 8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brorn(x, p, n)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the same number of unsigned 8-bit bytes as
the truncated absolute value of \f[B]n\f[R], by the number of places
equal to the truncated absolute value of \f[B]p\f[R] modded by the
\f[B]2\f[R] to the power of the number of binary digits in \f[B]n\f[R]
8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror8(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]8\f[R] binary digits (\f[B]1\f[R]
unsigned byte), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror16(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]16\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror32(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror64(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the minimum number of power of two
unsigned 8-bit bytes, by the number of places equal to the truncated
absolute value of \f[B]p\f[R] modded by 2 to the power of the number of
binary digits in the minimum number of 8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmodn(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of the multiplication of the truncated absolute
value of \f[B]n\f[R] and \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod8(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod16(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod32(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod64(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bunrev(t)\f[R]
Assumes \f[B]t\f[R] is a bitwise-reversed number with an extra set bit
one place more significant than the real most significant bit (which was
the least significant bit in the original number).
This number is reversed and returned without the extra set bit.
.RS
.PP
This function is used to implement other bitwise functions; it is not
meant to be used by users, but it can be.
.RE
.TP
+\f[B]plz(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed with a leading zero, regardless
+of the use of the \f[B]-z\f[R] option (see the \f[B]OPTIONS\f[R]
+section) and without a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, without a trailing newline.
+.RE
+.TP
+\f[B]plznl(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed with a leading zero, regardless
+of the use of the \f[B]-z\f[R] option (see the \f[B]OPTIONS\f[R]
+section) and with a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, with a trailing newline.
+.RE
+.TP
+\f[B]pnlz(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed without a leading zero,
+regardless of the use of the \f[B]-z\f[R] option (see the
+\f[B]OPTIONS\f[R] section) and without a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, without a trailing newline.
+.RE
+.TP
+\f[B]pnlznl(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed without a leading zero,
+regardless of the use of the \f[B]-z\f[R] option (see the
+\f[B]OPTIONS\f[R] section) and with a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, with a trailing newline.
+.RE
+.TP
\f[B]ubytes(x)\f[R]
Returns the numbers of unsigned integer bytes required to hold the
truncated absolute value of \f[B]x\f[R].
.TP
\f[B]sbytes(x)\f[R]
Returns the numbers of signed, two\[cq]s-complement integer bytes
required to hold the truncated value of \f[B]x\f[R].
.TP
\f[B]s2u(x)\f[R]
Returns \f[B]x\f[R] if it is non-negative.
If it \f[I]is\f[R] negative, then it calculates what \f[B]x\f[R] would
be as a 2\[cq]s-complement signed integer and returns the non-negative
integer that would have the same representation in binary.
.TP
\f[B]s2un(x,n)\f[R]
Returns \f[B]x\f[R] if it is non-negative.
If it \f[I]is\f[R] negative, then it calculates what \f[B]x\f[R] would
be as a 2\[cq]s-complement signed integer with \f[B]n\f[R] bytes and
returns the non-negative integer that would have the same representation
in binary.
If \f[B]x\f[R] cannot fit into \f[B]n\f[R] 2\[cq]s-complement signed
bytes, it is truncated to fit.
.TP
\f[B]hex(x)\f[R]
Outputs the hexadecimal (base \f[B]16\f[R]) representation of
\f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]binary(x)\f[R]
Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output(x, b)\f[R]
Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in as few power of two bytes as possible.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or is negative, an error message is
printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R]
section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in as few power of two bytes as
possible.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, an error message is printed instead,
but bc(1) is not reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uintn(x, n)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]n\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]intn(x, n)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint8(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]1\f[R] byte.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int8(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an
error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint16(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]2\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int16(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint32(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]4\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int32(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint64(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]8\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int64(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]hex_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R]
bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]binary_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see
the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output_byte(x, i)\f[R]
Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R],
where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes
- 1\f[R] is the most significant byte.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.SS Transcendental Functions
.PP
All transcendental functions can return slightly inaccurate results (up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)).
This is unavoidable, and this
article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains
why it is impossible and unnecessary to calculate exact results for the
transcendental functions.
.PP
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (\f[B]scale\f[R]) set to at least 1 higher
than is necessary.
If exact results are \f[I]absolutely\f[R] required, users can double the
precision (\f[B]scale\f[R]) and then truncate.
.PP
The transcendental functions in the standard math library are:
.IP \[bu] 2
\f[B]s(x)\f[R]
.IP \[bu] 2
\f[B]c(x)\f[R]
.IP \[bu] 2
\f[B]a(x)\f[R]
.IP \[bu] 2
\f[B]l(x)\f[R]
.IP \[bu] 2
\f[B]e(x)\f[R]
.IP \[bu] 2
\f[B]j(x, n)\f[R]
.PP
The transcendental functions in the extended math library are:
.IP \[bu] 2
\f[B]l2(x)\f[R]
.IP \[bu] 2
\f[B]l10(x)\f[R]
.IP \[bu] 2
\f[B]log(x, b)\f[R]
.IP \[bu] 2
\f[B]pi(p)\f[R]
.IP \[bu] 2
\f[B]t(x)\f[R]
.IP \[bu] 2
\f[B]a2(y, x)\f[R]
.IP \[bu] 2
\f[B]sin(x)\f[R]
.IP \[bu] 2
\f[B]cos(x)\f[R]
.IP \[bu] 2
\f[B]tan(x)\f[R]
.IP \[bu] 2
\f[B]atan(x)\f[R]
.IP \[bu] 2
\f[B]atan2(y, x)\f[R]
.IP \[bu] 2
\f[B]r2d(x)\f[R]
.IP \[bu] 2
\f[B]d2r(x)\f[R]
.SH RESET
.PP
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets.
This means that several things happen.
.PP
First, any functions 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.
.PP
Thus, when bc(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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.PP
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This bc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R]
can be queried with the \f[B]limits\f[R] statement.
.PP
In addition, this bc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bc(1):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bc(1) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]rand()\f[R]
operand.
Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
The actual values can be queried with the \f[B]limits\f[R] statement.
.PP
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
.PP
bc(1) recognizes the following environment variables:
.TP
\f[B]POSIXLY_CORRECT\f[R]
If this variable exists (no matter the contents), bc(1) behaves as if
the \f[B]-s\f[R] option was given.
.TP
\f[B]BC_ENV_ARGS\f[R]
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line arguments.
These are always processed first, so any files given in
\f[B]BC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 bc(1) runs.
.RS
.PP
The code that parses \f[B]BC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`bc' file.bc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]BC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]BC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length,
including the backslash (\f[B]\[rs]\f[R]).
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]BC_BANNER\f[R]
If this environment variable exists and contains an integer, then a
non-zero value activates the copyright banner when bc(1) is in
interactive mode, while zero deactivates it.
.RS
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
does not print the banner when not in interactive mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_SIGINT_RESET\f[R]
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes bc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then bc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use
TTY mode, and zero makes bc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a
prompt, and zero or a non-integer makes bc(1) not use a prompt.
If this environment variable does not exist and \f[B]BC_TTY_MODE\f[R]
does, then the value of the \f[B]BC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]BC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
bc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], 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, overflow when calculating the size of a number, and attempting
to use a non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift
(\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their
corresponding assignment operators.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an invalid
print statement, giving an invalid function definition, attempting to
assign to an expression that is not a named expression (see the
\f[I]Named Expressions\f[R] subsection of the \f[B]SYNTAX\f[R] section),
giving an invalid \f[B]auto\f[R] list, having a duplicate
\f[B]auto\f[R]/function parameter, failing to find the end of a code
block, attempting to return a value from a \f[B]void\f[R] function,
attempting to use a variable as a reference, and using any extensions
when the option \f[B]-s\f[R] or any equivalents were given.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors, passing the wrong number of
arguments to functions, attempting to call an undefined function, and
attempting to use a \f[B]void\f[R] function call as a value in an
expression.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
Fatal errors include memory allocation errors, I/O errors, failing to
open files, attempting to use files that do not have only ASCII
characters (bc(1) only accepts ASCII characters), attempting to open a
directory as a file, and giving invalid command-line options.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, bc(1)
always exits and returns \f[B]4\f[R], no matter what mode bc(1) is in.
.PP
The other statuses will only be returned when bc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
bc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Per the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, bc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
bc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]BC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, bc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]BC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, bc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]BC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then bc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]BC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Command-Line History
.PP
Command-line history is only enabled if TTY mode is, i.e., that
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to
a TTY and the \f[B]BC_TTY_MODE\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section) and its default do not disable
TTY mode.
See the \f[B]COMMAND LINE HISTORY\f[R] section for more information.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]BC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]BC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]BC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]BC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause bc(1) to do one of two things.
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, bc(1) will exit.
.PP
However, if bc(1) is in interactive mode, and the
\f[B]BC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then bc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If bc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If bc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] is sent to bc(1) as it is
executing a file, it can seem as though bc(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
bc(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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause bc(1) to clean up and
exit, and it uses the default handler for all other signals.
The one exception is \f[B]SIGHUP\f[R]; in that case, and only when bc(1)
is in TTY mode (see the \f[B]TTY MODE\f[R] section), a \f[B]SIGHUP\f[R]
will cause bc(1) to clean up and exit.
.SH COMMAND LINE HISTORY
.PP
bc(1) supports interactive command-line editing.
.PP
If bc(1) can be in TTY mode (see the \f[B]TTY MODE\f[R] section),
history can be enabled.
This means that command-line history can only be enabled when
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY.
.PP
Like TTY mode itself, it can be turned on or off with the environment
variable \f[B]BC_TTY_MODE\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If history is enabled, previous lines can be recalled and edited with
the arrow keys.
.PP
\f[B]Note\f[R]: tabs are converted to 8 spaces.
.SH LOCALES
.PP
This bc(1) ships with support for adding error messages for different
locales and thus, supports \f[B]LC_MESSAGES\f[R].
.SH SEE ALSO
.PP
dc(1)
.SH STANDARDS
.PP
bc(1) is compliant with the IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
The flags \f[B]-efghiqsvVw\f[R], all long options, and the extensions
noted above are extensions to that specification.
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
.PP
This bc(1) supports error messages for different locales, and thus, it
supports \f[B]LC_MESSAGES\f[R].
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bc/A.1.md b/manuals/bc/A.1.md
index 9ab4665e9ebd..e773d967284c 100644
--- a/manuals/bc/A.1.md
+++ b/manuals/bc/A.1.md
@@ -1,2285 +1,2347 @@
# NAME
bc - arbitrary-precision decimal arithmetic language and calculator
# SYNOPSIS
**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# DESCRIPTION
bc(1) is an interactive processor for a language first standardized in 1991 by
POSIX. (The current standard is [here][1].) The language provides unlimited
precision decimal arithmetic and is somewhat C-like, but there are differences.
Such differences will be noted in this document.
After parsing and handling options, this bc(1) reads any files given on the
command line and executes them before reading from **stdin**.
This bc(1) is a drop-in replacement for *any* bc(1), including (and
especially) the GNU bc(1). It also has many extensions and extra features beyond
other implementations.
**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
parse error, it is probably because a word this bc(1) reserves as a keyword is
used as the name of a function, variable, or array. To fix that, use the
command-line option **-r** *keyword*, where *keyword* is the keyword that is
used as a name in the script. For more information, see the **OPTIONS** section.
If parsing scripts meant for other bc(1) implementations still does not work,
that is a bug and should be reported. See the **BUGS** section.
# OPTIONS
The following are the options that bc(1) accepts.
**-g**, **-\-global-stacks**
: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks.
This has the effect that a copy of the current value of all four are pushed
onto a stack for every function call, as well as popped when every function
returns. This means that functions can assign to any and all of those
globals without worrying that the change will affect other functions.
Thus, a hypothetical function named **output(x,b)** that simply printed
**x** in base **b** could be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
(**Note**: the function **output(x,b)** exists in the extended math library.
See the **LIBRARY** section.)
However, since using this flag means that functions cannot set **ibase**,
**obase**, **scale**, or **seed** globally, functions that are made to do so
cannot work anymore. There are two possible use cases for that, and each has
a solution.
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set **ibase**, **obase**,
**scale**, or **seed** globally for any other purpose, it could be split
into one to four functions (based on how many globals it sets) and each of
those functions could return the desired value for a global.
For functions that set **seed**, the value assigned to **seed** is not
propagated to parent functions. This means that the sequence of
pseudo-random numbers that they see will not be the same sequence of
pseudo-random numbers that any parent sees. This is only the case once
**seed** has been set.
If a function desires to not affect the sequence of pseudo-random numbers
of its parents, but wants to use the same **seed**, it can use the following
line:
seed = seed
If the behavior of this option is desired for every run of bc(1), then users
could make sure to define **BC_ENV_ARGS** and include this option (see the
**ENVIRONMENT VARIABLES** section for more details).
If **-s**, **-w**, or any equivalents are used, this option is ignored.
This is a **non-portable extension**.
**-h**, **-\-help**
: Prints a usage message and quits.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-l**, **-\-mathlib**
: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
math library and the extended math library before running any code,
including any expressions or files specified on the command line.
To learn what is in the libraries, see the **LIBRARY** section.
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in bc(1). Most of those users
would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section).
These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of bc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **read()** built-in function is called.
These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-r** *keyword*, **-\-redefine**=*keyword*
: Redefines *keyword* in order to allow it to be used as a function, variable,
or array name. This is useful when this bc(1) gives parse errors when
parsing scripts meant for other bc(1) implementations.
The keywords this bc(1) allows to be redefined are:
* **abs**
* **asciify**
* **continue**
* **divmod**
* **else**
* **halt**
* **irand**
* **last**
* **limits**
* **maxibase**
* **maxobase**
* **maxrand**
* **maxscale**
* **modexp**
* **print**
* **rand**
* **read**
* **seed**
* **stream**
If any of those keywords are used as a function, variable, or array name in
a script, use this option with the keyword as the argument. If multiple are
used, use this option for all of them; it can be used multiple times.
Keywords are *not* redefined when parsing the builtin math library (see the
**LIBRARY** section).
It is a fatal error to redefine keywords mandated by the POSIX standard. It
is a fatal error to attempt to redefine words that this bc(1) does not
reserve as keywords.
**-q**, **-\-quiet**
: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
Without this option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the **-v**, **-V**, or
**-\-version** options are given.
This is a **non-portable extension**.
**-s**, **-\-standard**
: Process exactly the language defined by the [standard][1] and error if any
extensions are used.
This is a **non-portable extension**.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
This is a **non-portable extension**.
**-w**, **-\-warn**
: Like **-s** and **-\-standard**, except that warnings (and not errors) are
printed for non-standard extensions and execution continues normally.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
**-\-expression** options, then bc(1) read from **stdin**.
However, there are a few caveats to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
the parse cannot complete. That means that starting a string without ending it
or starting a function, **if** statement, or loop without ending it will also
cause bc(1) to not execute.
Second, after an **if** statement, bc(1) doesn't know if an **else** statement
will follow, so it will not execute until it knows there will not be an **else**
statement.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **bc >&-**, it will quit with an error. This
is done so that bc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This
is done so that bc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences. This
bc(1) follows the [POSIX standard][1], which is a much more thorough resource
for the language this bc(1) accepts. This section is meant to be a summary and a
listing of all the extensions to the standard.
In the sections below, **E** means expression, **S** means statement, and **I**
means identifier.
Identifiers (**I**) start with a lowercase letter and can be followed by any
number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
Identifiers with more than one character (letter) are a
**non-portable extension**.
**ibase** is a global variable determining how to interpret constant numbers. It
is the "input" base, or the number base used for interpreting input numbers.
**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
(**-\-warn**) flags were not given on the command line, the max allowable value
for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
**ibase** is **2**. The max allowable value for **ibase** can be queried in
bc(1) programs with the **maxibase()** built-in function.
**obase** is a global variable determining how to output results. It is the
"output" base, or the number base used for outputting numbers. **obase** is
initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
can be queried in bc(1) programs with the **maxobase()** built-in function. The
min allowable value for **obase** is **0**. If **obase** is **0**, values are
output in scientific notation, and if **obase** is **1**, values are output in
engineering notation. Otherwise, values are output in the specified base.
Outputting in scientific and engineering notations are **non-portable
extensions**.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a global variable that
sets the precision of any operations, with exceptions. **scale** is initially
**0**. **scale** cannot be negative. The max allowable value for **scale** is
**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
built-in function.
bc(1) has both *global* variables and *local* variables. All *local*
variables are local to the function; they are parameters or are introduced in
the **auto** list of a function (see the **FUNCTIONS** section). If a variable
is accessed which is not a parameter or in the **auto** list, it is assumed to
be *global*. If a parent function has a *local* variable version of a variable
that a child function considers *global*, the value of that *global* variable in
the child function is the value of the variable in the parent function, not the
value of the actual *global* variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence operator is an
assignment operator *and* the expression is notsurrounded by parentheses.
The value that is printed is also assigned to the special variable **last**. A
single dot (**.**) may also be used as a synonym for **last**. These are
**non-portable extensions**.
Either semicolons or newlines may separate statements.
## Comments
There are two kinds of comments:
1. Block comments are enclosed in **/\*** and **\*/**.
2. Line comments go from **#** until, and not including, the next newline. This
is a **non-portable extension**.
## Named Expressions
The following are named expressions in bc(1):
1. Variables: **I**
2. Array Elements: **I[E]**
3. **ibase**
4. **obase**
5. **scale**
6. **seed**
7. **last** or a single dot (**.**)
Numbers 6 and 7 are **non-portable extensions**.
The meaning of **seed** is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major versions.
The *scale* and sign of the value may be significant.
If a previously used **seed** value is assigned to **seed** and used again, the
pseudo-random number generator is guaranteed to produce the same sequence of
pseudo-random numbers as it did when the **seed** value was previously used.
The exact value assigned to **seed** is not guaranteed to be returned if
**seed** is queried again immediately. However, if **seed** *does* return a
different value, both values, when assigned to **seed**, are guaranteed to
produce the same sequence of pseudo-random numbers. This means that certain
values assigned to **seed** will *not* produce unique sequences of pseudo-random
numbers. The value of **seed** will change after any use of the **rand()** and
**irand(E)** operands (see the *Operands* subsection below), except if the
parameter passed to **irand(E)** is **0**, **1**, or negative.
There is no limit to the length (number of significant decimal digits) or
*scale* of the value that can be assigned to **seed**.
Variables and arrays do not interfere; users can have arrays named the same as
variables. This also applies to functions (see the **FUNCTIONS** section), so a
user can have a variable, array, and function that all have the same name, and
they will not shadow each other, whether inside of functions or not.
Named expressions are required as the operand of **increment**/**decrement**
operators and as the left side of **assignment** operators (see the *Operators*
subsection).
## Operands
The following are valid operands in bc(1):
1. Numbers (see the *Numbers* subsection below).
2. Array indices (**I[E]**).
3. **(E)**: The value of **E** (used to change precedence).
4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
5. **length(E)**: The number of significant decimal digits in **E**. Returns
**1** for **0** with no decimal places. If given a string, the length of the
string is returned. Passing a string to **length(E)** is a **non-portable
extension**.
6. **length(I[])**: The number of elements in the array **I**. This is a
**non-portable extension**.
7. **scale(E)**: The *scale* of **E**.
8. **abs(E)**: The absolute value of **E**. This is a **non-portable
extension**.
9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
the base, the second is the exponent, and the third is the modulus. All
three values must be integers. The second argument must be non-negative. The
third argument must be non-zero. This is a **non-portable extension**.
10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
optimization. The first expression is the dividend, and the second is the
divisor, which must be non-zero. The return value is the quotient, and the
modulus is stored in index **0** of the provided array (the last argument).
This is a **non-portable extension**.
11. **asciify(E)**: If **E** is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number mod **256**
and returns that number as a one-character string. This is a **non-portable
extension**.
12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a non-**void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
13. **read()**: Reads a line from **stdin** and uses that as an expression. The
result of that expression is the result of the **read()** operand. This is a
**non-portable extension**.
14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
extension**.
15. **maxobase()**: The max allowable **obase**. This is a **non-portable
extension**.
16. **maxscale()**: The max allowable **scale**. This is a **non-portable
extension**.
-17. **rand()**: A pseudo-random integer between **0** (inclusive) and
+17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
+ **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
+18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
+ or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
+ or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+20. **rand()**: A pseudo-random integer between **0** (inclusive) and
**BC_RAND_MAX** (inclusive). Using this operand will change the value of
**seed**. This is a **non-portable extension**.
-18. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
+21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
value of **E** (exclusive). If **E** is negative or is a non-integer
(**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see
the **RESET** section) while **seed** remains unchanged. If **E** is larger
than **BC_RAND_MAX**, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
**BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that
can be generated with this operand is unbounded. Using this operand will
change the value of **seed**, unless the value of **E** is **0** or **1**.
In that case, **0** is returned, and **seed** is *not* changed. This is a
**non-portable extension**.
-19. **maxrand()**: The max integer returned by **rand()**. This is a
+22. **maxrand()**: The max integer returned by **rand()**. This is a
**non-portable extension**.
The integers generated by **rand()** and **irand(E)** are guaranteed to be as
unbiased as possible, subject to the limitations of the pseudo-random number
generator.
**Note**: The values returned by the pseudo-random number generator with
**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator. However,
they *are* guaranteed to be reproducible with identical **seed** values. This
means that the pseudo-random values from bc(1) should only be used where a
reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
use a non-seeded pseudo-random number generator.
## Numbers
Numbers are strings made up of digits, uppercase letters, and at most **1**
period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
letters are equal to **9** + their position in the alphabet (i.e., **A** equals
**10**, or **9+1**). If a digit or letter makes no sense with the current value
of **ibase**, they are set to the value of the highest valid digit in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **Z** alone always equals decimal
**35**.
In addition, bc(1) accepts numbers in scientific notation. These have the form
**\e\**. The exponent (the portion after the **e**) must be
an integer. An example is **1.89237e9**, which is equal to **1892370000**.
Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**.
Using scientific notation is an error or warning if the **-s** or **-w**,
respectively, command-line options (or equivalents) are given.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For example,
if **ibase** is **16** and bc(1) is given the number string **FFeA**, the
resulting decimal number will be **2550000000000**, and if bc(1) is given the
number string **10e-4**, the resulting decimal number will be **0.0016**.
Accepting input as scientific notation is a **non-portable extension**.
## Operators
The following arithmetic and logical operators can be used. They are listed in
order of decreasing precedence. Operators in the same group have the same
precedence.
**++** **-\-**
: Type: Prefix and Postfix
Associativity: None
Description: **increment**, **decrement**
**-** **!**
: Type: Prefix
Associativity: None
Description: **negation**, **boolean not**
**\$**
: Type: Postfix
Associativity: None
Description: **truncation**
**\@**
: Type: Binary
Associativity: Right
Description: **set precision**
**\^**
: Type: Binary
Associativity: Right
Description: **power**
**\*** **/** **%**
: Type: Binary
Associativity: Left
Description: **multiply**, **divide**, **modulus**
**+** **-**
: Type: Binary
Associativity: Left
Description: **add**, **subtract**
**\<\<** **\>\>**
: Type: Binary
Associativity: Left
Description: **shift left**, **shift right**
**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
: Type: Binary
Associativity: Right
Description: **assignment**
**==** **\<=** **\>=** **!=** **\<** **\>**
: Type: Binary
Associativity: Left
Description: **relational**
**&&**
: Type: Binary
Associativity: Left
Description: **boolean and**
**||**
: Type: Binary
Associativity: Left
Description: **boolean or**
The operators will be described in more detail below.
**++** **-\-**
: The prefix and postfix **increment** and **decrement** operators behave
exactly like they would in C. They require a named expression (see the
*Named Expressions* subsection) as an operand.
The prefix versions of these operators are more efficient; use them where
possible.
**-**
: The **negation** operator returns **0** if a user attempts to negate any
expression with the value **0**. Otherwise, a copy of the expression with
its sign flipped is returned.
**!**
: The **boolean not** operator returns **1** if the expression is **0**, or
**0** otherwise.
This is a **non-portable extension**.
**\$**
: The **truncation** operator returns a copy of the given expression with all
of its *scale* removed.
This is a **non-portable extension**.
**\@**
: The **set precision** operator takes two expressions and returns a copy of
the first with its *scale* equal to the value of the second expression. That
could either mean that the number is returned without change (if the
*scale* of the first expression matches the value of the second
expression), extended (if it is less), or truncated (if it is more).
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**\^**
: The **power** operator (not the **exclusive or** operator, as it would be in
C) takes two expressions and raises the first to the power of the value of
the second. The *scale* of the result is equal to **scale**.
The second expression must be an integer (no *scale*), and if it is
negative, the first value must be non-zero.
**\***
: The **multiply** operator takes two expressions, multiplies them, and
returns the product. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result is
equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The **divide** operator takes two expressions, divides them, and returns the
quotient. The *scale* of the result shall be the value of **scale**.
The second expression must be non-zero.
**%**
: The **modulus** operator takes two expressions, **a** and **b**, and
evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The second expression must be non-zero.
**+**
: The **add** operator takes two expressions, **a** and **b**, and returns the
sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
**-**
: The **subtract** operator takes two expressions, **a** and **b**, and
returns the difference, with a *scale* equal to the max of the *scale*s of
**a** and **b**.
**\<\<**
: The **left shift** operator takes two expressions, **a** and **b**, and
returns a copy of the value of **a** with its decimal point moved **b**
places to the right.
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**\>\>**
: The **right shift** operator takes two expressions, **a** and **b**, and
returns a copy of the value of **a** with its decimal point moved **b**
places to the left.
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
: The **assignment** operators take two expressions, **a** and **b** where
**a** is a named expression (see the *Named Expressions* subsection).
For **=**, **b** is copied and the result is assigned to **a**. For all
others, **a** and **b** are applied as operands to the corresponding
arithmetic operator and the result is assigned to **a**.
The **assignment** operators that correspond to operators that are
extensions are themselves **non-portable extensions**.
**==** **\<=** **\>=** **!=** **\<** **\>**
: The **relational** operators compare two expressions, **a** and **b**, and
if the relation holds, according to C language semantics, the result is
**1**. Otherwise, it is **0**.
Note that unlike in C, these operators have a lower precedence than the
**assignment** operators, which means that **a=b\>c** is interpreted as
**(a=b)\>c**.
Also, unlike the [standard][1] requires, these operators can appear anywhere
any other expressions can be used. This allowance is a
**non-portable extension**.
**&&**
: The **boolean and** operator takes two expressions and returns **1** if both
expressions are non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
**||**
: The **boolean or** operator takes two expressions and returns **1** if one
of the expressions is non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
## Statements
The following items are statements:
1. **E**
2. **{** **S** **;** ... **;** **S** **}**
3. **if** **(** **E** **)** **S**
4. **if** **(** **E** **)** **S** **else** **S**
5. **while** **(** **E** **)** **S**
6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
7. An empty statement
8. **break**
9. **continue**
10. **quit**
11. **halt**
12. **limits**
13. A string of characters, enclosed in double quotes
14. **print** **E** **,** ... **,** **E**
15. **stream** **E** **,** ... **,** **E**
16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
Also, as a **non-portable extension**, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expression) is
omitted, it is assumed to be a constant **1**.
The **break** statement causes a loop to stop iterating and resume execution
immediately following a loop. This is only allowed in loops.
The **continue** statement causes a loop iteration to stop early and returns to
the start of the loop, including testing the loop condition. This is only
allowed in loops.
The **if** **else** statement does the same thing as in C.
The **quit** statement causes bc(1) to quit, even if it is on a branch that will
not be executed (it is a compile-time command).
The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
if it is on a branch of an **if** statement that is not executed, bc(1) does not
quit.)
The **limits** statement prints the limits that this bc(1) is subject to. This
is like the **quit** statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a newline.
Both scientific notation and engineering notation are available for printing the
results of expressions. Scientific notation is activated by assigning **0** to
**obase**, and engineering notation is activated by assigning **1** to
**obase**. To deactivate them, just assign a different value to **obase**.
Scientific notation and engineering notation are disabled if bc(1) is run with
either the **-s** or **-w** command-line options (or equivalents).
Printing numbers in scientific notation and/or engineering notation is a
**non-portable extension**.
## Strings
If strings appear as a statement by themselves, they are printed without a
trailing newline.
In addition to appearing as a lone statement by themselves, strings can be
assigned to variables and array elements. They can also be passed to functions
in variable parameters.
If any statement that expects a string is given a variable that had a string
assigned to it, the statement acts as though it had received a string.
If any math operation is attempted on a string or a variable or array element
that has been assigned a string, an error is raised, and bc(1) resets (see the
**RESET** section).
Assigning strings to variables and array elements and passing them to functions
are **non-portable extensions**.
## Print Statement
The "expressions" in a **print** statement may also be strings. If they are, there
are backslash escape sequences that are interpreted specially. What those
sequences are, and what they cause to be printed, are shown below:
**\\a**: **\\a**
**\\b**: **\\b**
**\\\\**: **\\**
**\\e**: **\\**
**\\f**: **\\f**
**\\n**: **\\n**
**\\q**: **"**
**\\r**: **\\r**
**\\t**: **\\t**
Any other character following a backslash causes the backslash and character to
be printed as-is.
Any non-string expression in a print statement shall be assigned to **last**,
like any other expression that is printed.
## Stream Statement
The "expressions in a **stream** statement may also be strings.
If a **stream** statement is given a string, it prints the string as though the
string had appeared as its own statement. In other words, the **stream**
statement prints strings normally, without a newline.
If a **stream** statement is given a number, a copy of it is truncated and its
absolute value is calculated. The result is then printed as though **obase** is
**256** and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
## Order of Evaluation
All expressions in a statment are evaluated left to right, except as necessary
to maintain order of operations. This means, for example, assuming that **i** is
equal to **0**, in the expression
a[i++] = i++
the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
at the end of the expression.
This includes function arguments. Thus, assuming **i** is equal to **0**, this
means that in the expression
x(i++, i++)
the first argument passed to **x()** is **0**, and the second argument is **1**,
while **i** is equal to **2** before the function starts executing.
# FUNCTIONS
Function definitions are as follows:
```
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
```
Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
make a parameter or **auto** var an array, and any **I** in the parameter list
may be replaced with **\*I[]** to make a parameter an array reference. Callers
of functions that take array references should not put an asterisk in the call;
they must be called with just **I[]** like normal array parameters and will be
automatically converted into references.
As a **non-portable extension**, the opening brace of a **define** statement may
appear on the next line.
As a **non-portable extension**, the return statement may also be in one of the
following forms:
1. **return**
2. **return** **(** **)**
3. **return** **E**
The first two, or not specifying a **return** statement, is equivalent to
**return (0)**, unless the function is a **void** function (see the *Void
Functions* subsection below).
## Void Functions
Functions can also be **void** functions, defined as follows:
```
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
```
They can only be used as standalone expressions, where such an expression would
be printed alone, except in a print statement.
Void functions can only use the first two **return** statements listed above.
They can also omit the return statement entirely.
The word "void" is not treated as a keyword; it is still possible to have
variables, arrays, and functions named **void**. The word "void" is only
treated specially right after the **define** keyword.
This is a **non-portable extension**.
## Array References
For any array in the parameter list, if the array is declared in the form
```
*I[]
```
it is a **reference**. Any changes to the array in the function are reflected,
when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a **non-portable extension**.
# LIBRARY
All of the functions below, including the functions in the extended math
library (see the *Extended Library* subsection below), are available when the
**-l** or **-\-mathlib** command-line flags are given, except that the extended
math library is not available when the **-s** option, the **-w** option, or
equivalents are given.
## Standard Library
The [standard][1] defines the following functions for the math library:
**s(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**c(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a(x)**
: Returns the arctangent of **x**, in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l(x)**
: Returns the natural logarithm of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**e(x)**
: Returns the mathematical constant **e** raised to the power of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**j(x, n)**
: Returns the bessel integer order **n** (truncated) of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
## Extended Library
The extended library is *not* loaded when the **-s**/**-\-standard** or
**-w**/**-\-warn** options are given since they are not part of the library
defined by the [standard][1].
The extended library is a **non-portable extension**.
**p(x, y)**
: Calculates **x** to the power of **y**, even if **y** is not an integer, and
returns the result to the current **scale**.
It is an error if **y** is negative and **x** is **0**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**r(x, p)**
: Returns **x** rounded to **p** decimal places according to the rounding mode
[round half away from **0**][3].
**ceil(x, p)**
: Returns **x** rounded to **p** decimal places according to the rounding mode
[round away from **0**][6].
**f(x)**
: Returns the factorial of the truncated absolute value of **x**.
**perm(n, k)**
: Returns the permutation of the truncated absolute value of **n** of the
truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
**comb(n, k)**
: Returns the combination of the truncated absolute value of **n** of the
truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
**l2(x)**
: Returns the logarithm base **2** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l10(x)**
: Returns the logarithm base **10** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**log(x, b)**
: Returns the logarithm base **b** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**cbrt(x)**
: Returns the cube root of **x**.
**root(x, n)**
: Calculates the truncated value of **n**, **r**, and returns the **r**th root
of **x** to the current **scale**.
If **r** is **0** or negative, this raises an error and causes bc(1) to
reset (see the **RESET** section). It also raises an error and causes bc(1)
to reset if **r** is even and **x** is negative.
**gcd(a, b)**
: Returns the greatest common divisor (factor) of the truncated absolute value
of **a** and the truncated absolute value of **b**.
**lcm(a, b)**
: Returns the least common multiple of the truncated absolute value of **a**
and the truncated absolute value of **b**.
**pi(p)**
: Returns **pi** to **p** decimal places.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**t(x)**
: Returns the tangent of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a2(y, x)**
: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
equal to **0**, it raises an error and causes bc(1) to reset (see the
**RESET** section). Otherwise, if **x** is greater than **0**, it returns
**a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
**0**, and **y** is less than **0**, it returns **-pi/2**.
This function is the same as the **atan2()** function in many programming
languages.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**sin(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is an alias of **s(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**cos(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is an alias of **c(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**tan(x)**
: Returns the tangent of **x**, which is assumed to be in radians.
If **x** is equal to **1** or **-1**, this raises an error and causes bc(1)
to reset (see the **RESET** section).
This is an alias of **t(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**atan(x)**
: Returns the arctangent of **x**, in radians.
This is an alias of **a(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**atan2(y, x)**
: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
equal to **0**, it raises an error and causes bc(1) to reset (see the
**RESET** section). Otherwise, if **x** is greater than **0**, it returns
**a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
**0**, and **y** is less than **0**, it returns **-pi/2**.
This function is the same as the **atan2()** function in many programming
languages.
This is an alias of **a2(y, x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**r2d(x)**
: Converts **x** from radians to degrees and returns the result.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**d2r(x)**
: Converts **x** from degrees to radians and returns the result.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**frand(p)**
: Generates a pseudo-random number between **0** (inclusive) and **1**
(exclusive) with the number of decimal digits after the decimal point equal
to the truncated absolute value of **p**. If **p** is not **0**, then
calling this function will change the value of **seed**. If **p** is **0**,
then **0** is returned, and **seed** is *not* changed.
**ifrand(i, p)**
: Generates a pseudo-random number that is between **0** (inclusive) and the
truncated absolute value of **i** (exclusive) with the number of decimal
digits after the decimal point equal to the truncated absolute value of
**p**. If the absolute value of **i** is greater than or equal to **2**, and
**p** is not **0**, then calling this function will change the value of
**seed**; otherwise, **0** is returned and **seed** is not changed.
**srand(x)**
: Returns **x** with its sign flipped with probability **0.5**. In other
words, it randomizes the sign of **x**.
**brand()**
: Returns a random boolean value (either **0** or **1**).
**band(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **and** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bor(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **or** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bxor(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **xor** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bshl(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of **a** bit-shifted left by **b** places.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bshr(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the truncated result of **a** bit-shifted right by **b** places.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bnotn(x, n)**
: Takes the truncated absolute value of **x** and does a bitwise not as though
it has the same number of bytes as the truncated absolute value of **n**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot8(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**8** binary digits (1 unsigned byte).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot16(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**16** binary digits (2 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot32(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**32** binary digits (4 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot64(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**64** binary digits (8 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
the minimum number of power of two unsigned bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brevn(x, n)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has the same number of 8-bit bytes as the truncated absolute value of **n**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev8(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 8 binary digits (1 unsigned byte).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev16(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 16 binary digits (2 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev32(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 32 binary digits (4 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev64(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 64 binary digits (8 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has the minimum number of power of two unsigned bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**broln(x, p, n)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has the same number of unsigned 8-bit bytes as the truncated
absolute value of **n**, by the number of places equal to the truncated
absolute value of **p** modded by the **2** to the power of the number of
binary digits in **n** 8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol8(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **8** binary digits (**1** unsigned byte), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol16(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **16** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol32(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **32** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol64(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **64** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has the minimum number of power of two unsigned 8-bit bytes, by
the number of places equal to the truncated absolute value of **p** modded
by 2 to the power of the number of binary digits in the minimum number of
8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brorn(x, p, n)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has the same number of unsigned 8-bit bytes as the truncated
absolute value of **n**, by the number of places equal to the truncated
absolute value of **p** modded by the **2** to the power of the number of
binary digits in **n** 8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror8(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **8** binary digits (**1** unsigned byte), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror16(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **16** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror32(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **32** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror64(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **64** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has the minimum number of power of two unsigned 8-bit bytes, by
the number of places equal to the truncated absolute value of **p** modded
by 2 to the power of the number of binary digits in the minimum number of
8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmodn(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of the multiplication of the truncated absolute value of **n** and
**8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod8(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod16(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod32(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod64(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bunrev(t)**
: Assumes **t** is a bitwise-reversed number with an extra set bit one place
more significant than the real most significant bit (which was the least
significant bit in the original number). This number is reversed and
returned without the extra set bit.
This function is used to implement other bitwise functions; it is not meant
to be used by users, but it can be.
+**plz(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed with a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and without a trailing newline.
+
+ Otherwise, **x** is printed normally, without a trailing newline.
+
+**plznl(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed with a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and with a trailing newline.
+
+ Otherwise, **x** is printed normally, with a trailing newline.
+
+**pnlz(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed without a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and without a trailing newline.
+
+ Otherwise, **x** is printed normally, without a trailing newline.
+
+**pnlznl(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed without a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and with a trailing newline.
+
+ Otherwise, **x** is printed normally, with a trailing newline.
+
**ubytes(x)**
: Returns the numbers of unsigned integer bytes required to hold the truncated
absolute value of **x**.
**sbytes(x)**
: Returns the numbers of signed, two's-complement integer bytes required to
hold the truncated value of **x**.
**s2u(x)**
: Returns **x** if it is non-negative. If it *is* negative, then it calculates
what **x** would be as a 2's-complement signed integer and returns the
non-negative integer that would have the same representation in binary.
**s2un(x,n)**
: Returns **x** if it is non-negative. If it *is* negative, then it calculates
what **x** would be as a 2's-complement signed integer with **n** bytes and
returns the non-negative integer that would have the same representation in
binary. If **x** cannot fit into **n** 2's-complement signed bytes, it is
truncated to fit.
**hex(x)**
: Outputs the hexadecimal (base **16**) representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**binary(x)**
: Outputs the binary (base **2**) representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output(x, b)**
: Outputs the base **b** representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in as few power of two bytes as possible. Both outputs are
split into bytes separated by spaces.
If **x** is not an integer or is negative, an error message is printed
instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in as few power of two bytes as possible. Both
outputs are split into bytes separated by spaces.
If **x** is not an integer, an error message is printed instead, but bc(1)
is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uintn(x, n)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **n** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **n** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**intn(x, n)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **n** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **n** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint8(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **1** byte. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **1** byte, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int8(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **1** byte. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **1** byte, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint16(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **2** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **2** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int16(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **2** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **2** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint32(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **4** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **4** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int32(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **4** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **4** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint64(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **8** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **8** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int64(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **8** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **8** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**hex_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in hexadecimal using **n** bytes. Not all of the value will
be output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**binary_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in binary using **n** bytes. Not all of the value will be
output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in the current **obase** (see the **SYNTAX** section) using
**n** bytes. Not all of the value will be output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output_byte(x, i)**
: Outputs byte **i** of the truncated absolute value of **x**, where **0** is
the least significant byte and **number_of_bytes - 1** is the most
significant byte.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
## Transcendental Functions
All transcendental functions can return slightly inaccurate results (up to 1
[ULP][4]). This is unavoidable, and [this article][5] explains why it is
impossible and unnecessary to calculate exact results for the transcendental
functions.
Because of the possible inaccuracy, I recommend that users call those functions
with the precision (**scale**) set to at least 1 higher than is necessary. If
exact results are *absolutely* required, users can double the precision
(**scale**) and then truncate.
The transcendental functions in the standard math library are:
* **s(x)**
* **c(x)**
* **a(x)**
* **l(x)**
* **e(x)**
* **j(x, n)**
The transcendental functions in the extended math library are:
* **l2(x)**
* **l10(x)**
* **log(x, b)**
* **pi(p)**
* **t(x)**
* **a2(y, x)**
* **sin(x)**
* **cos(x)**
* **tan(x)**
* **atan(x)**
* **atan2(y, x)**
* **r2d(x)**
* **d2r(x)**
# RESET
When bc(1) encounters an error or a signal that it has a non-default handler
for, it resets. This means that several things happen.
First, any functions 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.
Thus, when bc(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.
Note that this reset behavior is different from the GNU bc(1), which attempts to
start executing the statement right after the one that caused an error.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This bc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
the **limits** statement.
In addition, this bc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bc(1):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bc(1) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_STRING_MAX**
: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
**BC_NAME_MAX**
: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
**BC_RAND_MAX**
: The maximum integer (inclusive) returned by the **rand()** operand. Set at
**2\^BC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
The actual values can be queried with the **limits** statement.
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.
# ENVIRONMENT VARIABLES
bc(1) recognizes the following environment variables:
**POSIXLY_CORRECT**
: If this variable exists (no matter the contents), bc(1) behaves as if
the **-s** option was given.
**BC_ENV_ARGS**
: This is another way to give command-line arguments to bc(1). They should be
in the same format as all other command-line arguments. These are always
processed first, so any files given in **BC_ENV_ARGS** 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 bc(1) runs.
The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
**"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'bc' file.bc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **BC_ENV_ARGS** 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.
**BC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
lines to that length, including the backslash (**\\**). The default line
length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**BC_BANNER**
: If this environment variable exists and contains an integer, then a non-zero
value activates the copyright banner when bc(1) is in interactive mode,
while zero deactivates it.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) does not print
the banner when not in interactive mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_SIGINT_RESET**
: If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) exits on
**SIGINT** when not in interactive mode.
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1) reset
on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
environment variable exists and is *not* an integer, then bc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use TTY
mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a prompt,
and zero or a non-integer makes bc(1) not use a prompt. If this environment
variable does not exist and **BC_TTY_MODE** does, then the value of the
**BC_TTY_MODE** environment variable is used.
This environment variable and the **BC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
bc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, 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, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**)
operators and their corresponding assignment operators.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, using a token where it is invalid,
giving an invalid expression, giving an invalid print statement, giving an
invalid function definition, attempting to assign to an expression that is
not a named expression (see the *Named Expressions* subsection of the
**SYNTAX** section), giving an invalid **auto** list, having a duplicate
**auto**/function parameter, failing to find the end of a code block,
attempting to return a value from a **void** function, attempting to use a
variable as a reference, and using any extensions when the option **-s** or
any equivalents were given.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors, passing the
wrong number of arguments to functions, attempting to call an undefined
function, and attempting to use a **void** function call as a value in an
expression.
**4**
: A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, failing to open
files, attempting to use files that do not have only ASCII characters (bc(1)
only accepts ASCII characters), attempting to open a directory as a file,
and giving invalid command-line options.
The exit status **4** is special; when a fatal error occurs, bc(1) always exits
and returns **4**, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interactive mode
(see the **INTERACTIVE MODE** section), since bc(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
**-i** flag or **-\-interactive** option.
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **BC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **BC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
mode on.
If the environment variable **BC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
**stdout**, and **stderr** are connected to a TTY and the **BC_TTY_MODE**
environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
information.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **BC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, bc(1) will
exit.
However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
default is an integer and non-zero, then bc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If bc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If bc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
can seem as though bc(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 bc(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.
**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is **SIGHUP**; in that
case, and only when bc(1) is in TTY mode (see the **TTY MODE** section), a
**SIGHUP** will cause bc(1) to clean up and exit.
# COMMAND LINE HISTORY
bc(1) supports interactive command-line editing.
If bc(1) can be in TTY mode (see the **TTY MODE** section), history can be
enabled. This means that command-line history can only be enabled when
**stdin**, **stdout**, and **stderr** are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment variable
**BC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
If history is enabled, previous lines can be recalled and edited with the arrow
keys.
**Note**: tabs are converted to 8 spaces.
# LOCALES
This bc(1) ships with support for adding error messages for different locales
and thus, supports **LC_MESSAGES**.
# SEE ALSO
dc(1)
# STANDARDS
bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
specification. The flags **-efghiqsvVw**, all long options, and the extensions
noted above are extensions to that specification.
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**.
This bc(1) supports error messages for different locales, and thus, it supports
**LC_MESSAGES**.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
diff --git a/manuals/bc/E.1 b/manuals/bc/E.1
index f157f6668a48..bb563f5c96fc 100644
--- a/manuals/bc/E.1
+++ b/manuals/bc/E.1
@@ -1,1585 +1,1630 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH NAME
.PP
bc - arbitrary-precision decimal arithmetic language and calculator
.SH SYNOPSIS
.PP
\f[B]bc\f[R] [\f[B]-ghilPqRsvVw\f[R]] [\f[B]--global-stacks\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]]
[\f[B]--no-prompt\f[R]] [\f[B]--no-read-prompt\f[R]] [\f[B]--quiet\f[R]]
[\f[B]--standard\f[R]] [\f[B]--warn\f[R]] [\f[B]--version\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX.
(The current standard is
here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).)
The language provides unlimited precision decimal arithmetic and is
somewhat C-like, but there are differences.
Such differences will be noted in this document.
.PP
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from \f[B]stdin\f[R].
.PP
This bc(1) is a drop-in replacement for \f[I]any\f[R] bc(1), including
(and especially) the GNU bc(1).
.PP
\f[B]Note\f[R]: If running this bc(1) on \f[I]any\f[R] script meant for
another bc(1) gives a parse error, it is probably because a word this
bc(1) reserves as a keyword is used as the name of a function, variable,
or array.
To fix that, use the command-line option \f[B]-r\f[R] \f[I]keyword\f[R],
where \f[I]keyword\f[R] is the keyword that is used as a name in the
script.
For more information, see the \f[B]OPTIONS\f[R] section.
.PP
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported.
See the \f[B]BUGS\f[R] section.
.SH OPTIONS
.PP
The following are the options that bc(1) accepts.
.TP
\f[B]-g\f[R], \f[B]--global-stacks\f[R]
Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]
into stacks.
.RS
.PP
This has the effect that a copy of the current value of all three are
pushed onto a stack for every function call, as well as popped when
every function returns.
This means that functions can assign to any and all of those globals
without worrying that the change will affect other functions.
Thus, a hypothetical function named \f[B]output(x,b)\f[R] that simply
printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this:
.IP
.nf
\f[C]
define void output(x, b) {
obase=b
x
}
\f[R]
.fi
.PP
instead of like this:
.IP
.nf
\f[C]
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
\f[R]
.fi
.PP
This makes writing functions much easier.
.PP
However, since using this flag means that functions cannot set
\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R] globally, functions
that are made to do so cannot work anymore.
There are two possible use cases for that, and each has a solution.
.PP
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases.
Examples:
.IP
.nf
\f[C]
alias d2o=\[dq]bc -e ibase=A -e obase=8\[dq]
alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq]
\f[R]
.fi
.PP
Second, if the purpose of a function is to set \f[B]ibase\f[R],
\f[B]obase\f[R], or \f[B]scale\f[R] globally for any other purpose, it
could be split into one to three functions (based on how many globals it
sets) and each of those functions could return the desired value for a
global.
.PP
If the behavior of this option is desired for every run of bc(1), then
users could make sure to define \f[B]BC_ENV_ARGS\f[R] and include this
option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more
details).
.PP
If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option
is ignored.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-l\f[R], \f[B]--mathlib\f[R]
Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R]
and loads the included math library before running any code, including
any expressions or files specified on the command line.
.RS
.PP
To learn what is in the library, see the \f[B]LIBRARY\f[R] section.
.RE
.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.RS
.PP
These options override the \f[B]BC_PROMPT\f[R] and \f[B]BC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of bc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]read()\f[R] built-in function is called.
.PP
These options \f[I]do\f[R] override the \f[B]BC_PROMPT\f[R] and
\f[B]BC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-r\f[R] \f[I]keyword\f[R], \f[B]--redefine\f[R]=\f[I]keyword\f[R]
Redefines \f[I]keyword\f[R] in order to allow it to be used as a
function, variable, or array name.
This is useful when this bc(1) gives parse errors when parsing scripts
meant for other bc(1) implementations.
.RS
.PP
The keywords this bc(1) allows to be redefined are:
.IP \[bu] 2
\f[B]abs\f[R]
.IP \[bu] 2
\f[B]asciify\f[R]
.IP \[bu] 2
\f[B]continue\f[R]
.IP \[bu] 2
\f[B]divmod\f[R]
.IP \[bu] 2
\f[B]else\f[R]
.IP \[bu] 2
\f[B]halt\f[R]
.IP \[bu] 2
\f[B]last\f[R]
.IP \[bu] 2
\f[B]limits\f[R]
.IP \[bu] 2
\f[B]maxibase\f[R]
.IP \[bu] 2
\f[B]maxobase\f[R]
.IP \[bu] 2
\f[B]maxscale\f[R]
.IP \[bu] 2
\f[B]modexp\f[R]
.IP \[bu] 2
\f[B]print\f[R]
.IP \[bu] 2
\f[B]read\f[R]
.IP \[bu] 2
\f[B]stream\f[R]
.PP
If any of those keywords are used as a function, variable, or array name
in a script, use this option with the keyword as the argument.
If multiple are used, use this option for all of them; it can be used
multiple times.
.PP
Keywords are \f[I]not\f[R] redefined when parsing the builtin math
library (see the \f[B]LIBRARY\f[R] section).
.PP
It is a fatal error to redefine keywords mandated by the POSIX standard.
It is a fatal error to attempt to redefine words that this bc(1) does
not reserve as keywords.
.RE
.TP
\f[B]-q\f[R], \f[B]--quiet\f[R]
This option is for compatibility with the GNU
bc(1) (https://www.gnu.org/software/bc/); it is a no-op.
Without this option, GNU bc(1) prints a copyright header.
This bc(1) only prints the copyright header if one or more of the
\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-s\f[R], \f[B]--standard\f[R]
Process exactly the language defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
and error if any extensions are used.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-w\f[R], \f[B]--warn\f[R]
Like \f[B]-s\f[R] and \f[B]--standard\f[R], except that warnings (and
not errors) are printed for non-standard extensions and execution
continues normally.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]BC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files or expressions are given by the \f[B]-f\f[R],
\f[B]--file\f[R], \f[B]-e\f[R], or \f[B]--expression\f[R] options, then
bc(1) read from \f[B]stdin\f[R].
.PP
However, there are a few caveats to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if the parse cannot complete.
That means that starting a string without ending it or starting a
function, \f[B]if\f[R] statement, or loop without ending it will also
cause bc(1) to not execute.
.PP
Second, after an \f[B]if\f[R] statement, bc(1) doesn\[cq]t know if an
\f[B]else\f[R] statement will follow, so it will not execute until it
knows there will not be an \f[B]else\f[R] statement.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]bc >&-\f[R], it will quit with an error.
This is done so that bc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]bc 2>&-\f[R], it will quit with an error.
This is done so that bc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
which is a much more thorough resource for the language this bc(1)
accepts.
This section is meant to be a summary and a listing of all the
extensions to the standard.
.PP
In the sections below, \f[B]E\f[R] means expression, \f[B]S\f[R] means
statement, and \f[B]I\f[R] means identifier.
.PP
Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be
followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase
letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores
(\f[B]_\f[R]).
The regex is \f[B][a-z][a-z0-9_]*\f[R].
Identifiers with more than one character (letter) are a
\f[B]non-portable extension\f[R].
.PP
\f[B]ibase\f[R] is a global variable determining how to interpret
constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R]
(\f[B]--warn\f[R]) flags were not given on the command line, the max
allowable value for \f[B]ibase\f[R] is \f[B]36\f[R].
Otherwise, it is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in bc(1)
programs with the \f[B]maxibase()\f[R] built-in function.
.PP
\f[B]obase\f[R] is a global variable determining how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and
can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in
function.
The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R].
Values are output in the specified base.
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a global variable that sets the precision of any operations, with
exceptions.
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R]
and can be queried in bc(1) programs with the \f[B]maxscale()\f[R]
built-in function.
.PP
bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables.
All \f[I]local\f[R] variables are local to the function; they are
parameters or are introduced in the \f[B]auto\f[R] list of a function
(see the \f[B]FUNCTIONS\f[R] section).
If a variable is accessed which is not a parameter or in the
\f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R].
If a parent function has a \f[I]local\f[R] variable version of a
variable that a child function considers \f[I]global\f[R], the value of
that \f[I]global\f[R] variable in the child function is the value of the
variable in the parent function, not the value of the actual
\f[I]global\f[R] variable.
.PP
All of the above applies to arrays as well.
.PP
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence
operator is an assignment operator \f[I]and\f[R] the expression is
notsurrounded by parentheses.
.PP
The value that is printed is also assigned to the special variable
\f[B]last\f[R].
A single dot (\f[B].\f[R]) may also be used as a synonym for
\f[B]last\f[R].
These are \f[B]non-portable extensions\f[R].
.PP
Either semicolons or newlines may separate statements.
.SS Comments
.PP
There are two kinds of comments:
.IP "1." 3
Block comments are enclosed in \f[B]/*\f[R] and \f[B]*/\f[R].
.IP "2." 3
Line comments go from \f[B]#\f[R] until, and not including, the next
newline.
This is a \f[B]non-portable extension\f[R].
.SS Named Expressions
.PP
The following are named expressions in bc(1):
.IP "1." 3
Variables: \f[B]I\f[R]
.IP "2." 3
Array Elements: \f[B]I[E]\f[R]
.IP "3." 3
\f[B]ibase\f[R]
.IP "4." 3
\f[B]obase\f[R]
.IP "5." 3
\f[B]scale\f[R]
.IP "6." 3
\f[B]last\f[R] or a single dot (\f[B].\f[R])
.PP
Number 6 is a \f[B]non-portable extension\f[R].
.PP
Variables and arrays do not interfere; users can have arrays named the
same as variables.
This also applies to functions (see the \f[B]FUNCTIONS\f[R] section), so
a user can have a variable, array, and function that all have the same
name, and they will not shadow each other, whether inside of functions
or not.
.PP
Named expressions are required as the operand of
\f[B]increment\f[R]/\f[B]decrement\f[R] operators and as the left side
of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R]
subsection).
.SS Operands
.PP
The following are valid operands in bc(1):
.IP " 1." 4
Numbers (see the \f[I]Numbers\f[R] subsection below).
.IP " 2." 4
Array indices (\f[B]I[E]\f[R]).
.IP " 3." 4
\f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence).
.IP " 4." 4
\f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R].
\f[B]E\f[R] must be non-negative.
.IP " 5." 4
\f[B]length(E)\f[R]: The number of significant decimal digits in
\f[B]E\f[R].
Returns \f[B]1\f[R] for \f[B]0\f[R] with no decimal places.
If given a string, the length of the string is returned.
Passing a string to \f[B]length(E)\f[R] is a \f[B]non-portable
extension\f[R].
.IP " 6." 4
\f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 7." 4
\f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R].
.IP " 8." 4
\f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 9." 4
\f[B]modexp(E, E, E)\f[R]: Modular exponentiation, where the first
expression is the base, the second is the exponent, and the third is the
modulus.
All three values must be integers.
The second argument must be non-negative.
The third argument must be non-zero.
This is a \f[B]non-portable extension\f[R].
.IP "10." 4
\f[B]divmod(E, E, I[])\f[R]: Division and modulus in one operation.
This is for optimization.
The first expression is the dividend, and the second is the divisor,
which must be non-zero.
The return value is the quotient, and the modulus is stored in index
\f[B]0\f[R] of the provided array (the last argument).
This is a \f[B]non-portable extension\f[R].
.IP "11." 4
\f[B]asciify(E)\f[R]: If \f[B]E\f[R] is a string, returns a string that
is the first letter of its argument.
If it is a number, calculates the number mod \f[B]256\f[R] and returns
that number as a one-character string.
This is a \f[B]non-portable extension\f[R].
.IP "12." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.IP "13." 4
\f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an
expression.
The result of that expression is the result of the \f[B]read()\f[R]
operand.
This is a \f[B]non-portable extension\f[R].
.IP "14." 4
\f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "15." 4
\f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "16." 4
\f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R].
This is a \f[B]non-portable extension\f[R].
+.IP "17." 4
+\f[B]line_length()\f[R]: The line length set with
+\f[B]BC_LINE_LENGTH\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
+section).
+This is a \f[B]non-portable extension\f[R].
+.IP "18." 4
+\f[B]global_stacks()\f[R]: \f[B]0\f[R] if global stacks are not enabled
+with the \f[B]-g\f[R] or \f[B]--global-stacks\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "19." 4
+\f[B]leading_zero()\f[R]: \f[B]0\f[R] if leading zeroes are not enabled
+with the \f[B]-z\f[R] or \f[B]\[en]leading-zeroes\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
.SS Numbers
.PP
Numbers are strings made up of digits, uppercase letters, and at most
\f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R].
.SS Operators
.PP
The following arithmetic and logical operators can be used.
They are listed in order of decreasing precedence.
Operators in the same group have the same precedence.
.TP
\f[B]++\f[R] \f[B]--\f[R]
Type: Prefix and Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]increment\f[R], \f[B]decrement\f[R]
.RE
.TP
\f[B]-\f[R] \f[B]!\f[R]
Type: Prefix
.RS
.PP
Associativity: None
.PP
Description: \f[B]negation\f[R], \f[B]boolean not\f[R]
.RE
.TP
\f[B]\[ha]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]power\f[R]
.RE
.TP
\f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R]
.RE
.TP
\f[B]+\f[R] \f[B]-\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]add\f[R], \f[B]subtract\f[R]
.RE
.TP
\f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]assignment\f[R]
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]relational\f[R]
.RE
.TP
\f[B]&&\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean and\f[R]
.RE
.TP
\f[B]||\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean or\f[R]
.RE
.PP
The operators will be described in more detail below.
.TP
\f[B]++\f[R] \f[B]--\f[R]
The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R]
operators behave exactly like they would in C.
They require a named expression (see the \f[I]Named Expressions\f[R]
subsection) as an operand.
.RS
.PP
The prefix versions of these operators are more efficient; use them
where possible.
.RE
.TP
\f[B]-\f[R]
The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts
to negate any expression with the value \f[B]0\f[R].
Otherwise, a copy of the expression with its sign flipped is returned.
.TP
\f[B]!\f[R]
The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression
is \f[B]0\f[R], or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator,
as it would be in C) takes two expressions and raises the first to the
power of the value of the second.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]), and if it
is negative, the first value must be non-zero.
.RE
.TP
\f[B]*\f[R]
The \f[B]multiply\f[R] operator takes two expressions, multiplies them,
and returns the product.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The \f[B]divide\f[R] operator takes two expressions, divides them, and
returns the quotient.
The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]%\f[R]
The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R] and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]+\f[R]
The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the
max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]-\f[R]
The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to
the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R]
The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and
\f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named
Expressions\f[R] subsection).
.RS
.PP
For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to
\f[B]a\f[R].
For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to
the corresponding arithmetic operator and the result is assigned to
\f[B]a\f[R].
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and if the relation holds, according to C language
semantics, the result is \f[B]1\f[R].
Otherwise, it is \f[B]0\f[R].
.RS
.PP
Note that unlike in C, these operators have a lower precedence than the
\f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is
interpreted as \f[B](a=b)>c\f[R].
.PP
Also, unlike the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
requires, these operators can appear anywhere any other expressions can
be used.
This allowance is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]&&\f[R]
The \f[B]boolean and\f[R] operator takes two expressions and returns
\f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]||\f[R]
The \f[B]boolean or\f[R] operator takes two expressions and returns
\f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R]
otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Statements
.PP
The following items are statements:
.IP " 1." 4
\f[B]E\f[R]
.IP " 2." 4
\f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R]
\f[B]}\f[R]
.IP " 3." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 4." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
\f[B]else\f[R] \f[B]S\f[R]
.IP " 5." 4
\f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 6." 4
\f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R]
\f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 7." 4
An empty statement
.IP " 8." 4
\f[B]break\f[R]
.IP " 9." 4
\f[B]continue\f[R]
.IP "10." 4
\f[B]quit\f[R]
.IP "11." 4
\f[B]halt\f[R]
.IP "12." 4
\f[B]limits\f[R]
.IP "13." 4
A string of characters, enclosed in double quotes
.IP "14." 4
\f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "15." 4
\f[B]stream\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "16." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.PP
Numbers 4, 9, 11, 12, 14, 15, and 16 are \f[B]non-portable
extensions\f[R].
.PP
Also, as a \f[B]non-portable extension\f[R], any or all of the
expressions in the header of a for loop may be omitted.
If the condition (second expression) is omitted, it is assumed to be a
constant \f[B]1\f[R].
.PP
The \f[B]break\f[R] statement causes a loop to stop iterating and resume
execution immediately following a loop.
This is only allowed in loops.
.PP
The \f[B]continue\f[R] statement causes a loop iteration to stop early
and returns to the start of the loop, including testing the loop
condition.
This is only allowed in loops.
.PP
The \f[B]if\f[R] \f[B]else\f[R] statement does the same thing as in C.
.PP
The \f[B]quit\f[R] statement causes bc(1) to quit, even if it is on a
branch that will not be executed (it is a compile-time command).
.PP
The \f[B]halt\f[R] statement causes bc(1) to quit, if it is executed.
(Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement
that is not executed, bc(1) does not quit.)
.PP
The \f[B]limits\f[R] statement prints the limits that this bc(1) is
subject to.
This is like the \f[B]quit\f[R] statement in that it is a compile-time
command.
.PP
An expression by itself is evaluated and printed, followed by a newline.
.SS Strings
.PP
If strings appear as a statement by themselves, they are printed without
a trailing newline.
.PP
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements.
They can also be passed to functions in variable parameters.
.PP
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
.PP
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section).
.PP
Assigning strings to variables and array elements and passing them to
functions are \f[B]non-portable extensions\f[R].
.SS Print Statement
.PP
The \[lq]expressions\[rq] in a \f[B]print\f[R] statement may also be
strings.
If they are, there are backslash escape sequences that are interpreted
specially.
What those sequences are, and what they cause to be printed, are shown
below:
.PP
\f[B]\[rs]a\f[R]: \f[B]\[rs]a\f[R]
.PP
\f[B]\[rs]b\f[R]: \f[B]\[rs]b\f[R]
.PP
\f[B]\[rs]\[rs]\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]e\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]f\f[R]: \f[B]\[rs]f\f[R]
.PP
\f[B]\[rs]n\f[R]: \f[B]\[rs]n\f[R]
.PP
\f[B]\[rs]q\f[R]: \f[B]\[lq]\f[R]
.PP
\f[B]\[rs]r\f[R]: \f[B]\[rs]r\f[R]
.PP
\f[B]\[rs]t\f[R]: \f[B]\[rs]t\f[R]
.PP
Any other character following a backslash causes the backslash and
character to be printed as-is.
.PP
Any non-string expression in a print statement shall be assigned to
\f[B]last\f[R], like any other expression that is printed.
.SS Stream Statement
.PP
The \[lq]expressions in a \f[B]stream\f[R] statement may also be
strings.
.PP
If a \f[B]stream\f[R] statement is given a string, it prints the string
as though the string had appeared as its own statement.
In other words, the \f[B]stream\f[R] statement prints strings normally,
without a newline.
.PP
If a \f[B]stream\f[R] statement is given a number, a copy of it is
truncated and its absolute value is calculated.
The result is then printed as though \f[B]obase\f[R] is \f[B]256\f[R]
and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
.SS Order of Evaluation
.PP
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations.
This means, for example, assuming that \f[B]i\f[R] is equal to
\f[B]0\f[R], in the expression
.IP
.nf
\f[C]
a[i++] = i++
\f[R]
.fi
.PP
the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and
\f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression.
.PP
This includes function arguments.
Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in
the expression
.IP
.nf
\f[C]
x(i++, i++)
\f[R]
.fi
.PP
the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the
second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to
\f[B]2\f[R] before the function starts executing.
.SH FUNCTIONS
.PP
Function definitions are as follows:
.IP
.nf
\f[C]
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
\f[R]
.fi
.PP
Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be
replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an
array, and any \f[B]I\f[R] in the parameter list may be replaced with
\f[B]*I[]\f[R] to make a parameter an array reference.
Callers of functions that take array references should not put an
asterisk in the call; they must be called with just \f[B]I[]\f[R] like
normal array parameters and will be automatically converted into
references.
.PP
As a \f[B]non-portable extension\f[R], the opening brace of a
\f[B]define\f[R] statement may appear on the next line.
.PP
As a \f[B]non-portable extension\f[R], the return statement may also be
in one of the following forms:
.IP "1." 3
\f[B]return\f[R]
.IP "2." 3
\f[B]return\f[R] \f[B](\f[R] \f[B])\f[R]
.IP "3." 3
\f[B]return\f[R] \f[B]E\f[R]
.PP
The first two, or not specifying a \f[B]return\f[R] statement, is
equivalent to \f[B]return (0)\f[R], unless the function is a
\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection
below).
.SS Void Functions
.PP
Functions can also be \f[B]void\f[R] functions, defined as follows:
.IP
.nf
\f[C]
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
\f[R]
.fi
.PP
They can only be used as standalone expressions, where such an
expression would be printed alone, except in a print statement.
.PP
Void functions can only use the first two \f[B]return\f[R] statements
listed above.
They can also omit the return statement entirely.
.PP
The word \[lq]void\[rq] is not treated as a keyword; it is still
possible to have variables, arrays, and functions named \f[B]void\f[R].
The word \[lq]void\[rq] is only treated specially right after the
\f[B]define\f[R] keyword.
.PP
This is a \f[B]non-portable extension\f[R].
.SS Array References
.PP
For any array in the parameter list, if the array is declared in the
form
.IP
.nf
\f[C]
*I[]
\f[R]
.fi
.PP
it is a \f[B]reference\f[R].
Any changes to the array in the function are reflected, when the
function returns, to the array that was passed in.
.PP
Other than this, all function arguments are passed by value.
.PP
This is a \f[B]non-portable extension\f[R].
.SH LIBRARY
.PP
All of the functions below are available when the \f[B]-l\f[R] or
\f[B]--mathlib\f[R] command-line flags are given.
.SS Standard Library
.PP
The
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
defines the following functions for the math library:
.TP
\f[B]s(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]c(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l(x)\f[R]
Returns the natural logarithm of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]e(x)\f[R]
Returns the mathematical constant \f[B]e\f[R] raised to the power of
\f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]j(x, n)\f[R]
Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.SS Transcendental Functions
.PP
All transcendental functions can return slightly inaccurate results (up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)).
This is unavoidable, and this
article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains
why it is impossible and unnecessary to calculate exact results for the
transcendental functions.
.PP
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (\f[B]scale\f[R]) set to at least 1 higher
than is necessary.
If exact results are \f[I]absolutely\f[R] required, users can double the
precision (\f[B]scale\f[R]) and then truncate.
.PP
The transcendental functions in the standard math library are:
.IP \[bu] 2
\f[B]s(x)\f[R]
.IP \[bu] 2
\f[B]c(x)\f[R]
.IP \[bu] 2
\f[B]a(x)\f[R]
.IP \[bu] 2
\f[B]l(x)\f[R]
.IP \[bu] 2
\f[B]e(x)\f[R]
.IP \[bu] 2
\f[B]j(x, n)\f[R]
.SH RESET
.PP
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets.
This means that several things happen.
.PP
First, any functions 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.
.PP
Thus, when bc(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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.PP
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This bc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R]
can be queried with the \f[B]limits\f[R] statement.
.PP
In addition, this bc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bc(1):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bc(1) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
The actual values can be queried with the \f[B]limits\f[R] statement.
.PP
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
.PP
bc(1) recognizes the following environment variables:
.TP
\f[B]POSIXLY_CORRECT\f[R]
If this variable exists (no matter the contents), bc(1) behaves as if
the \f[B]-s\f[R] option was given.
.TP
\f[B]BC_ENV_ARGS\f[R]
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line arguments.
These are always processed first, so any files given in
\f[B]BC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 bc(1) runs.
.RS
.PP
The code that parses \f[B]BC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`bc' file.bc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]BC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]BC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length,
including the backslash (\f[B]\[rs]\f[R]).
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]BC_BANNER\f[R]
If this environment variable exists and contains an integer, then a
non-zero value activates the copyright banner when bc(1) is in
interactive mode, while zero deactivates it.
.RS
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
does not print the banner when not in interactive mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_SIGINT_RESET\f[R]
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes bc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then bc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use
TTY mode, and zero makes bc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a
prompt, and zero or a non-integer makes bc(1) not use a prompt.
If this environment variable does not exist and \f[B]BC_TTY_MODE\f[R]
does, then the value of the \f[B]BC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]BC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
bc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], taking the square root of a
negative number, attempting to convert a negative number to a hardware
integer, overflow when converting a number to a hardware integer,
overflow when calculating the size of a number, and attempting to use a
non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]) operator and the corresponding assignment
operator.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an invalid
print statement, giving an invalid function definition, attempting to
assign to an expression that is not a named expression (see the
\f[I]Named Expressions\f[R] subsection of the \f[B]SYNTAX\f[R] section),
giving an invalid \f[B]auto\f[R] list, having a duplicate
\f[B]auto\f[R]/function parameter, failing to find the end of a code
block, attempting to return a value from a \f[B]void\f[R] function,
attempting to use a variable as a reference, and using any extensions
when the option \f[B]-s\f[R] or any equivalents were given.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors, passing the wrong number of
arguments to functions, attempting to call an undefined function, and
attempting to use a \f[B]void\f[R] function call as a value in an
expression.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
Fatal errors include memory allocation errors, I/O errors, failing to
open files, attempting to use files that do not have only ASCII
characters (bc(1) only accepts ASCII characters), attempting to open a
directory as a file, and giving invalid command-line options.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, bc(1)
always exits and returns \f[B]4\f[R], no matter what mode bc(1) is in.
.PP
The other statuses will only be returned when bc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
bc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Per the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, bc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
bc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]BC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, bc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]BC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, bc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]BC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then bc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]BC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Command-Line History
.PP
Command-line history is only enabled if TTY mode is, i.e., that
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to
a TTY and the \f[B]BC_TTY_MODE\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section) and its default do not disable
TTY mode.
See the \f[B]COMMAND LINE HISTORY\f[R] section for more information.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]BC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]BC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]BC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]BC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause bc(1) to do one of two things.
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, bc(1) will exit.
.PP
However, if bc(1) is in interactive mode, and the
\f[B]BC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then bc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If bc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If bc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] is sent to bc(1) as it is
executing a file, it can seem as though bc(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
bc(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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause bc(1) to clean up and
exit, and it uses the default handler for all other signals.
The one exception is \f[B]SIGHUP\f[R]; in that case, and only when bc(1)
is in TTY mode (see the \f[B]TTY MODE\f[R] section), a \f[B]SIGHUP\f[R]
will cause bc(1) to clean up and exit.
.SH COMMAND LINE HISTORY
.PP
bc(1) supports interactive command-line editing.
.PP
If bc(1) can be in TTY mode (see the \f[B]TTY MODE\f[R] section),
history can be enabled.
This means that command-line history can only be enabled when
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY.
.PP
Like TTY mode itself, it can be turned on or off with the environment
variable \f[B]BC_TTY_MODE\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If history is enabled, previous lines can be recalled and edited with
the arrow keys.
.PP
\f[B]Note\f[R]: tabs are converted to 8 spaces.
.SH LOCALES
.PP
This bc(1) ships with support for adding error messages for different
locales and thus, supports \f[B]LC_MESSAGES\f[R].
.SH SEE ALSO
.PP
dc(1)
.SH STANDARDS
.PP
bc(1) is compliant with the IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
The flags \f[B]-efghiqsvVw\f[R], all long options, and the extensions
noted above are extensions to that specification.
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
.PP
This bc(1) supports error messages for different locales, and thus, it
supports \f[B]LC_MESSAGES\f[R].
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bc/E.1.md b/manuals/bc/E.1.md
index 5c9d83b97c4c..63367e436cc8 100644
--- a/manuals/bc/E.1.md
+++ b/manuals/bc/E.1.md
@@ -1,1335 +1,1365 @@
# NAME
bc - arbitrary-precision decimal arithmetic language and calculator
# SYNOPSIS
**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# DESCRIPTION
bc(1) is an interactive processor for a language first standardized in 1991 by
POSIX. (The current standard is [here][1].) The language provides unlimited
precision decimal arithmetic and is somewhat C-like, but there are differences.
Such differences will be noted in this document.
After parsing and handling options, this bc(1) reads any files given on the
command line and executes them before reading from **stdin**.
This bc(1) is a drop-in replacement for *any* bc(1), including (and especially)
the GNU bc(1).
**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
parse error, it is probably because a word this bc(1) reserves as a keyword is
used as the name of a function, variable, or array. To fix that, use the
command-line option **-r** *keyword*, where *keyword* is the keyword that is
used as a name in the script. For more information, see the **OPTIONS** section.
If parsing scripts meant for other bc(1) implementations still does not work,
that is a bug and should be reported. See the **BUGS** section.
# OPTIONS
The following are the options that bc(1) accepts.
**-g**, **-\-global-stacks**
: Turns the globals **ibase**, **obase**, and **scale** into stacks.
This has the effect that a copy of the current value of all three are pushed
onto a stack for every function call, as well as popped when every function
returns. This means that functions can assign to any and all of those
globals without worrying that the change will affect other functions.
Thus, a hypothetical function named **output(x,b)** that simply printed
**x** in base **b** could be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
However, since using this flag means that functions cannot set **ibase**,
**obase**, or **scale** globally, functions that are made to do so cannot
work anymore. There are two possible use cases for that, and each has a
solution.
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set **ibase**, **obase**, or
**scale** globally for any other purpose, it could be split into one to
three functions (based on how many globals it sets) and each of those
functions could return the desired value for a global.
If the behavior of this option is desired for every run of bc(1), then users
could make sure to define **BC_ENV_ARGS** and include this option (see the
**ENVIRONMENT VARIABLES** section for more details).
If **-s**, **-w**, or any equivalents are used, this option is ignored.
This is a **non-portable extension**.
**-h**, **-\-help**
: Prints a usage message and quits.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-l**, **-\-mathlib**
: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
math library before running any code, including any expressions or files
specified on the command line.
To learn what is in the library, see the **LIBRARY** section.
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in bc(1). Most of those users
would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section).
These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of bc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **read()** built-in function is called.
These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-r** *keyword*, **-\-redefine**=*keyword*
: Redefines *keyword* in order to allow it to be used as a function, variable,
or array name. This is useful when this bc(1) gives parse errors when
parsing scripts meant for other bc(1) implementations.
The keywords this bc(1) allows to be redefined are:
* **abs**
* **asciify**
* **continue**
* **divmod**
* **else**
* **halt**
* **last**
* **limits**
* **maxibase**
* **maxobase**
* **maxscale**
* **modexp**
* **print**
* **read**
* **stream**
If any of those keywords are used as a function, variable, or array name in
a script, use this option with the keyword as the argument. If multiple are
used, use this option for all of them; it can be used multiple times.
Keywords are *not* redefined when parsing the builtin math library (see the
**LIBRARY** section).
It is a fatal error to redefine keywords mandated by the POSIX standard. It
is a fatal error to attempt to redefine words that this bc(1) does not
reserve as keywords.
**-q**, **-\-quiet**
: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
Without this option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the **-v**, **-V**, or
**-\-version** options are given.
This is a **non-portable extension**.
**-s**, **-\-standard**
: Process exactly the language defined by the [standard][1] and error if any
extensions are used.
This is a **non-portable extension**.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
This is a **non-portable extension**.
**-w**, **-\-warn**
: Like **-s** and **-\-standard**, except that warnings (and not errors) are
printed for non-standard extensions and execution continues normally.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
**-\-expression** options, then bc(1) read from **stdin**.
However, there are a few caveats to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
the parse cannot complete. That means that starting a string without ending it
or starting a function, **if** statement, or loop without ending it will also
cause bc(1) to not execute.
Second, after an **if** statement, bc(1) doesn't know if an **else** statement
will follow, so it will not execute until it knows there will not be an **else**
statement.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **bc >&-**, it will quit with an error. This
is done so that bc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This
is done so that bc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences. This
bc(1) follows the [POSIX standard][1], which is a much more thorough resource
for the language this bc(1) accepts. This section is meant to be a summary and a
listing of all the extensions to the standard.
In the sections below, **E** means expression, **S** means statement, and **I**
means identifier.
Identifiers (**I**) start with a lowercase letter and can be followed by any
number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
Identifiers with more than one character (letter) are a
**non-portable extension**.
**ibase** is a global variable determining how to interpret constant numbers. It
is the "input" base, or the number base used for interpreting input numbers.
**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
(**-\-warn**) flags were not given on the command line, the max allowable value
for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
**ibase** is **2**. The max allowable value for **ibase** can be queried in
bc(1) programs with the **maxibase()** built-in function.
**obase** is a global variable determining how to output results. It is the
"output" base, or the number base used for outputting numbers. **obase** is
initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
can be queried in bc(1) programs with the **maxobase()** built-in function. The
min allowable value for **obase** is **2**. Values are output in the specified
base.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a global variable that
sets the precision of any operations, with exceptions. **scale** is initially
**0**. **scale** cannot be negative. The max allowable value for **scale** is
**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
built-in function.
bc(1) has both *global* variables and *local* variables. All *local*
variables are local to the function; they are parameters or are introduced in
the **auto** list of a function (see the **FUNCTIONS** section). If a variable
is accessed which is not a parameter or in the **auto** list, it is assumed to
be *global*. If a parent function has a *local* variable version of a variable
that a child function considers *global*, the value of that *global* variable in
the child function is the value of the variable in the parent function, not the
value of the actual *global* variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence operator is an
assignment operator *and* the expression is notsurrounded by parentheses.
The value that is printed is also assigned to the special variable **last**. A
single dot (**.**) may also be used as a synonym for **last**. These are
**non-portable extensions**.
Either semicolons or newlines may separate statements.
## Comments
There are two kinds of comments:
1. Block comments are enclosed in **/\*** and **\*/**.
2. Line comments go from **#** until, and not including, the next newline. This
is a **non-portable extension**.
## Named Expressions
The following are named expressions in bc(1):
1. Variables: **I**
2. Array Elements: **I[E]**
3. **ibase**
4. **obase**
5. **scale**
6. **last** or a single dot (**.**)
Number 6 is a **non-portable extension**.
Variables and arrays do not interfere; users can have arrays named the same as
variables. This also applies to functions (see the **FUNCTIONS** section), so a
user can have a variable, array, and function that all have the same name, and
they will not shadow each other, whether inside of functions or not.
Named expressions are required as the operand of **increment**/**decrement**
operators and as the left side of **assignment** operators (see the *Operators*
subsection).
## Operands
The following are valid operands in bc(1):
1. Numbers (see the *Numbers* subsection below).
2. Array indices (**I[E]**).
3. **(E)**: The value of **E** (used to change precedence).
4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
5. **length(E)**: The number of significant decimal digits in **E**. Returns
**1** for **0** with no decimal places. If given a string, the length of the
string is returned. Passing a string to **length(E)** is a **non-portable
extension**.
6. **length(I[])**: The number of elements in the array **I**. This is a
**non-portable extension**.
7. **scale(E)**: The *scale* of **E**.
8. **abs(E)**: The absolute value of **E**. This is a **non-portable
extension**.
9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
the base, the second is the exponent, and the third is the modulus. All
three values must be integers. The second argument must be non-negative. The
third argument must be non-zero. This is a **non-portable extension**.
10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
optimization. The first expression is the dividend, and the second is the
divisor, which must be non-zero. The return value is the quotient, and the
modulus is stored in index **0** of the provided array (the last argument).
This is a **non-portable extension**.
11. **asciify(E)**: If **E** is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number mod **256**
and returns that number as a one-character string. This is a **non-portable
extension**.
12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a non-**void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
13. **read()**: Reads a line from **stdin** and uses that as an expression. The
result of that expression is the result of the **read()** operand. This is a
**non-portable extension**.
14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
extension**.
15. **maxobase()**: The max allowable **obase**. This is a **non-portable
extension**.
16. **maxscale()**: The max allowable **scale**. This is a **non-portable
extension**.
+17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
+ **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
+18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
+ or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
+ or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
## Numbers
Numbers are strings made up of digits, uppercase letters, and at most **1**
period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
letters are equal to **9** + their position in the alphabet (i.e., **A** equals
**10**, or **9+1**). If a digit or letter makes no sense with the current value
of **ibase**, they are set to the value of the highest valid digit in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **Z** alone always equals decimal
**35**.
## Operators
The following arithmetic and logical operators can be used. They are listed in
order of decreasing precedence. Operators in the same group have the same
precedence.
**++** **-\-**
: Type: Prefix and Postfix
Associativity: None
Description: **increment**, **decrement**
**-** **!**
: Type: Prefix
Associativity: None
Description: **negation**, **boolean not**
**\^**
: Type: Binary
Associativity: Right
Description: **power**
**\*** **/** **%**
: Type: Binary
Associativity: Left
Description: **multiply**, **divide**, **modulus**
**+** **-**
: Type: Binary
Associativity: Left
Description: **add**, **subtract**
**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
: Type: Binary
Associativity: Right
Description: **assignment**
**==** **\<=** **\>=** **!=** **\<** **\>**
: Type: Binary
Associativity: Left
Description: **relational**
**&&**
: Type: Binary
Associativity: Left
Description: **boolean and**
**||**
: Type: Binary
Associativity: Left
Description: **boolean or**
The operators will be described in more detail below.
**++** **-\-**
: The prefix and postfix **increment** and **decrement** operators behave
exactly like they would in C. They require a named expression (see the
*Named Expressions* subsection) as an operand.
The prefix versions of these operators are more efficient; use them where
possible.
**-**
: The **negation** operator returns **0** if a user attempts to negate any
expression with the value **0**. Otherwise, a copy of the expression with
its sign flipped is returned.
**!**
: The **boolean not** operator returns **1** if the expression is **0**, or
**0** otherwise.
This is a **non-portable extension**.
**\^**
: The **power** operator (not the **exclusive or** operator, as it would be in
C) takes two expressions and raises the first to the power of the value of
the second. The *scale* of the result is equal to **scale**.
The second expression must be an integer (no *scale*), and if it is
negative, the first value must be non-zero.
**\***
: The **multiply** operator takes two expressions, multiplies them, and
returns the product. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result is
equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The **divide** operator takes two expressions, divides them, and returns the
quotient. The *scale* of the result shall be the value of **scale**.
The second expression must be non-zero.
**%**
: The **modulus** operator takes two expressions, **a** and **b**, and
evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The second expression must be non-zero.
**+**
: The **add** operator takes two expressions, **a** and **b**, and returns the
sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
**-**
: The **subtract** operator takes two expressions, **a** and **b**, and
returns the difference, with a *scale* equal to the max of the *scale*s of
**a** and **b**.
**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
: The **assignment** operators take two expressions, **a** and **b** where
**a** is a named expression (see the *Named Expressions* subsection).
For **=**, **b** is copied and the result is assigned to **a**. For all
others, **a** and **b** are applied as operands to the corresponding
arithmetic operator and the result is assigned to **a**.
**==** **\<=** **\>=** **!=** **\<** **\>**
: The **relational** operators compare two expressions, **a** and **b**, and
if the relation holds, according to C language semantics, the result is
**1**. Otherwise, it is **0**.
Note that unlike in C, these operators have a lower precedence than the
**assignment** operators, which means that **a=b\>c** is interpreted as
**(a=b)\>c**.
Also, unlike the [standard][1] requires, these operators can appear anywhere
any other expressions can be used. This allowance is a
**non-portable extension**.
**&&**
: The **boolean and** operator takes two expressions and returns **1** if both
expressions are non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
**||**
: The **boolean or** operator takes two expressions and returns **1** if one
of the expressions is non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
## Statements
The following items are statements:
1. **E**
2. **{** **S** **;** ... **;** **S** **}**
3. **if** **(** **E** **)** **S**
4. **if** **(** **E** **)** **S** **else** **S**
5. **while** **(** **E** **)** **S**
6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
7. An empty statement
8. **break**
9. **continue**
10. **quit**
11. **halt**
12. **limits**
13. A string of characters, enclosed in double quotes
14. **print** **E** **,** ... **,** **E**
15. **stream** **E** **,** ... **,** **E**
16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
Also, as a **non-portable extension**, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expression) is
omitted, it is assumed to be a constant **1**.
The **break** statement causes a loop to stop iterating and resume execution
immediately following a loop. This is only allowed in loops.
The **continue** statement causes a loop iteration to stop early and returns to
the start of the loop, including testing the loop condition. This is only
allowed in loops.
The **if** **else** statement does the same thing as in C.
The **quit** statement causes bc(1) to quit, even if it is on a branch that will
not be executed (it is a compile-time command).
The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
if it is on a branch of an **if** statement that is not executed, bc(1) does not
quit.)
The **limits** statement prints the limits that this bc(1) is subject to. This
is like the **quit** statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a newline.
## Strings
If strings appear as a statement by themselves, they are printed without a
trailing newline.
In addition to appearing as a lone statement by themselves, strings can be
assigned to variables and array elements. They can also be passed to functions
in variable parameters.
If any statement that expects a string is given a variable that had a string
assigned to it, the statement acts as though it had received a string.
If any math operation is attempted on a string or a variable or array element
that has been assigned a string, an error is raised, and bc(1) resets (see the
**RESET** section).
Assigning strings to variables and array elements and passing them to functions
are **non-portable extensions**.
## Print Statement
The "expressions" in a **print** statement may also be strings. If they are, there
are backslash escape sequences that are interpreted specially. What those
sequences are, and what they cause to be printed, are shown below:
**\\a**: **\\a**
**\\b**: **\\b**
**\\\\**: **\\**
**\\e**: **\\**
**\\f**: **\\f**
**\\n**: **\\n**
**\\q**: **"**
**\\r**: **\\r**
**\\t**: **\\t**
Any other character following a backslash causes the backslash and character to
be printed as-is.
Any non-string expression in a print statement shall be assigned to **last**,
like any other expression that is printed.
## Stream Statement
The "expressions in a **stream** statement may also be strings.
If a **stream** statement is given a string, it prints the string as though the
string had appeared as its own statement. In other words, the **stream**
statement prints strings normally, without a newline.
If a **stream** statement is given a number, a copy of it is truncated and its
absolute value is calculated. The result is then printed as though **obase** is
**256** and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
## Order of Evaluation
All expressions in a statment are evaluated left to right, except as necessary
to maintain order of operations. This means, for example, assuming that **i** is
equal to **0**, in the expression
a[i++] = i++
the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
at the end of the expression.
This includes function arguments. Thus, assuming **i** is equal to **0**, this
means that in the expression
x(i++, i++)
the first argument passed to **x()** is **0**, and the second argument is **1**,
while **i** is equal to **2** before the function starts executing.
# FUNCTIONS
Function definitions are as follows:
```
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
```
Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
make a parameter or **auto** var an array, and any **I** in the parameter list
may be replaced with **\*I[]** to make a parameter an array reference. Callers
of functions that take array references should not put an asterisk in the call;
they must be called with just **I[]** like normal array parameters and will be
automatically converted into references.
As a **non-portable extension**, the opening brace of a **define** statement may
appear on the next line.
As a **non-portable extension**, the return statement may also be in one of the
following forms:
1. **return**
2. **return** **(** **)**
3. **return** **E**
The first two, or not specifying a **return** statement, is equivalent to
**return (0)**, unless the function is a **void** function (see the *Void
Functions* subsection below).
## Void Functions
Functions can also be **void** functions, defined as follows:
```
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
```
They can only be used as standalone expressions, where such an expression would
be printed alone, except in a print statement.
Void functions can only use the first two **return** statements listed above.
They can also omit the return statement entirely.
The word "void" is not treated as a keyword; it is still possible to have
variables, arrays, and functions named **void**. The word "void" is only
treated specially right after the **define** keyword.
This is a **non-portable extension**.
## Array References
For any array in the parameter list, if the array is declared in the form
```
*I[]
```
it is a **reference**. Any changes to the array in the function are reflected,
when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a **non-portable extension**.
# LIBRARY
All of the functions below are available when the **-l** or **-\-mathlib**
command-line flags are given.
## Standard Library
The [standard][1] defines the following functions for the math library:
**s(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**c(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a(x)**
: Returns the arctangent of **x**, in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l(x)**
: Returns the natural logarithm of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**e(x)**
: Returns the mathematical constant **e** raised to the power of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**j(x, n)**
: Returns the bessel integer order **n** (truncated) of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
## Transcendental Functions
All transcendental functions can return slightly inaccurate results (up to 1
[ULP][4]). This is unavoidable, and [this article][5] explains why it is
impossible and unnecessary to calculate exact results for the transcendental
functions.
Because of the possible inaccuracy, I recommend that users call those functions
with the precision (**scale**) set to at least 1 higher than is necessary. If
exact results are *absolutely* required, users can double the precision
(**scale**) and then truncate.
The transcendental functions in the standard math library are:
* **s(x)**
* **c(x)**
* **a(x)**
* **l(x)**
* **e(x)**
* **j(x, n)**
# RESET
When bc(1) encounters an error or a signal that it has a non-default handler
for, it resets. This means that several things happen.
First, any functions 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.
Thus, when bc(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.
Note that this reset behavior is different from the GNU bc(1), which attempts to
start executing the statement right after the one that caused an error.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This bc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
the **limits** statement.
In addition, this bc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bc(1):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bc(1) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_STRING_MAX**
: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
**BC_NAME_MAX**
: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
The actual values can be queried with the **limits** statement.
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.
# ENVIRONMENT VARIABLES
bc(1) recognizes the following environment variables:
**POSIXLY_CORRECT**
: If this variable exists (no matter the contents), bc(1) behaves as if
the **-s** option was given.
**BC_ENV_ARGS**
: This is another way to give command-line arguments to bc(1). They should be
in the same format as all other command-line arguments. These are always
processed first, so any files given in **BC_ENV_ARGS** 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 bc(1) runs.
The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
**"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'bc' file.bc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **BC_ENV_ARGS** 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.
**BC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
lines to that length, including the backslash (**\\**). The default line
length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**BC_BANNER**
: If this environment variable exists and contains an integer, then a non-zero
value activates the copyright banner when bc(1) is in interactive mode,
while zero deactivates it.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) does not print
the banner when not in interactive mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_SIGINT_RESET**
: If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) exits on
**SIGINT** when not in interactive mode.
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1) reset
on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
environment variable exists and is *not* an integer, then bc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use TTY
mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a prompt,
and zero or a non-integer makes bc(1) not use a prompt. If this environment
variable does not exist and **BC_TTY_MODE** does, then the value of the
**BC_TTY_MODE** environment variable is used.
This environment variable and the **BC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
bc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, taking the square root of a negative
number, attempting to convert a negative number to a hardware integer,
overflow when converting a number to a hardware integer, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**) operator and the corresponding assignment operator.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, using a token where it is invalid,
giving an invalid expression, giving an invalid print statement, giving an
invalid function definition, attempting to assign to an expression that is
not a named expression (see the *Named Expressions* subsection of the
**SYNTAX** section), giving an invalid **auto** list, having a duplicate
**auto**/function parameter, failing to find the end of a code block,
attempting to return a value from a **void** function, attempting to use a
variable as a reference, and using any extensions when the option **-s** or
any equivalents were given.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors, passing the
wrong number of arguments to functions, attempting to call an undefined
function, and attempting to use a **void** function call as a value in an
expression.
**4**
: A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, failing to open
files, attempting to use files that do not have only ASCII characters (bc(1)
only accepts ASCII characters), attempting to open a directory as a file,
and giving invalid command-line options.
The exit status **4** is special; when a fatal error occurs, bc(1) always exits
and returns **4**, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interactive mode
(see the **INTERACTIVE MODE** section), since bc(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
**-i** flag or **-\-interactive** option.
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **BC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **BC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
mode on.
If the environment variable **BC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
**stdout**, and **stderr** are connected to a TTY and the **BC_TTY_MODE**
environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
information.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **BC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, bc(1) will
exit.
However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
default is an integer and non-zero, then bc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If bc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If bc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
can seem as though bc(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 bc(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.
**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is **SIGHUP**; in that
case, and only when bc(1) is in TTY mode (see the **TTY MODE** section), a
**SIGHUP** will cause bc(1) to clean up and exit.
# COMMAND LINE HISTORY
bc(1) supports interactive command-line editing.
If bc(1) can be in TTY mode (see the **TTY MODE** section), history can be
enabled. This means that command-line history can only be enabled when
**stdin**, **stdout**, and **stderr** are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment variable
**BC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
If history is enabled, previous lines can be recalled and edited with the arrow
keys.
**Note**: tabs are converted to 8 spaces.
# LOCALES
This bc(1) ships with support for adding error messages for different locales
and thus, supports **LC_MESSAGES**.
# SEE ALSO
dc(1)
# STANDARDS
bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
specification. The flags **-efghiqsvVw**, all long options, and the extensions
noted above are extensions to that specification.
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**.
This bc(1) supports error messages for different locales, and thus, it supports
**LC_MESSAGES**.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
diff --git a/manuals/bc/EH.1 b/manuals/bc/EH.1
index aca8e3b65f34..0bdfaa9fe14b 100644
--- a/manuals/bc/EH.1
+++ b/manuals/bc/EH.1
@@ -1,1556 +1,1601 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH NAME
.PP
bc - arbitrary-precision decimal arithmetic language and calculator
.SH SYNOPSIS
.PP
\f[B]bc\f[R] [\f[B]-ghilPqRsvVw\f[R]] [\f[B]--global-stacks\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]]
[\f[B]--no-prompt\f[R]] [\f[B]--no-read-prompt\f[R]] [\f[B]--quiet\f[R]]
[\f[B]--standard\f[R]] [\f[B]--warn\f[R]] [\f[B]--version\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX.
(The current standard is
here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).)
The language provides unlimited precision decimal arithmetic and is
somewhat C-like, but there are differences.
Such differences will be noted in this document.
.PP
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from \f[B]stdin\f[R].
.PP
This bc(1) is a drop-in replacement for \f[I]any\f[R] bc(1), including
(and especially) the GNU bc(1).
.PP
\f[B]Note\f[R]: If running this bc(1) on \f[I]any\f[R] script meant for
another bc(1) gives a parse error, it is probably because a word this
bc(1) reserves as a keyword is used as the name of a function, variable,
or array.
To fix that, use the command-line option \f[B]-r\f[R] \f[I]keyword\f[R],
where \f[I]keyword\f[R] is the keyword that is used as a name in the
script.
For more information, see the \f[B]OPTIONS\f[R] section.
.PP
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported.
See the \f[B]BUGS\f[R] section.
.SH OPTIONS
.PP
The following are the options that bc(1) accepts.
.TP
\f[B]-g\f[R], \f[B]--global-stacks\f[R]
Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]
into stacks.
.RS
.PP
This has the effect that a copy of the current value of all three are
pushed onto a stack for every function call, as well as popped when
every function returns.
This means that functions can assign to any and all of those globals
without worrying that the change will affect other functions.
Thus, a hypothetical function named \f[B]output(x,b)\f[R] that simply
printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this:
.IP
.nf
\f[C]
define void output(x, b) {
obase=b
x
}
\f[R]
.fi
.PP
instead of like this:
.IP
.nf
\f[C]
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
\f[R]
.fi
.PP
This makes writing functions much easier.
.PP
However, since using this flag means that functions cannot set
\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R] globally, functions
that are made to do so cannot work anymore.
There are two possible use cases for that, and each has a solution.
.PP
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases.
Examples:
.IP
.nf
\f[C]
alias d2o=\[dq]bc -e ibase=A -e obase=8\[dq]
alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq]
\f[R]
.fi
.PP
Second, if the purpose of a function is to set \f[B]ibase\f[R],
\f[B]obase\f[R], or \f[B]scale\f[R] globally for any other purpose, it
could be split into one to three functions (based on how many globals it
sets) and each of those functions could return the desired value for a
global.
.PP
If the behavior of this option is desired for every run of bc(1), then
users could make sure to define \f[B]BC_ENV_ARGS\f[R] and include this
option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more
details).
.PP
If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option
is ignored.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-l\f[R], \f[B]--mathlib\f[R]
Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R]
and loads the included math library before running any code, including
any expressions or files specified on the command line.
.RS
.PP
To learn what is in the library, see the \f[B]LIBRARY\f[R] section.
.RE
.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.RS
.PP
These options override the \f[B]BC_PROMPT\f[R] and \f[B]BC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of bc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]read()\f[R] built-in function is called.
.PP
These options \f[I]do\f[R] override the \f[B]BC_PROMPT\f[R] and
\f[B]BC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-r\f[R] \f[I]keyword\f[R], \f[B]--redefine\f[R]=\f[I]keyword\f[R]
Redefines \f[I]keyword\f[R] in order to allow it to be used as a
function, variable, or array name.
This is useful when this bc(1) gives parse errors when parsing scripts
meant for other bc(1) implementations.
.RS
.PP
The keywords this bc(1) allows to be redefined are:
.IP \[bu] 2
\f[B]abs\f[R]
.IP \[bu] 2
\f[B]asciify\f[R]
.IP \[bu] 2
\f[B]continue\f[R]
.IP \[bu] 2
\f[B]divmod\f[R]
.IP \[bu] 2
\f[B]else\f[R]
.IP \[bu] 2
\f[B]halt\f[R]
.IP \[bu] 2
\f[B]last\f[R]
.IP \[bu] 2
\f[B]limits\f[R]
.IP \[bu] 2
\f[B]maxibase\f[R]
.IP \[bu] 2
\f[B]maxobase\f[R]
.IP \[bu] 2
\f[B]maxscale\f[R]
.IP \[bu] 2
\f[B]modexp\f[R]
.IP \[bu] 2
\f[B]print\f[R]
.IP \[bu] 2
\f[B]read\f[R]
.IP \[bu] 2
\f[B]stream\f[R]
.PP
If any of those keywords are used as a function, variable, or array name
in a script, use this option with the keyword as the argument.
If multiple are used, use this option for all of them; it can be used
multiple times.
.PP
Keywords are \f[I]not\f[R] redefined when parsing the builtin math
library (see the \f[B]LIBRARY\f[R] section).
.PP
It is a fatal error to redefine keywords mandated by the POSIX standard.
It is a fatal error to attempt to redefine words that this bc(1) does
not reserve as keywords.
.RE
.TP
\f[B]-q\f[R], \f[B]--quiet\f[R]
This option is for compatibility with the GNU
bc(1) (https://www.gnu.org/software/bc/); it is a no-op.
Without this option, GNU bc(1) prints a copyright header.
This bc(1) only prints the copyright header if one or more of the
\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-s\f[R], \f[B]--standard\f[R]
Process exactly the language defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
and error if any extensions are used.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-w\f[R], \f[B]--warn\f[R]
Like \f[B]-s\f[R] and \f[B]--standard\f[R], except that warnings (and
not errors) are printed for non-standard extensions and execution
continues normally.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]BC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files or expressions are given by the \f[B]-f\f[R],
\f[B]--file\f[R], \f[B]-e\f[R], or \f[B]--expression\f[R] options, then
bc(1) read from \f[B]stdin\f[R].
.PP
However, there are a few caveats to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if the parse cannot complete.
That means that starting a string without ending it or starting a
function, \f[B]if\f[R] statement, or loop without ending it will also
cause bc(1) to not execute.
.PP
Second, after an \f[B]if\f[R] statement, bc(1) doesn\[cq]t know if an
\f[B]else\f[R] statement will follow, so it will not execute until it
knows there will not be an \f[B]else\f[R] statement.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]bc >&-\f[R], it will quit with an error.
This is done so that bc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]bc 2>&-\f[R], it will quit with an error.
This is done so that bc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
which is a much more thorough resource for the language this bc(1)
accepts.
This section is meant to be a summary and a listing of all the
extensions to the standard.
.PP
In the sections below, \f[B]E\f[R] means expression, \f[B]S\f[R] means
statement, and \f[B]I\f[R] means identifier.
.PP
Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be
followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase
letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores
(\f[B]_\f[R]).
The regex is \f[B][a-z][a-z0-9_]*\f[R].
Identifiers with more than one character (letter) are a
\f[B]non-portable extension\f[R].
.PP
\f[B]ibase\f[R] is a global variable determining how to interpret
constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R]
(\f[B]--warn\f[R]) flags were not given on the command line, the max
allowable value for \f[B]ibase\f[R] is \f[B]36\f[R].
Otherwise, it is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in bc(1)
programs with the \f[B]maxibase()\f[R] built-in function.
.PP
\f[B]obase\f[R] is a global variable determining how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and
can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in
function.
The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R].
Values are output in the specified base.
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a global variable that sets the precision of any operations, with
exceptions.
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R]
and can be queried in bc(1) programs with the \f[B]maxscale()\f[R]
built-in function.
.PP
bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables.
All \f[I]local\f[R] variables are local to the function; they are
parameters or are introduced in the \f[B]auto\f[R] list of a function
(see the \f[B]FUNCTIONS\f[R] section).
If a variable is accessed which is not a parameter or in the
\f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R].
If a parent function has a \f[I]local\f[R] variable version of a
variable that a child function considers \f[I]global\f[R], the value of
that \f[I]global\f[R] variable in the child function is the value of the
variable in the parent function, not the value of the actual
\f[I]global\f[R] variable.
.PP
All of the above applies to arrays as well.
.PP
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence
operator is an assignment operator \f[I]and\f[R] the expression is
notsurrounded by parentheses.
.PP
The value that is printed is also assigned to the special variable
\f[B]last\f[R].
A single dot (\f[B].\f[R]) may also be used as a synonym for
\f[B]last\f[R].
These are \f[B]non-portable extensions\f[R].
.PP
Either semicolons or newlines may separate statements.
.SS Comments
.PP
There are two kinds of comments:
.IP "1." 3
Block comments are enclosed in \f[B]/*\f[R] and \f[B]*/\f[R].
.IP "2." 3
Line comments go from \f[B]#\f[R] until, and not including, the next
newline.
This is a \f[B]non-portable extension\f[R].
.SS Named Expressions
.PP
The following are named expressions in bc(1):
.IP "1." 3
Variables: \f[B]I\f[R]
.IP "2." 3
Array Elements: \f[B]I[E]\f[R]
.IP "3." 3
\f[B]ibase\f[R]
.IP "4." 3
\f[B]obase\f[R]
.IP "5." 3
\f[B]scale\f[R]
.IP "6." 3
\f[B]last\f[R] or a single dot (\f[B].\f[R])
.PP
Number 6 is a \f[B]non-portable extension\f[R].
.PP
Variables and arrays do not interfere; users can have arrays named the
same as variables.
This also applies to functions (see the \f[B]FUNCTIONS\f[R] section), so
a user can have a variable, array, and function that all have the same
name, and they will not shadow each other, whether inside of functions
or not.
.PP
Named expressions are required as the operand of
\f[B]increment\f[R]/\f[B]decrement\f[R] operators and as the left side
of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R]
subsection).
.SS Operands
.PP
The following are valid operands in bc(1):
.IP " 1." 4
Numbers (see the \f[I]Numbers\f[R] subsection below).
.IP " 2." 4
Array indices (\f[B]I[E]\f[R]).
.IP " 3." 4
\f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence).
.IP " 4." 4
\f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R].
\f[B]E\f[R] must be non-negative.
.IP " 5." 4
\f[B]length(E)\f[R]: The number of significant decimal digits in
\f[B]E\f[R].
Returns \f[B]1\f[R] for \f[B]0\f[R] with no decimal places.
If given a string, the length of the string is returned.
Passing a string to \f[B]length(E)\f[R] is a \f[B]non-portable
extension\f[R].
.IP " 6." 4
\f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 7." 4
\f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R].
.IP " 8." 4
\f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 9." 4
\f[B]modexp(E, E, E)\f[R]: Modular exponentiation, where the first
expression is the base, the second is the exponent, and the third is the
modulus.
All three values must be integers.
The second argument must be non-negative.
The third argument must be non-zero.
This is a \f[B]non-portable extension\f[R].
.IP "10." 4
\f[B]divmod(E, E, I[])\f[R]: Division and modulus in one operation.
This is for optimization.
The first expression is the dividend, and the second is the divisor,
which must be non-zero.
The return value is the quotient, and the modulus is stored in index
\f[B]0\f[R] of the provided array (the last argument).
This is a \f[B]non-portable extension\f[R].
.IP "11." 4
\f[B]asciify(E)\f[R]: If \f[B]E\f[R] is a string, returns a string that
is the first letter of its argument.
If it is a number, calculates the number mod \f[B]256\f[R] and returns
that number as a one-character string.
This is a \f[B]non-portable extension\f[R].
.IP "12." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.IP "13." 4
\f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an
expression.
The result of that expression is the result of the \f[B]read()\f[R]
operand.
This is a \f[B]non-portable extension\f[R].
.IP "14." 4
\f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "15." 4
\f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "16." 4
\f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R].
This is a \f[B]non-portable extension\f[R].
+.IP "17." 4
+\f[B]line_length()\f[R]: The line length set with
+\f[B]BC_LINE_LENGTH\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
+section).
+This is a \f[B]non-portable extension\f[R].
+.IP "18." 4
+\f[B]global_stacks()\f[R]: \f[B]0\f[R] if global stacks are not enabled
+with the \f[B]-g\f[R] or \f[B]--global-stacks\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "19." 4
+\f[B]leading_zero()\f[R]: \f[B]0\f[R] if leading zeroes are not enabled
+with the \f[B]-z\f[R] or \f[B]\[en]leading-zeroes\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
.SS Numbers
.PP
Numbers are strings made up of digits, uppercase letters, and at most
\f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R].
.SS Operators
.PP
The following arithmetic and logical operators can be used.
They are listed in order of decreasing precedence.
Operators in the same group have the same precedence.
.TP
\f[B]++\f[R] \f[B]--\f[R]
Type: Prefix and Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]increment\f[R], \f[B]decrement\f[R]
.RE
.TP
\f[B]-\f[R] \f[B]!\f[R]
Type: Prefix
.RS
.PP
Associativity: None
.PP
Description: \f[B]negation\f[R], \f[B]boolean not\f[R]
.RE
.TP
\f[B]\[ha]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]power\f[R]
.RE
.TP
\f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R]
.RE
.TP
\f[B]+\f[R] \f[B]-\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]add\f[R], \f[B]subtract\f[R]
.RE
.TP
\f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]assignment\f[R]
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]relational\f[R]
.RE
.TP
\f[B]&&\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean and\f[R]
.RE
.TP
\f[B]||\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean or\f[R]
.RE
.PP
The operators will be described in more detail below.
.TP
\f[B]++\f[R] \f[B]--\f[R]
The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R]
operators behave exactly like they would in C.
They require a named expression (see the \f[I]Named Expressions\f[R]
subsection) as an operand.
.RS
.PP
The prefix versions of these operators are more efficient; use them
where possible.
.RE
.TP
\f[B]-\f[R]
The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts
to negate any expression with the value \f[B]0\f[R].
Otherwise, a copy of the expression with its sign flipped is returned.
.TP
\f[B]!\f[R]
The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression
is \f[B]0\f[R], or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator,
as it would be in C) takes two expressions and raises the first to the
power of the value of the second.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]), and if it
is negative, the first value must be non-zero.
.RE
.TP
\f[B]*\f[R]
The \f[B]multiply\f[R] operator takes two expressions, multiplies them,
and returns the product.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The \f[B]divide\f[R] operator takes two expressions, divides them, and
returns the quotient.
The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]%\f[R]
The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R] and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]+\f[R]
The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the
max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]-\f[R]
The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to
the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R]
The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and
\f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named
Expressions\f[R] subsection).
.RS
.PP
For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to
\f[B]a\f[R].
For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to
the corresponding arithmetic operator and the result is assigned to
\f[B]a\f[R].
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and if the relation holds, according to C language
semantics, the result is \f[B]1\f[R].
Otherwise, it is \f[B]0\f[R].
.RS
.PP
Note that unlike in C, these operators have a lower precedence than the
\f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is
interpreted as \f[B](a=b)>c\f[R].
.PP
Also, unlike the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
requires, these operators can appear anywhere any other expressions can
be used.
This allowance is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]&&\f[R]
The \f[B]boolean and\f[R] operator takes two expressions and returns
\f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]||\f[R]
The \f[B]boolean or\f[R] operator takes two expressions and returns
\f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R]
otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Statements
.PP
The following items are statements:
.IP " 1." 4
\f[B]E\f[R]
.IP " 2." 4
\f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R]
\f[B]}\f[R]
.IP " 3." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 4." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
\f[B]else\f[R] \f[B]S\f[R]
.IP " 5." 4
\f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 6." 4
\f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R]
\f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 7." 4
An empty statement
.IP " 8." 4
\f[B]break\f[R]
.IP " 9." 4
\f[B]continue\f[R]
.IP "10." 4
\f[B]quit\f[R]
.IP "11." 4
\f[B]halt\f[R]
.IP "12." 4
\f[B]limits\f[R]
.IP "13." 4
A string of characters, enclosed in double quotes
.IP "14." 4
\f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "15." 4
\f[B]stream\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "16." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.PP
Numbers 4, 9, 11, 12, 14, 15, and 16 are \f[B]non-portable
extensions\f[R].
.PP
Also, as a \f[B]non-portable extension\f[R], any or all of the
expressions in the header of a for loop may be omitted.
If the condition (second expression) is omitted, it is assumed to be a
constant \f[B]1\f[R].
.PP
The \f[B]break\f[R] statement causes a loop to stop iterating and resume
execution immediately following a loop.
This is only allowed in loops.
.PP
The \f[B]continue\f[R] statement causes a loop iteration to stop early
and returns to the start of the loop, including testing the loop
condition.
This is only allowed in loops.
.PP
The \f[B]if\f[R] \f[B]else\f[R] statement does the same thing as in C.
.PP
The \f[B]quit\f[R] statement causes bc(1) to quit, even if it is on a
branch that will not be executed (it is a compile-time command).
.PP
The \f[B]halt\f[R] statement causes bc(1) to quit, if it is executed.
(Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement
that is not executed, bc(1) does not quit.)
.PP
The \f[B]limits\f[R] statement prints the limits that this bc(1) is
subject to.
This is like the \f[B]quit\f[R] statement in that it is a compile-time
command.
.PP
An expression by itself is evaluated and printed, followed by a newline.
.SS Strings
.PP
If strings appear as a statement by themselves, they are printed without
a trailing newline.
.PP
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements.
They can also be passed to functions in variable parameters.
.PP
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
.PP
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section).
.PP
Assigning strings to variables and array elements and passing them to
functions are \f[B]non-portable extensions\f[R].
.SS Print Statement
.PP
The \[lq]expressions\[rq] in a \f[B]print\f[R] statement may also be
strings.
If they are, there are backslash escape sequences that are interpreted
specially.
What those sequences are, and what they cause to be printed, are shown
below:
.PP
\f[B]\[rs]a\f[R]: \f[B]\[rs]a\f[R]
.PP
\f[B]\[rs]b\f[R]: \f[B]\[rs]b\f[R]
.PP
\f[B]\[rs]\[rs]\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]e\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]f\f[R]: \f[B]\[rs]f\f[R]
.PP
\f[B]\[rs]n\f[R]: \f[B]\[rs]n\f[R]
.PP
\f[B]\[rs]q\f[R]: \f[B]\[lq]\f[R]
.PP
\f[B]\[rs]r\f[R]: \f[B]\[rs]r\f[R]
.PP
\f[B]\[rs]t\f[R]: \f[B]\[rs]t\f[R]
.PP
Any other character following a backslash causes the backslash and
character to be printed as-is.
.PP
Any non-string expression in a print statement shall be assigned to
\f[B]last\f[R], like any other expression that is printed.
.SS Stream Statement
.PP
The \[lq]expressions in a \f[B]stream\f[R] statement may also be
strings.
.PP
If a \f[B]stream\f[R] statement is given a string, it prints the string
as though the string had appeared as its own statement.
In other words, the \f[B]stream\f[R] statement prints strings normally,
without a newline.
.PP
If a \f[B]stream\f[R] statement is given a number, a copy of it is
truncated and its absolute value is calculated.
The result is then printed as though \f[B]obase\f[R] is \f[B]256\f[R]
and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
.SS Order of Evaluation
.PP
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations.
This means, for example, assuming that \f[B]i\f[R] is equal to
\f[B]0\f[R], in the expression
.IP
.nf
\f[C]
a[i++] = i++
\f[R]
.fi
.PP
the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and
\f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression.
.PP
This includes function arguments.
Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in
the expression
.IP
.nf
\f[C]
x(i++, i++)
\f[R]
.fi
.PP
the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the
second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to
\f[B]2\f[R] before the function starts executing.
.SH FUNCTIONS
.PP
Function definitions are as follows:
.IP
.nf
\f[C]
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
\f[R]
.fi
.PP
Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be
replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an
array, and any \f[B]I\f[R] in the parameter list may be replaced with
\f[B]*I[]\f[R] to make a parameter an array reference.
Callers of functions that take array references should not put an
asterisk in the call; they must be called with just \f[B]I[]\f[R] like
normal array parameters and will be automatically converted into
references.
.PP
As a \f[B]non-portable extension\f[R], the opening brace of a
\f[B]define\f[R] statement may appear on the next line.
.PP
As a \f[B]non-portable extension\f[R], the return statement may also be
in one of the following forms:
.IP "1." 3
\f[B]return\f[R]
.IP "2." 3
\f[B]return\f[R] \f[B](\f[R] \f[B])\f[R]
.IP "3." 3
\f[B]return\f[R] \f[B]E\f[R]
.PP
The first two, or not specifying a \f[B]return\f[R] statement, is
equivalent to \f[B]return (0)\f[R], unless the function is a
\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection
below).
.SS Void Functions
.PP
Functions can also be \f[B]void\f[R] functions, defined as follows:
.IP
.nf
\f[C]
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
\f[R]
.fi
.PP
They can only be used as standalone expressions, where such an
expression would be printed alone, except in a print statement.
.PP
Void functions can only use the first two \f[B]return\f[R] statements
listed above.
They can also omit the return statement entirely.
.PP
The word \[lq]void\[rq] is not treated as a keyword; it is still
possible to have variables, arrays, and functions named \f[B]void\f[R].
The word \[lq]void\[rq] is only treated specially right after the
\f[B]define\f[R] keyword.
.PP
This is a \f[B]non-portable extension\f[R].
.SS Array References
.PP
For any array in the parameter list, if the array is declared in the
form
.IP
.nf
\f[C]
*I[]
\f[R]
.fi
.PP
it is a \f[B]reference\f[R].
Any changes to the array in the function are reflected, when the
function returns, to the array that was passed in.
.PP
Other than this, all function arguments are passed by value.
.PP
This is a \f[B]non-portable extension\f[R].
.SH LIBRARY
.PP
All of the functions below are available when the \f[B]-l\f[R] or
\f[B]--mathlib\f[R] command-line flags are given.
.SS Standard Library
.PP
The
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
defines the following functions for the math library:
.TP
\f[B]s(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]c(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l(x)\f[R]
Returns the natural logarithm of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]e(x)\f[R]
Returns the mathematical constant \f[B]e\f[R] raised to the power of
\f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]j(x, n)\f[R]
Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.SS Transcendental Functions
.PP
All transcendental functions can return slightly inaccurate results (up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)).
This is unavoidable, and this
article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains
why it is impossible and unnecessary to calculate exact results for the
transcendental functions.
.PP
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (\f[B]scale\f[R]) set to at least 1 higher
than is necessary.
If exact results are \f[I]absolutely\f[R] required, users can double the
precision (\f[B]scale\f[R]) and then truncate.
.PP
The transcendental functions in the standard math library are:
.IP \[bu] 2
\f[B]s(x)\f[R]
.IP \[bu] 2
\f[B]c(x)\f[R]
.IP \[bu] 2
\f[B]a(x)\f[R]
.IP \[bu] 2
\f[B]l(x)\f[R]
.IP \[bu] 2
\f[B]e(x)\f[R]
.IP \[bu] 2
\f[B]j(x, n)\f[R]
.SH RESET
.PP
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets.
This means that several things happen.
.PP
First, any functions 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.
.PP
Thus, when bc(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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.PP
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This bc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R]
can be queried with the \f[B]limits\f[R] statement.
.PP
In addition, this bc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bc(1):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bc(1) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
The actual values can be queried with the \f[B]limits\f[R] statement.
.PP
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
.PP
bc(1) recognizes the following environment variables:
.TP
\f[B]POSIXLY_CORRECT\f[R]
If this variable exists (no matter the contents), bc(1) behaves as if
the \f[B]-s\f[R] option was given.
.TP
\f[B]BC_ENV_ARGS\f[R]
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line arguments.
These are always processed first, so any files given in
\f[B]BC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 bc(1) runs.
.RS
.PP
The code that parses \f[B]BC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`bc' file.bc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]BC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]BC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length,
including the backslash (\f[B]\[rs]\f[R]).
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]BC_BANNER\f[R]
If this environment variable exists and contains an integer, then a
non-zero value activates the copyright banner when bc(1) is in
interactive mode, while zero deactivates it.
.RS
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
does not print the banner when not in interactive mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_SIGINT_RESET\f[R]
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes bc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then bc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use
TTY mode, and zero makes bc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a
prompt, and zero or a non-integer makes bc(1) not use a prompt.
If this environment variable does not exist and \f[B]BC_TTY_MODE\f[R]
does, then the value of the \f[B]BC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]BC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
bc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], taking the square root of a
negative number, attempting to convert a negative number to a hardware
integer, overflow when converting a number to a hardware integer,
overflow when calculating the size of a number, and attempting to use a
non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]) operator and the corresponding assignment
operator.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an invalid
print statement, giving an invalid function definition, attempting to
assign to an expression that is not a named expression (see the
\f[I]Named Expressions\f[R] subsection of the \f[B]SYNTAX\f[R] section),
giving an invalid \f[B]auto\f[R] list, having a duplicate
\f[B]auto\f[R]/function parameter, failing to find the end of a code
block, attempting to return a value from a \f[B]void\f[R] function,
attempting to use a variable as a reference, and using any extensions
when the option \f[B]-s\f[R] or any equivalents were given.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors, passing the wrong number of
arguments to functions, attempting to call an undefined function, and
attempting to use a \f[B]void\f[R] function call as a value in an
expression.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
Fatal errors include memory allocation errors, I/O errors, failing to
open files, attempting to use files that do not have only ASCII
characters (bc(1) only accepts ASCII characters), attempting to open a
directory as a file, and giving invalid command-line options.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, bc(1)
always exits and returns \f[B]4\f[R], no matter what mode bc(1) is in.
.PP
The other statuses will only be returned when bc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
bc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Per the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, bc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
bc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]BC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, bc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]BC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, bc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]BC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then bc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]BC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]BC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]BC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]BC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]BC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause bc(1) to do one of two things.
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, bc(1) will exit.
.PP
However, if bc(1) is in interactive mode, and the
\f[B]BC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then bc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If bc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If bc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] is sent to bc(1) as it is
executing a file, it can seem as though bc(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
bc(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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause bc(1) to clean up and
exit, and it uses the default handler for all other signals.
.SH LOCALES
.PP
This bc(1) ships with support for adding error messages for different
locales and thus, supports \f[B]LC_MESSAGES\f[R].
.SH SEE ALSO
.PP
dc(1)
.SH STANDARDS
.PP
bc(1) is compliant with the IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
The flags \f[B]-efghiqsvVw\f[R], all long options, and the extensions
noted above are extensions to that specification.
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
.PP
This bc(1) supports error messages for different locales, and thus, it
supports \f[B]LC_MESSAGES\f[R].
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bc/EH.1.md b/manuals/bc/EH.1.md
index 89fc2b54f27f..044330b7fe0a 100644
--- a/manuals/bc/EH.1.md
+++ b/manuals/bc/EH.1.md
@@ -1,1309 +1,1339 @@
# NAME
bc - arbitrary-precision decimal arithmetic language and calculator
# SYNOPSIS
**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# DESCRIPTION
bc(1) is an interactive processor for a language first standardized in 1991 by
POSIX. (The current standard is [here][1].) The language provides unlimited
precision decimal arithmetic and is somewhat C-like, but there are differences.
Such differences will be noted in this document.
After parsing and handling options, this bc(1) reads any files given on the
command line and executes them before reading from **stdin**.
This bc(1) is a drop-in replacement for *any* bc(1), including (and especially)
the GNU bc(1).
**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
parse error, it is probably because a word this bc(1) reserves as a keyword is
used as the name of a function, variable, or array. To fix that, use the
command-line option **-r** *keyword*, where *keyword* is the keyword that is
used as a name in the script. For more information, see the **OPTIONS** section.
If parsing scripts meant for other bc(1) implementations still does not work,
that is a bug and should be reported. See the **BUGS** section.
# OPTIONS
The following are the options that bc(1) accepts.
**-g**, **-\-global-stacks**
: Turns the globals **ibase**, **obase**, and **scale** into stacks.
This has the effect that a copy of the current value of all three are pushed
onto a stack for every function call, as well as popped when every function
returns. This means that functions can assign to any and all of those
globals without worrying that the change will affect other functions.
Thus, a hypothetical function named **output(x,b)** that simply printed
**x** in base **b** could be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
However, since using this flag means that functions cannot set **ibase**,
**obase**, or **scale** globally, functions that are made to do so cannot
work anymore. There are two possible use cases for that, and each has a
solution.
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set **ibase**, **obase**, or
**scale** globally for any other purpose, it could be split into one to
three functions (based on how many globals it sets) and each of those
functions could return the desired value for a global.
If the behavior of this option is desired for every run of bc(1), then users
could make sure to define **BC_ENV_ARGS** and include this option (see the
**ENVIRONMENT VARIABLES** section for more details).
If **-s**, **-w**, or any equivalents are used, this option is ignored.
This is a **non-portable extension**.
**-h**, **-\-help**
: Prints a usage message and quits.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-l**, **-\-mathlib**
: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
math library before running any code, including any expressions or files
specified on the command line.
To learn what is in the library, see the **LIBRARY** section.
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in bc(1). Most of those users
would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section).
These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of bc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **read()** built-in function is called.
These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-r** *keyword*, **-\-redefine**=*keyword*
: Redefines *keyword* in order to allow it to be used as a function, variable,
or array name. This is useful when this bc(1) gives parse errors when
parsing scripts meant for other bc(1) implementations.
The keywords this bc(1) allows to be redefined are:
* **abs**
* **asciify**
* **continue**
* **divmod**
* **else**
* **halt**
* **last**
* **limits**
* **maxibase**
* **maxobase**
* **maxscale**
* **modexp**
* **print**
* **read**
* **stream**
If any of those keywords are used as a function, variable, or array name in
a script, use this option with the keyword as the argument. If multiple are
used, use this option for all of them; it can be used multiple times.
Keywords are *not* redefined when parsing the builtin math library (see the
**LIBRARY** section).
It is a fatal error to redefine keywords mandated by the POSIX standard. It
is a fatal error to attempt to redefine words that this bc(1) does not
reserve as keywords.
**-q**, **-\-quiet**
: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
Without this option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the **-v**, **-V**, or
**-\-version** options are given.
This is a **non-portable extension**.
**-s**, **-\-standard**
: Process exactly the language defined by the [standard][1] and error if any
extensions are used.
This is a **non-portable extension**.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
This is a **non-portable extension**.
**-w**, **-\-warn**
: Like **-s** and **-\-standard**, except that warnings (and not errors) are
printed for non-standard extensions and execution continues normally.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
**-\-expression** options, then bc(1) read from **stdin**.
However, there are a few caveats to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
the parse cannot complete. That means that starting a string without ending it
or starting a function, **if** statement, or loop without ending it will also
cause bc(1) to not execute.
Second, after an **if** statement, bc(1) doesn't know if an **else** statement
will follow, so it will not execute until it knows there will not be an **else**
statement.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **bc >&-**, it will quit with an error. This
is done so that bc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This
is done so that bc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences. This
bc(1) follows the [POSIX standard][1], which is a much more thorough resource
for the language this bc(1) accepts. This section is meant to be a summary and a
listing of all the extensions to the standard.
In the sections below, **E** means expression, **S** means statement, and **I**
means identifier.
Identifiers (**I**) start with a lowercase letter and can be followed by any
number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
Identifiers with more than one character (letter) are a
**non-portable extension**.
**ibase** is a global variable determining how to interpret constant numbers. It
is the "input" base, or the number base used for interpreting input numbers.
**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
(**-\-warn**) flags were not given on the command line, the max allowable value
for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
**ibase** is **2**. The max allowable value for **ibase** can be queried in
bc(1) programs with the **maxibase()** built-in function.
**obase** is a global variable determining how to output results. It is the
"output" base, or the number base used for outputting numbers. **obase** is
initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
can be queried in bc(1) programs with the **maxobase()** built-in function. The
min allowable value for **obase** is **2**. Values are output in the specified
base.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a global variable that
sets the precision of any operations, with exceptions. **scale** is initially
**0**. **scale** cannot be negative. The max allowable value for **scale** is
**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
built-in function.
bc(1) has both *global* variables and *local* variables. All *local*
variables are local to the function; they are parameters or are introduced in
the **auto** list of a function (see the **FUNCTIONS** section). If a variable
is accessed which is not a parameter or in the **auto** list, it is assumed to
be *global*. If a parent function has a *local* variable version of a variable
that a child function considers *global*, the value of that *global* variable in
the child function is the value of the variable in the parent function, not the
value of the actual *global* variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence operator is an
assignment operator *and* the expression is notsurrounded by parentheses.
The value that is printed is also assigned to the special variable **last**. A
single dot (**.**) may also be used as a synonym for **last**. These are
**non-portable extensions**.
Either semicolons or newlines may separate statements.
## Comments
There are two kinds of comments:
1. Block comments are enclosed in **/\*** and **\*/**.
2. Line comments go from **#** until, and not including, the next newline. This
is a **non-portable extension**.
## Named Expressions
The following are named expressions in bc(1):
1. Variables: **I**
2. Array Elements: **I[E]**
3. **ibase**
4. **obase**
5. **scale**
6. **last** or a single dot (**.**)
Number 6 is a **non-portable extension**.
Variables and arrays do not interfere; users can have arrays named the same as
variables. This also applies to functions (see the **FUNCTIONS** section), so a
user can have a variable, array, and function that all have the same name, and
they will not shadow each other, whether inside of functions or not.
Named expressions are required as the operand of **increment**/**decrement**
operators and as the left side of **assignment** operators (see the *Operators*
subsection).
## Operands
The following are valid operands in bc(1):
1. Numbers (see the *Numbers* subsection below).
2. Array indices (**I[E]**).
3. **(E)**: The value of **E** (used to change precedence).
4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
5. **length(E)**: The number of significant decimal digits in **E**. Returns
**1** for **0** with no decimal places. If given a string, the length of the
string is returned. Passing a string to **length(E)** is a **non-portable
extension**.
6. **length(I[])**: The number of elements in the array **I**. This is a
**non-portable extension**.
7. **scale(E)**: The *scale* of **E**.
8. **abs(E)**: The absolute value of **E**. This is a **non-portable
extension**.
9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
the base, the second is the exponent, and the third is the modulus. All
three values must be integers. The second argument must be non-negative. The
third argument must be non-zero. This is a **non-portable extension**.
10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
optimization. The first expression is the dividend, and the second is the
divisor, which must be non-zero. The return value is the quotient, and the
modulus is stored in index **0** of the provided array (the last argument).
This is a **non-portable extension**.
11. **asciify(E)**: If **E** is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number mod **256**
and returns that number as a one-character string. This is a **non-portable
extension**.
12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a non-**void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
13. **read()**: Reads a line from **stdin** and uses that as an expression. The
result of that expression is the result of the **read()** operand. This is a
**non-portable extension**.
14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
extension**.
15. **maxobase()**: The max allowable **obase**. This is a **non-portable
extension**.
16. **maxscale()**: The max allowable **scale**. This is a **non-portable
extension**.
+17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
+ **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
+18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
+ or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
+ or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
## Numbers
Numbers are strings made up of digits, uppercase letters, and at most **1**
period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
letters are equal to **9** + their position in the alphabet (i.e., **A** equals
**10**, or **9+1**). If a digit or letter makes no sense with the current value
of **ibase**, they are set to the value of the highest valid digit in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **Z** alone always equals decimal
**35**.
## Operators
The following arithmetic and logical operators can be used. They are listed in
order of decreasing precedence. Operators in the same group have the same
precedence.
**++** **-\-**
: Type: Prefix and Postfix
Associativity: None
Description: **increment**, **decrement**
**-** **!**
: Type: Prefix
Associativity: None
Description: **negation**, **boolean not**
**\^**
: Type: Binary
Associativity: Right
Description: **power**
**\*** **/** **%**
: Type: Binary
Associativity: Left
Description: **multiply**, **divide**, **modulus**
**+** **-**
: Type: Binary
Associativity: Left
Description: **add**, **subtract**
**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
: Type: Binary
Associativity: Right
Description: **assignment**
**==** **\<=** **\>=** **!=** **\<** **\>**
: Type: Binary
Associativity: Left
Description: **relational**
**&&**
: Type: Binary
Associativity: Left
Description: **boolean and**
**||**
: Type: Binary
Associativity: Left
Description: **boolean or**
The operators will be described in more detail below.
**++** **-\-**
: The prefix and postfix **increment** and **decrement** operators behave
exactly like they would in C. They require a named expression (see the
*Named Expressions* subsection) as an operand.
The prefix versions of these operators are more efficient; use them where
possible.
**-**
: The **negation** operator returns **0** if a user attempts to negate any
expression with the value **0**. Otherwise, a copy of the expression with
its sign flipped is returned.
**!**
: The **boolean not** operator returns **1** if the expression is **0**, or
**0** otherwise.
This is a **non-portable extension**.
**\^**
: The **power** operator (not the **exclusive or** operator, as it would be in
C) takes two expressions and raises the first to the power of the value of
the second. The *scale* of the result is equal to **scale**.
The second expression must be an integer (no *scale*), and if it is
negative, the first value must be non-zero.
**\***
: The **multiply** operator takes two expressions, multiplies them, and
returns the product. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result is
equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The **divide** operator takes two expressions, divides them, and returns the
quotient. The *scale* of the result shall be the value of **scale**.
The second expression must be non-zero.
**%**
: The **modulus** operator takes two expressions, **a** and **b**, and
evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The second expression must be non-zero.
**+**
: The **add** operator takes two expressions, **a** and **b**, and returns the
sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
**-**
: The **subtract** operator takes two expressions, **a** and **b**, and
returns the difference, with a *scale* equal to the max of the *scale*s of
**a** and **b**.
**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
: The **assignment** operators take two expressions, **a** and **b** where
**a** is a named expression (see the *Named Expressions* subsection).
For **=**, **b** is copied and the result is assigned to **a**. For all
others, **a** and **b** are applied as operands to the corresponding
arithmetic operator and the result is assigned to **a**.
**==** **\<=** **\>=** **!=** **\<** **\>**
: The **relational** operators compare two expressions, **a** and **b**, and
if the relation holds, according to C language semantics, the result is
**1**. Otherwise, it is **0**.
Note that unlike in C, these operators have a lower precedence than the
**assignment** operators, which means that **a=b\>c** is interpreted as
**(a=b)\>c**.
Also, unlike the [standard][1] requires, these operators can appear anywhere
any other expressions can be used. This allowance is a
**non-portable extension**.
**&&**
: The **boolean and** operator takes two expressions and returns **1** if both
expressions are non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
**||**
: The **boolean or** operator takes two expressions and returns **1** if one
of the expressions is non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
## Statements
The following items are statements:
1. **E**
2. **{** **S** **;** ... **;** **S** **}**
3. **if** **(** **E** **)** **S**
4. **if** **(** **E** **)** **S** **else** **S**
5. **while** **(** **E** **)** **S**
6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
7. An empty statement
8. **break**
9. **continue**
10. **quit**
11. **halt**
12. **limits**
13. A string of characters, enclosed in double quotes
14. **print** **E** **,** ... **,** **E**
15. **stream** **E** **,** ... **,** **E**
16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
Also, as a **non-portable extension**, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expression) is
omitted, it is assumed to be a constant **1**.
The **break** statement causes a loop to stop iterating and resume execution
immediately following a loop. This is only allowed in loops.
The **continue** statement causes a loop iteration to stop early and returns to
the start of the loop, including testing the loop condition. This is only
allowed in loops.
The **if** **else** statement does the same thing as in C.
The **quit** statement causes bc(1) to quit, even if it is on a branch that will
not be executed (it is a compile-time command).
The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
if it is on a branch of an **if** statement that is not executed, bc(1) does not
quit.)
The **limits** statement prints the limits that this bc(1) is subject to. This
is like the **quit** statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a newline.
## Strings
If strings appear as a statement by themselves, they are printed without a
trailing newline.
In addition to appearing as a lone statement by themselves, strings can be
assigned to variables and array elements. They can also be passed to functions
in variable parameters.
If any statement that expects a string is given a variable that had a string
assigned to it, the statement acts as though it had received a string.
If any math operation is attempted on a string or a variable or array element
that has been assigned a string, an error is raised, and bc(1) resets (see the
**RESET** section).
Assigning strings to variables and array elements and passing them to functions
are **non-portable extensions**.
## Print Statement
The "expressions" in a **print** statement may also be strings. If they are, there
are backslash escape sequences that are interpreted specially. What those
sequences are, and what they cause to be printed, are shown below:
**\\a**: **\\a**
**\\b**: **\\b**
**\\\\**: **\\**
**\\e**: **\\**
**\\f**: **\\f**
**\\n**: **\\n**
**\\q**: **"**
**\\r**: **\\r**
**\\t**: **\\t**
Any other character following a backslash causes the backslash and character to
be printed as-is.
Any non-string expression in a print statement shall be assigned to **last**,
like any other expression that is printed.
## Stream Statement
The "expressions in a **stream** statement may also be strings.
If a **stream** statement is given a string, it prints the string as though the
string had appeared as its own statement. In other words, the **stream**
statement prints strings normally, without a newline.
If a **stream** statement is given a number, a copy of it is truncated and its
absolute value is calculated. The result is then printed as though **obase** is
**256** and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
## Order of Evaluation
All expressions in a statment are evaluated left to right, except as necessary
to maintain order of operations. This means, for example, assuming that **i** is
equal to **0**, in the expression
a[i++] = i++
the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
at the end of the expression.
This includes function arguments. Thus, assuming **i** is equal to **0**, this
means that in the expression
x(i++, i++)
the first argument passed to **x()** is **0**, and the second argument is **1**,
while **i** is equal to **2** before the function starts executing.
# FUNCTIONS
Function definitions are as follows:
```
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
```
Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
make a parameter or **auto** var an array, and any **I** in the parameter list
may be replaced with **\*I[]** to make a parameter an array reference. Callers
of functions that take array references should not put an asterisk in the call;
they must be called with just **I[]** like normal array parameters and will be
automatically converted into references.
As a **non-portable extension**, the opening brace of a **define** statement may
appear on the next line.
As a **non-portable extension**, the return statement may also be in one of the
following forms:
1. **return**
2. **return** **(** **)**
3. **return** **E**
The first two, or not specifying a **return** statement, is equivalent to
**return (0)**, unless the function is a **void** function (see the *Void
Functions* subsection below).
## Void Functions
Functions can also be **void** functions, defined as follows:
```
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
```
They can only be used as standalone expressions, where such an expression would
be printed alone, except in a print statement.
Void functions can only use the first two **return** statements listed above.
They can also omit the return statement entirely.
The word "void" is not treated as a keyword; it is still possible to have
variables, arrays, and functions named **void**. The word "void" is only
treated specially right after the **define** keyword.
This is a **non-portable extension**.
## Array References
For any array in the parameter list, if the array is declared in the form
```
*I[]
```
it is a **reference**. Any changes to the array in the function are reflected,
when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a **non-portable extension**.
# LIBRARY
All of the functions below are available when the **-l** or **-\-mathlib**
command-line flags are given.
## Standard Library
The [standard][1] defines the following functions for the math library:
**s(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**c(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a(x)**
: Returns the arctangent of **x**, in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l(x)**
: Returns the natural logarithm of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**e(x)**
: Returns the mathematical constant **e** raised to the power of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**j(x, n)**
: Returns the bessel integer order **n** (truncated) of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
## Transcendental Functions
All transcendental functions can return slightly inaccurate results (up to 1
[ULP][4]). This is unavoidable, and [this article][5] explains why it is
impossible and unnecessary to calculate exact results for the transcendental
functions.
Because of the possible inaccuracy, I recommend that users call those functions
with the precision (**scale**) set to at least 1 higher than is necessary. If
exact results are *absolutely* required, users can double the precision
(**scale**) and then truncate.
The transcendental functions in the standard math library are:
* **s(x)**
* **c(x)**
* **a(x)**
* **l(x)**
* **e(x)**
* **j(x, n)**
# RESET
When bc(1) encounters an error or a signal that it has a non-default handler
for, it resets. This means that several things happen.
First, any functions 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.
Thus, when bc(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.
Note that this reset behavior is different from the GNU bc(1), which attempts to
start executing the statement right after the one that caused an error.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This bc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
the **limits** statement.
In addition, this bc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bc(1):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bc(1) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_STRING_MAX**
: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
**BC_NAME_MAX**
: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
The actual values can be queried with the **limits** statement.
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.
# ENVIRONMENT VARIABLES
bc(1) recognizes the following environment variables:
**POSIXLY_CORRECT**
: If this variable exists (no matter the contents), bc(1) behaves as if
the **-s** option was given.
**BC_ENV_ARGS**
: This is another way to give command-line arguments to bc(1). They should be
in the same format as all other command-line arguments. These are always
processed first, so any files given in **BC_ENV_ARGS** 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 bc(1) runs.
The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
**"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'bc' file.bc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **BC_ENV_ARGS** 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.
**BC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
lines to that length, including the backslash (**\\**). The default line
length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**BC_BANNER**
: If this environment variable exists and contains an integer, then a non-zero
value activates the copyright banner when bc(1) is in interactive mode,
while zero deactivates it.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) does not print
the banner when not in interactive mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_SIGINT_RESET**
: If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) exits on
**SIGINT** when not in interactive mode.
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1) reset
on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
environment variable exists and is *not* an integer, then bc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use TTY
mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a prompt,
and zero or a non-integer makes bc(1) not use a prompt. If this environment
variable does not exist and **BC_TTY_MODE** does, then the value of the
**BC_TTY_MODE** environment variable is used.
This environment variable and the **BC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
bc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, taking the square root of a negative
number, attempting to convert a negative number to a hardware integer,
overflow when converting a number to a hardware integer, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**) operator and the corresponding assignment operator.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, using a token where it is invalid,
giving an invalid expression, giving an invalid print statement, giving an
invalid function definition, attempting to assign to an expression that is
not a named expression (see the *Named Expressions* subsection of the
**SYNTAX** section), giving an invalid **auto** list, having a duplicate
**auto**/function parameter, failing to find the end of a code block,
attempting to return a value from a **void** function, attempting to use a
variable as a reference, and using any extensions when the option **-s** or
any equivalents were given.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors, passing the
wrong number of arguments to functions, attempting to call an undefined
function, and attempting to use a **void** function call as a value in an
expression.
**4**
: A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, failing to open
files, attempting to use files that do not have only ASCII characters (bc(1)
only accepts ASCII characters), attempting to open a directory as a file,
and giving invalid command-line options.
The exit status **4** is special; when a fatal error occurs, bc(1) always exits
and returns **4**, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interactive mode
(see the **INTERACTIVE MODE** section), since bc(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
**-i** flag or **-\-interactive** option.
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **BC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **BC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
mode on.
If the environment variable **BC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **BC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, bc(1) will
exit.
However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
default is an integer and non-zero, then bc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If bc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If bc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
can seem as though bc(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 bc(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.
**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
default handler for all other signals.
# LOCALES
This bc(1) ships with support for adding error messages for different locales
and thus, supports **LC_MESSAGES**.
# SEE ALSO
dc(1)
# STANDARDS
bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
specification. The flags **-efghiqsvVw**, all long options, and the extensions
noted above are extensions to that specification.
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**.
This bc(1) supports error messages for different locales, and thus, it supports
**LC_MESSAGES**.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
diff --git a/manuals/bc/EHN.1 b/manuals/bc/EHN.1
index 5aff4d53a344..f0519898ad7e 100644
--- a/manuals/bc/EHN.1
+++ b/manuals/bc/EHN.1
@@ -1,1549 +1,1594 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH NAME
.PP
bc - arbitrary-precision decimal arithmetic language and calculator
.SH SYNOPSIS
.PP
\f[B]bc\f[R] [\f[B]-ghilPqRsvVw\f[R]] [\f[B]--global-stacks\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]]
[\f[B]--no-prompt\f[R]] [\f[B]--no-read-prompt\f[R]] [\f[B]--quiet\f[R]]
[\f[B]--standard\f[R]] [\f[B]--warn\f[R]] [\f[B]--version\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX.
(The current standard is
here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).)
The language provides unlimited precision decimal arithmetic and is
somewhat C-like, but there are differences.
Such differences will be noted in this document.
.PP
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from \f[B]stdin\f[R].
.PP
This bc(1) is a drop-in replacement for \f[I]any\f[R] bc(1), including
(and especially) the GNU bc(1).
.PP
\f[B]Note\f[R]: If running this bc(1) on \f[I]any\f[R] script meant for
another bc(1) gives a parse error, it is probably because a word this
bc(1) reserves as a keyword is used as the name of a function, variable,
or array.
To fix that, use the command-line option \f[B]-r\f[R] \f[I]keyword\f[R],
where \f[I]keyword\f[R] is the keyword that is used as a name in the
script.
For more information, see the \f[B]OPTIONS\f[R] section.
.PP
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported.
See the \f[B]BUGS\f[R] section.
.SH OPTIONS
.PP
The following are the options that bc(1) accepts.
.TP
\f[B]-g\f[R], \f[B]--global-stacks\f[R]
Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]
into stacks.
.RS
.PP
This has the effect that a copy of the current value of all three are
pushed onto a stack for every function call, as well as popped when
every function returns.
This means that functions can assign to any and all of those globals
without worrying that the change will affect other functions.
Thus, a hypothetical function named \f[B]output(x,b)\f[R] that simply
printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this:
.IP
.nf
\f[C]
define void output(x, b) {
obase=b
x
}
\f[R]
.fi
.PP
instead of like this:
.IP
.nf
\f[C]
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
\f[R]
.fi
.PP
This makes writing functions much easier.
.PP
However, since using this flag means that functions cannot set
\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R] globally, functions
that are made to do so cannot work anymore.
There are two possible use cases for that, and each has a solution.
.PP
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases.
Examples:
.IP
.nf
\f[C]
alias d2o=\[dq]bc -e ibase=A -e obase=8\[dq]
alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq]
\f[R]
.fi
.PP
Second, if the purpose of a function is to set \f[B]ibase\f[R],
\f[B]obase\f[R], or \f[B]scale\f[R] globally for any other purpose, it
could be split into one to three functions (based on how many globals it
sets) and each of those functions could return the desired value for a
global.
.PP
If the behavior of this option is desired for every run of bc(1), then
users could make sure to define \f[B]BC_ENV_ARGS\f[R] and include this
option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more
details).
.PP
If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option
is ignored.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-l\f[R], \f[B]--mathlib\f[R]
Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R]
and loads the included math library before running any code, including
any expressions or files specified on the command line.
.RS
.PP
To learn what is in the library, see the \f[B]LIBRARY\f[R] section.
.RE
.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.RS
.PP
These options override the \f[B]BC_PROMPT\f[R] and \f[B]BC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of bc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]read()\f[R] built-in function is called.
.PP
These options \f[I]do\f[R] override the \f[B]BC_PROMPT\f[R] and
\f[B]BC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-r\f[R] \f[I]keyword\f[R], \f[B]--redefine\f[R]=\f[I]keyword\f[R]
Redefines \f[I]keyword\f[R] in order to allow it to be used as a
function, variable, or array name.
This is useful when this bc(1) gives parse errors when parsing scripts
meant for other bc(1) implementations.
.RS
.PP
The keywords this bc(1) allows to be redefined are:
.IP \[bu] 2
\f[B]abs\f[R]
.IP \[bu] 2
\f[B]asciify\f[R]
.IP \[bu] 2
\f[B]continue\f[R]
.IP \[bu] 2
\f[B]divmod\f[R]
.IP \[bu] 2
\f[B]else\f[R]
.IP \[bu] 2
\f[B]halt\f[R]
.IP \[bu] 2
\f[B]last\f[R]
.IP \[bu] 2
\f[B]limits\f[R]
.IP \[bu] 2
\f[B]maxibase\f[R]
.IP \[bu] 2
\f[B]maxobase\f[R]
.IP \[bu] 2
\f[B]maxscale\f[R]
.IP \[bu] 2
\f[B]modexp\f[R]
.IP \[bu] 2
\f[B]print\f[R]
.IP \[bu] 2
\f[B]read\f[R]
.IP \[bu] 2
\f[B]stream\f[R]
.PP
If any of those keywords are used as a function, variable, or array name
in a script, use this option with the keyword as the argument.
If multiple are used, use this option for all of them; it can be used
multiple times.
.PP
Keywords are \f[I]not\f[R] redefined when parsing the builtin math
library (see the \f[B]LIBRARY\f[R] section).
.PP
It is a fatal error to redefine keywords mandated by the POSIX standard.
It is a fatal error to attempt to redefine words that this bc(1) does
not reserve as keywords.
.RE
.TP
\f[B]-q\f[R], \f[B]--quiet\f[R]
This option is for compatibility with the GNU
bc(1) (https://www.gnu.org/software/bc/); it is a no-op.
Without this option, GNU bc(1) prints a copyright header.
This bc(1) only prints the copyright header if one or more of the
\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-s\f[R], \f[B]--standard\f[R]
Process exactly the language defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
and error if any extensions are used.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-w\f[R], \f[B]--warn\f[R]
Like \f[B]-s\f[R] and \f[B]--standard\f[R], except that warnings (and
not errors) are printed for non-standard extensions and execution
continues normally.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]BC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files or expressions are given by the \f[B]-f\f[R],
\f[B]--file\f[R], \f[B]-e\f[R], or \f[B]--expression\f[R] options, then
bc(1) read from \f[B]stdin\f[R].
.PP
However, there are a few caveats to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if the parse cannot complete.
That means that starting a string without ending it or starting a
function, \f[B]if\f[R] statement, or loop without ending it will also
cause bc(1) to not execute.
.PP
Second, after an \f[B]if\f[R] statement, bc(1) doesn\[cq]t know if an
\f[B]else\f[R] statement will follow, so it will not execute until it
knows there will not be an \f[B]else\f[R] statement.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]bc >&-\f[R], it will quit with an error.
This is done so that bc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]bc 2>&-\f[R], it will quit with an error.
This is done so that bc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
which is a much more thorough resource for the language this bc(1)
accepts.
This section is meant to be a summary and a listing of all the
extensions to the standard.
.PP
In the sections below, \f[B]E\f[R] means expression, \f[B]S\f[R] means
statement, and \f[B]I\f[R] means identifier.
.PP
Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be
followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase
letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores
(\f[B]_\f[R]).
The regex is \f[B][a-z][a-z0-9_]*\f[R].
Identifiers with more than one character (letter) are a
\f[B]non-portable extension\f[R].
.PP
\f[B]ibase\f[R] is a global variable determining how to interpret
constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R]
(\f[B]--warn\f[R]) flags were not given on the command line, the max
allowable value for \f[B]ibase\f[R] is \f[B]36\f[R].
Otherwise, it is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in bc(1)
programs with the \f[B]maxibase()\f[R] built-in function.
.PP
\f[B]obase\f[R] is a global variable determining how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and
can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in
function.
The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R].
Values are output in the specified base.
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a global variable that sets the precision of any operations, with
exceptions.
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R]
and can be queried in bc(1) programs with the \f[B]maxscale()\f[R]
built-in function.
.PP
bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables.
All \f[I]local\f[R] variables are local to the function; they are
parameters or are introduced in the \f[B]auto\f[R] list of a function
(see the \f[B]FUNCTIONS\f[R] section).
If a variable is accessed which is not a parameter or in the
\f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R].
If a parent function has a \f[I]local\f[R] variable version of a
variable that a child function considers \f[I]global\f[R], the value of
that \f[I]global\f[R] variable in the child function is the value of the
variable in the parent function, not the value of the actual
\f[I]global\f[R] variable.
.PP
All of the above applies to arrays as well.
.PP
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence
operator is an assignment operator \f[I]and\f[R] the expression is
notsurrounded by parentheses.
.PP
The value that is printed is also assigned to the special variable
\f[B]last\f[R].
A single dot (\f[B].\f[R]) may also be used as a synonym for
\f[B]last\f[R].
These are \f[B]non-portable extensions\f[R].
.PP
Either semicolons or newlines may separate statements.
.SS Comments
.PP
There are two kinds of comments:
.IP "1." 3
Block comments are enclosed in \f[B]/*\f[R] and \f[B]*/\f[R].
.IP "2." 3
Line comments go from \f[B]#\f[R] until, and not including, the next
newline.
This is a \f[B]non-portable extension\f[R].
.SS Named Expressions
.PP
The following are named expressions in bc(1):
.IP "1." 3
Variables: \f[B]I\f[R]
.IP "2." 3
Array Elements: \f[B]I[E]\f[R]
.IP "3." 3
\f[B]ibase\f[R]
.IP "4." 3
\f[B]obase\f[R]
.IP "5." 3
\f[B]scale\f[R]
.IP "6." 3
\f[B]last\f[R] or a single dot (\f[B].\f[R])
.PP
Number 6 is a \f[B]non-portable extension\f[R].
.PP
Variables and arrays do not interfere; users can have arrays named the
same as variables.
This also applies to functions (see the \f[B]FUNCTIONS\f[R] section), so
a user can have a variable, array, and function that all have the same
name, and they will not shadow each other, whether inside of functions
or not.
.PP
Named expressions are required as the operand of
\f[B]increment\f[R]/\f[B]decrement\f[R] operators and as the left side
of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R]
subsection).
.SS Operands
.PP
The following are valid operands in bc(1):
.IP " 1." 4
Numbers (see the \f[I]Numbers\f[R] subsection below).
.IP " 2." 4
Array indices (\f[B]I[E]\f[R]).
.IP " 3." 4
\f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence).
.IP " 4." 4
\f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R].
\f[B]E\f[R] must be non-negative.
.IP " 5." 4
\f[B]length(E)\f[R]: The number of significant decimal digits in
\f[B]E\f[R].
Returns \f[B]1\f[R] for \f[B]0\f[R] with no decimal places.
If given a string, the length of the string is returned.
Passing a string to \f[B]length(E)\f[R] is a \f[B]non-portable
extension\f[R].
.IP " 6." 4
\f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 7." 4
\f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R].
.IP " 8." 4
\f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 9." 4
\f[B]modexp(E, E, E)\f[R]: Modular exponentiation, where the first
expression is the base, the second is the exponent, and the third is the
modulus.
All three values must be integers.
The second argument must be non-negative.
The third argument must be non-zero.
This is a \f[B]non-portable extension\f[R].
.IP "10." 4
\f[B]divmod(E, E, I[])\f[R]: Division and modulus in one operation.
This is for optimization.
The first expression is the dividend, and the second is the divisor,
which must be non-zero.
The return value is the quotient, and the modulus is stored in index
\f[B]0\f[R] of the provided array (the last argument).
This is a \f[B]non-portable extension\f[R].
.IP "11." 4
\f[B]asciify(E)\f[R]: If \f[B]E\f[R] is a string, returns a string that
is the first letter of its argument.
If it is a number, calculates the number mod \f[B]256\f[R] and returns
that number as a one-character string.
This is a \f[B]non-portable extension\f[R].
.IP "12." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.IP "13." 4
\f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an
expression.
The result of that expression is the result of the \f[B]read()\f[R]
operand.
This is a \f[B]non-portable extension\f[R].
.IP "14." 4
\f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "15." 4
\f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "16." 4
\f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R].
This is a \f[B]non-portable extension\f[R].
+.IP "17." 4
+\f[B]line_length()\f[R]: The line length set with
+\f[B]BC_LINE_LENGTH\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
+section).
+This is a \f[B]non-portable extension\f[R].
+.IP "18." 4
+\f[B]global_stacks()\f[R]: \f[B]0\f[R] if global stacks are not enabled
+with the \f[B]-g\f[R] or \f[B]--global-stacks\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "19." 4
+\f[B]leading_zero()\f[R]: \f[B]0\f[R] if leading zeroes are not enabled
+with the \f[B]-z\f[R] or \f[B]\[en]leading-zeroes\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
.SS Numbers
.PP
Numbers are strings made up of digits, uppercase letters, and at most
\f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R].
.SS Operators
.PP
The following arithmetic and logical operators can be used.
They are listed in order of decreasing precedence.
Operators in the same group have the same precedence.
.TP
\f[B]++\f[R] \f[B]--\f[R]
Type: Prefix and Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]increment\f[R], \f[B]decrement\f[R]
.RE
.TP
\f[B]-\f[R] \f[B]!\f[R]
Type: Prefix
.RS
.PP
Associativity: None
.PP
Description: \f[B]negation\f[R], \f[B]boolean not\f[R]
.RE
.TP
\f[B]\[ha]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]power\f[R]
.RE
.TP
\f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R]
.RE
.TP
\f[B]+\f[R] \f[B]-\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]add\f[R], \f[B]subtract\f[R]
.RE
.TP
\f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]assignment\f[R]
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]relational\f[R]
.RE
.TP
\f[B]&&\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean and\f[R]
.RE
.TP
\f[B]||\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean or\f[R]
.RE
.PP
The operators will be described in more detail below.
.TP
\f[B]++\f[R] \f[B]--\f[R]
The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R]
operators behave exactly like they would in C.
They require a named expression (see the \f[I]Named Expressions\f[R]
subsection) as an operand.
.RS
.PP
The prefix versions of these operators are more efficient; use them
where possible.
.RE
.TP
\f[B]-\f[R]
The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts
to negate any expression with the value \f[B]0\f[R].
Otherwise, a copy of the expression with its sign flipped is returned.
.TP
\f[B]!\f[R]
The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression
is \f[B]0\f[R], or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator,
as it would be in C) takes two expressions and raises the first to the
power of the value of the second.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]), and if it
is negative, the first value must be non-zero.
.RE
.TP
\f[B]*\f[R]
The \f[B]multiply\f[R] operator takes two expressions, multiplies them,
and returns the product.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The \f[B]divide\f[R] operator takes two expressions, divides them, and
returns the quotient.
The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]%\f[R]
The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R] and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]+\f[R]
The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the
max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]-\f[R]
The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to
the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R]
The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and
\f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named
Expressions\f[R] subsection).
.RS
.PP
For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to
\f[B]a\f[R].
For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to
the corresponding arithmetic operator and the result is assigned to
\f[B]a\f[R].
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and if the relation holds, according to C language
semantics, the result is \f[B]1\f[R].
Otherwise, it is \f[B]0\f[R].
.RS
.PP
Note that unlike in C, these operators have a lower precedence than the
\f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is
interpreted as \f[B](a=b)>c\f[R].
.PP
Also, unlike the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
requires, these operators can appear anywhere any other expressions can
be used.
This allowance is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]&&\f[R]
The \f[B]boolean and\f[R] operator takes two expressions and returns
\f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]||\f[R]
The \f[B]boolean or\f[R] operator takes two expressions and returns
\f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R]
otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Statements
.PP
The following items are statements:
.IP " 1." 4
\f[B]E\f[R]
.IP " 2." 4
\f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R]
\f[B]}\f[R]
.IP " 3." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 4." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
\f[B]else\f[R] \f[B]S\f[R]
.IP " 5." 4
\f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 6." 4
\f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R]
\f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 7." 4
An empty statement
.IP " 8." 4
\f[B]break\f[R]
.IP " 9." 4
\f[B]continue\f[R]
.IP "10." 4
\f[B]quit\f[R]
.IP "11." 4
\f[B]halt\f[R]
.IP "12." 4
\f[B]limits\f[R]
.IP "13." 4
A string of characters, enclosed in double quotes
.IP "14." 4
\f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "15." 4
\f[B]stream\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "16." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.PP
Numbers 4, 9, 11, 12, 14, 15, and 16 are \f[B]non-portable
extensions\f[R].
.PP
Also, as a \f[B]non-portable extension\f[R], any or all of the
expressions in the header of a for loop may be omitted.
If the condition (second expression) is omitted, it is assumed to be a
constant \f[B]1\f[R].
.PP
The \f[B]break\f[R] statement causes a loop to stop iterating and resume
execution immediately following a loop.
This is only allowed in loops.
.PP
The \f[B]continue\f[R] statement causes a loop iteration to stop early
and returns to the start of the loop, including testing the loop
condition.
This is only allowed in loops.
.PP
The \f[B]if\f[R] \f[B]else\f[R] statement does the same thing as in C.
.PP
The \f[B]quit\f[R] statement causes bc(1) to quit, even if it is on a
branch that will not be executed (it is a compile-time command).
.PP
The \f[B]halt\f[R] statement causes bc(1) to quit, if it is executed.
(Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement
that is not executed, bc(1) does not quit.)
.PP
The \f[B]limits\f[R] statement prints the limits that this bc(1) is
subject to.
This is like the \f[B]quit\f[R] statement in that it is a compile-time
command.
.PP
An expression by itself is evaluated and printed, followed by a newline.
.SS Strings
.PP
If strings appear as a statement by themselves, they are printed without
a trailing newline.
.PP
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements.
They can also be passed to functions in variable parameters.
.PP
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
.PP
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section).
.PP
Assigning strings to variables and array elements and passing them to
functions are \f[B]non-portable extensions\f[R].
.SS Print Statement
.PP
The \[lq]expressions\[rq] in a \f[B]print\f[R] statement may also be
strings.
If they are, there are backslash escape sequences that are interpreted
specially.
What those sequences are, and what they cause to be printed, are shown
below:
.PP
\f[B]\[rs]a\f[R]: \f[B]\[rs]a\f[R]
.PP
\f[B]\[rs]b\f[R]: \f[B]\[rs]b\f[R]
.PP
\f[B]\[rs]\[rs]\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]e\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]f\f[R]: \f[B]\[rs]f\f[R]
.PP
\f[B]\[rs]n\f[R]: \f[B]\[rs]n\f[R]
.PP
\f[B]\[rs]q\f[R]: \f[B]\[lq]\f[R]
.PP
\f[B]\[rs]r\f[R]: \f[B]\[rs]r\f[R]
.PP
\f[B]\[rs]t\f[R]: \f[B]\[rs]t\f[R]
.PP
Any other character following a backslash causes the backslash and
character to be printed as-is.
.PP
Any non-string expression in a print statement shall be assigned to
\f[B]last\f[R], like any other expression that is printed.
.SS Stream Statement
.PP
The \[lq]expressions in a \f[B]stream\f[R] statement may also be
strings.
.PP
If a \f[B]stream\f[R] statement is given a string, it prints the string
as though the string had appeared as its own statement.
In other words, the \f[B]stream\f[R] statement prints strings normally,
without a newline.
.PP
If a \f[B]stream\f[R] statement is given a number, a copy of it is
truncated and its absolute value is calculated.
The result is then printed as though \f[B]obase\f[R] is \f[B]256\f[R]
and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
.SS Order of Evaluation
.PP
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations.
This means, for example, assuming that \f[B]i\f[R] is equal to
\f[B]0\f[R], in the expression
.IP
.nf
\f[C]
a[i++] = i++
\f[R]
.fi
.PP
the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and
\f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression.
.PP
This includes function arguments.
Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in
the expression
.IP
.nf
\f[C]
x(i++, i++)
\f[R]
.fi
.PP
the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the
second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to
\f[B]2\f[R] before the function starts executing.
.SH FUNCTIONS
.PP
Function definitions are as follows:
.IP
.nf
\f[C]
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
\f[R]
.fi
.PP
Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be
replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an
array, and any \f[B]I\f[R] in the parameter list may be replaced with
\f[B]*I[]\f[R] to make a parameter an array reference.
Callers of functions that take array references should not put an
asterisk in the call; they must be called with just \f[B]I[]\f[R] like
normal array parameters and will be automatically converted into
references.
.PP
As a \f[B]non-portable extension\f[R], the opening brace of a
\f[B]define\f[R] statement may appear on the next line.
.PP
As a \f[B]non-portable extension\f[R], the return statement may also be
in one of the following forms:
.IP "1." 3
\f[B]return\f[R]
.IP "2." 3
\f[B]return\f[R] \f[B](\f[R] \f[B])\f[R]
.IP "3." 3
\f[B]return\f[R] \f[B]E\f[R]
.PP
The first two, or not specifying a \f[B]return\f[R] statement, is
equivalent to \f[B]return (0)\f[R], unless the function is a
\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection
below).
.SS Void Functions
.PP
Functions can also be \f[B]void\f[R] functions, defined as follows:
.IP
.nf
\f[C]
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
\f[R]
.fi
.PP
They can only be used as standalone expressions, where such an
expression would be printed alone, except in a print statement.
.PP
Void functions can only use the first two \f[B]return\f[R] statements
listed above.
They can also omit the return statement entirely.
.PP
The word \[lq]void\[rq] is not treated as a keyword; it is still
possible to have variables, arrays, and functions named \f[B]void\f[R].
The word \[lq]void\[rq] is only treated specially right after the
\f[B]define\f[R] keyword.
.PP
This is a \f[B]non-portable extension\f[R].
.SS Array References
.PP
For any array in the parameter list, if the array is declared in the
form
.IP
.nf
\f[C]
*I[]
\f[R]
.fi
.PP
it is a \f[B]reference\f[R].
Any changes to the array in the function are reflected, when the
function returns, to the array that was passed in.
.PP
Other than this, all function arguments are passed by value.
.PP
This is a \f[B]non-portable extension\f[R].
.SH LIBRARY
.PP
All of the functions below are available when the \f[B]-l\f[R] or
\f[B]--mathlib\f[R] command-line flags are given.
.SS Standard Library
.PP
The
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
defines the following functions for the math library:
.TP
\f[B]s(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]c(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l(x)\f[R]
Returns the natural logarithm of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]e(x)\f[R]
Returns the mathematical constant \f[B]e\f[R] raised to the power of
\f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]j(x, n)\f[R]
Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.SS Transcendental Functions
.PP
All transcendental functions can return slightly inaccurate results (up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)).
This is unavoidable, and this
article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains
why it is impossible and unnecessary to calculate exact results for the
transcendental functions.
.PP
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (\f[B]scale\f[R]) set to at least 1 higher
than is necessary.
If exact results are \f[I]absolutely\f[R] required, users can double the
precision (\f[B]scale\f[R]) and then truncate.
.PP
The transcendental functions in the standard math library are:
.IP \[bu] 2
\f[B]s(x)\f[R]
.IP \[bu] 2
\f[B]c(x)\f[R]
.IP \[bu] 2
\f[B]a(x)\f[R]
.IP \[bu] 2
\f[B]l(x)\f[R]
.IP \[bu] 2
\f[B]e(x)\f[R]
.IP \[bu] 2
\f[B]j(x, n)\f[R]
.SH RESET
.PP
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets.
This means that several things happen.
.PP
First, any functions 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.
.PP
Thus, when bc(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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.PP
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This bc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R]
can be queried with the \f[B]limits\f[R] statement.
.PP
In addition, this bc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bc(1):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bc(1) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
The actual values can be queried with the \f[B]limits\f[R] statement.
.PP
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
.PP
bc(1) recognizes the following environment variables:
.TP
\f[B]POSIXLY_CORRECT\f[R]
If this variable exists (no matter the contents), bc(1) behaves as if
the \f[B]-s\f[R] option was given.
.TP
\f[B]BC_ENV_ARGS\f[R]
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line arguments.
These are always processed first, so any files given in
\f[B]BC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 bc(1) runs.
.RS
.PP
The code that parses \f[B]BC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`bc' file.bc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]BC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]BC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length,
including the backslash (\f[B]\[rs]\f[R]).
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]BC_BANNER\f[R]
If this environment variable exists and contains an integer, then a
non-zero value activates the copyright banner when bc(1) is in
interactive mode, while zero deactivates it.
.RS
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
does not print the banner when not in interactive mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_SIGINT_RESET\f[R]
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes bc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then bc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use
TTY mode, and zero makes bc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a
prompt, and zero or a non-integer makes bc(1) not use a prompt.
If this environment variable does not exist and \f[B]BC_TTY_MODE\f[R]
does, then the value of the \f[B]BC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]BC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
bc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], taking the square root of a
negative number, attempting to convert a negative number to a hardware
integer, overflow when converting a number to a hardware integer,
overflow when calculating the size of a number, and attempting to use a
non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]) operator and the corresponding assignment
operator.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an invalid
print statement, giving an invalid function definition, attempting to
assign to an expression that is not a named expression (see the
\f[I]Named Expressions\f[R] subsection of the \f[B]SYNTAX\f[R] section),
giving an invalid \f[B]auto\f[R] list, having a duplicate
\f[B]auto\f[R]/function parameter, failing to find the end of a code
block, attempting to return a value from a \f[B]void\f[R] function,
attempting to use a variable as a reference, and using any extensions
when the option \f[B]-s\f[R] or any equivalents were given.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors, passing the wrong number of
arguments to functions, attempting to call an undefined function, and
attempting to use a \f[B]void\f[R] function call as a value in an
expression.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
Fatal errors include memory allocation errors, I/O errors, failing to
open files, attempting to use files that do not have only ASCII
characters (bc(1) only accepts ASCII characters), attempting to open a
directory as a file, and giving invalid command-line options.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, bc(1)
always exits and returns \f[B]4\f[R], no matter what mode bc(1) is in.
.PP
The other statuses will only be returned when bc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
bc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Per the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, bc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
bc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]BC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, bc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]BC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, bc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]BC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then bc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]BC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]BC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]BC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]BC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]BC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause bc(1) to do one of two things.
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, bc(1) will exit.
.PP
However, if bc(1) is in interactive mode, and the
\f[B]BC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then bc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If bc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If bc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] is sent to bc(1) as it is
executing a file, it can seem as though bc(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
bc(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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause bc(1) to clean up and
exit, and it uses the default handler for all other signals.
.SH SEE ALSO
.PP
dc(1)
.SH STANDARDS
.PP
bc(1) is compliant with the IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
The flags \f[B]-efghiqsvVw\f[R], all long options, and the extensions
noted above are extensions to that specification.
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bc/EHN.1.md b/manuals/bc/EHN.1.md
index 618a09286de1..25543500eea7 100644
--- a/manuals/bc/EHN.1.md
+++ b/manuals/bc/EHN.1.md
@@ -1,1301 +1,1331 @@
# NAME
bc - arbitrary-precision decimal arithmetic language and calculator
# SYNOPSIS
**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# DESCRIPTION
bc(1) is an interactive processor for a language first standardized in 1991 by
POSIX. (The current standard is [here][1].) The language provides unlimited
precision decimal arithmetic and is somewhat C-like, but there are differences.
Such differences will be noted in this document.
After parsing and handling options, this bc(1) reads any files given on the
command line and executes them before reading from **stdin**.
This bc(1) is a drop-in replacement for *any* bc(1), including (and especially)
the GNU bc(1).
**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
parse error, it is probably because a word this bc(1) reserves as a keyword is
used as the name of a function, variable, or array. To fix that, use the
command-line option **-r** *keyword*, where *keyword* is the keyword that is
used as a name in the script. For more information, see the **OPTIONS** section.
If parsing scripts meant for other bc(1) implementations still does not work,
that is a bug and should be reported. See the **BUGS** section.
# OPTIONS
The following are the options that bc(1) accepts.
**-g**, **-\-global-stacks**
: Turns the globals **ibase**, **obase**, and **scale** into stacks.
This has the effect that a copy of the current value of all three are pushed
onto a stack for every function call, as well as popped when every function
returns. This means that functions can assign to any and all of those
globals without worrying that the change will affect other functions.
Thus, a hypothetical function named **output(x,b)** that simply printed
**x** in base **b** could be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
However, since using this flag means that functions cannot set **ibase**,
**obase**, or **scale** globally, functions that are made to do so cannot
work anymore. There are two possible use cases for that, and each has a
solution.
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set **ibase**, **obase**, or
**scale** globally for any other purpose, it could be split into one to
three functions (based on how many globals it sets) and each of those
functions could return the desired value for a global.
If the behavior of this option is desired for every run of bc(1), then users
could make sure to define **BC_ENV_ARGS** and include this option (see the
**ENVIRONMENT VARIABLES** section for more details).
If **-s**, **-w**, or any equivalents are used, this option is ignored.
This is a **non-portable extension**.
**-h**, **-\-help**
: Prints a usage message and quits.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-l**, **-\-mathlib**
: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
math library before running any code, including any expressions or files
specified on the command line.
To learn what is in the library, see the **LIBRARY** section.
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in bc(1). Most of those users
would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section).
These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of bc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **read()** built-in function is called.
These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-r** *keyword*, **-\-redefine**=*keyword*
: Redefines *keyword* in order to allow it to be used as a function, variable,
or array name. This is useful when this bc(1) gives parse errors when
parsing scripts meant for other bc(1) implementations.
The keywords this bc(1) allows to be redefined are:
* **abs**
* **asciify**
* **continue**
* **divmod**
* **else**
* **halt**
* **last**
* **limits**
* **maxibase**
* **maxobase**
* **maxscale**
* **modexp**
* **print**
* **read**
* **stream**
If any of those keywords are used as a function, variable, or array name in
a script, use this option with the keyword as the argument. If multiple are
used, use this option for all of them; it can be used multiple times.
Keywords are *not* redefined when parsing the builtin math library (see the
**LIBRARY** section).
It is a fatal error to redefine keywords mandated by the POSIX standard. It
is a fatal error to attempt to redefine words that this bc(1) does not
reserve as keywords.
**-q**, **-\-quiet**
: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
Without this option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the **-v**, **-V**, or
**-\-version** options are given.
This is a **non-portable extension**.
**-s**, **-\-standard**
: Process exactly the language defined by the [standard][1] and error if any
extensions are used.
This is a **non-portable extension**.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
This is a **non-portable extension**.
**-w**, **-\-warn**
: Like **-s** and **-\-standard**, except that warnings (and not errors) are
printed for non-standard extensions and execution continues normally.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
**-\-expression** options, then bc(1) read from **stdin**.
However, there are a few caveats to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
the parse cannot complete. That means that starting a string without ending it
or starting a function, **if** statement, or loop without ending it will also
cause bc(1) to not execute.
Second, after an **if** statement, bc(1) doesn't know if an **else** statement
will follow, so it will not execute until it knows there will not be an **else**
statement.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **bc >&-**, it will quit with an error. This
is done so that bc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This
is done so that bc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences. This
bc(1) follows the [POSIX standard][1], which is a much more thorough resource
for the language this bc(1) accepts. This section is meant to be a summary and a
listing of all the extensions to the standard.
In the sections below, **E** means expression, **S** means statement, and **I**
means identifier.
Identifiers (**I**) start with a lowercase letter and can be followed by any
number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
Identifiers with more than one character (letter) are a
**non-portable extension**.
**ibase** is a global variable determining how to interpret constant numbers. It
is the "input" base, or the number base used for interpreting input numbers.
**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
(**-\-warn**) flags were not given on the command line, the max allowable value
for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
**ibase** is **2**. The max allowable value for **ibase** can be queried in
bc(1) programs with the **maxibase()** built-in function.
**obase** is a global variable determining how to output results. It is the
"output" base, or the number base used for outputting numbers. **obase** is
initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
can be queried in bc(1) programs with the **maxobase()** built-in function. The
min allowable value for **obase** is **2**. Values are output in the specified
base.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a global variable that
sets the precision of any operations, with exceptions. **scale** is initially
**0**. **scale** cannot be negative. The max allowable value for **scale** is
**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
built-in function.
bc(1) has both *global* variables and *local* variables. All *local*
variables are local to the function; they are parameters or are introduced in
the **auto** list of a function (see the **FUNCTIONS** section). If a variable
is accessed which is not a parameter or in the **auto** list, it is assumed to
be *global*. If a parent function has a *local* variable version of a variable
that a child function considers *global*, the value of that *global* variable in
the child function is the value of the variable in the parent function, not the
value of the actual *global* variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence operator is an
assignment operator *and* the expression is notsurrounded by parentheses.
The value that is printed is also assigned to the special variable **last**. A
single dot (**.**) may also be used as a synonym for **last**. These are
**non-portable extensions**.
Either semicolons or newlines may separate statements.
## Comments
There are two kinds of comments:
1. Block comments are enclosed in **/\*** and **\*/**.
2. Line comments go from **#** until, and not including, the next newline. This
is a **non-portable extension**.
## Named Expressions
The following are named expressions in bc(1):
1. Variables: **I**
2. Array Elements: **I[E]**
3. **ibase**
4. **obase**
5. **scale**
6. **last** or a single dot (**.**)
Number 6 is a **non-portable extension**.
Variables and arrays do not interfere; users can have arrays named the same as
variables. This also applies to functions (see the **FUNCTIONS** section), so a
user can have a variable, array, and function that all have the same name, and
they will not shadow each other, whether inside of functions or not.
Named expressions are required as the operand of **increment**/**decrement**
operators and as the left side of **assignment** operators (see the *Operators*
subsection).
## Operands
The following are valid operands in bc(1):
1. Numbers (see the *Numbers* subsection below).
2. Array indices (**I[E]**).
3. **(E)**: The value of **E** (used to change precedence).
4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
5. **length(E)**: The number of significant decimal digits in **E**. Returns
**1** for **0** with no decimal places. If given a string, the length of the
string is returned. Passing a string to **length(E)** is a **non-portable
extension**.
6. **length(I[])**: The number of elements in the array **I**. This is a
**non-portable extension**.
7. **scale(E)**: The *scale* of **E**.
8. **abs(E)**: The absolute value of **E**. This is a **non-portable
extension**.
9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
the base, the second is the exponent, and the third is the modulus. All
three values must be integers. The second argument must be non-negative. The
third argument must be non-zero. This is a **non-portable extension**.
10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
optimization. The first expression is the dividend, and the second is the
divisor, which must be non-zero. The return value is the quotient, and the
modulus is stored in index **0** of the provided array (the last argument).
This is a **non-portable extension**.
11. **asciify(E)**: If **E** is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number mod **256**
and returns that number as a one-character string. This is a **non-portable
extension**.
12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a non-**void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
13. **read()**: Reads a line from **stdin** and uses that as an expression. The
result of that expression is the result of the **read()** operand. This is a
**non-portable extension**.
14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
extension**.
15. **maxobase()**: The max allowable **obase**. This is a **non-portable
extension**.
16. **maxscale()**: The max allowable **scale**. This is a **non-portable
extension**.
+17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
+ **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
+18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
+ or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
+ or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
## Numbers
Numbers are strings made up of digits, uppercase letters, and at most **1**
period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
letters are equal to **9** + their position in the alphabet (i.e., **A** equals
**10**, or **9+1**). If a digit or letter makes no sense with the current value
of **ibase**, they are set to the value of the highest valid digit in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **Z** alone always equals decimal
**35**.
## Operators
The following arithmetic and logical operators can be used. They are listed in
order of decreasing precedence. Operators in the same group have the same
precedence.
**++** **-\-**
: Type: Prefix and Postfix
Associativity: None
Description: **increment**, **decrement**
**-** **!**
: Type: Prefix
Associativity: None
Description: **negation**, **boolean not**
**\^**
: Type: Binary
Associativity: Right
Description: **power**
**\*** **/** **%**
: Type: Binary
Associativity: Left
Description: **multiply**, **divide**, **modulus**
**+** **-**
: Type: Binary
Associativity: Left
Description: **add**, **subtract**
**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
: Type: Binary
Associativity: Right
Description: **assignment**
**==** **\<=** **\>=** **!=** **\<** **\>**
: Type: Binary
Associativity: Left
Description: **relational**
**&&**
: Type: Binary
Associativity: Left
Description: **boolean and**
**||**
: Type: Binary
Associativity: Left
Description: **boolean or**
The operators will be described in more detail below.
**++** **-\-**
: The prefix and postfix **increment** and **decrement** operators behave
exactly like they would in C. They require a named expression (see the
*Named Expressions* subsection) as an operand.
The prefix versions of these operators are more efficient; use them where
possible.
**-**
: The **negation** operator returns **0** if a user attempts to negate any
expression with the value **0**. Otherwise, a copy of the expression with
its sign flipped is returned.
**!**
: The **boolean not** operator returns **1** if the expression is **0**, or
**0** otherwise.
This is a **non-portable extension**.
**\^**
: The **power** operator (not the **exclusive or** operator, as it would be in
C) takes two expressions and raises the first to the power of the value of
the second. The *scale* of the result is equal to **scale**.
The second expression must be an integer (no *scale*), and if it is
negative, the first value must be non-zero.
**\***
: The **multiply** operator takes two expressions, multiplies them, and
returns the product. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result is
equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The **divide** operator takes two expressions, divides them, and returns the
quotient. The *scale* of the result shall be the value of **scale**.
The second expression must be non-zero.
**%**
: The **modulus** operator takes two expressions, **a** and **b**, and
evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The second expression must be non-zero.
**+**
: The **add** operator takes two expressions, **a** and **b**, and returns the
sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
**-**
: The **subtract** operator takes two expressions, **a** and **b**, and
returns the difference, with a *scale* equal to the max of the *scale*s of
**a** and **b**.
**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
: The **assignment** operators take two expressions, **a** and **b** where
**a** is a named expression (see the *Named Expressions* subsection).
For **=**, **b** is copied and the result is assigned to **a**. For all
others, **a** and **b** are applied as operands to the corresponding
arithmetic operator and the result is assigned to **a**.
**==** **\<=** **\>=** **!=** **\<** **\>**
: The **relational** operators compare two expressions, **a** and **b**, and
if the relation holds, according to C language semantics, the result is
**1**. Otherwise, it is **0**.
Note that unlike in C, these operators have a lower precedence than the
**assignment** operators, which means that **a=b\>c** is interpreted as
**(a=b)\>c**.
Also, unlike the [standard][1] requires, these operators can appear anywhere
any other expressions can be used. This allowance is a
**non-portable extension**.
**&&**
: The **boolean and** operator takes two expressions and returns **1** if both
expressions are non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
**||**
: The **boolean or** operator takes two expressions and returns **1** if one
of the expressions is non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
## Statements
The following items are statements:
1. **E**
2. **{** **S** **;** ... **;** **S** **}**
3. **if** **(** **E** **)** **S**
4. **if** **(** **E** **)** **S** **else** **S**
5. **while** **(** **E** **)** **S**
6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
7. An empty statement
8. **break**
9. **continue**
10. **quit**
11. **halt**
12. **limits**
13. A string of characters, enclosed in double quotes
14. **print** **E** **,** ... **,** **E**
15. **stream** **E** **,** ... **,** **E**
16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
Also, as a **non-portable extension**, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expression) is
omitted, it is assumed to be a constant **1**.
The **break** statement causes a loop to stop iterating and resume execution
immediately following a loop. This is only allowed in loops.
The **continue** statement causes a loop iteration to stop early and returns to
the start of the loop, including testing the loop condition. This is only
allowed in loops.
The **if** **else** statement does the same thing as in C.
The **quit** statement causes bc(1) to quit, even if it is on a branch that will
not be executed (it is a compile-time command).
The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
if it is on a branch of an **if** statement that is not executed, bc(1) does not
quit.)
The **limits** statement prints the limits that this bc(1) is subject to. This
is like the **quit** statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a newline.
## Strings
If strings appear as a statement by themselves, they are printed without a
trailing newline.
In addition to appearing as a lone statement by themselves, strings can be
assigned to variables and array elements. They can also be passed to functions
in variable parameters.
If any statement that expects a string is given a variable that had a string
assigned to it, the statement acts as though it had received a string.
If any math operation is attempted on a string or a variable or array element
that has been assigned a string, an error is raised, and bc(1) resets (see the
**RESET** section).
Assigning strings to variables and array elements and passing them to functions
are **non-portable extensions**.
## Print Statement
The "expressions" in a **print** statement may also be strings. If they are, there
are backslash escape sequences that are interpreted specially. What those
sequences are, and what they cause to be printed, are shown below:
**\\a**: **\\a**
**\\b**: **\\b**
**\\\\**: **\\**
**\\e**: **\\**
**\\f**: **\\f**
**\\n**: **\\n**
**\\q**: **"**
**\\r**: **\\r**
**\\t**: **\\t**
Any other character following a backslash causes the backslash and character to
be printed as-is.
Any non-string expression in a print statement shall be assigned to **last**,
like any other expression that is printed.
## Stream Statement
The "expressions in a **stream** statement may also be strings.
If a **stream** statement is given a string, it prints the string as though the
string had appeared as its own statement. In other words, the **stream**
statement prints strings normally, without a newline.
If a **stream** statement is given a number, a copy of it is truncated and its
absolute value is calculated. The result is then printed as though **obase** is
**256** and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
## Order of Evaluation
All expressions in a statment are evaluated left to right, except as necessary
to maintain order of operations. This means, for example, assuming that **i** is
equal to **0**, in the expression
a[i++] = i++
the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
at the end of the expression.
This includes function arguments. Thus, assuming **i** is equal to **0**, this
means that in the expression
x(i++, i++)
the first argument passed to **x()** is **0**, and the second argument is **1**,
while **i** is equal to **2** before the function starts executing.
# FUNCTIONS
Function definitions are as follows:
```
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
```
Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
make a parameter or **auto** var an array, and any **I** in the parameter list
may be replaced with **\*I[]** to make a parameter an array reference. Callers
of functions that take array references should not put an asterisk in the call;
they must be called with just **I[]** like normal array parameters and will be
automatically converted into references.
As a **non-portable extension**, the opening brace of a **define** statement may
appear on the next line.
As a **non-portable extension**, the return statement may also be in one of the
following forms:
1. **return**
2. **return** **(** **)**
3. **return** **E**
The first two, or not specifying a **return** statement, is equivalent to
**return (0)**, unless the function is a **void** function (see the *Void
Functions* subsection below).
## Void Functions
Functions can also be **void** functions, defined as follows:
```
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
```
They can only be used as standalone expressions, where such an expression would
be printed alone, except in a print statement.
Void functions can only use the first two **return** statements listed above.
They can also omit the return statement entirely.
The word "void" is not treated as a keyword; it is still possible to have
variables, arrays, and functions named **void**. The word "void" is only
treated specially right after the **define** keyword.
This is a **non-portable extension**.
## Array References
For any array in the parameter list, if the array is declared in the form
```
*I[]
```
it is a **reference**. Any changes to the array in the function are reflected,
when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a **non-portable extension**.
# LIBRARY
All of the functions below are available when the **-l** or **-\-mathlib**
command-line flags are given.
## Standard Library
The [standard][1] defines the following functions for the math library:
**s(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**c(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a(x)**
: Returns the arctangent of **x**, in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l(x)**
: Returns the natural logarithm of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**e(x)**
: Returns the mathematical constant **e** raised to the power of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**j(x, n)**
: Returns the bessel integer order **n** (truncated) of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
## Transcendental Functions
All transcendental functions can return slightly inaccurate results (up to 1
[ULP][4]). This is unavoidable, and [this article][5] explains why it is
impossible and unnecessary to calculate exact results for the transcendental
functions.
Because of the possible inaccuracy, I recommend that users call those functions
with the precision (**scale**) set to at least 1 higher than is necessary. If
exact results are *absolutely* required, users can double the precision
(**scale**) and then truncate.
The transcendental functions in the standard math library are:
* **s(x)**
* **c(x)**
* **a(x)**
* **l(x)**
* **e(x)**
* **j(x, n)**
# RESET
When bc(1) encounters an error or a signal that it has a non-default handler
for, it resets. This means that several things happen.
First, any functions 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.
Thus, when bc(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.
Note that this reset behavior is different from the GNU bc(1), which attempts to
start executing the statement right after the one that caused an error.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This bc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
the **limits** statement.
In addition, this bc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bc(1):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bc(1) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_STRING_MAX**
: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
**BC_NAME_MAX**
: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
The actual values can be queried with the **limits** statement.
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.
# ENVIRONMENT VARIABLES
bc(1) recognizes the following environment variables:
**POSIXLY_CORRECT**
: If this variable exists (no matter the contents), bc(1) behaves as if
the **-s** option was given.
**BC_ENV_ARGS**
: This is another way to give command-line arguments to bc(1). They should be
in the same format as all other command-line arguments. These are always
processed first, so any files given in **BC_ENV_ARGS** 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 bc(1) runs.
The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
**"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'bc' file.bc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **BC_ENV_ARGS** 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.
**BC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
lines to that length, including the backslash (**\\**). The default line
length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**BC_BANNER**
: If this environment variable exists and contains an integer, then a non-zero
value activates the copyright banner when bc(1) is in interactive mode,
while zero deactivates it.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) does not print
the banner when not in interactive mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_SIGINT_RESET**
: If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) exits on
**SIGINT** when not in interactive mode.
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1) reset
on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
environment variable exists and is *not* an integer, then bc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use TTY
mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a prompt,
and zero or a non-integer makes bc(1) not use a prompt. If this environment
variable does not exist and **BC_TTY_MODE** does, then the value of the
**BC_TTY_MODE** environment variable is used.
This environment variable and the **BC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
bc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, taking the square root of a negative
number, attempting to convert a negative number to a hardware integer,
overflow when converting a number to a hardware integer, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**) operator and the corresponding assignment operator.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, using a token where it is invalid,
giving an invalid expression, giving an invalid print statement, giving an
invalid function definition, attempting to assign to an expression that is
not a named expression (see the *Named Expressions* subsection of the
**SYNTAX** section), giving an invalid **auto** list, having a duplicate
**auto**/function parameter, failing to find the end of a code block,
attempting to return a value from a **void** function, attempting to use a
variable as a reference, and using any extensions when the option **-s** or
any equivalents were given.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors, passing the
wrong number of arguments to functions, attempting to call an undefined
function, and attempting to use a **void** function call as a value in an
expression.
**4**
: A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, failing to open
files, attempting to use files that do not have only ASCII characters (bc(1)
only accepts ASCII characters), attempting to open a directory as a file,
and giving invalid command-line options.
The exit status **4** is special; when a fatal error occurs, bc(1) always exits
and returns **4**, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interactive mode
(see the **INTERACTIVE MODE** section), since bc(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
**-i** flag or **-\-interactive** option.
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **BC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **BC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
mode on.
If the environment variable **BC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **BC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, bc(1) will
exit.
However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
default is an integer and non-zero, then bc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If bc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If bc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
can seem as though bc(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 bc(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.
**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
default handler for all other signals.
# SEE ALSO
dc(1)
# STANDARDS
bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
specification. The flags **-efghiqsvVw**, all long options, and the extensions
noted above are extensions to that specification.
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
diff --git a/manuals/bc/EN.1 b/manuals/bc/EN.1
index e67cbf332c88..192dccfea2fc 100644
--- a/manuals/bc/EN.1
+++ b/manuals/bc/EN.1
@@ -1,1578 +1,1623 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH NAME
.PP
bc - arbitrary-precision decimal arithmetic language and calculator
.SH SYNOPSIS
.PP
\f[B]bc\f[R] [\f[B]-ghilPqRsvVw\f[R]] [\f[B]--global-stacks\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]]
[\f[B]--no-prompt\f[R]] [\f[B]--no-read-prompt\f[R]] [\f[B]--quiet\f[R]]
[\f[B]--standard\f[R]] [\f[B]--warn\f[R]] [\f[B]--version\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX.
(The current standard is
here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).)
The language provides unlimited precision decimal arithmetic and is
somewhat C-like, but there are differences.
Such differences will be noted in this document.
.PP
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from \f[B]stdin\f[R].
.PP
This bc(1) is a drop-in replacement for \f[I]any\f[R] bc(1), including
(and especially) the GNU bc(1).
.PP
\f[B]Note\f[R]: If running this bc(1) on \f[I]any\f[R] script meant for
another bc(1) gives a parse error, it is probably because a word this
bc(1) reserves as a keyword is used as the name of a function, variable,
or array.
To fix that, use the command-line option \f[B]-r\f[R] \f[I]keyword\f[R],
where \f[I]keyword\f[R] is the keyword that is used as a name in the
script.
For more information, see the \f[B]OPTIONS\f[R] section.
.PP
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported.
See the \f[B]BUGS\f[R] section.
.SH OPTIONS
.PP
The following are the options that bc(1) accepts.
.TP
\f[B]-g\f[R], \f[B]--global-stacks\f[R]
Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]
into stacks.
.RS
.PP
This has the effect that a copy of the current value of all three are
pushed onto a stack for every function call, as well as popped when
every function returns.
This means that functions can assign to any and all of those globals
without worrying that the change will affect other functions.
Thus, a hypothetical function named \f[B]output(x,b)\f[R] that simply
printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this:
.IP
.nf
\f[C]
define void output(x, b) {
obase=b
x
}
\f[R]
.fi
.PP
instead of like this:
.IP
.nf
\f[C]
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
\f[R]
.fi
.PP
This makes writing functions much easier.
.PP
However, since using this flag means that functions cannot set
\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R] globally, functions
that are made to do so cannot work anymore.
There are two possible use cases for that, and each has a solution.
.PP
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases.
Examples:
.IP
.nf
\f[C]
alias d2o=\[dq]bc -e ibase=A -e obase=8\[dq]
alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq]
\f[R]
.fi
.PP
Second, if the purpose of a function is to set \f[B]ibase\f[R],
\f[B]obase\f[R], or \f[B]scale\f[R] globally for any other purpose, it
could be split into one to three functions (based on how many globals it
sets) and each of those functions could return the desired value for a
global.
.PP
If the behavior of this option is desired for every run of bc(1), then
users could make sure to define \f[B]BC_ENV_ARGS\f[R] and include this
option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more
details).
.PP
If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option
is ignored.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-l\f[R], \f[B]--mathlib\f[R]
Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R]
and loads the included math library before running any code, including
any expressions or files specified on the command line.
.RS
.PP
To learn what is in the library, see the \f[B]LIBRARY\f[R] section.
.RE
.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.RS
.PP
These options override the \f[B]BC_PROMPT\f[R] and \f[B]BC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of bc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]read()\f[R] built-in function is called.
.PP
These options \f[I]do\f[R] override the \f[B]BC_PROMPT\f[R] and
\f[B]BC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-r\f[R] \f[I]keyword\f[R], \f[B]--redefine\f[R]=\f[I]keyword\f[R]
Redefines \f[I]keyword\f[R] in order to allow it to be used as a
function, variable, or array name.
This is useful when this bc(1) gives parse errors when parsing scripts
meant for other bc(1) implementations.
.RS
.PP
The keywords this bc(1) allows to be redefined are:
.IP \[bu] 2
\f[B]abs\f[R]
.IP \[bu] 2
\f[B]asciify\f[R]
.IP \[bu] 2
\f[B]continue\f[R]
.IP \[bu] 2
\f[B]divmod\f[R]
.IP \[bu] 2
\f[B]else\f[R]
.IP \[bu] 2
\f[B]halt\f[R]
.IP \[bu] 2
\f[B]last\f[R]
.IP \[bu] 2
\f[B]limits\f[R]
.IP \[bu] 2
\f[B]maxibase\f[R]
.IP \[bu] 2
\f[B]maxobase\f[R]
.IP \[bu] 2
\f[B]maxscale\f[R]
.IP \[bu] 2
\f[B]modexp\f[R]
.IP \[bu] 2
\f[B]print\f[R]
.IP \[bu] 2
\f[B]read\f[R]
.IP \[bu] 2
\f[B]stream\f[R]
.PP
If any of those keywords are used as a function, variable, or array name
in a script, use this option with the keyword as the argument.
If multiple are used, use this option for all of them; it can be used
multiple times.
.PP
Keywords are \f[I]not\f[R] redefined when parsing the builtin math
library (see the \f[B]LIBRARY\f[R] section).
.PP
It is a fatal error to redefine keywords mandated by the POSIX standard.
It is a fatal error to attempt to redefine words that this bc(1) does
not reserve as keywords.
.RE
.TP
\f[B]-q\f[R], \f[B]--quiet\f[R]
This option is for compatibility with the GNU
bc(1) (https://www.gnu.org/software/bc/); it is a no-op.
Without this option, GNU bc(1) prints a copyright header.
This bc(1) only prints the copyright header if one or more of the
\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-s\f[R], \f[B]--standard\f[R]
Process exactly the language defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
and error if any extensions are used.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-w\f[R], \f[B]--warn\f[R]
Like \f[B]-s\f[R] and \f[B]--standard\f[R], except that warnings (and
not errors) are printed for non-standard extensions and execution
continues normally.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]BC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files or expressions are given by the \f[B]-f\f[R],
\f[B]--file\f[R], \f[B]-e\f[R], or \f[B]--expression\f[R] options, then
bc(1) read from \f[B]stdin\f[R].
.PP
However, there are a few caveats to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if the parse cannot complete.
That means that starting a string without ending it or starting a
function, \f[B]if\f[R] statement, or loop without ending it will also
cause bc(1) to not execute.
.PP
Second, after an \f[B]if\f[R] statement, bc(1) doesn\[cq]t know if an
\f[B]else\f[R] statement will follow, so it will not execute until it
knows there will not be an \f[B]else\f[R] statement.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]bc >&-\f[R], it will quit with an error.
This is done so that bc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]bc 2>&-\f[R], it will quit with an error.
This is done so that bc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
which is a much more thorough resource for the language this bc(1)
accepts.
This section is meant to be a summary and a listing of all the
extensions to the standard.
.PP
In the sections below, \f[B]E\f[R] means expression, \f[B]S\f[R] means
statement, and \f[B]I\f[R] means identifier.
.PP
Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be
followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase
letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores
(\f[B]_\f[R]).
The regex is \f[B][a-z][a-z0-9_]*\f[R].
Identifiers with more than one character (letter) are a
\f[B]non-portable extension\f[R].
.PP
\f[B]ibase\f[R] is a global variable determining how to interpret
constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R]
(\f[B]--warn\f[R]) flags were not given on the command line, the max
allowable value for \f[B]ibase\f[R] is \f[B]36\f[R].
Otherwise, it is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in bc(1)
programs with the \f[B]maxibase()\f[R] built-in function.
.PP
\f[B]obase\f[R] is a global variable determining how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and
can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in
function.
The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R].
Values are output in the specified base.
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a global variable that sets the precision of any operations, with
exceptions.
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R]
and can be queried in bc(1) programs with the \f[B]maxscale()\f[R]
built-in function.
.PP
bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables.
All \f[I]local\f[R] variables are local to the function; they are
parameters or are introduced in the \f[B]auto\f[R] list of a function
(see the \f[B]FUNCTIONS\f[R] section).
If a variable is accessed which is not a parameter or in the
\f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R].
If a parent function has a \f[I]local\f[R] variable version of a
variable that a child function considers \f[I]global\f[R], the value of
that \f[I]global\f[R] variable in the child function is the value of the
variable in the parent function, not the value of the actual
\f[I]global\f[R] variable.
.PP
All of the above applies to arrays as well.
.PP
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence
operator is an assignment operator \f[I]and\f[R] the expression is
notsurrounded by parentheses.
.PP
The value that is printed is also assigned to the special variable
\f[B]last\f[R].
A single dot (\f[B].\f[R]) may also be used as a synonym for
\f[B]last\f[R].
These are \f[B]non-portable extensions\f[R].
.PP
Either semicolons or newlines may separate statements.
.SS Comments
.PP
There are two kinds of comments:
.IP "1." 3
Block comments are enclosed in \f[B]/*\f[R] and \f[B]*/\f[R].
.IP "2." 3
Line comments go from \f[B]#\f[R] until, and not including, the next
newline.
This is a \f[B]non-portable extension\f[R].
.SS Named Expressions
.PP
The following are named expressions in bc(1):
.IP "1." 3
Variables: \f[B]I\f[R]
.IP "2." 3
Array Elements: \f[B]I[E]\f[R]
.IP "3." 3
\f[B]ibase\f[R]
.IP "4." 3
\f[B]obase\f[R]
.IP "5." 3
\f[B]scale\f[R]
.IP "6." 3
\f[B]last\f[R] or a single dot (\f[B].\f[R])
.PP
Number 6 is a \f[B]non-portable extension\f[R].
.PP
Variables and arrays do not interfere; users can have arrays named the
same as variables.
This also applies to functions (see the \f[B]FUNCTIONS\f[R] section), so
a user can have a variable, array, and function that all have the same
name, and they will not shadow each other, whether inside of functions
or not.
.PP
Named expressions are required as the operand of
\f[B]increment\f[R]/\f[B]decrement\f[R] operators and as the left side
of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R]
subsection).
.SS Operands
.PP
The following are valid operands in bc(1):
.IP " 1." 4
Numbers (see the \f[I]Numbers\f[R] subsection below).
.IP " 2." 4
Array indices (\f[B]I[E]\f[R]).
.IP " 3." 4
\f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence).
.IP " 4." 4
\f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R].
\f[B]E\f[R] must be non-negative.
.IP " 5." 4
\f[B]length(E)\f[R]: The number of significant decimal digits in
\f[B]E\f[R].
Returns \f[B]1\f[R] for \f[B]0\f[R] with no decimal places.
If given a string, the length of the string is returned.
Passing a string to \f[B]length(E)\f[R] is a \f[B]non-portable
extension\f[R].
.IP " 6." 4
\f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 7." 4
\f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R].
.IP " 8." 4
\f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 9." 4
\f[B]modexp(E, E, E)\f[R]: Modular exponentiation, where the first
expression is the base, the second is the exponent, and the third is the
modulus.
All three values must be integers.
The second argument must be non-negative.
The third argument must be non-zero.
This is a \f[B]non-portable extension\f[R].
.IP "10." 4
\f[B]divmod(E, E, I[])\f[R]: Division and modulus in one operation.
This is for optimization.
The first expression is the dividend, and the second is the divisor,
which must be non-zero.
The return value is the quotient, and the modulus is stored in index
\f[B]0\f[R] of the provided array (the last argument).
This is a \f[B]non-portable extension\f[R].
.IP "11." 4
\f[B]asciify(E)\f[R]: If \f[B]E\f[R] is a string, returns a string that
is the first letter of its argument.
If it is a number, calculates the number mod \f[B]256\f[R] and returns
that number as a one-character string.
This is a \f[B]non-portable extension\f[R].
.IP "12." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.IP "13." 4
\f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an
expression.
The result of that expression is the result of the \f[B]read()\f[R]
operand.
This is a \f[B]non-portable extension\f[R].
.IP "14." 4
\f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "15." 4
\f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "16." 4
\f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R].
This is a \f[B]non-portable extension\f[R].
+.IP "17." 4
+\f[B]line_length()\f[R]: The line length set with
+\f[B]BC_LINE_LENGTH\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
+section).
+This is a \f[B]non-portable extension\f[R].
+.IP "18." 4
+\f[B]global_stacks()\f[R]: \f[B]0\f[R] if global stacks are not enabled
+with the \f[B]-g\f[R] or \f[B]--global-stacks\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "19." 4
+\f[B]leading_zero()\f[R]: \f[B]0\f[R] if leading zeroes are not enabled
+with the \f[B]-z\f[R] or \f[B]\[en]leading-zeroes\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
.SS Numbers
.PP
Numbers are strings made up of digits, uppercase letters, and at most
\f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R].
.SS Operators
.PP
The following arithmetic and logical operators can be used.
They are listed in order of decreasing precedence.
Operators in the same group have the same precedence.
.TP
\f[B]++\f[R] \f[B]--\f[R]
Type: Prefix and Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]increment\f[R], \f[B]decrement\f[R]
.RE
.TP
\f[B]-\f[R] \f[B]!\f[R]
Type: Prefix
.RS
.PP
Associativity: None
.PP
Description: \f[B]negation\f[R], \f[B]boolean not\f[R]
.RE
.TP
\f[B]\[ha]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]power\f[R]
.RE
.TP
\f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R]
.RE
.TP
\f[B]+\f[R] \f[B]-\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]add\f[R], \f[B]subtract\f[R]
.RE
.TP
\f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]assignment\f[R]
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]relational\f[R]
.RE
.TP
\f[B]&&\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean and\f[R]
.RE
.TP
\f[B]||\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean or\f[R]
.RE
.PP
The operators will be described in more detail below.
.TP
\f[B]++\f[R] \f[B]--\f[R]
The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R]
operators behave exactly like they would in C.
They require a named expression (see the \f[I]Named Expressions\f[R]
subsection) as an operand.
.RS
.PP
The prefix versions of these operators are more efficient; use them
where possible.
.RE
.TP
\f[B]-\f[R]
The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts
to negate any expression with the value \f[B]0\f[R].
Otherwise, a copy of the expression with its sign flipped is returned.
.TP
\f[B]!\f[R]
The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression
is \f[B]0\f[R], or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator,
as it would be in C) takes two expressions and raises the first to the
power of the value of the second.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]), and if it
is negative, the first value must be non-zero.
.RE
.TP
\f[B]*\f[R]
The \f[B]multiply\f[R] operator takes two expressions, multiplies them,
and returns the product.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The \f[B]divide\f[R] operator takes two expressions, divides them, and
returns the quotient.
The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]%\f[R]
The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R] and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]+\f[R]
The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the
max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]-\f[R]
The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to
the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R]
The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and
\f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named
Expressions\f[R] subsection).
.RS
.PP
For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to
\f[B]a\f[R].
For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to
the corresponding arithmetic operator and the result is assigned to
\f[B]a\f[R].
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and if the relation holds, according to C language
semantics, the result is \f[B]1\f[R].
Otherwise, it is \f[B]0\f[R].
.RS
.PP
Note that unlike in C, these operators have a lower precedence than the
\f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is
interpreted as \f[B](a=b)>c\f[R].
.PP
Also, unlike the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
requires, these operators can appear anywhere any other expressions can
be used.
This allowance is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]&&\f[R]
The \f[B]boolean and\f[R] operator takes two expressions and returns
\f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]||\f[R]
The \f[B]boolean or\f[R] operator takes two expressions and returns
\f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R]
otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Statements
.PP
The following items are statements:
.IP " 1." 4
\f[B]E\f[R]
.IP " 2." 4
\f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R]
\f[B]}\f[R]
.IP " 3." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 4." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
\f[B]else\f[R] \f[B]S\f[R]
.IP " 5." 4
\f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 6." 4
\f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R]
\f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 7." 4
An empty statement
.IP " 8." 4
\f[B]break\f[R]
.IP " 9." 4
\f[B]continue\f[R]
.IP "10." 4
\f[B]quit\f[R]
.IP "11." 4
\f[B]halt\f[R]
.IP "12." 4
\f[B]limits\f[R]
.IP "13." 4
A string of characters, enclosed in double quotes
.IP "14." 4
\f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "15." 4
\f[B]stream\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "16." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.PP
Numbers 4, 9, 11, 12, 14, 15, and 16 are \f[B]non-portable
extensions\f[R].
.PP
Also, as a \f[B]non-portable extension\f[R], any or all of the
expressions in the header of a for loop may be omitted.
If the condition (second expression) is omitted, it is assumed to be a
constant \f[B]1\f[R].
.PP
The \f[B]break\f[R] statement causes a loop to stop iterating and resume
execution immediately following a loop.
This is only allowed in loops.
.PP
The \f[B]continue\f[R] statement causes a loop iteration to stop early
and returns to the start of the loop, including testing the loop
condition.
This is only allowed in loops.
.PP
The \f[B]if\f[R] \f[B]else\f[R] statement does the same thing as in C.
.PP
The \f[B]quit\f[R] statement causes bc(1) to quit, even if it is on a
branch that will not be executed (it is a compile-time command).
.PP
The \f[B]halt\f[R] statement causes bc(1) to quit, if it is executed.
(Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement
that is not executed, bc(1) does not quit.)
.PP
The \f[B]limits\f[R] statement prints the limits that this bc(1) is
subject to.
This is like the \f[B]quit\f[R] statement in that it is a compile-time
command.
.PP
An expression by itself is evaluated and printed, followed by a newline.
.SS Strings
.PP
If strings appear as a statement by themselves, they are printed without
a trailing newline.
.PP
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements.
They can also be passed to functions in variable parameters.
.PP
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
.PP
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section).
.PP
Assigning strings to variables and array elements and passing them to
functions are \f[B]non-portable extensions\f[R].
.SS Print Statement
.PP
The \[lq]expressions\[rq] in a \f[B]print\f[R] statement may also be
strings.
If they are, there are backslash escape sequences that are interpreted
specially.
What those sequences are, and what they cause to be printed, are shown
below:
.PP
\f[B]\[rs]a\f[R]: \f[B]\[rs]a\f[R]
.PP
\f[B]\[rs]b\f[R]: \f[B]\[rs]b\f[R]
.PP
\f[B]\[rs]\[rs]\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]e\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]f\f[R]: \f[B]\[rs]f\f[R]
.PP
\f[B]\[rs]n\f[R]: \f[B]\[rs]n\f[R]
.PP
\f[B]\[rs]q\f[R]: \f[B]\[lq]\f[R]
.PP
\f[B]\[rs]r\f[R]: \f[B]\[rs]r\f[R]
.PP
\f[B]\[rs]t\f[R]: \f[B]\[rs]t\f[R]
.PP
Any other character following a backslash causes the backslash and
character to be printed as-is.
.PP
Any non-string expression in a print statement shall be assigned to
\f[B]last\f[R], like any other expression that is printed.
.SS Stream Statement
.PP
The \[lq]expressions in a \f[B]stream\f[R] statement may also be
strings.
.PP
If a \f[B]stream\f[R] statement is given a string, it prints the string
as though the string had appeared as its own statement.
In other words, the \f[B]stream\f[R] statement prints strings normally,
without a newline.
.PP
If a \f[B]stream\f[R] statement is given a number, a copy of it is
truncated and its absolute value is calculated.
The result is then printed as though \f[B]obase\f[R] is \f[B]256\f[R]
and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
.SS Order of Evaluation
.PP
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations.
This means, for example, assuming that \f[B]i\f[R] is equal to
\f[B]0\f[R], in the expression
.IP
.nf
\f[C]
a[i++] = i++
\f[R]
.fi
.PP
the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and
\f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression.
.PP
This includes function arguments.
Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in
the expression
.IP
.nf
\f[C]
x(i++, i++)
\f[R]
.fi
.PP
the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the
second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to
\f[B]2\f[R] before the function starts executing.
.SH FUNCTIONS
.PP
Function definitions are as follows:
.IP
.nf
\f[C]
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
\f[R]
.fi
.PP
Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be
replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an
array, and any \f[B]I\f[R] in the parameter list may be replaced with
\f[B]*I[]\f[R] to make a parameter an array reference.
Callers of functions that take array references should not put an
asterisk in the call; they must be called with just \f[B]I[]\f[R] like
normal array parameters and will be automatically converted into
references.
.PP
As a \f[B]non-portable extension\f[R], the opening brace of a
\f[B]define\f[R] statement may appear on the next line.
.PP
As a \f[B]non-portable extension\f[R], the return statement may also be
in one of the following forms:
.IP "1." 3
\f[B]return\f[R]
.IP "2." 3
\f[B]return\f[R] \f[B](\f[R] \f[B])\f[R]
.IP "3." 3
\f[B]return\f[R] \f[B]E\f[R]
.PP
The first two, or not specifying a \f[B]return\f[R] statement, is
equivalent to \f[B]return (0)\f[R], unless the function is a
\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection
below).
.SS Void Functions
.PP
Functions can also be \f[B]void\f[R] functions, defined as follows:
.IP
.nf
\f[C]
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
\f[R]
.fi
.PP
They can only be used as standalone expressions, where such an
expression would be printed alone, except in a print statement.
.PP
Void functions can only use the first two \f[B]return\f[R] statements
listed above.
They can also omit the return statement entirely.
.PP
The word \[lq]void\[rq] is not treated as a keyword; it is still
possible to have variables, arrays, and functions named \f[B]void\f[R].
The word \[lq]void\[rq] is only treated specially right after the
\f[B]define\f[R] keyword.
.PP
This is a \f[B]non-portable extension\f[R].
.SS Array References
.PP
For any array in the parameter list, if the array is declared in the
form
.IP
.nf
\f[C]
*I[]
\f[R]
.fi
.PP
it is a \f[B]reference\f[R].
Any changes to the array in the function are reflected, when the
function returns, to the array that was passed in.
.PP
Other than this, all function arguments are passed by value.
.PP
This is a \f[B]non-portable extension\f[R].
.SH LIBRARY
.PP
All of the functions below are available when the \f[B]-l\f[R] or
\f[B]--mathlib\f[R] command-line flags are given.
.SS Standard Library
.PP
The
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
defines the following functions for the math library:
.TP
\f[B]s(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]c(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l(x)\f[R]
Returns the natural logarithm of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]e(x)\f[R]
Returns the mathematical constant \f[B]e\f[R] raised to the power of
\f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]j(x, n)\f[R]
Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.SS Transcendental Functions
.PP
All transcendental functions can return slightly inaccurate results (up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)).
This is unavoidable, and this
article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains
why it is impossible and unnecessary to calculate exact results for the
transcendental functions.
.PP
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (\f[B]scale\f[R]) set to at least 1 higher
than is necessary.
If exact results are \f[I]absolutely\f[R] required, users can double the
precision (\f[B]scale\f[R]) and then truncate.
.PP
The transcendental functions in the standard math library are:
.IP \[bu] 2
\f[B]s(x)\f[R]
.IP \[bu] 2
\f[B]c(x)\f[R]
.IP \[bu] 2
\f[B]a(x)\f[R]
.IP \[bu] 2
\f[B]l(x)\f[R]
.IP \[bu] 2
\f[B]e(x)\f[R]
.IP \[bu] 2
\f[B]j(x, n)\f[R]
.SH RESET
.PP
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets.
This means that several things happen.
.PP
First, any functions 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.
.PP
Thus, when bc(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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.PP
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This bc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R]
can be queried with the \f[B]limits\f[R] statement.
.PP
In addition, this bc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bc(1):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bc(1) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
The actual values can be queried with the \f[B]limits\f[R] statement.
.PP
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
.PP
bc(1) recognizes the following environment variables:
.TP
\f[B]POSIXLY_CORRECT\f[R]
If this variable exists (no matter the contents), bc(1) behaves as if
the \f[B]-s\f[R] option was given.
.TP
\f[B]BC_ENV_ARGS\f[R]
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line arguments.
These are always processed first, so any files given in
\f[B]BC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 bc(1) runs.
.RS
.PP
The code that parses \f[B]BC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`bc' file.bc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]BC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]BC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length,
including the backslash (\f[B]\[rs]\f[R]).
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]BC_BANNER\f[R]
If this environment variable exists and contains an integer, then a
non-zero value activates the copyright banner when bc(1) is in
interactive mode, while zero deactivates it.
.RS
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
does not print the banner when not in interactive mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_SIGINT_RESET\f[R]
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes bc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then bc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use
TTY mode, and zero makes bc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a
prompt, and zero or a non-integer makes bc(1) not use a prompt.
If this environment variable does not exist and \f[B]BC_TTY_MODE\f[R]
does, then the value of the \f[B]BC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]BC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
bc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], taking the square root of a
negative number, attempting to convert a negative number to a hardware
integer, overflow when converting a number to a hardware integer,
overflow when calculating the size of a number, and attempting to use a
non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]) operator and the corresponding assignment
operator.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an invalid
print statement, giving an invalid function definition, attempting to
assign to an expression that is not a named expression (see the
\f[I]Named Expressions\f[R] subsection of the \f[B]SYNTAX\f[R] section),
giving an invalid \f[B]auto\f[R] list, having a duplicate
\f[B]auto\f[R]/function parameter, failing to find the end of a code
block, attempting to return a value from a \f[B]void\f[R] function,
attempting to use a variable as a reference, and using any extensions
when the option \f[B]-s\f[R] or any equivalents were given.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors, passing the wrong number of
arguments to functions, attempting to call an undefined function, and
attempting to use a \f[B]void\f[R] function call as a value in an
expression.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
Fatal errors include memory allocation errors, I/O errors, failing to
open files, attempting to use files that do not have only ASCII
characters (bc(1) only accepts ASCII characters), attempting to open a
directory as a file, and giving invalid command-line options.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, bc(1)
always exits and returns \f[B]4\f[R], no matter what mode bc(1) is in.
.PP
The other statuses will only be returned when bc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
bc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Per the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, bc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
bc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]BC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, bc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]BC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, bc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]BC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then bc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]BC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Command-Line History
.PP
Command-line history is only enabled if TTY mode is, i.e., that
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to
a TTY and the \f[B]BC_TTY_MODE\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section) and its default do not disable
TTY mode.
See the \f[B]COMMAND LINE HISTORY\f[R] section for more information.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]BC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]BC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]BC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]BC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause bc(1) to do one of two things.
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, bc(1) will exit.
.PP
However, if bc(1) is in interactive mode, and the
\f[B]BC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then bc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If bc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If bc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] is sent to bc(1) as it is
executing a file, it can seem as though bc(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
bc(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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause bc(1) to clean up and
exit, and it uses the default handler for all other signals.
The one exception is \f[B]SIGHUP\f[R]; in that case, and only when bc(1)
is in TTY mode (see the \f[B]TTY MODE\f[R] section), a \f[B]SIGHUP\f[R]
will cause bc(1) to clean up and exit.
.SH COMMAND LINE HISTORY
.PP
bc(1) supports interactive command-line editing.
.PP
If bc(1) can be in TTY mode (see the \f[B]TTY MODE\f[R] section),
history can be enabled.
This means that command-line history can only be enabled when
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY.
.PP
Like TTY mode itself, it can be turned on or off with the environment
variable \f[B]BC_TTY_MODE\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If history is enabled, previous lines can be recalled and edited with
the arrow keys.
.PP
\f[B]Note\f[R]: tabs are converted to 8 spaces.
.SH SEE ALSO
.PP
dc(1)
.SH STANDARDS
.PP
bc(1) is compliant with the IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
The flags \f[B]-efghiqsvVw\f[R], all long options, and the extensions
noted above are extensions to that specification.
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bc/EN.1.md b/manuals/bc/EN.1.md
index c99a9a28a405..e77d64cd7a56 100644
--- a/manuals/bc/EN.1.md
+++ b/manuals/bc/EN.1.md
@@ -1,1327 +1,1357 @@
# NAME
bc - arbitrary-precision decimal arithmetic language and calculator
# SYNOPSIS
**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# DESCRIPTION
bc(1) is an interactive processor for a language first standardized in 1991 by
POSIX. (The current standard is [here][1].) The language provides unlimited
precision decimal arithmetic and is somewhat C-like, but there are differences.
Such differences will be noted in this document.
After parsing and handling options, this bc(1) reads any files given on the
command line and executes them before reading from **stdin**.
This bc(1) is a drop-in replacement for *any* bc(1), including (and especially)
the GNU bc(1).
**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
parse error, it is probably because a word this bc(1) reserves as a keyword is
used as the name of a function, variable, or array. To fix that, use the
command-line option **-r** *keyword*, where *keyword* is the keyword that is
used as a name in the script. For more information, see the **OPTIONS** section.
If parsing scripts meant for other bc(1) implementations still does not work,
that is a bug and should be reported. See the **BUGS** section.
# OPTIONS
The following are the options that bc(1) accepts.
**-g**, **-\-global-stacks**
: Turns the globals **ibase**, **obase**, and **scale** into stacks.
This has the effect that a copy of the current value of all three are pushed
onto a stack for every function call, as well as popped when every function
returns. This means that functions can assign to any and all of those
globals without worrying that the change will affect other functions.
Thus, a hypothetical function named **output(x,b)** that simply printed
**x** in base **b** could be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
However, since using this flag means that functions cannot set **ibase**,
**obase**, or **scale** globally, functions that are made to do so cannot
work anymore. There are two possible use cases for that, and each has a
solution.
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set **ibase**, **obase**, or
**scale** globally for any other purpose, it could be split into one to
three functions (based on how many globals it sets) and each of those
functions could return the desired value for a global.
If the behavior of this option is desired for every run of bc(1), then users
could make sure to define **BC_ENV_ARGS** and include this option (see the
**ENVIRONMENT VARIABLES** section for more details).
If **-s**, **-w**, or any equivalents are used, this option is ignored.
This is a **non-portable extension**.
**-h**, **-\-help**
: Prints a usage message and quits.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-l**, **-\-mathlib**
: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
math library before running any code, including any expressions or files
specified on the command line.
To learn what is in the library, see the **LIBRARY** section.
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in bc(1). Most of those users
would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section).
These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of bc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **read()** built-in function is called.
These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-r** *keyword*, **-\-redefine**=*keyword*
: Redefines *keyword* in order to allow it to be used as a function, variable,
or array name. This is useful when this bc(1) gives parse errors when
parsing scripts meant for other bc(1) implementations.
The keywords this bc(1) allows to be redefined are:
* **abs**
* **asciify**
* **continue**
* **divmod**
* **else**
* **halt**
* **last**
* **limits**
* **maxibase**
* **maxobase**
* **maxscale**
* **modexp**
* **print**
* **read**
* **stream**
If any of those keywords are used as a function, variable, or array name in
a script, use this option with the keyword as the argument. If multiple are
used, use this option for all of them; it can be used multiple times.
Keywords are *not* redefined when parsing the builtin math library (see the
**LIBRARY** section).
It is a fatal error to redefine keywords mandated by the POSIX standard. It
is a fatal error to attempt to redefine words that this bc(1) does not
reserve as keywords.
**-q**, **-\-quiet**
: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
Without this option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the **-v**, **-V**, or
**-\-version** options are given.
This is a **non-portable extension**.
**-s**, **-\-standard**
: Process exactly the language defined by the [standard][1] and error if any
extensions are used.
This is a **non-portable extension**.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
This is a **non-portable extension**.
**-w**, **-\-warn**
: Like **-s** and **-\-standard**, except that warnings (and not errors) are
printed for non-standard extensions and execution continues normally.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
**-\-expression** options, then bc(1) read from **stdin**.
However, there are a few caveats to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
the parse cannot complete. That means that starting a string without ending it
or starting a function, **if** statement, or loop without ending it will also
cause bc(1) to not execute.
Second, after an **if** statement, bc(1) doesn't know if an **else** statement
will follow, so it will not execute until it knows there will not be an **else**
statement.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **bc >&-**, it will quit with an error. This
is done so that bc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This
is done so that bc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences. This
bc(1) follows the [POSIX standard][1], which is a much more thorough resource
for the language this bc(1) accepts. This section is meant to be a summary and a
listing of all the extensions to the standard.
In the sections below, **E** means expression, **S** means statement, and **I**
means identifier.
Identifiers (**I**) start with a lowercase letter and can be followed by any
number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
Identifiers with more than one character (letter) are a
**non-portable extension**.
**ibase** is a global variable determining how to interpret constant numbers. It
is the "input" base, or the number base used for interpreting input numbers.
**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
(**-\-warn**) flags were not given on the command line, the max allowable value
for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
**ibase** is **2**. The max allowable value for **ibase** can be queried in
bc(1) programs with the **maxibase()** built-in function.
**obase** is a global variable determining how to output results. It is the
"output" base, or the number base used for outputting numbers. **obase** is
initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
can be queried in bc(1) programs with the **maxobase()** built-in function. The
min allowable value for **obase** is **2**. Values are output in the specified
base.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a global variable that
sets the precision of any operations, with exceptions. **scale** is initially
**0**. **scale** cannot be negative. The max allowable value for **scale** is
**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
built-in function.
bc(1) has both *global* variables and *local* variables. All *local*
variables are local to the function; they are parameters or are introduced in
the **auto** list of a function (see the **FUNCTIONS** section). If a variable
is accessed which is not a parameter or in the **auto** list, it is assumed to
be *global*. If a parent function has a *local* variable version of a variable
that a child function considers *global*, the value of that *global* variable in
the child function is the value of the variable in the parent function, not the
value of the actual *global* variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence operator is an
assignment operator *and* the expression is notsurrounded by parentheses.
The value that is printed is also assigned to the special variable **last**. A
single dot (**.**) may also be used as a synonym for **last**. These are
**non-portable extensions**.
Either semicolons or newlines may separate statements.
## Comments
There are two kinds of comments:
1. Block comments are enclosed in **/\*** and **\*/**.
2. Line comments go from **#** until, and not including, the next newline. This
is a **non-portable extension**.
## Named Expressions
The following are named expressions in bc(1):
1. Variables: **I**
2. Array Elements: **I[E]**
3. **ibase**
4. **obase**
5. **scale**
6. **last** or a single dot (**.**)
Number 6 is a **non-portable extension**.
Variables and arrays do not interfere; users can have arrays named the same as
variables. This also applies to functions (see the **FUNCTIONS** section), so a
user can have a variable, array, and function that all have the same name, and
they will not shadow each other, whether inside of functions or not.
Named expressions are required as the operand of **increment**/**decrement**
operators and as the left side of **assignment** operators (see the *Operators*
subsection).
## Operands
The following are valid operands in bc(1):
1. Numbers (see the *Numbers* subsection below).
2. Array indices (**I[E]**).
3. **(E)**: The value of **E** (used to change precedence).
4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
5. **length(E)**: The number of significant decimal digits in **E**. Returns
**1** for **0** with no decimal places. If given a string, the length of the
string is returned. Passing a string to **length(E)** is a **non-portable
extension**.
6. **length(I[])**: The number of elements in the array **I**. This is a
**non-portable extension**.
7. **scale(E)**: The *scale* of **E**.
8. **abs(E)**: The absolute value of **E**. This is a **non-portable
extension**.
9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
the base, the second is the exponent, and the third is the modulus. All
three values must be integers. The second argument must be non-negative. The
third argument must be non-zero. This is a **non-portable extension**.
10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
optimization. The first expression is the dividend, and the second is the
divisor, which must be non-zero. The return value is the quotient, and the
modulus is stored in index **0** of the provided array (the last argument).
This is a **non-portable extension**.
11. **asciify(E)**: If **E** is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number mod **256**
and returns that number as a one-character string. This is a **non-portable
extension**.
12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a non-**void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
13. **read()**: Reads a line from **stdin** and uses that as an expression. The
result of that expression is the result of the **read()** operand. This is a
**non-portable extension**.
14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
extension**.
15. **maxobase()**: The max allowable **obase**. This is a **non-portable
extension**.
16. **maxscale()**: The max allowable **scale**. This is a **non-portable
extension**.
+17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
+ **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
+18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
+ or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
+ or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
## Numbers
Numbers are strings made up of digits, uppercase letters, and at most **1**
period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
letters are equal to **9** + their position in the alphabet (i.e., **A** equals
**10**, or **9+1**). If a digit or letter makes no sense with the current value
of **ibase**, they are set to the value of the highest valid digit in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **Z** alone always equals decimal
**35**.
## Operators
The following arithmetic and logical operators can be used. They are listed in
order of decreasing precedence. Operators in the same group have the same
precedence.
**++** **-\-**
: Type: Prefix and Postfix
Associativity: None
Description: **increment**, **decrement**
**-** **!**
: Type: Prefix
Associativity: None
Description: **negation**, **boolean not**
**\^**
: Type: Binary
Associativity: Right
Description: **power**
**\*** **/** **%**
: Type: Binary
Associativity: Left
Description: **multiply**, **divide**, **modulus**
**+** **-**
: Type: Binary
Associativity: Left
Description: **add**, **subtract**
**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
: Type: Binary
Associativity: Right
Description: **assignment**
**==** **\<=** **\>=** **!=** **\<** **\>**
: Type: Binary
Associativity: Left
Description: **relational**
**&&**
: Type: Binary
Associativity: Left
Description: **boolean and**
**||**
: Type: Binary
Associativity: Left
Description: **boolean or**
The operators will be described in more detail below.
**++** **-\-**
: The prefix and postfix **increment** and **decrement** operators behave
exactly like they would in C. They require a named expression (see the
*Named Expressions* subsection) as an operand.
The prefix versions of these operators are more efficient; use them where
possible.
**-**
: The **negation** operator returns **0** if a user attempts to negate any
expression with the value **0**. Otherwise, a copy of the expression with
its sign flipped is returned.
**!**
: The **boolean not** operator returns **1** if the expression is **0**, or
**0** otherwise.
This is a **non-portable extension**.
**\^**
: The **power** operator (not the **exclusive or** operator, as it would be in
C) takes two expressions and raises the first to the power of the value of
the second. The *scale* of the result is equal to **scale**.
The second expression must be an integer (no *scale*), and if it is
negative, the first value must be non-zero.
**\***
: The **multiply** operator takes two expressions, multiplies them, and
returns the product. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result is
equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The **divide** operator takes two expressions, divides them, and returns the
quotient. The *scale* of the result shall be the value of **scale**.
The second expression must be non-zero.
**%**
: The **modulus** operator takes two expressions, **a** and **b**, and
evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The second expression must be non-zero.
**+**
: The **add** operator takes two expressions, **a** and **b**, and returns the
sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
**-**
: The **subtract** operator takes two expressions, **a** and **b**, and
returns the difference, with a *scale* equal to the max of the *scale*s of
**a** and **b**.
**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
: The **assignment** operators take two expressions, **a** and **b** where
**a** is a named expression (see the *Named Expressions* subsection).
For **=**, **b** is copied and the result is assigned to **a**. For all
others, **a** and **b** are applied as operands to the corresponding
arithmetic operator and the result is assigned to **a**.
**==** **\<=** **\>=** **!=** **\<** **\>**
: The **relational** operators compare two expressions, **a** and **b**, and
if the relation holds, according to C language semantics, the result is
**1**. Otherwise, it is **0**.
Note that unlike in C, these operators have a lower precedence than the
**assignment** operators, which means that **a=b\>c** is interpreted as
**(a=b)\>c**.
Also, unlike the [standard][1] requires, these operators can appear anywhere
any other expressions can be used. This allowance is a
**non-portable extension**.
**&&**
: The **boolean and** operator takes two expressions and returns **1** if both
expressions are non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
**||**
: The **boolean or** operator takes two expressions and returns **1** if one
of the expressions is non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
## Statements
The following items are statements:
1. **E**
2. **{** **S** **;** ... **;** **S** **}**
3. **if** **(** **E** **)** **S**
4. **if** **(** **E** **)** **S** **else** **S**
5. **while** **(** **E** **)** **S**
6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
7. An empty statement
8. **break**
9. **continue**
10. **quit**
11. **halt**
12. **limits**
13. A string of characters, enclosed in double quotes
14. **print** **E** **,** ... **,** **E**
15. **stream** **E** **,** ... **,** **E**
16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
Also, as a **non-portable extension**, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expression) is
omitted, it is assumed to be a constant **1**.
The **break** statement causes a loop to stop iterating and resume execution
immediately following a loop. This is only allowed in loops.
The **continue** statement causes a loop iteration to stop early and returns to
the start of the loop, including testing the loop condition. This is only
allowed in loops.
The **if** **else** statement does the same thing as in C.
The **quit** statement causes bc(1) to quit, even if it is on a branch that will
not be executed (it is a compile-time command).
The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
if it is on a branch of an **if** statement that is not executed, bc(1) does not
quit.)
The **limits** statement prints the limits that this bc(1) is subject to. This
is like the **quit** statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a newline.
## Strings
If strings appear as a statement by themselves, they are printed without a
trailing newline.
In addition to appearing as a lone statement by themselves, strings can be
assigned to variables and array elements. They can also be passed to functions
in variable parameters.
If any statement that expects a string is given a variable that had a string
assigned to it, the statement acts as though it had received a string.
If any math operation is attempted on a string or a variable or array element
that has been assigned a string, an error is raised, and bc(1) resets (see the
**RESET** section).
Assigning strings to variables and array elements and passing them to functions
are **non-portable extensions**.
## Print Statement
The "expressions" in a **print** statement may also be strings. If they are, there
are backslash escape sequences that are interpreted specially. What those
sequences are, and what they cause to be printed, are shown below:
**\\a**: **\\a**
**\\b**: **\\b**
**\\\\**: **\\**
**\\e**: **\\**
**\\f**: **\\f**
**\\n**: **\\n**
**\\q**: **"**
**\\r**: **\\r**
**\\t**: **\\t**
Any other character following a backslash causes the backslash and character to
be printed as-is.
Any non-string expression in a print statement shall be assigned to **last**,
like any other expression that is printed.
## Stream Statement
The "expressions in a **stream** statement may also be strings.
If a **stream** statement is given a string, it prints the string as though the
string had appeared as its own statement. In other words, the **stream**
statement prints strings normally, without a newline.
If a **stream** statement is given a number, a copy of it is truncated and its
absolute value is calculated. The result is then printed as though **obase** is
**256** and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
## Order of Evaluation
All expressions in a statment are evaluated left to right, except as necessary
to maintain order of operations. This means, for example, assuming that **i** is
equal to **0**, in the expression
a[i++] = i++
the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
at the end of the expression.
This includes function arguments. Thus, assuming **i** is equal to **0**, this
means that in the expression
x(i++, i++)
the first argument passed to **x()** is **0**, and the second argument is **1**,
while **i** is equal to **2** before the function starts executing.
# FUNCTIONS
Function definitions are as follows:
```
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
```
Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
make a parameter or **auto** var an array, and any **I** in the parameter list
may be replaced with **\*I[]** to make a parameter an array reference. Callers
of functions that take array references should not put an asterisk in the call;
they must be called with just **I[]** like normal array parameters and will be
automatically converted into references.
As a **non-portable extension**, the opening brace of a **define** statement may
appear on the next line.
As a **non-portable extension**, the return statement may also be in one of the
following forms:
1. **return**
2. **return** **(** **)**
3. **return** **E**
The first two, or not specifying a **return** statement, is equivalent to
**return (0)**, unless the function is a **void** function (see the *Void
Functions* subsection below).
## Void Functions
Functions can also be **void** functions, defined as follows:
```
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
```
They can only be used as standalone expressions, where such an expression would
be printed alone, except in a print statement.
Void functions can only use the first two **return** statements listed above.
They can also omit the return statement entirely.
The word "void" is not treated as a keyword; it is still possible to have
variables, arrays, and functions named **void**. The word "void" is only
treated specially right after the **define** keyword.
This is a **non-portable extension**.
## Array References
For any array in the parameter list, if the array is declared in the form
```
*I[]
```
it is a **reference**. Any changes to the array in the function are reflected,
when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a **non-portable extension**.
# LIBRARY
All of the functions below are available when the **-l** or **-\-mathlib**
command-line flags are given.
## Standard Library
The [standard][1] defines the following functions for the math library:
**s(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**c(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a(x)**
: Returns the arctangent of **x**, in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l(x)**
: Returns the natural logarithm of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**e(x)**
: Returns the mathematical constant **e** raised to the power of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**j(x, n)**
: Returns the bessel integer order **n** (truncated) of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
## Transcendental Functions
All transcendental functions can return slightly inaccurate results (up to 1
[ULP][4]). This is unavoidable, and [this article][5] explains why it is
impossible and unnecessary to calculate exact results for the transcendental
functions.
Because of the possible inaccuracy, I recommend that users call those functions
with the precision (**scale**) set to at least 1 higher than is necessary. If
exact results are *absolutely* required, users can double the precision
(**scale**) and then truncate.
The transcendental functions in the standard math library are:
* **s(x)**
* **c(x)**
* **a(x)**
* **l(x)**
* **e(x)**
* **j(x, n)**
# RESET
When bc(1) encounters an error or a signal that it has a non-default handler
for, it resets. This means that several things happen.
First, any functions 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.
Thus, when bc(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.
Note that this reset behavior is different from the GNU bc(1), which attempts to
start executing the statement right after the one that caused an error.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This bc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
the **limits** statement.
In addition, this bc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bc(1):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bc(1) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_STRING_MAX**
: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
**BC_NAME_MAX**
: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
The actual values can be queried with the **limits** statement.
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.
# ENVIRONMENT VARIABLES
bc(1) recognizes the following environment variables:
**POSIXLY_CORRECT**
: If this variable exists (no matter the contents), bc(1) behaves as if
the **-s** option was given.
**BC_ENV_ARGS**
: This is another way to give command-line arguments to bc(1). They should be
in the same format as all other command-line arguments. These are always
processed first, so any files given in **BC_ENV_ARGS** 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 bc(1) runs.
The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
**"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'bc' file.bc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **BC_ENV_ARGS** 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.
**BC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
lines to that length, including the backslash (**\\**). The default line
length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**BC_BANNER**
: If this environment variable exists and contains an integer, then a non-zero
value activates the copyright banner when bc(1) is in interactive mode,
while zero deactivates it.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) does not print
the banner when not in interactive mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_SIGINT_RESET**
: If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) exits on
**SIGINT** when not in interactive mode.
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1) reset
on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
environment variable exists and is *not* an integer, then bc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use TTY
mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a prompt,
and zero or a non-integer makes bc(1) not use a prompt. If this environment
variable does not exist and **BC_TTY_MODE** does, then the value of the
**BC_TTY_MODE** environment variable is used.
This environment variable and the **BC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
bc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, taking the square root of a negative
number, attempting to convert a negative number to a hardware integer,
overflow when converting a number to a hardware integer, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**) operator and the corresponding assignment operator.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, using a token where it is invalid,
giving an invalid expression, giving an invalid print statement, giving an
invalid function definition, attempting to assign to an expression that is
not a named expression (see the *Named Expressions* subsection of the
**SYNTAX** section), giving an invalid **auto** list, having a duplicate
**auto**/function parameter, failing to find the end of a code block,
attempting to return a value from a **void** function, attempting to use a
variable as a reference, and using any extensions when the option **-s** or
any equivalents were given.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors, passing the
wrong number of arguments to functions, attempting to call an undefined
function, and attempting to use a **void** function call as a value in an
expression.
**4**
: A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, failing to open
files, attempting to use files that do not have only ASCII characters (bc(1)
only accepts ASCII characters), attempting to open a directory as a file,
and giving invalid command-line options.
The exit status **4** is special; when a fatal error occurs, bc(1) always exits
and returns **4**, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interactive mode
(see the **INTERACTIVE MODE** section), since bc(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
**-i** flag or **-\-interactive** option.
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **BC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **BC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
mode on.
If the environment variable **BC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
**stdout**, and **stderr** are connected to a TTY and the **BC_TTY_MODE**
environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
information.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **BC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, bc(1) will
exit.
However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
default is an integer and non-zero, then bc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If bc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If bc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
can seem as though bc(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 bc(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.
**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is **SIGHUP**; in that
case, and only when bc(1) is in TTY mode (see the **TTY MODE** section), a
**SIGHUP** will cause bc(1) to clean up and exit.
# COMMAND LINE HISTORY
bc(1) supports interactive command-line editing.
If bc(1) can be in TTY mode (see the **TTY MODE** section), history can be
enabled. This means that command-line history can only be enabled when
**stdin**, **stdout**, and **stderr** are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment variable
**BC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
If history is enabled, previous lines can be recalled and edited with the arrow
keys.
**Note**: tabs are converted to 8 spaces.
# SEE ALSO
dc(1)
# STANDARDS
bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
specification. The flags **-efghiqsvVw**, all long options, and the extensions
noted above are extensions to that specification.
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
diff --git a/manuals/bc/H.1 b/manuals/bc/H.1
index 2fab932ce05c..5f290f12ae32 100644
--- a/manuals/bc/H.1
+++ b/manuals/bc/H.1
@@ -1,2670 +1,2755 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH NAME
.PP
bc - arbitrary-precision decimal arithmetic language and calculator
.SH SYNOPSIS
.PP
\f[B]bc\f[R] [\f[B]-ghilPqRsvVw\f[R]] [\f[B]--global-stacks\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]]
[\f[B]--no-prompt\f[R]] [\f[B]--no-read-prompt\f[R]] [\f[B]--quiet\f[R]]
[\f[B]--standard\f[R]] [\f[B]--warn\f[R]] [\f[B]--version\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX.
(The current standard is
here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).)
The language provides unlimited precision decimal arithmetic and is
somewhat C-like, but there are differences.
Such differences will be noted in this document.
.PP
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from \f[B]stdin\f[R].
.PP
This bc(1) is a drop-in replacement for \f[I]any\f[R] bc(1), including
(and especially) the GNU bc(1).
It also has many extensions and extra features beyond other
implementations.
.PP
\f[B]Note\f[R]: If running this bc(1) on \f[I]any\f[R] script meant for
another bc(1) gives a parse error, it is probably because a word this
bc(1) reserves as a keyword is used as the name of a function, variable,
or array.
To fix that, use the command-line option \f[B]-r\f[R] \f[I]keyword\f[R],
where \f[I]keyword\f[R] is the keyword that is used as a name in the
script.
For more information, see the \f[B]OPTIONS\f[R] section.
.PP
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported.
See the \f[B]BUGS\f[R] section.
.SH OPTIONS
.PP
The following are the options that bc(1) accepts.
.TP
\f[B]-g\f[R], \f[B]--global-stacks\f[R]
Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and
\f[B]seed\f[R] into stacks.
.RS
.PP
This has the effect that a copy of the current value of all four are
pushed onto a stack for every function call, as well as popped when
every function returns.
This means that functions can assign to any and all of those globals
without worrying that the change will affect other functions.
Thus, a hypothetical function named \f[B]output(x,b)\f[R] that simply
printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this:
.IP
.nf
\f[C]
define void output(x, b) {
obase=b
x
}
\f[R]
.fi
.PP
instead of like this:
.IP
.nf
\f[C]
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
\f[R]
.fi
.PP
This makes writing functions much easier.
.PP
(\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the
extended math library.
See the \f[B]LIBRARY\f[R] section.)
.PP
However, since using this flag means that functions cannot set
\f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R]
globally, functions that are made to do so cannot work anymore.
There are two possible use cases for that, and each has a solution.
.PP
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases.
Examples:
.IP
.nf
\f[C]
alias d2o=\[dq]bc -e ibase=A -e obase=8\[dq]
alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq]
\f[R]
.fi
.PP
Second, if the purpose of a function is to set \f[B]ibase\f[R],
\f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] globally for any
other purpose, it could be split into one to four functions (based on
how many globals it sets) and each of those functions could return the
desired value for a global.
.PP
For functions that set \f[B]seed\f[R], the value assigned to
\f[B]seed\f[R] is not propagated to parent functions.
This means that the sequence of pseudo-random numbers that they see will
not be the same sequence of pseudo-random numbers that any parent sees.
This is only the case once \f[B]seed\f[R] has been set.
.PP
If a function desires to not affect the sequence of pseudo-random
numbers of its parents, but wants to use the same \f[B]seed\f[R], it can
use the following line:
.IP
.nf
\f[C]
seed = seed
\f[R]
.fi
.PP
If the behavior of this option is desired for every run of bc(1), then
users could make sure to define \f[B]BC_ENV_ARGS\f[R] and include this
option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more
details).
.PP
If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option
is ignored.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-l\f[R], \f[B]--mathlib\f[R]
Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R]
and loads the included math library and the extended math library before
running any code, including any expressions or files specified on the
command line.
.RS
.PP
To learn what is in the libraries, see the \f[B]LIBRARY\f[R] section.
.RE
.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.RS
.PP
These options override the \f[B]BC_PROMPT\f[R] and \f[B]BC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of bc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]read()\f[R] built-in function is called.
.PP
These options \f[I]do\f[R] override the \f[B]BC_PROMPT\f[R] and
\f[B]BC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-r\f[R] \f[I]keyword\f[R], \f[B]--redefine\f[R]=\f[I]keyword\f[R]
Redefines \f[I]keyword\f[R] in order to allow it to be used as a
function, variable, or array name.
This is useful when this bc(1) gives parse errors when parsing scripts
meant for other bc(1) implementations.
.RS
.PP
The keywords this bc(1) allows to be redefined are:
.IP \[bu] 2
\f[B]abs\f[R]
.IP \[bu] 2
\f[B]asciify\f[R]
.IP \[bu] 2
\f[B]continue\f[R]
.IP \[bu] 2
\f[B]divmod\f[R]
.IP \[bu] 2
\f[B]else\f[R]
.IP \[bu] 2
\f[B]halt\f[R]
.IP \[bu] 2
\f[B]irand\f[R]
.IP \[bu] 2
\f[B]last\f[R]
.IP \[bu] 2
\f[B]limits\f[R]
.IP \[bu] 2
\f[B]maxibase\f[R]
.IP \[bu] 2
\f[B]maxobase\f[R]
.IP \[bu] 2
\f[B]maxrand\f[R]
.IP \[bu] 2
\f[B]maxscale\f[R]
.IP \[bu] 2
\f[B]modexp\f[R]
.IP \[bu] 2
\f[B]print\f[R]
.IP \[bu] 2
\f[B]rand\f[R]
.IP \[bu] 2
\f[B]read\f[R]
.IP \[bu] 2
\f[B]seed\f[R]
.IP \[bu] 2
\f[B]stream\f[R]
.PP
If any of those keywords are used as a function, variable, or array name
in a script, use this option with the keyword as the argument.
If multiple are used, use this option for all of them; it can be used
multiple times.
.PP
Keywords are \f[I]not\f[R] redefined when parsing the builtin math
library (see the \f[B]LIBRARY\f[R] section).
.PP
It is a fatal error to redefine keywords mandated by the POSIX standard.
It is a fatal error to attempt to redefine words that this bc(1) does
not reserve as keywords.
.RE
.TP
\f[B]-q\f[R], \f[B]--quiet\f[R]
This option is for compatibility with the GNU
bc(1) (https://www.gnu.org/software/bc/); it is a no-op.
Without this option, GNU bc(1) prints a copyright header.
This bc(1) only prints the copyright header if one or more of the
\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-s\f[R], \f[B]--standard\f[R]
Process exactly the language defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
and error if any extensions are used.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-w\f[R], \f[B]--warn\f[R]
Like \f[B]-s\f[R] and \f[B]--standard\f[R], except that warnings (and
not errors) are printed for non-standard extensions and execution
continues normally.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]BC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files or expressions are given by the \f[B]-f\f[R],
\f[B]--file\f[R], \f[B]-e\f[R], or \f[B]--expression\f[R] options, then
bc(1) read from \f[B]stdin\f[R].
.PP
However, there are a few caveats to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if the parse cannot complete.
That means that starting a string without ending it or starting a
function, \f[B]if\f[R] statement, or loop without ending it will also
cause bc(1) to not execute.
.PP
Second, after an \f[B]if\f[R] statement, bc(1) doesn\[cq]t know if an
\f[B]else\f[R] statement will follow, so it will not execute until it
knows there will not be an \f[B]else\f[R] statement.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]bc >&-\f[R], it will quit with an error.
This is done so that bc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]bc 2>&-\f[R], it will quit with an error.
This is done so that bc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
which is a much more thorough resource for the language this bc(1)
accepts.
This section is meant to be a summary and a listing of all the
extensions to the standard.
.PP
In the sections below, \f[B]E\f[R] means expression, \f[B]S\f[R] means
statement, and \f[B]I\f[R] means identifier.
.PP
Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be
followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase
letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores
(\f[B]_\f[R]).
The regex is \f[B][a-z][a-z0-9_]*\f[R].
Identifiers with more than one character (letter) are a
\f[B]non-portable extension\f[R].
.PP
\f[B]ibase\f[R] is a global variable determining how to interpret
constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R]
(\f[B]--warn\f[R]) flags were not given on the command line, the max
allowable value for \f[B]ibase\f[R] is \f[B]36\f[R].
Otherwise, it is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in bc(1)
programs with the \f[B]maxibase()\f[R] built-in function.
.PP
\f[B]obase\f[R] is a global variable determining how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and
can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in
function.
The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R].
If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific
notation, and if \f[B]obase\f[R] is \f[B]1\f[R], values are output in
engineering notation.
Otherwise, values are output in the specified base.
.PP
Outputting in scientific and engineering notations are \f[B]non-portable
extensions\f[R].
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a global variable that sets the precision of any operations, with
exceptions.
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R]
and can be queried in bc(1) programs with the \f[B]maxscale()\f[R]
built-in function.
.PP
bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables.
All \f[I]local\f[R] variables are local to the function; they are
parameters or are introduced in the \f[B]auto\f[R] list of a function
(see the \f[B]FUNCTIONS\f[R] section).
If a variable is accessed which is not a parameter or in the
\f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R].
If a parent function has a \f[I]local\f[R] variable version of a
variable that a child function considers \f[I]global\f[R], the value of
that \f[I]global\f[R] variable in the child function is the value of the
variable in the parent function, not the value of the actual
\f[I]global\f[R] variable.
.PP
All of the above applies to arrays as well.
.PP
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence
operator is an assignment operator \f[I]and\f[R] the expression is
notsurrounded by parentheses.
.PP
The value that is printed is also assigned to the special variable
\f[B]last\f[R].
A single dot (\f[B].\f[R]) may also be used as a synonym for
\f[B]last\f[R].
These are \f[B]non-portable extensions\f[R].
.PP
Either semicolons or newlines may separate statements.
.SS Comments
.PP
There are two kinds of comments:
.IP "1." 3
Block comments are enclosed in \f[B]/*\f[R] and \f[B]*/\f[R].
.IP "2." 3
Line comments go from \f[B]#\f[R] until, and not including, the next
newline.
This is a \f[B]non-portable extension\f[R].
.SS Named Expressions
.PP
The following are named expressions in bc(1):
.IP "1." 3
Variables: \f[B]I\f[R]
.IP "2." 3
Array Elements: \f[B]I[E]\f[R]
.IP "3." 3
\f[B]ibase\f[R]
.IP "4." 3
\f[B]obase\f[R]
.IP "5." 3
\f[B]scale\f[R]
.IP "6." 3
\f[B]seed\f[R]
.IP "7." 3
\f[B]last\f[R] or a single dot (\f[B].\f[R])
.PP
Numbers 6 and 7 are \f[B]non-portable extensions\f[R].
.PP
The meaning of \f[B]seed\f[R] is dependent on the current pseudo-random
number generator but is guaranteed to not change except for new major
versions.
.PP
The \f[I]scale\f[R] and sign of the value may be significant.
.PP
If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R]
and used again, the pseudo-random number generator is guaranteed to
produce the same sequence of pseudo-random numbers as it did when the
\f[B]seed\f[R] value was previously used.
.PP
The exact value assigned to \f[B]seed\f[R] is not guaranteed to be
returned if \f[B]seed\f[R] is queried again immediately.
However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both
values, when assigned to \f[B]seed\f[R], are guaranteed to produce the
same sequence of pseudo-random numbers.
This means that certain values assigned to \f[B]seed\f[R] will
\f[I]not\f[R] produce unique sequences of pseudo-random numbers.
The value of \f[B]seed\f[R] will change after any use of the
\f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the
\f[I]Operands\f[R] subsection below), except if the parameter passed to
\f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative.
.PP
There is no limit to the length (number of significant decimal digits)
or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R].
.PP
Variables and arrays do not interfere; users can have arrays named the
same as variables.
This also applies to functions (see the \f[B]FUNCTIONS\f[R] section), so
a user can have a variable, array, and function that all have the same
name, and they will not shadow each other, whether inside of functions
or not.
.PP
Named expressions are required as the operand of
\f[B]increment\f[R]/\f[B]decrement\f[R] operators and as the left side
of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R]
subsection).
.SS Operands
.PP
The following are valid operands in bc(1):
.IP " 1." 4
Numbers (see the \f[I]Numbers\f[R] subsection below).
.IP " 2." 4
Array indices (\f[B]I[E]\f[R]).
.IP " 3." 4
\f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence).
.IP " 4." 4
\f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R].
\f[B]E\f[R] must be non-negative.
.IP " 5." 4
\f[B]length(E)\f[R]: The number of significant decimal digits in
\f[B]E\f[R].
Returns \f[B]1\f[R] for \f[B]0\f[R] with no decimal places.
If given a string, the length of the string is returned.
Passing a string to \f[B]length(E)\f[R] is a \f[B]non-portable
extension\f[R].
.IP " 6." 4
\f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 7." 4
\f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R].
.IP " 8." 4
\f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 9." 4
\f[B]modexp(E, E, E)\f[R]: Modular exponentiation, where the first
expression is the base, the second is the exponent, and the third is the
modulus.
All three values must be integers.
The second argument must be non-negative.
The third argument must be non-zero.
This is a \f[B]non-portable extension\f[R].
.IP "10." 4
\f[B]divmod(E, E, I[])\f[R]: Division and modulus in one operation.
This is for optimization.
The first expression is the dividend, and the second is the divisor,
which must be non-zero.
The return value is the quotient, and the modulus is stored in index
\f[B]0\f[R] of the provided array (the last argument).
This is a \f[B]non-portable extension\f[R].
.IP "11." 4
\f[B]asciify(E)\f[R]: If \f[B]E\f[R] is a string, returns a string that
is the first letter of its argument.
If it is a number, calculates the number mod \f[B]256\f[R] and returns
that number as a one-character string.
This is a \f[B]non-portable extension\f[R].
.IP "12." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.IP "13." 4
\f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an
expression.
The result of that expression is the result of the \f[B]read()\f[R]
operand.
This is a \f[B]non-portable extension\f[R].
.IP "14." 4
\f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "15." 4
\f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "16." 4
\f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "17." 4
+\f[B]line_length()\f[R]: The line length set with
+\f[B]BC_LINE_LENGTH\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
+section).
+This is a \f[B]non-portable extension\f[R].
+.IP "18." 4
+\f[B]global_stacks()\f[R]: \f[B]0\f[R] if global stacks are not enabled
+with the \f[B]-g\f[R] or \f[B]--global-stacks\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "19." 4
+\f[B]leading_zero()\f[R]: \f[B]0\f[R] if leading zeroes are not enabled
+with the \f[B]-z\f[R] or \f[B]\[en]leading-zeroes\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "20." 4
\f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R]
(inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive).
Using this operand will change the value of \f[B]seed\f[R].
This is a \f[B]non-portable extension\f[R].
-.IP "18." 4
+.IP "21." 4
\f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R]
(inclusive) and the value of \f[B]E\f[R] (exclusive).
If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s
\f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains
unchanged.
If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is
honored by generating several pseudo-random integers, multiplying them
by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], and adding them
together.
Thus, the size of integer that can be generated with this operand is
unbounded.
Using this operand will change the value of \f[B]seed\f[R], unless the
value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R].
In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is
\f[I]not\f[R] changed.
This is a \f[B]non-portable extension\f[R].
-.IP "19." 4
+.IP "22." 4
\f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R].
This is a \f[B]non-portable extension\f[R].
.PP
The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are
guaranteed to be as unbiased as possible, subject to the limitations of
the pseudo-random number generator.
.PP
\f[B]Note\f[R]: The values returned by the pseudo-random number
generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to
\f[I]NOT\f[R] be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they \f[I]are\f[R] guaranteed to be reproducible with identical
\f[B]seed\f[R] values.
This means that the pseudo-random values from bc(1) should only be used
where a reproducible stream of pseudo-random numbers is
\f[I]ESSENTIAL\f[R].
In any other case, use a non-seeded pseudo-random number generator.
.SS Numbers
.PP
Numbers are strings made up of digits, uppercase letters, and at most
\f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R].
.PP
In addition, bc(1) accepts numbers in scientific notation.
These have the form \f[B]e\f[R].
The exponent (the portion after the \f[B]e\f[R]) must be an integer.
An example is \f[B]1.89237e9\f[R], which is equal to
\f[B]1892370000\f[R].
Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to
\f[B]0.0042890\f[R].
.PP
Using scientific notation is an error or warning if the \f[B]-s\f[R] or
\f[B]-w\f[R], respectively, command-line options (or equivalents) are
given.
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if bc(1) is given the number string
\f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.PP
Accepting input as scientific notation is a \f[B]non-portable
extension\f[R].
.SS Operators
.PP
The following arithmetic and logical operators can be used.
They are listed in order of decreasing precedence.
Operators in the same group have the same precedence.
.TP
\f[B]++\f[R] \f[B]--\f[R]
Type: Prefix and Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]increment\f[R], \f[B]decrement\f[R]
.RE
.TP
\f[B]-\f[R] \f[B]!\f[R]
Type: Prefix
.RS
.PP
Associativity: None
.PP
Description: \f[B]negation\f[R], \f[B]boolean not\f[R]
.RE
.TP
\f[B]$\f[R]
Type: Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]truncation\f[R]
.RE
.TP
\f[B]\[at]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]set precision\f[R]
.RE
.TP
\f[B]\[ha]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]power\f[R]
.RE
.TP
\f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R]
.RE
.TP
\f[B]+\f[R] \f[B]-\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]add\f[R], \f[B]subtract\f[R]
.RE
.TP
\f[B]<<\f[R] \f[B]>>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]shift left\f[R], \f[B]shift right\f[R]
.RE
.TP
\f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]assignment\f[R]
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]relational\f[R]
.RE
.TP
\f[B]&&\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean and\f[R]
.RE
.TP
\f[B]||\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean or\f[R]
.RE
.PP
The operators will be described in more detail below.
.TP
\f[B]++\f[R] \f[B]--\f[R]
The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R]
operators behave exactly like they would in C.
They require a named expression (see the \f[I]Named Expressions\f[R]
subsection) as an operand.
.RS
.PP
The prefix versions of these operators are more efficient; use them
where possible.
.RE
.TP
\f[B]-\f[R]
The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts
to negate any expression with the value \f[B]0\f[R].
Otherwise, a copy of the expression with its sign flipped is returned.
.TP
\f[B]!\f[R]
The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression
is \f[B]0\f[R], or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]$\f[R]
The \f[B]truncation\f[R] operator returns a copy of the given expression
with all of its \f[I]scale\f[R] removed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[at]\f[R]
The \f[B]set precision\f[R] operator takes two expressions and returns a
copy of the first with its \f[I]scale\f[R] equal to the value of the
second expression.
That could either mean that the number is returned without change (if
the \f[I]scale\f[R] of the first expression matches the value of the
second expression), extended (if it is less), or truncated (if it is
more).
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator,
as it would be in C) takes two expressions and raises the first to the
power of the value of the second.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]), and if it
is negative, the first value must be non-zero.
.RE
.TP
\f[B]*\f[R]
The \f[B]multiply\f[R] operator takes two expressions, multiplies them,
and returns the product.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The \f[B]divide\f[R] operator takes two expressions, divides them, and
returns the quotient.
The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]%\f[R]
The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R] and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]+\f[R]
The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the
max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]-\f[R]
The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to
the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]<<\f[R]
The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its
decimal point moved \f[B]b\f[R] places to the right.
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]>>\f[R]
The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its
decimal point moved \f[B]b\f[R] places to the left.
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R]
The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and
\f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named
Expressions\f[R] subsection).
.RS
.PP
For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to
\f[B]a\f[R].
For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to
the corresponding arithmetic operator and the result is assigned to
\f[B]a\f[R].
.PP
The \f[B]assignment\f[R] operators that correspond to operators that are
extensions are themselves \f[B]non-portable extensions\f[R].
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and if the relation holds, according to C language
semantics, the result is \f[B]1\f[R].
Otherwise, it is \f[B]0\f[R].
.RS
.PP
Note that unlike in C, these operators have a lower precedence than the
\f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is
interpreted as \f[B](a=b)>c\f[R].
.PP
Also, unlike the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
requires, these operators can appear anywhere any other expressions can
be used.
This allowance is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]&&\f[R]
The \f[B]boolean and\f[R] operator takes two expressions and returns
\f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]||\f[R]
The \f[B]boolean or\f[R] operator takes two expressions and returns
\f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R]
otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Statements
.PP
The following items are statements:
.IP " 1." 4
\f[B]E\f[R]
.IP " 2." 4
\f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R]
\f[B]}\f[R]
.IP " 3." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 4." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
\f[B]else\f[R] \f[B]S\f[R]
.IP " 5." 4
\f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 6." 4
\f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R]
\f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 7." 4
An empty statement
.IP " 8." 4
\f[B]break\f[R]
.IP " 9." 4
\f[B]continue\f[R]
.IP "10." 4
\f[B]quit\f[R]
.IP "11." 4
\f[B]halt\f[R]
.IP "12." 4
\f[B]limits\f[R]
.IP "13." 4
A string of characters, enclosed in double quotes
.IP "14." 4
\f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "15." 4
\f[B]stream\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "16." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.PP
Numbers 4, 9, 11, 12, 14, 15, and 16 are \f[B]non-portable
extensions\f[R].
.PP
Also, as a \f[B]non-portable extension\f[R], any or all of the
expressions in the header of a for loop may be omitted.
If the condition (second expression) is omitted, it is assumed to be a
constant \f[B]1\f[R].
.PP
The \f[B]break\f[R] statement causes a loop to stop iterating and resume
execution immediately following a loop.
This is only allowed in loops.
.PP
The \f[B]continue\f[R] statement causes a loop iteration to stop early
and returns to the start of the loop, including testing the loop
condition.
This is only allowed in loops.
.PP
The \f[B]if\f[R] \f[B]else\f[R] statement does the same thing as in C.
.PP
The \f[B]quit\f[R] statement causes bc(1) to quit, even if it is on a
branch that will not be executed (it is a compile-time command).
.PP
The \f[B]halt\f[R] statement causes bc(1) to quit, if it is executed.
(Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement
that is not executed, bc(1) does not quit.)
.PP
The \f[B]limits\f[R] statement prints the limits that this bc(1) is
subject to.
This is like the \f[B]quit\f[R] statement in that it is a compile-time
command.
.PP
An expression by itself is evaluated and printed, followed by a newline.
.PP
Both scientific notation and engineering notation are available for
printing the results of expressions.
Scientific notation is activated by assigning \f[B]0\f[R] to
\f[B]obase\f[R], and engineering notation is activated by assigning
\f[B]1\f[R] to \f[B]obase\f[R].
To deactivate them, just assign a different value to \f[B]obase\f[R].
.PP
Scientific notation and engineering notation are disabled if bc(1) is
run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options
(or equivalents).
.PP
Printing numbers in scientific notation and/or engineering notation is a
\f[B]non-portable extension\f[R].
.SS Strings
.PP
If strings appear as a statement by themselves, they are printed without
a trailing newline.
.PP
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements.
They can also be passed to functions in variable parameters.
.PP
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
.PP
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section).
.PP
Assigning strings to variables and array elements and passing them to
functions are \f[B]non-portable extensions\f[R].
.SS Print Statement
.PP
The \[lq]expressions\[rq] in a \f[B]print\f[R] statement may also be
strings.
If they are, there are backslash escape sequences that are interpreted
specially.
What those sequences are, and what they cause to be printed, are shown
below:
.PP
\f[B]\[rs]a\f[R]: \f[B]\[rs]a\f[R]
.PP
\f[B]\[rs]b\f[R]: \f[B]\[rs]b\f[R]
.PP
\f[B]\[rs]\[rs]\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]e\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]f\f[R]: \f[B]\[rs]f\f[R]
.PP
\f[B]\[rs]n\f[R]: \f[B]\[rs]n\f[R]
.PP
\f[B]\[rs]q\f[R]: \f[B]\[lq]\f[R]
.PP
\f[B]\[rs]r\f[R]: \f[B]\[rs]r\f[R]
.PP
\f[B]\[rs]t\f[R]: \f[B]\[rs]t\f[R]
.PP
Any other character following a backslash causes the backslash and
character to be printed as-is.
.PP
Any non-string expression in a print statement shall be assigned to
\f[B]last\f[R], like any other expression that is printed.
.SS Stream Statement
.PP
The \[lq]expressions in a \f[B]stream\f[R] statement may also be
strings.
.PP
If a \f[B]stream\f[R] statement is given a string, it prints the string
as though the string had appeared as its own statement.
In other words, the \f[B]stream\f[R] statement prints strings normally,
without a newline.
.PP
If a \f[B]stream\f[R] statement is given a number, a copy of it is
truncated and its absolute value is calculated.
The result is then printed as though \f[B]obase\f[R] is \f[B]256\f[R]
and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
.SS Order of Evaluation
.PP
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations.
This means, for example, assuming that \f[B]i\f[R] is equal to
\f[B]0\f[R], in the expression
.IP
.nf
\f[C]
a[i++] = i++
\f[R]
.fi
.PP
the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and
\f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression.
.PP
This includes function arguments.
Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in
the expression
.IP
.nf
\f[C]
x(i++, i++)
\f[R]
.fi
.PP
the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the
second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to
\f[B]2\f[R] before the function starts executing.
.SH FUNCTIONS
.PP
Function definitions are as follows:
.IP
.nf
\f[C]
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
\f[R]
.fi
.PP
Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be
replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an
array, and any \f[B]I\f[R] in the parameter list may be replaced with
\f[B]*I[]\f[R] to make a parameter an array reference.
Callers of functions that take array references should not put an
asterisk in the call; they must be called with just \f[B]I[]\f[R] like
normal array parameters and will be automatically converted into
references.
.PP
As a \f[B]non-portable extension\f[R], the opening brace of a
\f[B]define\f[R] statement may appear on the next line.
.PP
As a \f[B]non-portable extension\f[R], the return statement may also be
in one of the following forms:
.IP "1." 3
\f[B]return\f[R]
.IP "2." 3
\f[B]return\f[R] \f[B](\f[R] \f[B])\f[R]
.IP "3." 3
\f[B]return\f[R] \f[B]E\f[R]
.PP
The first two, or not specifying a \f[B]return\f[R] statement, is
equivalent to \f[B]return (0)\f[R], unless the function is a
\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection
below).
.SS Void Functions
.PP
Functions can also be \f[B]void\f[R] functions, defined as follows:
.IP
.nf
\f[C]
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
\f[R]
.fi
.PP
They can only be used as standalone expressions, where such an
expression would be printed alone, except in a print statement.
.PP
Void functions can only use the first two \f[B]return\f[R] statements
listed above.
They can also omit the return statement entirely.
.PP
The word \[lq]void\[rq] is not treated as a keyword; it is still
possible to have variables, arrays, and functions named \f[B]void\f[R].
The word \[lq]void\[rq] is only treated specially right after the
\f[B]define\f[R] keyword.
.PP
This is a \f[B]non-portable extension\f[R].
.SS Array References
.PP
For any array in the parameter list, if the array is declared in the
form
.IP
.nf
\f[C]
*I[]
\f[R]
.fi
.PP
it is a \f[B]reference\f[R].
Any changes to the array in the function are reflected, when the
function returns, to the array that was passed in.
.PP
Other than this, all function arguments are passed by value.
.PP
This is a \f[B]non-portable extension\f[R].
.SH LIBRARY
.PP
All of the functions below, including the functions in the extended math
library (see the \f[I]Extended Library\f[R] subsection below), are
available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line
flags are given, except that the extended math library is not available
when the \f[B]-s\f[R] option, the \f[B]-w\f[R] option, or equivalents
are given.
.SS Standard Library
.PP
The
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
defines the following functions for the math library:
.TP
\f[B]s(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]c(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l(x)\f[R]
Returns the natural logarithm of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]e(x)\f[R]
Returns the mathematical constant \f[B]e\f[R] raised to the power of
\f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]j(x, n)\f[R]
Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.SS Extended Library
.PP
The extended library is \f[I]not\f[R] loaded when the
\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R]
options are given since they are not part of the library defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
.PP
The extended library is a \f[B]non-portable extension\f[R].
.TP
\f[B]p(x, y)\f[R]
Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R]
is not an integer, and returns the result to the current
\f[B]scale\f[R].
.RS
.PP
It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is
\f[B]0\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]r(x, p)\f[R]
Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to
the rounding mode round half away from
\f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero).
.TP
\f[B]ceil(x, p)\f[R]
Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to
the rounding mode round away from
\f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero).
.TP
\f[B]f(x)\f[R]
Returns the factorial of the truncated absolute value of \f[B]x\f[R].
.TP
\f[B]perm(n, k)\f[R]
Returns the permutation of the truncated absolute value of \f[B]n\f[R]
of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R].
If not, it returns \f[B]0\f[R].
.TP
\f[B]comb(n, k)\f[R]
Returns the combination of the truncated absolute value of \f[B]n\f[R]
of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R].
If not, it returns \f[B]0\f[R].
.TP
\f[B]l2(x)\f[R]
Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l10(x)\f[R]
Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]log(x, b)\f[R]
Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]cbrt(x)\f[R]
Returns the cube root of \f[B]x\f[R].
.TP
\f[B]root(x, n)\f[R]
Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns
the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R].
.RS
.PP
If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and
causes bc(1) to reset (see the \f[B]RESET\f[R] section).
It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even
and \f[B]x\f[R] is negative.
.RE
.TP
\f[B]gcd(a, b)\f[R]
Returns the greatest common divisor (factor) of the truncated absolute
value of \f[B]a\f[R] and the truncated absolute value of \f[B]b\f[R].
.TP
\f[B]lcm(a, b)\f[R]
Returns the least common multiple of the truncated absolute value of
\f[B]a\f[R] and the truncated absolute value of \f[B]b\f[R].
.TP
\f[B]pi(p)\f[R]
Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]t(x)\f[R]
Returns the tangent of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a2(y, x)\f[R]
Returns the arctangent of \f[B]y/x\f[R], in radians.
If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises
an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns
\f[B]a(y/x)\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than
or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than
\f[B]0\f[R], it returns \f[B]pi/2\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]-pi/2\f[R].
.RS
.PP
This function is the same as the \f[B]atan2()\f[R] function in many
programming languages.
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]sin(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is an alias of \f[B]s(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]cos(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is an alias of \f[B]c(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]tan(x)\f[R]
Returns the tangent of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an
error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
.PP
This is an alias of \f[B]t(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]atan(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is an alias of \f[B]a(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]atan2(y, x)\f[R]
Returns the arctangent of \f[B]y/x\f[R], in radians.
If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises
an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns
\f[B]a(y/x)\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than
or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than
\f[B]0\f[R], it returns \f[B]pi/2\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]-pi/2\f[R].
.RS
.PP
This function is the same as the \f[B]atan2()\f[R] function in many
programming languages.
.PP
This is an alias of \f[B]a2(y, x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]r2d(x)\f[R]
Converts \f[B]x\f[R] from radians to degrees and returns the result.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]d2r(x)\f[R]
Converts \f[B]x\f[R] from degrees to radians and returns the result.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]frand(p)\f[R]
Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and
\f[B]1\f[R] (exclusive) with the number of decimal digits after the
decimal point equal to the truncated absolute value of \f[B]p\f[R].
If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will
change the value of \f[B]seed\f[R].
If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and
\f[B]seed\f[R] is \f[I]not\f[R] changed.
.TP
\f[B]ifrand(i, p)\f[R]
Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive)
and the truncated absolute value of \f[B]i\f[R] (exclusive) with the
number of decimal digits after the decimal point equal to the truncated
absolute value of \f[B]p\f[R].
If the absolute value of \f[B]i\f[R] is greater than or equal to
\f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this
function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R]
is returned and \f[B]seed\f[R] is not changed.
.TP
\f[B]srand(x)\f[R]
Returns \f[B]x\f[R] with its sign flipped with probability
\f[B]0.5\f[R].
In other words, it randomizes the sign of \f[B]x\f[R].
.TP
\f[B]brand()\f[R]
Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]).
.TP
\f[B]band(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]and\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bor(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]or\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bxor(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]xor\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bshl(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of \f[B]a\f[R] bit-shifted left by
\f[B]b\f[R] places.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bshr(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the truncated result of \f[B]a\f[R]
bit-shifted right by \f[B]b\f[R] places.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnotn(x, n)\f[R]
Takes the truncated absolute value of \f[B]x\f[R] and does a bitwise not
as though it has the same number of bytes as the truncated absolute
value of \f[B]n\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot8(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]8\f[R] binary digits (1 unsigned byte).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot16(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]16\f[R] binary digits (2 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot32(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]32\f[R] binary digits (4 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot64(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]64\f[R] binary digits (8 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has the minimum number of power of two unsigned bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brevn(x, n)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has the same number of 8-bit bytes as the truncated absolute
value of \f[B]n\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev8(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 8 binary digits (1 unsigned byte).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev16(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 16 binary digits (2 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev32(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 32 binary digits (4 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev64(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 64 binary digits (8 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has the minimum number of power of two unsigned bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]broln(x, p, n)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the same number of unsigned 8-bit bytes as
the truncated absolute value of \f[B]n\f[R], by the number of places
equal to the truncated absolute value of \f[B]p\f[R] modded by the
\f[B]2\f[R] to the power of the number of binary digits in \f[B]n\f[R]
8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol8(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]8\f[R] binary digits (\f[B]1\f[R]
unsigned byte), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol16(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]16\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol32(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol64(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the minimum number of power of two
unsigned 8-bit bytes, by the number of places equal to the truncated
absolute value of \f[B]p\f[R] modded by 2 to the power of the number of
binary digits in the minimum number of 8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brorn(x, p, n)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the same number of unsigned 8-bit bytes as
the truncated absolute value of \f[B]n\f[R], by the number of places
equal to the truncated absolute value of \f[B]p\f[R] modded by the
\f[B]2\f[R] to the power of the number of binary digits in \f[B]n\f[R]
8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror8(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]8\f[R] binary digits (\f[B]1\f[R]
unsigned byte), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror16(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]16\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror32(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror64(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the minimum number of power of two
unsigned 8-bit bytes, by the number of places equal to the truncated
absolute value of \f[B]p\f[R] modded by 2 to the power of the number of
binary digits in the minimum number of 8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmodn(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of the multiplication of the truncated absolute
value of \f[B]n\f[R] and \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod8(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod16(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod32(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod64(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bunrev(t)\f[R]
Assumes \f[B]t\f[R] is a bitwise-reversed number with an extra set bit
one place more significant than the real most significant bit (which was
the least significant bit in the original number).
This number is reversed and returned without the extra set bit.
.RS
.PP
This function is used to implement other bitwise functions; it is not
meant to be used by users, but it can be.
.RE
.TP
+\f[B]plz(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed with a leading zero, regardless
+of the use of the \f[B]-z\f[R] option (see the \f[B]OPTIONS\f[R]
+section) and without a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, without a trailing newline.
+.RE
+.TP
+\f[B]plznl(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed with a leading zero, regardless
+of the use of the \f[B]-z\f[R] option (see the \f[B]OPTIONS\f[R]
+section) and with a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, with a trailing newline.
+.RE
+.TP
+\f[B]pnlz(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed without a leading zero,
+regardless of the use of the \f[B]-z\f[R] option (see the
+\f[B]OPTIONS\f[R] section) and without a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, without a trailing newline.
+.RE
+.TP
+\f[B]pnlznl(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed without a leading zero,
+regardless of the use of the \f[B]-z\f[R] option (see the
+\f[B]OPTIONS\f[R] section) and with a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, with a trailing newline.
+.RE
+.TP
\f[B]ubytes(x)\f[R]
Returns the numbers of unsigned integer bytes required to hold the
truncated absolute value of \f[B]x\f[R].
.TP
\f[B]sbytes(x)\f[R]
Returns the numbers of signed, two\[cq]s-complement integer bytes
required to hold the truncated value of \f[B]x\f[R].
.TP
\f[B]s2u(x)\f[R]
Returns \f[B]x\f[R] if it is non-negative.
If it \f[I]is\f[R] negative, then it calculates what \f[B]x\f[R] would
be as a 2\[cq]s-complement signed integer and returns the non-negative
integer that would have the same representation in binary.
.TP
\f[B]s2un(x,n)\f[R]
Returns \f[B]x\f[R] if it is non-negative.
If it \f[I]is\f[R] negative, then it calculates what \f[B]x\f[R] would
be as a 2\[cq]s-complement signed integer with \f[B]n\f[R] bytes and
returns the non-negative integer that would have the same representation
in binary.
If \f[B]x\f[R] cannot fit into \f[B]n\f[R] 2\[cq]s-complement signed
bytes, it is truncated to fit.
.TP
\f[B]hex(x)\f[R]
Outputs the hexadecimal (base \f[B]16\f[R]) representation of
\f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]binary(x)\f[R]
Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output(x, b)\f[R]
Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in as few power of two bytes as possible.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or is negative, an error message is
printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R]
section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in as few power of two bytes as
possible.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, an error message is printed instead,
but bc(1) is not reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uintn(x, n)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]n\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]intn(x, n)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint8(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]1\f[R] byte.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int8(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an
error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint16(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]2\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int16(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint32(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]4\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int32(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint64(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]8\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int64(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]hex_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R]
bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]binary_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see
the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output_byte(x, i)\f[R]
Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R],
where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes
- 1\f[R] is the most significant byte.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.SS Transcendental Functions
.PP
All transcendental functions can return slightly inaccurate results (up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)).
This is unavoidable, and this
article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains
why it is impossible and unnecessary to calculate exact results for the
transcendental functions.
.PP
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (\f[B]scale\f[R]) set to at least 1 higher
than is necessary.
If exact results are \f[I]absolutely\f[R] required, users can double the
precision (\f[B]scale\f[R]) and then truncate.
.PP
The transcendental functions in the standard math library are:
.IP \[bu] 2
\f[B]s(x)\f[R]
.IP \[bu] 2
\f[B]c(x)\f[R]
.IP \[bu] 2
\f[B]a(x)\f[R]
.IP \[bu] 2
\f[B]l(x)\f[R]
.IP \[bu] 2
\f[B]e(x)\f[R]
.IP \[bu] 2
\f[B]j(x, n)\f[R]
.PP
The transcendental functions in the extended math library are:
.IP \[bu] 2
\f[B]l2(x)\f[R]
.IP \[bu] 2
\f[B]l10(x)\f[R]
.IP \[bu] 2
\f[B]log(x, b)\f[R]
.IP \[bu] 2
\f[B]pi(p)\f[R]
.IP \[bu] 2
\f[B]t(x)\f[R]
.IP \[bu] 2
\f[B]a2(y, x)\f[R]
.IP \[bu] 2
\f[B]sin(x)\f[R]
.IP \[bu] 2
\f[B]cos(x)\f[R]
.IP \[bu] 2
\f[B]tan(x)\f[R]
.IP \[bu] 2
\f[B]atan(x)\f[R]
.IP \[bu] 2
\f[B]atan2(y, x)\f[R]
.IP \[bu] 2
\f[B]r2d(x)\f[R]
.IP \[bu] 2
\f[B]d2r(x)\f[R]
.SH RESET
.PP
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets.
This means that several things happen.
.PP
First, any functions 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.
.PP
Thus, when bc(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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.PP
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This bc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R]
can be queried with the \f[B]limits\f[R] statement.
.PP
In addition, this bc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bc(1):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bc(1) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]rand()\f[R]
operand.
Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
The actual values can be queried with the \f[B]limits\f[R] statement.
.PP
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
.PP
bc(1) recognizes the following environment variables:
.TP
\f[B]POSIXLY_CORRECT\f[R]
If this variable exists (no matter the contents), bc(1) behaves as if
the \f[B]-s\f[R] option was given.
.TP
\f[B]BC_ENV_ARGS\f[R]
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line arguments.
These are always processed first, so any files given in
\f[B]BC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 bc(1) runs.
.RS
.PP
The code that parses \f[B]BC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`bc' file.bc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]BC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]BC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length,
including the backslash (\f[B]\[rs]\f[R]).
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]BC_BANNER\f[R]
If this environment variable exists and contains an integer, then a
non-zero value activates the copyright banner when bc(1) is in
interactive mode, while zero deactivates it.
.RS
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
does not print the banner when not in interactive mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_SIGINT_RESET\f[R]
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes bc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then bc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use
TTY mode, and zero makes bc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a
prompt, and zero or a non-integer makes bc(1) not use a prompt.
If this environment variable does not exist and \f[B]BC_TTY_MODE\f[R]
does, then the value of the \f[B]BC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]BC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
bc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], 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, overflow when calculating the size of a number, and attempting
to use a non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift
(\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their
corresponding assignment operators.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an invalid
print statement, giving an invalid function definition, attempting to
assign to an expression that is not a named expression (see the
\f[I]Named Expressions\f[R] subsection of the \f[B]SYNTAX\f[R] section),
giving an invalid \f[B]auto\f[R] list, having a duplicate
\f[B]auto\f[R]/function parameter, failing to find the end of a code
block, attempting to return a value from a \f[B]void\f[R] function,
attempting to use a variable as a reference, and using any extensions
when the option \f[B]-s\f[R] or any equivalents were given.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors, passing the wrong number of
arguments to functions, attempting to call an undefined function, and
attempting to use a \f[B]void\f[R] function call as a value in an
expression.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
Fatal errors include memory allocation errors, I/O errors, failing to
open files, attempting to use files that do not have only ASCII
characters (bc(1) only accepts ASCII characters), attempting to open a
directory as a file, and giving invalid command-line options.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, bc(1)
always exits and returns \f[B]4\f[R], no matter what mode bc(1) is in.
.PP
The other statuses will only be returned when bc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
bc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Per the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, bc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
bc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]BC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, bc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]BC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, bc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]BC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then bc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]BC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]BC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]BC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]BC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]BC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause bc(1) to do one of two things.
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, bc(1) will exit.
.PP
However, if bc(1) is in interactive mode, and the
\f[B]BC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then bc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If bc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If bc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] is sent to bc(1) as it is
executing a file, it can seem as though bc(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
bc(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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause bc(1) to clean up and
exit, and it uses the default handler for all other signals.
.SH LOCALES
.PP
This bc(1) ships with support for adding error messages for different
locales and thus, supports \f[B]LC_MESSAGES\f[R].
.SH SEE ALSO
.PP
dc(1)
.SH STANDARDS
.PP
bc(1) is compliant with the IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
The flags \f[B]-efghiqsvVw\f[R], all long options, and the extensions
noted above are extensions to that specification.
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
.PP
This bc(1) supports error messages for different locales, and thus, it
supports \f[B]LC_MESSAGES\f[R].
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bc/H.1.md b/manuals/bc/H.1.md
index 9a1cbbf5d518..99c88db93230 100644
--- a/manuals/bc/H.1.md
+++ b/manuals/bc/H.1.md
@@ -1,2259 +1,2321 @@
# NAME
bc - arbitrary-precision decimal arithmetic language and calculator
# SYNOPSIS
**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# DESCRIPTION
bc(1) is an interactive processor for a language first standardized in 1991 by
POSIX. (The current standard is [here][1].) The language provides unlimited
precision decimal arithmetic and is somewhat C-like, but there are differences.
Such differences will be noted in this document.
After parsing and handling options, this bc(1) reads any files given on the
command line and executes them before reading from **stdin**.
This bc(1) is a drop-in replacement for *any* bc(1), including (and
especially) the GNU bc(1). It also has many extensions and extra features beyond
other implementations.
**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
parse error, it is probably because a word this bc(1) reserves as a keyword is
used as the name of a function, variable, or array. To fix that, use the
command-line option **-r** *keyword*, where *keyword* is the keyword that is
used as a name in the script. For more information, see the **OPTIONS** section.
If parsing scripts meant for other bc(1) implementations still does not work,
that is a bug and should be reported. See the **BUGS** section.
# OPTIONS
The following are the options that bc(1) accepts.
**-g**, **-\-global-stacks**
: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks.
This has the effect that a copy of the current value of all four are pushed
onto a stack for every function call, as well as popped when every function
returns. This means that functions can assign to any and all of those
globals without worrying that the change will affect other functions.
Thus, a hypothetical function named **output(x,b)** that simply printed
**x** in base **b** could be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
(**Note**: the function **output(x,b)** exists in the extended math library.
See the **LIBRARY** section.)
However, since using this flag means that functions cannot set **ibase**,
**obase**, **scale**, or **seed** globally, functions that are made to do so
cannot work anymore. There are two possible use cases for that, and each has
a solution.
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set **ibase**, **obase**,
**scale**, or **seed** globally for any other purpose, it could be split
into one to four functions (based on how many globals it sets) and each of
those functions could return the desired value for a global.
For functions that set **seed**, the value assigned to **seed** is not
propagated to parent functions. This means that the sequence of
pseudo-random numbers that they see will not be the same sequence of
pseudo-random numbers that any parent sees. This is only the case once
**seed** has been set.
If a function desires to not affect the sequence of pseudo-random numbers
of its parents, but wants to use the same **seed**, it can use the following
line:
seed = seed
If the behavior of this option is desired for every run of bc(1), then users
could make sure to define **BC_ENV_ARGS** and include this option (see the
**ENVIRONMENT VARIABLES** section for more details).
If **-s**, **-w**, or any equivalents are used, this option is ignored.
This is a **non-portable extension**.
**-h**, **-\-help**
: Prints a usage message and quits.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-l**, **-\-mathlib**
: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
math library and the extended math library before running any code,
including any expressions or files specified on the command line.
To learn what is in the libraries, see the **LIBRARY** section.
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in bc(1). Most of those users
would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section).
These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of bc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **read()** built-in function is called.
These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-r** *keyword*, **-\-redefine**=*keyword*
: Redefines *keyword* in order to allow it to be used as a function, variable,
or array name. This is useful when this bc(1) gives parse errors when
parsing scripts meant for other bc(1) implementations.
The keywords this bc(1) allows to be redefined are:
* **abs**
* **asciify**
* **continue**
* **divmod**
* **else**
* **halt**
* **irand**
* **last**
* **limits**
* **maxibase**
* **maxobase**
* **maxrand**
* **maxscale**
* **modexp**
* **print**
* **rand**
* **read**
* **seed**
* **stream**
If any of those keywords are used as a function, variable, or array name in
a script, use this option with the keyword as the argument. If multiple are
used, use this option for all of them; it can be used multiple times.
Keywords are *not* redefined when parsing the builtin math library (see the
**LIBRARY** section).
It is a fatal error to redefine keywords mandated by the POSIX standard. It
is a fatal error to attempt to redefine words that this bc(1) does not
reserve as keywords.
**-q**, **-\-quiet**
: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
Without this option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the **-v**, **-V**, or
**-\-version** options are given.
This is a **non-portable extension**.
**-s**, **-\-standard**
: Process exactly the language defined by the [standard][1] and error if any
extensions are used.
This is a **non-portable extension**.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
This is a **non-portable extension**.
**-w**, **-\-warn**
: Like **-s** and **-\-standard**, except that warnings (and not errors) are
printed for non-standard extensions and execution continues normally.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
**-\-expression** options, then bc(1) read from **stdin**.
However, there are a few caveats to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
the parse cannot complete. That means that starting a string without ending it
or starting a function, **if** statement, or loop without ending it will also
cause bc(1) to not execute.
Second, after an **if** statement, bc(1) doesn't know if an **else** statement
will follow, so it will not execute until it knows there will not be an **else**
statement.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **bc >&-**, it will quit with an error. This
is done so that bc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This
is done so that bc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences. This
bc(1) follows the [POSIX standard][1], which is a much more thorough resource
for the language this bc(1) accepts. This section is meant to be a summary and a
listing of all the extensions to the standard.
In the sections below, **E** means expression, **S** means statement, and **I**
means identifier.
Identifiers (**I**) start with a lowercase letter and can be followed by any
number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
Identifiers with more than one character (letter) are a
**non-portable extension**.
**ibase** is a global variable determining how to interpret constant numbers. It
is the "input" base, or the number base used for interpreting input numbers.
**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
(**-\-warn**) flags were not given on the command line, the max allowable value
for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
**ibase** is **2**. The max allowable value for **ibase** can be queried in
bc(1) programs with the **maxibase()** built-in function.
**obase** is a global variable determining how to output results. It is the
"output" base, or the number base used for outputting numbers. **obase** is
initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
can be queried in bc(1) programs with the **maxobase()** built-in function. The
min allowable value for **obase** is **0**. If **obase** is **0**, values are
output in scientific notation, and if **obase** is **1**, values are output in
engineering notation. Otherwise, values are output in the specified base.
Outputting in scientific and engineering notations are **non-portable
extensions**.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a global variable that
sets the precision of any operations, with exceptions. **scale** is initially
**0**. **scale** cannot be negative. The max allowable value for **scale** is
**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
built-in function.
bc(1) has both *global* variables and *local* variables. All *local*
variables are local to the function; they are parameters or are introduced in
the **auto** list of a function (see the **FUNCTIONS** section). If a variable
is accessed which is not a parameter or in the **auto** list, it is assumed to
be *global*. If a parent function has a *local* variable version of a variable
that a child function considers *global*, the value of that *global* variable in
the child function is the value of the variable in the parent function, not the
value of the actual *global* variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence operator is an
assignment operator *and* the expression is notsurrounded by parentheses.
The value that is printed is also assigned to the special variable **last**. A
single dot (**.**) may also be used as a synonym for **last**. These are
**non-portable extensions**.
Either semicolons or newlines may separate statements.
## Comments
There are two kinds of comments:
1. Block comments are enclosed in **/\*** and **\*/**.
2. Line comments go from **#** until, and not including, the next newline. This
is a **non-portable extension**.
## Named Expressions
The following are named expressions in bc(1):
1. Variables: **I**
2. Array Elements: **I[E]**
3. **ibase**
4. **obase**
5. **scale**
6. **seed**
7. **last** or a single dot (**.**)
Numbers 6 and 7 are **non-portable extensions**.
The meaning of **seed** is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major versions.
The *scale* and sign of the value may be significant.
If a previously used **seed** value is assigned to **seed** and used again, the
pseudo-random number generator is guaranteed to produce the same sequence of
pseudo-random numbers as it did when the **seed** value was previously used.
The exact value assigned to **seed** is not guaranteed to be returned if
**seed** is queried again immediately. However, if **seed** *does* return a
different value, both values, when assigned to **seed**, are guaranteed to
produce the same sequence of pseudo-random numbers. This means that certain
values assigned to **seed** will *not* produce unique sequences of pseudo-random
numbers. The value of **seed** will change after any use of the **rand()** and
**irand(E)** operands (see the *Operands* subsection below), except if the
parameter passed to **irand(E)** is **0**, **1**, or negative.
There is no limit to the length (number of significant decimal digits) or
*scale* of the value that can be assigned to **seed**.
Variables and arrays do not interfere; users can have arrays named the same as
variables. This also applies to functions (see the **FUNCTIONS** section), so a
user can have a variable, array, and function that all have the same name, and
they will not shadow each other, whether inside of functions or not.
Named expressions are required as the operand of **increment**/**decrement**
operators and as the left side of **assignment** operators (see the *Operators*
subsection).
## Operands
The following are valid operands in bc(1):
1. Numbers (see the *Numbers* subsection below).
2. Array indices (**I[E]**).
3. **(E)**: The value of **E** (used to change precedence).
4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
5. **length(E)**: The number of significant decimal digits in **E**. Returns
**1** for **0** with no decimal places. If given a string, the length of the
string is returned. Passing a string to **length(E)** is a **non-portable
extension**.
6. **length(I[])**: The number of elements in the array **I**. This is a
**non-portable extension**.
7. **scale(E)**: The *scale* of **E**.
8. **abs(E)**: The absolute value of **E**. This is a **non-portable
extension**.
9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
the base, the second is the exponent, and the third is the modulus. All
three values must be integers. The second argument must be non-negative. The
third argument must be non-zero. This is a **non-portable extension**.
10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
optimization. The first expression is the dividend, and the second is the
divisor, which must be non-zero. The return value is the quotient, and the
modulus is stored in index **0** of the provided array (the last argument).
This is a **non-portable extension**.
11. **asciify(E)**: If **E** is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number mod **256**
and returns that number as a one-character string. This is a **non-portable
extension**.
12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a non-**void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
13. **read()**: Reads a line from **stdin** and uses that as an expression. The
result of that expression is the result of the **read()** operand. This is a
**non-portable extension**.
14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
extension**.
15. **maxobase()**: The max allowable **obase**. This is a **non-portable
extension**.
16. **maxscale()**: The max allowable **scale**. This is a **non-portable
extension**.
-17. **rand()**: A pseudo-random integer between **0** (inclusive) and
+17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
+ **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
+18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
+ or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
+ or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+20. **rand()**: A pseudo-random integer between **0** (inclusive) and
**BC_RAND_MAX** (inclusive). Using this operand will change the value of
**seed**. This is a **non-portable extension**.
-18. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
+21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
value of **E** (exclusive). If **E** is negative or is a non-integer
(**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see
the **RESET** section) while **seed** remains unchanged. If **E** is larger
than **BC_RAND_MAX**, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
**BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that
can be generated with this operand is unbounded. Using this operand will
change the value of **seed**, unless the value of **E** is **0** or **1**.
In that case, **0** is returned, and **seed** is *not* changed. This is a
**non-portable extension**.
-19. **maxrand()**: The max integer returned by **rand()**. This is a
+22. **maxrand()**: The max integer returned by **rand()**. This is a
**non-portable extension**.
The integers generated by **rand()** and **irand(E)** are guaranteed to be as
unbiased as possible, subject to the limitations of the pseudo-random number
generator.
**Note**: The values returned by the pseudo-random number generator with
**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator. However,
they *are* guaranteed to be reproducible with identical **seed** values. This
means that the pseudo-random values from bc(1) should only be used where a
reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
use a non-seeded pseudo-random number generator.
## Numbers
Numbers are strings made up of digits, uppercase letters, and at most **1**
period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
letters are equal to **9** + their position in the alphabet (i.e., **A** equals
**10**, or **9+1**). If a digit or letter makes no sense with the current value
of **ibase**, they are set to the value of the highest valid digit in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **Z** alone always equals decimal
**35**.
In addition, bc(1) accepts numbers in scientific notation. These have the form
**\e\**. The exponent (the portion after the **e**) must be
an integer. An example is **1.89237e9**, which is equal to **1892370000**.
Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**.
Using scientific notation is an error or warning if the **-s** or **-w**,
respectively, command-line options (or equivalents) are given.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For example,
if **ibase** is **16** and bc(1) is given the number string **FFeA**, the
resulting decimal number will be **2550000000000**, and if bc(1) is given the
number string **10e-4**, the resulting decimal number will be **0.0016**.
Accepting input as scientific notation is a **non-portable extension**.
## Operators
The following arithmetic and logical operators can be used. They are listed in
order of decreasing precedence. Operators in the same group have the same
precedence.
**++** **-\-**
: Type: Prefix and Postfix
Associativity: None
Description: **increment**, **decrement**
**-** **!**
: Type: Prefix
Associativity: None
Description: **negation**, **boolean not**
**\$**
: Type: Postfix
Associativity: None
Description: **truncation**
**\@**
: Type: Binary
Associativity: Right
Description: **set precision**
**\^**
: Type: Binary
Associativity: Right
Description: **power**
**\*** **/** **%**
: Type: Binary
Associativity: Left
Description: **multiply**, **divide**, **modulus**
**+** **-**
: Type: Binary
Associativity: Left
Description: **add**, **subtract**
**\<\<** **\>\>**
: Type: Binary
Associativity: Left
Description: **shift left**, **shift right**
**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
: Type: Binary
Associativity: Right
Description: **assignment**
**==** **\<=** **\>=** **!=** **\<** **\>**
: Type: Binary
Associativity: Left
Description: **relational**
**&&**
: Type: Binary
Associativity: Left
Description: **boolean and**
**||**
: Type: Binary
Associativity: Left
Description: **boolean or**
The operators will be described in more detail below.
**++** **-\-**
: The prefix and postfix **increment** and **decrement** operators behave
exactly like they would in C. They require a named expression (see the
*Named Expressions* subsection) as an operand.
The prefix versions of these operators are more efficient; use them where
possible.
**-**
: The **negation** operator returns **0** if a user attempts to negate any
expression with the value **0**. Otherwise, a copy of the expression with
its sign flipped is returned.
**!**
: The **boolean not** operator returns **1** if the expression is **0**, or
**0** otherwise.
This is a **non-portable extension**.
**\$**
: The **truncation** operator returns a copy of the given expression with all
of its *scale* removed.
This is a **non-portable extension**.
**\@**
: The **set precision** operator takes two expressions and returns a copy of
the first with its *scale* equal to the value of the second expression. That
could either mean that the number is returned without change (if the
*scale* of the first expression matches the value of the second
expression), extended (if it is less), or truncated (if it is more).
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**\^**
: The **power** operator (not the **exclusive or** operator, as it would be in
C) takes two expressions and raises the first to the power of the value of
the second. The *scale* of the result is equal to **scale**.
The second expression must be an integer (no *scale*), and if it is
negative, the first value must be non-zero.
**\***
: The **multiply** operator takes two expressions, multiplies them, and
returns the product. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result is
equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The **divide** operator takes two expressions, divides them, and returns the
quotient. The *scale* of the result shall be the value of **scale**.
The second expression must be non-zero.
**%**
: The **modulus** operator takes two expressions, **a** and **b**, and
evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The second expression must be non-zero.
**+**
: The **add** operator takes two expressions, **a** and **b**, and returns the
sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
**-**
: The **subtract** operator takes two expressions, **a** and **b**, and
returns the difference, with a *scale* equal to the max of the *scale*s of
**a** and **b**.
**\<\<**
: The **left shift** operator takes two expressions, **a** and **b**, and
returns a copy of the value of **a** with its decimal point moved **b**
places to the right.
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**\>\>**
: The **right shift** operator takes two expressions, **a** and **b**, and
returns a copy of the value of **a** with its decimal point moved **b**
places to the left.
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
: The **assignment** operators take two expressions, **a** and **b** where
**a** is a named expression (see the *Named Expressions* subsection).
For **=**, **b** is copied and the result is assigned to **a**. For all
others, **a** and **b** are applied as operands to the corresponding
arithmetic operator and the result is assigned to **a**.
The **assignment** operators that correspond to operators that are
extensions are themselves **non-portable extensions**.
**==** **\<=** **\>=** **!=** **\<** **\>**
: The **relational** operators compare two expressions, **a** and **b**, and
if the relation holds, according to C language semantics, the result is
**1**. Otherwise, it is **0**.
Note that unlike in C, these operators have a lower precedence than the
**assignment** operators, which means that **a=b\>c** is interpreted as
**(a=b)\>c**.
Also, unlike the [standard][1] requires, these operators can appear anywhere
any other expressions can be used. This allowance is a
**non-portable extension**.
**&&**
: The **boolean and** operator takes two expressions and returns **1** if both
expressions are non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
**||**
: The **boolean or** operator takes two expressions and returns **1** if one
of the expressions is non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
## Statements
The following items are statements:
1. **E**
2. **{** **S** **;** ... **;** **S** **}**
3. **if** **(** **E** **)** **S**
4. **if** **(** **E** **)** **S** **else** **S**
5. **while** **(** **E** **)** **S**
6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
7. An empty statement
8. **break**
9. **continue**
10. **quit**
11. **halt**
12. **limits**
13. A string of characters, enclosed in double quotes
14. **print** **E** **,** ... **,** **E**
15. **stream** **E** **,** ... **,** **E**
16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
Also, as a **non-portable extension**, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expression) is
omitted, it is assumed to be a constant **1**.
The **break** statement causes a loop to stop iterating and resume execution
immediately following a loop. This is only allowed in loops.
The **continue** statement causes a loop iteration to stop early and returns to
the start of the loop, including testing the loop condition. This is only
allowed in loops.
The **if** **else** statement does the same thing as in C.
The **quit** statement causes bc(1) to quit, even if it is on a branch that will
not be executed (it is a compile-time command).
The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
if it is on a branch of an **if** statement that is not executed, bc(1) does not
quit.)
The **limits** statement prints the limits that this bc(1) is subject to. This
is like the **quit** statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a newline.
Both scientific notation and engineering notation are available for printing the
results of expressions. Scientific notation is activated by assigning **0** to
**obase**, and engineering notation is activated by assigning **1** to
**obase**. To deactivate them, just assign a different value to **obase**.
Scientific notation and engineering notation are disabled if bc(1) is run with
either the **-s** or **-w** command-line options (or equivalents).
Printing numbers in scientific notation and/or engineering notation is a
**non-portable extension**.
## Strings
If strings appear as a statement by themselves, they are printed without a
trailing newline.
In addition to appearing as a lone statement by themselves, strings can be
assigned to variables and array elements. They can also be passed to functions
in variable parameters.
If any statement that expects a string is given a variable that had a string
assigned to it, the statement acts as though it had received a string.
If any math operation is attempted on a string or a variable or array element
that has been assigned a string, an error is raised, and bc(1) resets (see the
**RESET** section).
Assigning strings to variables and array elements and passing them to functions
are **non-portable extensions**.
## Print Statement
The "expressions" in a **print** statement may also be strings. If they are, there
are backslash escape sequences that are interpreted specially. What those
sequences are, and what they cause to be printed, are shown below:
**\\a**: **\\a**
**\\b**: **\\b**
**\\\\**: **\\**
**\\e**: **\\**
**\\f**: **\\f**
**\\n**: **\\n**
**\\q**: **"**
**\\r**: **\\r**
**\\t**: **\\t**
Any other character following a backslash causes the backslash and character to
be printed as-is.
Any non-string expression in a print statement shall be assigned to **last**,
like any other expression that is printed.
## Stream Statement
The "expressions in a **stream** statement may also be strings.
If a **stream** statement is given a string, it prints the string as though the
string had appeared as its own statement. In other words, the **stream**
statement prints strings normally, without a newline.
If a **stream** statement is given a number, a copy of it is truncated and its
absolute value is calculated. The result is then printed as though **obase** is
**256** and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
## Order of Evaluation
All expressions in a statment are evaluated left to right, except as necessary
to maintain order of operations. This means, for example, assuming that **i** is
equal to **0**, in the expression
a[i++] = i++
the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
at the end of the expression.
This includes function arguments. Thus, assuming **i** is equal to **0**, this
means that in the expression
x(i++, i++)
the first argument passed to **x()** is **0**, and the second argument is **1**,
while **i** is equal to **2** before the function starts executing.
# FUNCTIONS
Function definitions are as follows:
```
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
```
Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
make a parameter or **auto** var an array, and any **I** in the parameter list
may be replaced with **\*I[]** to make a parameter an array reference. Callers
of functions that take array references should not put an asterisk in the call;
they must be called with just **I[]** like normal array parameters and will be
automatically converted into references.
As a **non-portable extension**, the opening brace of a **define** statement may
appear on the next line.
As a **non-portable extension**, the return statement may also be in one of the
following forms:
1. **return**
2. **return** **(** **)**
3. **return** **E**
The first two, or not specifying a **return** statement, is equivalent to
**return (0)**, unless the function is a **void** function (see the *Void
Functions* subsection below).
## Void Functions
Functions can also be **void** functions, defined as follows:
```
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
```
They can only be used as standalone expressions, where such an expression would
be printed alone, except in a print statement.
Void functions can only use the first two **return** statements listed above.
They can also omit the return statement entirely.
The word "void" is not treated as a keyword; it is still possible to have
variables, arrays, and functions named **void**. The word "void" is only
treated specially right after the **define** keyword.
This is a **non-portable extension**.
## Array References
For any array in the parameter list, if the array is declared in the form
```
*I[]
```
it is a **reference**. Any changes to the array in the function are reflected,
when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a **non-portable extension**.
# LIBRARY
All of the functions below, including the functions in the extended math
library (see the *Extended Library* subsection below), are available when the
**-l** or **-\-mathlib** command-line flags are given, except that the extended
math library is not available when the **-s** option, the **-w** option, or
equivalents are given.
## Standard Library
The [standard][1] defines the following functions for the math library:
**s(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**c(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a(x)**
: Returns the arctangent of **x**, in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l(x)**
: Returns the natural logarithm of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**e(x)**
: Returns the mathematical constant **e** raised to the power of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**j(x, n)**
: Returns the bessel integer order **n** (truncated) of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
## Extended Library
The extended library is *not* loaded when the **-s**/**-\-standard** or
**-w**/**-\-warn** options are given since they are not part of the library
defined by the [standard][1].
The extended library is a **non-portable extension**.
**p(x, y)**
: Calculates **x** to the power of **y**, even if **y** is not an integer, and
returns the result to the current **scale**.
It is an error if **y** is negative and **x** is **0**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**r(x, p)**
: Returns **x** rounded to **p** decimal places according to the rounding mode
[round half away from **0**][3].
**ceil(x, p)**
: Returns **x** rounded to **p** decimal places according to the rounding mode
[round away from **0**][6].
**f(x)**
: Returns the factorial of the truncated absolute value of **x**.
**perm(n, k)**
: Returns the permutation of the truncated absolute value of **n** of the
truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
**comb(n, k)**
: Returns the combination of the truncated absolute value of **n** of the
truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
**l2(x)**
: Returns the logarithm base **2** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l10(x)**
: Returns the logarithm base **10** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**log(x, b)**
: Returns the logarithm base **b** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**cbrt(x)**
: Returns the cube root of **x**.
**root(x, n)**
: Calculates the truncated value of **n**, **r**, and returns the **r**th root
of **x** to the current **scale**.
If **r** is **0** or negative, this raises an error and causes bc(1) to
reset (see the **RESET** section). It also raises an error and causes bc(1)
to reset if **r** is even and **x** is negative.
**gcd(a, b)**
: Returns the greatest common divisor (factor) of the truncated absolute value
of **a** and the truncated absolute value of **b**.
**lcm(a, b)**
: Returns the least common multiple of the truncated absolute value of **a**
and the truncated absolute value of **b**.
**pi(p)**
: Returns **pi** to **p** decimal places.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**t(x)**
: Returns the tangent of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a2(y, x)**
: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
equal to **0**, it raises an error and causes bc(1) to reset (see the
**RESET** section). Otherwise, if **x** is greater than **0**, it returns
**a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
**0**, and **y** is less than **0**, it returns **-pi/2**.
This function is the same as the **atan2()** function in many programming
languages.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**sin(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is an alias of **s(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**cos(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is an alias of **c(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**tan(x)**
: Returns the tangent of **x**, which is assumed to be in radians.
If **x** is equal to **1** or **-1**, this raises an error and causes bc(1)
to reset (see the **RESET** section).
This is an alias of **t(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**atan(x)**
: Returns the arctangent of **x**, in radians.
This is an alias of **a(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**atan2(y, x)**
: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
equal to **0**, it raises an error and causes bc(1) to reset (see the
**RESET** section). Otherwise, if **x** is greater than **0**, it returns
**a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
**0**, and **y** is less than **0**, it returns **-pi/2**.
This function is the same as the **atan2()** function in many programming
languages.
This is an alias of **a2(y, x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**r2d(x)**
: Converts **x** from radians to degrees and returns the result.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**d2r(x)**
: Converts **x** from degrees to radians and returns the result.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**frand(p)**
: Generates a pseudo-random number between **0** (inclusive) and **1**
(exclusive) with the number of decimal digits after the decimal point equal
to the truncated absolute value of **p**. If **p** is not **0**, then
calling this function will change the value of **seed**. If **p** is **0**,
then **0** is returned, and **seed** is *not* changed.
**ifrand(i, p)**
: Generates a pseudo-random number that is between **0** (inclusive) and the
truncated absolute value of **i** (exclusive) with the number of decimal
digits after the decimal point equal to the truncated absolute value of
**p**. If the absolute value of **i** is greater than or equal to **2**, and
**p** is not **0**, then calling this function will change the value of
**seed**; otherwise, **0** is returned and **seed** is not changed.
**srand(x)**
: Returns **x** with its sign flipped with probability **0.5**. In other
words, it randomizes the sign of **x**.
**brand()**
: Returns a random boolean value (either **0** or **1**).
**band(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **and** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bor(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **or** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bxor(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **xor** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bshl(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of **a** bit-shifted left by **b** places.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bshr(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the truncated result of **a** bit-shifted right by **b** places.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bnotn(x, n)**
: Takes the truncated absolute value of **x** and does a bitwise not as though
it has the same number of bytes as the truncated absolute value of **n**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot8(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**8** binary digits (1 unsigned byte).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot16(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**16** binary digits (2 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot32(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**32** binary digits (4 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot64(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**64** binary digits (8 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
the minimum number of power of two unsigned bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brevn(x, n)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has the same number of 8-bit bytes as the truncated absolute value of **n**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev8(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 8 binary digits (1 unsigned byte).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev16(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 16 binary digits (2 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev32(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 32 binary digits (4 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev64(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 64 binary digits (8 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has the minimum number of power of two unsigned bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**broln(x, p, n)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has the same number of unsigned 8-bit bytes as the truncated
absolute value of **n**, by the number of places equal to the truncated
absolute value of **p** modded by the **2** to the power of the number of
binary digits in **n** 8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol8(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **8** binary digits (**1** unsigned byte), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol16(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **16** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol32(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **32** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol64(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **64** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has the minimum number of power of two unsigned 8-bit bytes, by
the number of places equal to the truncated absolute value of **p** modded
by 2 to the power of the number of binary digits in the minimum number of
8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brorn(x, p, n)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has the same number of unsigned 8-bit bytes as the truncated
absolute value of **n**, by the number of places equal to the truncated
absolute value of **p** modded by the **2** to the power of the number of
binary digits in **n** 8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror8(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **8** binary digits (**1** unsigned byte), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror16(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **16** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror32(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **32** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror64(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **64** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has the minimum number of power of two unsigned 8-bit bytes, by
the number of places equal to the truncated absolute value of **p** modded
by 2 to the power of the number of binary digits in the minimum number of
8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmodn(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of the multiplication of the truncated absolute value of **n** and
**8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod8(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod16(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod32(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod64(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bunrev(t)**
: Assumes **t** is a bitwise-reversed number with an extra set bit one place
more significant than the real most significant bit (which was the least
significant bit in the original number). This number is reversed and
returned without the extra set bit.
This function is used to implement other bitwise functions; it is not meant
to be used by users, but it can be.
+**plz(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed with a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and without a trailing newline.
+
+ Otherwise, **x** is printed normally, without a trailing newline.
+
+**plznl(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed with a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and with a trailing newline.
+
+ Otherwise, **x** is printed normally, with a trailing newline.
+
+**pnlz(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed without a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and without a trailing newline.
+
+ Otherwise, **x** is printed normally, without a trailing newline.
+
+**pnlznl(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed without a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and with a trailing newline.
+
+ Otherwise, **x** is printed normally, with a trailing newline.
+
**ubytes(x)**
: Returns the numbers of unsigned integer bytes required to hold the truncated
absolute value of **x**.
**sbytes(x)**
: Returns the numbers of signed, two's-complement integer bytes required to
hold the truncated value of **x**.
**s2u(x)**
: Returns **x** if it is non-negative. If it *is* negative, then it calculates
what **x** would be as a 2's-complement signed integer and returns the
non-negative integer that would have the same representation in binary.
**s2un(x,n)**
: Returns **x** if it is non-negative. If it *is* negative, then it calculates
what **x** would be as a 2's-complement signed integer with **n** bytes and
returns the non-negative integer that would have the same representation in
binary. If **x** cannot fit into **n** 2's-complement signed bytes, it is
truncated to fit.
**hex(x)**
: Outputs the hexadecimal (base **16**) representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**binary(x)**
: Outputs the binary (base **2**) representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output(x, b)**
: Outputs the base **b** representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in as few power of two bytes as possible. Both outputs are
split into bytes separated by spaces.
If **x** is not an integer or is negative, an error message is printed
instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in as few power of two bytes as possible. Both
outputs are split into bytes separated by spaces.
If **x** is not an integer, an error message is printed instead, but bc(1)
is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uintn(x, n)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **n** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **n** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**intn(x, n)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **n** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **n** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint8(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **1** byte. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **1** byte, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int8(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **1** byte. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **1** byte, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint16(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **2** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **2** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int16(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **2** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **2** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint32(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **4** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **4** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int32(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **4** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **4** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint64(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **8** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **8** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int64(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **8** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **8** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**hex_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in hexadecimal using **n** bytes. Not all of the value will
be output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**binary_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in binary using **n** bytes. Not all of the value will be
output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in the current **obase** (see the **SYNTAX** section) using
**n** bytes. Not all of the value will be output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output_byte(x, i)**
: Outputs byte **i** of the truncated absolute value of **x**, where **0** is
the least significant byte and **number_of_bytes - 1** is the most
significant byte.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
## Transcendental Functions
All transcendental functions can return slightly inaccurate results (up to 1
[ULP][4]). This is unavoidable, and [this article][5] explains why it is
impossible and unnecessary to calculate exact results for the transcendental
functions.
Because of the possible inaccuracy, I recommend that users call those functions
with the precision (**scale**) set to at least 1 higher than is necessary. If
exact results are *absolutely* required, users can double the precision
(**scale**) and then truncate.
The transcendental functions in the standard math library are:
* **s(x)**
* **c(x)**
* **a(x)**
* **l(x)**
* **e(x)**
* **j(x, n)**
The transcendental functions in the extended math library are:
* **l2(x)**
* **l10(x)**
* **log(x, b)**
* **pi(p)**
* **t(x)**
* **a2(y, x)**
* **sin(x)**
* **cos(x)**
* **tan(x)**
* **atan(x)**
* **atan2(y, x)**
* **r2d(x)**
* **d2r(x)**
# RESET
When bc(1) encounters an error or a signal that it has a non-default handler
for, it resets. This means that several things happen.
First, any functions 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.
Thus, when bc(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.
Note that this reset behavior is different from the GNU bc(1), which attempts to
start executing the statement right after the one that caused an error.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This bc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
the **limits** statement.
In addition, this bc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bc(1):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bc(1) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_STRING_MAX**
: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
**BC_NAME_MAX**
: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
**BC_RAND_MAX**
: The maximum integer (inclusive) returned by the **rand()** operand. Set at
**2\^BC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
The actual values can be queried with the **limits** statement.
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.
# ENVIRONMENT VARIABLES
bc(1) recognizes the following environment variables:
**POSIXLY_CORRECT**
: If this variable exists (no matter the contents), bc(1) behaves as if
the **-s** option was given.
**BC_ENV_ARGS**
: This is another way to give command-line arguments to bc(1). They should be
in the same format as all other command-line arguments. These are always
processed first, so any files given in **BC_ENV_ARGS** 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 bc(1) runs.
The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
**"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'bc' file.bc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **BC_ENV_ARGS** 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.
**BC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
lines to that length, including the backslash (**\\**). The default line
length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**BC_BANNER**
: If this environment variable exists and contains an integer, then a non-zero
value activates the copyright banner when bc(1) is in interactive mode,
while zero deactivates it.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) does not print
the banner when not in interactive mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_SIGINT_RESET**
: If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) exits on
**SIGINT** when not in interactive mode.
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1) reset
on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
environment variable exists and is *not* an integer, then bc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use TTY
mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a prompt,
and zero or a non-integer makes bc(1) not use a prompt. If this environment
variable does not exist and **BC_TTY_MODE** does, then the value of the
**BC_TTY_MODE** environment variable is used.
This environment variable and the **BC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
bc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, 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, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**)
operators and their corresponding assignment operators.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, using a token where it is invalid,
giving an invalid expression, giving an invalid print statement, giving an
invalid function definition, attempting to assign to an expression that is
not a named expression (see the *Named Expressions* subsection of the
**SYNTAX** section), giving an invalid **auto** list, having a duplicate
**auto**/function parameter, failing to find the end of a code block,
attempting to return a value from a **void** function, attempting to use a
variable as a reference, and using any extensions when the option **-s** or
any equivalents were given.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors, passing the
wrong number of arguments to functions, attempting to call an undefined
function, and attempting to use a **void** function call as a value in an
expression.
**4**
: A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, failing to open
files, attempting to use files that do not have only ASCII characters (bc(1)
only accepts ASCII characters), attempting to open a directory as a file,
and giving invalid command-line options.
The exit status **4** is special; when a fatal error occurs, bc(1) always exits
and returns **4**, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interactive mode
(see the **INTERACTIVE MODE** section), since bc(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
**-i** flag or **-\-interactive** option.
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **BC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **BC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
mode on.
If the environment variable **BC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **BC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, bc(1) will
exit.
However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
default is an integer and non-zero, then bc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If bc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If bc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
can seem as though bc(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 bc(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.
**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
default handler for all other signals.
# LOCALES
This bc(1) ships with support for adding error messages for different locales
and thus, supports **LC_MESSAGES**.
# SEE ALSO
dc(1)
# STANDARDS
bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
specification. The flags **-efghiqsvVw**, all long options, and the extensions
noted above are extensions to that specification.
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**.
This bc(1) supports error messages for different locales, and thus, it supports
**LC_MESSAGES**.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
diff --git a/manuals/bc/HN.1 b/manuals/bc/HN.1
index 1ca11d9b4579..4773ff77efea 100644
--- a/manuals/bc/HN.1
+++ b/manuals/bc/HN.1
@@ -1,2663 +1,2748 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH NAME
.PP
bc - arbitrary-precision decimal arithmetic language and calculator
.SH SYNOPSIS
.PP
\f[B]bc\f[R] [\f[B]-ghilPqRsvVw\f[R]] [\f[B]--global-stacks\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]]
[\f[B]--no-prompt\f[R]] [\f[B]--no-read-prompt\f[R]] [\f[B]--quiet\f[R]]
[\f[B]--standard\f[R]] [\f[B]--warn\f[R]] [\f[B]--version\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX.
(The current standard is
here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).)
The language provides unlimited precision decimal arithmetic and is
somewhat C-like, but there are differences.
Such differences will be noted in this document.
.PP
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from \f[B]stdin\f[R].
.PP
This bc(1) is a drop-in replacement for \f[I]any\f[R] bc(1), including
(and especially) the GNU bc(1).
It also has many extensions and extra features beyond other
implementations.
.PP
\f[B]Note\f[R]: If running this bc(1) on \f[I]any\f[R] script meant for
another bc(1) gives a parse error, it is probably because a word this
bc(1) reserves as a keyword is used as the name of a function, variable,
or array.
To fix that, use the command-line option \f[B]-r\f[R] \f[I]keyword\f[R],
where \f[I]keyword\f[R] is the keyword that is used as a name in the
script.
For more information, see the \f[B]OPTIONS\f[R] section.
.PP
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported.
See the \f[B]BUGS\f[R] section.
.SH OPTIONS
.PP
The following are the options that bc(1) accepts.
.TP
\f[B]-g\f[R], \f[B]--global-stacks\f[R]
Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and
\f[B]seed\f[R] into stacks.
.RS
.PP
This has the effect that a copy of the current value of all four are
pushed onto a stack for every function call, as well as popped when
every function returns.
This means that functions can assign to any and all of those globals
without worrying that the change will affect other functions.
Thus, a hypothetical function named \f[B]output(x,b)\f[R] that simply
printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this:
.IP
.nf
\f[C]
define void output(x, b) {
obase=b
x
}
\f[R]
.fi
.PP
instead of like this:
.IP
.nf
\f[C]
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
\f[R]
.fi
.PP
This makes writing functions much easier.
.PP
(\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the
extended math library.
See the \f[B]LIBRARY\f[R] section.)
.PP
However, since using this flag means that functions cannot set
\f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R]
globally, functions that are made to do so cannot work anymore.
There are two possible use cases for that, and each has a solution.
.PP
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases.
Examples:
.IP
.nf
\f[C]
alias d2o=\[dq]bc -e ibase=A -e obase=8\[dq]
alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq]
\f[R]
.fi
.PP
Second, if the purpose of a function is to set \f[B]ibase\f[R],
\f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] globally for any
other purpose, it could be split into one to four functions (based on
how many globals it sets) and each of those functions could return the
desired value for a global.
.PP
For functions that set \f[B]seed\f[R], the value assigned to
\f[B]seed\f[R] is not propagated to parent functions.
This means that the sequence of pseudo-random numbers that they see will
not be the same sequence of pseudo-random numbers that any parent sees.
This is only the case once \f[B]seed\f[R] has been set.
.PP
If a function desires to not affect the sequence of pseudo-random
numbers of its parents, but wants to use the same \f[B]seed\f[R], it can
use the following line:
.IP
.nf
\f[C]
seed = seed
\f[R]
.fi
.PP
If the behavior of this option is desired for every run of bc(1), then
users could make sure to define \f[B]BC_ENV_ARGS\f[R] and include this
option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more
details).
.PP
If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option
is ignored.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-l\f[R], \f[B]--mathlib\f[R]
Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R]
and loads the included math library and the extended math library before
running any code, including any expressions or files specified on the
command line.
.RS
.PP
To learn what is in the libraries, see the \f[B]LIBRARY\f[R] section.
.RE
.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.RS
.PP
These options override the \f[B]BC_PROMPT\f[R] and \f[B]BC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of bc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]read()\f[R] built-in function is called.
.PP
These options \f[I]do\f[R] override the \f[B]BC_PROMPT\f[R] and
\f[B]BC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-r\f[R] \f[I]keyword\f[R], \f[B]--redefine\f[R]=\f[I]keyword\f[R]
Redefines \f[I]keyword\f[R] in order to allow it to be used as a
function, variable, or array name.
This is useful when this bc(1) gives parse errors when parsing scripts
meant for other bc(1) implementations.
.RS
.PP
The keywords this bc(1) allows to be redefined are:
.IP \[bu] 2
\f[B]abs\f[R]
.IP \[bu] 2
\f[B]asciify\f[R]
.IP \[bu] 2
\f[B]continue\f[R]
.IP \[bu] 2
\f[B]divmod\f[R]
.IP \[bu] 2
\f[B]else\f[R]
.IP \[bu] 2
\f[B]halt\f[R]
.IP \[bu] 2
\f[B]irand\f[R]
.IP \[bu] 2
\f[B]last\f[R]
.IP \[bu] 2
\f[B]limits\f[R]
.IP \[bu] 2
\f[B]maxibase\f[R]
.IP \[bu] 2
\f[B]maxobase\f[R]
.IP \[bu] 2
\f[B]maxrand\f[R]
.IP \[bu] 2
\f[B]maxscale\f[R]
.IP \[bu] 2
\f[B]modexp\f[R]
.IP \[bu] 2
\f[B]print\f[R]
.IP \[bu] 2
\f[B]rand\f[R]
.IP \[bu] 2
\f[B]read\f[R]
.IP \[bu] 2
\f[B]seed\f[R]
.IP \[bu] 2
\f[B]stream\f[R]
.PP
If any of those keywords are used as a function, variable, or array name
in a script, use this option with the keyword as the argument.
If multiple are used, use this option for all of them; it can be used
multiple times.
.PP
Keywords are \f[I]not\f[R] redefined when parsing the builtin math
library (see the \f[B]LIBRARY\f[R] section).
.PP
It is a fatal error to redefine keywords mandated by the POSIX standard.
It is a fatal error to attempt to redefine words that this bc(1) does
not reserve as keywords.
.RE
.TP
\f[B]-q\f[R], \f[B]--quiet\f[R]
This option is for compatibility with the GNU
bc(1) (https://www.gnu.org/software/bc/); it is a no-op.
Without this option, GNU bc(1) prints a copyright header.
This bc(1) only prints the copyright header if one or more of the
\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-s\f[R], \f[B]--standard\f[R]
Process exactly the language defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
and error if any extensions are used.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-w\f[R], \f[B]--warn\f[R]
Like \f[B]-s\f[R] and \f[B]--standard\f[R], except that warnings (and
not errors) are printed for non-standard extensions and execution
continues normally.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]BC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files or expressions are given by the \f[B]-f\f[R],
\f[B]--file\f[R], \f[B]-e\f[R], or \f[B]--expression\f[R] options, then
bc(1) read from \f[B]stdin\f[R].
.PP
However, there are a few caveats to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if the parse cannot complete.
That means that starting a string without ending it or starting a
function, \f[B]if\f[R] statement, or loop without ending it will also
cause bc(1) to not execute.
.PP
Second, after an \f[B]if\f[R] statement, bc(1) doesn\[cq]t know if an
\f[B]else\f[R] statement will follow, so it will not execute until it
knows there will not be an \f[B]else\f[R] statement.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]bc >&-\f[R], it will quit with an error.
This is done so that bc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]bc 2>&-\f[R], it will quit with an error.
This is done so that bc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
which is a much more thorough resource for the language this bc(1)
accepts.
This section is meant to be a summary and a listing of all the
extensions to the standard.
.PP
In the sections below, \f[B]E\f[R] means expression, \f[B]S\f[R] means
statement, and \f[B]I\f[R] means identifier.
.PP
Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be
followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase
letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores
(\f[B]_\f[R]).
The regex is \f[B][a-z][a-z0-9_]*\f[R].
Identifiers with more than one character (letter) are a
\f[B]non-portable extension\f[R].
.PP
\f[B]ibase\f[R] is a global variable determining how to interpret
constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R]
(\f[B]--warn\f[R]) flags were not given on the command line, the max
allowable value for \f[B]ibase\f[R] is \f[B]36\f[R].
Otherwise, it is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in bc(1)
programs with the \f[B]maxibase()\f[R] built-in function.
.PP
\f[B]obase\f[R] is a global variable determining how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and
can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in
function.
The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R].
If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific
notation, and if \f[B]obase\f[R] is \f[B]1\f[R], values are output in
engineering notation.
Otherwise, values are output in the specified base.
.PP
Outputting in scientific and engineering notations are \f[B]non-portable
extensions\f[R].
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a global variable that sets the precision of any operations, with
exceptions.
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R]
and can be queried in bc(1) programs with the \f[B]maxscale()\f[R]
built-in function.
.PP
bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables.
All \f[I]local\f[R] variables are local to the function; they are
parameters or are introduced in the \f[B]auto\f[R] list of a function
(see the \f[B]FUNCTIONS\f[R] section).
If a variable is accessed which is not a parameter or in the
\f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R].
If a parent function has a \f[I]local\f[R] variable version of a
variable that a child function considers \f[I]global\f[R], the value of
that \f[I]global\f[R] variable in the child function is the value of the
variable in the parent function, not the value of the actual
\f[I]global\f[R] variable.
.PP
All of the above applies to arrays as well.
.PP
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence
operator is an assignment operator \f[I]and\f[R] the expression is
notsurrounded by parentheses.
.PP
The value that is printed is also assigned to the special variable
\f[B]last\f[R].
A single dot (\f[B].\f[R]) may also be used as a synonym for
\f[B]last\f[R].
These are \f[B]non-portable extensions\f[R].
.PP
Either semicolons or newlines may separate statements.
.SS Comments
.PP
There are two kinds of comments:
.IP "1." 3
Block comments are enclosed in \f[B]/*\f[R] and \f[B]*/\f[R].
.IP "2." 3
Line comments go from \f[B]#\f[R] until, and not including, the next
newline.
This is a \f[B]non-portable extension\f[R].
.SS Named Expressions
.PP
The following are named expressions in bc(1):
.IP "1." 3
Variables: \f[B]I\f[R]
.IP "2." 3
Array Elements: \f[B]I[E]\f[R]
.IP "3." 3
\f[B]ibase\f[R]
.IP "4." 3
\f[B]obase\f[R]
.IP "5." 3
\f[B]scale\f[R]
.IP "6." 3
\f[B]seed\f[R]
.IP "7." 3
\f[B]last\f[R] or a single dot (\f[B].\f[R])
.PP
Numbers 6 and 7 are \f[B]non-portable extensions\f[R].
.PP
The meaning of \f[B]seed\f[R] is dependent on the current pseudo-random
number generator but is guaranteed to not change except for new major
versions.
.PP
The \f[I]scale\f[R] and sign of the value may be significant.
.PP
If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R]
and used again, the pseudo-random number generator is guaranteed to
produce the same sequence of pseudo-random numbers as it did when the
\f[B]seed\f[R] value was previously used.
.PP
The exact value assigned to \f[B]seed\f[R] is not guaranteed to be
returned if \f[B]seed\f[R] is queried again immediately.
However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both
values, when assigned to \f[B]seed\f[R], are guaranteed to produce the
same sequence of pseudo-random numbers.
This means that certain values assigned to \f[B]seed\f[R] will
\f[I]not\f[R] produce unique sequences of pseudo-random numbers.
The value of \f[B]seed\f[R] will change after any use of the
\f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the
\f[I]Operands\f[R] subsection below), except if the parameter passed to
\f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative.
.PP
There is no limit to the length (number of significant decimal digits)
or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R].
.PP
Variables and arrays do not interfere; users can have arrays named the
same as variables.
This also applies to functions (see the \f[B]FUNCTIONS\f[R] section), so
a user can have a variable, array, and function that all have the same
name, and they will not shadow each other, whether inside of functions
or not.
.PP
Named expressions are required as the operand of
\f[B]increment\f[R]/\f[B]decrement\f[R] operators and as the left side
of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R]
subsection).
.SS Operands
.PP
The following are valid operands in bc(1):
.IP " 1." 4
Numbers (see the \f[I]Numbers\f[R] subsection below).
.IP " 2." 4
Array indices (\f[B]I[E]\f[R]).
.IP " 3." 4
\f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence).
.IP " 4." 4
\f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R].
\f[B]E\f[R] must be non-negative.
.IP " 5." 4
\f[B]length(E)\f[R]: The number of significant decimal digits in
\f[B]E\f[R].
Returns \f[B]1\f[R] for \f[B]0\f[R] with no decimal places.
If given a string, the length of the string is returned.
Passing a string to \f[B]length(E)\f[R] is a \f[B]non-portable
extension\f[R].
.IP " 6." 4
\f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 7." 4
\f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R].
.IP " 8." 4
\f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 9." 4
\f[B]modexp(E, E, E)\f[R]: Modular exponentiation, where the first
expression is the base, the second is the exponent, and the third is the
modulus.
All three values must be integers.
The second argument must be non-negative.
The third argument must be non-zero.
This is a \f[B]non-portable extension\f[R].
.IP "10." 4
\f[B]divmod(E, E, I[])\f[R]: Division and modulus in one operation.
This is for optimization.
The first expression is the dividend, and the second is the divisor,
which must be non-zero.
The return value is the quotient, and the modulus is stored in index
\f[B]0\f[R] of the provided array (the last argument).
This is a \f[B]non-portable extension\f[R].
.IP "11." 4
\f[B]asciify(E)\f[R]: If \f[B]E\f[R] is a string, returns a string that
is the first letter of its argument.
If it is a number, calculates the number mod \f[B]256\f[R] and returns
that number as a one-character string.
This is a \f[B]non-portable extension\f[R].
.IP "12." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.IP "13." 4
\f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an
expression.
The result of that expression is the result of the \f[B]read()\f[R]
operand.
This is a \f[B]non-portable extension\f[R].
.IP "14." 4
\f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "15." 4
\f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "16." 4
\f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "17." 4
+\f[B]line_length()\f[R]: The line length set with
+\f[B]BC_LINE_LENGTH\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
+section).
+This is a \f[B]non-portable extension\f[R].
+.IP "18." 4
+\f[B]global_stacks()\f[R]: \f[B]0\f[R] if global stacks are not enabled
+with the \f[B]-g\f[R] or \f[B]--global-stacks\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "19." 4
+\f[B]leading_zero()\f[R]: \f[B]0\f[R] if leading zeroes are not enabled
+with the \f[B]-z\f[R] or \f[B]\[en]leading-zeroes\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "20." 4
\f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R]
(inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive).
Using this operand will change the value of \f[B]seed\f[R].
This is a \f[B]non-portable extension\f[R].
-.IP "18." 4
+.IP "21." 4
\f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R]
(inclusive) and the value of \f[B]E\f[R] (exclusive).
If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s
\f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains
unchanged.
If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is
honored by generating several pseudo-random integers, multiplying them
by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], and adding them
together.
Thus, the size of integer that can be generated with this operand is
unbounded.
Using this operand will change the value of \f[B]seed\f[R], unless the
value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R].
In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is
\f[I]not\f[R] changed.
This is a \f[B]non-portable extension\f[R].
-.IP "19." 4
+.IP "22." 4
\f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R].
This is a \f[B]non-portable extension\f[R].
.PP
The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are
guaranteed to be as unbiased as possible, subject to the limitations of
the pseudo-random number generator.
.PP
\f[B]Note\f[R]: The values returned by the pseudo-random number
generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to
\f[I]NOT\f[R] be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they \f[I]are\f[R] guaranteed to be reproducible with identical
\f[B]seed\f[R] values.
This means that the pseudo-random values from bc(1) should only be used
where a reproducible stream of pseudo-random numbers is
\f[I]ESSENTIAL\f[R].
In any other case, use a non-seeded pseudo-random number generator.
.SS Numbers
.PP
Numbers are strings made up of digits, uppercase letters, and at most
\f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R].
.PP
In addition, bc(1) accepts numbers in scientific notation.
These have the form \f[B]e\f[R].
The exponent (the portion after the \f[B]e\f[R]) must be an integer.
An example is \f[B]1.89237e9\f[R], which is equal to
\f[B]1892370000\f[R].
Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to
\f[B]0.0042890\f[R].
.PP
Using scientific notation is an error or warning if the \f[B]-s\f[R] or
\f[B]-w\f[R], respectively, command-line options (or equivalents) are
given.
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if bc(1) is given the number string
\f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.PP
Accepting input as scientific notation is a \f[B]non-portable
extension\f[R].
.SS Operators
.PP
The following arithmetic and logical operators can be used.
They are listed in order of decreasing precedence.
Operators in the same group have the same precedence.
.TP
\f[B]++\f[R] \f[B]--\f[R]
Type: Prefix and Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]increment\f[R], \f[B]decrement\f[R]
.RE
.TP
\f[B]-\f[R] \f[B]!\f[R]
Type: Prefix
.RS
.PP
Associativity: None
.PP
Description: \f[B]negation\f[R], \f[B]boolean not\f[R]
.RE
.TP
\f[B]$\f[R]
Type: Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]truncation\f[R]
.RE
.TP
\f[B]\[at]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]set precision\f[R]
.RE
.TP
\f[B]\[ha]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]power\f[R]
.RE
.TP
\f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R]
.RE
.TP
\f[B]+\f[R] \f[B]-\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]add\f[R], \f[B]subtract\f[R]
.RE
.TP
\f[B]<<\f[R] \f[B]>>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]shift left\f[R], \f[B]shift right\f[R]
.RE
.TP
\f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]assignment\f[R]
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]relational\f[R]
.RE
.TP
\f[B]&&\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean and\f[R]
.RE
.TP
\f[B]||\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean or\f[R]
.RE
.PP
The operators will be described in more detail below.
.TP
\f[B]++\f[R] \f[B]--\f[R]
The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R]
operators behave exactly like they would in C.
They require a named expression (see the \f[I]Named Expressions\f[R]
subsection) as an operand.
.RS
.PP
The prefix versions of these operators are more efficient; use them
where possible.
.RE
.TP
\f[B]-\f[R]
The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts
to negate any expression with the value \f[B]0\f[R].
Otherwise, a copy of the expression with its sign flipped is returned.
.TP
\f[B]!\f[R]
The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression
is \f[B]0\f[R], or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]$\f[R]
The \f[B]truncation\f[R] operator returns a copy of the given expression
with all of its \f[I]scale\f[R] removed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[at]\f[R]
The \f[B]set precision\f[R] operator takes two expressions and returns a
copy of the first with its \f[I]scale\f[R] equal to the value of the
second expression.
That could either mean that the number is returned without change (if
the \f[I]scale\f[R] of the first expression matches the value of the
second expression), extended (if it is less), or truncated (if it is
more).
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator,
as it would be in C) takes two expressions and raises the first to the
power of the value of the second.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]), and if it
is negative, the first value must be non-zero.
.RE
.TP
\f[B]*\f[R]
The \f[B]multiply\f[R] operator takes two expressions, multiplies them,
and returns the product.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The \f[B]divide\f[R] operator takes two expressions, divides them, and
returns the quotient.
The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]%\f[R]
The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R] and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]+\f[R]
The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the
max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]-\f[R]
The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to
the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]<<\f[R]
The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its
decimal point moved \f[B]b\f[R] places to the right.
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]>>\f[R]
The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its
decimal point moved \f[B]b\f[R] places to the left.
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R]
The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and
\f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named
Expressions\f[R] subsection).
.RS
.PP
For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to
\f[B]a\f[R].
For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to
the corresponding arithmetic operator and the result is assigned to
\f[B]a\f[R].
.PP
The \f[B]assignment\f[R] operators that correspond to operators that are
extensions are themselves \f[B]non-portable extensions\f[R].
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and if the relation holds, according to C language
semantics, the result is \f[B]1\f[R].
Otherwise, it is \f[B]0\f[R].
.RS
.PP
Note that unlike in C, these operators have a lower precedence than the
\f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is
interpreted as \f[B](a=b)>c\f[R].
.PP
Also, unlike the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
requires, these operators can appear anywhere any other expressions can
be used.
This allowance is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]&&\f[R]
The \f[B]boolean and\f[R] operator takes two expressions and returns
\f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]||\f[R]
The \f[B]boolean or\f[R] operator takes two expressions and returns
\f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R]
otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Statements
.PP
The following items are statements:
.IP " 1." 4
\f[B]E\f[R]
.IP " 2." 4
\f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R]
\f[B]}\f[R]
.IP " 3." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 4." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
\f[B]else\f[R] \f[B]S\f[R]
.IP " 5." 4
\f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 6." 4
\f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R]
\f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 7." 4
An empty statement
.IP " 8." 4
\f[B]break\f[R]
.IP " 9." 4
\f[B]continue\f[R]
.IP "10." 4
\f[B]quit\f[R]
.IP "11." 4
\f[B]halt\f[R]
.IP "12." 4
\f[B]limits\f[R]
.IP "13." 4
A string of characters, enclosed in double quotes
.IP "14." 4
\f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "15." 4
\f[B]stream\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "16." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.PP
Numbers 4, 9, 11, 12, 14, 15, and 16 are \f[B]non-portable
extensions\f[R].
.PP
Also, as a \f[B]non-portable extension\f[R], any or all of the
expressions in the header of a for loop may be omitted.
If the condition (second expression) is omitted, it is assumed to be a
constant \f[B]1\f[R].
.PP
The \f[B]break\f[R] statement causes a loop to stop iterating and resume
execution immediately following a loop.
This is only allowed in loops.
.PP
The \f[B]continue\f[R] statement causes a loop iteration to stop early
and returns to the start of the loop, including testing the loop
condition.
This is only allowed in loops.
.PP
The \f[B]if\f[R] \f[B]else\f[R] statement does the same thing as in C.
.PP
The \f[B]quit\f[R] statement causes bc(1) to quit, even if it is on a
branch that will not be executed (it is a compile-time command).
.PP
The \f[B]halt\f[R] statement causes bc(1) to quit, if it is executed.
(Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement
that is not executed, bc(1) does not quit.)
.PP
The \f[B]limits\f[R] statement prints the limits that this bc(1) is
subject to.
This is like the \f[B]quit\f[R] statement in that it is a compile-time
command.
.PP
An expression by itself is evaluated and printed, followed by a newline.
.PP
Both scientific notation and engineering notation are available for
printing the results of expressions.
Scientific notation is activated by assigning \f[B]0\f[R] to
\f[B]obase\f[R], and engineering notation is activated by assigning
\f[B]1\f[R] to \f[B]obase\f[R].
To deactivate them, just assign a different value to \f[B]obase\f[R].
.PP
Scientific notation and engineering notation are disabled if bc(1) is
run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options
(or equivalents).
.PP
Printing numbers in scientific notation and/or engineering notation is a
\f[B]non-portable extension\f[R].
.SS Strings
.PP
If strings appear as a statement by themselves, they are printed without
a trailing newline.
.PP
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements.
They can also be passed to functions in variable parameters.
.PP
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
.PP
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section).
.PP
Assigning strings to variables and array elements and passing them to
functions are \f[B]non-portable extensions\f[R].
.SS Print Statement
.PP
The \[lq]expressions\[rq] in a \f[B]print\f[R] statement may also be
strings.
If they are, there are backslash escape sequences that are interpreted
specially.
What those sequences are, and what they cause to be printed, are shown
below:
.PP
\f[B]\[rs]a\f[R]: \f[B]\[rs]a\f[R]
.PP
\f[B]\[rs]b\f[R]: \f[B]\[rs]b\f[R]
.PP
\f[B]\[rs]\[rs]\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]e\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]f\f[R]: \f[B]\[rs]f\f[R]
.PP
\f[B]\[rs]n\f[R]: \f[B]\[rs]n\f[R]
.PP
\f[B]\[rs]q\f[R]: \f[B]\[lq]\f[R]
.PP
\f[B]\[rs]r\f[R]: \f[B]\[rs]r\f[R]
.PP
\f[B]\[rs]t\f[R]: \f[B]\[rs]t\f[R]
.PP
Any other character following a backslash causes the backslash and
character to be printed as-is.
.PP
Any non-string expression in a print statement shall be assigned to
\f[B]last\f[R], like any other expression that is printed.
.SS Stream Statement
.PP
The \[lq]expressions in a \f[B]stream\f[R] statement may also be
strings.
.PP
If a \f[B]stream\f[R] statement is given a string, it prints the string
as though the string had appeared as its own statement.
In other words, the \f[B]stream\f[R] statement prints strings normally,
without a newline.
.PP
If a \f[B]stream\f[R] statement is given a number, a copy of it is
truncated and its absolute value is calculated.
The result is then printed as though \f[B]obase\f[R] is \f[B]256\f[R]
and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
.SS Order of Evaluation
.PP
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations.
This means, for example, assuming that \f[B]i\f[R] is equal to
\f[B]0\f[R], in the expression
.IP
.nf
\f[C]
a[i++] = i++
\f[R]
.fi
.PP
the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and
\f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression.
.PP
This includes function arguments.
Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in
the expression
.IP
.nf
\f[C]
x(i++, i++)
\f[R]
.fi
.PP
the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the
second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to
\f[B]2\f[R] before the function starts executing.
.SH FUNCTIONS
.PP
Function definitions are as follows:
.IP
.nf
\f[C]
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
\f[R]
.fi
.PP
Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be
replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an
array, and any \f[B]I\f[R] in the parameter list may be replaced with
\f[B]*I[]\f[R] to make a parameter an array reference.
Callers of functions that take array references should not put an
asterisk in the call; they must be called with just \f[B]I[]\f[R] like
normal array parameters and will be automatically converted into
references.
.PP
As a \f[B]non-portable extension\f[R], the opening brace of a
\f[B]define\f[R] statement may appear on the next line.
.PP
As a \f[B]non-portable extension\f[R], the return statement may also be
in one of the following forms:
.IP "1." 3
\f[B]return\f[R]
.IP "2." 3
\f[B]return\f[R] \f[B](\f[R] \f[B])\f[R]
.IP "3." 3
\f[B]return\f[R] \f[B]E\f[R]
.PP
The first two, or not specifying a \f[B]return\f[R] statement, is
equivalent to \f[B]return (0)\f[R], unless the function is a
\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection
below).
.SS Void Functions
.PP
Functions can also be \f[B]void\f[R] functions, defined as follows:
.IP
.nf
\f[C]
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
\f[R]
.fi
.PP
They can only be used as standalone expressions, where such an
expression would be printed alone, except in a print statement.
.PP
Void functions can only use the first two \f[B]return\f[R] statements
listed above.
They can also omit the return statement entirely.
.PP
The word \[lq]void\[rq] is not treated as a keyword; it is still
possible to have variables, arrays, and functions named \f[B]void\f[R].
The word \[lq]void\[rq] is only treated specially right after the
\f[B]define\f[R] keyword.
.PP
This is a \f[B]non-portable extension\f[R].
.SS Array References
.PP
For any array in the parameter list, if the array is declared in the
form
.IP
.nf
\f[C]
*I[]
\f[R]
.fi
.PP
it is a \f[B]reference\f[R].
Any changes to the array in the function are reflected, when the
function returns, to the array that was passed in.
.PP
Other than this, all function arguments are passed by value.
.PP
This is a \f[B]non-portable extension\f[R].
.SH LIBRARY
.PP
All of the functions below, including the functions in the extended math
library (see the \f[I]Extended Library\f[R] subsection below), are
available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line
flags are given, except that the extended math library is not available
when the \f[B]-s\f[R] option, the \f[B]-w\f[R] option, or equivalents
are given.
.SS Standard Library
.PP
The
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
defines the following functions for the math library:
.TP
\f[B]s(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]c(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l(x)\f[R]
Returns the natural logarithm of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]e(x)\f[R]
Returns the mathematical constant \f[B]e\f[R] raised to the power of
\f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]j(x, n)\f[R]
Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.SS Extended Library
.PP
The extended library is \f[I]not\f[R] loaded when the
\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R]
options are given since they are not part of the library defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
.PP
The extended library is a \f[B]non-portable extension\f[R].
.TP
\f[B]p(x, y)\f[R]
Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R]
is not an integer, and returns the result to the current
\f[B]scale\f[R].
.RS
.PP
It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is
\f[B]0\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]r(x, p)\f[R]
Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to
the rounding mode round half away from
\f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero).
.TP
\f[B]ceil(x, p)\f[R]
Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to
the rounding mode round away from
\f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero).
.TP
\f[B]f(x)\f[R]
Returns the factorial of the truncated absolute value of \f[B]x\f[R].
.TP
\f[B]perm(n, k)\f[R]
Returns the permutation of the truncated absolute value of \f[B]n\f[R]
of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R].
If not, it returns \f[B]0\f[R].
.TP
\f[B]comb(n, k)\f[R]
Returns the combination of the truncated absolute value of \f[B]n\f[R]
of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R].
If not, it returns \f[B]0\f[R].
.TP
\f[B]l2(x)\f[R]
Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l10(x)\f[R]
Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]log(x, b)\f[R]
Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]cbrt(x)\f[R]
Returns the cube root of \f[B]x\f[R].
.TP
\f[B]root(x, n)\f[R]
Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns
the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R].
.RS
.PP
If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and
causes bc(1) to reset (see the \f[B]RESET\f[R] section).
It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even
and \f[B]x\f[R] is negative.
.RE
.TP
\f[B]gcd(a, b)\f[R]
Returns the greatest common divisor (factor) of the truncated absolute
value of \f[B]a\f[R] and the truncated absolute value of \f[B]b\f[R].
.TP
\f[B]lcm(a, b)\f[R]
Returns the least common multiple of the truncated absolute value of
\f[B]a\f[R] and the truncated absolute value of \f[B]b\f[R].
.TP
\f[B]pi(p)\f[R]
Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]t(x)\f[R]
Returns the tangent of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a2(y, x)\f[R]
Returns the arctangent of \f[B]y/x\f[R], in radians.
If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises
an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns
\f[B]a(y/x)\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than
or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than
\f[B]0\f[R], it returns \f[B]pi/2\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]-pi/2\f[R].
.RS
.PP
This function is the same as the \f[B]atan2()\f[R] function in many
programming languages.
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]sin(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is an alias of \f[B]s(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]cos(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is an alias of \f[B]c(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]tan(x)\f[R]
Returns the tangent of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an
error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
.PP
This is an alias of \f[B]t(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]atan(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is an alias of \f[B]a(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]atan2(y, x)\f[R]
Returns the arctangent of \f[B]y/x\f[R], in radians.
If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises
an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns
\f[B]a(y/x)\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than
or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than
\f[B]0\f[R], it returns \f[B]pi/2\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]-pi/2\f[R].
.RS
.PP
This function is the same as the \f[B]atan2()\f[R] function in many
programming languages.
.PP
This is an alias of \f[B]a2(y, x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]r2d(x)\f[R]
Converts \f[B]x\f[R] from radians to degrees and returns the result.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]d2r(x)\f[R]
Converts \f[B]x\f[R] from degrees to radians and returns the result.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]frand(p)\f[R]
Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and
\f[B]1\f[R] (exclusive) with the number of decimal digits after the
decimal point equal to the truncated absolute value of \f[B]p\f[R].
If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will
change the value of \f[B]seed\f[R].
If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and
\f[B]seed\f[R] is \f[I]not\f[R] changed.
.TP
\f[B]ifrand(i, p)\f[R]
Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive)
and the truncated absolute value of \f[B]i\f[R] (exclusive) with the
number of decimal digits after the decimal point equal to the truncated
absolute value of \f[B]p\f[R].
If the absolute value of \f[B]i\f[R] is greater than or equal to
\f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this
function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R]
is returned and \f[B]seed\f[R] is not changed.
.TP
\f[B]srand(x)\f[R]
Returns \f[B]x\f[R] with its sign flipped with probability
\f[B]0.5\f[R].
In other words, it randomizes the sign of \f[B]x\f[R].
.TP
\f[B]brand()\f[R]
Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]).
.TP
\f[B]band(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]and\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bor(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]or\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bxor(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]xor\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bshl(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of \f[B]a\f[R] bit-shifted left by
\f[B]b\f[R] places.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bshr(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the truncated result of \f[B]a\f[R]
bit-shifted right by \f[B]b\f[R] places.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnotn(x, n)\f[R]
Takes the truncated absolute value of \f[B]x\f[R] and does a bitwise not
as though it has the same number of bytes as the truncated absolute
value of \f[B]n\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot8(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]8\f[R] binary digits (1 unsigned byte).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot16(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]16\f[R] binary digits (2 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot32(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]32\f[R] binary digits (4 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot64(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]64\f[R] binary digits (8 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has the minimum number of power of two unsigned bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brevn(x, n)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has the same number of 8-bit bytes as the truncated absolute
value of \f[B]n\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev8(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 8 binary digits (1 unsigned byte).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev16(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 16 binary digits (2 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev32(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 32 binary digits (4 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev64(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 64 binary digits (8 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has the minimum number of power of two unsigned bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]broln(x, p, n)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the same number of unsigned 8-bit bytes as
the truncated absolute value of \f[B]n\f[R], by the number of places
equal to the truncated absolute value of \f[B]p\f[R] modded by the
\f[B]2\f[R] to the power of the number of binary digits in \f[B]n\f[R]
8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol8(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]8\f[R] binary digits (\f[B]1\f[R]
unsigned byte), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol16(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]16\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol32(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol64(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the minimum number of power of two
unsigned 8-bit bytes, by the number of places equal to the truncated
absolute value of \f[B]p\f[R] modded by 2 to the power of the number of
binary digits in the minimum number of 8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brorn(x, p, n)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the same number of unsigned 8-bit bytes as
the truncated absolute value of \f[B]n\f[R], by the number of places
equal to the truncated absolute value of \f[B]p\f[R] modded by the
\f[B]2\f[R] to the power of the number of binary digits in \f[B]n\f[R]
8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror8(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]8\f[R] binary digits (\f[B]1\f[R]
unsigned byte), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror16(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]16\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror32(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror64(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the minimum number of power of two
unsigned 8-bit bytes, by the number of places equal to the truncated
absolute value of \f[B]p\f[R] modded by 2 to the power of the number of
binary digits in the minimum number of 8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmodn(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of the multiplication of the truncated absolute
value of \f[B]n\f[R] and \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod8(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod16(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod32(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod64(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bunrev(t)\f[R]
Assumes \f[B]t\f[R] is a bitwise-reversed number with an extra set bit
one place more significant than the real most significant bit (which was
the least significant bit in the original number).
This number is reversed and returned without the extra set bit.
.RS
.PP
This function is used to implement other bitwise functions; it is not
meant to be used by users, but it can be.
.RE
.TP
+\f[B]plz(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed with a leading zero, regardless
+of the use of the \f[B]-z\f[R] option (see the \f[B]OPTIONS\f[R]
+section) and without a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, without a trailing newline.
+.RE
+.TP
+\f[B]plznl(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed with a leading zero, regardless
+of the use of the \f[B]-z\f[R] option (see the \f[B]OPTIONS\f[R]
+section) and with a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, with a trailing newline.
+.RE
+.TP
+\f[B]pnlz(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed without a leading zero,
+regardless of the use of the \f[B]-z\f[R] option (see the
+\f[B]OPTIONS\f[R] section) and without a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, without a trailing newline.
+.RE
+.TP
+\f[B]pnlznl(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed without a leading zero,
+regardless of the use of the \f[B]-z\f[R] option (see the
+\f[B]OPTIONS\f[R] section) and with a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, with a trailing newline.
+.RE
+.TP
\f[B]ubytes(x)\f[R]
Returns the numbers of unsigned integer bytes required to hold the
truncated absolute value of \f[B]x\f[R].
.TP
\f[B]sbytes(x)\f[R]
Returns the numbers of signed, two\[cq]s-complement integer bytes
required to hold the truncated value of \f[B]x\f[R].
.TP
\f[B]s2u(x)\f[R]
Returns \f[B]x\f[R] if it is non-negative.
If it \f[I]is\f[R] negative, then it calculates what \f[B]x\f[R] would
be as a 2\[cq]s-complement signed integer and returns the non-negative
integer that would have the same representation in binary.
.TP
\f[B]s2un(x,n)\f[R]
Returns \f[B]x\f[R] if it is non-negative.
If it \f[I]is\f[R] negative, then it calculates what \f[B]x\f[R] would
be as a 2\[cq]s-complement signed integer with \f[B]n\f[R] bytes and
returns the non-negative integer that would have the same representation
in binary.
If \f[B]x\f[R] cannot fit into \f[B]n\f[R] 2\[cq]s-complement signed
bytes, it is truncated to fit.
.TP
\f[B]hex(x)\f[R]
Outputs the hexadecimal (base \f[B]16\f[R]) representation of
\f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]binary(x)\f[R]
Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output(x, b)\f[R]
Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in as few power of two bytes as possible.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or is negative, an error message is
printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R]
section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in as few power of two bytes as
possible.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, an error message is printed instead,
but bc(1) is not reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uintn(x, n)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]n\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]intn(x, n)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint8(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]1\f[R] byte.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int8(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an
error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint16(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]2\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int16(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint32(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]4\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int32(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint64(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]8\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int64(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]hex_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R]
bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]binary_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see
the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output_byte(x, i)\f[R]
Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R],
where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes
- 1\f[R] is the most significant byte.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.SS Transcendental Functions
.PP
All transcendental functions can return slightly inaccurate results (up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)).
This is unavoidable, and this
article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains
why it is impossible and unnecessary to calculate exact results for the
transcendental functions.
.PP
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (\f[B]scale\f[R]) set to at least 1 higher
than is necessary.
If exact results are \f[I]absolutely\f[R] required, users can double the
precision (\f[B]scale\f[R]) and then truncate.
.PP
The transcendental functions in the standard math library are:
.IP \[bu] 2
\f[B]s(x)\f[R]
.IP \[bu] 2
\f[B]c(x)\f[R]
.IP \[bu] 2
\f[B]a(x)\f[R]
.IP \[bu] 2
\f[B]l(x)\f[R]
.IP \[bu] 2
\f[B]e(x)\f[R]
.IP \[bu] 2
\f[B]j(x, n)\f[R]
.PP
The transcendental functions in the extended math library are:
.IP \[bu] 2
\f[B]l2(x)\f[R]
.IP \[bu] 2
\f[B]l10(x)\f[R]
.IP \[bu] 2
\f[B]log(x, b)\f[R]
.IP \[bu] 2
\f[B]pi(p)\f[R]
.IP \[bu] 2
\f[B]t(x)\f[R]
.IP \[bu] 2
\f[B]a2(y, x)\f[R]
.IP \[bu] 2
\f[B]sin(x)\f[R]
.IP \[bu] 2
\f[B]cos(x)\f[R]
.IP \[bu] 2
\f[B]tan(x)\f[R]
.IP \[bu] 2
\f[B]atan(x)\f[R]
.IP \[bu] 2
\f[B]atan2(y, x)\f[R]
.IP \[bu] 2
\f[B]r2d(x)\f[R]
.IP \[bu] 2
\f[B]d2r(x)\f[R]
.SH RESET
.PP
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets.
This means that several things happen.
.PP
First, any functions 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.
.PP
Thus, when bc(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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.PP
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This bc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R]
can be queried with the \f[B]limits\f[R] statement.
.PP
In addition, this bc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bc(1):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bc(1) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]rand()\f[R]
operand.
Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
The actual values can be queried with the \f[B]limits\f[R] statement.
.PP
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
.PP
bc(1) recognizes the following environment variables:
.TP
\f[B]POSIXLY_CORRECT\f[R]
If this variable exists (no matter the contents), bc(1) behaves as if
the \f[B]-s\f[R] option was given.
.TP
\f[B]BC_ENV_ARGS\f[R]
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line arguments.
These are always processed first, so any files given in
\f[B]BC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 bc(1) runs.
.RS
.PP
The code that parses \f[B]BC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`bc' file.bc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]BC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]BC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length,
including the backslash (\f[B]\[rs]\f[R]).
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]BC_BANNER\f[R]
If this environment variable exists and contains an integer, then a
non-zero value activates the copyright banner when bc(1) is in
interactive mode, while zero deactivates it.
.RS
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
does not print the banner when not in interactive mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_SIGINT_RESET\f[R]
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes bc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then bc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use
TTY mode, and zero makes bc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a
prompt, and zero or a non-integer makes bc(1) not use a prompt.
If this environment variable does not exist and \f[B]BC_TTY_MODE\f[R]
does, then the value of the \f[B]BC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]BC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
bc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], 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, overflow when calculating the size of a number, and attempting
to use a non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift
(\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their
corresponding assignment operators.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an invalid
print statement, giving an invalid function definition, attempting to
assign to an expression that is not a named expression (see the
\f[I]Named Expressions\f[R] subsection of the \f[B]SYNTAX\f[R] section),
giving an invalid \f[B]auto\f[R] list, having a duplicate
\f[B]auto\f[R]/function parameter, failing to find the end of a code
block, attempting to return a value from a \f[B]void\f[R] function,
attempting to use a variable as a reference, and using any extensions
when the option \f[B]-s\f[R] or any equivalents were given.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors, passing the wrong number of
arguments to functions, attempting to call an undefined function, and
attempting to use a \f[B]void\f[R] function call as a value in an
expression.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
Fatal errors include memory allocation errors, I/O errors, failing to
open files, attempting to use files that do not have only ASCII
characters (bc(1) only accepts ASCII characters), attempting to open a
directory as a file, and giving invalid command-line options.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, bc(1)
always exits and returns \f[B]4\f[R], no matter what mode bc(1) is in.
.PP
The other statuses will only be returned when bc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
bc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Per the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, bc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
bc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]BC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, bc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]BC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, bc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]BC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then bc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]BC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]BC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]BC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]BC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]BC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause bc(1) to do one of two things.
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, bc(1) will exit.
.PP
However, if bc(1) is in interactive mode, and the
\f[B]BC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then bc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If bc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If bc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] is sent to bc(1) as it is
executing a file, it can seem as though bc(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
bc(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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause bc(1) to clean up and
exit, and it uses the default handler for all other signals.
.SH SEE ALSO
.PP
dc(1)
.SH STANDARDS
.PP
bc(1) is compliant with the IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
The flags \f[B]-efghiqsvVw\f[R], all long options, and the extensions
noted above are extensions to that specification.
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bc/HN.1.md b/manuals/bc/HN.1.md
index d61d15122bd8..d5b3324514ad 100644
--- a/manuals/bc/HN.1.md
+++ b/manuals/bc/HN.1.md
@@ -1,2251 +1,2313 @@
# NAME
bc - arbitrary-precision decimal arithmetic language and calculator
# SYNOPSIS
**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# DESCRIPTION
bc(1) is an interactive processor for a language first standardized in 1991 by
POSIX. (The current standard is [here][1].) The language provides unlimited
precision decimal arithmetic and is somewhat C-like, but there are differences.
Such differences will be noted in this document.
After parsing and handling options, this bc(1) reads any files given on the
command line and executes them before reading from **stdin**.
This bc(1) is a drop-in replacement for *any* bc(1), including (and
especially) the GNU bc(1). It also has many extensions and extra features beyond
other implementations.
**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
parse error, it is probably because a word this bc(1) reserves as a keyword is
used as the name of a function, variable, or array. To fix that, use the
command-line option **-r** *keyword*, where *keyword* is the keyword that is
used as a name in the script. For more information, see the **OPTIONS** section.
If parsing scripts meant for other bc(1) implementations still does not work,
that is a bug and should be reported. See the **BUGS** section.
# OPTIONS
The following are the options that bc(1) accepts.
**-g**, **-\-global-stacks**
: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks.
This has the effect that a copy of the current value of all four are pushed
onto a stack for every function call, as well as popped when every function
returns. This means that functions can assign to any and all of those
globals without worrying that the change will affect other functions.
Thus, a hypothetical function named **output(x,b)** that simply printed
**x** in base **b** could be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
(**Note**: the function **output(x,b)** exists in the extended math library.
See the **LIBRARY** section.)
However, since using this flag means that functions cannot set **ibase**,
**obase**, **scale**, or **seed** globally, functions that are made to do so
cannot work anymore. There are two possible use cases for that, and each has
a solution.
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set **ibase**, **obase**,
**scale**, or **seed** globally for any other purpose, it could be split
into one to four functions (based on how many globals it sets) and each of
those functions could return the desired value for a global.
For functions that set **seed**, the value assigned to **seed** is not
propagated to parent functions. This means that the sequence of
pseudo-random numbers that they see will not be the same sequence of
pseudo-random numbers that any parent sees. This is only the case once
**seed** has been set.
If a function desires to not affect the sequence of pseudo-random numbers
of its parents, but wants to use the same **seed**, it can use the following
line:
seed = seed
If the behavior of this option is desired for every run of bc(1), then users
could make sure to define **BC_ENV_ARGS** and include this option (see the
**ENVIRONMENT VARIABLES** section for more details).
If **-s**, **-w**, or any equivalents are used, this option is ignored.
This is a **non-portable extension**.
**-h**, **-\-help**
: Prints a usage message and quits.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-l**, **-\-mathlib**
: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
math library and the extended math library before running any code,
including any expressions or files specified on the command line.
To learn what is in the libraries, see the **LIBRARY** section.
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in bc(1). Most of those users
would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section).
These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of bc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **read()** built-in function is called.
These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-r** *keyword*, **-\-redefine**=*keyword*
: Redefines *keyword* in order to allow it to be used as a function, variable,
or array name. This is useful when this bc(1) gives parse errors when
parsing scripts meant for other bc(1) implementations.
The keywords this bc(1) allows to be redefined are:
* **abs**
* **asciify**
* **continue**
* **divmod**
* **else**
* **halt**
* **irand**
* **last**
* **limits**
* **maxibase**
* **maxobase**
* **maxrand**
* **maxscale**
* **modexp**
* **print**
* **rand**
* **read**
* **seed**
* **stream**
If any of those keywords are used as a function, variable, or array name in
a script, use this option with the keyword as the argument. If multiple are
used, use this option for all of them; it can be used multiple times.
Keywords are *not* redefined when parsing the builtin math library (see the
**LIBRARY** section).
It is a fatal error to redefine keywords mandated by the POSIX standard. It
is a fatal error to attempt to redefine words that this bc(1) does not
reserve as keywords.
**-q**, **-\-quiet**
: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
Without this option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the **-v**, **-V**, or
**-\-version** options are given.
This is a **non-portable extension**.
**-s**, **-\-standard**
: Process exactly the language defined by the [standard][1] and error if any
extensions are used.
This is a **non-portable extension**.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
This is a **non-portable extension**.
**-w**, **-\-warn**
: Like **-s** and **-\-standard**, except that warnings (and not errors) are
printed for non-standard extensions and execution continues normally.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
**-\-expression** options, then bc(1) read from **stdin**.
However, there are a few caveats to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
the parse cannot complete. That means that starting a string without ending it
or starting a function, **if** statement, or loop without ending it will also
cause bc(1) to not execute.
Second, after an **if** statement, bc(1) doesn't know if an **else** statement
will follow, so it will not execute until it knows there will not be an **else**
statement.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **bc >&-**, it will quit with an error. This
is done so that bc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This
is done so that bc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences. This
bc(1) follows the [POSIX standard][1], which is a much more thorough resource
for the language this bc(1) accepts. This section is meant to be a summary and a
listing of all the extensions to the standard.
In the sections below, **E** means expression, **S** means statement, and **I**
means identifier.
Identifiers (**I**) start with a lowercase letter and can be followed by any
number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
Identifiers with more than one character (letter) are a
**non-portable extension**.
**ibase** is a global variable determining how to interpret constant numbers. It
is the "input" base, or the number base used for interpreting input numbers.
**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
(**-\-warn**) flags were not given on the command line, the max allowable value
for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
**ibase** is **2**. The max allowable value for **ibase** can be queried in
bc(1) programs with the **maxibase()** built-in function.
**obase** is a global variable determining how to output results. It is the
"output" base, or the number base used for outputting numbers. **obase** is
initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
can be queried in bc(1) programs with the **maxobase()** built-in function. The
min allowable value for **obase** is **0**. If **obase** is **0**, values are
output in scientific notation, and if **obase** is **1**, values are output in
engineering notation. Otherwise, values are output in the specified base.
Outputting in scientific and engineering notations are **non-portable
extensions**.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a global variable that
sets the precision of any operations, with exceptions. **scale** is initially
**0**. **scale** cannot be negative. The max allowable value for **scale** is
**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
built-in function.
bc(1) has both *global* variables and *local* variables. All *local*
variables are local to the function; they are parameters or are introduced in
the **auto** list of a function (see the **FUNCTIONS** section). If a variable
is accessed which is not a parameter or in the **auto** list, it is assumed to
be *global*. If a parent function has a *local* variable version of a variable
that a child function considers *global*, the value of that *global* variable in
the child function is the value of the variable in the parent function, not the
value of the actual *global* variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence operator is an
assignment operator *and* the expression is notsurrounded by parentheses.
The value that is printed is also assigned to the special variable **last**. A
single dot (**.**) may also be used as a synonym for **last**. These are
**non-portable extensions**.
Either semicolons or newlines may separate statements.
## Comments
There are two kinds of comments:
1. Block comments are enclosed in **/\*** and **\*/**.
2. Line comments go from **#** until, and not including, the next newline. This
is a **non-portable extension**.
## Named Expressions
The following are named expressions in bc(1):
1. Variables: **I**
2. Array Elements: **I[E]**
3. **ibase**
4. **obase**
5. **scale**
6. **seed**
7. **last** or a single dot (**.**)
Numbers 6 and 7 are **non-portable extensions**.
The meaning of **seed** is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major versions.
The *scale* and sign of the value may be significant.
If a previously used **seed** value is assigned to **seed** and used again, the
pseudo-random number generator is guaranteed to produce the same sequence of
pseudo-random numbers as it did when the **seed** value was previously used.
The exact value assigned to **seed** is not guaranteed to be returned if
**seed** is queried again immediately. However, if **seed** *does* return a
different value, both values, when assigned to **seed**, are guaranteed to
produce the same sequence of pseudo-random numbers. This means that certain
values assigned to **seed** will *not* produce unique sequences of pseudo-random
numbers. The value of **seed** will change after any use of the **rand()** and
**irand(E)** operands (see the *Operands* subsection below), except if the
parameter passed to **irand(E)** is **0**, **1**, or negative.
There is no limit to the length (number of significant decimal digits) or
*scale* of the value that can be assigned to **seed**.
Variables and arrays do not interfere; users can have arrays named the same as
variables. This also applies to functions (see the **FUNCTIONS** section), so a
user can have a variable, array, and function that all have the same name, and
they will not shadow each other, whether inside of functions or not.
Named expressions are required as the operand of **increment**/**decrement**
operators and as the left side of **assignment** operators (see the *Operators*
subsection).
## Operands
The following are valid operands in bc(1):
1. Numbers (see the *Numbers* subsection below).
2. Array indices (**I[E]**).
3. **(E)**: The value of **E** (used to change precedence).
4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
5. **length(E)**: The number of significant decimal digits in **E**. Returns
**1** for **0** with no decimal places. If given a string, the length of the
string is returned. Passing a string to **length(E)** is a **non-portable
extension**.
6. **length(I[])**: The number of elements in the array **I**. This is a
**non-portable extension**.
7. **scale(E)**: The *scale* of **E**.
8. **abs(E)**: The absolute value of **E**. This is a **non-portable
extension**.
9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
the base, the second is the exponent, and the third is the modulus. All
three values must be integers. The second argument must be non-negative. The
third argument must be non-zero. This is a **non-portable extension**.
10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
optimization. The first expression is the dividend, and the second is the
divisor, which must be non-zero. The return value is the quotient, and the
modulus is stored in index **0** of the provided array (the last argument).
This is a **non-portable extension**.
11. **asciify(E)**: If **E** is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number mod **256**
and returns that number as a one-character string. This is a **non-portable
extension**.
12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a non-**void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
13. **read()**: Reads a line from **stdin** and uses that as an expression. The
result of that expression is the result of the **read()** operand. This is a
**non-portable extension**.
14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
extension**.
15. **maxobase()**: The max allowable **obase**. This is a **non-portable
extension**.
16. **maxscale()**: The max allowable **scale**. This is a **non-portable
extension**.
-17. **rand()**: A pseudo-random integer between **0** (inclusive) and
+17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
+ **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
+18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
+ or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
+ or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+20. **rand()**: A pseudo-random integer between **0** (inclusive) and
**BC_RAND_MAX** (inclusive). Using this operand will change the value of
**seed**. This is a **non-portable extension**.
-18. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
+21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
value of **E** (exclusive). If **E** is negative or is a non-integer
(**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see
the **RESET** section) while **seed** remains unchanged. If **E** is larger
than **BC_RAND_MAX**, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
**BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that
can be generated with this operand is unbounded. Using this operand will
change the value of **seed**, unless the value of **E** is **0** or **1**.
In that case, **0** is returned, and **seed** is *not* changed. This is a
**non-portable extension**.
-19. **maxrand()**: The max integer returned by **rand()**. This is a
+22. **maxrand()**: The max integer returned by **rand()**. This is a
**non-portable extension**.
The integers generated by **rand()** and **irand(E)** are guaranteed to be as
unbiased as possible, subject to the limitations of the pseudo-random number
generator.
**Note**: The values returned by the pseudo-random number generator with
**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator. However,
they *are* guaranteed to be reproducible with identical **seed** values. This
means that the pseudo-random values from bc(1) should only be used where a
reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
use a non-seeded pseudo-random number generator.
## Numbers
Numbers are strings made up of digits, uppercase letters, and at most **1**
period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
letters are equal to **9** + their position in the alphabet (i.e., **A** equals
**10**, or **9+1**). If a digit or letter makes no sense with the current value
of **ibase**, they are set to the value of the highest valid digit in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **Z** alone always equals decimal
**35**.
In addition, bc(1) accepts numbers in scientific notation. These have the form
**\e\**. The exponent (the portion after the **e**) must be
an integer. An example is **1.89237e9**, which is equal to **1892370000**.
Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**.
Using scientific notation is an error or warning if the **-s** or **-w**,
respectively, command-line options (or equivalents) are given.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For example,
if **ibase** is **16** and bc(1) is given the number string **FFeA**, the
resulting decimal number will be **2550000000000**, and if bc(1) is given the
number string **10e-4**, the resulting decimal number will be **0.0016**.
Accepting input as scientific notation is a **non-portable extension**.
## Operators
The following arithmetic and logical operators can be used. They are listed in
order of decreasing precedence. Operators in the same group have the same
precedence.
**++** **-\-**
: Type: Prefix and Postfix
Associativity: None
Description: **increment**, **decrement**
**-** **!**
: Type: Prefix
Associativity: None
Description: **negation**, **boolean not**
**\$**
: Type: Postfix
Associativity: None
Description: **truncation**
**\@**
: Type: Binary
Associativity: Right
Description: **set precision**
**\^**
: Type: Binary
Associativity: Right
Description: **power**
**\*** **/** **%**
: Type: Binary
Associativity: Left
Description: **multiply**, **divide**, **modulus**
**+** **-**
: Type: Binary
Associativity: Left
Description: **add**, **subtract**
**\<\<** **\>\>**
: Type: Binary
Associativity: Left
Description: **shift left**, **shift right**
**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
: Type: Binary
Associativity: Right
Description: **assignment**
**==** **\<=** **\>=** **!=** **\<** **\>**
: Type: Binary
Associativity: Left
Description: **relational**
**&&**
: Type: Binary
Associativity: Left
Description: **boolean and**
**||**
: Type: Binary
Associativity: Left
Description: **boolean or**
The operators will be described in more detail below.
**++** **-\-**
: The prefix and postfix **increment** and **decrement** operators behave
exactly like they would in C. They require a named expression (see the
*Named Expressions* subsection) as an operand.
The prefix versions of these operators are more efficient; use them where
possible.
**-**
: The **negation** operator returns **0** if a user attempts to negate any
expression with the value **0**. Otherwise, a copy of the expression with
its sign flipped is returned.
**!**
: The **boolean not** operator returns **1** if the expression is **0**, or
**0** otherwise.
This is a **non-portable extension**.
**\$**
: The **truncation** operator returns a copy of the given expression with all
of its *scale* removed.
This is a **non-portable extension**.
**\@**
: The **set precision** operator takes two expressions and returns a copy of
the first with its *scale* equal to the value of the second expression. That
could either mean that the number is returned without change (if the
*scale* of the first expression matches the value of the second
expression), extended (if it is less), or truncated (if it is more).
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**\^**
: The **power** operator (not the **exclusive or** operator, as it would be in
C) takes two expressions and raises the first to the power of the value of
the second. The *scale* of the result is equal to **scale**.
The second expression must be an integer (no *scale*), and if it is
negative, the first value must be non-zero.
**\***
: The **multiply** operator takes two expressions, multiplies them, and
returns the product. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result is
equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The **divide** operator takes two expressions, divides them, and returns the
quotient. The *scale* of the result shall be the value of **scale**.
The second expression must be non-zero.
**%**
: The **modulus** operator takes two expressions, **a** and **b**, and
evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The second expression must be non-zero.
**+**
: The **add** operator takes two expressions, **a** and **b**, and returns the
sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
**-**
: The **subtract** operator takes two expressions, **a** and **b**, and
returns the difference, with a *scale* equal to the max of the *scale*s of
**a** and **b**.
**\<\<**
: The **left shift** operator takes two expressions, **a** and **b**, and
returns a copy of the value of **a** with its decimal point moved **b**
places to the right.
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**\>\>**
: The **right shift** operator takes two expressions, **a** and **b**, and
returns a copy of the value of **a** with its decimal point moved **b**
places to the left.
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
: The **assignment** operators take two expressions, **a** and **b** where
**a** is a named expression (see the *Named Expressions* subsection).
For **=**, **b** is copied and the result is assigned to **a**. For all
others, **a** and **b** are applied as operands to the corresponding
arithmetic operator and the result is assigned to **a**.
The **assignment** operators that correspond to operators that are
extensions are themselves **non-portable extensions**.
**==** **\<=** **\>=** **!=** **\<** **\>**
: The **relational** operators compare two expressions, **a** and **b**, and
if the relation holds, according to C language semantics, the result is
**1**. Otherwise, it is **0**.
Note that unlike in C, these operators have a lower precedence than the
**assignment** operators, which means that **a=b\>c** is interpreted as
**(a=b)\>c**.
Also, unlike the [standard][1] requires, these operators can appear anywhere
any other expressions can be used. This allowance is a
**non-portable extension**.
**&&**
: The **boolean and** operator takes two expressions and returns **1** if both
expressions are non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
**||**
: The **boolean or** operator takes two expressions and returns **1** if one
of the expressions is non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
## Statements
The following items are statements:
1. **E**
2. **{** **S** **;** ... **;** **S** **}**
3. **if** **(** **E** **)** **S**
4. **if** **(** **E** **)** **S** **else** **S**
5. **while** **(** **E** **)** **S**
6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
7. An empty statement
8. **break**
9. **continue**
10. **quit**
11. **halt**
12. **limits**
13. A string of characters, enclosed in double quotes
14. **print** **E** **,** ... **,** **E**
15. **stream** **E** **,** ... **,** **E**
16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
Also, as a **non-portable extension**, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expression) is
omitted, it is assumed to be a constant **1**.
The **break** statement causes a loop to stop iterating and resume execution
immediately following a loop. This is only allowed in loops.
The **continue** statement causes a loop iteration to stop early and returns to
the start of the loop, including testing the loop condition. This is only
allowed in loops.
The **if** **else** statement does the same thing as in C.
The **quit** statement causes bc(1) to quit, even if it is on a branch that will
not be executed (it is a compile-time command).
The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
if it is on a branch of an **if** statement that is not executed, bc(1) does not
quit.)
The **limits** statement prints the limits that this bc(1) is subject to. This
is like the **quit** statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a newline.
Both scientific notation and engineering notation are available for printing the
results of expressions. Scientific notation is activated by assigning **0** to
**obase**, and engineering notation is activated by assigning **1** to
**obase**. To deactivate them, just assign a different value to **obase**.
Scientific notation and engineering notation are disabled if bc(1) is run with
either the **-s** or **-w** command-line options (or equivalents).
Printing numbers in scientific notation and/or engineering notation is a
**non-portable extension**.
## Strings
If strings appear as a statement by themselves, they are printed without a
trailing newline.
In addition to appearing as a lone statement by themselves, strings can be
assigned to variables and array elements. They can also be passed to functions
in variable parameters.
If any statement that expects a string is given a variable that had a string
assigned to it, the statement acts as though it had received a string.
If any math operation is attempted on a string or a variable or array element
that has been assigned a string, an error is raised, and bc(1) resets (see the
**RESET** section).
Assigning strings to variables and array elements and passing them to functions
are **non-portable extensions**.
## Print Statement
The "expressions" in a **print** statement may also be strings. If they are, there
are backslash escape sequences that are interpreted specially. What those
sequences are, and what they cause to be printed, are shown below:
**\\a**: **\\a**
**\\b**: **\\b**
**\\\\**: **\\**
**\\e**: **\\**
**\\f**: **\\f**
**\\n**: **\\n**
**\\q**: **"**
**\\r**: **\\r**
**\\t**: **\\t**
Any other character following a backslash causes the backslash and character to
be printed as-is.
Any non-string expression in a print statement shall be assigned to **last**,
like any other expression that is printed.
## Stream Statement
The "expressions in a **stream** statement may also be strings.
If a **stream** statement is given a string, it prints the string as though the
string had appeared as its own statement. In other words, the **stream**
statement prints strings normally, without a newline.
If a **stream** statement is given a number, a copy of it is truncated and its
absolute value is calculated. The result is then printed as though **obase** is
**256** and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
## Order of Evaluation
All expressions in a statment are evaluated left to right, except as necessary
to maintain order of operations. This means, for example, assuming that **i** is
equal to **0**, in the expression
a[i++] = i++
the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
at the end of the expression.
This includes function arguments. Thus, assuming **i** is equal to **0**, this
means that in the expression
x(i++, i++)
the first argument passed to **x()** is **0**, and the second argument is **1**,
while **i** is equal to **2** before the function starts executing.
# FUNCTIONS
Function definitions are as follows:
```
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
```
Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
make a parameter or **auto** var an array, and any **I** in the parameter list
may be replaced with **\*I[]** to make a parameter an array reference. Callers
of functions that take array references should not put an asterisk in the call;
they must be called with just **I[]** like normal array parameters and will be
automatically converted into references.
As a **non-portable extension**, the opening brace of a **define** statement may
appear on the next line.
As a **non-portable extension**, the return statement may also be in one of the
following forms:
1. **return**
2. **return** **(** **)**
3. **return** **E**
The first two, or not specifying a **return** statement, is equivalent to
**return (0)**, unless the function is a **void** function (see the *Void
Functions* subsection below).
## Void Functions
Functions can also be **void** functions, defined as follows:
```
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
```
They can only be used as standalone expressions, where such an expression would
be printed alone, except in a print statement.
Void functions can only use the first two **return** statements listed above.
They can also omit the return statement entirely.
The word "void" is not treated as a keyword; it is still possible to have
variables, arrays, and functions named **void**. The word "void" is only
treated specially right after the **define** keyword.
This is a **non-portable extension**.
## Array References
For any array in the parameter list, if the array is declared in the form
```
*I[]
```
it is a **reference**. Any changes to the array in the function are reflected,
when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a **non-portable extension**.
# LIBRARY
All of the functions below, including the functions in the extended math
library (see the *Extended Library* subsection below), are available when the
**-l** or **-\-mathlib** command-line flags are given, except that the extended
math library is not available when the **-s** option, the **-w** option, or
equivalents are given.
## Standard Library
The [standard][1] defines the following functions for the math library:
**s(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**c(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a(x)**
: Returns the arctangent of **x**, in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l(x)**
: Returns the natural logarithm of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**e(x)**
: Returns the mathematical constant **e** raised to the power of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**j(x, n)**
: Returns the bessel integer order **n** (truncated) of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
## Extended Library
The extended library is *not* loaded when the **-s**/**-\-standard** or
**-w**/**-\-warn** options are given since they are not part of the library
defined by the [standard][1].
The extended library is a **non-portable extension**.
**p(x, y)**
: Calculates **x** to the power of **y**, even if **y** is not an integer, and
returns the result to the current **scale**.
It is an error if **y** is negative and **x** is **0**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**r(x, p)**
: Returns **x** rounded to **p** decimal places according to the rounding mode
[round half away from **0**][3].
**ceil(x, p)**
: Returns **x** rounded to **p** decimal places according to the rounding mode
[round away from **0**][6].
**f(x)**
: Returns the factorial of the truncated absolute value of **x**.
**perm(n, k)**
: Returns the permutation of the truncated absolute value of **n** of the
truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
**comb(n, k)**
: Returns the combination of the truncated absolute value of **n** of the
truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
**l2(x)**
: Returns the logarithm base **2** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l10(x)**
: Returns the logarithm base **10** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**log(x, b)**
: Returns the logarithm base **b** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**cbrt(x)**
: Returns the cube root of **x**.
**root(x, n)**
: Calculates the truncated value of **n**, **r**, and returns the **r**th root
of **x** to the current **scale**.
If **r** is **0** or negative, this raises an error and causes bc(1) to
reset (see the **RESET** section). It also raises an error and causes bc(1)
to reset if **r** is even and **x** is negative.
**gcd(a, b)**
: Returns the greatest common divisor (factor) of the truncated absolute value
of **a** and the truncated absolute value of **b**.
**lcm(a, b)**
: Returns the least common multiple of the truncated absolute value of **a**
and the truncated absolute value of **b**.
**pi(p)**
: Returns **pi** to **p** decimal places.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**t(x)**
: Returns the tangent of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a2(y, x)**
: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
equal to **0**, it raises an error and causes bc(1) to reset (see the
**RESET** section). Otherwise, if **x** is greater than **0**, it returns
**a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
**0**, and **y** is less than **0**, it returns **-pi/2**.
This function is the same as the **atan2()** function in many programming
languages.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**sin(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is an alias of **s(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**cos(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is an alias of **c(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**tan(x)**
: Returns the tangent of **x**, which is assumed to be in radians.
If **x** is equal to **1** or **-1**, this raises an error and causes bc(1)
to reset (see the **RESET** section).
This is an alias of **t(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**atan(x)**
: Returns the arctangent of **x**, in radians.
This is an alias of **a(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**atan2(y, x)**
: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
equal to **0**, it raises an error and causes bc(1) to reset (see the
**RESET** section). Otherwise, if **x** is greater than **0**, it returns
**a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
**0**, and **y** is less than **0**, it returns **-pi/2**.
This function is the same as the **atan2()** function in many programming
languages.
This is an alias of **a2(y, x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**r2d(x)**
: Converts **x** from radians to degrees and returns the result.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**d2r(x)**
: Converts **x** from degrees to radians and returns the result.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**frand(p)**
: Generates a pseudo-random number between **0** (inclusive) and **1**
(exclusive) with the number of decimal digits after the decimal point equal
to the truncated absolute value of **p**. If **p** is not **0**, then
calling this function will change the value of **seed**. If **p** is **0**,
then **0** is returned, and **seed** is *not* changed.
**ifrand(i, p)**
: Generates a pseudo-random number that is between **0** (inclusive) and the
truncated absolute value of **i** (exclusive) with the number of decimal
digits after the decimal point equal to the truncated absolute value of
**p**. If the absolute value of **i** is greater than or equal to **2**, and
**p** is not **0**, then calling this function will change the value of
**seed**; otherwise, **0** is returned and **seed** is not changed.
**srand(x)**
: Returns **x** with its sign flipped with probability **0.5**. In other
words, it randomizes the sign of **x**.
**brand()**
: Returns a random boolean value (either **0** or **1**).
**band(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **and** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bor(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **or** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bxor(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **xor** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bshl(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of **a** bit-shifted left by **b** places.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bshr(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the truncated result of **a** bit-shifted right by **b** places.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bnotn(x, n)**
: Takes the truncated absolute value of **x** and does a bitwise not as though
it has the same number of bytes as the truncated absolute value of **n**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot8(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**8** binary digits (1 unsigned byte).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot16(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**16** binary digits (2 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot32(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**32** binary digits (4 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot64(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**64** binary digits (8 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
the minimum number of power of two unsigned bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brevn(x, n)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has the same number of 8-bit bytes as the truncated absolute value of **n**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev8(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 8 binary digits (1 unsigned byte).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev16(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 16 binary digits (2 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev32(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 32 binary digits (4 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev64(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 64 binary digits (8 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has the minimum number of power of two unsigned bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**broln(x, p, n)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has the same number of unsigned 8-bit bytes as the truncated
absolute value of **n**, by the number of places equal to the truncated
absolute value of **p** modded by the **2** to the power of the number of
binary digits in **n** 8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol8(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **8** binary digits (**1** unsigned byte), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol16(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **16** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol32(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **32** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol64(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **64** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has the minimum number of power of two unsigned 8-bit bytes, by
the number of places equal to the truncated absolute value of **p** modded
by 2 to the power of the number of binary digits in the minimum number of
8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brorn(x, p, n)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has the same number of unsigned 8-bit bytes as the truncated
absolute value of **n**, by the number of places equal to the truncated
absolute value of **p** modded by the **2** to the power of the number of
binary digits in **n** 8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror8(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **8** binary digits (**1** unsigned byte), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror16(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **16** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror32(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **32** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror64(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **64** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has the minimum number of power of two unsigned 8-bit bytes, by
the number of places equal to the truncated absolute value of **p** modded
by 2 to the power of the number of binary digits in the minimum number of
8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmodn(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of the multiplication of the truncated absolute value of **n** and
**8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod8(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod16(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod32(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod64(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bunrev(t)**
: Assumes **t** is a bitwise-reversed number with an extra set bit one place
more significant than the real most significant bit (which was the least
significant bit in the original number). This number is reversed and
returned without the extra set bit.
This function is used to implement other bitwise functions; it is not meant
to be used by users, but it can be.
+**plz(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed with a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and without a trailing newline.
+
+ Otherwise, **x** is printed normally, without a trailing newline.
+
+**plznl(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed with a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and with a trailing newline.
+
+ Otherwise, **x** is printed normally, with a trailing newline.
+
+**pnlz(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed without a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and without a trailing newline.
+
+ Otherwise, **x** is printed normally, without a trailing newline.
+
+**pnlznl(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed without a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and with a trailing newline.
+
+ Otherwise, **x** is printed normally, with a trailing newline.
+
**ubytes(x)**
: Returns the numbers of unsigned integer bytes required to hold the truncated
absolute value of **x**.
**sbytes(x)**
: Returns the numbers of signed, two's-complement integer bytes required to
hold the truncated value of **x**.
**s2u(x)**
: Returns **x** if it is non-negative. If it *is* negative, then it calculates
what **x** would be as a 2's-complement signed integer and returns the
non-negative integer that would have the same representation in binary.
**s2un(x,n)**
: Returns **x** if it is non-negative. If it *is* negative, then it calculates
what **x** would be as a 2's-complement signed integer with **n** bytes and
returns the non-negative integer that would have the same representation in
binary. If **x** cannot fit into **n** 2's-complement signed bytes, it is
truncated to fit.
**hex(x)**
: Outputs the hexadecimal (base **16**) representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**binary(x)**
: Outputs the binary (base **2**) representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output(x, b)**
: Outputs the base **b** representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in as few power of two bytes as possible. Both outputs are
split into bytes separated by spaces.
If **x** is not an integer or is negative, an error message is printed
instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in as few power of two bytes as possible. Both
outputs are split into bytes separated by spaces.
If **x** is not an integer, an error message is printed instead, but bc(1)
is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uintn(x, n)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **n** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **n** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**intn(x, n)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **n** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **n** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint8(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **1** byte. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **1** byte, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int8(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **1** byte. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **1** byte, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint16(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **2** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **2** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int16(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **2** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **2** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint32(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **4** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **4** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int32(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **4** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **4** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint64(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **8** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **8** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int64(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **8** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **8** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**hex_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in hexadecimal using **n** bytes. Not all of the value will
be output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**binary_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in binary using **n** bytes. Not all of the value will be
output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in the current **obase** (see the **SYNTAX** section) using
**n** bytes. Not all of the value will be output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output_byte(x, i)**
: Outputs byte **i** of the truncated absolute value of **x**, where **0** is
the least significant byte and **number_of_bytes - 1** is the most
significant byte.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
## Transcendental Functions
All transcendental functions can return slightly inaccurate results (up to 1
[ULP][4]). This is unavoidable, and [this article][5] explains why it is
impossible and unnecessary to calculate exact results for the transcendental
functions.
Because of the possible inaccuracy, I recommend that users call those functions
with the precision (**scale**) set to at least 1 higher than is necessary. If
exact results are *absolutely* required, users can double the precision
(**scale**) and then truncate.
The transcendental functions in the standard math library are:
* **s(x)**
* **c(x)**
* **a(x)**
* **l(x)**
* **e(x)**
* **j(x, n)**
The transcendental functions in the extended math library are:
* **l2(x)**
* **l10(x)**
* **log(x, b)**
* **pi(p)**
* **t(x)**
* **a2(y, x)**
* **sin(x)**
* **cos(x)**
* **tan(x)**
* **atan(x)**
* **atan2(y, x)**
* **r2d(x)**
* **d2r(x)**
# RESET
When bc(1) encounters an error or a signal that it has a non-default handler
for, it resets. This means that several things happen.
First, any functions 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.
Thus, when bc(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.
Note that this reset behavior is different from the GNU bc(1), which attempts to
start executing the statement right after the one that caused an error.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This bc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
the **limits** statement.
In addition, this bc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bc(1):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bc(1) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_STRING_MAX**
: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
**BC_NAME_MAX**
: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
**BC_RAND_MAX**
: The maximum integer (inclusive) returned by the **rand()** operand. Set at
**2\^BC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
The actual values can be queried with the **limits** statement.
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.
# ENVIRONMENT VARIABLES
bc(1) recognizes the following environment variables:
**POSIXLY_CORRECT**
: If this variable exists (no matter the contents), bc(1) behaves as if
the **-s** option was given.
**BC_ENV_ARGS**
: This is another way to give command-line arguments to bc(1). They should be
in the same format as all other command-line arguments. These are always
processed first, so any files given in **BC_ENV_ARGS** 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 bc(1) runs.
The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
**"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'bc' file.bc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **BC_ENV_ARGS** 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.
**BC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
lines to that length, including the backslash (**\\**). The default line
length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**BC_BANNER**
: If this environment variable exists and contains an integer, then a non-zero
value activates the copyright banner when bc(1) is in interactive mode,
while zero deactivates it.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) does not print
the banner when not in interactive mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_SIGINT_RESET**
: If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) exits on
**SIGINT** when not in interactive mode.
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1) reset
on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
environment variable exists and is *not* an integer, then bc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use TTY
mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a prompt,
and zero or a non-integer makes bc(1) not use a prompt. If this environment
variable does not exist and **BC_TTY_MODE** does, then the value of the
**BC_TTY_MODE** environment variable is used.
This environment variable and the **BC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
bc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, 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, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**)
operators and their corresponding assignment operators.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, using a token where it is invalid,
giving an invalid expression, giving an invalid print statement, giving an
invalid function definition, attempting to assign to an expression that is
not a named expression (see the *Named Expressions* subsection of the
**SYNTAX** section), giving an invalid **auto** list, having a duplicate
**auto**/function parameter, failing to find the end of a code block,
attempting to return a value from a **void** function, attempting to use a
variable as a reference, and using any extensions when the option **-s** or
any equivalents were given.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors, passing the
wrong number of arguments to functions, attempting to call an undefined
function, and attempting to use a **void** function call as a value in an
expression.
**4**
: A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, failing to open
files, attempting to use files that do not have only ASCII characters (bc(1)
only accepts ASCII characters), attempting to open a directory as a file,
and giving invalid command-line options.
The exit status **4** is special; when a fatal error occurs, bc(1) always exits
and returns **4**, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interactive mode
(see the **INTERACTIVE MODE** section), since bc(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
**-i** flag or **-\-interactive** option.
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **BC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **BC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
mode on.
If the environment variable **BC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **BC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, bc(1) will
exit.
However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
default is an integer and non-zero, then bc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If bc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If bc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
can seem as though bc(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 bc(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.
**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
default handler for all other signals.
# SEE ALSO
dc(1)
# STANDARDS
bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
specification. The flags **-efghiqsvVw**, all long options, and the extensions
noted above are extensions to that specification.
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
diff --git a/manuals/bc/N.1 b/manuals/bc/N.1
index f5dc39a246c4..56fca3d02b4d 100644
--- a/manuals/bc/N.1
+++ b/manuals/bc/N.1
@@ -1,2692 +1,2777 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH NAME
.PP
bc - arbitrary-precision decimal arithmetic language and calculator
.SH SYNOPSIS
.PP
\f[B]bc\f[R] [\f[B]-ghilPqRsvVw\f[R]] [\f[B]--global-stacks\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]]
[\f[B]--no-prompt\f[R]] [\f[B]--no-read-prompt\f[R]] [\f[B]--quiet\f[R]]
[\f[B]--standard\f[R]] [\f[B]--warn\f[R]] [\f[B]--version\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
bc(1) is an interactive processor for a language first standardized in
1991 by POSIX.
(The current standard is
here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).)
The language provides unlimited precision decimal arithmetic and is
somewhat C-like, but there are differences.
Such differences will be noted in this document.
.PP
After parsing and handling options, this bc(1) reads any files given on
the command line and executes them before reading from \f[B]stdin\f[R].
.PP
This bc(1) is a drop-in replacement for \f[I]any\f[R] bc(1), including
(and especially) the GNU bc(1).
It also has many extensions and extra features beyond other
implementations.
.PP
\f[B]Note\f[R]: If running this bc(1) on \f[I]any\f[R] script meant for
another bc(1) gives a parse error, it is probably because a word this
bc(1) reserves as a keyword is used as the name of a function, variable,
or array.
To fix that, use the command-line option \f[B]-r\f[R] \f[I]keyword\f[R],
where \f[I]keyword\f[R] is the keyword that is used as a name in the
script.
For more information, see the \f[B]OPTIONS\f[R] section.
.PP
If parsing scripts meant for other bc(1) implementations still does not
work, that is a bug and should be reported.
See the \f[B]BUGS\f[R] section.
.SH OPTIONS
.PP
The following are the options that bc(1) accepts.
.TP
\f[B]-g\f[R], \f[B]--global-stacks\f[R]
Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and
\f[B]seed\f[R] into stacks.
.RS
.PP
This has the effect that a copy of the current value of all four are
pushed onto a stack for every function call, as well as popped when
every function returns.
This means that functions can assign to any and all of those globals
without worrying that the change will affect other functions.
Thus, a hypothetical function named \f[B]output(x,b)\f[R] that simply
printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this:
.IP
.nf
\f[C]
define void output(x, b) {
obase=b
x
}
\f[R]
.fi
.PP
instead of like this:
.IP
.nf
\f[C]
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
\f[R]
.fi
.PP
This makes writing functions much easier.
.PP
(\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the
extended math library.
See the \f[B]LIBRARY\f[R] section.)
.PP
However, since using this flag means that functions cannot set
\f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R]
globally, functions that are made to do so cannot work anymore.
There are two possible use cases for that, and each has a solution.
.PP
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases.
Examples:
.IP
.nf
\f[C]
alias d2o=\[dq]bc -e ibase=A -e obase=8\[dq]
alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq]
\f[R]
.fi
.PP
Second, if the purpose of a function is to set \f[B]ibase\f[R],
\f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] globally for any
other purpose, it could be split into one to four functions (based on
how many globals it sets) and each of those functions could return the
desired value for a global.
.PP
For functions that set \f[B]seed\f[R], the value assigned to
\f[B]seed\f[R] is not propagated to parent functions.
This means that the sequence of pseudo-random numbers that they see will
not be the same sequence of pseudo-random numbers that any parent sees.
This is only the case once \f[B]seed\f[R] has been set.
.PP
If a function desires to not affect the sequence of pseudo-random
numbers of its parents, but wants to use the same \f[B]seed\f[R], it can
use the following line:
.IP
.nf
\f[C]
seed = seed
\f[R]
.fi
.PP
If the behavior of this option is desired for every run of bc(1), then
users could make sure to define \f[B]BC_ENV_ARGS\f[R] and include this
option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more
details).
.PP
If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option
is ignored.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-l\f[R], \f[B]--mathlib\f[R]
Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R]
and loads the included math library and the extended math library before
running any code, including any expressions or files specified on the
command line.
.RS
.PP
To learn what is in the libraries, see the \f[B]LIBRARY\f[R] section.
.RE
.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.RS
.PP
These options override the \f[B]BC_PROMPT\f[R] and \f[B]BC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of bc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]read()\f[R] built-in function is called.
.PP
These options \f[I]do\f[R] override the \f[B]BC_PROMPT\f[R] and
\f[B]BC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-r\f[R] \f[I]keyword\f[R], \f[B]--redefine\f[R]=\f[I]keyword\f[R]
Redefines \f[I]keyword\f[R] in order to allow it to be used as a
function, variable, or array name.
This is useful when this bc(1) gives parse errors when parsing scripts
meant for other bc(1) implementations.
.RS
.PP
The keywords this bc(1) allows to be redefined are:
.IP \[bu] 2
\f[B]abs\f[R]
.IP \[bu] 2
\f[B]asciify\f[R]
.IP \[bu] 2
\f[B]continue\f[R]
.IP \[bu] 2
\f[B]divmod\f[R]
.IP \[bu] 2
\f[B]else\f[R]
.IP \[bu] 2
\f[B]halt\f[R]
.IP \[bu] 2
\f[B]irand\f[R]
.IP \[bu] 2
\f[B]last\f[R]
.IP \[bu] 2
\f[B]limits\f[R]
.IP \[bu] 2
\f[B]maxibase\f[R]
.IP \[bu] 2
\f[B]maxobase\f[R]
.IP \[bu] 2
\f[B]maxrand\f[R]
.IP \[bu] 2
\f[B]maxscale\f[R]
.IP \[bu] 2
\f[B]modexp\f[R]
.IP \[bu] 2
\f[B]print\f[R]
.IP \[bu] 2
\f[B]rand\f[R]
.IP \[bu] 2
\f[B]read\f[R]
.IP \[bu] 2
\f[B]seed\f[R]
.IP \[bu] 2
\f[B]stream\f[R]
.PP
If any of those keywords are used as a function, variable, or array name
in a script, use this option with the keyword as the argument.
If multiple are used, use this option for all of them; it can be used
multiple times.
.PP
Keywords are \f[I]not\f[R] redefined when parsing the builtin math
library (see the \f[B]LIBRARY\f[R] section).
.PP
It is a fatal error to redefine keywords mandated by the POSIX standard.
It is a fatal error to attempt to redefine words that this bc(1) does
not reserve as keywords.
.RE
.TP
\f[B]-q\f[R], \f[B]--quiet\f[R]
This option is for compatibility with the GNU
bc(1) (https://www.gnu.org/software/bc/); it is a no-op.
Without this option, GNU bc(1) prints a copyright header.
This bc(1) only prints the copyright header if one or more of the
\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-s\f[R], \f[B]--standard\f[R]
Process exactly the language defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
and error if any extensions are used.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-w\f[R], \f[B]--warn\f[R]
Like \f[B]-s\f[R] and \f[B]--standard\f[R], except that warnings (and
not errors) are printed for non-standard extensions and execution
continues normally.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]BC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, bc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files or expressions are given by the \f[B]-f\f[R],
\f[B]--file\f[R], \f[B]-e\f[R], or \f[B]--expression\f[R] options, then
bc(1) read from \f[B]stdin\f[R].
.PP
However, there are a few caveats to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if the parse cannot complete.
That means that starting a string without ending it or starting a
function, \f[B]if\f[R] statement, or loop without ending it will also
cause bc(1) to not execute.
.PP
Second, after an \f[B]if\f[R] statement, bc(1) doesn\[cq]t know if an
\f[B]else\f[R] statement will follow, so it will not execute until it
knows there will not be an \f[B]else\f[R] statement.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]bc >&-\f[R], it will quit with an error.
This is done so that bc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]bc 2>&-\f[R], it will quit with an error.
This is done so that bc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other bc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
The syntax for bc(1) programs is mostly C-like, with some differences.
This bc(1) follows the POSIX
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
which is a much more thorough resource for the language this bc(1)
accepts.
This section is meant to be a summary and a listing of all the
extensions to the standard.
.PP
In the sections below, \f[B]E\f[R] means expression, \f[B]S\f[R] means
statement, and \f[B]I\f[R] means identifier.
.PP
Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be
followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase
letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores
(\f[B]_\f[R]).
The regex is \f[B][a-z][a-z0-9_]*\f[R].
Identifiers with more than one character (letter) are a
\f[B]non-portable extension\f[R].
.PP
\f[B]ibase\f[R] is a global variable determining how to interpret
constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R]
(\f[B]--warn\f[R]) flags were not given on the command line, the max
allowable value for \f[B]ibase\f[R] is \f[B]36\f[R].
Otherwise, it is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in bc(1)
programs with the \f[B]maxibase()\f[R] built-in function.
.PP
\f[B]obase\f[R] is a global variable determining how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and
can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in
function.
The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R].
If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific
notation, and if \f[B]obase\f[R] is \f[B]1\f[R], values are output in
engineering notation.
Otherwise, values are output in the specified base.
.PP
Outputting in scientific and engineering notations are \f[B]non-portable
extensions\f[R].
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a global variable that sets the precision of any operations, with
exceptions.
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R]
and can be queried in bc(1) programs with the \f[B]maxscale()\f[R]
built-in function.
.PP
bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables.
All \f[I]local\f[R] variables are local to the function; they are
parameters or are introduced in the \f[B]auto\f[R] list of a function
(see the \f[B]FUNCTIONS\f[R] section).
If a variable is accessed which is not a parameter or in the
\f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R].
If a parent function has a \f[I]local\f[R] variable version of a
variable that a child function considers \f[I]global\f[R], the value of
that \f[I]global\f[R] variable in the child function is the value of the
variable in the parent function, not the value of the actual
\f[I]global\f[R] variable.
.PP
All of the above applies to arrays as well.
.PP
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence
operator is an assignment operator \f[I]and\f[R] the expression is
notsurrounded by parentheses.
.PP
The value that is printed is also assigned to the special variable
\f[B]last\f[R].
A single dot (\f[B].\f[R]) may also be used as a synonym for
\f[B]last\f[R].
These are \f[B]non-portable extensions\f[R].
.PP
Either semicolons or newlines may separate statements.
.SS Comments
.PP
There are two kinds of comments:
.IP "1." 3
Block comments are enclosed in \f[B]/*\f[R] and \f[B]*/\f[R].
.IP "2." 3
Line comments go from \f[B]#\f[R] until, and not including, the next
newline.
This is a \f[B]non-portable extension\f[R].
.SS Named Expressions
.PP
The following are named expressions in bc(1):
.IP "1." 3
Variables: \f[B]I\f[R]
.IP "2." 3
Array Elements: \f[B]I[E]\f[R]
.IP "3." 3
\f[B]ibase\f[R]
.IP "4." 3
\f[B]obase\f[R]
.IP "5." 3
\f[B]scale\f[R]
.IP "6." 3
\f[B]seed\f[R]
.IP "7." 3
\f[B]last\f[R] or a single dot (\f[B].\f[R])
.PP
Numbers 6 and 7 are \f[B]non-portable extensions\f[R].
.PP
The meaning of \f[B]seed\f[R] is dependent on the current pseudo-random
number generator but is guaranteed to not change except for new major
versions.
.PP
The \f[I]scale\f[R] and sign of the value may be significant.
.PP
If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R]
and used again, the pseudo-random number generator is guaranteed to
produce the same sequence of pseudo-random numbers as it did when the
\f[B]seed\f[R] value was previously used.
.PP
The exact value assigned to \f[B]seed\f[R] is not guaranteed to be
returned if \f[B]seed\f[R] is queried again immediately.
However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both
values, when assigned to \f[B]seed\f[R], are guaranteed to produce the
same sequence of pseudo-random numbers.
This means that certain values assigned to \f[B]seed\f[R] will
\f[I]not\f[R] produce unique sequences of pseudo-random numbers.
The value of \f[B]seed\f[R] will change after any use of the
\f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the
\f[I]Operands\f[R] subsection below), except if the parameter passed to
\f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative.
.PP
There is no limit to the length (number of significant decimal digits)
or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R].
.PP
Variables and arrays do not interfere; users can have arrays named the
same as variables.
This also applies to functions (see the \f[B]FUNCTIONS\f[R] section), so
a user can have a variable, array, and function that all have the same
name, and they will not shadow each other, whether inside of functions
or not.
.PP
Named expressions are required as the operand of
\f[B]increment\f[R]/\f[B]decrement\f[R] operators and as the left side
of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R]
subsection).
.SS Operands
.PP
The following are valid operands in bc(1):
.IP " 1." 4
Numbers (see the \f[I]Numbers\f[R] subsection below).
.IP " 2." 4
Array indices (\f[B]I[E]\f[R]).
.IP " 3." 4
\f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence).
.IP " 4." 4
\f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R].
\f[B]E\f[R] must be non-negative.
.IP " 5." 4
\f[B]length(E)\f[R]: The number of significant decimal digits in
\f[B]E\f[R].
Returns \f[B]1\f[R] for \f[B]0\f[R] with no decimal places.
If given a string, the length of the string is returned.
Passing a string to \f[B]length(E)\f[R] is a \f[B]non-portable
extension\f[R].
.IP " 6." 4
\f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 7." 4
\f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R].
.IP " 8." 4
\f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R].
This is a \f[B]non-portable extension\f[R].
.IP " 9." 4
\f[B]modexp(E, E, E)\f[R]: Modular exponentiation, where the first
expression is the base, the second is the exponent, and the third is the
modulus.
All three values must be integers.
The second argument must be non-negative.
The third argument must be non-zero.
This is a \f[B]non-portable extension\f[R].
.IP "10." 4
\f[B]divmod(E, E, I[])\f[R]: Division and modulus in one operation.
This is for optimization.
The first expression is the dividend, and the second is the divisor,
which must be non-zero.
The return value is the quotient, and the modulus is stored in index
\f[B]0\f[R] of the provided array (the last argument).
This is a \f[B]non-portable extension\f[R].
.IP "11." 4
\f[B]asciify(E)\f[R]: If \f[B]E\f[R] is a string, returns a string that
is the first letter of its argument.
If it is a number, calculates the number mod \f[B]256\f[R] and returns
that number as a one-character string.
This is a \f[B]non-portable extension\f[R].
.IP "12." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.IP "13." 4
\f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an
expression.
The result of that expression is the result of the \f[B]read()\f[R]
operand.
This is a \f[B]non-portable extension\f[R].
.IP "14." 4
\f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "15." 4
\f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "16." 4
\f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R].
This is a \f[B]non-portable extension\f[R].
.IP "17." 4
+\f[B]line_length()\f[R]: The line length set with
+\f[B]BC_LINE_LENGTH\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
+section).
+This is a \f[B]non-portable extension\f[R].
+.IP "18." 4
+\f[B]global_stacks()\f[R]: \f[B]0\f[R] if global stacks are not enabled
+with the \f[B]-g\f[R] or \f[B]--global-stacks\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "19." 4
+\f[B]leading_zero()\f[R]: \f[B]0\f[R] if leading zeroes are not enabled
+with the \f[B]-z\f[R] or \f[B]\[en]leading-zeroes\f[R] options, non-zero
+otherwise.
+See the \f[B]OPTIONS\f[R] section.
+This is a \f[B]non-portable extension\f[R].
+.IP "20." 4
\f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R]
(inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive).
Using this operand will change the value of \f[B]seed\f[R].
This is a \f[B]non-portable extension\f[R].
-.IP "18." 4
+.IP "21." 4
\f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R]
(inclusive) and the value of \f[B]E\f[R] (exclusive).
If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s
\f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains
unchanged.
If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is
honored by generating several pseudo-random integers, multiplying them
by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], and adding them
together.
Thus, the size of integer that can be generated with this operand is
unbounded.
Using this operand will change the value of \f[B]seed\f[R], unless the
value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R].
In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is
\f[I]not\f[R] changed.
This is a \f[B]non-portable extension\f[R].
-.IP "19." 4
+.IP "22." 4
\f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R].
This is a \f[B]non-portable extension\f[R].
.PP
The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are
guaranteed to be as unbiased as possible, subject to the limitations of
the pseudo-random number generator.
.PP
\f[B]Note\f[R]: The values returned by the pseudo-random number
generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to
\f[I]NOT\f[R] be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they \f[I]are\f[R] guaranteed to be reproducible with identical
\f[B]seed\f[R] values.
This means that the pseudo-random values from bc(1) should only be used
where a reproducible stream of pseudo-random numbers is
\f[I]ESSENTIAL\f[R].
In any other case, use a non-seeded pseudo-random number generator.
.SS Numbers
.PP
Numbers are strings made up of digits, uppercase letters, and at most
\f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]Z\f[R] alone always equals decimal \f[B]35\f[R].
.PP
In addition, bc(1) accepts numbers in scientific notation.
These have the form \f[B]e\f[R].
The exponent (the portion after the \f[B]e\f[R]) must be an integer.
An example is \f[B]1.89237e9\f[R], which is equal to
\f[B]1892370000\f[R].
Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to
\f[B]0.0042890\f[R].
.PP
Using scientific notation is an error or warning if the \f[B]-s\f[R] or
\f[B]-w\f[R], respectively, command-line options (or equivalents) are
given.
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if bc(1) is given the number string
\f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.PP
Accepting input as scientific notation is a \f[B]non-portable
extension\f[R].
.SS Operators
.PP
The following arithmetic and logical operators can be used.
They are listed in order of decreasing precedence.
Operators in the same group have the same precedence.
.TP
\f[B]++\f[R] \f[B]--\f[R]
Type: Prefix and Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]increment\f[R], \f[B]decrement\f[R]
.RE
.TP
\f[B]-\f[R] \f[B]!\f[R]
Type: Prefix
.RS
.PP
Associativity: None
.PP
Description: \f[B]negation\f[R], \f[B]boolean not\f[R]
.RE
.TP
\f[B]$\f[R]
Type: Postfix
.RS
.PP
Associativity: None
.PP
Description: \f[B]truncation\f[R]
.RE
.TP
\f[B]\[at]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]set precision\f[R]
.RE
.TP
\f[B]\[ha]\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]power\f[R]
.RE
.TP
\f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R]
.RE
.TP
\f[B]+\f[R] \f[B]-\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]add\f[R], \f[B]subtract\f[R]
.RE
.TP
\f[B]<<\f[R] \f[B]>>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]shift left\f[R], \f[B]shift right\f[R]
.RE
.TP
\f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R]
Type: Binary
.RS
.PP
Associativity: Right
.PP
Description: \f[B]assignment\f[R]
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]relational\f[R]
.RE
.TP
\f[B]&&\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean and\f[R]
.RE
.TP
\f[B]||\f[R]
Type: Binary
.RS
.PP
Associativity: Left
.PP
Description: \f[B]boolean or\f[R]
.RE
.PP
The operators will be described in more detail below.
.TP
\f[B]++\f[R] \f[B]--\f[R]
The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R]
operators behave exactly like they would in C.
They require a named expression (see the \f[I]Named Expressions\f[R]
subsection) as an operand.
.RS
.PP
The prefix versions of these operators are more efficient; use them
where possible.
.RE
.TP
\f[B]-\f[R]
The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts
to negate any expression with the value \f[B]0\f[R].
Otherwise, a copy of the expression with its sign flipped is returned.
.TP
\f[B]!\f[R]
The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression
is \f[B]0\f[R], or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]$\f[R]
The \f[B]truncation\f[R] operator returns a copy of the given expression
with all of its \f[I]scale\f[R] removed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[at]\f[R]
The \f[B]set precision\f[R] operator takes two expressions and returns a
copy of the first with its \f[I]scale\f[R] equal to the value of the
second expression.
That could either mean that the number is returned without change (if
the \f[I]scale\f[R] of the first expression matches the value of the
second expression), extended (if it is less), or truncated (if it is
more).
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator,
as it would be in C) takes two expressions and raises the first to the
power of the value of the second.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]), and if it
is negative, the first value must be non-zero.
.RE
.TP
\f[B]*\f[R]
The \f[B]multiply\f[R] operator takes two expressions, multiplies them,
and returns the product.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The \f[B]divide\f[R] operator takes two expressions, divides them, and
returns the quotient.
The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]%\f[R]
The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R] and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.RS
.PP
The second expression must be non-zero.
.RE
.TP
\f[B]+\f[R]
The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the
max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]-\f[R]
The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to
the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R].
.TP
\f[B]<<\f[R]
The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and
\f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its
decimal point moved \f[B]b\f[R] places to the right.
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]>>\f[R]
The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its
decimal point moved \f[B]b\f[R] places to the left.
.RS
.PP
The second expression must be an integer (no \f[I]scale\f[R]) and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R]
The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and
\f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named
Expressions\f[R] subsection).
.RS
.PP
For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to
\f[B]a\f[R].
For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to
the corresponding arithmetic operator and the result is assigned to
\f[B]a\f[R].
.PP
The \f[B]assignment\f[R] operators that correspond to operators that are
extensions are themselves \f[B]non-portable extensions\f[R].
.RE
.TP
\f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R]
The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R]
and \f[B]b\f[R], and if the relation holds, according to C language
semantics, the result is \f[B]1\f[R].
Otherwise, it is \f[B]0\f[R].
.RS
.PP
Note that unlike in C, these operators have a lower precedence than the
\f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is
interpreted as \f[B](a=b)>c\f[R].
.PP
Also, unlike the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
requires, these operators can appear anywhere any other expressions can
be used.
This allowance is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]&&\f[R]
The \f[B]boolean and\f[R] operator takes two expressions and returns
\f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]||\f[R]
The \f[B]boolean or\f[R] operator takes two expressions and returns
\f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R]
otherwise.
.RS
.PP
This is \f[I]not\f[R] a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Statements
.PP
The following items are statements:
.IP " 1." 4
\f[B]E\f[R]
.IP " 2." 4
\f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R]
\f[B]}\f[R]
.IP " 3." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 4." 4
\f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
\f[B]else\f[R] \f[B]S\f[R]
.IP " 5." 4
\f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 6." 4
\f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R]
\f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R]
.IP " 7." 4
An empty statement
.IP " 8." 4
\f[B]break\f[R]
.IP " 9." 4
\f[B]continue\f[R]
.IP "10." 4
\f[B]quit\f[R]
.IP "11." 4
\f[B]halt\f[R]
.IP "12." 4
\f[B]limits\f[R]
.IP "13." 4
A string of characters, enclosed in double quotes
.IP "14." 4
\f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "15." 4
\f[B]stream\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R]
.IP "16." 4
\f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where
\f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the
\f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section).
The \f[B]E\f[R] argument(s) may also be arrays of the form
\f[B]I[]\f[R], which will automatically be turned into array references
(see the \f[I]Array References\f[R] subsection of the
\f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the
function definition is an array reference.
.PP
Numbers 4, 9, 11, 12, 14, 15, and 16 are \f[B]non-portable
extensions\f[R].
.PP
Also, as a \f[B]non-portable extension\f[R], any or all of the
expressions in the header of a for loop may be omitted.
If the condition (second expression) is omitted, it is assumed to be a
constant \f[B]1\f[R].
.PP
The \f[B]break\f[R] statement causes a loop to stop iterating and resume
execution immediately following a loop.
This is only allowed in loops.
.PP
The \f[B]continue\f[R] statement causes a loop iteration to stop early
and returns to the start of the loop, including testing the loop
condition.
This is only allowed in loops.
.PP
The \f[B]if\f[R] \f[B]else\f[R] statement does the same thing as in C.
.PP
The \f[B]quit\f[R] statement causes bc(1) to quit, even if it is on a
branch that will not be executed (it is a compile-time command).
.PP
The \f[B]halt\f[R] statement causes bc(1) to quit, if it is executed.
(Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement
that is not executed, bc(1) does not quit.)
.PP
The \f[B]limits\f[R] statement prints the limits that this bc(1) is
subject to.
This is like the \f[B]quit\f[R] statement in that it is a compile-time
command.
.PP
An expression by itself is evaluated and printed, followed by a newline.
.PP
Both scientific notation and engineering notation are available for
printing the results of expressions.
Scientific notation is activated by assigning \f[B]0\f[R] to
\f[B]obase\f[R], and engineering notation is activated by assigning
\f[B]1\f[R] to \f[B]obase\f[R].
To deactivate them, just assign a different value to \f[B]obase\f[R].
.PP
Scientific notation and engineering notation are disabled if bc(1) is
run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options
(or equivalents).
.PP
Printing numbers in scientific notation and/or engineering notation is a
\f[B]non-portable extension\f[R].
.SS Strings
.PP
If strings appear as a statement by themselves, they are printed without
a trailing newline.
.PP
In addition to appearing as a lone statement by themselves, strings can
be assigned to variables and array elements.
They can also be passed to functions in variable parameters.
.PP
If any statement that expects a string is given a variable that had a
string assigned to it, the statement acts as though it had received a
string.
.PP
If any math operation is attempted on a string or a variable or array
element that has been assigned a string, an error is raised, and bc(1)
resets (see the \f[B]RESET\f[R] section).
.PP
Assigning strings to variables and array elements and passing them to
functions are \f[B]non-portable extensions\f[R].
.SS Print Statement
.PP
The \[lq]expressions\[rq] in a \f[B]print\f[R] statement may also be
strings.
If they are, there are backslash escape sequences that are interpreted
specially.
What those sequences are, and what they cause to be printed, are shown
below:
.PP
\f[B]\[rs]a\f[R]: \f[B]\[rs]a\f[R]
.PP
\f[B]\[rs]b\f[R]: \f[B]\[rs]b\f[R]
.PP
\f[B]\[rs]\[rs]\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]e\f[R]: \f[B]\[rs]\f[R]
.PP
\f[B]\[rs]f\f[R]: \f[B]\[rs]f\f[R]
.PP
\f[B]\[rs]n\f[R]: \f[B]\[rs]n\f[R]
.PP
\f[B]\[rs]q\f[R]: \f[B]\[lq]\f[R]
.PP
\f[B]\[rs]r\f[R]: \f[B]\[rs]r\f[R]
.PP
\f[B]\[rs]t\f[R]: \f[B]\[rs]t\f[R]
.PP
Any other character following a backslash causes the backslash and
character to be printed as-is.
.PP
Any non-string expression in a print statement shall be assigned to
\f[B]last\f[R], like any other expression that is printed.
.SS Stream Statement
.PP
The \[lq]expressions in a \f[B]stream\f[R] statement may also be
strings.
.PP
If a \f[B]stream\f[R] statement is given a string, it prints the string
as though the string had appeared as its own statement.
In other words, the \f[B]stream\f[R] statement prints strings normally,
without a newline.
.PP
If a \f[B]stream\f[R] statement is given a number, a copy of it is
truncated and its absolute value is calculated.
The result is then printed as though \f[B]obase\f[R] is \f[B]256\f[R]
and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
.SS Order of Evaluation
.PP
All expressions in a statment are evaluated left to right, except as
necessary to maintain order of operations.
This means, for example, assuming that \f[B]i\f[R] is equal to
\f[B]0\f[R], in the expression
.IP
.nf
\f[C]
a[i++] = i++
\f[R]
.fi
.PP
the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and
\f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression.
.PP
This includes function arguments.
Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in
the expression
.IP
.nf
\f[C]
x(i++, i++)
\f[R]
.fi
.PP
the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the
second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to
\f[B]2\f[R] before the function starts executing.
.SH FUNCTIONS
.PP
Function definitions are as follows:
.IP
.nf
\f[C]
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
\f[R]
.fi
.PP
Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be
replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an
array, and any \f[B]I\f[R] in the parameter list may be replaced with
\f[B]*I[]\f[R] to make a parameter an array reference.
Callers of functions that take array references should not put an
asterisk in the call; they must be called with just \f[B]I[]\f[R] like
normal array parameters and will be automatically converted into
references.
.PP
As a \f[B]non-portable extension\f[R], the opening brace of a
\f[B]define\f[R] statement may appear on the next line.
.PP
As a \f[B]non-portable extension\f[R], the return statement may also be
in one of the following forms:
.IP "1." 3
\f[B]return\f[R]
.IP "2." 3
\f[B]return\f[R] \f[B](\f[R] \f[B])\f[R]
.IP "3." 3
\f[B]return\f[R] \f[B]E\f[R]
.PP
The first two, or not specifying a \f[B]return\f[R] statement, is
equivalent to \f[B]return (0)\f[R], unless the function is a
\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection
below).
.SS Void Functions
.PP
Functions can also be \f[B]void\f[R] functions, defined as follows:
.IP
.nf
\f[C]
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
\f[R]
.fi
.PP
They can only be used as standalone expressions, where such an
expression would be printed alone, except in a print statement.
.PP
Void functions can only use the first two \f[B]return\f[R] statements
listed above.
They can also omit the return statement entirely.
.PP
The word \[lq]void\[rq] is not treated as a keyword; it is still
possible to have variables, arrays, and functions named \f[B]void\f[R].
The word \[lq]void\[rq] is only treated specially right after the
\f[B]define\f[R] keyword.
.PP
This is a \f[B]non-portable extension\f[R].
.SS Array References
.PP
For any array in the parameter list, if the array is declared in the
form
.IP
.nf
\f[C]
*I[]
\f[R]
.fi
.PP
it is a \f[B]reference\f[R].
Any changes to the array in the function are reflected, when the
function returns, to the array that was passed in.
.PP
Other than this, all function arguments are passed by value.
.PP
This is a \f[B]non-portable extension\f[R].
.SH LIBRARY
.PP
All of the functions below, including the functions in the extended math
library (see the \f[I]Extended Library\f[R] subsection below), are
available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line
flags are given, except that the extended math library is not available
when the \f[B]-s\f[R] option, the \f[B]-w\f[R] option, or equivalents
are given.
.SS Standard Library
.PP
The
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
defines the following functions for the math library:
.TP
\f[B]s(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]c(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l(x)\f[R]
Returns the natural logarithm of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]e(x)\f[R]
Returns the mathematical constant \f[B]e\f[R] raised to the power of
\f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]j(x, n)\f[R]
Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.SS Extended Library
.PP
The extended library is \f[I]not\f[R] loaded when the
\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R]
options are given since they are not part of the library defined by the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).
.PP
The extended library is a \f[B]non-portable extension\f[R].
.TP
\f[B]p(x, y)\f[R]
Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R]
is not an integer, and returns the result to the current
\f[B]scale\f[R].
.RS
.PP
It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is
\f[B]0\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]r(x, p)\f[R]
Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to
the rounding mode round half away from
\f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero).
.TP
\f[B]ceil(x, p)\f[R]
Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to
the rounding mode round away from
\f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero).
.TP
\f[B]f(x)\f[R]
Returns the factorial of the truncated absolute value of \f[B]x\f[R].
.TP
\f[B]perm(n, k)\f[R]
Returns the permutation of the truncated absolute value of \f[B]n\f[R]
of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R].
If not, it returns \f[B]0\f[R].
.TP
\f[B]comb(n, k)\f[R]
Returns the combination of the truncated absolute value of \f[B]n\f[R]
of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R].
If not, it returns \f[B]0\f[R].
.TP
\f[B]l2(x)\f[R]
Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]l10(x)\f[R]
Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]log(x, b)\f[R]
Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R].
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]cbrt(x)\f[R]
Returns the cube root of \f[B]x\f[R].
.TP
\f[B]root(x, n)\f[R]
Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns
the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R].
.RS
.PP
If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and
causes bc(1) to reset (see the \f[B]RESET\f[R] section).
It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even
and \f[B]x\f[R] is negative.
.RE
.TP
\f[B]gcd(a, b)\f[R]
Returns the greatest common divisor (factor) of the truncated absolute
value of \f[B]a\f[R] and the truncated absolute value of \f[B]b\f[R].
.TP
\f[B]lcm(a, b)\f[R]
Returns the least common multiple of the truncated absolute value of
\f[B]a\f[R] and the truncated absolute value of \f[B]b\f[R].
.TP
\f[B]pi(p)\f[R]
Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]t(x)\f[R]
Returns the tangent of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]a2(y, x)\f[R]
Returns the arctangent of \f[B]y/x\f[R], in radians.
If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises
an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns
\f[B]a(y/x)\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than
or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than
\f[B]0\f[R], it returns \f[B]pi/2\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]-pi/2\f[R].
.RS
.PP
This function is the same as the \f[B]atan2()\f[R] function in many
programming languages.
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]sin(x)\f[R]
Returns the sine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is an alias of \f[B]s(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]cos(x)\f[R]
Returns the cosine of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
This is an alias of \f[B]c(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]tan(x)\f[R]
Returns the tangent of \f[B]x\f[R], which is assumed to be in radians.
.RS
.PP
If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an
error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
.PP
This is an alias of \f[B]t(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]atan(x)\f[R]
Returns the arctangent of \f[B]x\f[R], in radians.
.RS
.PP
This is an alias of \f[B]a(x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]atan2(y, x)\f[R]
Returns the arctangent of \f[B]y/x\f[R], in radians.
If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises
an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section).
Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns
\f[B]a(y/x)\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than
or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R].
If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than
\f[B]0\f[R], it returns \f[B]pi/2\f[R].
If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than
\f[B]0\f[R], it returns \f[B]-pi/2\f[R].
.RS
.PP
This function is the same as the \f[B]atan2()\f[R] function in many
programming languages.
.PP
This is an alias of \f[B]a2(y, x)\f[R].
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]r2d(x)\f[R]
Converts \f[B]x\f[R] from radians to degrees and returns the result.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]d2r(x)\f[R]
Converts \f[B]x\f[R] from degrees to radians and returns the result.
.RS
.PP
This is a transcendental function (see the \f[I]Transcendental
Functions\f[R] subsection below).
.RE
.TP
\f[B]frand(p)\f[R]
Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and
\f[B]1\f[R] (exclusive) with the number of decimal digits after the
decimal point equal to the truncated absolute value of \f[B]p\f[R].
If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will
change the value of \f[B]seed\f[R].
If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and
\f[B]seed\f[R] is \f[I]not\f[R] changed.
.TP
\f[B]ifrand(i, p)\f[R]
Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive)
and the truncated absolute value of \f[B]i\f[R] (exclusive) with the
number of decimal digits after the decimal point equal to the truncated
absolute value of \f[B]p\f[R].
If the absolute value of \f[B]i\f[R] is greater than or equal to
\f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this
function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R]
is returned and \f[B]seed\f[R] is not changed.
.TP
\f[B]srand(x)\f[R]
Returns \f[B]x\f[R] with its sign flipped with probability
\f[B]0.5\f[R].
In other words, it randomizes the sign of \f[B]x\f[R].
.TP
\f[B]brand()\f[R]
Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]).
.TP
\f[B]band(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]and\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bor(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]or\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bxor(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of the bitwise \f[B]xor\f[R]
operation between them.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bshl(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the result of \f[B]a\f[R] bit-shifted left by
\f[B]b\f[R] places.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bshr(a, b)\f[R]
Takes the truncated absolute value of both \f[B]a\f[R] and \f[B]b\f[R]
and calculates and returns the truncated result of \f[B]a\f[R]
bit-shifted right by \f[B]b\f[R] places.
.RS
.PP
If you want to use signed two\[cq]s complement arguments, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnotn(x, n)\f[R]
Takes the truncated absolute value of \f[B]x\f[R] and does a bitwise not
as though it has the same number of bytes as the truncated absolute
value of \f[B]n\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot8(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]8\f[R] binary digits (1 unsigned byte).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot16(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]16\f[R] binary digits (2 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot32(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]32\f[R] binary digits (4 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot64(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has \f[B]64\f[R] binary digits (8 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bnot(x)\f[R]
Does a bitwise not of the truncated absolute value of \f[B]x\f[R] as
though it has the minimum number of power of two unsigned bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brevn(x, n)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has the same number of 8-bit bytes as the truncated absolute
value of \f[B]n\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev8(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 8 binary digits (1 unsigned byte).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev16(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 16 binary digits (2 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev32(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 32 binary digits (4 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev64(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has 64 binary digits (8 unsigned bytes).
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brev(x)\f[R]
Runs a bit reversal on the truncated absolute value of \f[B]x\f[R] as
though it has the minimum number of power of two unsigned bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]broln(x, p, n)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the same number of unsigned 8-bit bytes as
the truncated absolute value of \f[B]n\f[R], by the number of places
equal to the truncated absolute value of \f[B]p\f[R] modded by the
\f[B]2\f[R] to the power of the number of binary digits in \f[B]n\f[R]
8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol8(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]8\f[R] binary digits (\f[B]1\f[R]
unsigned byte), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol16(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]16\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol32(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol64(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brol(x, p)\f[R]
Does a left bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the minimum number of power of two
unsigned 8-bit bytes, by the number of places equal to the truncated
absolute value of \f[B]p\f[R] modded by 2 to the power of the number of
binary digits in the minimum number of 8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]brorn(x, p, n)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the same number of unsigned 8-bit bytes as
the truncated absolute value of \f[B]n\f[R], by the number of places
equal to the truncated absolute value of \f[B]p\f[R] modded by the
\f[B]2\f[R] to the power of the number of binary digits in \f[B]n\f[R]
8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror8(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]8\f[R] binary digits (\f[B]1\f[R]
unsigned byte), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror16(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]16\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror32(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]32\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror64(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has \f[B]64\f[R] binary digits (\f[B]2\f[R]
unsigned bytes), by the number of places equal to the truncated absolute
value of \f[B]p\f[R] modded by \f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bror(x, p)\f[R]
Does a right bitwise rotatation of the truncated absolute value of
\f[B]x\f[R], as though it has the minimum number of power of two
unsigned 8-bit bytes, by the number of places equal to the truncated
absolute value of \f[B]p\f[R] modded by 2 to the power of the number of
binary digits in the minimum number of 8-bit bytes.
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmodn(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of the multiplication of the truncated absolute
value of \f[B]n\f[R] and \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod8(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]8\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod16(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]16\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod32(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]32\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bmod64(x, n)\f[R]
Returns the modulus of the truncated absolute value of \f[B]x\f[R] by
\f[B]2\f[R] to the power of \f[B]64\f[R].
.RS
.PP
If you want to a use signed two\[cq]s complement argument, use
\f[B]s2u(x)\f[R] to convert.
.RE
.TP
\f[B]bunrev(t)\f[R]
Assumes \f[B]t\f[R] is a bitwise-reversed number with an extra set bit
one place more significant than the real most significant bit (which was
the least significant bit in the original number).
This number is reversed and returned without the extra set bit.
.RS
.PP
This function is used to implement other bitwise functions; it is not
meant to be used by users, but it can be.
.RE
.TP
+\f[B]plz(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed with a leading zero, regardless
+of the use of the \f[B]-z\f[R] option (see the \f[B]OPTIONS\f[R]
+section) and without a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, without a trailing newline.
+.RE
+.TP
+\f[B]plznl(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed with a leading zero, regardless
+of the use of the \f[B]-z\f[R] option (see the \f[B]OPTIONS\f[R]
+section) and with a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, with a trailing newline.
+.RE
+.TP
+\f[B]pnlz(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed without a leading zero,
+regardless of the use of the \f[B]-z\f[R] option (see the
+\f[B]OPTIONS\f[R] section) and without a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, without a trailing newline.
+.RE
+.TP
+\f[B]pnlznl(x)\f[R]
+If \f[B]x\f[R] is not equal to \f[B]0\f[R] and greater that \f[B]-1\f[R]
+and less than \f[B]1\f[R], it is printed without a leading zero,
+regardless of the use of the \f[B]-z\f[R] option (see the
+\f[B]OPTIONS\f[R] section) and with a trailing newline.
+.RS
+.PP
+Otherwise, \f[B]x\f[R] is printed normally, with a trailing newline.
+.RE
+.TP
\f[B]ubytes(x)\f[R]
Returns the numbers of unsigned integer bytes required to hold the
truncated absolute value of \f[B]x\f[R].
.TP
\f[B]sbytes(x)\f[R]
Returns the numbers of signed, two\[cq]s-complement integer bytes
required to hold the truncated value of \f[B]x\f[R].
.TP
\f[B]s2u(x)\f[R]
Returns \f[B]x\f[R] if it is non-negative.
If it \f[I]is\f[R] negative, then it calculates what \f[B]x\f[R] would
be as a 2\[cq]s-complement signed integer and returns the non-negative
integer that would have the same representation in binary.
.TP
\f[B]s2un(x,n)\f[R]
Returns \f[B]x\f[R] if it is non-negative.
If it \f[I]is\f[R] negative, then it calculates what \f[B]x\f[R] would
be as a 2\[cq]s-complement signed integer with \f[B]n\f[R] bytes and
returns the non-negative integer that would have the same representation
in binary.
If \f[B]x\f[R] cannot fit into \f[B]n\f[R] 2\[cq]s-complement signed
bytes, it is truncated to fit.
.TP
\f[B]hex(x)\f[R]
Outputs the hexadecimal (base \f[B]16\f[R]) representation of
\f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]binary(x)\f[R]
Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output(x, b)\f[R]
Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R].
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in as few power of two bytes as possible.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or is negative, an error message is
printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R]
section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in as few power of two bytes as
possible.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, an error message is printed instead,
but bc(1) is not reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uintn(x, n)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]n\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]intn(x, n)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint8(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]1\f[R] byte.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int8(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an
error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint16(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]2\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int16(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint32(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]4\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int32(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]uint64(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
an unsigned integer in \f[B]8\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer, is negative, or cannot fit into
\f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not
reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]int64(x)\f[R]
Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as
a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes.
Both outputs are split into bytes separated by spaces.
.RS
.PP
If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes,
an error message is printed instead, but bc(1) is not reset (see the
\f[B]RESET\f[R] section).
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]hex_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R]
bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]binary_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output_uint(x, n)\f[R]
Outputs the representation of the truncated absolute value of
\f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see
the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes.
Not all of the value will be output if \f[B]n\f[R] is too small.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.TP
\f[B]output_byte(x, i)\f[R]
Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R],
where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes
- 1\f[R] is the most significant byte.
.RS
.PP
This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R]
subsection of the \f[B]FUNCTIONS\f[R] section).
.RE
.SS Transcendental Functions
.PP
All transcendental functions can return slightly inaccurate results (up
to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)).
This is unavoidable, and this
article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains
why it is impossible and unnecessary to calculate exact results for the
transcendental functions.
.PP
Because of the possible inaccuracy, I recommend that users call those
functions with the precision (\f[B]scale\f[R]) set to at least 1 higher
than is necessary.
If exact results are \f[I]absolutely\f[R] required, users can double the
precision (\f[B]scale\f[R]) and then truncate.
.PP
The transcendental functions in the standard math library are:
.IP \[bu] 2
\f[B]s(x)\f[R]
.IP \[bu] 2
\f[B]c(x)\f[R]
.IP \[bu] 2
\f[B]a(x)\f[R]
.IP \[bu] 2
\f[B]l(x)\f[R]
.IP \[bu] 2
\f[B]e(x)\f[R]
.IP \[bu] 2
\f[B]j(x, n)\f[R]
.PP
The transcendental functions in the extended math library are:
.IP \[bu] 2
\f[B]l2(x)\f[R]
.IP \[bu] 2
\f[B]l10(x)\f[R]
.IP \[bu] 2
\f[B]log(x, b)\f[R]
.IP \[bu] 2
\f[B]pi(p)\f[R]
.IP \[bu] 2
\f[B]t(x)\f[R]
.IP \[bu] 2
\f[B]a2(y, x)\f[R]
.IP \[bu] 2
\f[B]sin(x)\f[R]
.IP \[bu] 2
\f[B]cos(x)\f[R]
.IP \[bu] 2
\f[B]tan(x)\f[R]
.IP \[bu] 2
\f[B]atan(x)\f[R]
.IP \[bu] 2
\f[B]atan2(y, x)\f[R]
.IP \[bu] 2
\f[B]r2d(x)\f[R]
.IP \[bu] 2
\f[B]d2r(x)\f[R]
.SH RESET
.PP
When bc(1) encounters an error or a signal that it has a non-default
handler for, it resets.
This means that several things happen.
.PP
First, any functions 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.
.PP
Thus, when bc(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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.PP
Note that this reset behavior is different from the GNU bc(1), which
attempts to start executing the statement right after the one that
caused an error.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This bc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R]
can be queried with the \f[B]limits\f[R] statement.
.PP
In addition, this bc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bc(1):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bc(1) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]rand()\f[R]
operand.
Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
The actual values can be queried with the \f[B]limits\f[R] statement.
.PP
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
.PP
bc(1) recognizes the following environment variables:
.TP
\f[B]POSIXLY_CORRECT\f[R]
If this variable exists (no matter the contents), bc(1) behaves as if
the \f[B]-s\f[R] option was given.
.TP
\f[B]BC_ENV_ARGS\f[R]
This is another way to give command-line arguments to bc(1).
They should be in the same format as all other command-line arguments.
These are always processed first, so any files given in
\f[B]BC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 bc(1) runs.
.RS
.PP
The code that parses \f[B]BC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`bc' file.bc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]BC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]BC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length,
including the backslash (\f[B]\[rs]\f[R]).
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]BC_BANNER\f[R]
If this environment variable exists and contains an integer, then a
non-zero value activates the copyright banner when bc(1) is in
interactive mode, while zero deactivates it.
.RS
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
does not print the banner when not in interactive mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_SIGINT_RESET\f[R]
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because bc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes bc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then bc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use
TTY mode, and zero makes bc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]BC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a
prompt, and zero or a non-integer makes bc(1) not use a prompt.
If this environment variable does not exist and \f[B]BC_TTY_MODE\f[R]
does, then the value of the \f[B]BC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]BC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
bc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], 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, overflow when calculating the size of a number, and attempting
to use a non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift
(\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their
corresponding assignment operators.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, using a token
where it is invalid, giving an invalid expression, giving an invalid
print statement, giving an invalid function definition, attempting to
assign to an expression that is not a named expression (see the
\f[I]Named Expressions\f[R] subsection of the \f[B]SYNTAX\f[R] section),
giving an invalid \f[B]auto\f[R] list, having a duplicate
\f[B]auto\f[R]/function parameter, failing to find the end of a code
block, attempting to return a value from a \f[B]void\f[R] function,
attempting to use a variable as a reference, and using any extensions
when the option \f[B]-s\f[R] or any equivalents were given.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors, passing the wrong number of
arguments to functions, attempting to call an undefined function, and
attempting to use a \f[B]void\f[R] function call as a value in an
expression.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
Fatal errors include memory allocation errors, I/O errors, failing to
open files, attempting to use files that do not have only ASCII
characters (bc(1) only accepts ASCII characters), attempting to open a
directory as a file, and giving invalid command-line options.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, bc(1)
always exits and returns \f[B]4\f[R], no matter what mode bc(1) is in.
.PP
The other statuses will only be returned when bc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
bc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Per the
standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, bc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
bc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]BC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, bc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]BC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, bc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]BC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then bc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]BC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Command-Line History
.PP
Command-line history is only enabled if TTY mode is, i.e., that
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to
a TTY and the \f[B]BC_TTY_MODE\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section) and its default do not disable
TTY mode.
See the \f[B]COMMAND LINE HISTORY\f[R] section for more information.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]BC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]BC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]BC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]BC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause bc(1) to do one of two things.
.PP
If bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]BC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, bc(1) will exit.
.PP
However, if bc(1) is in interactive mode, and the
\f[B]BC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then bc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If bc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If bc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] is sent to bc(1) as it is
executing a file, it can seem as though bc(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
bc(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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause bc(1) to clean up and
exit, and it uses the default handler for all other signals.
The one exception is \f[B]SIGHUP\f[R]; in that case, and only when bc(1)
is in TTY mode (see the \f[B]TTY MODE\f[R] section), a \f[B]SIGHUP\f[R]
will cause bc(1) to clean up and exit.
.SH COMMAND LINE HISTORY
.PP
bc(1) supports interactive command-line editing.
.PP
If bc(1) can be in TTY mode (see the \f[B]TTY MODE\f[R] section),
history can be enabled.
This means that command-line history can only be enabled when
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY.
.PP
Like TTY mode itself, it can be turned on or off with the environment
variable \f[B]BC_TTY_MODE\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If history is enabled, previous lines can be recalled and edited with
the arrow keys.
.PP
\f[B]Note\f[R]: tabs are converted to 8 spaces.
.SH SEE ALSO
.PP
dc(1)
.SH STANDARDS
.PP
bc(1) is compliant with the IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
The flags \f[B]-efghiqsvVw\f[R], all long options, and the extensions
noted above are extensions to that specification.
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bc/N.1.md b/manuals/bc/N.1.md
index 6867a05d2184..51dad376b56d 100644
--- a/manuals/bc/N.1.md
+++ b/manuals/bc/N.1.md
@@ -1,2277 +1,2339 @@
# NAME
bc - arbitrary-precision decimal arithmetic language and calculator
# SYNOPSIS
**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# DESCRIPTION
bc(1) is an interactive processor for a language first standardized in 1991 by
POSIX. (The current standard is [here][1].) The language provides unlimited
precision decimal arithmetic and is somewhat C-like, but there are differences.
Such differences will be noted in this document.
After parsing and handling options, this bc(1) reads any files given on the
command line and executes them before reading from **stdin**.
This bc(1) is a drop-in replacement for *any* bc(1), including (and
especially) the GNU bc(1). It also has many extensions and extra features beyond
other implementations.
**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
parse error, it is probably because a word this bc(1) reserves as a keyword is
used as the name of a function, variable, or array. To fix that, use the
command-line option **-r** *keyword*, where *keyword* is the keyword that is
used as a name in the script. For more information, see the **OPTIONS** section.
If parsing scripts meant for other bc(1) implementations still does not work,
that is a bug and should be reported. See the **BUGS** section.
# OPTIONS
The following are the options that bc(1) accepts.
**-g**, **-\-global-stacks**
: Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks.
This has the effect that a copy of the current value of all four are pushed
onto a stack for every function call, as well as popped when every function
returns. This means that functions can assign to any and all of those
globals without worrying that the change will affect other functions.
Thus, a hypothetical function named **output(x,b)** that simply printed
**x** in base **b** could be written like this:
define void output(x, b) {
obase=b
x
}
instead of like this:
define void output(x, b) {
auto c
c=obase
obase=b
x
obase=c
}
This makes writing functions much easier.
(**Note**: the function **output(x,b)** exists in the extended math library.
See the **LIBRARY** section.)
However, since using this flag means that functions cannot set **ibase**,
**obase**, **scale**, or **seed** globally, functions that are made to do so
cannot work anymore. There are two possible use cases for that, and each has
a solution.
First, if a function is called on startup to turn bc(1) into a number
converter, it is possible to replace that capability with various shell
aliases. Examples:
alias d2o="bc -e ibase=A -e obase=8"
alias h2b="bc -e ibase=G -e obase=2"
Second, if the purpose of a function is to set **ibase**, **obase**,
**scale**, or **seed** globally for any other purpose, it could be split
into one to four functions (based on how many globals it sets) and each of
those functions could return the desired value for a global.
For functions that set **seed**, the value assigned to **seed** is not
propagated to parent functions. This means that the sequence of
pseudo-random numbers that they see will not be the same sequence of
pseudo-random numbers that any parent sees. This is only the case once
**seed** has been set.
If a function desires to not affect the sequence of pseudo-random numbers
of its parents, but wants to use the same **seed**, it can use the following
line:
seed = seed
If the behavior of this option is desired for every run of bc(1), then users
could make sure to define **BC_ENV_ARGS** and include this option (see the
**ENVIRONMENT VARIABLES** section for more details).
If **-s**, **-w**, or any equivalents are used, this option is ignored.
This is a **non-portable extension**.
**-h**, **-\-help**
: Prints a usage message and quits.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-l**, **-\-mathlib**
: Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
math library and the extended math library before running any code,
including any expressions or files specified on the command line.
To learn what is in the libraries, see the **LIBRARY** section.
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in bc(1). Most of those users
would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section).
These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in bc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of bc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **read()** built-in function is called.
These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-r** *keyword*, **-\-redefine**=*keyword*
: Redefines *keyword* in order to allow it to be used as a function, variable,
or array name. This is useful when this bc(1) gives parse errors when
parsing scripts meant for other bc(1) implementations.
The keywords this bc(1) allows to be redefined are:
* **abs**
* **asciify**
* **continue**
* **divmod**
* **else**
* **halt**
* **irand**
* **last**
* **limits**
* **maxibase**
* **maxobase**
* **maxrand**
* **maxscale**
* **modexp**
* **print**
* **rand**
* **read**
* **seed**
* **stream**
If any of those keywords are used as a function, variable, or array name in
a script, use this option with the keyword as the argument. If multiple are
used, use this option for all of them; it can be used multiple times.
Keywords are *not* redefined when parsing the builtin math library (see the
**LIBRARY** section).
It is a fatal error to redefine keywords mandated by the POSIX standard. It
is a fatal error to attempt to redefine words that this bc(1) does not
reserve as keywords.
**-q**, **-\-quiet**
: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
Without this option, GNU bc(1) prints a copyright header. This bc(1) only
prints the copyright header if one or more of the **-v**, **-V**, or
**-\-version** options are given.
This is a **non-portable extension**.
**-s**, **-\-standard**
: Process exactly the language defined by the [standard][1] and error if any
extensions are used.
This is a **non-portable extension**.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
This is a **non-portable extension**.
**-w**, **-\-warn**
: Like **-s** and **-\-standard**, except that warnings (and not errors) are
printed for non-standard extensions and execution continues normally.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, bc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
**-\-expression** options, then bc(1) read from **stdin**.
However, there are a few caveats to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
the parse cannot complete. That means that starting a string without ending it
or starting a function, **if** statement, or loop without ending it will also
cause bc(1) to not execute.
Second, after an **if** statement, bc(1) doesn't know if an **else** statement
will follow, so it will not execute until it knows there will not be an **else**
statement.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **bc >&-**, it will quit with an error. This
is done so that bc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **bc 2>&-**, it will quit with an error. This
is done so that bc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other bc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
The syntax for bc(1) programs is mostly C-like, with some differences. This
bc(1) follows the [POSIX standard][1], which is a much more thorough resource
for the language this bc(1) accepts. This section is meant to be a summary and a
listing of all the extensions to the standard.
In the sections below, **E** means expression, **S** means statement, and **I**
means identifier.
Identifiers (**I**) start with a lowercase letter and can be followed by any
number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
Identifiers with more than one character (letter) are a
**non-portable extension**.
**ibase** is a global variable determining how to interpret constant numbers. It
is the "input" base, or the number base used for interpreting input numbers.
**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
(**-\-warn**) flags were not given on the command line, the max allowable value
for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
**ibase** is **2**. The max allowable value for **ibase** can be queried in
bc(1) programs with the **maxibase()** built-in function.
**obase** is a global variable determining how to output results. It is the
"output" base, or the number base used for outputting numbers. **obase** is
initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
can be queried in bc(1) programs with the **maxobase()** built-in function. The
min allowable value for **obase** is **0**. If **obase** is **0**, values are
output in scientific notation, and if **obase** is **1**, values are output in
engineering notation. Otherwise, values are output in the specified base.
Outputting in scientific and engineering notations are **non-portable
extensions**.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a global variable that
sets the precision of any operations, with exceptions. **scale** is initially
**0**. **scale** cannot be negative. The max allowable value for **scale** is
**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
built-in function.
bc(1) has both *global* variables and *local* variables. All *local*
variables are local to the function; they are parameters or are introduced in
the **auto** list of a function (see the **FUNCTIONS** section). If a variable
is accessed which is not a parameter or in the **auto** list, it is assumed to
be *global*. If a parent function has a *local* variable version of a variable
that a child function considers *global*, the value of that *global* variable in
the child function is the value of the variable in the parent function, not the
value of the actual *global* variable.
All of the above applies to arrays as well.
The value of a statement that is an expression (i.e., any of the named
expressions or operands) is printed unless the lowest precedence operator is an
assignment operator *and* the expression is notsurrounded by parentheses.
The value that is printed is also assigned to the special variable **last**. A
single dot (**.**) may also be used as a synonym for **last**. These are
**non-portable extensions**.
Either semicolons or newlines may separate statements.
## Comments
There are two kinds of comments:
1. Block comments are enclosed in **/\*** and **\*/**.
2. Line comments go from **#** until, and not including, the next newline. This
is a **non-portable extension**.
## Named Expressions
The following are named expressions in bc(1):
1. Variables: **I**
2. Array Elements: **I[E]**
3. **ibase**
4. **obase**
5. **scale**
6. **seed**
7. **last** or a single dot (**.**)
Numbers 6 and 7 are **non-portable extensions**.
The meaning of **seed** is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major versions.
The *scale* and sign of the value may be significant.
If a previously used **seed** value is assigned to **seed** and used again, the
pseudo-random number generator is guaranteed to produce the same sequence of
pseudo-random numbers as it did when the **seed** value was previously used.
The exact value assigned to **seed** is not guaranteed to be returned if
**seed** is queried again immediately. However, if **seed** *does* return a
different value, both values, when assigned to **seed**, are guaranteed to
produce the same sequence of pseudo-random numbers. This means that certain
values assigned to **seed** will *not* produce unique sequences of pseudo-random
numbers. The value of **seed** will change after any use of the **rand()** and
**irand(E)** operands (see the *Operands* subsection below), except if the
parameter passed to **irand(E)** is **0**, **1**, or negative.
There is no limit to the length (number of significant decimal digits) or
*scale* of the value that can be assigned to **seed**.
Variables and arrays do not interfere; users can have arrays named the same as
variables. This also applies to functions (see the **FUNCTIONS** section), so a
user can have a variable, array, and function that all have the same name, and
they will not shadow each other, whether inside of functions or not.
Named expressions are required as the operand of **increment**/**decrement**
operators and as the left side of **assignment** operators (see the *Operators*
subsection).
## Operands
The following are valid operands in bc(1):
1. Numbers (see the *Numbers* subsection below).
2. Array indices (**I[E]**).
3. **(E)**: The value of **E** (used to change precedence).
4. **sqrt(E)**: The square root of **E**. **E** must be non-negative.
5. **length(E)**: The number of significant decimal digits in **E**. Returns
**1** for **0** with no decimal places. If given a string, the length of the
string is returned. Passing a string to **length(E)** is a **non-portable
extension**.
6. **length(I[])**: The number of elements in the array **I**. This is a
**non-portable extension**.
7. **scale(E)**: The *scale* of **E**.
8. **abs(E)**: The absolute value of **E**. This is a **non-portable
extension**.
9. **modexp(E, E, E)**: Modular exponentiation, where the first expression is
the base, the second is the exponent, and the third is the modulus. All
three values must be integers. The second argument must be non-negative. The
third argument must be non-zero. This is a **non-portable extension**.
10. **divmod(E, E, I[])**: Division and modulus in one operation. This is for
optimization. The first expression is the dividend, and the second is the
divisor, which must be non-zero. The return value is the quotient, and the
modulus is stored in index **0** of the provided array (the last argument).
This is a **non-portable extension**.
11. **asciify(E)**: If **E** is a string, returns a string that is the first
letter of its argument. If it is a number, calculates the number mod **256**
and returns that number as a one-character string. This is a **non-portable
extension**.
12. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a non-**void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
13. **read()**: Reads a line from **stdin** and uses that as an expression. The
result of that expression is the result of the **read()** operand. This is a
**non-portable extension**.
14. **maxibase()**: The max allowable **ibase**. This is a **non-portable
extension**.
15. **maxobase()**: The max allowable **obase**. This is a **non-portable
extension**.
16. **maxscale()**: The max allowable **scale**. This is a **non-portable
extension**.
-17. **rand()**: A pseudo-random integer between **0** (inclusive) and
+17. **line_length()**: The line length set with **BC_LINE_LENGTH** (see the
+ **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**.
+18. **global_stacks()**: **0** if global stacks are not enabled with the **-g**
+ or **-\-global-stacks** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+19. **leading_zero()**: **0** if leading zeroes are not enabled with the **-z**
+ or **--leading-zeroes** options, non-zero otherwise. See the **OPTIONS**
+ section. This is a **non-portable extension**.
+20. **rand()**: A pseudo-random integer between **0** (inclusive) and
**BC_RAND_MAX** (inclusive). Using this operand will change the value of
**seed**. This is a **non-portable extension**.
-18. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
+21. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the
value of **E** (exclusive). If **E** is negative or is a non-integer
(**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see
the **RESET** section) while **seed** remains unchanged. If **E** is larger
than **BC_RAND_MAX**, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
**BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that
can be generated with this operand is unbounded. Using this operand will
change the value of **seed**, unless the value of **E** is **0** or **1**.
In that case, **0** is returned, and **seed** is *not* changed. This is a
**non-portable extension**.
-19. **maxrand()**: The max integer returned by **rand()**. This is a
+22. **maxrand()**: The max integer returned by **rand()**. This is a
**non-portable extension**.
The integers generated by **rand()** and **irand(E)** are guaranteed to be as
unbiased as possible, subject to the limitations of the pseudo-random number
generator.
**Note**: The values returned by the pseudo-random number generator with
**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator. However,
they *are* guaranteed to be reproducible with identical **seed** values. This
means that the pseudo-random values from bc(1) should only be used where a
reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
use a non-seeded pseudo-random number generator.
## Numbers
Numbers are strings made up of digits, uppercase letters, and at most **1**
period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
letters are equal to **9** + their position in the alphabet (i.e., **A** equals
**10**, or **9+1**). If a digit or letter makes no sense with the current value
of **ibase**, they are set to the value of the highest valid digit in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **Z** alone always equals decimal
**35**.
In addition, bc(1) accepts numbers in scientific notation. These have the form
**\e\**. The exponent (the portion after the **e**) must be
an integer. An example is **1.89237e9**, which is equal to **1892370000**.
Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**.
Using scientific notation is an error or warning if the **-s** or **-w**,
respectively, command-line options (or equivalents) are given.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For example,
if **ibase** is **16** and bc(1) is given the number string **FFeA**, the
resulting decimal number will be **2550000000000**, and if bc(1) is given the
number string **10e-4**, the resulting decimal number will be **0.0016**.
Accepting input as scientific notation is a **non-portable extension**.
## Operators
The following arithmetic and logical operators can be used. They are listed in
order of decreasing precedence. Operators in the same group have the same
precedence.
**++** **-\-**
: Type: Prefix and Postfix
Associativity: None
Description: **increment**, **decrement**
**-** **!**
: Type: Prefix
Associativity: None
Description: **negation**, **boolean not**
**\$**
: Type: Postfix
Associativity: None
Description: **truncation**
**\@**
: Type: Binary
Associativity: Right
Description: **set precision**
**\^**
: Type: Binary
Associativity: Right
Description: **power**
**\*** **/** **%**
: Type: Binary
Associativity: Left
Description: **multiply**, **divide**, **modulus**
**+** **-**
: Type: Binary
Associativity: Left
Description: **add**, **subtract**
**\<\<** **\>\>**
: Type: Binary
Associativity: Left
Description: **shift left**, **shift right**
**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
: Type: Binary
Associativity: Right
Description: **assignment**
**==** **\<=** **\>=** **!=** **\<** **\>**
: Type: Binary
Associativity: Left
Description: **relational**
**&&**
: Type: Binary
Associativity: Left
Description: **boolean and**
**||**
: Type: Binary
Associativity: Left
Description: **boolean or**
The operators will be described in more detail below.
**++** **-\-**
: The prefix and postfix **increment** and **decrement** operators behave
exactly like they would in C. They require a named expression (see the
*Named Expressions* subsection) as an operand.
The prefix versions of these operators are more efficient; use them where
possible.
**-**
: The **negation** operator returns **0** if a user attempts to negate any
expression with the value **0**. Otherwise, a copy of the expression with
its sign flipped is returned.
**!**
: The **boolean not** operator returns **1** if the expression is **0**, or
**0** otherwise.
This is a **non-portable extension**.
**\$**
: The **truncation** operator returns a copy of the given expression with all
of its *scale* removed.
This is a **non-portable extension**.
**\@**
: The **set precision** operator takes two expressions and returns a copy of
the first with its *scale* equal to the value of the second expression. That
could either mean that the number is returned without change (if the
*scale* of the first expression matches the value of the second
expression), extended (if it is less), or truncated (if it is more).
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**\^**
: The **power** operator (not the **exclusive or** operator, as it would be in
C) takes two expressions and raises the first to the power of the value of
the second. The *scale* of the result is equal to **scale**.
The second expression must be an integer (no *scale*), and if it is
negative, the first value must be non-zero.
**\***
: The **multiply** operator takes two expressions, multiplies them, and
returns the product. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result is
equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The **divide** operator takes two expressions, divides them, and returns the
quotient. The *scale* of the result shall be the value of **scale**.
The second expression must be non-zero.
**%**
: The **modulus** operator takes two expressions, **a** and **b**, and
evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The second expression must be non-zero.
**+**
: The **add** operator takes two expressions, **a** and **b**, and returns the
sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
**-**
: The **subtract** operator takes two expressions, **a** and **b**, and
returns the difference, with a *scale* equal to the max of the *scale*s of
**a** and **b**.
**\<\<**
: The **left shift** operator takes two expressions, **a** and **b**, and
returns a copy of the value of **a** with its decimal point moved **b**
places to the right.
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**\>\>**
: The **right shift** operator takes two expressions, **a** and **b**, and
returns a copy of the value of **a** with its decimal point moved **b**
places to the left.
The second expression must be an integer (no *scale*) and non-negative.
This is a **non-portable extension**.
**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
: The **assignment** operators take two expressions, **a** and **b** where
**a** is a named expression (see the *Named Expressions* subsection).
For **=**, **b** is copied and the result is assigned to **a**. For all
others, **a** and **b** are applied as operands to the corresponding
arithmetic operator and the result is assigned to **a**.
The **assignment** operators that correspond to operators that are
extensions are themselves **non-portable extensions**.
**==** **\<=** **\>=** **!=** **\<** **\>**
: The **relational** operators compare two expressions, **a** and **b**, and
if the relation holds, according to C language semantics, the result is
**1**. Otherwise, it is **0**.
Note that unlike in C, these operators have a lower precedence than the
**assignment** operators, which means that **a=b\>c** is interpreted as
**(a=b)\>c**.
Also, unlike the [standard][1] requires, these operators can appear anywhere
any other expressions can be used. This allowance is a
**non-portable extension**.
**&&**
: The **boolean and** operator takes two expressions and returns **1** if both
expressions are non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
**||**
: The **boolean or** operator takes two expressions and returns **1** if one
of the expressions is non-zero, **0** otherwise.
This is *not* a short-circuit operator.
This is a **non-portable extension**.
## Statements
The following items are statements:
1. **E**
2. **{** **S** **;** ... **;** **S** **}**
3. **if** **(** **E** **)** **S**
4. **if** **(** **E** **)** **S** **else** **S**
5. **while** **(** **E** **)** **S**
6. **for** **(** **E** **;** **E** **;** **E** **)** **S**
7. An empty statement
8. **break**
9. **continue**
10. **quit**
11. **halt**
12. **limits**
13. A string of characters, enclosed in double quotes
14. **print** **E** **,** ... **,** **E**
15. **stream** **E** **,** ... **,** **E**
16. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
**I[]**, which will automatically be turned into array references (see the
*Array References* subsection of the **FUNCTIONS** section) if the
corresponding parameter in the function definition is an array reference.
Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
Also, as a **non-portable extension**, any or all of the expressions in the
header of a for loop may be omitted. If the condition (second expression) is
omitted, it is assumed to be a constant **1**.
The **break** statement causes a loop to stop iterating and resume execution
immediately following a loop. This is only allowed in loops.
The **continue** statement causes a loop iteration to stop early and returns to
the start of the loop, including testing the loop condition. This is only
allowed in loops.
The **if** **else** statement does the same thing as in C.
The **quit** statement causes bc(1) to quit, even if it is on a branch that will
not be executed (it is a compile-time command).
The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
if it is on a branch of an **if** statement that is not executed, bc(1) does not
quit.)
The **limits** statement prints the limits that this bc(1) is subject to. This
is like the **quit** statement in that it is a compile-time command.
An expression by itself is evaluated and printed, followed by a newline.
Both scientific notation and engineering notation are available for printing the
results of expressions. Scientific notation is activated by assigning **0** to
**obase**, and engineering notation is activated by assigning **1** to
**obase**. To deactivate them, just assign a different value to **obase**.
Scientific notation and engineering notation are disabled if bc(1) is run with
either the **-s** or **-w** command-line options (or equivalents).
Printing numbers in scientific notation and/or engineering notation is a
**non-portable extension**.
## Strings
If strings appear as a statement by themselves, they are printed without a
trailing newline.
In addition to appearing as a lone statement by themselves, strings can be
assigned to variables and array elements. They can also be passed to functions
in variable parameters.
If any statement that expects a string is given a variable that had a string
assigned to it, the statement acts as though it had received a string.
If any math operation is attempted on a string or a variable or array element
that has been assigned a string, an error is raised, and bc(1) resets (see the
**RESET** section).
Assigning strings to variables and array elements and passing them to functions
are **non-portable extensions**.
## Print Statement
The "expressions" in a **print** statement may also be strings. If they are, there
are backslash escape sequences that are interpreted specially. What those
sequences are, and what they cause to be printed, are shown below:
**\\a**: **\\a**
**\\b**: **\\b**
**\\\\**: **\\**
**\\e**: **\\**
**\\f**: **\\f**
**\\n**: **\\n**
**\\q**: **"**
**\\r**: **\\r**
**\\t**: **\\t**
Any other character following a backslash causes the backslash and character to
be printed as-is.
Any non-string expression in a print statement shall be assigned to **last**,
like any other expression that is printed.
## Stream Statement
The "expressions in a **stream** statement may also be strings.
If a **stream** statement is given a string, it prints the string as though the
string had appeared as its own statement. In other words, the **stream**
statement prints strings normally, without a newline.
If a **stream** statement is given a number, a copy of it is truncated and its
absolute value is calculated. The result is then printed as though **obase** is
**256** and each digit is interpreted as an 8-bit ASCII character, making it a
byte stream.
## Order of Evaluation
All expressions in a statment are evaluated left to right, except as necessary
to maintain order of operations. This means, for example, assuming that **i** is
equal to **0**, in the expression
a[i++] = i++
the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
at the end of the expression.
This includes function arguments. Thus, assuming **i** is equal to **0**, this
means that in the expression
x(i++, i++)
the first argument passed to **x()** is **0**, and the second argument is **1**,
while **i** is equal to **2** before the function starts executing.
# FUNCTIONS
Function definitions are as follows:
```
define I(I,...,I){
auto I,...,I
S;...;S
return(E)
}
```
Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
make a parameter or **auto** var an array, and any **I** in the parameter list
may be replaced with **\*I[]** to make a parameter an array reference. Callers
of functions that take array references should not put an asterisk in the call;
they must be called with just **I[]** like normal array parameters and will be
automatically converted into references.
As a **non-portable extension**, the opening brace of a **define** statement may
appear on the next line.
As a **non-portable extension**, the return statement may also be in one of the
following forms:
1. **return**
2. **return** **(** **)**
3. **return** **E**
The first two, or not specifying a **return** statement, is equivalent to
**return (0)**, unless the function is a **void** function (see the *Void
Functions* subsection below).
## Void Functions
Functions can also be **void** functions, defined as follows:
```
define void I(I,...,I){
auto I,...,I
S;...;S
return
}
```
They can only be used as standalone expressions, where such an expression would
be printed alone, except in a print statement.
Void functions can only use the first two **return** statements listed above.
They can also omit the return statement entirely.
The word "void" is not treated as a keyword; it is still possible to have
variables, arrays, and functions named **void**. The word "void" is only
treated specially right after the **define** keyword.
This is a **non-portable extension**.
## Array References
For any array in the parameter list, if the array is declared in the form
```
*I[]
```
it is a **reference**. Any changes to the array in the function are reflected,
when the function returns, to the array that was passed in.
Other than this, all function arguments are passed by value.
This is a **non-portable extension**.
# LIBRARY
All of the functions below, including the functions in the extended math
library (see the *Extended Library* subsection below), are available when the
**-l** or **-\-mathlib** command-line flags are given, except that the extended
math library is not available when the **-s** option, the **-w** option, or
equivalents are given.
## Standard Library
The [standard][1] defines the following functions for the math library:
**s(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**c(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a(x)**
: Returns the arctangent of **x**, in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l(x)**
: Returns the natural logarithm of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**e(x)**
: Returns the mathematical constant **e** raised to the power of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**j(x, n)**
: Returns the bessel integer order **n** (truncated) of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
## Extended Library
The extended library is *not* loaded when the **-s**/**-\-standard** or
**-w**/**-\-warn** options are given since they are not part of the library
defined by the [standard][1].
The extended library is a **non-portable extension**.
**p(x, y)**
: Calculates **x** to the power of **y**, even if **y** is not an integer, and
returns the result to the current **scale**.
It is an error if **y** is negative and **x** is **0**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**r(x, p)**
: Returns **x** rounded to **p** decimal places according to the rounding mode
[round half away from **0**][3].
**ceil(x, p)**
: Returns **x** rounded to **p** decimal places according to the rounding mode
[round away from **0**][6].
**f(x)**
: Returns the factorial of the truncated absolute value of **x**.
**perm(n, k)**
: Returns the permutation of the truncated absolute value of **n** of the
truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
**comb(n, k)**
: Returns the combination of the truncated absolute value of **n** of the
truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
**l2(x)**
: Returns the logarithm base **2** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**l10(x)**
: Returns the logarithm base **10** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**log(x, b)**
: Returns the logarithm base **b** of **x**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**cbrt(x)**
: Returns the cube root of **x**.
**root(x, n)**
: Calculates the truncated value of **n**, **r**, and returns the **r**th root
of **x** to the current **scale**.
If **r** is **0** or negative, this raises an error and causes bc(1) to
reset (see the **RESET** section). It also raises an error and causes bc(1)
to reset if **r** is even and **x** is negative.
**gcd(a, b)**
: Returns the greatest common divisor (factor) of the truncated absolute value
of **a** and the truncated absolute value of **b**.
**lcm(a, b)**
: Returns the least common multiple of the truncated absolute value of **a**
and the truncated absolute value of **b**.
**pi(p)**
: Returns **pi** to **p** decimal places.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**t(x)**
: Returns the tangent of **x**, which is assumed to be in radians.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**a2(y, x)**
: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
equal to **0**, it raises an error and causes bc(1) to reset (see the
**RESET** section). Otherwise, if **x** is greater than **0**, it returns
**a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
**0**, and **y** is less than **0**, it returns **-pi/2**.
This function is the same as the **atan2()** function in many programming
languages.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**sin(x)**
: Returns the sine of **x**, which is assumed to be in radians.
This is an alias of **s(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**cos(x)**
: Returns the cosine of **x**, which is assumed to be in radians.
This is an alias of **c(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**tan(x)**
: Returns the tangent of **x**, which is assumed to be in radians.
If **x** is equal to **1** or **-1**, this raises an error and causes bc(1)
to reset (see the **RESET** section).
This is an alias of **t(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**atan(x)**
: Returns the arctangent of **x**, in radians.
This is an alias of **a(x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**atan2(y, x)**
: Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
equal to **0**, it raises an error and causes bc(1) to reset (see the
**RESET** section). Otherwise, if **x** is greater than **0**, it returns
**a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
**0**, and **y** is less than **0**, it returns **-pi/2**.
This function is the same as the **atan2()** function in many programming
languages.
This is an alias of **a2(y, x)**.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**r2d(x)**
: Converts **x** from radians to degrees and returns the result.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**d2r(x)**
: Converts **x** from degrees to radians and returns the result.
This is a transcendental function (see the *Transcendental Functions*
subsection below).
**frand(p)**
: Generates a pseudo-random number between **0** (inclusive) and **1**
(exclusive) with the number of decimal digits after the decimal point equal
to the truncated absolute value of **p**. If **p** is not **0**, then
calling this function will change the value of **seed**. If **p** is **0**,
then **0** is returned, and **seed** is *not* changed.
**ifrand(i, p)**
: Generates a pseudo-random number that is between **0** (inclusive) and the
truncated absolute value of **i** (exclusive) with the number of decimal
digits after the decimal point equal to the truncated absolute value of
**p**. If the absolute value of **i** is greater than or equal to **2**, and
**p** is not **0**, then calling this function will change the value of
**seed**; otherwise, **0** is returned and **seed** is not changed.
**srand(x)**
: Returns **x** with its sign flipped with probability **0.5**. In other
words, it randomizes the sign of **x**.
**brand()**
: Returns a random boolean value (either **0** or **1**).
**band(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **and** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bor(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **or** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bxor(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of the bitwise **xor** operation between them.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bshl(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the result of **a** bit-shifted left by **b** places.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bshr(a, b)**
: Takes the truncated absolute value of both **a** and **b** and calculates
and returns the truncated result of **a** bit-shifted right by **b** places.
If you want to use signed two's complement arguments, use **s2u(x)** to
convert.
**bnotn(x, n)**
: Takes the truncated absolute value of **x** and does a bitwise not as though
it has the same number of bytes as the truncated absolute value of **n**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot8(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**8** binary digits (1 unsigned byte).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot16(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**16** binary digits (2 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot32(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**32** binary digits (4 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot64(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
**64** binary digits (8 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bnot(x)**
: Does a bitwise not of the truncated absolute value of **x** as though it has
the minimum number of power of two unsigned bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brevn(x, n)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has the same number of 8-bit bytes as the truncated absolute value of **n**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev8(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 8 binary digits (1 unsigned byte).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev16(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 16 binary digits (2 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev32(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 32 binary digits (4 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev64(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has 64 binary digits (8 unsigned bytes).
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brev(x)**
: Runs a bit reversal on the truncated absolute value of **x** as though it
has the minimum number of power of two unsigned bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**broln(x, p, n)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has the same number of unsigned 8-bit bytes as the truncated
absolute value of **n**, by the number of places equal to the truncated
absolute value of **p** modded by the **2** to the power of the number of
binary digits in **n** 8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol8(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **8** binary digits (**1** unsigned byte), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol16(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **16** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol32(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **32** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol64(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has **64** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brol(x, p)**
: Does a left bitwise rotatation of the truncated absolute value of **x**, as
though it has the minimum number of power of two unsigned 8-bit bytes, by
the number of places equal to the truncated absolute value of **p** modded
by 2 to the power of the number of binary digits in the minimum number of
8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**brorn(x, p, n)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has the same number of unsigned 8-bit bytes as the truncated
absolute value of **n**, by the number of places equal to the truncated
absolute value of **p** modded by the **2** to the power of the number of
binary digits in **n** 8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror8(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **8** binary digits (**1** unsigned byte), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror16(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **16** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror32(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **32** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror64(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has **64** binary digits (**2** unsigned bytes), by the number of
places equal to the truncated absolute value of **p** modded by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bror(x, p)**
: Does a right bitwise rotatation of the truncated absolute value of **x**, as
though it has the minimum number of power of two unsigned 8-bit bytes, by
the number of places equal to the truncated absolute value of **p** modded
by 2 to the power of the number of binary digits in the minimum number of
8-bit bytes.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmodn(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of the multiplication of the truncated absolute value of **n** and
**8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod8(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **8**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod16(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **16**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod32(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **32**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bmod64(x, n)**
: Returns the modulus of the truncated absolute value of **x** by **2** to the
power of **64**.
If you want to a use signed two's complement argument, use **s2u(x)** to
convert.
**bunrev(t)**
: Assumes **t** is a bitwise-reversed number with an extra set bit one place
more significant than the real most significant bit (which was the least
significant bit in the original number). This number is reversed and
returned without the extra set bit.
This function is used to implement other bitwise functions; it is not meant
to be used by users, but it can be.
+**plz(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed with a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and without a trailing newline.
+
+ Otherwise, **x** is printed normally, without a trailing newline.
+
+**plznl(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed with a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and with a trailing newline.
+
+ Otherwise, **x** is printed normally, with a trailing newline.
+
+**pnlz(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed without a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and without a trailing newline.
+
+ Otherwise, **x** is printed normally, without a trailing newline.
+
+**pnlznl(x)**
+
+: If **x** is not equal to **0** and greater that **-1** and less than **1**,
+ it is printed without a leading zero, regardless of the use of the **-z**
+ option (see the **OPTIONS** section) and with a trailing newline.
+
+ Otherwise, **x** is printed normally, with a trailing newline.
+
**ubytes(x)**
: Returns the numbers of unsigned integer bytes required to hold the truncated
absolute value of **x**.
**sbytes(x)**
: Returns the numbers of signed, two's-complement integer bytes required to
hold the truncated value of **x**.
**s2u(x)**
: Returns **x** if it is non-negative. If it *is* negative, then it calculates
what **x** would be as a 2's-complement signed integer and returns the
non-negative integer that would have the same representation in binary.
**s2un(x,n)**
: Returns **x** if it is non-negative. If it *is* negative, then it calculates
what **x** would be as a 2's-complement signed integer with **n** bytes and
returns the non-negative integer that would have the same representation in
binary. If **x** cannot fit into **n** 2's-complement signed bytes, it is
truncated to fit.
**hex(x)**
: Outputs the hexadecimal (base **16**) representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**binary(x)**
: Outputs the binary (base **2**) representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output(x, b)**
: Outputs the base **b** representation of **x**.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in as few power of two bytes as possible. Both outputs are
split into bytes separated by spaces.
If **x** is not an integer or is negative, an error message is printed
instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in as few power of two bytes as possible. Both
outputs are split into bytes separated by spaces.
If **x** is not an integer, an error message is printed instead, but bc(1)
is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uintn(x, n)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **n** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **n** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**intn(x, n)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **n** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **n** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint8(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **1** byte. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **1** byte, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int8(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **1** byte. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **1** byte, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint16(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **2** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **2** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int16(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **2** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **2** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint32(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **4** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **4** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int32(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **4** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **4** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**uint64(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as an
unsigned integer in **8** bytes. Both outputs are split into bytes separated
by spaces.
If **x** is not an integer, is negative, or cannot fit into **8** bytes, an
error message is printed instead, but bc(1) is not reset (see the **RESET**
section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**int64(x)**
: Outputs the representation, in binary and hexadecimal, of **x** as a signed,
two's-complement integer in **8** bytes. Both outputs are split into bytes
separated by spaces.
If **x** is not an integer or cannot fit into **8** bytes, an error message
is printed instead, but bc(1) is not reset (see the **RESET** section).
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**hex_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in hexadecimal using **n** bytes. Not all of the value will
be output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**binary_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in binary using **n** bytes. Not all of the value will be
output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output_uint(x, n)**
: Outputs the representation of the truncated absolute value of **x** as an
unsigned integer in the current **obase** (see the **SYNTAX** section) using
**n** bytes. Not all of the value will be output if **n** is too small.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
**output_byte(x, i)**
: Outputs byte **i** of the truncated absolute value of **x**, where **0** is
the least significant byte and **number_of_bytes - 1** is the most
significant byte.
This is a **void** function (see the *Void Functions* subsection of the
**FUNCTIONS** section).
## Transcendental Functions
All transcendental functions can return slightly inaccurate results (up to 1
[ULP][4]). This is unavoidable, and [this article][5] explains why it is
impossible and unnecessary to calculate exact results for the transcendental
functions.
Because of the possible inaccuracy, I recommend that users call those functions
with the precision (**scale**) set to at least 1 higher than is necessary. If
exact results are *absolutely* required, users can double the precision
(**scale**) and then truncate.
The transcendental functions in the standard math library are:
* **s(x)**
* **c(x)**
* **a(x)**
* **l(x)**
* **e(x)**
* **j(x, n)**
The transcendental functions in the extended math library are:
* **l2(x)**
* **l10(x)**
* **log(x, b)**
* **pi(p)**
* **t(x)**
* **a2(y, x)**
* **sin(x)**
* **cos(x)**
* **tan(x)**
* **atan(x)**
* **atan2(y, x)**
* **r2d(x)**
* **d2r(x)**
# RESET
When bc(1) encounters an error or a signal that it has a non-default handler
for, it resets. This means that several things happen.
First, any functions 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.
Thus, when bc(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.
Note that this reset behavior is different from the GNU bc(1), which attempts to
start executing the statement right after the one that caused an error.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This bc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
the **limits** statement.
In addition, this bc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bc(1):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bc(1) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_STRING_MAX**
: The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
**BC_NAME_MAX**
: The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
**BC_RAND_MAX**
: The maximum integer (inclusive) returned by the **rand()** operand. Set at
**2\^BC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
The actual values can be queried with the **limits** statement.
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.
# ENVIRONMENT VARIABLES
bc(1) recognizes the following environment variables:
**POSIXLY_CORRECT**
: If this variable exists (no matter the contents), bc(1) behaves as if
the **-s** option was given.
**BC_ENV_ARGS**
: This is another way to give command-line arguments to bc(1). They should be
in the same format as all other command-line arguments. These are always
processed first, so any files given in **BC_ENV_ARGS** 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 bc(1) runs.
The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
**"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'bc' file.bc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **BC_ENV_ARGS** 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.
**BC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
lines to that length, including the backslash (**\\**). The default line
length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**BC_BANNER**
: If this environment variable exists and contains an integer, then a non-zero
value activates the copyright banner when bc(1) is in interactive mode,
while zero deactivates it.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) does not print
the banner when not in interactive mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_SIGINT_RESET**
: If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because bc(1) exits on
**SIGINT** when not in interactive mode.
However, when bc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes bc(1) reset
on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
environment variable exists and is *not* an integer, then bc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes bc(1) use TTY
mode, and zero makes bc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**BC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes bc(1) use a prompt,
and zero or a non-integer makes bc(1) not use a prompt. If this environment
variable does not exist and **BC_TTY_MODE** does, then the value of the
**BC_TTY_MODE** environment variable is used.
This environment variable and the **BC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
bc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, 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, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**)
operators and their corresponding assignment operators.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, using a token where it is invalid,
giving an invalid expression, giving an invalid print statement, giving an
invalid function definition, attempting to assign to an expression that is
not a named expression (see the *Named Expressions* subsection of the
**SYNTAX** section), giving an invalid **auto** list, having a duplicate
**auto**/function parameter, failing to find the end of a code block,
attempting to return a value from a **void** function, attempting to use a
variable as a reference, and using any extensions when the option **-s** or
any equivalents were given.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors, passing the
wrong number of arguments to functions, attempting to call an undefined
function, and attempting to use a **void** function call as a value in an
expression.
**4**
: A fatal error occurred.
Fatal errors include memory allocation errors, I/O errors, failing to open
files, attempting to use files that do not have only ASCII characters (bc(1)
only accepts ASCII characters), attempting to open a directory as a file,
and giving invalid command-line options.
The exit status **4** is special; when a fatal error occurs, bc(1) always exits
and returns **4**, no matter what mode bc(1) is in.
The other statuses will only be returned when bc(1) is not in interactive mode
(see the **INTERACTIVE MODE** section), since bc(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
**-i** flag or **-\-interactive** option.
These exit statuses allow bc(1) to be used in shell scripting with error
checking, and its normal behavior can be forced by using the **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **BC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **BC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
mode on.
If the environment variable **BC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
**stdout**, and **stderr** are connected to a TTY and the **BC_TTY_MODE**
environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
information.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **BC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause bc(1) to do one of two things.
If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, bc(1) will
exit.
However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
default is an integer and non-zero, then bc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If bc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If bc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
can seem as though bc(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 bc(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.
**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is **SIGHUP**; in that
case, and only when bc(1) is in TTY mode (see the **TTY MODE** section), a
**SIGHUP** will cause bc(1) to clean up and exit.
# COMMAND LINE HISTORY
bc(1) supports interactive command-line editing.
If bc(1) can be in TTY mode (see the **TTY MODE** section), history can be
enabled. This means that command-line history can only be enabled when
**stdin**, **stdout**, and **stderr** are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment variable
**BC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
If history is enabled, previous lines can be recalled and edited with the arrow
keys.
**Note**: tabs are converted to 8 spaces.
# SEE ALSO
dc(1)
# STANDARDS
bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
specification. The flags **-efghiqsvVw**, all long options, and the extensions
noted above are extensions to that specification.
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
[2]: https://www.gnu.org/software/bc/
[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
diff --git a/manuals/bcl.3 b/manuals/bcl.3
index c079a20c40ba..9370417dcfef 100644
--- a/manuals/bcl.3
+++ b/manuals/bcl.3
@@ -1,1369 +1,1394 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "BCL" "3" "June 2021" "Gavin D. Howard" "Libraries Manual"
.SH NAME
.PP
bcl - library of arbitrary precision decimal arithmetic
.SH SYNOPSIS
.SS Use
.PP
\f[I]#include \f[R]
.PP
Link with \f[I]-lbcl\f[R].
.SS Signals
.PP
This procedure will allow clients to use signals to interrupt
computations running in bcl(3).
.PP
\f[B]void bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]bool bcl_running(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.SS Setup
.PP
These items allow clients to set up bcl(3).
.PP
\f[B]BclError bcl_init(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_free(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]bool bcl_abortOnFatalError(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_setAbortOnFatalError(bool\f[R] \f[I]abrt\f[R]\f[B]);\f[R]
.PP
+\f[B]bool bcl_leadingZeroes(\f[R]\f[I]void\f[R]\f[B]);\f[R]
+.PP
+\f[B]void bcl_setLeadingZeroes(bool\f[R]
+\f[I]leadingZeroes\f[R]\f[B]);\f[R]
+.PP
\f[B]void bcl_gc(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.SS Contexts
.PP
These items will allow clients to handle contexts, which are isolated
from each other.
This allows more than one client to use bcl(3) in the same program.
.PP
\f[B]struct BclCtxt;\f[R]
.PP
\f[B]typedef struct BclCtxt* BclContext;\f[R]
.PP
\f[B]BclContext bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_ctxt_free(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R]
.PP
\f[B]BclError bcl_pushContext(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_popContext(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]BclContext bcl_context(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_ctxt_freeNums(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R]
.PP
\f[B]size_t bcl_ctxt_scale(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_ctxt_setScale(BclContext\f[R] \f[I]ctxt\f[R]\f[B],
size_t\f[R] \f[I]scale\f[R]\f[B]);\f[R]
.PP
\f[B]size_t bcl_ctxt_ibase(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_ctxt_setIbase(BclContext\f[R] \f[I]ctxt\f[R]\f[B],
size_t\f[R] \f[I]ibase\f[R]\f[B]);\f[R]
.PP
\f[B]size_t bcl_ctxt_obase(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_ctxt_setObase(BclContext\f[R] \f[I]ctxt\f[R]\f[B],
size_t\f[R] \f[I]obase\f[R]\f[B]);\f[R]
.SS Errors
.PP
These items allow clients to handle errors.
.PP
\f[B]typedef enum BclError BclError;\f[R]
.PP
\f[B]BclError bcl_err(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R]
.SS Numbers
.PP
These items allow clients to manipulate and query the
arbitrary-precision numbers managed by bcl(3).
.PP
\f[B]typedef struct { size_t i; } BclNumber;\f[R]
.PP
\f[B]BclNumber bcl_num_create(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_num_free(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R]
.PP
\f[B]bool bcl_num_neg(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_num_setNeg(BclNumber\f[R] \f[I]n\f[R]\f[B], bool\f[R]
\f[I]neg\f[R]\f[B]);\f[R]
.PP
\f[B]size_t bcl_num_scale(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R]
.PP
\f[B]BclError bcl_num_setScale(BclNumber\f[R] \f[I]n\f[R]\f[B],
size_t\f[R] \f[I]scale\f[R]\f[B]);\f[R]
.PP
\f[B]size_t bcl_num_len(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R]
.SS Conversion
.PP
These items allow clients to convert numbers into and from strings and
integers.
.PP
\f[B]BclNumber bcl_parse(const char *restrict\f[R]
\f[I]val\f[R]\f[B]);\f[R]
.PP
\f[B]char* bcl_string(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R]
.PP
\f[B]BclError bcl_bigdig(BclNumber\f[R] \f[I]n\f[R]\f[B], BclBigDig
*\f[R]\f[I]result\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_bigdig2num(BclBigDig\f[R] \f[I]val\f[R]\f[B]);\f[R]
.SS Math
.PP
These items allow clients to run math on numbers.
.PP
\f[B]BclNumber bcl_add(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R]
\f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_sub(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R]
\f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_mul(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R]
\f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_div(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R]
\f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_mod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R]
\f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_pow(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R]
\f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_lshift(BclNumber\f[R] \f[I]a\f[R]\f[B],
BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_rshift(BclNumber\f[R] \f[I]a\f[R]\f[B],
BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_sqrt(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R]
.PP
\f[B]BclError bcl_divmod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R]
\f[I]b\f[R]\f[B], BclNumber *\f[R]\f[I]c\f[R]\f[B], BclNumber
*\f[R]\f[I]d\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_modexp(BclNumber\f[R] \f[I]a\f[R]\f[B],
BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber\f[R] \f[I]c\f[R]\f[B]);\f[R]
.SS Miscellaneous
.PP
These items are miscellaneous.
.PP
\f[B]void bcl_zero(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R]
.PP
\f[B]void bcl_one(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R]
.PP
\f[B]ssize_t bcl_cmp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R]
\f[I]b\f[R]\f[B]);\f[R]
.PP
\f[B]BclError bcl_copy(BclNumber\f[R] \f[I]d\f[R]\f[B], BclNumber\f[R]
\f[I]s\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_dup(BclNumber\f[R] \f[I]s\f[R]\f[B]);\f[R]
.SS Pseudo-Random Number Generator
.PP
These items allow clients to manipulate the seeded pseudo-random number
generator in bcl(3).
.PP
\f[B]#define BCL_SEED_ULONGS\f[R]
.PP
\f[B]#define BCL_SEED_SIZE\f[R]
.PP
\f[B]typedef unsigned long BclBigDig;\f[R]
.PP
\f[B]typedef unsigned long BclRandInt;\f[R]
.PP
\f[B]BclNumber bcl_irand(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_frand(size_t\f[R] \f[I]places\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_ifrand(BclNumber\f[R] \f[I]a\f[R]\f[B], size_t\f[R]
\f[I]places\f[R]\f[B]);\f[R]
.PP
\f[B]BclError bcl_rand_seedWithNum(BclNumber\f[R]
\f[I]n\f[R]\f[B]);\f[R]
.PP
\f[B]BclError bcl_rand_seed(unsigned char\f[R]
\f[I]seed\f[R]\f[B][\f[R]\f[I]BCL_SEED_SIZE\f[R]\f[B]]);\f[R]
.PP
\f[B]void bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]BclNumber bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]BclRandInt bcl_rand_int(\f[R]\f[I]void\f[R]\f[B]);\f[R]
.PP
\f[B]BclRandInt bcl_rand_bounded(BclRandInt\f[R]
\f[I]bound\f[R]\f[B]);\f[R]
.SH DESCRIPTION
.PP
bcl(3) is a library that implements arbitrary-precision decimal math, as
standardized by
POSIX (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
in bc(1).
.PP
bcl(3) is async-signal-safe if
\f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] is used properly.
(See the \f[B]SIGNAL HANDLING\f[R] section.)
.PP
-bcl(3) assumes that it is allowed to use the \f[B]bcl_\f[R] and
-\f[B]bc_\f[R] prefixes for symbol names without collision.
+bcl(3) assumes that it is allowed to use the \f[B]bcl\f[R],
+\f[B]Bcl\f[R], \f[B]bc\f[R], and \f[B]Bc\f[R] prefixes for symbol names
+without collision.
.PP
All of the items in its interface are described below.
See the documentation for each function for what each function can
return.
.SS Signals
.TP
\f[B]void bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R]
An async-signal-safe function that can be called from a signal handler.
If called from a signal handler on the same thread as any executing
bcl(3) functions, it will interrupt the functions and force them to
return early.
It is undefined behavior if this function is called from a thread that
is \f[I]not\f[R] executing any bcl(3) functions while any bcl(3)
functions are executing.
.RS
.PP
If execution \f[I]is\f[R] interrupted,
\f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] does \f[I]not\f[R]
return to its caller.
.PP
See the \f[B]SIGNAL HANDLING\f[R] section.
.RE
.TP
\f[B]bool bcl_running(\f[R]\f[I]void\f[R]\f[B])\f[R]
An async-signal-safe function that can be called from a signal handler.
It will return \f[B]true\f[R] if any bcl(3) procedures are running,
which means it is safe to call
\f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R].
Otherwise, it returns \f[B]false\f[R].
.RS
.PP
See the \f[B]SIGNAL HANDLING\f[R] section.
.RE
.SS Setup
.TP
\f[B]BclError bcl_init(\f[R]\f[I]void\f[R]\f[B])\f[R]
Initializes this library.
This function can be called multiple times, but each call must be
matched by a call to \f[B]bcl_free(\f[R]\f[I]void\f[R]\f[B])\f[R].
This is to make it possible for multiple libraries and applications to
initialize bcl(3) without problem.
.RS
.PP
If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned.
Otherwise, this function can return:
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.PP
This function must be the first one clients call.
Calling any other function without calling this one first is undefined
behavior.
.RE
.TP
\f[B]void bcl_free(\f[R]\f[I]void\f[R]\f[B])\f[R]
Decrements bcl(3)\[cq]s reference count and frees the data associated
with it if the reference count is \f[B]0\f[R].
.RS
.PP
This function must be the last one clients call.
Calling this function before calling any other function is undefined
behavior.
.RE
.TP
\f[B]bool bcl_abortOnFatalError(\f[R]\f[I]void\f[R]\f[B])\f[R]
Queries and returns the current state of calling \f[B]abort()\f[R] on
fatal errors.
If \f[B]true\f[R] is returned, bcl(3) will cause a \f[B]SIGABRT\f[R] if
a fatal error occurs.
.RS
.PP
If activated, clients do not need to check for fatal errors.
+.PP
+The default is \f[B]false\f[R].
.RE
.TP
\f[B]void bcl_setAbortOnFatalError(bool\f[R] \f[I]abrt\f[R]\f[B])\f[R]
Sets the state of calling \f[B]abort()\f[R] on fatal errors.
If \f[I]abrt\f[R] is \f[B]false\f[R], bcl(3) will not cause a
\f[B]SIGABRT\f[R] on fatal errors after the call.
If \f[I]abrt\f[R] is \f[B]true\f[R], bcl(3) will cause a
\f[B]SIGABRT\f[R] on fatal errors after the call.
.RS
.PP
If activated, clients do not need to check for fatal errors.
.RE
.TP
+\f[B]bool bcl_leadingZeroes(\f[R]\f[I]void\f[R]\f[B])\f[R]
+Queries and returns the state of whether leading zeroes are added to
+strings returned by \f[B]bcl_string()\f[R] when numbers are greater than
+\f[B]-1\f[R], less than \f[B]1\f[R], and not equal to \f[B]0\f[R].
+If \f[B]true\f[R] is returned, then leading zeroes will be added.
+.RS
+.PP
+The default is \f[B]false\f[R].
+.RE
+.TP
+\f[B]void bcl_setLeadingZeroes(bool\f[R] \f[I]leadingZeroes\f[R]\f[B])\f[R]
+Sets the state of whether leading zeroes are added to strings returned
+by \f[B]bcl_string()\f[R] when numbers are greater than \f[B]-1\f[R],
+less than \f[B]1\f[R], and not equal to \f[B]0\f[R].
+If \f[I]leadingZeroes\f[R] is \f[B]true\f[R], leading zeroes will be
+added to strings returned by \f[B]bcl_string()\f[R].
+.TP
\f[B]void bcl_gc(\f[R]\f[I]void\f[R]\f[B])\f[R]
Garbage collects cached instances of arbitrary-precision numbers.
This only frees the memory of numbers that are \f[I]not\f[R] in use, so
it is safe to call at any time.
.SS Contexts
.PP
All procedures that take a \f[B]BclContext\f[R] parameter a require a
valid context as an argument.
.TP
\f[B]struct BclCtxt\f[R]
A forward declaration for a hidden \f[B]struct\f[R] type.
Clients cannot access the internals of the \f[B]struct\f[R] type
directly.
All interactions with the type are done through pointers.
See \f[B]BclContext\f[R] below.
.TP
\f[B]BclContext\f[R]
A typedef to a pointer of \f[B]struct BclCtxt\f[R].
This is the only handle clients can get to \f[B]struct BclCtxt\f[R].
.RS
.PP
A \f[B]BclContext\f[R] contains the values \f[B]scale\f[R],
\f[B]ibase\f[R], and \f[B]obase\f[R], as well as a list of numbers.
.PP
\f[B]scale\f[R] is a value used to control how many decimal places
calculations should use.
A value of \f[B]0\f[R] means that calculations are done on integers
only, where applicable, and a value of 20, for example, means that all
applicable calculations return results with 20 decimal places.
The default is \f[B]0\f[R].
.PP
\f[B]ibase\f[R] is a value used to control the input base.
The minimum \f[B]ibase\f[R] is \f[B]2\f[R], and the maximum is
\f[B]36\f[R].
If \f[B]ibase\f[R] is \f[B]2\f[R], numbers are parsed as though they are
in binary, and any digits larger than \f[B]1\f[R] are clamped.
Likewise, a value of \f[B]10\f[R] means that numbers are parsed as
though they are decimal, and any larger digits are clamped.
The default is \f[B]10\f[R].
.PP
\f[B]obase\f[R] is a value used to control the output base.
The minimum \f[B]obase\f[R] is \f[B]0\f[R] and the maximum is
\f[B]BC_BASE_MAX\f[R] (see the \f[B]LIMITS\f[R] section).
.PP
Numbers created in one context are not valid in another context.
It is undefined behavior to use a number created in a different context.
Contexts are meant to isolate the numbers used by different clients in
the same application.
.RE
.TP
\f[B]BclContext bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B])\f[R]
Creates a context and returns it.
Returns \f[B]NULL\f[R] if there was an error.
.TP
\f[B]void bcl_ctxt_free(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R]
Frees \f[I]ctxt\f[R], after which it is no longer valid.
It is undefined behavior to attempt to use an invalid context.
.TP
\f[B]BclError bcl_pushContext(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R]
Pushes \f[I]ctxt\f[R] onto bcl(3)\[cq]s stack of contexts.
\f[I]ctxt\f[R] must have been created with
\f[B]bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B])\f[R].
.RS
.PP
If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned.
Otherwise, this function can return:
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.PP
There \f[I]must\f[R] be a valid context to do any arithmetic.
.RE
.TP
\f[B]void bcl_popContext(\f[R]\f[I]void\f[R]\f[B])\f[R]
Pops the current context off of the stack, if one exists.
.TP
\f[B]BclContext bcl_context(\f[R]\f[I]void\f[R]\f[B])\f[R]
Returns the current context, or \f[B]NULL\f[R] if no context exists.
.TP
\f[B]void bcl_ctxt_freeNums(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R]
Frees all numbers in use that are associated with \f[I]ctxt\f[R].
It is undefined behavior to attempt to use a number associated with
\f[I]ctxt\f[R] after calling this procedure unless such numbers have
been created with \f[B]bcl_num_create(\f[R]\f[I]void\f[R]\f[B])\f[R]
after calling this procedure.
.TP
\f[B]size_t bcl_ctxt_scale(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R]
Returns the \f[B]scale\f[R] for given context.
.TP
\f[B]void bcl_ctxt_setScale(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B])\f[R]
Sets the \f[B]scale\f[R] for the given context to the argument
\f[I]scale\f[R].
.TP
\f[B]size_t bcl_ctxt_ibase(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R]
Returns the \f[B]ibase\f[R] for the given context.
.TP
\f[B]void bcl_ctxt_setIbase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]ibase\f[R]\f[B])\f[R]
Sets the \f[B]ibase\f[R] for the given context to the argument
\f[I]ibase\f[R].
If the argument \f[I]ibase\f[R] is invalid, it clamped, so an
\f[I]ibase\f[R] of \f[B]0\f[R] or \f[B]1\f[R] is clamped to \f[B]2\f[R],
and any values above \f[B]36\f[R] are clamped to \f[B]36\f[R].
.TP
\f[B]size_t bcl_ctxt_obase(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R]
Returns the \f[B]obase\f[R] for the given context.
.TP
\f[B]void bcl_ctxt_setObase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]obase\f[R]\f[B])\f[R]
Sets the \f[B]obase\f[R] for the given context to the argument
\f[I]obase\f[R].
.SS Errors
.TP
\f[B]BclError\f[R]
An \f[B]enum\f[R] of possible error codes.
See the \f[B]ERRORS\f[R] section for a complete listing the codes.
.TP
\f[B]BclError bcl_err(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Checks for errors in a \f[B]BclNumber\f[R].
All functions that can return a \f[B]BclNumber\f[R] can encode an error
in the number, and this function will return the error, if any.
If there was no error, it will return \f[B]BCL_ERROR_NONE\f[R].
.RS
.PP
There must be a valid current context.
.RE
.SS Numbers
.PP
All procedures in this section require a valid current context.
.TP
\f[B]BclNumber\f[R]
A handle to an arbitrary-precision number.
The actual number type is not exposed; the \f[B]BclNumber\f[R] handle is
the only way clients can refer to instances of arbitrary-precision
numbers.
.TP
\f[B]BclNumber bcl_num_create(\f[R]\f[I]void\f[R]\f[B])\f[R]
Creates and returns a \f[B]BclNumber\f[R].
.RS
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]void bcl_num_free(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Frees \f[I]n\f[R].
It is undefined behavior to use \f[I]n\f[R] after calling this function.
.TP
\f[B]bool bcl_num_neg(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Returns \f[B]true\f[R] if \f[I]n\f[R] is negative, \f[B]false\f[R]
otherwise.
.TP
\f[B]void bcl_num_setNeg(BclNumber\f[R] \f[I]n\f[R]\f[B], bool\f[R] \f[I]neg\f[R]\f[B])\f[R]
Sets \f[I]n\f[R]\[cq]s sign to \f[I]neg\f[R], where \f[B]true\f[R] is
negative, and \f[B]false\f[R] is positive.
.TP
\f[B]size_t bcl_num_scale(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Returns the \f[I]scale\f[R] of \f[I]n\f[R].
.RS
.PP
The \f[I]scale\f[R] of a number is the number of decimal places it has
after the radix (decimal point).
.RE
.TP
\f[B]BclError bcl_num_setScale(BclNumber\f[R] \f[I]n\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B])\f[R]
Sets the \f[I]scale\f[R] of \f[I]n\f[R] to the argument \f[I]scale\f[R].
If the argument \f[I]scale\f[R] is greater than the \f[I]scale\f[R] of
\f[I]n\f[R], \f[I]n\f[R] is extended.
If the argument \f[I]scale\f[R] is less than the \f[I]scale\f[R] of
\f[I]n\f[R], \f[I]n\f[R] is truncated.
.RS
.PP
If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned.
Otherwise, this function can return:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]size_t bcl_num_len(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Returns the number of \f[I]significant decimal digits\f[R] in
\f[I]n\f[R].
.SS Conversion
.PP
All procedures in this section require a valid current context.
.PP
All procedures in this section consume the given \f[B]BclNumber\f[R]
arguments that are not given to pointer arguments.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.TP
\f[B]BclNumber bcl_parse(const char *restrict\f[R] \f[I]val\f[R]\f[B])\f[R]
Parses a number string according to the current context\[cq]s
\f[B]ibase\f[R] and returns the resulting number.
.RS
.PP
\f[I]val\f[R] must be non-\f[B]NULL\f[R] and a valid string.
See \f[B]BCL_ERROR_PARSE_INVALID_STR\f[R] in the \f[B]ERRORS\f[R]
section for more information.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_PARSE_INVALID_STR\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]char* bcl_string(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Returns a string representation of \f[I]n\f[R] according the the current
context\[cq]s \f[B]ibase\f[R].
The string is dynamically allocated and must be freed by the caller.
.RS
.PP
\f[I]n\f[R] is consumed; it cannot be used after the call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.RE
.TP
\f[B]BclError bcl_bigdig(BclNumber\f[R] \f[I]n\f[R]\f[B], BclBigDig *\f[R]\f[I]result\f[R]\f[B])\f[R]
Converts \f[I]n\f[R] into a \f[B]BclBigDig\f[R] and returns the result
in the space pointed to by \f[I]result\f[R].
.RS
.PP
\f[I]a\f[R] must be smaller than \f[B]BC_OVERFLOW_MAX\f[R].
See the \f[B]LIMITS\f[R] section.
.PP
If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned.
Otherwise, this function can return:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_OVERFLOW\f[R]
.PP
\f[I]n\f[R] is consumed; it cannot be used after the call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.RE
.TP
\f[B]BclNumber bcl_bigdig2num(BclBigDig\f[R] \f[I]val\f[R]\f[B])\f[R]
Creates a \f[B]BclNumber\f[R] from \f[I]val\f[R].
.RS
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.SS Math
.PP
All procedures in this section require a valid current context.
.PP
All procedures in this section can return the following errors:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.TP
\f[B]BclNumber bcl_add(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Adds \f[I]a\f[R] and \f[I]b\f[R] and returns the result.
The \f[I]scale\f[R] of the result is the max of the \f[I]scale\f[R]s of
\f[I]a\f[R] and \f[I]b\f[R].
.RS
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]a\f[R] and \f[I]b\f[R] can be the same number.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_sub(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Subtracts \f[I]b\f[R] from \f[I]a\f[R] and returns the result.
The \f[I]scale\f[R] of the result is the max of the \f[I]scale\f[R]s of
\f[I]a\f[R] and \f[I]b\f[R].
.RS
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]a\f[R] and \f[I]b\f[R] can be the same number.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_mul(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Multiplies \f[I]a\f[R] and \f[I]b\f[R] and returns the result.
If \f[I]ascale\f[R] is the \f[I]scale\f[R] of \f[I]a\f[R] and
\f[I]bscale\f[R] is the \f[I]scale\f[R] of \f[I]b\f[R], the
\f[I]scale\f[R] of the result is equal to
\f[B]min(ascale+bscale,max(scale,ascale,bscale))\f[R], where
\f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values.
.RS
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]a\f[R] and \f[I]b\f[R] can be the same number.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_div(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Divides \f[I]a\f[R] by \f[I]b\f[R] and returns the result.
The \f[I]scale\f[R] of the result is the \f[I]scale\f[R] of the current
context.
.RS
.PP
\f[I]b\f[R] cannot be \f[B]0\f[R].
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]a\f[R] and \f[I]b\f[R] can be the same number.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_mod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Divides \f[I]a\f[R] by \f[I]b\f[R] to the \f[I]scale\f[R] of the current
context, computes the modulus \f[B]a-(a/b)*b\f[R], and returns the
modulus.
.RS
.PP
\f[I]b\f[R] cannot be \f[B]0\f[R].
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]a\f[R] and \f[I]b\f[R] can be the same number.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_pow(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Calculates \f[I]a\f[R] to the power of \f[I]b\f[R] to the
\f[I]scale\f[R] of the current context.
\f[I]b\f[R] must be an integer, but can be negative.
If it is negative, \f[I]a\f[R] must be non-zero.
.RS
.PP
\f[I]b\f[R] must be an integer.
If \f[I]b\f[R] is negative, \f[I]a\f[R] must not be \f[B]0\f[R].
.PP
\f[I]a\f[R] must be smaller than \f[B]BC_OVERFLOW_MAX\f[R].
See the \f[B]LIMITS\f[R] section.
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]a\f[R] and \f[I]b\f[R] can be the same number.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_OVERFLOW\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_lshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Shifts \f[I]a\f[R] left (moves the radix right) by \f[I]b\f[R] places
and returns the result.
This is done in decimal.
\f[I]b\f[R] must be an integer.
.RS
.PP
\f[I]b\f[R] must be an integer.
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]a\f[R] and \f[I]b\f[R] can be the same number.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_rshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Shifts \f[I]a\f[R] right (moves the radix left) by \f[I]b\f[R] places
and returns the result.
This is done in decimal.
\f[I]b\f[R] must be an integer.
.RS
.PP
\f[I]b\f[R] must be an integer.
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]a\f[R] and \f[I]b\f[R] can be the same number.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_sqrt(BclNumber\f[R] \f[I]a\f[R]\f[B])\f[R]
Calculates the square root of \f[I]a\f[R] and returns the result.
The \f[I]scale\f[R] of the result is equal to the \f[B]scale\f[R] of the
current context.
.RS
.PP
\f[I]a\f[R] cannot be negative.
.PP
\f[I]a\f[R] is consumed; it cannot be used after the call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NEGATIVE\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclError bcl_divmod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber *\f[R]\f[I]c\f[R]\f[B], BclNumber *\f[R]\f[I]d\f[R]\f[B])\f[R]
Divides \f[I]a\f[R] by \f[I]b\f[R] and returns the quotient in a new
number which is put into the space pointed to by \f[I]c\f[R], and puts
the modulus in a new number which is put into the space pointed to by
\f[I]d\f[R].
.RS
.PP
\f[I]b\f[R] cannot be \f[B]0\f[R].
.PP
\f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the
call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
\f[I]c\f[R] and \f[I]d\f[R] cannot point to the same place, nor can they
point to the space occupied by \f[I]a\f[R] or \f[I]b\f[R].
.PP
If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned.
Otherwise, this function can return:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_modexp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber\f[R] \f[I]c\f[R]\f[B])\f[R]
Computes a modular exponentiation where \f[I]a\f[R] is the base,
\f[I]b\f[R] is the exponent, and \f[I]c\f[R] is the modulus, and returns
the result.
The \f[I]scale\f[R] of the result is equal to the \f[B]scale\f[R] of the
current context.
.RS
.PP
\f[I]a\f[R], \f[I]b\f[R], and \f[I]c\f[R] must be integers.
\f[I]c\f[R] must not be \f[B]0\f[R].
\f[I]b\f[R] must not be negative.
.PP
\f[I]a\f[R], \f[I]b\f[R], and \f[I]c\f[R] are consumed; they cannot be
used after the call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NEGATIVE\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.SS Miscellaneous
.TP
\f[B]void bcl_zero(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Sets \f[I]n\f[R] to \f[B]0\f[R].
.TP
\f[B]void bcl_one(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Sets \f[I]n\f[R] to \f[B]1\f[R].
.TP
\f[B]ssize_t bcl_cmp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R]
Compares \f[I]a\f[R] and \f[I]b\f[R] and returns \f[B]0\f[R] if
\f[I]a\f[R] and \f[I]b\f[R] are equal, \f[B]<0\f[R] if \f[I]a\f[R] is
less than \f[I]b\f[R], and \f[B]>0\f[R] if \f[I]a\f[R] is greater than
\f[I]b\f[R].
.TP
\f[B]BclError bcl_copy(BclNumber\f[R] \f[I]d\f[R]\f[B], BclNumber\f[R] \f[I]s\f[R]\f[B])\f[R]
Copies \f[I]s\f[R] into \f[I]d\f[R].
.RS
.PP
If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned.
Otherwise, this function can return:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_dup(BclNumber\f[R] \f[I]s\f[R]\f[B])\f[R]
Creates and returns a new \f[B]BclNumber\f[R] that is a copy of
\f[I]s\f[R].
.RS
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.SS Pseudo-Random Number Generator
.PP
The pseudo-random number generator in bcl(3) is a \f[I]seeded\f[R] PRNG.
Given the same seed twice, it will produce the same sequence of
pseudo-random numbers twice.
.PP
By default, bcl(3) attempts to seed the PRNG with data from
\f[B]/dev/urandom\f[R].
If that fails, it seeds itself with by calling \f[B]libc\f[R]\[cq]s
\f[B]srand(time(NULL))\f[R] and then calling \f[B]rand()\f[R] for each
byte, since \f[B]rand()\f[R] is only guaranteed to return \f[B]15\f[R]
bits.
.PP
This should provide fairly good seeding in the standard case while also
remaining fairly portable.
.PP
If necessary, the PRNG can be reseeded with one of the following
functions:
.IP \[bu] 2
\f[B]bcl_rand_seedWithNum(BclNumber)\f[R]
.IP \[bu] 2
\f[B]bcl_rand_seed(unsigned
char[\f[R]\f[I]BCL_SEED_SIZE\f[R]\f[B]])\f[R]
.IP \[bu] 2
\f[B]bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B])\f[R]
.PP
The following items allow clients to use the pseudo-random number
generator.
All procedures require a valid current context.
.TP
\f[B]BCL_SEED_ULONGS\f[R]
The number of \f[B]unsigned long\f[R]\[cq]s in a seed for bcl(3)\[cq]s
random number generator.
.TP
\f[B]BCL_SEED_SIZE\f[R]
The size, in \f[B]char\f[R]\[cq]s, of a seed for bcl(3)\[cq]s random
number generator.
.TP
\f[B]BclBigDig\f[R]
bcl(3)\[cq]s overflow type (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BclRandInt\f[R]
An unsigned integer type returned by bcl(3)\[cq]s random number
generator.
.TP
\f[B]BclNumber bcl_irand(BclNumber\f[R] \f[I]a\f[R]\f[B])\f[R]
Returns a random number that is not larger than \f[I]a\f[R] in a new
number.
If \f[I]a\f[R] is \f[B]0\f[R] or \f[B]1\f[R], the new number is equal to
\f[B]0\f[R].
The bound is unlimited, so it is not bound to the size of
\f[B]BclRandInt\f[R].
This is done by generating as many random numbers as necessary,
multiplying them by certain exponents, and adding them all together.
.RS
.PP
\f[I]a\f[R] must be an integer and non-negative.
.PP
\f[I]a\f[R] is consumed; it cannot be used after the call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
This procedure requires a valid current context.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NEGATIVE\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_frand(size_t\f[R] \f[I]places\f[R]\f[B])\f[R]
Returns a random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R]
(exclusive) that has \f[I]places\f[R] decimal digits after the radix
(decimal point).
There are no limits on \f[I]places\f[R].
.RS
.PP
This procedure requires a valid current context.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclNumber bcl_ifrand(BclNumber\f[R] \f[I]a\f[R]\f[B], size_t\f[R] \f[I]places\f[R]\f[B])\f[R]
Returns a random number less than \f[I]a\f[R] with \f[I]places\f[R]
decimal digits after the radix (decimal point).
There are no limits on \f[I]a\f[R] or \f[I]places\f[R].
.RS
.PP
\f[I]a\f[R] must be an integer and non-negative.
.PP
\f[I]a\f[R] is consumed; it cannot be used after the call.
See the \f[B]Consumption and Propagation\f[R] subsection below.
.PP
This procedure requires a valid current context.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NEGATIVE\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclError bcl_rand_seedWithNum(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R]
Seeds the PRNG with \f[I]n\f[R].
.RS
.PP
\f[I]n\f[R] is \f[I]not\f[R] consumed.
.PP
This procedure requires a valid current context.
.PP
If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned.
Otherwise, this function can return:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_NUM\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.PP
Note that if \f[B]bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B])\f[R] or
\f[B]bcl_rand_seed2num_err(BclNumber)\f[R] are called right after this
function, they are not guaranteed to return a number equal to
\f[I]n\f[R].
.RE
.TP
\f[B]BclError bcl_rand_seed(unsigned char\f[R] \f[I]seed\f[R]\f[B][\f[R]\f[I]BCL_SEED_SIZE\f[R]\f[B]])\f[R]
Seeds the PRNG with the bytes in \f[I]seed\f[R].
.RS
.PP
If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned.
Otherwise, this function can return:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.RE
.TP
\f[B]void bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B])\f[R]
Reseeds the PRNG with the default reseeding behavior.
First, it attempts to read data from \f[B]/dev/urandom\f[R] and falls
back to \f[B]libc\f[R]\[cq]s \f[B]rand()\f[R].
.RS
.PP
This procedure cannot fail.
.RE
.TP
\f[B]BclNumber bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B])\f[R]
Returns the current seed of the PRNG as a \f[B]BclNumber\f[R].
.RS
.PP
This procedure requires a valid current context.
.PP
bcl(3) will encode an error in the return value, if there was one.
The error can be queried with \f[B]bcl_err(BclNumber)\f[R].
Possible errors include:
.IP \[bu] 2
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
.IP \[bu] 2
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
.RE
.TP
\f[B]BclRandInt bcl_rand_int(\f[R]\f[I]void\f[R]\f[B])\f[R]
Returns a random integer between \f[B]0\f[R] and \f[B]BC_RAND_MAX\f[R]
(inclusive).
.RS
.PP
This procedure cannot fail.
.RE
.TP
\f[B]BclRandInt bcl_rand_bounded(BclRandInt\f[R] \f[I]bound\f[R]\f[B])\f[R]
Returns a random integer between \f[B]0\f[R] and \f[I]bound\f[R]
(exclusive).
Bias is removed before returning the integer.
.RS
.PP
This procedure cannot fail.
.RE
.SS Consumption and Propagation
.PP
Some functions are listed as consuming some or all of their arguments.
This means that the arguments are freed, regardless of if there were
errors or not.
.PP
This is to enable compact code like the following:
.IP
.nf
\f[C]
BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
\f[R]
.fi
.PP
If arguments to those functions were not consumed, memory would be
leaked until reclaimed with \f[B]bcl_ctxt_freeNums(BclContext)\f[R].
.PP
When errors occur, they are propagated through.
The result should always be checked with \f[B]bcl_err(BclNumber)\f[R],
so the example above should properly be:
.IP
.nf
\f[C]
BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
if (bc_num_err(n) != BCL_ERROR_NONE) {
// Handle the error.
}
\f[R]
.fi
.SH ERRORS
.PP
Most functions in bcl(3) return, directly or indirectly, any one of the
error codes defined in \f[B]BclError\f[R].
The complete list of codes is the following:
.TP
\f[B]BCL_ERROR_NONE\f[R]
Success; no error occurred.
.TP
\f[B]BCL_ERROR_INVALID_NUM\f[R]
An invalid \f[B]BclNumber\f[R] was given as a parameter.
.TP
\f[B]BCL_ERROR_INVALID_CONTEXT\f[R]
An invalid \f[B]BclContext\f[R] is being used.
.TP
\f[B]BCL_ERROR_SIGNAL\f[R]
A signal interrupted execution.
.TP
\f[B]BCL_ERROR_MATH_NEGATIVE\f[R]
A negative number was given as an argument to a parameter that cannot
accept negative numbers, such as for square roots.
.TP
\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R]
A non-integer was given as an argument to a parameter that cannot accept
non-integer numbers, such as for the second parameter of
\f[B]bcl_num_pow()\f[R].
.TP
\f[B]BCL_ERROR_MATH_OVERFLOW\f[R]
A number that would overflow its result was given as an argument, such
as for converting a \f[B]BclNumber\f[R] to a \f[B]BclBigDig\f[R].
.TP
\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R]
A divide by zero occurred.
.TP
\f[B]BCL_ERROR_PARSE_INVALID_STR\f[R]
An invalid number string was passed to a parsing function.
.RS
.PP
A valid number string can only be one radix (period).
In addition, any lowercase ASCII letters, symbols, or non-ASCII
characters are invalid.
It is allowed for the first character to be a dash.
In that case, the number is considered to be negative.
.PP
There is one exception to the above: one lowercase \f[B]e\f[R] is
allowed in the number, after the radix, if it exists.
If the letter \f[B]e\f[R] exists, the number is considered to be in
scientific notation, where the part before the \f[B]e\f[R] is the
number, and the part after, which must be an integer, is the exponent.
There can be a dash right after the \f[B]e\f[R] to indicate a negative
exponent.
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bcl(3) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if bcl(3) is given the number string
\f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.RE
.TP
\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R]
bcl(3) failed to allocate memory.
.RS
.PP
If clients call \f[B]bcl_setAbortOnFatalError()\f[R] with an
\f[B]true\f[R] argument, this error will cause bcl(3) to throw a
\f[B]SIGABRT\f[R].
This behavior can also be turned off later by calling that same function
with a \f[B]false\f[R] argument.
By default, this behavior is off.
.PP
It is highly recommended that client libraries do \f[I]not\f[R] activate
this behavior.
.RE
.TP
\f[B]BCL_ERROR_FATAL_UNKNOWN_ERR\f[R]
An unknown error occurred.
.RS
.PP
If clients call \f[B]bcl_setAbortOnFatalError()\f[R] with an
\f[B]true\f[R] argument, this error will cause bcl(3) to throw a
\f[B]SIGABRT\f[R].
This behavior can also be turned off later by calling that same function
with a \f[B]false\f[R] argument.
By default, this behavior is off.
.PP
It is highly recommended that client libraries do \f[I]not\f[R] activate
this behavior.
.RE
.SH ATTRIBUTES
.PP
When \f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] is used
properly, bcl(3) is async-signal-safe.
.PP
bcl(3) is \f[I]MT-Unsafe\f[R]: it is unsafe to call any functions from
more than one thread.
.SH PERFORMANCE
.PP
Most bc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
bcl(3) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]BC_BASE_DIGS\f[R].
.PP
In addition, this bcl(3) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on bcl(3):
.TP
\f[B]BC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] type in the environment where
bcl(3) was built.
This determines how many decimal digits can be stored in a single large
integer (see the \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]BC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]BC_BASE_DIGS\f[R].
.TP
\f[B]BC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]BC_LONG_BIT\f[R].
.TP
\f[B]BC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]BC_BASE_POW\f[R].
.TP
\f[B]BC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]BC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]BC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]bcl_rand_int()\f[R]
function.
Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]BC_OVERFLOW_MAX\f[R].
.PP
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 SIGNAL HANDLING
.PP
If a signal handler calls
\f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] from the same
thread that there are bcl(3) functions executing in, it will cause all
execution to stop as soon as possible, interrupting long-running
calculations, if necessary and cause the function that was executing to
return.
If possible, the error code \f[B]BC_ERROR_SIGNAL\f[R] is returned.
.PP
If execution \f[I]is\f[R] interrupted,
\f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] does \f[I]not\f[R]
return to its caller.
.PP
It is undefined behavior if
\f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] is called from a
thread that is not executing bcl(3) functions, if bcl(3) functions are
executing.
.SH SEE ALSO
.PP
bc(1) and dc(1)
.SH STANDARDS
.PP
bcl(3) is compliant with the arithmetic defined in the IEEE Std
1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification for bc(1).
.PP
Note that the specification explicitly says that bc(1) only accepts
numbers that use a period (\f[B].\f[R]) as a radix point, regardless of
the value of \f[B]LC_NUMERIC\f[R].
This is also true of bcl(3).
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHORS
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/bcl.3.md b/manuals/bcl.3.md
index daf5f461cc94..fa630fc79f1a 100644
--- a/manuals/bcl.3.md
+++ b/manuals/bcl.3.md
@@ -1,1180 +1,1202 @@
# NAME
bcl - library of arbitrary precision decimal arithmetic
# SYNOPSIS
## Use
*#include *
Link with *-lbcl*.
## Signals
This procedure will allow clients to use signals to interrupt computations
running in bcl(3).
**void bcl_handleSignal(**_void_**);**
**bool bcl_running(**_void_**);**
## Setup
These items allow clients to set up bcl(3).
**BclError bcl_init(**_void_**);**
**void bcl_free(**_void_**);**
**bool bcl_abortOnFatalError(**_void_**);**
**void bcl_setAbortOnFatalError(bool** _abrt_**);**
+**bool bcl_leadingZeroes(**_void_**);**
+
+**void bcl_setLeadingZeroes(bool** _leadingZeroes_**);**
+
**void bcl_gc(**_void_**);**
## Contexts
These items will allow clients to handle contexts, which are isolated from each
other. This allows more than one client to use bcl(3) in the same program.
**struct BclCtxt;**
**typedef struct BclCtxt\* BclContext;**
**BclContext bcl_ctxt_create(**_void_**);**
**void bcl_ctxt_free(BclContext** _ctxt_**);**
**BclError bcl_pushContext(BclContext** _ctxt_**);**
**void bcl_popContext(**_void_**);**
**BclContext bcl_context(**_void_**);**
**void bcl_ctxt_freeNums(BclContext** _ctxt_**);**
**size_t bcl_ctxt_scale(BclContext** _ctxt_**);**
**void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**);**
**size_t bcl_ctxt_ibase(BclContext** _ctxt_**);**
**void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**);**
**size_t bcl_ctxt_obase(BclContext** _ctxt_**);**
**void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**);**
## Errors
These items allow clients to handle errors.
**typedef enum BclError BclError;**
**BclError bcl_err(BclNumber** _n_**);**
## Numbers
These items allow clients to manipulate and query the arbitrary-precision
numbers managed by bcl(3).
**typedef struct { size_t i; } BclNumber;**
**BclNumber bcl_num_create(**_void_**);**
**void bcl_num_free(BclNumber** _n_**);**
**bool bcl_num_neg(BclNumber** _n_**);**
**void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**);**
**size_t bcl_num_scale(BclNumber** _n_**);**
**BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**);**
**size_t bcl_num_len(BclNumber** _n_**);**
## Conversion
These items allow clients to convert numbers into and from strings and integers.
**BclNumber bcl_parse(const char \*restrict** _val_**);**
**char\* bcl_string(BclNumber** _n_**);**
**BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**);**
**BclNumber bcl_bigdig2num(BclBigDig** _val_**);**
## Math
These items allow clients to run math on numbers.
**BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**);**
**BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**);**
**BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**);**
**BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**);**
**BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**);**
**BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**);**
**BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**);**
**BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**);**
**BclNumber bcl_sqrt(BclNumber** _a_**);**
**BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);**
**BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);**
## Miscellaneous
These items are miscellaneous.
**void bcl_zero(BclNumber** _n_**);**
**void bcl_one(BclNumber** _n_**);**
**ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**);**
**BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**);**
**BclNumber bcl_dup(BclNumber** _s_**);**
## Pseudo-Random Number Generator
These items allow clients to manipulate the seeded pseudo-random number
generator in bcl(3).
**#define BCL_SEED_ULONGS**
**#define BCL_SEED_SIZE**
**typedef unsigned long BclBigDig;**
**typedef unsigned long BclRandInt;**
**BclNumber bcl_irand(BclNumber** _a_**);**
**BclNumber bcl_frand(size_t** _places_**);**
**BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**);**
**BclError bcl_rand_seedWithNum(BclNumber** _n_**);**
**BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**]);**
**void bcl_rand_reseed(**_void_**);**
**BclNumber bcl_rand_seed2num(**_void_**);**
**BclRandInt bcl_rand_int(**_void_**);**
**BclRandInt bcl_rand_bounded(BclRandInt** _bound_**);**
# DESCRIPTION
bcl(3) is a library that implements arbitrary-precision decimal math, as
[standardized by POSIX][1] in bc(1).
bcl(3) is async-signal-safe if **bcl_handleSignal(**_void_**)** is used
properly. (See the **SIGNAL HANDLING** section.)
-bcl(3) assumes that it is allowed to use the **bcl_** and **bc_** prefixes for
-symbol names without collision.
+bcl(3) assumes that it is allowed to use the **bcl**, **Bcl**, **bc**, and
+**Bc** prefixes for symbol names without collision.
All of the items in its interface are described below. See the documentation for
each function for what each function can return.
## Signals
**void bcl_handleSignal(**_void_**)**
: An async-signal-safe function that can be called from a signal handler. If
called from a signal handler on the same thread as any executing bcl(3)
functions, it will interrupt the functions and force them to return early.
It is undefined behavior if this function is called from a thread that is
*not* executing any bcl(3) functions while any bcl(3) functions are
executing.
If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
return to its caller.
See the **SIGNAL HANDLING** section.
**bool bcl_running(**_void_**)**
: An async-signal-safe function that can be called from a signal handler. It
will return **true** if any bcl(3) procedures are running, which means it is
safe to call **bcl_handleSignal(**_void_**)**. Otherwise, it returns
**false**.
See the **SIGNAL HANDLING** section.
## Setup
**BclError bcl_init(**_void_**)**
: Initializes this library. This function can be called multiple times, but
each call must be matched by a call to **bcl_free(**_void_**)**. This is to
make it possible for multiple libraries and applications to initialize
bcl(3) without problem.
If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
function can return:
* **BCL_ERROR_FATAL_ALLOC_ERR**
This function must be the first one clients call. Calling any other
function without calling this one first is undefined behavior.
**void bcl_free(**_void_**)**
: Decrements bcl(3)'s reference count and frees the data associated with it if
the reference count is **0**.
This function must be the last one clients call. Calling this function
before calling any other function is undefined behavior.
**bool bcl_abortOnFatalError(**_void_**)**
: Queries and returns the current state of calling **abort()** on fatal
errors. If **true** is returned, bcl(3) will cause a **SIGABRT** if a fatal
error occurs.
If activated, clients do not need to check for fatal errors.
+ The default is **false**.
+
**void bcl_setAbortOnFatalError(bool** _abrt_**)**
: Sets the state of calling **abort()** on fatal errors. If *abrt* is
**false**, bcl(3) will not cause a **SIGABRT** on fatal errors after the
call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors
after the call.
If activated, clients do not need to check for fatal errors.
+**bool bcl_leadingZeroes(**_void_**)**
+
+: Queries and returns the state of whether leading zeroes are added to strings
+ returned by **bcl_string()** when numbers are greater than **-1**, less than
+ **1**, and not equal to **0**. If **true** is returned, then leading zeroes
+ will be added.
+
+ The default is **false**.
+
+**void bcl_setLeadingZeroes(bool** _leadingZeroes_**)**
+
+: Sets the state of whether leading zeroes are added to strings returned by
+ **bcl_string()** when numbers are greater than **-1**, less than **1**, and
+ not equal to **0**. If *leadingZeroes* is **true**, leading zeroes will be
+ added to strings returned by **bcl_string()**.
+
**void bcl_gc(**_void_**)**
: Garbage collects cached instances of arbitrary-precision numbers. This only
frees the memory of numbers that are *not* in use, so it is safe to call at
any time.
## Contexts
All procedures that take a **BclContext** parameter a require a valid context as
an argument.
**struct BclCtxt**
: A forward declaration for a hidden **struct** type. Clients cannot access
the internals of the **struct** type directly. All interactions with the
type are done through pointers. See **BclContext** below.
**BclContext**
: A typedef to a pointer of **struct BclCtxt**. This is the only handle
clients can get to **struct BclCtxt**.
A **BclContext** contains the values **scale**, **ibase**, and **obase**, as
well as a list of numbers.
**scale** is a value used to control how many decimal places calculations
should use. A value of **0** means that calculations are done on integers
only, where applicable, and a value of 20, for example, means that all
applicable calculations return results with 20 decimal places. The default
is **0**.
**ibase** is a value used to control the input base. The minimum **ibase**
is **2**, and the maximum is **36**. If **ibase** is **2**, numbers are
parsed as though they are in binary, and any digits larger than **1** are
clamped. Likewise, a value of **10** means that numbers are parsed as though
they are decimal, and any larger digits are clamped. The default is **10**.
**obase** is a value used to control the output base. The minimum **obase**
is **0** and the maximum is **BC_BASE_MAX** (see the **LIMITS** section).
Numbers created in one context are not valid in another context. It is
undefined behavior to use a number created in a different context. Contexts
are meant to isolate the numbers used by different clients in the same
application.
**BclContext bcl_ctxt_create(**_void_**)**
: Creates a context and returns it. Returns **NULL** if there was an error.
**void bcl_ctxt_free(BclContext** _ctxt_**)**
: Frees *ctxt*, after which it is no longer valid. It is undefined behavior to
attempt to use an invalid context.
**BclError bcl_pushContext(BclContext** _ctxt_**)**
: Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created
with **bcl_ctxt_create(**_void_**)**.
If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
function can return:
* **BCL_ERROR_FATAL_ALLOC_ERR**
There *must* be a valid context to do any arithmetic.
**void bcl_popContext(**_void_**)**
: Pops the current context off of the stack, if one exists.
**BclContext bcl_context(**_void_**)**
: Returns the current context, or **NULL** if no context exists.
**void bcl_ctxt_freeNums(BclContext** _ctxt_**)**
: Frees all numbers in use that are associated with *ctxt*. It is undefined
behavior to attempt to use a number associated with *ctxt* after calling
this procedure unless such numbers have been created with
**bcl_num_create(**_void_**)** after calling this procedure.
**size_t bcl_ctxt_scale(BclContext** _ctxt_**)**
: Returns the **scale** for given context.
**void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**)**
: Sets the **scale** for the given context to the argument *scale*.
**size_t bcl_ctxt_ibase(BclContext** _ctxt_**)**
: Returns the **ibase** for the given context.
**void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**)**
: Sets the **ibase** for the given context to the argument *ibase*. If the
argument *ibase* is invalid, it clamped, so an *ibase* of **0** or **1** is
clamped to **2**, and any values above **36** are clamped to **36**.
**size_t bcl_ctxt_obase(BclContext** _ctxt_**)**
: Returns the **obase** for the given context.
**void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**)**
: Sets the **obase** for the given context to the argument *obase*.
## Errors
**BclError**
: An **enum** of possible error codes. See the **ERRORS** section for a
complete listing the codes.
**BclError bcl_err(BclNumber** _n_**)**
: Checks for errors in a **BclNumber**. All functions that can return a
**BclNumber** can encode an error in the number, and this function will
return the error, if any. If there was no error, it will return
**BCL_ERROR_NONE**.
There must be a valid current context.
## Numbers
All procedures in this section require a valid current context.
**BclNumber**
: A handle to an arbitrary-precision number. The actual number type is not
exposed; the **BclNumber** handle is the only way clients can refer to
instances of arbitrary-precision numbers.
**BclNumber bcl_num_create(**_void_**)**
: Creates and returns a **BclNumber**.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**void bcl_num_free(BclNumber** _n_**)**
: Frees *n*. It is undefined behavior to use *n* after calling this function.
**bool bcl_num_neg(BclNumber** _n_**)**
: Returns **true** if *n* is negative, **false** otherwise.
**void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**)**
: Sets *n*'s sign to *neg*, where **true** is negative, and **false** is
positive.
**size_t bcl_num_scale(BclNumber** _n_**)**
: Returns the *scale* of *n*.
The *scale* of a number is the number of decimal places it has after the
radix (decimal point).
**BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**)**
: Sets the *scale* of *n* to the argument *scale*. If the argument *scale* is
greater than the *scale* of *n*, *n* is extended. If the argument *scale* is
less than the *scale* of *n*, *n* is truncated.
If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
function can return:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**size_t bcl_num_len(BclNumber** _n_**)**
: Returns the number of *significant decimal digits* in *n*.
## Conversion
All procedures in this section require a valid current context.
All procedures in this section consume the given **BclNumber** arguments that
are not given to pointer arguments. See the **Consumption and Propagation**
subsection below.
**BclNumber bcl_parse(const char \*restrict** _val_**)**
: Parses a number string according to the current context's **ibase** and
returns the resulting number.
*val* must be non-**NULL** and a valid string. See
**BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more
information.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_PARSE_INVALID_STR**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**char\* bcl_string(BclNumber** _n_**)**
: Returns a string representation of *n* according the the current context's
**ibase**. The string is dynamically allocated and must be freed by the
caller.
*n* is consumed; it cannot be used after the call. See the
**Consumption and Propagation** subsection below.
**BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**)**
: Converts *n* into a **BclBigDig** and returns the result in the space
pointed to by *result*.
*a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
function can return:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_OVERFLOW**
*n* is consumed; it cannot be used after the call. See the
**Consumption and Propagation** subsection below.
**BclNumber bcl_bigdig2num(BclBigDig** _val_**)**
: Creates a **BclNumber** from *val*.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
## Math
All procedures in this section require a valid current context.
All procedures in this section can return the following errors:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**)**
: Adds *a* and *b* and returns the result. The *scale* of the result is the
max of the *scale*s of *a* and *b*.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*a* and *b* can be the same number.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**)**
: Subtracts *b* from *a* and returns the result. The *scale* of the result is
the max of the *scale*s of *a* and *b*.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*a* and *b* can be the same number.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**)**
: Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of
*a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal
to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and
**max()** return the obvious values.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*a* and *b* can be the same number.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**)**
: Divides *a* by *b* and returns the result. The *scale* of the result is the
*scale* of the current context.
*b* cannot be **0**.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*a* and *b* can be the same number.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**)**
: Divides *a* by *b* to the *scale* of the current context, computes the
modulus **a-(a/b)\*b**, and returns the modulus.
*b* cannot be **0**.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*a* and *b* can be the same number.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**)**
: Calculates *a* to the power of *b* to the *scale* of the current context.
*b* must be an integer, but can be negative. If it is negative, *a* must
be non-zero.
*b* must be an integer. If *b* is negative, *a* must not be **0**.
*a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*a* and *b* can be the same number.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_NON_INTEGER**
* **BCL_ERROR_MATH_OVERFLOW**
* **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**)**
: Shifts *a* left (moves the radix right) by *b* places and returns the
result. This is done in decimal. *b* must be an integer.
*b* must be an integer.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*a* and *b* can be the same number.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_NON_INTEGER**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**)**
: Shifts *a* right (moves the radix left) by *b* places and returns the
result. This is done in decimal. *b* must be an integer.
*b* must be an integer.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*a* and *b* can be the same number.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_NON_INTEGER**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_sqrt(BclNumber** _a_**)**
: Calculates the square root of *a* and returns the result. The *scale* of the
result is equal to the **scale** of the current context.
*a* cannot be negative.
*a* is consumed; it cannot be used after the call. See the
**Consumption and Propagation** subsection below.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_NEGATIVE**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**)**
: Divides *a* by *b* and returns the quotient in a new number which is put
into the space pointed to by *c*, and puts the modulus in a new number which
is put into the space pointed to by *d*.
*b* cannot be **0**.
*a* and *b* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
*c* and *d* cannot point to the same place, nor can they point to the space
occupied by *a* or *b*.
If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
function can return:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**)**
: Computes a modular exponentiation where *a* is the base, *b* is the
exponent, and *c* is the modulus, and returns the result. The *scale* of the
result is equal to the **scale** of the current context.
*a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be
negative.
*a*, *b*, and *c* are consumed; they cannot be used after the call. See the
**Consumption and Propagation** subsection below.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_NEGATIVE**
* **BCL_ERROR_MATH_NON_INTEGER**
* **BCL_ERROR_MATH_DIVIDE_BY_ZERO**
* **BCL_ERROR_FATAL_ALLOC_ERR**
## Miscellaneous
**void bcl_zero(BclNumber** _n_**)**
: Sets *n* to **0**.
**void bcl_one(BclNumber** _n_**)**
: Sets *n* to **1**.
**ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**)**
: Compares *a* and *b* and returns **0** if *a* and *b* are equal, **<0** if
*a* is less than *b*, and **>0** if *a* is greater than *b*.
**BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**)**
: Copies *s* into *d*.
If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
function can return:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_dup(BclNumber** _s_**)**
: Creates and returns a new **BclNumber** that is a copy of *s*.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
## Pseudo-Random Number Generator
The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same
seed twice, it will produce the same sequence of pseudo-random numbers twice.
By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If
that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and
then calling **rand()** for each byte, since **rand()** is only guaranteed to
return **15** bits.
This should provide fairly good seeding in the standard case while also
remaining fairly portable.
If necessary, the PRNG can be reseeded with one of the following functions:
* **bcl_rand_seedWithNum(BclNumber)**
* **bcl_rand_seed(unsigned char[**_BCL_SEED_SIZE_**])**
* **bcl_rand_reseed(**_void_**)**
The following items allow clients to use the pseudo-random number generator. All
procedures require a valid current context.
**BCL_SEED_ULONGS**
: The number of **unsigned long**'s in a seed for bcl(3)'s random number
generator.
**BCL_SEED_SIZE**
: The size, in **char**'s, of a seed for bcl(3)'s random number generator.
**BclBigDig**
: bcl(3)'s overflow type (see the **PERFORMANCE** section).
**BclRandInt**
: An unsigned integer type returned by bcl(3)'s random number generator.
**BclNumber bcl_irand(BclNumber** _a_**)**
: Returns a random number that is not larger than *a* in a new number. If *a*
is **0** or **1**, the new number is equal to **0**. The bound is unlimited,
so it is not bound to the size of **BclRandInt**. This is done by generating
as many random numbers as necessary, multiplying them by certain exponents,
and adding them all together.
*a* must be an integer and non-negative.
*a* is consumed; it cannot be used after the call. See the
**Consumption and Propagation** subsection below.
This procedure requires a valid current context.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_NEGATIVE**
* **BCL_ERROR_MATH_NON_INTEGER**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_frand(size_t** _places_**)**
: Returns a random number between **0** (inclusive) and **1** (exclusive) that
has *places* decimal digits after the radix (decimal point). There are no
limits on *places*.
This procedure requires a valid current context.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**)**
: Returns a random number less than *a* with *places* decimal digits after the
radix (decimal point). There are no limits on *a* or *places*.
*a* must be an integer and non-negative.
*a* is consumed; it cannot be used after the call. See the
**Consumption and Propagation** subsection below.
This procedure requires a valid current context.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_MATH_NEGATIVE**
* **BCL_ERROR_MATH_NON_INTEGER**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclError bcl_rand_seedWithNum(BclNumber** _n_**)**
: Seeds the PRNG with *n*.
*n* is *not* consumed.
This procedure requires a valid current context.
If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
function can return:
* **BCL_ERROR_INVALID_NUM**
* **BCL_ERROR_INVALID_CONTEXT**
Note that if **bcl_rand_seed2num(**_void_**)** or
**bcl_rand_seed2num_err(BclNumber)** are called right after this function,
they are not guaranteed to return a number equal to *n*.
**BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**])**
: Seeds the PRNG with the bytes in *seed*.
If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this
function can return:
* **BCL_ERROR_INVALID_CONTEXT**
**void bcl_rand_reseed(**_void_**)**
: Reseeds the PRNG with the default reseeding behavior. First, it attempts to
read data from **/dev/urandom** and falls back to **libc**'s **rand()**.
This procedure cannot fail.
**BclNumber bcl_rand_seed2num(**_void_**)**
: Returns the current seed of the PRNG as a **BclNumber**.
This procedure requires a valid current context.
bcl(3) will encode an error in the return value, if there was one. The error
can be queried with **bcl_err(BclNumber)**. Possible errors include:
* **BCL_ERROR_INVALID_CONTEXT**
* **BCL_ERROR_FATAL_ALLOC_ERR**
**BclRandInt bcl_rand_int(**_void_**)**
: Returns a random integer between **0** and **BC_RAND_MAX** (inclusive).
This procedure cannot fail.
**BclRandInt bcl_rand_bounded(BclRandInt** _bound_**)**
: Returns a random integer between **0** and *bound* (exclusive). Bias is
removed before returning the integer.
This procedure cannot fail.
## Consumption and Propagation
Some functions are listed as consuming some or all of their arguments. This
means that the arguments are freed, regardless of if there were errors or not.
This is to enable compact code like the following:
BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
If arguments to those functions were not consumed, memory would be leaked until
reclaimed with **bcl_ctxt_freeNums(BclContext)**.
When errors occur, they are propagated through. The result should always be
checked with **bcl_err(BclNumber)**, so the example above should properly
be:
BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d));
if (bc_num_err(n) != BCL_ERROR_NONE) {
// Handle the error.
}
# ERRORS
Most functions in bcl(3) return, directly or indirectly, any one of the error
codes defined in **BclError**. The complete list of codes is the following:
**BCL_ERROR_NONE**
: Success; no error occurred.
**BCL_ERROR_INVALID_NUM**
: An invalid **BclNumber** was given as a parameter.
**BCL_ERROR_INVALID_CONTEXT**
: An invalid **BclContext** is being used.
**BCL_ERROR_SIGNAL**
: A signal interrupted execution.
**BCL_ERROR_MATH_NEGATIVE**
: A negative number was given as an argument to a parameter that cannot accept
negative numbers, such as for square roots.
**BCL_ERROR_MATH_NON_INTEGER**
: A non-integer was given as an argument to a parameter that cannot accept
non-integer numbers, such as for the second parameter of **bcl_num_pow()**.
**BCL_ERROR_MATH_OVERFLOW**
: A number that would overflow its result was given as an argument, such as
for converting a **BclNumber** to a **BclBigDig**.
**BCL_ERROR_MATH_DIVIDE_BY_ZERO**
: A divide by zero occurred.
**BCL_ERROR_PARSE_INVALID_STR**
: An invalid number string was passed to a parsing function.
A valid number string can only be one radix (period). In addition, any
lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is
allowed for the first character to be a dash. In that case, the number is
considered to be negative.
There is one exception to the above: one lowercase **e** is allowed in the
number, after the radix, if it exists. If the letter **e** exists, the
number is considered to be in scientific notation, where the part before the
**e** is the number, and the part after, which must be an integer, is the
exponent. There can be a dash right after the **e** to indicate a negative
exponent.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For
example, if **ibase** is **16** and bcl(3) is given the number string
**FFeA**, the resulting decimal number will be **2550000000000**, and if
bcl(3) is given the number string **10e-4**, the resulting decimal number
will be **0.0016**.
**BCL_ERROR_FATAL_ALLOC_ERR**
: bcl(3) failed to allocate memory.
If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
be turned off later by calling that same function with a **false** argument.
By default, this behavior is off.
It is highly recommended that client libraries do *not* activate this
behavior.
**BCL_ERROR_FATAL_UNKNOWN_ERR**
: An unknown error occurred.
If clients call **bcl_setAbortOnFatalError()** with an **true** argument,
this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also
be turned off later by calling that same function with a **false** argument.
By default, this behavior is off.
It is highly recommended that client libraries do *not* activate this
behavior.
# ATTRIBUTES
When **bcl_handleSignal(**_void_**)** is used properly, bcl(3) is
async-signal-safe.
bcl(3) is *MT-Unsafe*: it is unsafe to call any functions from more than one
thread.
# PERFORMANCE
Most bc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. bcl(3) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**BC_BASE_DIGS**.
In addition, this bcl(3) uses an even larger integer for overflow checking. This
integer type depends on the value of **BC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on bcl(3):
**BC_LONG_BIT**
: The number of bits in the **long** type in the environment where bcl(3) was
built. This determines how many decimal digits can be stored in a single
large integer (see the **PERFORMANCE** section).
**BC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **BC_LONG_BIT**.
**BC_BASE_POW**
: The max decimal number that each large integer can store (see
**BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
**BC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **BC_LONG_BIT**.
**BC_BASE_MAX**
: The maximum output base. Set at **BC_BASE_POW**.
**BC_SCALE_MAX**
: The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
**BC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
**BC_RAND_MAX**
: The maximum integer (inclusive) returned by the **bcl_rand_int()** function.
Set at **2\^BC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**BC_OVERFLOW_MAX**.
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.
# SIGNAL HANDLING
If a signal handler calls **bcl_handleSignal(**_void_**)** from the same thread
that there are bcl(3) functions executing in, it will cause all execution to
stop as soon as possible, interrupting long-running calculations, if necessary
and cause the function that was executing to return. If possible, the error code
**BC_ERROR_SIGNAL** is returned.
If execution *is* interrupted, **bcl_handleSignal(**_void_**)** does *not*
return to its caller.
It is undefined behavior if **bcl_handleSignal(**_void_**)** is called from
a thread that is not executing bcl(3) functions, if bcl(3) functions are
executing.
# SEE ALSO
bc(1) and dc(1)
# STANDARDS
bcl(3) is compliant with the arithmetic defined in the
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification for bc(1).
Note that the specification explicitly says that bc(1) only accepts numbers that
use a period (**.**) as a radix point, regardless of the value of
**LC_NUMERIC**. This is also true of bcl(3).
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHORS
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/manuals/build.md b/manuals/build.md
index f8fc786329eb..13e969e8e673 100644
--- a/manuals/build.md
+++ b/manuals/build.md
@@ -1,838 +1,838 @@
# 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=...] ./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.
## Windows
For releases, Windows builds of `bc`, `dc`, and `bcl` are available for download
from and GitHub.
However, if you wish to build it yourself, this `bc` can be built using Visual
Studio or MSBuild.
Unfortunately, only one build configuration (besides Debug or Release) is
-supported: extra math, and history enabled, NLS (locale support) disabled, with
+supported: extra math enabled, history and NLS (locale support) disabled, with
both calculators built. The default [settings][11] are `BC_BANNER=1`,
`{BC,DC}_SIGINT_RESET=0`, `{BC,DC}_TTY_MODE=1`, `{BC,DC}_PROMPT=1`.
The library can also be built on Windows.
### Visual Studio
In Visual Studio, open up the solution file (`bc.sln` for `bc`, or `bcl.sln` for
the library), select the desired configuration, and build.
### MSBuild
To build with MSBuild, first, *be sure that you are using the MSBuild that comes
with Visual Studio*.
To build `bc`, run the following from the root directory:
```
msbuild -property:Configuration= bc.sln
```
where `` is either one of `Debug` or `Release`.
To build the library, run the following from the root directory:
```
msbuild -property:Configuration= bcl.sln
```
where `` is either one of `Debug` or `Release`.
## POSIX-Compatible Systems
Building `bc`, `dc`, and `bcl` (the library) is more complex than on Windows
because many build options are supported.
### 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`.
### 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`.
#### `INCLUDEDIR`
The directory to install header files in.
Can be overridden by passing the `--includedir` option to `configure.sh`.
Defaults to `$PREFIX/include`.
#### `LIBDIR`
The directory to install libraries in.
Can be overridden by passing the `--libdir` option to `configure.sh`.
Defaults to `$PREFIX/lib`.
#### `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.
### 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
```
#### Library
To build the math library, use the following commands for the configure step:
```
./configure.sh -a
./configure.sh --library
```
Both commands are equivalent.
When the library is built, history and locales are disabled, and the
functionality for `bc` and `dc` are both enabled, though the executables are
*not* built. This is because the library's options clash with the executables.
To build an optimized version of the library, users can pass optimization
options to `configure.sh` or include them in `CFLAGS`.
The library API can be found in `manuals/bcl.3.md` or `man bcl` once the library
is installed.
The library is built as `bin/libbcl.a`.
#### `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).
#### History
To disable hisory, 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.
This option affects the [build type][7].
#### 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.
This option affects the [build type][7].
#### 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 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 section of the full manual.
This option affects the [build type][7].
#### 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 -k32
./configure.sh --karatsuba-len 32
```
Both commands are equivalent.
Default is `32`.
***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.
#### Settings
This `bc` and `dc` have a few settings to override default behavior.
The defaults for these settings can be set by package maintainers, and the
settings themselves can be overriden by users.
To set a default to **on**, use the `-s` or `--set-default-on` option to
`configure.sh`, with the name of the setting, as follows:
```
./configure.sh -s bc.banner
./configure.sh --set-default-on=bc.banner
```
Both commands are equivalent.
To set a default to **off**, use the `-S` or `--set-default-off` option to
`configure.sh`, with the name of the setting, as follows:
```
./configure.sh -S bc.banner
./configure.sh --set-default-off=bc.banner
```
Both commands are equivalent.
Users can override the default settings set by packagers with environment
variables. If the environment variable has an integer, then the setting is
turned **on** for a non-zero integer, and **off** for zero.
The table of the available settings, along with their defaults and the
environment variables to override them, is below:
```
| Setting | Description | Default | Env Variable |
| =============== | ==================== | ============ | ==================== |
| bc.banner | Whether to display | 0 | BC_BANNER |
| | the bc version | | |
| | banner when in | | |
| | interactive mode. | | |
| --------------- | -------------------- | ------------ | -------------------- |
| bc.sigint_reset | Whether SIGINT will | 1 | BC_SIGINT_RESET |
| | reset bc, instead of | | |
| | exiting, when in | | |
| | interactive mode. | | |
| --------------- | -------------------- | ------------ | -------------------- |
| dc.sigint_reset | Whether SIGINT will | 1 | DC_SIGINT_RESET |
| | reset dc, instead of | | |
| | exiting, when in | | |
| | interactive mode. | | |
| --------------- | -------------------- | ------------ | -------------------- |
| bc.tty_mode | Whether TTY mode for | 1 | BC_TTY_MODE |
| | bc should be on when | | |
| | available. | | |
| --------------- | -------------------- | ------------ | -------------------- |
| dc.tty_mode | Whether TTY mode for | 0 | BC_TTY_MODE |
| | dc should be on when | | |
| | available. | | |
| --------------- | -------------------- | ------------ | -------------------- |
| bc.prompt | Whether the prompt | $BC_TTY_MODE | BC_PROMPT |
| | for bc should be on | | |
| | in tty mode. | | |
| --------------- | -------------------- | ------------ | -------------------- |
| dc.prompt | Whether the prompt | $DC_TTY_MODE | DC_PROMPT |
| | for dc should be on | | |
| | in tty mode. | | |
| --------------- | -------------------- | ------------ | -------------------- |
```
These settings are not meant to be changed on a whim. They are meant to ensure
that this bc and dc will conform to the expectations of the user on each
platform.
#### 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.
##### 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.
##### Locales
By default, `bc` and `dc` do not install all locales, but only the enabled
locales. If `DESTDIR` exists and is not empty, then they will install all of
the locales that exist on the system. The `-l` flag or `--install-all-locales`
option skips all of that and just installs all of the locales that `bc` and `dc`
have, regardless. To enable that behavior, you can pass the `-l` flag or the
`--install-all-locales` option to `configure.sh`, as follows:
```
./configure.sh -l
./configure.sh --install-all-locales
```
Both commands are equivalent.
### 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
```
### Build Type
`bc` and `dc` have 8 build types, affected by the [History][8], [NLS (Locale
Support)][9], and [Extra Math][10] build options.
The build types are as follows:
* `A`: Nothing disabled.
* `E`: Extra math disabled.
* `H`: History disabled.
* `N`: NLS disabled.
* `EH`: Extra math and History disabled.
* `EN`: Extra math and NLS disabled.
* `HN`: History and NLS disabled.
* `EHN`: Extra math, History, and NLS all disabled.
These build types correspond to the generated manuals in `manuals/bc` and
`manuals/dc`.
### 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
[7]: #build-type
[8]: #history
[9]: #nls-locale-support
[10]: #extra-math
[11]: #settings
diff --git a/manuals/dc/A.1 b/manuals/dc/A.1
index f1151a812509..a7ff2e3a6963 100644
--- a/manuals/dc/A.1
+++ b/manuals/dc/A.1
@@ -1,1504 +1,1549 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "DC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH Name
.PP
dc - arbitrary-precision decimal reverse-Polish notation calculator
.SH SYNOPSIS
.PP
\f[B]dc\f[R] [\f[B]-hiPRvVx\f[R]] [\f[B]--version\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]]
[\f[B]--no-read-prompt\f[R]] [\f[B]--extended-register\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
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.
.PP
If no files are given on the command-line, then dc(1) reads from
\f[B]stdin\f[R] (see the \f[B]STDIN\f[R] section).
Otherwise, those files are processed, and dc(1) will then exit.
.PP
If a user wants to set up a standard environment, they can use
\f[B]DC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
For example, if a user wants the \f[B]scale\f[R] always set to
\f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R],
and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R].
.SH OPTIONS
.PP
The following are the options that dc(1) accepts.
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]DC_ENV_ARGS\f[R].
.RS
.PP
These options override the \f[B]DC_PROMPT\f[R] and \f[B]DC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of dc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]?\f[R] command is used.
.PP
These options \f[I]do\f[R] override the \f[B]DC_PROMPT\f[R] and
\f[B]DC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-x\f[R] \f[B]--extended-register\f[R]
Enables extended register mode.
See the \f[I]Extended Register Mode\f[R] subsection of the
\f[B]REGISTERS\f[R] section for more information.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]DC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files are given on the command-line and no files or expressions
are given by the \f[B]-f\f[R], \f[B]--file\f[R], \f[B]-e\f[R], or
\f[B]--expression\f[R] options, then dc(1) read from \f[B]stdin\f[R].
.PP
However, there is a caveat to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if a string has been finished, but not
ended.
This means that, except for escaped brackets, all brackets must be
balanced before dc(1) parses and executes.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]dc >&-\f[R], it will quit with an error.
This is done so that dc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]dc 2>&-\f[R], it will quit with an error.
This is done so that dc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
Each item in the input source code, either a number (see the
\f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R]
section), is processed and executed, in order.
Input is processed immediately when entered.
.PP
\f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to interpret constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in dc(1)
programs with the \f[B]T\f[R] command.
.PP
\f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and
can be queried with the \f[B]U\f[R] command.
The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R].
If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific
notation, and if \f[B]obase\f[R] is \f[B]1\f[R], values are output in
engineering notation.
Otherwise, values are output in the specified base.
.PP
Outputting in scientific and engineering notations are \f[B]non-portable
extensions\f[R].
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a register (see the \f[B]REGISTERS\f[R] section) that sets the
precision of any operations (with exceptions).
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] can be queried in dc(1)
programs with the \f[B]V\f[R] command.
.PP
\f[B]seed\f[R] is a register containing the current seed for the
pseudo-random number generator.
If the current value of \f[B]seed\f[R] is queried and stored, then if it
is assigned to \f[B]seed\f[R] later, the pseudo-random number generator
is guaranteed to produce the same sequence of pseudo-random numbers that
were generated after the value of \f[B]seed\f[R] was first queried.
.PP
Multiple values assigned to \f[B]seed\f[R] can produce the same sequence
of pseudo-random numbers.
Likewise, when a value is assigned to \f[B]seed\f[R], it is not
guaranteed that querying \f[B]seed\f[R] immediately after will return
the same value.
In addition, the value of \f[B]seed\f[R] will change after any call to
the \f[B]\[cq]\f[R] command or the \f[B]\[lq]\f[R] command that does not
get receive a value of \f[B]0\f[R] or \f[B]1\f[R].
The maximum integer returned by the \f[B]\[cq]\f[R] command can be
queried with the \f[B]W\f[R] command.
.PP
\f[B]Note\f[R]: The values returned by the pseudo-random number
generator with the \f[B]\[cq]\f[R] and \f[B]\[lq]\f[R] commands are
guaranteed to \f[B]NOT\f[R] be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they \f[I]are\f[R] guaranteed to be reproducible with identical
\f[B]seed\f[R] values.
This means that the pseudo-random values from dc(1) should only be used
where a reproducible stream of pseudo-random numbers is
\f[I]ESSENTIAL\f[R].
In any other case, use a non-seeded pseudo-random number generator.
.PP
The pseudo-random number generator, \f[B]seed\f[R], and all associated
operations are \f[B]non-portable extensions\f[R].
.SS Comments
.PP
Comments go from \f[B]#\f[R] until, and not including, the next newline.
This is a \f[B]non-portable extension\f[R].
.SH NUMBERS
.PP
Numbers are strings made up of digits, uppercase letters up to
\f[B]F\f[R], and at most \f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]F\f[R] alone always equals decimal \f[B]15\f[R].
.PP
In addition, dc(1) accepts numbers in scientific notation.
These have the form \f[B]e\f[R].
The exponent (the portion after the \f[B]e\f[R]) must be an integer.
An example is \f[B]1.89237e9\f[R], which is equal to
\f[B]1892370000\f[R].
Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to
\f[B]0.0042890\f[R].
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if dc(1) is given the number string
\f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.PP
Accepting input as scientific notation is a \f[B]non-portable
extension\f[R].
.SH COMMANDS
.PP
The valid commands are listed below.
.SS Printing
.PP
These commands are used for printing.
.PP
Note that both scientific notation and engineering notation are
available for printing numbers.
Scientific notation is activated by assigning \f[B]0\f[R] to
\f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is
activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using
\f[B]1o\f[R].
To deactivate them, just assign a different value to \f[B]obase\f[R].
.PP
Printing numbers in scientific notation and/or engineering notation is a
\f[B]non-portable extension\f[R].
.TP
\f[B]p\f[R]
Prints the value on top of the stack, whether number or string, and
prints a newline after.
.RS
.PP
This does not alter the stack.
.RE
.TP
\f[B]n\f[R]
Prints the value on top of the stack, whether number or string, and pops
it off of the stack.
.TP
\f[B]P\f[R]
Pops a value off the stack.
.RS
.PP
If the value is a number, it is truncated and the absolute value of the
result is printed as though \f[B]obase\f[R] is \f[B]256\f[R] and each
digit is interpreted as an 8-bit ASCII character, making it a byte
stream.
.PP
If the value is a string, it is printed without a trailing newline.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]f\f[R]
Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
.RS
.PP
Users should use this command when they get lost.
.RE
.SS Arithmetic
.PP
These are the commands used for arithmetic.
.TP
\f[B]+\f[R]
The top two values are popped off the stack, added, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]-\f[R]
The top two values are popped off the stack, subtracted, and the result
is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]*\f[R]
The top two values are popped off the stack, multiplied, and the result
is pushed onto the stack.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The top two values are popped off the stack, divided, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]%\f[R]
The top two values are popped off the stack, remaindered, and the result
is pushed onto the stack.
.RS
.PP
Remaindering is equivalent to 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R], and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]\[ti]\f[R]
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 \f[B]x y / x y %\f[R] except that \f[B]x\f[R] and
\f[B]y\f[R] are only evaluated once.
.RS
.PP
The first value popped off of the stack must be non-zero.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
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.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
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.
.RE
.TP
\f[B]v\f[R]
The top value is popped off the stack, its square root is computed, and
the result is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The value popped off of the stack must be non-negative.
.RE
.TP
\f[B]_\f[R]
If this command \f[I]immediately\f[R] precedes a number (i.e., no spaces
or other commands), then that number is input as a negative number.
.RS
.PP
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 \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]b\f[R]
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.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]|\f[R]
The top three values are popped off the stack, a modular exponentiation
is computed, and the result is pushed onto the stack.
.RS
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]$\f[R]
The top value is popped off the stack and copied, and the copy is
truncated and pushed onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[at]\f[R]
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.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]H\f[R]
The top two values are popped off the stack, and the second is shifted
left (radix shifted right) to the value of the first.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]h\f[R]
The top two values are popped off the stack, and the second is shifted
right (radix shifted left) to the value of the first.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]G\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]N\f[R]
The top value is popped off of the stack, and if it a \f[B]0\f[R], a
\f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B](\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]{\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than or equal to the second,
or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B])\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]}\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than or equal to the
second, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]M\f[R]
The top two values are popped off of the stack.
If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack.
If either of them is zero, or both of them are, then a \f[B]0\f[R] is
pushed onto the stack.
.RS
.PP
This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]m\f[R]
The top two values are popped off of the stack.
If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the
stack.
If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack.
.RS
.PP
This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Pseudo-Random Number Generator
.PP
dc(1) has a built-in pseudo-random number generator.
These commands query the pseudo-random number generator.
(See Parameters for more information about the \f[B]seed\f[R] value that
controls the pseudo-random number generator.)
.PP
The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be
cryptographically secure.
.TP
\f[B]\[cq]\f[R]
Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see
the \f[B]LIMITS\f[R] section).
.RS
.PP
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[lq]\f[R]
Pops a value off of the stack, which is used as an \f[B]exclusive\f[R]
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 \f[B]RESET\f[R] section) while \f[B]seed\f[R]
remains unchanged.
If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is
honored by generating several pseudo-random integers, multiplying them
by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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 \f[B]seed\f[R], unless the
operand is \f[B]0\f[R] or \f[B]1\f[R].
In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R]
is \f[I]not\f[R] changed.
.RS
.PP
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Stack Control
.PP
These commands control the stack.
.TP
\f[B]c\f[R]
Removes all items from (\[lq]clears\[rq]) the stack.
.TP
\f[B]d\f[R]
Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes
the copy onto the stack.
.TP
\f[B]r\f[R]
Swaps (\[lq]reverses\[rq]) the two top items on the stack.
.TP
\f[B]R\f[R]
Pops (\[lq]removes\[rq]) the top value from the stack.
.SS Register Control
.PP
These commands control registers (see the \f[B]REGISTERS\f[R] section).
.TP
\f[B]s\f[R]\f[I]r\f[R]
Pops the value off the top of the stack and stores it into register
\f[I]r\f[R].
.TP
\f[B]l\f[R]\f[I]r\f[R]
Copies the value in register \f[I]r\f[R] and pushes it onto the stack.
This does not alter the contents of \f[I]r\f[R].
.TP
\f[B]S\f[R]\f[I]r\f[R]
Pops the value off the top of the (main) stack and pushes it onto the
stack of register \f[I]r\f[R].
The previous value of the register becomes inaccessible.
.TP
\f[B]L\f[R]\f[I]r\f[R]
Pops the value off the top of the stack for register \f[I]r\f[R] and
push it onto the main stack.
The previous value in the stack for register \f[I]r\f[R], if any, is now
accessible via the \f[B]l\f[R]\f[I]r\f[R] command.
.SS Parameters
.PP
These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R],
\f[B]scale\f[R], and \f[B]seed\f[R].
Also see the \f[B]SYNTAX\f[R] section.
.TP
\f[B]i\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R],
inclusive.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]o\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]obase\f[R], which must be between \f[B]0\f[R] and
\f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and
the \f[B]NUMBERS\f[R] section).
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]k\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]scale\f[R], which must be non-negative.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]j\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]seed\f[R].
The meaning of \f[B]seed\f[R] is dependent on the current pseudo-random
number generator but is guaranteed to not change except for new major
versions.
.RS
.PP
The \f[I]scale\f[R] and sign of the value may be significant.
.PP
If a previously used \f[B]seed\f[R] 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 \f[B]seed\f[R]
value was previously used.
.PP
The exact value assigned to \f[B]seed\f[R] is not guaranteed to be
returned if the \f[B]J\f[R] command is used.
However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both
values, when assigned to \f[B]seed\f[R], are guaranteed to produce the
same sequence of pseudo-random numbers.
This means that certain values assigned to \f[B]seed\f[R] will not
produce unique sequences of pseudo-random numbers.
.PP
There is no limit to the length (number of significant decimal digits)
or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]I\f[R]
Pushes the current value of \f[B]ibase\f[R] onto the main stack.
.TP
\f[B]O\f[R]
Pushes the current value of \f[B]obase\f[R] onto the main stack.
.TP
\f[B]K\f[R]
Pushes the current value of \f[B]scale\f[R] onto the main stack.
.TP
\f[B]J\f[R]
Pushes the current value of \f[B]seed\f[R] onto the main stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]T\f[R]
Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]U\f[R]
Pushes the maximum allowable value of \f[B]obase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]V\f[R]
Pushes the maximum allowable value of \f[B]scale\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]W\f[R]
Pushes the maximum (inclusive) integer that can be generated with the
\f[B]\[cq]\f[R] pseudo-random number generator command.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Strings
.PP
The following commands control strings.
.PP
dc(1) can work with both numbers and strings, and registers (see the
\f[B]REGISTERS\f[R] section) can hold both strings and numbers.
dc(1) always knows whether the contents of a register are a string or a
number.
.PP
While arithmetic operations have to have numbers, and will print an
error if given a string, other commands accept strings.
.PP
Strings can also be executed as macros.
For example, if the string \f[B][1pR]\f[R] is executed as a macro, then
the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be
printed with a newline after and then popped from the stack.
.TP
\f[B][\f[R]\f[I]characters\f[R]\f[B]]\f[R]
Makes a string containing \f[I]characters\f[R] and pushes it onto the
stack.
.RS
.PP
If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then
they must be balanced.
Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R])
character.
.PP
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.
.RE
.TP
\f[B]a\f[R]
The value on top of the stack is popped.
.RS
.PP
If it is a number, it is truncated and its absolute value is taken.
The result mod \f[B]256\f[R] is calculated.
If that result is \f[B]0\f[R], push an empty string; otherwise, push a
one-character string where the character is the result of the mod
interpreted as an ASCII character.
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]x\f[R]
Pops a value off of the top of the stack.
.RS
.PP
If it is a number, it is pushed back onto the stack.
.PP
If it is a string, it is executed as a macro.
.PP
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
For example, \f[B]0 1>a\f[R] will execute the contents of register
\f[B]a\f[R], and \f[B]1 0>a\f[R] will not.
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]
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
\f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]?\f[R]
Reads a line from the \f[B]stdin\f[R] and executes it.
This is to allow macros to request input from users.
.TP
\f[B]q\f[R]
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
\f[B]Q\f[R]
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.
.TP
\f[B],\f[R]
Pushes the depth of the execution stack onto the stack.
The execution stack is the stack of string executions.
The number that is pushed onto the stack is exactly as many as is needed
to make dc(1) exit with the \f[B]Q\f[R] command, so the sequence
\f[B],Q\f[R] will make dc(1) exit.
.SS Status
.PP
These commands query status of the stack or its top value.
.TP
\f[B]Z\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, calculates the number of significant decimal digits
it has and pushes the result.
It will push \f[B]1\f[R] if the argument is \f[B]0\f[R] with no decimal
places.
.PP
If it is a string, pushes the number of characters the string has.
.RE
.TP
\f[B]X\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, pushes the \f[I]scale\f[R] of the value onto the
stack.
.PP
If it is a string, pushes \f[B]0\f[R].
.RE
.TP
\f[B]z\f[R]
Pushes the current depth of the stack (before execution of this command)
onto the stack.
.TP
\f[B]y\f[R]\f[I]r\f[R]
Pushes the current stack depth of the register \f[I]r\f[R] onto the main
stack.
.RS
.PP
Because each register has a depth of \f[B]1\f[R] (with the value
\f[B]0\f[R] in the top item) when dc(1) starts, dc(1) requires that each
register\[cq]s stack must always have at least one item; dc(1) will give
an error and reset otherwise (see the \f[B]RESET\f[R] section).
This means that this command will never push \f[B]0\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Arrays
.PP
These commands manipulate arrays.
.TP
\f[B]:\f[R]\f[I]r\f[R]
Pops the top two values off of the stack.
The second value will be stored in the array \f[I]r\f[R] (see the
\f[B]REGISTERS\f[R] section), indexed by the first value.
.TP
\f[B];\f[R]\f[I]r\f[R]
Pops the value on top of the stack and uses it as an index into the
array \f[I]r\f[R].
The selected value is then pushed onto the stack.
.TP
\f[B]Y\f[R]\f[I]r\f[R]
Pushes the length of the array \f[I]r\f[R] onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
+.SS Global Settings
+.PP
+These commands retrieve global settings.
+These are the only commands that require multiple specific characters,
+and all of them begin with the letter \f[B]g\f[R].
+Only the characters below are allowed after the character \f[B]g\f[R];
+any other character produces a parse error (see the \f[B]ERRORS\f[R]
+section).
+.TP
+\f[B]gl\f[R]
+Pushes the line length set by \f[B]DC_LINE_LENGTH\f[R] (see the
+\f[B]ENVIRONMENT VARIABLES\f[R] section) onto the stack.
+.TP
+\f[B]gz\f[R]
+Pushes \f[B]0\f[R] onto the stack if the leading zero setting has not
+been enabled with the \f[B]-z\f[R] or \f[B]--leading-zeroes\f[R] options
+(see the \f[B]OPTIONS\f[R] section), non-zero otherwise.
.SH REGISTERS
.PP
Registers are names that can store strings, numbers, and arrays.
(Number/string registers do not interfere with array registers.)
.PP
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 (\f[B]0\f[R]) in
their stack, and it is a runtime error to attempt to pop that item off
of the register stack.
.PP
In non-extended register mode, a register name is just the single
character that follows any command that needs a register name.
The only exceptions are: a newline (\f[B]`\[rs]n'\f[R]) and a left
bracket (\f[B]`['\f[R]); it is a parse error for a newline or a left
bracket to be used as a register name.
.SS Extended Register Mode
.PP
Unlike most other dc(1) implentations, this dc(1) provides nearly
unlimited amounts of registers, if extended register mode is enabled.
.PP
If extended register mode is enabled (\f[B]-x\f[R] or
\f[B]--extended-register\f[R] command-line arguments are given), then
normal single character registers are used \f[I]unless\f[R] the
character immediately following a command that needs a register name is
a space (according to \f[B]isspace()\f[R]) and not a newline
(\f[B]`\[rs]n'\f[R]).
.PP
In that case, the register name is found according to the regex
\f[B][a-z][a-z0-9_]*\f[R] (like bc(1) identifiers), and it is a parse
error if the next non-space characters do not match that regex.
.SH RESET
.PP
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.
.PP
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 macros returned) is skipped.
.PP
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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.SH PERFORMANCE
.PP
Most dc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This dc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]DC_BASE_DIGS\f[R].
.PP
In addition, this dc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]DC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on dc(1):
.TP
\f[B]DC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] 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 \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]DC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]DC_BASE_DIGS\f[R].
.TP
\f[B]DC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]DC_BASE_POW\f[R].
.TP
\f[B]DC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]DC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command,
if dc(1).
Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]DC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
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
.PP
dc(1) recognizes the following environment variables:
.TP
\f[B]DC_ENV_ARGS\f[R]
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
\f[B]DC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 \f[B]-e\f[R] option to set
\f[B]scale\f[R] to a value other than \f[B]0\f[R].
.RS
.PP
The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`dc' file.dc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]DC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]DC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length,
including the backslash newline combo.
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]DC_SIGINT_RESET\f[R]
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because dc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes dc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then dc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use
TTY mode, and zero makes dc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a
prompt, and zero or a non-integer makes dc(1) not use a prompt.
If this environment variable does not exist and \f[B]DC_TTY_MODE\f[R]
does, then the value of the \f[B]DC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]DC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
dc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], 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, overflow when calculating the size of a number, and attempting
to use a non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift
(\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, and using a
token where it is invalid.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors (including attempting to execute
a number), and attempting an operation when the stack has too few
elements.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
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.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, dc(1)
always exits and returns \f[B]4\f[R], no matter what mode dc(1) is in.
.PP
The other statuses will only be returned when dc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
dc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, dc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
dc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]DC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, dc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]DC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, dc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]DC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then dc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]DC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Command-Line History
.PP
Command-line history is only enabled if TTY mode is, i.e., that
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to
a TTY and the \f[B]DC_TTY_MODE\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section) and its default do not disable
TTY mode.
See the \f[B]COMMAND LINE HISTORY\f[R] section for more information.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]DC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]DC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]DC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]DC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause dc(1) to do one of two things.
.PP
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, dc(1) will exit.
.PP
However, if dc(1) is in interactive mode, and the
\f[B]DC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then dc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If dc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If dc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] 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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause dc(1) to clean up and
exit, and it uses the default handler for all other signals.
The one exception is \f[B]SIGHUP\f[R]; in that case, and only when dc(1)
is in TTY mode (see the \f[B]TTY MODE\f[R] section), a \f[B]SIGHUP\f[R]
will cause dc(1) to clean up and exit.
.SH COMMAND LINE HISTORY
.PP
dc(1) supports interactive command-line editing.
.PP
If dc(1) can be in TTY mode (see the \f[B]TTY MODE\f[R] section),
history can be enabled.
This means that command-line history can only be enabled when
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY.
.PP
Like TTY mode itself, it can be turned on or off with the environment
variable \f[B]DC_TTY_MODE\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
\f[B]Note\f[R]: tabs are converted to 8 spaces.
.SH LOCALES
.PP
This dc(1) ships with support for adding error messages for different
locales and thus, supports \f[B]LC_MESSAGES\f[R].
.SH SEE ALSO
.PP
bc(1)
.SH STANDARDS
.PP
The dc(1) utility operators are compliant with the operators in the
bc(1) IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHOR
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/dc/A.1.md b/manuals/dc/A.1.md
index 3a09d4375395..0007cc76760a 100644
--- a/manuals/dc/A.1.md
+++ b/manuals/dc/A.1.md
@@ -1,1344 +1,1384 @@
# Name
dc - arbitrary-precision decimal reverse-Polish notation calculator
# SYNOPSIS
**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# 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.
If no files are given on the command-line, then dc(1) reads from **stdin** (see
the **STDIN** section). Otherwise, those files are processed, and dc(1) will
then exit.
If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
this dc(1) will always start with a **scale** of **10**.
# OPTIONS
The following are the options that dc(1) accepts.
**-h**, **-\-help**
: Prints a usage message and quits.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in dc(1). Most of those users
would want to put this option in **DC_ENV_ARGS**.
These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of dc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **?** command is used.
These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-x** **-\-extended-register**
: Enables extended register mode. See the *Extended Register Mode* subsection
of the **REGISTERS** section for more information.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files are given on the command-line and no files or expressions are given
by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
read from **stdin**.
However, there is a caveat to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
a string has been finished, but not ended. This means that, except for escaped
brackets, all brackets must be balanced before dc(1) parses and executes.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **dc >&-**, it will quit with an error. This
is done so that dc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This
is done so that dc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
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.
**ibase** is a register (see the **REGISTERS** section) that determines how to
interpret constant numbers. It is the "input" base, or the number base used for
interpreting input numbers. **ibase** is initially **10**. The max allowable
value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
The max allowable value for **ibase** can be queried in dc(1) programs with the
**T** command.
**obase** is a register (see the **REGISTERS** section) that determines how to
output results. It is the "output" base, or the number base used for outputting
numbers. **obase** is initially **10**. The max allowable value for **obase** is
**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
value for **obase** is **0**. If **obase** is **0**, values are output in
scientific notation, and if **obase** is **1**, values are output in engineering
notation. Otherwise, values are output in the specified base.
Outputting in scientific and engineering notations are **non-portable
extensions**.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a register (see the
**REGISTERS** section) that sets the precision of any operations (with
exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
allowable value for **scale** can be queried in dc(1) programs with the **V**
command.
**seed** is a register containing the current seed for the pseudo-random number
generator. If the current value of **seed** is queried and stored, then if it is
assigned to **seed** later, the pseudo-random number generator is guaranteed to
produce the same sequence of pseudo-random numbers that were generated after the
value of **seed** was first queried.
Multiple values assigned to **seed** can produce the same sequence of
pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not
guaranteed that querying **seed** immediately after will return the same value.
In addition, the value of **seed** will change after any call to the **'**
command or the **"** command that does not get receive a value of **0** or
**1**. The maximum integer returned by the **'** command can be queried with the
**W** command.
**Note**: The values returned by the pseudo-random number generator with the
**'** and **"** commands are guaranteed to **NOT** be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator. However,
they *are* guaranteed to be reproducible with identical **seed** values. This
means that the pseudo-random values from dc(1) should only be used where a
reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
use a non-seeded pseudo-random number generator.
The pseudo-random number generator, **seed**, and all associated operations are
**non-portable extensions**.
## Comments
Comments go from **#** until, and not including, the next newline. This is a
**non-portable extension**.
# NUMBERS
Numbers are strings made up of digits, uppercase letters up to **F**, and at
most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
current value of **ibase**, they are set to the value of the highest valid digit
in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **F** alone always equals decimal
**15**.
In addition, dc(1) accepts numbers in scientific notation. These have the form
**\e\**. The exponent (the portion after the **e**) must be
an integer. An example is **1.89237e9**, which is equal to **1892370000**.
Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For example,
if **ibase** is **16** and dc(1) is given the number string **FFeA**, the
resulting decimal number will be **2550000000000**, and if dc(1) is given the
number string **10e_4**, the resulting decimal number will be **0.0016**.
Accepting input as scientific notation is a **non-portable extension**.
# COMMANDS
The valid commands are listed below.
## Printing
These commands are used for printing.
Note that both scientific notation and engineering notation are available for
printing numbers. Scientific notation is activated by assigning **0** to
**obase** using **0o**, and engineering notation is activated by assigning **1**
to **obase** using **1o**. To deactivate them, just assign a different value to
**obase**.
Printing numbers in scientific notation and/or engineering notation is a
**non-portable extension**.
**p**
: Prints the value on top of the stack, whether number or string, and prints a
newline after.
This does not alter the stack.
**n**
: Prints the value on top of the stack, whether number or string, and pops it
off of the stack.
**P**
: Pops a value off the stack.
If the value is a number, it is truncated and the absolute value of the
result is printed as though **obase** is **256** and each digit is
interpreted as an 8-bit ASCII character, making it a byte stream.
If the value is a string, it is printed without a trailing newline.
This is a **non-portable extension**.
**f**
: Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
Users should use this command when they get lost.
## Arithmetic
These are the commands used for arithmetic.
**+**
: The top two values are popped off the stack, added, and the result is pushed
onto the stack. The *scale* of the result is equal to the max *scale* of
both operands.
**-**
: The top two values are popped off the stack, subtracted, and the result is
pushed onto the stack. The *scale* of the result is equal to the max
*scale* of both operands.
**\***
: The top two values are popped off the stack, multiplied, and the result is
pushed onto the stack. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result
is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The top two values are popped off the stack, divided, and the result is
pushed onto the stack. The *scale* of the result is equal to **scale**.
The first value popped off of the stack must be non-zero.
**%**
: The top two values are popped off the stack, remaindered, and the result is
pushed onto the stack.
Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The first value popped off of the stack must be non-zero.
**~**
: 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 **x y / x y %** except that **x** and **y** are only
evaluated once.
The first value popped off of the stack must be non-zero.
This is a **non-portable extension**.
**\^**
: 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. The *scale* of
the result is equal to **scale**.
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.
**v**
: The top value is popped off the stack, its square root is computed, and the
result is pushed onto the stack. The *scale* of the result is equal to
**scale**.
The value popped off of the stack must be non-negative.
**\_**
: If this command *immediately* precedes a number (i.e., no spaces or other
commands), then that number is input as a negative number.
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
**non-portable extension**.
**b**
: 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.
This is a **non-portable extension**.
**|**
: The top three values are popped off the stack, a modular exponentiation is
computed, and the result is pushed onto the stack.
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.
This is a **non-portable extension**.
**\$**
: The top value is popped off the stack and copied, and the copy is truncated
and pushed onto the stack.
This is a **non-portable extension**.
**\@**
: 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.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**H**
: The top two values are popped off the stack, and the second is shifted left
(radix shifted right) to the value of the first.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**h**
: The top two values are popped off the stack, and the second is shifted right
(radix shifted left) to the value of the first.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**G**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if they are equal, or **0** otherwise.
This is a **non-portable extension**.
**N**
: The top value is popped off of the stack, and if it a **0**, a **1** is
pushed; otherwise, a **0** is pushed.
This is a **non-portable extension**.
**(**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than the second, or **0** otherwise.
This is a **non-portable extension**.
**{**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than or equal to the second, or **0**
otherwise.
This is a **non-portable extension**.
**)**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than the second, or **0** otherwise.
This is a **non-portable extension**.
**}**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than or equal to the second, or
**0** otherwise.
This is a **non-portable extension**.
**M**
: The top two values are popped off of the stack. If they are both non-zero, a
**1** is pushed onto the stack. If either of them is zero, or both of them
are, then a **0** is pushed onto the stack.
This is like the **&&** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
**m**
: The top two values are popped off of the stack. If at least one of them is
non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
**0** is pushed onto the stack.
This is like the **||** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
## Pseudo-Random Number Generator
dc(1) has a built-in pseudo-random number generator. These commands query the
pseudo-random number generator. (See Parameters for more information about the
**seed** value that controls the pseudo-random number generator.)
The pseudo-random number generator is guaranteed to **NOT** be
cryptographically secure.
**'**
: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the
**LIMITS** section).
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
This is a **non-portable extension**.
**"**
: Pops a value off of the stack, which is used as an **exclusive** 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) while **seed** remains unchanged. If the bound is larger than
**DC_RAND_MAX**, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
**DC_RAND_MAX+1**, 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 **seed**, unless the operand is **0** or **1**. In that
case, **0** is pushed onto the stack, and **seed** is *not* changed.
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
This is a **non-portable extension**.
## Stack Control
These commands control the stack.
**c**
: Removes all items from ("clears") the stack.
**d**
: Copies the item on top of the stack ("duplicates") and pushes the copy onto
the stack.
**r**
: Swaps ("reverses") the two top items on the stack.
**R**
: Pops ("removes") the top value from the stack.
## Register Control
These commands control registers (see the **REGISTERS** section).
**s**_r_
: Pops the value off the top of the stack and stores it into register *r*.
**l**_r_
: Copies the value in register *r* and pushes it onto the stack. This does not
alter the contents of *r*.
**S**_r_
: Pops the value off the top of the (main) stack and pushes it onto the stack
of register *r*. The previous value of the register becomes inaccessible.
**L**_r_
: Pops the value off the top of the stack for register *r* and push it onto
the main stack. The previous value in the stack for register *r*, if any, is
now accessible via the **l**_r_ command.
## Parameters
These commands control the values of **ibase**, **obase**, **scale**, and
**seed**. Also see the **SYNTAX** section.
**i**
: Pops the value off of the top of the stack and uses it to set **ibase**,
which must be between **2** and **16**, inclusive.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**o**
: Pops the value off of the top of the stack and uses it to set **obase**,
which must be between **0** and **DC_BASE_MAX**, inclusive (see the
**LIMITS** section and the **NUMBERS** section).
If the value on top of the stack has any *scale*, the *scale* is ignored.
**k**
: Pops the value off of the top of the stack and uses it to set **scale**,
which must be non-negative.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**j**
: Pops the value off of the top of the stack and uses it to set **seed**. The
meaning of **seed** is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major versions.
The *scale* and sign of the value may be significant.
If a previously used **seed** 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 **seed** value was previously used.
The exact value assigned to **seed** is not guaranteed to be returned if the
**J** command is used. However, if **seed** *does* return a different value,
both values, when assigned to **seed**, are guaranteed to produce the same
sequence of pseudo-random numbers. This means that certain values assigned
to **seed** will not produce unique sequences of pseudo-random numbers.
There is no limit to the length (number of significant decimal digits) or
*scale* of the value that can be assigned to **seed**.
This is a **non-portable extension**.
**I**
: Pushes the current value of **ibase** onto the main stack.
**O**
: Pushes the current value of **obase** onto the main stack.
**K**
: Pushes the current value of **scale** onto the main stack.
**J**
: Pushes the current value of **seed** onto the main stack.
This is a **non-portable extension**.
**T**
: Pushes the maximum allowable value of **ibase** onto the main stack.
This is a **non-portable extension**.
**U**
: Pushes the maximum allowable value of **obase** onto the main stack.
This is a **non-portable extension**.
**V**
: Pushes the maximum allowable value of **scale** onto the main stack.
This is a **non-portable extension**.
**W**
: Pushes the maximum (inclusive) integer that can be generated with the **'**
pseudo-random number generator command.
This is a **non-portable extension**.
## Strings
The following commands control strings.
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.
While arithmetic operations have to have numbers, and will print an error if
given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string **[1pR]** is
executed as a macro, then the code **1pR** is executed, meaning that the **1**
will be printed with a newline after and then popped from the stack.
**\[**_characters_**\]**
: Makes a string containing *characters* and pushes it onto the stack.
If there are brackets (**\[** and **\]**) in the string, then they must be
balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
character.
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.
**a**
: The value on top of the stack is popped.
If it is a number, it is truncated and its absolute value is taken. The
result mod **256** is calculated. If that result is **0**, push an empty
string; otherwise, push a one-character string where the character is the
result of the mod interpreted as an ASCII character.
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.
This is a **non-portable extension**.
**x**
: Pops a value off of the top of the stack.
If it is a number, it is pushed back onto the stack.
If it is a string, it is executed as a macro.
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
**\>**_r_
: 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
*r* are executed.
For example, **0 1>a** will execute the contents of register **a**, and
**1 0>a** will not.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\>**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**\<**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\<**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**=**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!=**_r_
: 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
*r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**?**
: Reads a line from the **stdin** and executes it. This is to allow macros to
request input from users.
**q**
: 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.
**Q**
: 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.
**,**
: Pushes the depth of the execution stack onto the stack. The execution stack
is the stack of string executions. The number that is pushed onto the stack
is exactly as many as is needed to make dc(1) exit with the **Q** command,
so the sequence **,Q** will make dc(1) exit.
## Status
These commands query status of the stack or its top value.
**Z**
: Pops a value off of the stack.
If it is a number, calculates the number of significant decimal digits it
has and pushes the result. It will push **1** if the argument is **0** with
no decimal places.
If it is a string, pushes the number of characters the string has.
**X**
: Pops a value off of the stack.
If it is a number, pushes the *scale* of the value onto the stack.
If it is a string, pushes **0**.
**z**
: Pushes the current depth of the stack (before execution of this command)
onto the stack.
**y**_r_
: Pushes the current stack depth of the register *r* onto the main stack.
Because each register has a depth of **1** (with the value **0** in the top
item) when dc(1) starts, dc(1) requires that each register's stack must
always have at least one item; dc(1) will give an error and reset otherwise
(see the **RESET** section). This means that this command will never push
**0**.
This is a **non-portable extension**.
## Arrays
These commands manipulate arrays.
**:**_r_
: Pops the top two values off of the stack. The second value will be stored in
the array *r* (see the **REGISTERS** section), indexed by the first value.
**;**_r_
: Pops the value on top of the stack and uses it as an index into the array
*r*. The selected value is then pushed onto the stack.
**Y**_r_
: Pushes the length of the array *r* onto the stack.
This is a **non-portable extension**.
+## Global Settings
+
+These commands retrieve global settings. These are the only commands that
+require multiple specific characters, and all of them begin with the letter
+**g**. Only the characters below are allowed after the character **g**; any
+other character produces a parse error (see the **ERRORS** section).
+
+**gl**
+
+: Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT
+ VARIABLES** section) onto the stack.
+
+**gz**
+
+: Pushes **0** onto the stack if the leading zero setting has not been enabled
+ with the **-z** or **-\-leading-zeroes** options (see the **OPTIONS**
+ section), non-zero otherwise.
+
# REGISTERS
Registers are names that can store strings, numbers, and arrays. (Number/string
registers do not interfere with array registers.)
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
(**0**) in their stack, and it is a runtime error to attempt to pop that item
off of the register stack.
In non-extended register mode, a register name is just the single character that
follows any command that needs a register name. The only exceptions are: a
newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
newline or a left bracket to be used as a register name.
## Extended Register Mode
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
amounts of registers, if extended register mode is enabled.
If extended register mode is enabled (**-x** or **-\-extended-register**
command-line arguments are given), then normal single character registers are
used *unless* the character immediately following a command that needs a
register name is a space (according to **isspace()**) and not a newline
(**'\\n'**).
In that case, the register name is found according to the regex
**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
the next non-space characters do not match that regex.
# 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.
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
macros returned) is skipped.
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.
# PERFORMANCE
Most dc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This dc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**DC_BASE_DIGS**.
In addition, this dc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **DC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on dc(1):
**DC_LONG_BIT**
: The number of bits in the **long** 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).
**DC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **DC_LONG_BIT**.
**DC_BASE_POW**
: The max decimal number that each large integer can store (see
**DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
**DC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **DC_LONG_BIT**.
**DC_BASE_MAX**
: The maximum output base. Set at **DC_BASE_POW**.
**DC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**DC_SCALE_MAX**
: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
**DC_STRING_MAX**
: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
**DC_NAME_MAX**
: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
**DC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
**DC_RAND_MAX**
: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set
at **2\^DC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**DC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
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.
# ENVIRONMENT VARIABLES
dc(1) recognizes the following environment variables:
**DC_ENV_ARGS**
: 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 **DC_ENV_ARGS** 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 **-e** option to set **scale** to a value other than **0**.
The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
**"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'dc' file.dc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **DC_ENV_ARGS** 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.
**DC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
lines to that length, including the backslash newline combo. The default
line length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**DC_SIGINT_RESET**
: If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because dc(1) exits on
**SIGINT** when not in interactive mode.
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1) reset
on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
environment variable exists and is *not* an integer, then dc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use TTY
mode, and zero makes dc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a prompt,
and zero or a non-integer makes dc(1) not use a prompt. If this environment
variable does not exist and **DC_TTY_MODE** does, then the value of the
**DC_TTY_MODE** environment variable is used.
This environment variable and the **DC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
dc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, 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, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**), places (**\@**), left shift (**H**), and right shift (**h**)
operators.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, and using a token where it is
invalid.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors (including
attempting to execute a number), and attempting an operation when the stack
has too few elements.
**4**
: A fatal error occurred.
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.
The exit status **4** is special; when a fatal error occurs, dc(1) always exits
and returns **4**, no matter what mode dc(1) is in.
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
**-i** flag or **-\-interactive** option.
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 **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **DC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **DC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
mode on.
If the environment variable **DC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
**stdout**, and **stderr** are connected to a TTY and the **DC_TTY_MODE**
environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
information.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **DC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause dc(1) to do one of two things.
If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, dc(1) will
exit.
However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
default is an integer and non-zero, then dc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If dc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If dc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** 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.
**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is **SIGHUP**; in that
case, and only when dc(1) is in TTY mode (see the **TTY MODE** section), a
**SIGHUP** will cause dc(1) to clean up and exit.
# COMMAND LINE HISTORY
dc(1) supports interactive command-line editing.
If dc(1) can be in TTY mode (see the **TTY MODE** section), history can be
enabled. This means that command-line history can only be enabled when
**stdin**, **stdout**, and **stderr** are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment variable
**DC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
**Note**: tabs are converted to 8 spaces.
# LOCALES
This dc(1) ships with support for adding error messages for different locales
and thus, supports **LC_MESSAGES**.
# SEE ALSO
bc(1)
# STANDARDS
The dc(1) utility operators are compliant with the operators in the bc(1)
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHOR
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/manuals/dc/E.1 b/manuals/dc/E.1
index 9f8859b8f6b0..8760477a03ff 100644
--- a/manuals/dc/E.1
+++ b/manuals/dc/E.1
@@ -1,1297 +1,1342 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "DC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH Name
.PP
dc - arbitrary-precision decimal reverse-Polish notation calculator
.SH SYNOPSIS
.PP
\f[B]dc\f[R] [\f[B]-hiPRvVx\f[R]] [\f[B]--version\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]]
[\f[B]--no-read-prompt\f[R]] [\f[B]--extended-register\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
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.
.PP
If no files are given on the command-line, then dc(1) reads from
\f[B]stdin\f[R] (see the \f[B]STDIN\f[R] section).
Otherwise, those files are processed, and dc(1) will then exit.
.PP
If a user wants to set up a standard environment, they can use
\f[B]DC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
For example, if a user wants the \f[B]scale\f[R] always set to
\f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R],
and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R].
.SH OPTIONS
.PP
The following are the options that dc(1) accepts.
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]DC_ENV_ARGS\f[R].
.RS
.PP
These options override the \f[B]DC_PROMPT\f[R] and \f[B]DC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of dc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]?\f[R] command is used.
.PP
These options \f[I]do\f[R] override the \f[B]DC_PROMPT\f[R] and
\f[B]DC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-x\f[R] \f[B]--extended-register\f[R]
Enables extended register mode.
See the \f[I]Extended Register Mode\f[R] subsection of the
\f[B]REGISTERS\f[R] section for more information.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]DC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files are given on the command-line and no files or expressions
are given by the \f[B]-f\f[R], \f[B]--file\f[R], \f[B]-e\f[R], or
\f[B]--expression\f[R] options, then dc(1) read from \f[B]stdin\f[R].
.PP
However, there is a caveat to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if a string has been finished, but not
ended.
This means that, except for escaped brackets, all brackets must be
balanced before dc(1) parses and executes.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]dc >&-\f[R], it will quit with an error.
This is done so that dc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]dc 2>&-\f[R], it will quit with an error.
This is done so that dc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
Each item in the input source code, either a number (see the
\f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R]
section), is processed and executed, in order.
Input is processed immediately when entered.
.PP
\f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to interpret constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in dc(1)
programs with the \f[B]T\f[R] command.
.PP
\f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and
can be queried with the \f[B]U\f[R] command.
The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R].
Values are output in the specified base.
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a register (see the \f[B]REGISTERS\f[R] section) that sets the
precision of any operations (with exceptions).
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] can be queried in dc(1)
programs with the \f[B]V\f[R] command.
.SS Comments
.PP
Comments go from \f[B]#\f[R] until, and not including, the next newline.
This is a \f[B]non-portable extension\f[R].
.SH NUMBERS
.PP
Numbers are strings made up of digits, uppercase letters up to
\f[B]F\f[R], and at most \f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]F\f[R] alone always equals decimal \f[B]15\f[R].
.SH COMMANDS
.PP
The valid commands are listed below.
.SS Printing
.PP
These commands are used for printing.
.TP
\f[B]p\f[R]
Prints the value on top of the stack, whether number or string, and
prints a newline after.
.RS
.PP
This does not alter the stack.
.RE
.TP
\f[B]n\f[R]
Prints the value on top of the stack, whether number or string, and pops
it off of the stack.
.TP
\f[B]P\f[R]
Pops a value off the stack.
.RS
.PP
If the value is a number, it is truncated and the absolute value of the
result is printed as though \f[B]obase\f[R] is \f[B]256\f[R] and each
digit is interpreted as an 8-bit ASCII character, making it a byte
stream.
.PP
If the value is a string, it is printed without a trailing newline.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]f\f[R]
Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
.RS
.PP
Users should use this command when they get lost.
.RE
.SS Arithmetic
.PP
These are the commands used for arithmetic.
.TP
\f[B]+\f[R]
The top two values are popped off the stack, added, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]-\f[R]
The top two values are popped off the stack, subtracted, and the result
is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]*\f[R]
The top two values are popped off the stack, multiplied, and the result
is pushed onto the stack.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The top two values are popped off the stack, divided, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]%\f[R]
The top two values are popped off the stack, remaindered, and the result
is pushed onto the stack.
.RS
.PP
Remaindering is equivalent to 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R], and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]\[ti]\f[R]
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 \f[B]x y / x y %\f[R] except that \f[B]x\f[R] and
\f[B]y\f[R] are only evaluated once.
.RS
.PP
The first value popped off of the stack must be non-zero.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
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.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
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.
.RE
.TP
\f[B]v\f[R]
The top value is popped off the stack, its square root is computed, and
the result is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The value popped off of the stack must be non-negative.
.RE
.TP
\f[B]_\f[R]
If this command \f[I]immediately\f[R] precedes a number (i.e., no spaces
or other commands), then that number is input as a negative number.
.RS
.PP
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 \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]b\f[R]
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.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]|\f[R]
The top three values are popped off the stack, a modular exponentiation
is computed, and the result is pushed onto the stack.
.RS
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]G\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]N\f[R]
The top value is popped off of the stack, and if it a \f[B]0\f[R], a
\f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B](\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]{\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than or equal to the second,
or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B])\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]}\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than or equal to the
second, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]M\f[R]
The top two values are popped off of the stack.
If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack.
If either of them is zero, or both of them are, then a \f[B]0\f[R] is
pushed onto the stack.
.RS
.PP
This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]m\f[R]
The top two values are popped off of the stack.
If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the
stack.
If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack.
.RS
.PP
This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Stack Control
.PP
These commands control the stack.
.TP
\f[B]c\f[R]
Removes all items from (\[lq]clears\[rq]) the stack.
.TP
\f[B]d\f[R]
Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes
the copy onto the stack.
.TP
\f[B]r\f[R]
Swaps (\[lq]reverses\[rq]) the two top items on the stack.
.TP
\f[B]R\f[R]
Pops (\[lq]removes\[rq]) the top value from the stack.
.SS Register Control
.PP
These commands control registers (see the \f[B]REGISTERS\f[R] section).
.TP
\f[B]s\f[R]\f[I]r\f[R]
Pops the value off the top of the stack and stores it into register
\f[I]r\f[R].
.TP
\f[B]l\f[R]\f[I]r\f[R]
Copies the value in register \f[I]r\f[R] and pushes it onto the stack.
This does not alter the contents of \f[I]r\f[R].
.TP
\f[B]S\f[R]\f[I]r\f[R]
Pops the value off the top of the (main) stack and pushes it onto the
stack of register \f[I]r\f[R].
The previous value of the register becomes inaccessible.
.TP
\f[B]L\f[R]\f[I]r\f[R]
Pops the value off the top of the stack for register \f[I]r\f[R] and
push it onto the main stack.
The previous value in the stack for register \f[I]r\f[R], if any, is now
accessible via the \f[B]l\f[R]\f[I]r\f[R] command.
.SS Parameters
.PP
These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R],
and \f[B]scale\f[R].
Also see the \f[B]SYNTAX\f[R] section.
.TP
\f[B]i\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R],
inclusive.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]o\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]obase\f[R], which must be between \f[B]2\f[R] and
\f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section).
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]k\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]scale\f[R], which must be non-negative.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]I\f[R]
Pushes the current value of \f[B]ibase\f[R] onto the main stack.
.TP
\f[B]O\f[R]
Pushes the current value of \f[B]obase\f[R] onto the main stack.
.TP
\f[B]K\f[R]
Pushes the current value of \f[B]scale\f[R] onto the main stack.
.TP
\f[B]T\f[R]
Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]U\f[R]
Pushes the maximum allowable value of \f[B]obase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]V\f[R]
Pushes the maximum allowable value of \f[B]scale\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Strings
.PP
The following commands control strings.
.PP
dc(1) can work with both numbers and strings, and registers (see the
\f[B]REGISTERS\f[R] section) can hold both strings and numbers.
dc(1) always knows whether the contents of a register are a string or a
number.
.PP
While arithmetic operations have to have numbers, and will print an
error if given a string, other commands accept strings.
.PP
Strings can also be executed as macros.
For example, if the string \f[B][1pR]\f[R] is executed as a macro, then
the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be
printed with a newline after and then popped from the stack.
.TP
\f[B][\f[R]\f[I]characters\f[R]\f[B]]\f[R]
Makes a string containing \f[I]characters\f[R] and pushes it onto the
stack.
.RS
.PP
If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then
they must be balanced.
Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R])
character.
.PP
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.
.RE
.TP
\f[B]a\f[R]
The value on top of the stack is popped.
.RS
.PP
If it is a number, it is truncated and its absolute value is taken.
The result mod \f[B]256\f[R] is calculated.
If that result is \f[B]0\f[R], push an empty string; otherwise, push a
one-character string where the character is the result of the mod
interpreted as an ASCII character.
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]x\f[R]
Pops a value off of the top of the stack.
.RS
.PP
If it is a number, it is pushed back onto the stack.
.PP
If it is a string, it is executed as a macro.
.PP
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
For example, \f[B]0 1>a\f[R] will execute the contents of register
\f[B]a\f[R], and \f[B]1 0>a\f[R] will not.
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]
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
\f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]?\f[R]
Reads a line from the \f[B]stdin\f[R] and executes it.
This is to allow macros to request input from users.
.TP
\f[B]q\f[R]
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
\f[B]Q\f[R]
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.
.TP
\f[B],\f[R]
Pushes the depth of the execution stack onto the stack.
The execution stack is the stack of string executions.
The number that is pushed onto the stack is exactly as many as is needed
to make dc(1) exit with the \f[B]Q\f[R] command, so the sequence
\f[B],Q\f[R] will make dc(1) exit.
.SS Status
.PP
These commands query status of the stack or its top value.
.TP
\f[B]Z\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, calculates the number of significant decimal digits
it has and pushes the result.
It will push \f[B]1\f[R] if the argument is \f[B]0\f[R] with no decimal
places.
.PP
If it is a string, pushes the number of characters the string has.
.RE
.TP
\f[B]X\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, pushes the \f[I]scale\f[R] of the value onto the
stack.
.PP
If it is a string, pushes \f[B]0\f[R].
.RE
.TP
\f[B]z\f[R]
Pushes the current depth of the stack (before execution of this command)
onto the stack.
.TP
\f[B]y\f[R]\f[I]r\f[R]
Pushes the current stack depth of the register \f[I]r\f[R] onto the main
stack.
.RS
.PP
Because each register has a depth of \f[B]1\f[R] (with the value
\f[B]0\f[R] in the top item) when dc(1) starts, dc(1) requires that each
register\[cq]s stack must always have at least one item; dc(1) will give
an error and reset otherwise (see the \f[B]RESET\f[R] section).
This means that this command will never push \f[B]0\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Arrays
.PP
These commands manipulate arrays.
.TP
\f[B]:\f[R]\f[I]r\f[R]
Pops the top two values off of the stack.
The second value will be stored in the array \f[I]r\f[R] (see the
\f[B]REGISTERS\f[R] section), indexed by the first value.
.TP
\f[B];\f[R]\f[I]r\f[R]
Pops the value on top of the stack and uses it as an index into the
array \f[I]r\f[R].
The selected value is then pushed onto the stack.
.TP
\f[B]Y\f[R]\f[I]r\f[R]
Pushes the length of the array \f[I]r\f[R] onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
+.SS Global Settings
+.PP
+These commands retrieve global settings.
+These are the only commands that require multiple specific characters,
+and all of them begin with the letter \f[B]g\f[R].
+Only the characters below are allowed after the character \f[B]g\f[R];
+any other character produces a parse error (see the \f[B]ERRORS\f[R]
+section).
+.TP
+\f[B]gl\f[R]
+Pushes the line length set by \f[B]DC_LINE_LENGTH\f[R] (see the
+\f[B]ENVIRONMENT VARIABLES\f[R] section) onto the stack.
+.TP
+\f[B]gz\f[R]
+Pushes \f[B]0\f[R] onto the stack if the leading zero setting has not
+been enabled with the \f[B]-z\f[R] or \f[B]--leading-zeroes\f[R] options
+(see the \f[B]OPTIONS\f[R] section), non-zero otherwise.
.SH REGISTERS
.PP
Registers are names that can store strings, numbers, and arrays.
(Number/string registers do not interfere with array registers.)
.PP
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 (\f[B]0\f[R]) in
their stack, and it is a runtime error to attempt to pop that item off
of the register stack.
.PP
In non-extended register mode, a register name is just the single
character that follows any command that needs a register name.
The only exceptions are: a newline (\f[B]`\[rs]n'\f[R]) and a left
bracket (\f[B]`['\f[R]); it is a parse error for a newline or a left
bracket to be used as a register name.
.SS Extended Register Mode
.PP
Unlike most other dc(1) implentations, this dc(1) provides nearly
unlimited amounts of registers, if extended register mode is enabled.
.PP
If extended register mode is enabled (\f[B]-x\f[R] or
\f[B]--extended-register\f[R] command-line arguments are given), then
normal single character registers are used \f[I]unless\f[R] the
character immediately following a command that needs a register name is
a space (according to \f[B]isspace()\f[R]) and not a newline
(\f[B]`\[rs]n'\f[R]).
.PP
In that case, the register name is found according to the regex
\f[B][a-z][a-z0-9_]*\f[R] (like bc(1) identifiers), and it is a parse
error if the next non-space characters do not match that regex.
.SH RESET
.PP
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.
.PP
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 macros returned) is skipped.
.PP
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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.SH PERFORMANCE
.PP
Most dc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This dc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]DC_BASE_DIGS\f[R].
.PP
In addition, this dc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]DC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on dc(1):
.TP
\f[B]DC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] 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 \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]DC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]DC_BASE_DIGS\f[R].
.TP
\f[B]DC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]DC_BASE_POW\f[R].
.TP
\f[B]DC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]DC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]DC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
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
.PP
dc(1) recognizes the following environment variables:
.TP
\f[B]DC_ENV_ARGS\f[R]
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
\f[B]DC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 \f[B]-e\f[R] option to set
\f[B]scale\f[R] to a value other than \f[B]0\f[R].
.RS
.PP
The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`dc' file.dc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]DC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]DC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length,
including the backslash newline combo.
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]DC_SIGINT_RESET\f[R]
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because dc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes dc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then dc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use
TTY mode, and zero makes dc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a
prompt, and zero or a non-integer makes dc(1) not use a prompt.
If this environment variable does not exist and \f[B]DC_TTY_MODE\f[R]
does, then the value of the \f[B]DC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]DC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
dc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], taking the square root of a
negative number, attempting to convert a negative number to a hardware
integer, overflow when converting a number to a hardware integer,
overflow when calculating the size of a number, and attempting to use a
non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]) operator.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, and using a
token where it is invalid.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors (including attempting to execute
a number), and attempting an operation when the stack has too few
elements.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
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.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, dc(1)
always exits and returns \f[B]4\f[R], no matter what mode dc(1) is in.
.PP
The other statuses will only be returned when dc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
dc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, dc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
dc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]DC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, dc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]DC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, dc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]DC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then dc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]DC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Command-Line History
.PP
Command-line history is only enabled if TTY mode is, i.e., that
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to
a TTY and the \f[B]DC_TTY_MODE\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section) and its default do not disable
TTY mode.
See the \f[B]COMMAND LINE HISTORY\f[R] section for more information.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]DC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]DC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]DC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]DC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause dc(1) to do one of two things.
.PP
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, dc(1) will exit.
.PP
However, if dc(1) is in interactive mode, and the
\f[B]DC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then dc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If dc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If dc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] 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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause dc(1) to clean up and
exit, and it uses the default handler for all other signals.
The one exception is \f[B]SIGHUP\f[R]; in that case, and only when dc(1)
is in TTY mode (see the \f[B]TTY MODE\f[R] section), a \f[B]SIGHUP\f[R]
will cause dc(1) to clean up and exit.
.SH COMMAND LINE HISTORY
.PP
dc(1) supports interactive command-line editing.
.PP
If dc(1) can be in TTY mode (see the \f[B]TTY MODE\f[R] section),
history can be enabled.
This means that command-line history can only be enabled when
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY.
.PP
Like TTY mode itself, it can be turned on or off with the environment
variable \f[B]DC_TTY_MODE\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
\f[B]Note\f[R]: tabs are converted to 8 spaces.
.SH LOCALES
.PP
This dc(1) ships with support for adding error messages for different
locales and thus, supports \f[B]LC_MESSAGES\f[R].
.SH SEE ALSO
.PP
bc(1)
.SH STANDARDS
.PP
The dc(1) utility operators are compliant with the operators in the
bc(1) IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHOR
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/dc/E.1.md b/manuals/dc/E.1.md
index 9e14d20f76b2..6a2c465e5642 100644
--- a/manuals/dc/E.1.md
+++ b/manuals/dc/E.1.md
@@ -1,1177 +1,1217 @@
# Name
dc - arbitrary-precision decimal reverse-Polish notation calculator
# SYNOPSIS
**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# 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.
If no files are given on the command-line, then dc(1) reads from **stdin** (see
the **STDIN** section). Otherwise, those files are processed, and dc(1) will
then exit.
If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
this dc(1) will always start with a **scale** of **10**.
# OPTIONS
The following are the options that dc(1) accepts.
**-h**, **-\-help**
: Prints a usage message and quits.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in dc(1). Most of those users
would want to put this option in **DC_ENV_ARGS**.
These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of dc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **?** command is used.
These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-x** **-\-extended-register**
: Enables extended register mode. See the *Extended Register Mode* subsection
of the **REGISTERS** section for more information.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files are given on the command-line and no files or expressions are given
by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
read from **stdin**.
However, there is a caveat to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
a string has been finished, but not ended. This means that, except for escaped
brackets, all brackets must be balanced before dc(1) parses and executes.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **dc >&-**, it will quit with an error. This
is done so that dc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This
is done so that dc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
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.
**ibase** is a register (see the **REGISTERS** section) that determines how to
interpret constant numbers. It is the "input" base, or the number base used for
interpreting input numbers. **ibase** is initially **10**. The max allowable
value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
The max allowable value for **ibase** can be queried in dc(1) programs with the
**T** command.
**obase** is a register (see the **REGISTERS** section) that determines how to
output results. It is the "output" base, or the number base used for outputting
numbers. **obase** is initially **10**. The max allowable value for **obase** is
**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
value for **obase** is **2**. Values are output in the specified base.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a register (see the
**REGISTERS** section) that sets the precision of any operations (with
exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
allowable value for **scale** can be queried in dc(1) programs with the **V**
command.
## Comments
Comments go from **#** until, and not including, the next newline. This is a
**non-portable extension**.
# NUMBERS
Numbers are strings made up of digits, uppercase letters up to **F**, and at
most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
current value of **ibase**, they are set to the value of the highest valid digit
in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **F** alone always equals decimal
**15**.
# COMMANDS
The valid commands are listed below.
## Printing
These commands are used for printing.
**p**
: Prints the value on top of the stack, whether number or string, and prints a
newline after.
This does not alter the stack.
**n**
: Prints the value on top of the stack, whether number or string, and pops it
off of the stack.
**P**
: Pops a value off the stack.
If the value is a number, it is truncated and the absolute value of the
result is printed as though **obase** is **256** and each digit is
interpreted as an 8-bit ASCII character, making it a byte stream.
If the value is a string, it is printed without a trailing newline.
This is a **non-portable extension**.
**f**
: Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
Users should use this command when they get lost.
## Arithmetic
These are the commands used for arithmetic.
**+**
: The top two values are popped off the stack, added, and the result is pushed
onto the stack. The *scale* of the result is equal to the max *scale* of
both operands.
**-**
: The top two values are popped off the stack, subtracted, and the result is
pushed onto the stack. The *scale* of the result is equal to the max
*scale* of both operands.
**\***
: The top two values are popped off the stack, multiplied, and the result is
pushed onto the stack. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result
is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The top two values are popped off the stack, divided, and the result is
pushed onto the stack. The *scale* of the result is equal to **scale**.
The first value popped off of the stack must be non-zero.
**%**
: The top two values are popped off the stack, remaindered, and the result is
pushed onto the stack.
Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The first value popped off of the stack must be non-zero.
**~**
: 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 **x y / x y %** except that **x** and **y** are only
evaluated once.
The first value popped off of the stack must be non-zero.
This is a **non-portable extension**.
**\^**
: 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. The *scale* of
the result is equal to **scale**.
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.
**v**
: The top value is popped off the stack, its square root is computed, and the
result is pushed onto the stack. The *scale* of the result is equal to
**scale**.
The value popped off of the stack must be non-negative.
**\_**
: If this command *immediately* precedes a number (i.e., no spaces or other
commands), then that number is input as a negative number.
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
**non-portable extension**.
**b**
: 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.
This is a **non-portable extension**.
**|**
: The top three values are popped off the stack, a modular exponentiation is
computed, and the result is pushed onto the stack.
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.
This is a **non-portable extension**.
**G**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if they are equal, or **0** otherwise.
This is a **non-portable extension**.
**N**
: The top value is popped off of the stack, and if it a **0**, a **1** is
pushed; otherwise, a **0** is pushed.
This is a **non-portable extension**.
**(**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than the second, or **0** otherwise.
This is a **non-portable extension**.
**{**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than or equal to the second, or **0**
otherwise.
This is a **non-portable extension**.
**)**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than the second, or **0** otherwise.
This is a **non-portable extension**.
**}**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than or equal to the second, or
**0** otherwise.
This is a **non-portable extension**.
**M**
: The top two values are popped off of the stack. If they are both non-zero, a
**1** is pushed onto the stack. If either of them is zero, or both of them
are, then a **0** is pushed onto the stack.
This is like the **&&** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
**m**
: The top two values are popped off of the stack. If at least one of them is
non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
**0** is pushed onto the stack.
This is like the **||** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
## Stack Control
These commands control the stack.
**c**
: Removes all items from ("clears") the stack.
**d**
: Copies the item on top of the stack ("duplicates") and pushes the copy onto
the stack.
**r**
: Swaps ("reverses") the two top items on the stack.
**R**
: Pops ("removes") the top value from the stack.
## Register Control
These commands control registers (see the **REGISTERS** section).
**s**_r_
: Pops the value off the top of the stack and stores it into register *r*.
**l**_r_
: Copies the value in register *r* and pushes it onto the stack. This does not
alter the contents of *r*.
**S**_r_
: Pops the value off the top of the (main) stack and pushes it onto the stack
of register *r*. The previous value of the register becomes inaccessible.
**L**_r_
: Pops the value off the top of the stack for register *r* and push it onto
the main stack. The previous value in the stack for register *r*, if any, is
now accessible via the **l**_r_ command.
## Parameters
These commands control the values of **ibase**, **obase**, and **scale**. Also
see the **SYNTAX** section.
**i**
: Pops the value off of the top of the stack and uses it to set **ibase**,
which must be between **2** and **16**, inclusive.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**o**
: Pops the value off of the top of the stack and uses it to set **obase**,
which must be between **2** and **DC_BASE_MAX**, inclusive (see the
**LIMITS** section).
If the value on top of the stack has any *scale*, the *scale* is ignored.
**k**
: Pops the value off of the top of the stack and uses it to set **scale**,
which must be non-negative.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**I**
: Pushes the current value of **ibase** onto the main stack.
**O**
: Pushes the current value of **obase** onto the main stack.
**K**
: Pushes the current value of **scale** onto the main stack.
**T**
: Pushes the maximum allowable value of **ibase** onto the main stack.
This is a **non-portable extension**.
**U**
: Pushes the maximum allowable value of **obase** onto the main stack.
This is a **non-portable extension**.
**V**
: Pushes the maximum allowable value of **scale** onto the main stack.
This is a **non-portable extension**.
## Strings
The following commands control strings.
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.
While arithmetic operations have to have numbers, and will print an error if
given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string **[1pR]** is
executed as a macro, then the code **1pR** is executed, meaning that the **1**
will be printed with a newline after and then popped from the stack.
**\[**_characters_**\]**
: Makes a string containing *characters* and pushes it onto the stack.
If there are brackets (**\[** and **\]**) in the string, then they must be
balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
character.
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.
**a**
: The value on top of the stack is popped.
If it is a number, it is truncated and its absolute value is taken. The
result mod **256** is calculated. If that result is **0**, push an empty
string; otherwise, push a one-character string where the character is the
result of the mod interpreted as an ASCII character.
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.
This is a **non-portable extension**.
**x**
: Pops a value off of the top of the stack.
If it is a number, it is pushed back onto the stack.
If it is a string, it is executed as a macro.
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
**\>**_r_
: 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
*r* are executed.
For example, **0 1>a** will execute the contents of register **a**, and
**1 0>a** will not.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\>**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**\<**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\<**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**=**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!=**_r_
: 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
*r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**?**
: Reads a line from the **stdin** and executes it. This is to allow macros to
request input from users.
**q**
: 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.
**Q**
: 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.
**,**
: Pushes the depth of the execution stack onto the stack. The execution stack
is the stack of string executions. The number that is pushed onto the stack
is exactly as many as is needed to make dc(1) exit with the **Q** command,
so the sequence **,Q** will make dc(1) exit.
## Status
These commands query status of the stack or its top value.
**Z**
: Pops a value off of the stack.
If it is a number, calculates the number of significant decimal digits it
has and pushes the result. It will push **1** if the argument is **0** with
no decimal places.
If it is a string, pushes the number of characters the string has.
**X**
: Pops a value off of the stack.
If it is a number, pushes the *scale* of the value onto the stack.
If it is a string, pushes **0**.
**z**
: Pushes the current depth of the stack (before execution of this command)
onto the stack.
**y**_r_
: Pushes the current stack depth of the register *r* onto the main stack.
Because each register has a depth of **1** (with the value **0** in the top
item) when dc(1) starts, dc(1) requires that each register's stack must
always have at least one item; dc(1) will give an error and reset otherwise
(see the **RESET** section). This means that this command will never push
**0**.
This is a **non-portable extension**.
## Arrays
These commands manipulate arrays.
**:**_r_
: Pops the top two values off of the stack. The second value will be stored in
the array *r* (see the **REGISTERS** section), indexed by the first value.
**;**_r_
: Pops the value on top of the stack and uses it as an index into the array
*r*. The selected value is then pushed onto the stack.
**Y**_r_
: Pushes the length of the array *r* onto the stack.
This is a **non-portable extension**.
+## Global Settings
+
+These commands retrieve global settings. These are the only commands that
+require multiple specific characters, and all of them begin with the letter
+**g**. Only the characters below are allowed after the character **g**; any
+other character produces a parse error (see the **ERRORS** section).
+
+**gl**
+
+: Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT
+ VARIABLES** section) onto the stack.
+
+**gz**
+
+: Pushes **0** onto the stack if the leading zero setting has not been enabled
+ with the **-z** or **-\-leading-zeroes** options (see the **OPTIONS**
+ section), non-zero otherwise.
+
# REGISTERS
Registers are names that can store strings, numbers, and arrays. (Number/string
registers do not interfere with array registers.)
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
(**0**) in their stack, and it is a runtime error to attempt to pop that item
off of the register stack.
In non-extended register mode, a register name is just the single character that
follows any command that needs a register name. The only exceptions are: a
newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
newline or a left bracket to be used as a register name.
## Extended Register Mode
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
amounts of registers, if extended register mode is enabled.
If extended register mode is enabled (**-x** or **-\-extended-register**
command-line arguments are given), then normal single character registers are
used *unless* the character immediately following a command that needs a
register name is a space (according to **isspace()**) and not a newline
(**'\\n'**).
In that case, the register name is found according to the regex
**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
the next non-space characters do not match that regex.
# 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.
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
macros returned) is skipped.
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.
# PERFORMANCE
Most dc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This dc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**DC_BASE_DIGS**.
In addition, this dc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **DC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on dc(1):
**DC_LONG_BIT**
: The number of bits in the **long** 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).
**DC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **DC_LONG_BIT**.
**DC_BASE_POW**
: The max decimal number that each large integer can store (see
**DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
**DC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **DC_LONG_BIT**.
**DC_BASE_MAX**
: The maximum output base. Set at **DC_BASE_POW**.
**DC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**DC_SCALE_MAX**
: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
**DC_STRING_MAX**
: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
**DC_NAME_MAX**
: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
**DC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**DC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
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.
# ENVIRONMENT VARIABLES
dc(1) recognizes the following environment variables:
**DC_ENV_ARGS**
: 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 **DC_ENV_ARGS** 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 **-e** option to set **scale** to a value other than **0**.
The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
**"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'dc' file.dc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **DC_ENV_ARGS** 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.
**DC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
lines to that length, including the backslash newline combo. The default
line length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**DC_SIGINT_RESET**
: If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because dc(1) exits on
**SIGINT** when not in interactive mode.
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1) reset
on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
environment variable exists and is *not* an integer, then dc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use TTY
mode, and zero makes dc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a prompt,
and zero or a non-integer makes dc(1) not use a prompt. If this environment
variable does not exist and **DC_TTY_MODE** does, then the value of the
**DC_TTY_MODE** environment variable is used.
This environment variable and the **DC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
dc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, taking the square root of a negative
number, attempting to convert a negative number to a hardware integer,
overflow when converting a number to a hardware integer, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**) operator.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, and using a token where it is
invalid.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors (including
attempting to execute a number), and attempting an operation when the stack
has too few elements.
**4**
: A fatal error occurred.
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.
The exit status **4** is special; when a fatal error occurs, dc(1) always exits
and returns **4**, no matter what mode dc(1) is in.
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
**-i** flag or **-\-interactive** option.
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 **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **DC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **DC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
mode on.
If the environment variable **DC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
**stdout**, and **stderr** are connected to a TTY and the **DC_TTY_MODE**
environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
information.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **DC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause dc(1) to do one of two things.
If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, dc(1) will
exit.
However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
default is an integer and non-zero, then dc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If dc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If dc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** 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.
**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is **SIGHUP**; in that
case, and only when dc(1) is in TTY mode (see the **TTY MODE** section), a
**SIGHUP** will cause dc(1) to clean up and exit.
# COMMAND LINE HISTORY
dc(1) supports interactive command-line editing.
If dc(1) can be in TTY mode (see the **TTY MODE** section), history can be
enabled. This means that command-line history can only be enabled when
**stdin**, **stdout**, and **stderr** are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment variable
**DC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
**Note**: tabs are converted to 8 spaces.
# LOCALES
This dc(1) ships with support for adding error messages for different locales
and thus, supports **LC_MESSAGES**.
# SEE ALSO
bc(1)
# STANDARDS
The dc(1) utility operators are compliant with the operators in the bc(1)
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHOR
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/manuals/dc/EH.1 b/manuals/dc/EH.1
index 050074bca762..4506001dfe55 100644
--- a/manuals/dc/EH.1
+++ b/manuals/dc/EH.1
@@ -1,1271 +1,1316 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "DC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH Name
.PP
dc - arbitrary-precision decimal reverse-Polish notation calculator
.SH SYNOPSIS
.PP
\f[B]dc\f[R] [\f[B]-hiPRvVx\f[R]] [\f[B]--version\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]]
[\f[B]--no-read-prompt\f[R]] [\f[B]--extended-register\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
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.
.PP
If no files are given on the command-line, then dc(1) reads from
\f[B]stdin\f[R] (see the \f[B]STDIN\f[R] section).
Otherwise, those files are processed, and dc(1) will then exit.
.PP
If a user wants to set up a standard environment, they can use
\f[B]DC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
For example, if a user wants the \f[B]scale\f[R] always set to
\f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R],
and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R].
.SH OPTIONS
.PP
The following are the options that dc(1) accepts.
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]DC_ENV_ARGS\f[R].
.RS
.PP
These options override the \f[B]DC_PROMPT\f[R] and \f[B]DC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of dc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]?\f[R] command is used.
.PP
These options \f[I]do\f[R] override the \f[B]DC_PROMPT\f[R] and
\f[B]DC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-x\f[R] \f[B]--extended-register\f[R]
Enables extended register mode.
See the \f[I]Extended Register Mode\f[R] subsection of the
\f[B]REGISTERS\f[R] section for more information.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]DC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files are given on the command-line and no files or expressions
are given by the \f[B]-f\f[R], \f[B]--file\f[R], \f[B]-e\f[R], or
\f[B]--expression\f[R] options, then dc(1) read from \f[B]stdin\f[R].
.PP
However, there is a caveat to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if a string has been finished, but not
ended.
This means that, except for escaped brackets, all brackets must be
balanced before dc(1) parses and executes.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]dc >&-\f[R], it will quit with an error.
This is done so that dc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]dc 2>&-\f[R], it will quit with an error.
This is done so that dc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
Each item in the input source code, either a number (see the
\f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R]
section), is processed and executed, in order.
Input is processed immediately when entered.
.PP
\f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to interpret constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in dc(1)
programs with the \f[B]T\f[R] command.
.PP
\f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and
can be queried with the \f[B]U\f[R] command.
The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R].
Values are output in the specified base.
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a register (see the \f[B]REGISTERS\f[R] section) that sets the
precision of any operations (with exceptions).
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] can be queried in dc(1)
programs with the \f[B]V\f[R] command.
.SS Comments
.PP
Comments go from \f[B]#\f[R] until, and not including, the next newline.
This is a \f[B]non-portable extension\f[R].
.SH NUMBERS
.PP
Numbers are strings made up of digits, uppercase letters up to
\f[B]F\f[R], and at most \f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]F\f[R] alone always equals decimal \f[B]15\f[R].
.SH COMMANDS
.PP
The valid commands are listed below.
.SS Printing
.PP
These commands are used for printing.
.TP
\f[B]p\f[R]
Prints the value on top of the stack, whether number or string, and
prints a newline after.
.RS
.PP
This does not alter the stack.
.RE
.TP
\f[B]n\f[R]
Prints the value on top of the stack, whether number or string, and pops
it off of the stack.
.TP
\f[B]P\f[R]
Pops a value off the stack.
.RS
.PP
If the value is a number, it is truncated and the absolute value of the
result is printed as though \f[B]obase\f[R] is \f[B]256\f[R] and each
digit is interpreted as an 8-bit ASCII character, making it a byte
stream.
.PP
If the value is a string, it is printed without a trailing newline.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]f\f[R]
Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
.RS
.PP
Users should use this command when they get lost.
.RE
.SS Arithmetic
.PP
These are the commands used for arithmetic.
.TP
\f[B]+\f[R]
The top two values are popped off the stack, added, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]-\f[R]
The top two values are popped off the stack, subtracted, and the result
is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]*\f[R]
The top two values are popped off the stack, multiplied, and the result
is pushed onto the stack.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The top two values are popped off the stack, divided, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]%\f[R]
The top two values are popped off the stack, remaindered, and the result
is pushed onto the stack.
.RS
.PP
Remaindering is equivalent to 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R], and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]\[ti]\f[R]
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 \f[B]x y / x y %\f[R] except that \f[B]x\f[R] and
\f[B]y\f[R] are only evaluated once.
.RS
.PP
The first value popped off of the stack must be non-zero.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
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.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
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.
.RE
.TP
\f[B]v\f[R]
The top value is popped off the stack, its square root is computed, and
the result is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The value popped off of the stack must be non-negative.
.RE
.TP
\f[B]_\f[R]
If this command \f[I]immediately\f[R] precedes a number (i.e., no spaces
or other commands), then that number is input as a negative number.
.RS
.PP
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 \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]b\f[R]
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.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]|\f[R]
The top three values are popped off the stack, a modular exponentiation
is computed, and the result is pushed onto the stack.
.RS
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]G\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]N\f[R]
The top value is popped off of the stack, and if it a \f[B]0\f[R], a
\f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B](\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]{\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than or equal to the second,
or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B])\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]}\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than or equal to the
second, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]M\f[R]
The top two values are popped off of the stack.
If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack.
If either of them is zero, or both of them are, then a \f[B]0\f[R] is
pushed onto the stack.
.RS
.PP
This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]m\f[R]
The top two values are popped off of the stack.
If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the
stack.
If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack.
.RS
.PP
This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Stack Control
.PP
These commands control the stack.
.TP
\f[B]c\f[R]
Removes all items from (\[lq]clears\[rq]) the stack.
.TP
\f[B]d\f[R]
Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes
the copy onto the stack.
.TP
\f[B]r\f[R]
Swaps (\[lq]reverses\[rq]) the two top items on the stack.
.TP
\f[B]R\f[R]
Pops (\[lq]removes\[rq]) the top value from the stack.
.SS Register Control
.PP
These commands control registers (see the \f[B]REGISTERS\f[R] section).
.TP
\f[B]s\f[R]\f[I]r\f[R]
Pops the value off the top of the stack and stores it into register
\f[I]r\f[R].
.TP
\f[B]l\f[R]\f[I]r\f[R]
Copies the value in register \f[I]r\f[R] and pushes it onto the stack.
This does not alter the contents of \f[I]r\f[R].
.TP
\f[B]S\f[R]\f[I]r\f[R]
Pops the value off the top of the (main) stack and pushes it onto the
stack of register \f[I]r\f[R].
The previous value of the register becomes inaccessible.
.TP
\f[B]L\f[R]\f[I]r\f[R]
Pops the value off the top of the stack for register \f[I]r\f[R] and
push it onto the main stack.
The previous value in the stack for register \f[I]r\f[R], if any, is now
accessible via the \f[B]l\f[R]\f[I]r\f[R] command.
.SS Parameters
.PP
These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R],
and \f[B]scale\f[R].
Also see the \f[B]SYNTAX\f[R] section.
.TP
\f[B]i\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R],
inclusive.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]o\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]obase\f[R], which must be between \f[B]2\f[R] and
\f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section).
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]k\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]scale\f[R], which must be non-negative.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]I\f[R]
Pushes the current value of \f[B]ibase\f[R] onto the main stack.
.TP
\f[B]O\f[R]
Pushes the current value of \f[B]obase\f[R] onto the main stack.
.TP
\f[B]K\f[R]
Pushes the current value of \f[B]scale\f[R] onto the main stack.
.TP
\f[B]T\f[R]
Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]U\f[R]
Pushes the maximum allowable value of \f[B]obase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]V\f[R]
Pushes the maximum allowable value of \f[B]scale\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Strings
.PP
The following commands control strings.
.PP
dc(1) can work with both numbers and strings, and registers (see the
\f[B]REGISTERS\f[R] section) can hold both strings and numbers.
dc(1) always knows whether the contents of a register are a string or a
number.
.PP
While arithmetic operations have to have numbers, and will print an
error if given a string, other commands accept strings.
.PP
Strings can also be executed as macros.
For example, if the string \f[B][1pR]\f[R] is executed as a macro, then
the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be
printed with a newline after and then popped from the stack.
.TP
\f[B][\f[R]\f[I]characters\f[R]\f[B]]\f[R]
Makes a string containing \f[I]characters\f[R] and pushes it onto the
stack.
.RS
.PP
If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then
they must be balanced.
Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R])
character.
.PP
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.
.RE
.TP
\f[B]a\f[R]
The value on top of the stack is popped.
.RS
.PP
If it is a number, it is truncated and its absolute value is taken.
The result mod \f[B]256\f[R] is calculated.
If that result is \f[B]0\f[R], push an empty string; otherwise, push a
one-character string where the character is the result of the mod
interpreted as an ASCII character.
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]x\f[R]
Pops a value off of the top of the stack.
.RS
.PP
If it is a number, it is pushed back onto the stack.
.PP
If it is a string, it is executed as a macro.
.PP
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
For example, \f[B]0 1>a\f[R] will execute the contents of register
\f[B]a\f[R], and \f[B]1 0>a\f[R] will not.
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]
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
\f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]?\f[R]
Reads a line from the \f[B]stdin\f[R] and executes it.
This is to allow macros to request input from users.
.TP
\f[B]q\f[R]
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
\f[B]Q\f[R]
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.
.TP
\f[B],\f[R]
Pushes the depth of the execution stack onto the stack.
The execution stack is the stack of string executions.
The number that is pushed onto the stack is exactly as many as is needed
to make dc(1) exit with the \f[B]Q\f[R] command, so the sequence
\f[B],Q\f[R] will make dc(1) exit.
.SS Status
.PP
These commands query status of the stack or its top value.
.TP
\f[B]Z\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, calculates the number of significant decimal digits
it has and pushes the result.
It will push \f[B]1\f[R] if the argument is \f[B]0\f[R] with no decimal
places.
.PP
If it is a string, pushes the number of characters the string has.
.RE
.TP
\f[B]X\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, pushes the \f[I]scale\f[R] of the value onto the
stack.
.PP
If it is a string, pushes \f[B]0\f[R].
.RE
.TP
\f[B]z\f[R]
Pushes the current depth of the stack (before execution of this command)
onto the stack.
.TP
\f[B]y\f[R]\f[I]r\f[R]
Pushes the current stack depth of the register \f[I]r\f[R] onto the main
stack.
.RS
.PP
Because each register has a depth of \f[B]1\f[R] (with the value
\f[B]0\f[R] in the top item) when dc(1) starts, dc(1) requires that each
register\[cq]s stack must always have at least one item; dc(1) will give
an error and reset otherwise (see the \f[B]RESET\f[R] section).
This means that this command will never push \f[B]0\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Arrays
.PP
These commands manipulate arrays.
.TP
\f[B]:\f[R]\f[I]r\f[R]
Pops the top two values off of the stack.
The second value will be stored in the array \f[I]r\f[R] (see the
\f[B]REGISTERS\f[R] section), indexed by the first value.
.TP
\f[B];\f[R]\f[I]r\f[R]
Pops the value on top of the stack and uses it as an index into the
array \f[I]r\f[R].
The selected value is then pushed onto the stack.
.TP
\f[B]Y\f[R]\f[I]r\f[R]
Pushes the length of the array \f[I]r\f[R] onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
+.SS Global Settings
+.PP
+These commands retrieve global settings.
+These are the only commands that require multiple specific characters,
+and all of them begin with the letter \f[B]g\f[R].
+Only the characters below are allowed after the character \f[B]g\f[R];
+any other character produces a parse error (see the \f[B]ERRORS\f[R]
+section).
+.TP
+\f[B]gl\f[R]
+Pushes the line length set by \f[B]DC_LINE_LENGTH\f[R] (see the
+\f[B]ENVIRONMENT VARIABLES\f[R] section) onto the stack.
+.TP
+\f[B]gz\f[R]
+Pushes \f[B]0\f[R] onto the stack if the leading zero setting has not
+been enabled with the \f[B]-z\f[R] or \f[B]--leading-zeroes\f[R] options
+(see the \f[B]OPTIONS\f[R] section), non-zero otherwise.
.SH REGISTERS
.PP
Registers are names that can store strings, numbers, and arrays.
(Number/string registers do not interfere with array registers.)
.PP
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 (\f[B]0\f[R]) in
their stack, and it is a runtime error to attempt to pop that item off
of the register stack.
.PP
In non-extended register mode, a register name is just the single
character that follows any command that needs a register name.
The only exceptions are: a newline (\f[B]`\[rs]n'\f[R]) and a left
bracket (\f[B]`['\f[R]); it is a parse error for a newline or a left
bracket to be used as a register name.
.SS Extended Register Mode
.PP
Unlike most other dc(1) implentations, this dc(1) provides nearly
unlimited amounts of registers, if extended register mode is enabled.
.PP
If extended register mode is enabled (\f[B]-x\f[R] or
\f[B]--extended-register\f[R] command-line arguments are given), then
normal single character registers are used \f[I]unless\f[R] the
character immediately following a command that needs a register name is
a space (according to \f[B]isspace()\f[R]) and not a newline
(\f[B]`\[rs]n'\f[R]).
.PP
In that case, the register name is found according to the regex
\f[B][a-z][a-z0-9_]*\f[R] (like bc(1) identifiers), and it is a parse
error if the next non-space characters do not match that regex.
.SH RESET
.PP
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.
.PP
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 macros returned) is skipped.
.PP
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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.SH PERFORMANCE
.PP
Most dc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This dc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]DC_BASE_DIGS\f[R].
.PP
In addition, this dc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]DC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on dc(1):
.TP
\f[B]DC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] 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 \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]DC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]DC_BASE_DIGS\f[R].
.TP
\f[B]DC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]DC_BASE_POW\f[R].
.TP
\f[B]DC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]DC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]DC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
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
.PP
dc(1) recognizes the following environment variables:
.TP
\f[B]DC_ENV_ARGS\f[R]
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
\f[B]DC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 \f[B]-e\f[R] option to set
\f[B]scale\f[R] to a value other than \f[B]0\f[R].
.RS
.PP
The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`dc' file.dc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]DC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]DC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length,
including the backslash newline combo.
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]DC_SIGINT_RESET\f[R]
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because dc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes dc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then dc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use
TTY mode, and zero makes dc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a
prompt, and zero or a non-integer makes dc(1) not use a prompt.
If this environment variable does not exist and \f[B]DC_TTY_MODE\f[R]
does, then the value of the \f[B]DC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]DC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
dc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], taking the square root of a
negative number, attempting to convert a negative number to a hardware
integer, overflow when converting a number to a hardware integer,
overflow when calculating the size of a number, and attempting to use a
non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]) operator.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, and using a
token where it is invalid.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors (including attempting to execute
a number), and attempting an operation when the stack has too few
elements.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
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.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, dc(1)
always exits and returns \f[B]4\f[R], no matter what mode dc(1) is in.
.PP
The other statuses will only be returned when dc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
dc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, dc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
dc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]DC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, dc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]DC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, dc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]DC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then dc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]DC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]DC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]DC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]DC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]DC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause dc(1) to do one of two things.
.PP
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, dc(1) will exit.
.PP
However, if dc(1) is in interactive mode, and the
\f[B]DC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then dc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If dc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If dc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] 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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause dc(1) to clean up and
exit, and it uses the default handler for all other signals.
.SH LOCALES
.PP
This dc(1) ships with support for adding error messages for different
locales and thus, supports \f[B]LC_MESSAGES\f[R].
.SH SEE ALSO
.PP
bc(1)
.SH STANDARDS
.PP
The dc(1) utility operators are compliant with the operators in the
bc(1) IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHOR
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/dc/EH.1.md b/manuals/dc/EH.1.md
index 1175c57ee85d..06ec59d4b3f7 100644
--- a/manuals/dc/EH.1.md
+++ b/manuals/dc/EH.1.md
@@ -1,1154 +1,1194 @@
# Name
dc - arbitrary-precision decimal reverse-Polish notation calculator
# SYNOPSIS
**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# 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.
If no files are given on the command-line, then dc(1) reads from **stdin** (see
the **STDIN** section). Otherwise, those files are processed, and dc(1) will
then exit.
If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
this dc(1) will always start with a **scale** of **10**.
# OPTIONS
The following are the options that dc(1) accepts.
**-h**, **-\-help**
: Prints a usage message and quits.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in dc(1). Most of those users
would want to put this option in **DC_ENV_ARGS**.
These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of dc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **?** command is used.
These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-x** **-\-extended-register**
: Enables extended register mode. See the *Extended Register Mode* subsection
of the **REGISTERS** section for more information.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files are given on the command-line and no files or expressions are given
by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
read from **stdin**.
However, there is a caveat to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
a string has been finished, but not ended. This means that, except for escaped
brackets, all brackets must be balanced before dc(1) parses and executes.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **dc >&-**, it will quit with an error. This
is done so that dc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This
is done so that dc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
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.
**ibase** is a register (see the **REGISTERS** section) that determines how to
interpret constant numbers. It is the "input" base, or the number base used for
interpreting input numbers. **ibase** is initially **10**. The max allowable
value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
The max allowable value for **ibase** can be queried in dc(1) programs with the
**T** command.
**obase** is a register (see the **REGISTERS** section) that determines how to
output results. It is the "output" base, or the number base used for outputting
numbers. **obase** is initially **10**. The max allowable value for **obase** is
**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
value for **obase** is **2**. Values are output in the specified base.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a register (see the
**REGISTERS** section) that sets the precision of any operations (with
exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
allowable value for **scale** can be queried in dc(1) programs with the **V**
command.
## Comments
Comments go from **#** until, and not including, the next newline. This is a
**non-portable extension**.
# NUMBERS
Numbers are strings made up of digits, uppercase letters up to **F**, and at
most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
current value of **ibase**, they are set to the value of the highest valid digit
in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **F** alone always equals decimal
**15**.
# COMMANDS
The valid commands are listed below.
## Printing
These commands are used for printing.
**p**
: Prints the value on top of the stack, whether number or string, and prints a
newline after.
This does not alter the stack.
**n**
: Prints the value on top of the stack, whether number or string, and pops it
off of the stack.
**P**
: Pops a value off the stack.
If the value is a number, it is truncated and the absolute value of the
result is printed as though **obase** is **256** and each digit is
interpreted as an 8-bit ASCII character, making it a byte stream.
If the value is a string, it is printed without a trailing newline.
This is a **non-portable extension**.
**f**
: Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
Users should use this command when they get lost.
## Arithmetic
These are the commands used for arithmetic.
**+**
: The top two values are popped off the stack, added, and the result is pushed
onto the stack. The *scale* of the result is equal to the max *scale* of
both operands.
**-**
: The top two values are popped off the stack, subtracted, and the result is
pushed onto the stack. The *scale* of the result is equal to the max
*scale* of both operands.
**\***
: The top two values are popped off the stack, multiplied, and the result is
pushed onto the stack. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result
is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The top two values are popped off the stack, divided, and the result is
pushed onto the stack. The *scale* of the result is equal to **scale**.
The first value popped off of the stack must be non-zero.
**%**
: The top two values are popped off the stack, remaindered, and the result is
pushed onto the stack.
Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The first value popped off of the stack must be non-zero.
**~**
: 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 **x y / x y %** except that **x** and **y** are only
evaluated once.
The first value popped off of the stack must be non-zero.
This is a **non-portable extension**.
**\^**
: 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. The *scale* of
the result is equal to **scale**.
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.
**v**
: The top value is popped off the stack, its square root is computed, and the
result is pushed onto the stack. The *scale* of the result is equal to
**scale**.
The value popped off of the stack must be non-negative.
**\_**
: If this command *immediately* precedes a number (i.e., no spaces or other
commands), then that number is input as a negative number.
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
**non-portable extension**.
**b**
: 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.
This is a **non-portable extension**.
**|**
: The top three values are popped off the stack, a modular exponentiation is
computed, and the result is pushed onto the stack.
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.
This is a **non-portable extension**.
**G**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if they are equal, or **0** otherwise.
This is a **non-portable extension**.
**N**
: The top value is popped off of the stack, and if it a **0**, a **1** is
pushed; otherwise, a **0** is pushed.
This is a **non-portable extension**.
**(**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than the second, or **0** otherwise.
This is a **non-portable extension**.
**{**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than or equal to the second, or **0**
otherwise.
This is a **non-portable extension**.
**)**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than the second, or **0** otherwise.
This is a **non-portable extension**.
**}**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than or equal to the second, or
**0** otherwise.
This is a **non-portable extension**.
**M**
: The top two values are popped off of the stack. If they are both non-zero, a
**1** is pushed onto the stack. If either of them is zero, or both of them
are, then a **0** is pushed onto the stack.
This is like the **&&** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
**m**
: The top two values are popped off of the stack. If at least one of them is
non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
**0** is pushed onto the stack.
This is like the **||** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
## Stack Control
These commands control the stack.
**c**
: Removes all items from ("clears") the stack.
**d**
: Copies the item on top of the stack ("duplicates") and pushes the copy onto
the stack.
**r**
: Swaps ("reverses") the two top items on the stack.
**R**
: Pops ("removes") the top value from the stack.
## Register Control
These commands control registers (see the **REGISTERS** section).
**s**_r_
: Pops the value off the top of the stack and stores it into register *r*.
**l**_r_
: Copies the value in register *r* and pushes it onto the stack. This does not
alter the contents of *r*.
**S**_r_
: Pops the value off the top of the (main) stack and pushes it onto the stack
of register *r*. The previous value of the register becomes inaccessible.
**L**_r_
: Pops the value off the top of the stack for register *r* and push it onto
the main stack. The previous value in the stack for register *r*, if any, is
now accessible via the **l**_r_ command.
## Parameters
These commands control the values of **ibase**, **obase**, and **scale**. Also
see the **SYNTAX** section.
**i**
: Pops the value off of the top of the stack and uses it to set **ibase**,
which must be between **2** and **16**, inclusive.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**o**
: Pops the value off of the top of the stack and uses it to set **obase**,
which must be between **2** and **DC_BASE_MAX**, inclusive (see the
**LIMITS** section).
If the value on top of the stack has any *scale*, the *scale* is ignored.
**k**
: Pops the value off of the top of the stack and uses it to set **scale**,
which must be non-negative.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**I**
: Pushes the current value of **ibase** onto the main stack.
**O**
: Pushes the current value of **obase** onto the main stack.
**K**
: Pushes the current value of **scale** onto the main stack.
**T**
: Pushes the maximum allowable value of **ibase** onto the main stack.
This is a **non-portable extension**.
**U**
: Pushes the maximum allowable value of **obase** onto the main stack.
This is a **non-portable extension**.
**V**
: Pushes the maximum allowable value of **scale** onto the main stack.
This is a **non-portable extension**.
## Strings
The following commands control strings.
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.
While arithmetic operations have to have numbers, and will print an error if
given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string **[1pR]** is
executed as a macro, then the code **1pR** is executed, meaning that the **1**
will be printed with a newline after and then popped from the stack.
**\[**_characters_**\]**
: Makes a string containing *characters* and pushes it onto the stack.
If there are brackets (**\[** and **\]**) in the string, then they must be
balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
character.
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.
**a**
: The value on top of the stack is popped.
If it is a number, it is truncated and its absolute value is taken. The
result mod **256** is calculated. If that result is **0**, push an empty
string; otherwise, push a one-character string where the character is the
result of the mod interpreted as an ASCII character.
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.
This is a **non-portable extension**.
**x**
: Pops a value off of the top of the stack.
If it is a number, it is pushed back onto the stack.
If it is a string, it is executed as a macro.
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
**\>**_r_
: 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
*r* are executed.
For example, **0 1>a** will execute the contents of register **a**, and
**1 0>a** will not.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\>**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**\<**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\<**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**=**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!=**_r_
: 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
*r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**?**
: Reads a line from the **stdin** and executes it. This is to allow macros to
request input from users.
**q**
: 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.
**Q**
: 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.
**,**
: Pushes the depth of the execution stack onto the stack. The execution stack
is the stack of string executions. The number that is pushed onto the stack
is exactly as many as is needed to make dc(1) exit with the **Q** command,
so the sequence **,Q** will make dc(1) exit.
## Status
These commands query status of the stack or its top value.
**Z**
: Pops a value off of the stack.
If it is a number, calculates the number of significant decimal digits it
has and pushes the result. It will push **1** if the argument is **0** with
no decimal places.
If it is a string, pushes the number of characters the string has.
**X**
: Pops a value off of the stack.
If it is a number, pushes the *scale* of the value onto the stack.
If it is a string, pushes **0**.
**z**
: Pushes the current depth of the stack (before execution of this command)
onto the stack.
**y**_r_
: Pushes the current stack depth of the register *r* onto the main stack.
Because each register has a depth of **1** (with the value **0** in the top
item) when dc(1) starts, dc(1) requires that each register's stack must
always have at least one item; dc(1) will give an error and reset otherwise
(see the **RESET** section). This means that this command will never push
**0**.
This is a **non-portable extension**.
## Arrays
These commands manipulate arrays.
**:**_r_
: Pops the top two values off of the stack. The second value will be stored in
the array *r* (see the **REGISTERS** section), indexed by the first value.
**;**_r_
: Pops the value on top of the stack and uses it as an index into the array
*r*. The selected value is then pushed onto the stack.
**Y**_r_
: Pushes the length of the array *r* onto the stack.
This is a **non-portable extension**.
+## Global Settings
+
+These commands retrieve global settings. These are the only commands that
+require multiple specific characters, and all of them begin with the letter
+**g**. Only the characters below are allowed after the character **g**; any
+other character produces a parse error (see the **ERRORS** section).
+
+**gl**
+
+: Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT
+ VARIABLES** section) onto the stack.
+
+**gz**
+
+: Pushes **0** onto the stack if the leading zero setting has not been enabled
+ with the **-z** or **-\-leading-zeroes** options (see the **OPTIONS**
+ section), non-zero otherwise.
+
# REGISTERS
Registers are names that can store strings, numbers, and arrays. (Number/string
registers do not interfere with array registers.)
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
(**0**) in their stack, and it is a runtime error to attempt to pop that item
off of the register stack.
In non-extended register mode, a register name is just the single character that
follows any command that needs a register name. The only exceptions are: a
newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
newline or a left bracket to be used as a register name.
## Extended Register Mode
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
amounts of registers, if extended register mode is enabled.
If extended register mode is enabled (**-x** or **-\-extended-register**
command-line arguments are given), then normal single character registers are
used *unless* the character immediately following a command that needs a
register name is a space (according to **isspace()**) and not a newline
(**'\\n'**).
In that case, the register name is found according to the regex
**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
the next non-space characters do not match that regex.
# 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.
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
macros returned) is skipped.
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.
# PERFORMANCE
Most dc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This dc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**DC_BASE_DIGS**.
In addition, this dc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **DC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on dc(1):
**DC_LONG_BIT**
: The number of bits in the **long** 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).
**DC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **DC_LONG_BIT**.
**DC_BASE_POW**
: The max decimal number that each large integer can store (see
**DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
**DC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **DC_LONG_BIT**.
**DC_BASE_MAX**
: The maximum output base. Set at **DC_BASE_POW**.
**DC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**DC_SCALE_MAX**
: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
**DC_STRING_MAX**
: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
**DC_NAME_MAX**
: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
**DC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**DC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
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.
# ENVIRONMENT VARIABLES
dc(1) recognizes the following environment variables:
**DC_ENV_ARGS**
: 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 **DC_ENV_ARGS** 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 **-e** option to set **scale** to a value other than **0**.
The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
**"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'dc' file.dc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **DC_ENV_ARGS** 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.
**DC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
lines to that length, including the backslash newline combo. The default
line length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**DC_SIGINT_RESET**
: If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because dc(1) exits on
**SIGINT** when not in interactive mode.
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1) reset
on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
environment variable exists and is *not* an integer, then dc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use TTY
mode, and zero makes dc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a prompt,
and zero or a non-integer makes dc(1) not use a prompt. If this environment
variable does not exist and **DC_TTY_MODE** does, then the value of the
**DC_TTY_MODE** environment variable is used.
This environment variable and the **DC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
dc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, taking the square root of a negative
number, attempting to convert a negative number to a hardware integer,
overflow when converting a number to a hardware integer, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**) operator.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, and using a token where it is
invalid.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors (including
attempting to execute a number), and attempting an operation when the stack
has too few elements.
**4**
: A fatal error occurred.
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.
The exit status **4** is special; when a fatal error occurs, dc(1) always exits
and returns **4**, no matter what mode dc(1) is in.
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
**-i** flag or **-\-interactive** option.
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 **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **DC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **DC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
mode on.
If the environment variable **DC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **DC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause dc(1) to do one of two things.
If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, dc(1) will
exit.
However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
default is an integer and non-zero, then dc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If dc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If dc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** 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.
**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
default handler for all other signals.
# LOCALES
This dc(1) ships with support for adding error messages for different locales
and thus, supports **LC_MESSAGES**.
# SEE ALSO
bc(1)
# STANDARDS
The dc(1) utility operators are compliant with the operators in the bc(1)
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHOR
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/manuals/dc/EHN.1 b/manuals/dc/EHN.1
index b552b611c3d7..1124d907bdd9 100644
--- a/manuals/dc/EHN.1
+++ b/manuals/dc/EHN.1
@@ -1,1267 +1,1312 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "DC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH Name
.PP
dc - arbitrary-precision decimal reverse-Polish notation calculator
.SH SYNOPSIS
.PP
\f[B]dc\f[R] [\f[B]-hiPRvVx\f[R]] [\f[B]--version\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]]
[\f[B]--no-read-prompt\f[R]] [\f[B]--extended-register\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
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.
.PP
If no files are given on the command-line, then dc(1) reads from
\f[B]stdin\f[R] (see the \f[B]STDIN\f[R] section).
Otherwise, those files are processed, and dc(1) will then exit.
.PP
If a user wants to set up a standard environment, they can use
\f[B]DC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
For example, if a user wants the \f[B]scale\f[R] always set to
\f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R],
and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R].
.SH OPTIONS
.PP
The following are the options that dc(1) accepts.
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]DC_ENV_ARGS\f[R].
.RS
.PP
These options override the \f[B]DC_PROMPT\f[R] and \f[B]DC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of dc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]?\f[R] command is used.
.PP
These options \f[I]do\f[R] override the \f[B]DC_PROMPT\f[R] and
\f[B]DC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-x\f[R] \f[B]--extended-register\f[R]
Enables extended register mode.
See the \f[I]Extended Register Mode\f[R] subsection of the
\f[B]REGISTERS\f[R] section for more information.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]DC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files are given on the command-line and no files or expressions
are given by the \f[B]-f\f[R], \f[B]--file\f[R], \f[B]-e\f[R], or
\f[B]--expression\f[R] options, then dc(1) read from \f[B]stdin\f[R].
.PP
However, there is a caveat to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if a string has been finished, but not
ended.
This means that, except for escaped brackets, all brackets must be
balanced before dc(1) parses and executes.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]dc >&-\f[R], it will quit with an error.
This is done so that dc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]dc 2>&-\f[R], it will quit with an error.
This is done so that dc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
Each item in the input source code, either a number (see the
\f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R]
section), is processed and executed, in order.
Input is processed immediately when entered.
.PP
\f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to interpret constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in dc(1)
programs with the \f[B]T\f[R] command.
.PP
\f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and
can be queried with the \f[B]U\f[R] command.
The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R].
Values are output in the specified base.
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a register (see the \f[B]REGISTERS\f[R] section) that sets the
precision of any operations (with exceptions).
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] can be queried in dc(1)
programs with the \f[B]V\f[R] command.
.SS Comments
.PP
Comments go from \f[B]#\f[R] until, and not including, the next newline.
This is a \f[B]non-portable extension\f[R].
.SH NUMBERS
.PP
Numbers are strings made up of digits, uppercase letters up to
\f[B]F\f[R], and at most \f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]F\f[R] alone always equals decimal \f[B]15\f[R].
.SH COMMANDS
.PP
The valid commands are listed below.
.SS Printing
.PP
These commands are used for printing.
.TP
\f[B]p\f[R]
Prints the value on top of the stack, whether number or string, and
prints a newline after.
.RS
.PP
This does not alter the stack.
.RE
.TP
\f[B]n\f[R]
Prints the value on top of the stack, whether number or string, and pops
it off of the stack.
.TP
\f[B]P\f[R]
Pops a value off the stack.
.RS
.PP
If the value is a number, it is truncated and the absolute value of the
result is printed as though \f[B]obase\f[R] is \f[B]256\f[R] and each
digit is interpreted as an 8-bit ASCII character, making it a byte
stream.
.PP
If the value is a string, it is printed without a trailing newline.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]f\f[R]
Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
.RS
.PP
Users should use this command when they get lost.
.RE
.SS Arithmetic
.PP
These are the commands used for arithmetic.
.TP
\f[B]+\f[R]
The top two values are popped off the stack, added, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]-\f[R]
The top two values are popped off the stack, subtracted, and the result
is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]*\f[R]
The top two values are popped off the stack, multiplied, and the result
is pushed onto the stack.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The top two values are popped off the stack, divided, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]%\f[R]
The top two values are popped off the stack, remaindered, and the result
is pushed onto the stack.
.RS
.PP
Remaindering is equivalent to 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R], and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]\[ti]\f[R]
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 \f[B]x y / x y %\f[R] except that \f[B]x\f[R] and
\f[B]y\f[R] are only evaluated once.
.RS
.PP
The first value popped off of the stack must be non-zero.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
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.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
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.
.RE
.TP
\f[B]v\f[R]
The top value is popped off the stack, its square root is computed, and
the result is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The value popped off of the stack must be non-negative.
.RE
.TP
\f[B]_\f[R]
If this command \f[I]immediately\f[R] precedes a number (i.e., no spaces
or other commands), then that number is input as a negative number.
.RS
.PP
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 \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]b\f[R]
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.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]|\f[R]
The top three values are popped off the stack, a modular exponentiation
is computed, and the result is pushed onto the stack.
.RS
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]G\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]N\f[R]
The top value is popped off of the stack, and if it a \f[B]0\f[R], a
\f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B](\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]{\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than or equal to the second,
or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B])\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]}\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than or equal to the
second, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]M\f[R]
The top two values are popped off of the stack.
If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack.
If either of them is zero, or both of them are, then a \f[B]0\f[R] is
pushed onto the stack.
.RS
.PP
This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]m\f[R]
The top two values are popped off of the stack.
If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the
stack.
If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack.
.RS
.PP
This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Stack Control
.PP
These commands control the stack.
.TP
\f[B]c\f[R]
Removes all items from (\[lq]clears\[rq]) the stack.
.TP
\f[B]d\f[R]
Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes
the copy onto the stack.
.TP
\f[B]r\f[R]
Swaps (\[lq]reverses\[rq]) the two top items on the stack.
.TP
\f[B]R\f[R]
Pops (\[lq]removes\[rq]) the top value from the stack.
.SS Register Control
.PP
These commands control registers (see the \f[B]REGISTERS\f[R] section).
.TP
\f[B]s\f[R]\f[I]r\f[R]
Pops the value off the top of the stack and stores it into register
\f[I]r\f[R].
.TP
\f[B]l\f[R]\f[I]r\f[R]
Copies the value in register \f[I]r\f[R] and pushes it onto the stack.
This does not alter the contents of \f[I]r\f[R].
.TP
\f[B]S\f[R]\f[I]r\f[R]
Pops the value off the top of the (main) stack and pushes it onto the
stack of register \f[I]r\f[R].
The previous value of the register becomes inaccessible.
.TP
\f[B]L\f[R]\f[I]r\f[R]
Pops the value off the top of the stack for register \f[I]r\f[R] and
push it onto the main stack.
The previous value in the stack for register \f[I]r\f[R], if any, is now
accessible via the \f[B]l\f[R]\f[I]r\f[R] command.
.SS Parameters
.PP
These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R],
and \f[B]scale\f[R].
Also see the \f[B]SYNTAX\f[R] section.
.TP
\f[B]i\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R],
inclusive.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]o\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]obase\f[R], which must be between \f[B]2\f[R] and
\f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section).
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]k\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]scale\f[R], which must be non-negative.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]I\f[R]
Pushes the current value of \f[B]ibase\f[R] onto the main stack.
.TP
\f[B]O\f[R]
Pushes the current value of \f[B]obase\f[R] onto the main stack.
.TP
\f[B]K\f[R]
Pushes the current value of \f[B]scale\f[R] onto the main stack.
.TP
\f[B]T\f[R]
Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]U\f[R]
Pushes the maximum allowable value of \f[B]obase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]V\f[R]
Pushes the maximum allowable value of \f[B]scale\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Strings
.PP
The following commands control strings.
.PP
dc(1) can work with both numbers and strings, and registers (see the
\f[B]REGISTERS\f[R] section) can hold both strings and numbers.
dc(1) always knows whether the contents of a register are a string or a
number.
.PP
While arithmetic operations have to have numbers, and will print an
error if given a string, other commands accept strings.
.PP
Strings can also be executed as macros.
For example, if the string \f[B][1pR]\f[R] is executed as a macro, then
the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be
printed with a newline after and then popped from the stack.
.TP
\f[B][\f[R]\f[I]characters\f[R]\f[B]]\f[R]
Makes a string containing \f[I]characters\f[R] and pushes it onto the
stack.
.RS
.PP
If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then
they must be balanced.
Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R])
character.
.PP
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.
.RE
.TP
\f[B]a\f[R]
The value on top of the stack is popped.
.RS
.PP
If it is a number, it is truncated and its absolute value is taken.
The result mod \f[B]256\f[R] is calculated.
If that result is \f[B]0\f[R], push an empty string; otherwise, push a
one-character string where the character is the result of the mod
interpreted as an ASCII character.
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]x\f[R]
Pops a value off of the top of the stack.
.RS
.PP
If it is a number, it is pushed back onto the stack.
.PP
If it is a string, it is executed as a macro.
.PP
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
For example, \f[B]0 1>a\f[R] will execute the contents of register
\f[B]a\f[R], and \f[B]1 0>a\f[R] will not.
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]
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
\f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]?\f[R]
Reads a line from the \f[B]stdin\f[R] and executes it.
This is to allow macros to request input from users.
.TP
\f[B]q\f[R]
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
\f[B]Q\f[R]
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.
.TP
\f[B],\f[R]
Pushes the depth of the execution stack onto the stack.
The execution stack is the stack of string executions.
The number that is pushed onto the stack is exactly as many as is needed
to make dc(1) exit with the \f[B]Q\f[R] command, so the sequence
\f[B],Q\f[R] will make dc(1) exit.
.SS Status
.PP
These commands query status of the stack or its top value.
.TP
\f[B]Z\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, calculates the number of significant decimal digits
it has and pushes the result.
It will push \f[B]1\f[R] if the argument is \f[B]0\f[R] with no decimal
places.
.PP
If it is a string, pushes the number of characters the string has.
.RE
.TP
\f[B]X\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, pushes the \f[I]scale\f[R] of the value onto the
stack.
.PP
If it is a string, pushes \f[B]0\f[R].
.RE
.TP
\f[B]z\f[R]
Pushes the current depth of the stack (before execution of this command)
onto the stack.
.TP
\f[B]y\f[R]\f[I]r\f[R]
Pushes the current stack depth of the register \f[I]r\f[R] onto the main
stack.
.RS
.PP
Because each register has a depth of \f[B]1\f[R] (with the value
\f[B]0\f[R] in the top item) when dc(1) starts, dc(1) requires that each
register\[cq]s stack must always have at least one item; dc(1) will give
an error and reset otherwise (see the \f[B]RESET\f[R] section).
This means that this command will never push \f[B]0\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Arrays
.PP
These commands manipulate arrays.
.TP
\f[B]:\f[R]\f[I]r\f[R]
Pops the top two values off of the stack.
The second value will be stored in the array \f[I]r\f[R] (see the
\f[B]REGISTERS\f[R] section), indexed by the first value.
.TP
\f[B];\f[R]\f[I]r\f[R]
Pops the value on top of the stack and uses it as an index into the
array \f[I]r\f[R].
The selected value is then pushed onto the stack.
.TP
\f[B]Y\f[R]\f[I]r\f[R]
Pushes the length of the array \f[I]r\f[R] onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
+.SS Global Settings
+.PP
+These commands retrieve global settings.
+These are the only commands that require multiple specific characters,
+and all of them begin with the letter \f[B]g\f[R].
+Only the characters below are allowed after the character \f[B]g\f[R];
+any other character produces a parse error (see the \f[B]ERRORS\f[R]
+section).
+.TP
+\f[B]gl\f[R]
+Pushes the line length set by \f[B]DC_LINE_LENGTH\f[R] (see the
+\f[B]ENVIRONMENT VARIABLES\f[R] section) onto the stack.
+.TP
+\f[B]gz\f[R]
+Pushes \f[B]0\f[R] onto the stack if the leading zero setting has not
+been enabled with the \f[B]-z\f[R] or \f[B]--leading-zeroes\f[R] options
+(see the \f[B]OPTIONS\f[R] section), non-zero otherwise.
.SH REGISTERS
.PP
Registers are names that can store strings, numbers, and arrays.
(Number/string registers do not interfere with array registers.)
.PP
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 (\f[B]0\f[R]) in
their stack, and it is a runtime error to attempt to pop that item off
of the register stack.
.PP
In non-extended register mode, a register name is just the single
character that follows any command that needs a register name.
The only exceptions are: a newline (\f[B]`\[rs]n'\f[R]) and a left
bracket (\f[B]`['\f[R]); it is a parse error for a newline or a left
bracket to be used as a register name.
.SS Extended Register Mode
.PP
Unlike most other dc(1) implentations, this dc(1) provides nearly
unlimited amounts of registers, if extended register mode is enabled.
.PP
If extended register mode is enabled (\f[B]-x\f[R] or
\f[B]--extended-register\f[R] command-line arguments are given), then
normal single character registers are used \f[I]unless\f[R] the
character immediately following a command that needs a register name is
a space (according to \f[B]isspace()\f[R]) and not a newline
(\f[B]`\[rs]n'\f[R]).
.PP
In that case, the register name is found according to the regex
\f[B][a-z][a-z0-9_]*\f[R] (like bc(1) identifiers), and it is a parse
error if the next non-space characters do not match that regex.
.SH RESET
.PP
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.
.PP
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 macros returned) is skipped.
.PP
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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.SH PERFORMANCE
.PP
Most dc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This dc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]DC_BASE_DIGS\f[R].
.PP
In addition, this dc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]DC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on dc(1):
.TP
\f[B]DC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] 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 \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]DC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]DC_BASE_DIGS\f[R].
.TP
\f[B]DC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]DC_BASE_POW\f[R].
.TP
\f[B]DC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]DC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]DC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
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
.PP
dc(1) recognizes the following environment variables:
.TP
\f[B]DC_ENV_ARGS\f[R]
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
\f[B]DC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 \f[B]-e\f[R] option to set
\f[B]scale\f[R] to a value other than \f[B]0\f[R].
.RS
.PP
The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`dc' file.dc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]DC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]DC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length,
including the backslash newline combo.
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]DC_SIGINT_RESET\f[R]
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because dc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes dc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then dc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use
TTY mode, and zero makes dc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a
prompt, and zero or a non-integer makes dc(1) not use a prompt.
If this environment variable does not exist and \f[B]DC_TTY_MODE\f[R]
does, then the value of the \f[B]DC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]DC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
dc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], taking the square root of a
negative number, attempting to convert a negative number to a hardware
integer, overflow when converting a number to a hardware integer,
overflow when calculating the size of a number, and attempting to use a
non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]) operator.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, and using a
token where it is invalid.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors (including attempting to execute
a number), and attempting an operation when the stack has too few
elements.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
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.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, dc(1)
always exits and returns \f[B]4\f[R], no matter what mode dc(1) is in.
.PP
The other statuses will only be returned when dc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
dc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, dc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
dc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]DC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, dc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]DC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, dc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]DC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then dc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]DC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]DC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]DC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]DC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]DC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause dc(1) to do one of two things.
.PP
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, dc(1) will exit.
.PP
However, if dc(1) is in interactive mode, and the
\f[B]DC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then dc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If dc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If dc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] 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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause dc(1) to clean up and
exit, and it uses the default handler for all other signals.
.SH SEE ALSO
.PP
bc(1)
.SH STANDARDS
.PP
The dc(1) utility operators are compliant with the operators in the
bc(1) IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHOR
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/dc/EHN.1.md b/manuals/dc/EHN.1.md
index b6aedde3e0d8..50cb37ef2586 100644
--- a/manuals/dc/EHN.1.md
+++ b/manuals/dc/EHN.1.md
@@ -1,1149 +1,1189 @@
# Name
dc - arbitrary-precision decimal reverse-Polish notation calculator
# SYNOPSIS
**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# 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.
If no files are given on the command-line, then dc(1) reads from **stdin** (see
the **STDIN** section). Otherwise, those files are processed, and dc(1) will
then exit.
If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
this dc(1) will always start with a **scale** of **10**.
# OPTIONS
The following are the options that dc(1) accepts.
**-h**, **-\-help**
: Prints a usage message and quits.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in dc(1). Most of those users
would want to put this option in **DC_ENV_ARGS**.
These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of dc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **?** command is used.
These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-x** **-\-extended-register**
: Enables extended register mode. See the *Extended Register Mode* subsection
of the **REGISTERS** section for more information.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files are given on the command-line and no files or expressions are given
by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
read from **stdin**.
However, there is a caveat to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
a string has been finished, but not ended. This means that, except for escaped
brackets, all brackets must be balanced before dc(1) parses and executes.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **dc >&-**, it will quit with an error. This
is done so that dc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This
is done so that dc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
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.
**ibase** is a register (see the **REGISTERS** section) that determines how to
interpret constant numbers. It is the "input" base, or the number base used for
interpreting input numbers. **ibase** is initially **10**. The max allowable
value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
The max allowable value for **ibase** can be queried in dc(1) programs with the
**T** command.
**obase** is a register (see the **REGISTERS** section) that determines how to
output results. It is the "output" base, or the number base used for outputting
numbers. **obase** is initially **10**. The max allowable value for **obase** is
**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
value for **obase** is **2**. Values are output in the specified base.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a register (see the
**REGISTERS** section) that sets the precision of any operations (with
exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
allowable value for **scale** can be queried in dc(1) programs with the **V**
command.
## Comments
Comments go from **#** until, and not including, the next newline. This is a
**non-portable extension**.
# NUMBERS
Numbers are strings made up of digits, uppercase letters up to **F**, and at
most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
current value of **ibase**, they are set to the value of the highest valid digit
in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **F** alone always equals decimal
**15**.
# COMMANDS
The valid commands are listed below.
## Printing
These commands are used for printing.
**p**
: Prints the value on top of the stack, whether number or string, and prints a
newline after.
This does not alter the stack.
**n**
: Prints the value on top of the stack, whether number or string, and pops it
off of the stack.
**P**
: Pops a value off the stack.
If the value is a number, it is truncated and the absolute value of the
result is printed as though **obase** is **256** and each digit is
interpreted as an 8-bit ASCII character, making it a byte stream.
If the value is a string, it is printed without a trailing newline.
This is a **non-portable extension**.
**f**
: Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
Users should use this command when they get lost.
## Arithmetic
These are the commands used for arithmetic.
**+**
: The top two values are popped off the stack, added, and the result is pushed
onto the stack. The *scale* of the result is equal to the max *scale* of
both operands.
**-**
: The top two values are popped off the stack, subtracted, and the result is
pushed onto the stack. The *scale* of the result is equal to the max
*scale* of both operands.
**\***
: The top two values are popped off the stack, multiplied, and the result is
pushed onto the stack. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result
is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The top two values are popped off the stack, divided, and the result is
pushed onto the stack. The *scale* of the result is equal to **scale**.
The first value popped off of the stack must be non-zero.
**%**
: The top two values are popped off the stack, remaindered, and the result is
pushed onto the stack.
Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The first value popped off of the stack must be non-zero.
**~**
: 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 **x y / x y %** except that **x** and **y** are only
evaluated once.
The first value popped off of the stack must be non-zero.
This is a **non-portable extension**.
**\^**
: 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. The *scale* of
the result is equal to **scale**.
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.
**v**
: The top value is popped off the stack, its square root is computed, and the
result is pushed onto the stack. The *scale* of the result is equal to
**scale**.
The value popped off of the stack must be non-negative.
**\_**
: If this command *immediately* precedes a number (i.e., no spaces or other
commands), then that number is input as a negative number.
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
**non-portable extension**.
**b**
: 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.
This is a **non-portable extension**.
**|**
: The top three values are popped off the stack, a modular exponentiation is
computed, and the result is pushed onto the stack.
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.
This is a **non-portable extension**.
**G**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if they are equal, or **0** otherwise.
This is a **non-portable extension**.
**N**
: The top value is popped off of the stack, and if it a **0**, a **1** is
pushed; otherwise, a **0** is pushed.
This is a **non-portable extension**.
**(**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than the second, or **0** otherwise.
This is a **non-portable extension**.
**{**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than or equal to the second, or **0**
otherwise.
This is a **non-portable extension**.
**)**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than the second, or **0** otherwise.
This is a **non-portable extension**.
**}**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than or equal to the second, or
**0** otherwise.
This is a **non-portable extension**.
**M**
: The top two values are popped off of the stack. If they are both non-zero, a
**1** is pushed onto the stack. If either of them is zero, or both of them
are, then a **0** is pushed onto the stack.
This is like the **&&** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
**m**
: The top two values are popped off of the stack. If at least one of them is
non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
**0** is pushed onto the stack.
This is like the **||** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
## Stack Control
These commands control the stack.
**c**
: Removes all items from ("clears") the stack.
**d**
: Copies the item on top of the stack ("duplicates") and pushes the copy onto
the stack.
**r**
: Swaps ("reverses") the two top items on the stack.
**R**
: Pops ("removes") the top value from the stack.
## Register Control
These commands control registers (see the **REGISTERS** section).
**s**_r_
: Pops the value off the top of the stack and stores it into register *r*.
**l**_r_
: Copies the value in register *r* and pushes it onto the stack. This does not
alter the contents of *r*.
**S**_r_
: Pops the value off the top of the (main) stack and pushes it onto the stack
of register *r*. The previous value of the register becomes inaccessible.
**L**_r_
: Pops the value off the top of the stack for register *r* and push it onto
the main stack. The previous value in the stack for register *r*, if any, is
now accessible via the **l**_r_ command.
## Parameters
These commands control the values of **ibase**, **obase**, and **scale**. Also
see the **SYNTAX** section.
**i**
: Pops the value off of the top of the stack and uses it to set **ibase**,
which must be between **2** and **16**, inclusive.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**o**
: Pops the value off of the top of the stack and uses it to set **obase**,
which must be between **2** and **DC_BASE_MAX**, inclusive (see the
**LIMITS** section).
If the value on top of the stack has any *scale*, the *scale* is ignored.
**k**
: Pops the value off of the top of the stack and uses it to set **scale**,
which must be non-negative.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**I**
: Pushes the current value of **ibase** onto the main stack.
**O**
: Pushes the current value of **obase** onto the main stack.
**K**
: Pushes the current value of **scale** onto the main stack.
**T**
: Pushes the maximum allowable value of **ibase** onto the main stack.
This is a **non-portable extension**.
**U**
: Pushes the maximum allowable value of **obase** onto the main stack.
This is a **non-portable extension**.
**V**
: Pushes the maximum allowable value of **scale** onto the main stack.
This is a **non-portable extension**.
## Strings
The following commands control strings.
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.
While arithmetic operations have to have numbers, and will print an error if
given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string **[1pR]** is
executed as a macro, then the code **1pR** is executed, meaning that the **1**
will be printed with a newline after and then popped from the stack.
**\[**_characters_**\]**
: Makes a string containing *characters* and pushes it onto the stack.
If there are brackets (**\[** and **\]**) in the string, then they must be
balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
character.
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.
**a**
: The value on top of the stack is popped.
If it is a number, it is truncated and its absolute value is taken. The
result mod **256** is calculated. If that result is **0**, push an empty
string; otherwise, push a one-character string where the character is the
result of the mod interpreted as an ASCII character.
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.
This is a **non-portable extension**.
**x**
: Pops a value off of the top of the stack.
If it is a number, it is pushed back onto the stack.
If it is a string, it is executed as a macro.
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
**\>**_r_
: 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
*r* are executed.
For example, **0 1>a** will execute the contents of register **a**, and
**1 0>a** will not.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\>**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**\<**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\<**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**=**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!=**_r_
: 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
*r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**?**
: Reads a line from the **stdin** and executes it. This is to allow macros to
request input from users.
**q**
: 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.
**Q**
: 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.
**,**
: Pushes the depth of the execution stack onto the stack. The execution stack
is the stack of string executions. The number that is pushed onto the stack
is exactly as many as is needed to make dc(1) exit with the **Q** command,
so the sequence **,Q** will make dc(1) exit.
## Status
These commands query status of the stack or its top value.
**Z**
: Pops a value off of the stack.
If it is a number, calculates the number of significant decimal digits it
has and pushes the result. It will push **1** if the argument is **0** with
no decimal places.
If it is a string, pushes the number of characters the string has.
**X**
: Pops a value off of the stack.
If it is a number, pushes the *scale* of the value onto the stack.
If it is a string, pushes **0**.
**z**
: Pushes the current depth of the stack (before execution of this command)
onto the stack.
**y**_r_
: Pushes the current stack depth of the register *r* onto the main stack.
Because each register has a depth of **1** (with the value **0** in the top
item) when dc(1) starts, dc(1) requires that each register's stack must
always have at least one item; dc(1) will give an error and reset otherwise
(see the **RESET** section). This means that this command will never push
**0**.
This is a **non-portable extension**.
## Arrays
These commands manipulate arrays.
**:**_r_
: Pops the top two values off of the stack. The second value will be stored in
the array *r* (see the **REGISTERS** section), indexed by the first value.
**;**_r_
: Pops the value on top of the stack and uses it as an index into the array
*r*. The selected value is then pushed onto the stack.
**Y**_r_
: Pushes the length of the array *r* onto the stack.
This is a **non-portable extension**.
+## Global Settings
+
+These commands retrieve global settings. These are the only commands that
+require multiple specific characters, and all of them begin with the letter
+**g**. Only the characters below are allowed after the character **g**; any
+other character produces a parse error (see the **ERRORS** section).
+
+**gl**
+
+: Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT
+ VARIABLES** section) onto the stack.
+
+**gz**
+
+: Pushes **0** onto the stack if the leading zero setting has not been enabled
+ with the **-z** or **-\-leading-zeroes** options (see the **OPTIONS**
+ section), non-zero otherwise.
+
# REGISTERS
Registers are names that can store strings, numbers, and arrays. (Number/string
registers do not interfere with array registers.)
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
(**0**) in their stack, and it is a runtime error to attempt to pop that item
off of the register stack.
In non-extended register mode, a register name is just the single character that
follows any command that needs a register name. The only exceptions are: a
newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
newline or a left bracket to be used as a register name.
## Extended Register Mode
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
amounts of registers, if extended register mode is enabled.
If extended register mode is enabled (**-x** or **-\-extended-register**
command-line arguments are given), then normal single character registers are
used *unless* the character immediately following a command that needs a
register name is a space (according to **isspace()**) and not a newline
(**'\\n'**).
In that case, the register name is found according to the regex
**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
the next non-space characters do not match that regex.
# 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.
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
macros returned) is skipped.
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.
# PERFORMANCE
Most dc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This dc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**DC_BASE_DIGS**.
In addition, this dc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **DC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on dc(1):
**DC_LONG_BIT**
: The number of bits in the **long** 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).
**DC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **DC_LONG_BIT**.
**DC_BASE_POW**
: The max decimal number that each large integer can store (see
**DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
**DC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **DC_LONG_BIT**.
**DC_BASE_MAX**
: The maximum output base. Set at **DC_BASE_POW**.
**DC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**DC_SCALE_MAX**
: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
**DC_STRING_MAX**
: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
**DC_NAME_MAX**
: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
**DC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**DC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
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.
# ENVIRONMENT VARIABLES
dc(1) recognizes the following environment variables:
**DC_ENV_ARGS**
: 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 **DC_ENV_ARGS** 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 **-e** option to set **scale** to a value other than **0**.
The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
**"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'dc' file.dc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **DC_ENV_ARGS** 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.
**DC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
lines to that length, including the backslash newline combo. The default
line length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**DC_SIGINT_RESET**
: If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because dc(1) exits on
**SIGINT** when not in interactive mode.
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1) reset
on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
environment variable exists and is *not* an integer, then dc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use TTY
mode, and zero makes dc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a prompt,
and zero or a non-integer makes dc(1) not use a prompt. If this environment
variable does not exist and **DC_TTY_MODE** does, then the value of the
**DC_TTY_MODE** environment variable is used.
This environment variable and the **DC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
dc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, taking the square root of a negative
number, attempting to convert a negative number to a hardware integer,
overflow when converting a number to a hardware integer, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**) operator.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, and using a token where it is
invalid.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors (including
attempting to execute a number), and attempting an operation when the stack
has too few elements.
**4**
: A fatal error occurred.
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.
The exit status **4** is special; when a fatal error occurs, dc(1) always exits
and returns **4**, no matter what mode dc(1) is in.
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
**-i** flag or **-\-interactive** option.
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 **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **DC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **DC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
mode on.
If the environment variable **DC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **DC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause dc(1) to do one of two things.
If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, dc(1) will
exit.
However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
default is an integer and non-zero, then dc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If dc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If dc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** 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.
**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
default handler for all other signals.
# SEE ALSO
bc(1)
# STANDARDS
The dc(1) utility operators are compliant with the operators in the bc(1)
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHOR
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/manuals/dc/EN.1 b/manuals/dc/EN.1
index d1de8e208f32..beae0e46a9b6 100644
--- a/manuals/dc/EN.1
+++ b/manuals/dc/EN.1
@@ -1,1293 +1,1338 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "DC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH Name
.PP
dc - arbitrary-precision decimal reverse-Polish notation calculator
.SH SYNOPSIS
.PP
\f[B]dc\f[R] [\f[B]-hiPRvVx\f[R]] [\f[B]--version\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]]
[\f[B]--no-read-prompt\f[R]] [\f[B]--extended-register\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
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.
.PP
If no files are given on the command-line, then dc(1) reads from
\f[B]stdin\f[R] (see the \f[B]STDIN\f[R] section).
Otherwise, those files are processed, and dc(1) will then exit.
.PP
If a user wants to set up a standard environment, they can use
\f[B]DC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
For example, if a user wants the \f[B]scale\f[R] always set to
\f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R],
and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R].
.SH OPTIONS
.PP
The following are the options that dc(1) accepts.
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]DC_ENV_ARGS\f[R].
.RS
.PP
These options override the \f[B]DC_PROMPT\f[R] and \f[B]DC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of dc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]?\f[R] command is used.
.PP
These options \f[I]do\f[R] override the \f[B]DC_PROMPT\f[R] and
\f[B]DC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-x\f[R] \f[B]--extended-register\f[R]
Enables extended register mode.
See the \f[I]Extended Register Mode\f[R] subsection of the
\f[B]REGISTERS\f[R] section for more information.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]DC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files are given on the command-line and no files or expressions
are given by the \f[B]-f\f[R], \f[B]--file\f[R], \f[B]-e\f[R], or
\f[B]--expression\f[R] options, then dc(1) read from \f[B]stdin\f[R].
.PP
However, there is a caveat to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if a string has been finished, but not
ended.
This means that, except for escaped brackets, all brackets must be
balanced before dc(1) parses and executes.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]dc >&-\f[R], it will quit with an error.
This is done so that dc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]dc 2>&-\f[R], it will quit with an error.
This is done so that dc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
Each item in the input source code, either a number (see the
\f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R]
section), is processed and executed, in order.
Input is processed immediately when entered.
.PP
\f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to interpret constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in dc(1)
programs with the \f[B]T\f[R] command.
.PP
\f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and
can be queried with the \f[B]U\f[R] command.
The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R].
Values are output in the specified base.
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a register (see the \f[B]REGISTERS\f[R] section) that sets the
precision of any operations (with exceptions).
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] can be queried in dc(1)
programs with the \f[B]V\f[R] command.
.SS Comments
.PP
Comments go from \f[B]#\f[R] until, and not including, the next newline.
This is a \f[B]non-portable extension\f[R].
.SH NUMBERS
.PP
Numbers are strings made up of digits, uppercase letters up to
\f[B]F\f[R], and at most \f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]F\f[R] alone always equals decimal \f[B]15\f[R].
.SH COMMANDS
.PP
The valid commands are listed below.
.SS Printing
.PP
These commands are used for printing.
.TP
\f[B]p\f[R]
Prints the value on top of the stack, whether number or string, and
prints a newline after.
.RS
.PP
This does not alter the stack.
.RE
.TP
\f[B]n\f[R]
Prints the value on top of the stack, whether number or string, and pops
it off of the stack.
.TP
\f[B]P\f[R]
Pops a value off the stack.
.RS
.PP
If the value is a number, it is truncated and the absolute value of the
result is printed as though \f[B]obase\f[R] is \f[B]256\f[R] and each
digit is interpreted as an 8-bit ASCII character, making it a byte
stream.
.PP
If the value is a string, it is printed without a trailing newline.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]f\f[R]
Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
.RS
.PP
Users should use this command when they get lost.
.RE
.SS Arithmetic
.PP
These are the commands used for arithmetic.
.TP
\f[B]+\f[R]
The top two values are popped off the stack, added, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]-\f[R]
The top two values are popped off the stack, subtracted, and the result
is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]*\f[R]
The top two values are popped off the stack, multiplied, and the result
is pushed onto the stack.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The top two values are popped off the stack, divided, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]%\f[R]
The top two values are popped off the stack, remaindered, and the result
is pushed onto the stack.
.RS
.PP
Remaindering is equivalent to 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R], and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]\[ti]\f[R]
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 \f[B]x y / x y %\f[R] except that \f[B]x\f[R] and
\f[B]y\f[R] are only evaluated once.
.RS
.PP
The first value popped off of the stack must be non-zero.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
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.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
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.
.RE
.TP
\f[B]v\f[R]
The top value is popped off the stack, its square root is computed, and
the result is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The value popped off of the stack must be non-negative.
.RE
.TP
\f[B]_\f[R]
If this command \f[I]immediately\f[R] precedes a number (i.e., no spaces
or other commands), then that number is input as a negative number.
.RS
.PP
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 \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]b\f[R]
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.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]|\f[R]
The top three values are popped off the stack, a modular exponentiation
is computed, and the result is pushed onto the stack.
.RS
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]G\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]N\f[R]
The top value is popped off of the stack, and if it a \f[B]0\f[R], a
\f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B](\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]{\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than or equal to the second,
or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B])\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]}\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than or equal to the
second, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]M\f[R]
The top two values are popped off of the stack.
If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack.
If either of them is zero, or both of them are, then a \f[B]0\f[R] is
pushed onto the stack.
.RS
.PP
This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]m\f[R]
The top two values are popped off of the stack.
If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the
stack.
If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack.
.RS
.PP
This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Stack Control
.PP
These commands control the stack.
.TP
\f[B]c\f[R]
Removes all items from (\[lq]clears\[rq]) the stack.
.TP
\f[B]d\f[R]
Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes
the copy onto the stack.
.TP
\f[B]r\f[R]
Swaps (\[lq]reverses\[rq]) the two top items on the stack.
.TP
\f[B]R\f[R]
Pops (\[lq]removes\[rq]) the top value from the stack.
.SS Register Control
.PP
These commands control registers (see the \f[B]REGISTERS\f[R] section).
.TP
\f[B]s\f[R]\f[I]r\f[R]
Pops the value off the top of the stack and stores it into register
\f[I]r\f[R].
.TP
\f[B]l\f[R]\f[I]r\f[R]
Copies the value in register \f[I]r\f[R] and pushes it onto the stack.
This does not alter the contents of \f[I]r\f[R].
.TP
\f[B]S\f[R]\f[I]r\f[R]
Pops the value off the top of the (main) stack and pushes it onto the
stack of register \f[I]r\f[R].
The previous value of the register becomes inaccessible.
.TP
\f[B]L\f[R]\f[I]r\f[R]
Pops the value off the top of the stack for register \f[I]r\f[R] and
push it onto the main stack.
The previous value in the stack for register \f[I]r\f[R], if any, is now
accessible via the \f[B]l\f[R]\f[I]r\f[R] command.
.SS Parameters
.PP
These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R],
and \f[B]scale\f[R].
Also see the \f[B]SYNTAX\f[R] section.
.TP
\f[B]i\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R],
inclusive.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]o\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]obase\f[R], which must be between \f[B]2\f[R] and
\f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section).
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]k\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]scale\f[R], which must be non-negative.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]I\f[R]
Pushes the current value of \f[B]ibase\f[R] onto the main stack.
.TP
\f[B]O\f[R]
Pushes the current value of \f[B]obase\f[R] onto the main stack.
.TP
\f[B]K\f[R]
Pushes the current value of \f[B]scale\f[R] onto the main stack.
.TP
\f[B]T\f[R]
Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]U\f[R]
Pushes the maximum allowable value of \f[B]obase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]V\f[R]
Pushes the maximum allowable value of \f[B]scale\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Strings
.PP
The following commands control strings.
.PP
dc(1) can work with both numbers and strings, and registers (see the
\f[B]REGISTERS\f[R] section) can hold both strings and numbers.
dc(1) always knows whether the contents of a register are a string or a
number.
.PP
While arithmetic operations have to have numbers, and will print an
error if given a string, other commands accept strings.
.PP
Strings can also be executed as macros.
For example, if the string \f[B][1pR]\f[R] is executed as a macro, then
the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be
printed with a newline after and then popped from the stack.
.TP
\f[B][\f[R]\f[I]characters\f[R]\f[B]]\f[R]
Makes a string containing \f[I]characters\f[R] and pushes it onto the
stack.
.RS
.PP
If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then
they must be balanced.
Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R])
character.
.PP
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.
.RE
.TP
\f[B]a\f[R]
The value on top of the stack is popped.
.RS
.PP
If it is a number, it is truncated and its absolute value is taken.
The result mod \f[B]256\f[R] is calculated.
If that result is \f[B]0\f[R], push an empty string; otherwise, push a
one-character string where the character is the result of the mod
interpreted as an ASCII character.
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]x\f[R]
Pops a value off of the top of the stack.
.RS
.PP
If it is a number, it is pushed back onto the stack.
.PP
If it is a string, it is executed as a macro.
.PP
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
For example, \f[B]0 1>a\f[R] will execute the contents of register
\f[B]a\f[R], and \f[B]1 0>a\f[R] will not.
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]
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
\f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]?\f[R]
Reads a line from the \f[B]stdin\f[R] and executes it.
This is to allow macros to request input from users.
.TP
\f[B]q\f[R]
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
\f[B]Q\f[R]
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.
.TP
\f[B],\f[R]
Pushes the depth of the execution stack onto the stack.
The execution stack is the stack of string executions.
The number that is pushed onto the stack is exactly as many as is needed
to make dc(1) exit with the \f[B]Q\f[R] command, so the sequence
\f[B],Q\f[R] will make dc(1) exit.
.SS Status
.PP
These commands query status of the stack or its top value.
.TP
\f[B]Z\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, calculates the number of significant decimal digits
it has and pushes the result.
It will push \f[B]1\f[R] if the argument is \f[B]0\f[R] with no decimal
places.
.PP
If it is a string, pushes the number of characters the string has.
.RE
.TP
\f[B]X\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, pushes the \f[I]scale\f[R] of the value onto the
stack.
.PP
If it is a string, pushes \f[B]0\f[R].
.RE
.TP
\f[B]z\f[R]
Pushes the current depth of the stack (before execution of this command)
onto the stack.
.TP
\f[B]y\f[R]\f[I]r\f[R]
Pushes the current stack depth of the register \f[I]r\f[R] onto the main
stack.
.RS
.PP
Because each register has a depth of \f[B]1\f[R] (with the value
\f[B]0\f[R] in the top item) when dc(1) starts, dc(1) requires that each
register\[cq]s stack must always have at least one item; dc(1) will give
an error and reset otherwise (see the \f[B]RESET\f[R] section).
This means that this command will never push \f[B]0\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Arrays
.PP
These commands manipulate arrays.
.TP
\f[B]:\f[R]\f[I]r\f[R]
Pops the top two values off of the stack.
The second value will be stored in the array \f[I]r\f[R] (see the
\f[B]REGISTERS\f[R] section), indexed by the first value.
.TP
\f[B];\f[R]\f[I]r\f[R]
Pops the value on top of the stack and uses it as an index into the
array \f[I]r\f[R].
The selected value is then pushed onto the stack.
.TP
\f[B]Y\f[R]\f[I]r\f[R]
Pushes the length of the array \f[I]r\f[R] onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
+.SS Global Settings
+.PP
+These commands retrieve global settings.
+These are the only commands that require multiple specific characters,
+and all of them begin with the letter \f[B]g\f[R].
+Only the characters below are allowed after the character \f[B]g\f[R];
+any other character produces a parse error (see the \f[B]ERRORS\f[R]
+section).
+.TP
+\f[B]gl\f[R]
+Pushes the line length set by \f[B]DC_LINE_LENGTH\f[R] (see the
+\f[B]ENVIRONMENT VARIABLES\f[R] section) onto the stack.
+.TP
+\f[B]gz\f[R]
+Pushes \f[B]0\f[R] onto the stack if the leading zero setting has not
+been enabled with the \f[B]-z\f[R] or \f[B]--leading-zeroes\f[R] options
+(see the \f[B]OPTIONS\f[R] section), non-zero otherwise.
.SH REGISTERS
.PP
Registers are names that can store strings, numbers, and arrays.
(Number/string registers do not interfere with array registers.)
.PP
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 (\f[B]0\f[R]) in
their stack, and it is a runtime error to attempt to pop that item off
of the register stack.
.PP
In non-extended register mode, a register name is just the single
character that follows any command that needs a register name.
The only exceptions are: a newline (\f[B]`\[rs]n'\f[R]) and a left
bracket (\f[B]`['\f[R]); it is a parse error for a newline or a left
bracket to be used as a register name.
.SS Extended Register Mode
.PP
Unlike most other dc(1) implentations, this dc(1) provides nearly
unlimited amounts of registers, if extended register mode is enabled.
.PP
If extended register mode is enabled (\f[B]-x\f[R] or
\f[B]--extended-register\f[R] command-line arguments are given), then
normal single character registers are used \f[I]unless\f[R] the
character immediately following a command that needs a register name is
a space (according to \f[B]isspace()\f[R]) and not a newline
(\f[B]`\[rs]n'\f[R]).
.PP
In that case, the register name is found according to the regex
\f[B][a-z][a-z0-9_]*\f[R] (like bc(1) identifiers), and it is a parse
error if the next non-space characters do not match that regex.
.SH RESET
.PP
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.
.PP
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 macros returned) is skipped.
.PP
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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.SH PERFORMANCE
.PP
Most dc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This dc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]DC_BASE_DIGS\f[R].
.PP
In addition, this dc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]DC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on dc(1):
.TP
\f[B]DC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] 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 \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]DC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]DC_BASE_DIGS\f[R].
.TP
\f[B]DC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]DC_BASE_POW\f[R].
.TP
\f[B]DC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]DC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]DC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
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
.PP
dc(1) recognizes the following environment variables:
.TP
\f[B]DC_ENV_ARGS\f[R]
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
\f[B]DC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 \f[B]-e\f[R] option to set
\f[B]scale\f[R] to a value other than \f[B]0\f[R].
.RS
.PP
The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`dc' file.dc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]DC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]DC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length,
including the backslash newline combo.
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]DC_SIGINT_RESET\f[R]
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because dc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes dc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then dc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use
TTY mode, and zero makes dc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a
prompt, and zero or a non-integer makes dc(1) not use a prompt.
If this environment variable does not exist and \f[B]DC_TTY_MODE\f[R]
does, then the value of the \f[B]DC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]DC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
dc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], taking the square root of a
negative number, attempting to convert a negative number to a hardware
integer, overflow when converting a number to a hardware integer,
overflow when calculating the size of a number, and attempting to use a
non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]) operator.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, and using a
token where it is invalid.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors (including attempting to execute
a number), and attempting an operation when the stack has too few
elements.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
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.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, dc(1)
always exits and returns \f[B]4\f[R], no matter what mode dc(1) is in.
.PP
The other statuses will only be returned when dc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
dc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, dc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
dc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]DC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, dc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]DC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, dc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]DC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then dc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]DC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Command-Line History
.PP
Command-line history is only enabled if TTY mode is, i.e., that
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to
a TTY and the \f[B]DC_TTY_MODE\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section) and its default do not disable
TTY mode.
See the \f[B]COMMAND LINE HISTORY\f[R] section for more information.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]DC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]DC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]DC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]DC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause dc(1) to do one of two things.
.PP
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, dc(1) will exit.
.PP
However, if dc(1) is in interactive mode, and the
\f[B]DC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then dc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If dc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If dc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] 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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause dc(1) to clean up and
exit, and it uses the default handler for all other signals.
The one exception is \f[B]SIGHUP\f[R]; in that case, and only when dc(1)
is in TTY mode (see the \f[B]TTY MODE\f[R] section), a \f[B]SIGHUP\f[R]
will cause dc(1) to clean up and exit.
.SH COMMAND LINE HISTORY
.PP
dc(1) supports interactive command-line editing.
.PP
If dc(1) can be in TTY mode (see the \f[B]TTY MODE\f[R] section),
history can be enabled.
This means that command-line history can only be enabled when
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY.
.PP
Like TTY mode itself, it can be turned on or off with the environment
variable \f[B]DC_TTY_MODE\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
\f[B]Note\f[R]: tabs are converted to 8 spaces.
.SH SEE ALSO
.PP
bc(1)
.SH STANDARDS
.PP
The dc(1) utility operators are compliant with the operators in the
bc(1) IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHOR
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/dc/EN.1.md b/manuals/dc/EN.1.md
index 22983732721b..db6f27f34576 100644
--- a/manuals/dc/EN.1.md
+++ b/manuals/dc/EN.1.md
@@ -1,1172 +1,1212 @@
# Name
dc - arbitrary-precision decimal reverse-Polish notation calculator
# SYNOPSIS
**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# 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.
If no files are given on the command-line, then dc(1) reads from **stdin** (see
the **STDIN** section). Otherwise, those files are processed, and dc(1) will
then exit.
If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
this dc(1) will always start with a **scale** of **10**.
# OPTIONS
The following are the options that dc(1) accepts.
**-h**, **-\-help**
: Prints a usage message and quits.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in dc(1). Most of those users
would want to put this option in **DC_ENV_ARGS**.
These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of dc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **?** command is used.
These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-x** **-\-extended-register**
: Enables extended register mode. See the *Extended Register Mode* subsection
of the **REGISTERS** section for more information.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files are given on the command-line and no files or expressions are given
by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
read from **stdin**.
However, there is a caveat to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
a string has been finished, but not ended. This means that, except for escaped
brackets, all brackets must be balanced before dc(1) parses and executes.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **dc >&-**, it will quit with an error. This
is done so that dc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This
is done so that dc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
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.
**ibase** is a register (see the **REGISTERS** section) that determines how to
interpret constant numbers. It is the "input" base, or the number base used for
interpreting input numbers. **ibase** is initially **10**. The max allowable
value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
The max allowable value for **ibase** can be queried in dc(1) programs with the
**T** command.
**obase** is a register (see the **REGISTERS** section) that determines how to
output results. It is the "output" base, or the number base used for outputting
numbers. **obase** is initially **10**. The max allowable value for **obase** is
**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
value for **obase** is **2**. Values are output in the specified base.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a register (see the
**REGISTERS** section) that sets the precision of any operations (with
exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
allowable value for **scale** can be queried in dc(1) programs with the **V**
command.
## Comments
Comments go from **#** until, and not including, the next newline. This is a
**non-portable extension**.
# NUMBERS
Numbers are strings made up of digits, uppercase letters up to **F**, and at
most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
current value of **ibase**, they are set to the value of the highest valid digit
in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **F** alone always equals decimal
**15**.
# COMMANDS
The valid commands are listed below.
## Printing
These commands are used for printing.
**p**
: Prints the value on top of the stack, whether number or string, and prints a
newline after.
This does not alter the stack.
**n**
: Prints the value on top of the stack, whether number or string, and pops it
off of the stack.
**P**
: Pops a value off the stack.
If the value is a number, it is truncated and the absolute value of the
result is printed as though **obase** is **256** and each digit is
interpreted as an 8-bit ASCII character, making it a byte stream.
If the value is a string, it is printed without a trailing newline.
This is a **non-portable extension**.
**f**
: Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
Users should use this command when they get lost.
## Arithmetic
These are the commands used for arithmetic.
**+**
: The top two values are popped off the stack, added, and the result is pushed
onto the stack. The *scale* of the result is equal to the max *scale* of
both operands.
**-**
: The top two values are popped off the stack, subtracted, and the result is
pushed onto the stack. The *scale* of the result is equal to the max
*scale* of both operands.
**\***
: The top two values are popped off the stack, multiplied, and the result is
pushed onto the stack. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result
is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The top two values are popped off the stack, divided, and the result is
pushed onto the stack. The *scale* of the result is equal to **scale**.
The first value popped off of the stack must be non-zero.
**%**
: The top two values are popped off the stack, remaindered, and the result is
pushed onto the stack.
Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The first value popped off of the stack must be non-zero.
**~**
: 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 **x y / x y %** except that **x** and **y** are only
evaluated once.
The first value popped off of the stack must be non-zero.
This is a **non-portable extension**.
**\^**
: 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. The *scale* of
the result is equal to **scale**.
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.
**v**
: The top value is popped off the stack, its square root is computed, and the
result is pushed onto the stack. The *scale* of the result is equal to
**scale**.
The value popped off of the stack must be non-negative.
**\_**
: If this command *immediately* precedes a number (i.e., no spaces or other
commands), then that number is input as a negative number.
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
**non-portable extension**.
**b**
: 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.
This is a **non-portable extension**.
**|**
: The top three values are popped off the stack, a modular exponentiation is
computed, and the result is pushed onto the stack.
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.
This is a **non-portable extension**.
**G**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if they are equal, or **0** otherwise.
This is a **non-portable extension**.
**N**
: The top value is popped off of the stack, and if it a **0**, a **1** is
pushed; otherwise, a **0** is pushed.
This is a **non-portable extension**.
**(**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than the second, or **0** otherwise.
This is a **non-portable extension**.
**{**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than or equal to the second, or **0**
otherwise.
This is a **non-portable extension**.
**)**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than the second, or **0** otherwise.
This is a **non-portable extension**.
**}**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than or equal to the second, or
**0** otherwise.
This is a **non-portable extension**.
**M**
: The top two values are popped off of the stack. If they are both non-zero, a
**1** is pushed onto the stack. If either of them is zero, or both of them
are, then a **0** is pushed onto the stack.
This is like the **&&** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
**m**
: The top two values are popped off of the stack. If at least one of them is
non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
**0** is pushed onto the stack.
This is like the **||** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
## Stack Control
These commands control the stack.
**c**
: Removes all items from ("clears") the stack.
**d**
: Copies the item on top of the stack ("duplicates") and pushes the copy onto
the stack.
**r**
: Swaps ("reverses") the two top items on the stack.
**R**
: Pops ("removes") the top value from the stack.
## Register Control
These commands control registers (see the **REGISTERS** section).
**s**_r_
: Pops the value off the top of the stack and stores it into register *r*.
**l**_r_
: Copies the value in register *r* and pushes it onto the stack. This does not
alter the contents of *r*.
**S**_r_
: Pops the value off the top of the (main) stack and pushes it onto the stack
of register *r*. The previous value of the register becomes inaccessible.
**L**_r_
: Pops the value off the top of the stack for register *r* and push it onto
the main stack. The previous value in the stack for register *r*, if any, is
now accessible via the **l**_r_ command.
## Parameters
These commands control the values of **ibase**, **obase**, and **scale**. Also
see the **SYNTAX** section.
**i**
: Pops the value off of the top of the stack and uses it to set **ibase**,
which must be between **2** and **16**, inclusive.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**o**
: Pops the value off of the top of the stack and uses it to set **obase**,
which must be between **2** and **DC_BASE_MAX**, inclusive (see the
**LIMITS** section).
If the value on top of the stack has any *scale*, the *scale* is ignored.
**k**
: Pops the value off of the top of the stack and uses it to set **scale**,
which must be non-negative.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**I**
: Pushes the current value of **ibase** onto the main stack.
**O**
: Pushes the current value of **obase** onto the main stack.
**K**
: Pushes the current value of **scale** onto the main stack.
**T**
: Pushes the maximum allowable value of **ibase** onto the main stack.
This is a **non-portable extension**.
**U**
: Pushes the maximum allowable value of **obase** onto the main stack.
This is a **non-portable extension**.
**V**
: Pushes the maximum allowable value of **scale** onto the main stack.
This is a **non-portable extension**.
## Strings
The following commands control strings.
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.
While arithmetic operations have to have numbers, and will print an error if
given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string **[1pR]** is
executed as a macro, then the code **1pR** is executed, meaning that the **1**
will be printed with a newline after and then popped from the stack.
**\[**_characters_**\]**
: Makes a string containing *characters* and pushes it onto the stack.
If there are brackets (**\[** and **\]**) in the string, then they must be
balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
character.
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.
**a**
: The value on top of the stack is popped.
If it is a number, it is truncated and its absolute value is taken. The
result mod **256** is calculated. If that result is **0**, push an empty
string; otherwise, push a one-character string where the character is the
result of the mod interpreted as an ASCII character.
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.
This is a **non-portable extension**.
**x**
: Pops a value off of the top of the stack.
If it is a number, it is pushed back onto the stack.
If it is a string, it is executed as a macro.
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
**\>**_r_
: 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
*r* are executed.
For example, **0 1>a** will execute the contents of register **a**, and
**1 0>a** will not.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\>**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**\<**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\<**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**=**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!=**_r_
: 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
*r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**?**
: Reads a line from the **stdin** and executes it. This is to allow macros to
request input from users.
**q**
: 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.
**Q**
: 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.
**,**
: Pushes the depth of the execution stack onto the stack. The execution stack
is the stack of string executions. The number that is pushed onto the stack
is exactly as many as is needed to make dc(1) exit with the **Q** command,
so the sequence **,Q** will make dc(1) exit.
## Status
These commands query status of the stack or its top value.
**Z**
: Pops a value off of the stack.
If it is a number, calculates the number of significant decimal digits it
has and pushes the result. It will push **1** if the argument is **0** with
no decimal places.
If it is a string, pushes the number of characters the string has.
**X**
: Pops a value off of the stack.
If it is a number, pushes the *scale* of the value onto the stack.
If it is a string, pushes **0**.
**z**
: Pushes the current depth of the stack (before execution of this command)
onto the stack.
**y**_r_
: Pushes the current stack depth of the register *r* onto the main stack.
Because each register has a depth of **1** (with the value **0** in the top
item) when dc(1) starts, dc(1) requires that each register's stack must
always have at least one item; dc(1) will give an error and reset otherwise
(see the **RESET** section). This means that this command will never push
**0**.
This is a **non-portable extension**.
## Arrays
These commands manipulate arrays.
**:**_r_
: Pops the top two values off of the stack. The second value will be stored in
the array *r* (see the **REGISTERS** section), indexed by the first value.
**;**_r_
: Pops the value on top of the stack and uses it as an index into the array
*r*. The selected value is then pushed onto the stack.
**Y**_r_
: Pushes the length of the array *r* onto the stack.
This is a **non-portable extension**.
+## Global Settings
+
+These commands retrieve global settings. These are the only commands that
+require multiple specific characters, and all of them begin with the letter
+**g**. Only the characters below are allowed after the character **g**; any
+other character produces a parse error (see the **ERRORS** section).
+
+**gl**
+
+: Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT
+ VARIABLES** section) onto the stack.
+
+**gz**
+
+: Pushes **0** onto the stack if the leading zero setting has not been enabled
+ with the **-z** or **-\-leading-zeroes** options (see the **OPTIONS**
+ section), non-zero otherwise.
+
# REGISTERS
Registers are names that can store strings, numbers, and arrays. (Number/string
registers do not interfere with array registers.)
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
(**0**) in their stack, and it is a runtime error to attempt to pop that item
off of the register stack.
In non-extended register mode, a register name is just the single character that
follows any command that needs a register name. The only exceptions are: a
newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
newline or a left bracket to be used as a register name.
## Extended Register Mode
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
amounts of registers, if extended register mode is enabled.
If extended register mode is enabled (**-x** or **-\-extended-register**
command-line arguments are given), then normal single character registers are
used *unless* the character immediately following a command that needs a
register name is a space (according to **isspace()**) and not a newline
(**'\\n'**).
In that case, the register name is found according to the regex
**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
the next non-space characters do not match that regex.
# 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.
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
macros returned) is skipped.
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.
# PERFORMANCE
Most dc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This dc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**DC_BASE_DIGS**.
In addition, this dc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **DC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on dc(1):
**DC_LONG_BIT**
: The number of bits in the **long** 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).
**DC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **DC_LONG_BIT**.
**DC_BASE_POW**
: The max decimal number that each large integer can store (see
**DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
**DC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **DC_LONG_BIT**.
**DC_BASE_MAX**
: The maximum output base. Set at **DC_BASE_POW**.
**DC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**DC_SCALE_MAX**
: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
**DC_STRING_MAX**
: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
**DC_NAME_MAX**
: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
**DC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**DC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
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.
# ENVIRONMENT VARIABLES
dc(1) recognizes the following environment variables:
**DC_ENV_ARGS**
: 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 **DC_ENV_ARGS** 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 **-e** option to set **scale** to a value other than **0**.
The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
**"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'dc' file.dc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **DC_ENV_ARGS** 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.
**DC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
lines to that length, including the backslash newline combo. The default
line length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**DC_SIGINT_RESET**
: If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because dc(1) exits on
**SIGINT** when not in interactive mode.
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1) reset
on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
environment variable exists and is *not* an integer, then dc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use TTY
mode, and zero makes dc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a prompt,
and zero or a non-integer makes dc(1) not use a prompt. If this environment
variable does not exist and **DC_TTY_MODE** does, then the value of the
**DC_TTY_MODE** environment variable is used.
This environment variable and the **DC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
dc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, taking the square root of a negative
number, attempting to convert a negative number to a hardware integer,
overflow when converting a number to a hardware integer, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**) operator.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, and using a token where it is
invalid.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors (including
attempting to execute a number), and attempting an operation when the stack
has too few elements.
**4**
: A fatal error occurred.
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.
The exit status **4** is special; when a fatal error occurs, dc(1) always exits
and returns **4**, no matter what mode dc(1) is in.
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
**-i** flag or **-\-interactive** option.
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 **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **DC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **DC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
mode on.
If the environment variable **DC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
**stdout**, and **stderr** are connected to a TTY and the **DC_TTY_MODE**
environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
information.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **DC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause dc(1) to do one of two things.
If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, dc(1) will
exit.
However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
default is an integer and non-zero, then dc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If dc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If dc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** 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.
**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is **SIGHUP**; in that
case, and only when dc(1) is in TTY mode (see the **TTY MODE** section), a
**SIGHUP** will cause dc(1) to clean up and exit.
# COMMAND LINE HISTORY
dc(1) supports interactive command-line editing.
If dc(1) can be in TTY mode (see the **TTY MODE** section), history can be
enabled. This means that command-line history can only be enabled when
**stdin**, **stdout**, and **stderr** are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment variable
**DC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
**Note**: tabs are converted to 8 spaces.
# SEE ALSO
bc(1)
# STANDARDS
The dc(1) utility operators are compliant with the operators in the bc(1)
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHOR
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/manuals/dc/H.1 b/manuals/dc/H.1
index ba30beb54d95..b4ab9f511080 100644
--- a/manuals/dc/H.1
+++ b/manuals/dc/H.1
@@ -1,1478 +1,1523 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "DC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH Name
.PP
dc - arbitrary-precision decimal reverse-Polish notation calculator
.SH SYNOPSIS
.PP
\f[B]dc\f[R] [\f[B]-hiPRvVx\f[R]] [\f[B]--version\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]]
[\f[B]--no-read-prompt\f[R]] [\f[B]--extended-register\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
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.
.PP
If no files are given on the command-line, then dc(1) reads from
\f[B]stdin\f[R] (see the \f[B]STDIN\f[R] section).
Otherwise, those files are processed, and dc(1) will then exit.
.PP
If a user wants to set up a standard environment, they can use
\f[B]DC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
For example, if a user wants the \f[B]scale\f[R] always set to
\f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R],
and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R].
.SH OPTIONS
.PP
The following are the options that dc(1) accepts.
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]DC_ENV_ARGS\f[R].
.RS
.PP
These options override the \f[B]DC_PROMPT\f[R] and \f[B]DC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of dc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]?\f[R] command is used.
.PP
These options \f[I]do\f[R] override the \f[B]DC_PROMPT\f[R] and
\f[B]DC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-x\f[R] \f[B]--extended-register\f[R]
Enables extended register mode.
See the \f[I]Extended Register Mode\f[R] subsection of the
\f[B]REGISTERS\f[R] section for more information.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]DC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files are given on the command-line and no files or expressions
are given by the \f[B]-f\f[R], \f[B]--file\f[R], \f[B]-e\f[R], or
\f[B]--expression\f[R] options, then dc(1) read from \f[B]stdin\f[R].
.PP
However, there is a caveat to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if a string has been finished, but not
ended.
This means that, except for escaped brackets, all brackets must be
balanced before dc(1) parses and executes.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]dc >&-\f[R], it will quit with an error.
This is done so that dc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]dc 2>&-\f[R], it will quit with an error.
This is done so that dc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
Each item in the input source code, either a number (see the
\f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R]
section), is processed and executed, in order.
Input is processed immediately when entered.
.PP
\f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to interpret constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in dc(1)
programs with the \f[B]T\f[R] command.
.PP
\f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and
can be queried with the \f[B]U\f[R] command.
The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R].
If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific
notation, and if \f[B]obase\f[R] is \f[B]1\f[R], values are output in
engineering notation.
Otherwise, values are output in the specified base.
.PP
Outputting in scientific and engineering notations are \f[B]non-portable
extensions\f[R].
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a register (see the \f[B]REGISTERS\f[R] section) that sets the
precision of any operations (with exceptions).
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] can be queried in dc(1)
programs with the \f[B]V\f[R] command.
.PP
\f[B]seed\f[R] is a register containing the current seed for the
pseudo-random number generator.
If the current value of \f[B]seed\f[R] is queried and stored, then if it
is assigned to \f[B]seed\f[R] later, the pseudo-random number generator
is guaranteed to produce the same sequence of pseudo-random numbers that
were generated after the value of \f[B]seed\f[R] was first queried.
.PP
Multiple values assigned to \f[B]seed\f[R] can produce the same sequence
of pseudo-random numbers.
Likewise, when a value is assigned to \f[B]seed\f[R], it is not
guaranteed that querying \f[B]seed\f[R] immediately after will return
the same value.
In addition, the value of \f[B]seed\f[R] will change after any call to
the \f[B]\[cq]\f[R] command or the \f[B]\[lq]\f[R] command that does not
get receive a value of \f[B]0\f[R] or \f[B]1\f[R].
The maximum integer returned by the \f[B]\[cq]\f[R] command can be
queried with the \f[B]W\f[R] command.
.PP
\f[B]Note\f[R]: The values returned by the pseudo-random number
generator with the \f[B]\[cq]\f[R] and \f[B]\[lq]\f[R] commands are
guaranteed to \f[B]NOT\f[R] be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they \f[I]are\f[R] guaranteed to be reproducible with identical
\f[B]seed\f[R] values.
This means that the pseudo-random values from dc(1) should only be used
where a reproducible stream of pseudo-random numbers is
\f[I]ESSENTIAL\f[R].
In any other case, use a non-seeded pseudo-random number generator.
.PP
The pseudo-random number generator, \f[B]seed\f[R], and all associated
operations are \f[B]non-portable extensions\f[R].
.SS Comments
.PP
Comments go from \f[B]#\f[R] until, and not including, the next newline.
This is a \f[B]non-portable extension\f[R].
.SH NUMBERS
.PP
Numbers are strings made up of digits, uppercase letters up to
\f[B]F\f[R], and at most \f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]F\f[R] alone always equals decimal \f[B]15\f[R].
.PP
In addition, dc(1) accepts numbers in scientific notation.
These have the form \f[B]e\f[R].
The exponent (the portion after the \f[B]e\f[R]) must be an integer.
An example is \f[B]1.89237e9\f[R], which is equal to
\f[B]1892370000\f[R].
Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to
\f[B]0.0042890\f[R].
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if dc(1) is given the number string
\f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.PP
Accepting input as scientific notation is a \f[B]non-portable
extension\f[R].
.SH COMMANDS
.PP
The valid commands are listed below.
.SS Printing
.PP
These commands are used for printing.
.PP
Note that both scientific notation and engineering notation are
available for printing numbers.
Scientific notation is activated by assigning \f[B]0\f[R] to
\f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is
activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using
\f[B]1o\f[R].
To deactivate them, just assign a different value to \f[B]obase\f[R].
.PP
Printing numbers in scientific notation and/or engineering notation is a
\f[B]non-portable extension\f[R].
.TP
\f[B]p\f[R]
Prints the value on top of the stack, whether number or string, and
prints a newline after.
.RS
.PP
This does not alter the stack.
.RE
.TP
\f[B]n\f[R]
Prints the value on top of the stack, whether number or string, and pops
it off of the stack.
.TP
\f[B]P\f[R]
Pops a value off the stack.
.RS
.PP
If the value is a number, it is truncated and the absolute value of the
result is printed as though \f[B]obase\f[R] is \f[B]256\f[R] and each
digit is interpreted as an 8-bit ASCII character, making it a byte
stream.
.PP
If the value is a string, it is printed without a trailing newline.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]f\f[R]
Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
.RS
.PP
Users should use this command when they get lost.
.RE
.SS Arithmetic
.PP
These are the commands used for arithmetic.
.TP
\f[B]+\f[R]
The top two values are popped off the stack, added, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]-\f[R]
The top two values are popped off the stack, subtracted, and the result
is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]*\f[R]
The top two values are popped off the stack, multiplied, and the result
is pushed onto the stack.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The top two values are popped off the stack, divided, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]%\f[R]
The top two values are popped off the stack, remaindered, and the result
is pushed onto the stack.
.RS
.PP
Remaindering is equivalent to 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R], and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]\[ti]\f[R]
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 \f[B]x y / x y %\f[R] except that \f[B]x\f[R] and
\f[B]y\f[R] are only evaluated once.
.RS
.PP
The first value popped off of the stack must be non-zero.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
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.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
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.
.RE
.TP
\f[B]v\f[R]
The top value is popped off the stack, its square root is computed, and
the result is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The value popped off of the stack must be non-negative.
.RE
.TP
\f[B]_\f[R]
If this command \f[I]immediately\f[R] precedes a number (i.e., no spaces
or other commands), then that number is input as a negative number.
.RS
.PP
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 \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]b\f[R]
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.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]|\f[R]
The top three values are popped off the stack, a modular exponentiation
is computed, and the result is pushed onto the stack.
.RS
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]$\f[R]
The top value is popped off the stack and copied, and the copy is
truncated and pushed onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[at]\f[R]
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.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]H\f[R]
The top two values are popped off the stack, and the second is shifted
left (radix shifted right) to the value of the first.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]h\f[R]
The top two values are popped off the stack, and the second is shifted
right (radix shifted left) to the value of the first.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]G\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]N\f[R]
The top value is popped off of the stack, and if it a \f[B]0\f[R], a
\f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B](\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]{\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than or equal to the second,
or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B])\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]}\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than or equal to the
second, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]M\f[R]
The top two values are popped off of the stack.
If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack.
If either of them is zero, or both of them are, then a \f[B]0\f[R] is
pushed onto the stack.
.RS
.PP
This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]m\f[R]
The top two values are popped off of the stack.
If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the
stack.
If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack.
.RS
.PP
This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Pseudo-Random Number Generator
.PP
dc(1) has a built-in pseudo-random number generator.
These commands query the pseudo-random number generator.
(See Parameters for more information about the \f[B]seed\f[R] value that
controls the pseudo-random number generator.)
.PP
The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be
cryptographically secure.
.TP
\f[B]\[cq]\f[R]
Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see
the \f[B]LIMITS\f[R] section).
.RS
.PP
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[lq]\f[R]
Pops a value off of the stack, which is used as an \f[B]exclusive\f[R]
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 \f[B]RESET\f[R] section) while \f[B]seed\f[R]
remains unchanged.
If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is
honored by generating several pseudo-random integers, multiplying them
by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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 \f[B]seed\f[R], unless the
operand is \f[B]0\f[R] or \f[B]1\f[R].
In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R]
is \f[I]not\f[R] changed.
.RS
.PP
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Stack Control
.PP
These commands control the stack.
.TP
\f[B]c\f[R]
Removes all items from (\[lq]clears\[rq]) the stack.
.TP
\f[B]d\f[R]
Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes
the copy onto the stack.
.TP
\f[B]r\f[R]
Swaps (\[lq]reverses\[rq]) the two top items on the stack.
.TP
\f[B]R\f[R]
Pops (\[lq]removes\[rq]) the top value from the stack.
.SS Register Control
.PP
These commands control registers (see the \f[B]REGISTERS\f[R] section).
.TP
\f[B]s\f[R]\f[I]r\f[R]
Pops the value off the top of the stack and stores it into register
\f[I]r\f[R].
.TP
\f[B]l\f[R]\f[I]r\f[R]
Copies the value in register \f[I]r\f[R] and pushes it onto the stack.
This does not alter the contents of \f[I]r\f[R].
.TP
\f[B]S\f[R]\f[I]r\f[R]
Pops the value off the top of the (main) stack and pushes it onto the
stack of register \f[I]r\f[R].
The previous value of the register becomes inaccessible.
.TP
\f[B]L\f[R]\f[I]r\f[R]
Pops the value off the top of the stack for register \f[I]r\f[R] and
push it onto the main stack.
The previous value in the stack for register \f[I]r\f[R], if any, is now
accessible via the \f[B]l\f[R]\f[I]r\f[R] command.
.SS Parameters
.PP
These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R],
\f[B]scale\f[R], and \f[B]seed\f[R].
Also see the \f[B]SYNTAX\f[R] section.
.TP
\f[B]i\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R],
inclusive.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]o\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]obase\f[R], which must be between \f[B]0\f[R] and
\f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and
the \f[B]NUMBERS\f[R] section).
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]k\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]scale\f[R], which must be non-negative.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]j\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]seed\f[R].
The meaning of \f[B]seed\f[R] is dependent on the current pseudo-random
number generator but is guaranteed to not change except for new major
versions.
.RS
.PP
The \f[I]scale\f[R] and sign of the value may be significant.
.PP
If a previously used \f[B]seed\f[R] 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 \f[B]seed\f[R]
value was previously used.
.PP
The exact value assigned to \f[B]seed\f[R] is not guaranteed to be
returned if the \f[B]J\f[R] command is used.
However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both
values, when assigned to \f[B]seed\f[R], are guaranteed to produce the
same sequence of pseudo-random numbers.
This means that certain values assigned to \f[B]seed\f[R] will not
produce unique sequences of pseudo-random numbers.
.PP
There is no limit to the length (number of significant decimal digits)
or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]I\f[R]
Pushes the current value of \f[B]ibase\f[R] onto the main stack.
.TP
\f[B]O\f[R]
Pushes the current value of \f[B]obase\f[R] onto the main stack.
.TP
\f[B]K\f[R]
Pushes the current value of \f[B]scale\f[R] onto the main stack.
.TP
\f[B]J\f[R]
Pushes the current value of \f[B]seed\f[R] onto the main stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]T\f[R]
Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]U\f[R]
Pushes the maximum allowable value of \f[B]obase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]V\f[R]
Pushes the maximum allowable value of \f[B]scale\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]W\f[R]
Pushes the maximum (inclusive) integer that can be generated with the
\f[B]\[cq]\f[R] pseudo-random number generator command.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Strings
.PP
The following commands control strings.
.PP
dc(1) can work with both numbers and strings, and registers (see the
\f[B]REGISTERS\f[R] section) can hold both strings and numbers.
dc(1) always knows whether the contents of a register are a string or a
number.
.PP
While arithmetic operations have to have numbers, and will print an
error if given a string, other commands accept strings.
.PP
Strings can also be executed as macros.
For example, if the string \f[B][1pR]\f[R] is executed as a macro, then
the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be
printed with a newline after and then popped from the stack.
.TP
\f[B][\f[R]\f[I]characters\f[R]\f[B]]\f[R]
Makes a string containing \f[I]characters\f[R] and pushes it onto the
stack.
.RS
.PP
If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then
they must be balanced.
Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R])
character.
.PP
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.
.RE
.TP
\f[B]a\f[R]
The value on top of the stack is popped.
.RS
.PP
If it is a number, it is truncated and its absolute value is taken.
The result mod \f[B]256\f[R] is calculated.
If that result is \f[B]0\f[R], push an empty string; otherwise, push a
one-character string where the character is the result of the mod
interpreted as an ASCII character.
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]x\f[R]
Pops a value off of the top of the stack.
.RS
.PP
If it is a number, it is pushed back onto the stack.
.PP
If it is a string, it is executed as a macro.
.PP
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
For example, \f[B]0 1>a\f[R] will execute the contents of register
\f[B]a\f[R], and \f[B]1 0>a\f[R] will not.
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]
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
\f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]?\f[R]
Reads a line from the \f[B]stdin\f[R] and executes it.
This is to allow macros to request input from users.
.TP
\f[B]q\f[R]
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
\f[B]Q\f[R]
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.
.TP
\f[B],\f[R]
Pushes the depth of the execution stack onto the stack.
The execution stack is the stack of string executions.
The number that is pushed onto the stack is exactly as many as is needed
to make dc(1) exit with the \f[B]Q\f[R] command, so the sequence
\f[B],Q\f[R] will make dc(1) exit.
.SS Status
.PP
These commands query status of the stack or its top value.
.TP
\f[B]Z\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, calculates the number of significant decimal digits
it has and pushes the result.
It will push \f[B]1\f[R] if the argument is \f[B]0\f[R] with no decimal
places.
.PP
If it is a string, pushes the number of characters the string has.
.RE
.TP
\f[B]X\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, pushes the \f[I]scale\f[R] of the value onto the
stack.
.PP
If it is a string, pushes \f[B]0\f[R].
.RE
.TP
\f[B]z\f[R]
Pushes the current depth of the stack (before execution of this command)
onto the stack.
.TP
\f[B]y\f[R]\f[I]r\f[R]
Pushes the current stack depth of the register \f[I]r\f[R] onto the main
stack.
.RS
.PP
Because each register has a depth of \f[B]1\f[R] (with the value
\f[B]0\f[R] in the top item) when dc(1) starts, dc(1) requires that each
register\[cq]s stack must always have at least one item; dc(1) will give
an error and reset otherwise (see the \f[B]RESET\f[R] section).
This means that this command will never push \f[B]0\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Arrays
.PP
These commands manipulate arrays.
.TP
\f[B]:\f[R]\f[I]r\f[R]
Pops the top two values off of the stack.
The second value will be stored in the array \f[I]r\f[R] (see the
\f[B]REGISTERS\f[R] section), indexed by the first value.
.TP
\f[B];\f[R]\f[I]r\f[R]
Pops the value on top of the stack and uses it as an index into the
array \f[I]r\f[R].
The selected value is then pushed onto the stack.
.TP
\f[B]Y\f[R]\f[I]r\f[R]
Pushes the length of the array \f[I]r\f[R] onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
+.SS Global Settings
+.PP
+These commands retrieve global settings.
+These are the only commands that require multiple specific characters,
+and all of them begin with the letter \f[B]g\f[R].
+Only the characters below are allowed after the character \f[B]g\f[R];
+any other character produces a parse error (see the \f[B]ERRORS\f[R]
+section).
+.TP
+\f[B]gl\f[R]
+Pushes the line length set by \f[B]DC_LINE_LENGTH\f[R] (see the
+\f[B]ENVIRONMENT VARIABLES\f[R] section) onto the stack.
+.TP
+\f[B]gz\f[R]
+Pushes \f[B]0\f[R] onto the stack if the leading zero setting has not
+been enabled with the \f[B]-z\f[R] or \f[B]--leading-zeroes\f[R] options
+(see the \f[B]OPTIONS\f[R] section), non-zero otherwise.
.SH REGISTERS
.PP
Registers are names that can store strings, numbers, and arrays.
(Number/string registers do not interfere with array registers.)
.PP
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 (\f[B]0\f[R]) in
their stack, and it is a runtime error to attempt to pop that item off
of the register stack.
.PP
In non-extended register mode, a register name is just the single
character that follows any command that needs a register name.
The only exceptions are: a newline (\f[B]`\[rs]n'\f[R]) and a left
bracket (\f[B]`['\f[R]); it is a parse error for a newline or a left
bracket to be used as a register name.
.SS Extended Register Mode
.PP
Unlike most other dc(1) implentations, this dc(1) provides nearly
unlimited amounts of registers, if extended register mode is enabled.
.PP
If extended register mode is enabled (\f[B]-x\f[R] or
\f[B]--extended-register\f[R] command-line arguments are given), then
normal single character registers are used \f[I]unless\f[R] the
character immediately following a command that needs a register name is
a space (according to \f[B]isspace()\f[R]) and not a newline
(\f[B]`\[rs]n'\f[R]).
.PP
In that case, the register name is found according to the regex
\f[B][a-z][a-z0-9_]*\f[R] (like bc(1) identifiers), and it is a parse
error if the next non-space characters do not match that regex.
.SH RESET
.PP
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.
.PP
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 macros returned) is skipped.
.PP
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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.SH PERFORMANCE
.PP
Most dc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This dc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]DC_BASE_DIGS\f[R].
.PP
In addition, this dc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]DC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on dc(1):
.TP
\f[B]DC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] 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 \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]DC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]DC_BASE_DIGS\f[R].
.TP
\f[B]DC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]DC_BASE_POW\f[R].
.TP
\f[B]DC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]DC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command,
if dc(1).
Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]DC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
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
.PP
dc(1) recognizes the following environment variables:
.TP
\f[B]DC_ENV_ARGS\f[R]
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
\f[B]DC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 \f[B]-e\f[R] option to set
\f[B]scale\f[R] to a value other than \f[B]0\f[R].
.RS
.PP
The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`dc' file.dc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]DC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]DC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length,
including the backslash newline combo.
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]DC_SIGINT_RESET\f[R]
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because dc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes dc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then dc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use
TTY mode, and zero makes dc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a
prompt, and zero or a non-integer makes dc(1) not use a prompt.
If this environment variable does not exist and \f[B]DC_TTY_MODE\f[R]
does, then the value of the \f[B]DC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]DC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
dc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], 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, overflow when calculating the size of a number, and attempting
to use a non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift
(\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, and using a
token where it is invalid.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors (including attempting to execute
a number), and attempting an operation when the stack has too few
elements.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
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.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, dc(1)
always exits and returns \f[B]4\f[R], no matter what mode dc(1) is in.
.PP
The other statuses will only be returned when dc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
dc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, dc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
dc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]DC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, dc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]DC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, dc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]DC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then dc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]DC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]DC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]DC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]DC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]DC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause dc(1) to do one of two things.
.PP
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, dc(1) will exit.
.PP
However, if dc(1) is in interactive mode, and the
\f[B]DC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then dc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If dc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If dc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] 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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause dc(1) to clean up and
exit, and it uses the default handler for all other signals.
.SH LOCALES
.PP
This dc(1) ships with support for adding error messages for different
locales and thus, supports \f[B]LC_MESSAGES\f[R].
.SH SEE ALSO
.PP
bc(1)
.SH STANDARDS
.PP
The dc(1) utility operators are compliant with the operators in the
bc(1) IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHOR
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/dc/H.1.md b/manuals/dc/H.1.md
index 0fee947ec5c3..647d486adc38 100644
--- a/manuals/dc/H.1.md
+++ b/manuals/dc/H.1.md
@@ -1,1321 +1,1361 @@
# Name
dc - arbitrary-precision decimal reverse-Polish notation calculator
# SYNOPSIS
**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# 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.
If no files are given on the command-line, then dc(1) reads from **stdin** (see
the **STDIN** section). Otherwise, those files are processed, and dc(1) will
then exit.
If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
this dc(1) will always start with a **scale** of **10**.
# OPTIONS
The following are the options that dc(1) accepts.
**-h**, **-\-help**
: Prints a usage message and quits.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in dc(1). Most of those users
would want to put this option in **DC_ENV_ARGS**.
These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of dc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **?** command is used.
These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-x** **-\-extended-register**
: Enables extended register mode. See the *Extended Register Mode* subsection
of the **REGISTERS** section for more information.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files are given on the command-line and no files or expressions are given
by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
read from **stdin**.
However, there is a caveat to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
a string has been finished, but not ended. This means that, except for escaped
brackets, all brackets must be balanced before dc(1) parses and executes.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **dc >&-**, it will quit with an error. This
is done so that dc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This
is done so that dc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
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.
**ibase** is a register (see the **REGISTERS** section) that determines how to
interpret constant numbers. It is the "input" base, or the number base used for
interpreting input numbers. **ibase** is initially **10**. The max allowable
value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
The max allowable value for **ibase** can be queried in dc(1) programs with the
**T** command.
**obase** is a register (see the **REGISTERS** section) that determines how to
output results. It is the "output" base, or the number base used for outputting
numbers. **obase** is initially **10**. The max allowable value for **obase** is
**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
value for **obase** is **0**. If **obase** is **0**, values are output in
scientific notation, and if **obase** is **1**, values are output in engineering
notation. Otherwise, values are output in the specified base.
Outputting in scientific and engineering notations are **non-portable
extensions**.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a register (see the
**REGISTERS** section) that sets the precision of any operations (with
exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
allowable value for **scale** can be queried in dc(1) programs with the **V**
command.
**seed** is a register containing the current seed for the pseudo-random number
generator. If the current value of **seed** is queried and stored, then if it is
assigned to **seed** later, the pseudo-random number generator is guaranteed to
produce the same sequence of pseudo-random numbers that were generated after the
value of **seed** was first queried.
Multiple values assigned to **seed** can produce the same sequence of
pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not
guaranteed that querying **seed** immediately after will return the same value.
In addition, the value of **seed** will change after any call to the **'**
command or the **"** command that does not get receive a value of **0** or
**1**. The maximum integer returned by the **'** command can be queried with the
**W** command.
**Note**: The values returned by the pseudo-random number generator with the
**'** and **"** commands are guaranteed to **NOT** be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator. However,
they *are* guaranteed to be reproducible with identical **seed** values. This
means that the pseudo-random values from dc(1) should only be used where a
reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
use a non-seeded pseudo-random number generator.
The pseudo-random number generator, **seed**, and all associated operations are
**non-portable extensions**.
## Comments
Comments go from **#** until, and not including, the next newline. This is a
**non-portable extension**.
# NUMBERS
Numbers are strings made up of digits, uppercase letters up to **F**, and at
most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
current value of **ibase**, they are set to the value of the highest valid digit
in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **F** alone always equals decimal
**15**.
In addition, dc(1) accepts numbers in scientific notation. These have the form
**\e\**. The exponent (the portion after the **e**) must be
an integer. An example is **1.89237e9**, which is equal to **1892370000**.
Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For example,
if **ibase** is **16** and dc(1) is given the number string **FFeA**, the
resulting decimal number will be **2550000000000**, and if dc(1) is given the
number string **10e_4**, the resulting decimal number will be **0.0016**.
Accepting input as scientific notation is a **non-portable extension**.
# COMMANDS
The valid commands are listed below.
## Printing
These commands are used for printing.
Note that both scientific notation and engineering notation are available for
printing numbers. Scientific notation is activated by assigning **0** to
**obase** using **0o**, and engineering notation is activated by assigning **1**
to **obase** using **1o**. To deactivate them, just assign a different value to
**obase**.
Printing numbers in scientific notation and/or engineering notation is a
**non-portable extension**.
**p**
: Prints the value on top of the stack, whether number or string, and prints a
newline after.
This does not alter the stack.
**n**
: Prints the value on top of the stack, whether number or string, and pops it
off of the stack.
**P**
: Pops a value off the stack.
If the value is a number, it is truncated and the absolute value of the
result is printed as though **obase** is **256** and each digit is
interpreted as an 8-bit ASCII character, making it a byte stream.
If the value is a string, it is printed without a trailing newline.
This is a **non-portable extension**.
**f**
: Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
Users should use this command when they get lost.
## Arithmetic
These are the commands used for arithmetic.
**+**
: The top two values are popped off the stack, added, and the result is pushed
onto the stack. The *scale* of the result is equal to the max *scale* of
both operands.
**-**
: The top two values are popped off the stack, subtracted, and the result is
pushed onto the stack. The *scale* of the result is equal to the max
*scale* of both operands.
**\***
: The top two values are popped off the stack, multiplied, and the result is
pushed onto the stack. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result
is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The top two values are popped off the stack, divided, and the result is
pushed onto the stack. The *scale* of the result is equal to **scale**.
The first value popped off of the stack must be non-zero.
**%**
: The top two values are popped off the stack, remaindered, and the result is
pushed onto the stack.
Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The first value popped off of the stack must be non-zero.
**~**
: 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 **x y / x y %** except that **x** and **y** are only
evaluated once.
The first value popped off of the stack must be non-zero.
This is a **non-portable extension**.
**\^**
: 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. The *scale* of
the result is equal to **scale**.
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.
**v**
: The top value is popped off the stack, its square root is computed, and the
result is pushed onto the stack. The *scale* of the result is equal to
**scale**.
The value popped off of the stack must be non-negative.
**\_**
: If this command *immediately* precedes a number (i.e., no spaces or other
commands), then that number is input as a negative number.
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
**non-portable extension**.
**b**
: 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.
This is a **non-portable extension**.
**|**
: The top three values are popped off the stack, a modular exponentiation is
computed, and the result is pushed onto the stack.
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.
This is a **non-portable extension**.
**\$**
: The top value is popped off the stack and copied, and the copy is truncated
and pushed onto the stack.
This is a **non-portable extension**.
**\@**
: 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.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**H**
: The top two values are popped off the stack, and the second is shifted left
(radix shifted right) to the value of the first.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**h**
: The top two values are popped off the stack, and the second is shifted right
(radix shifted left) to the value of the first.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**G**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if they are equal, or **0** otherwise.
This is a **non-portable extension**.
**N**
: The top value is popped off of the stack, and if it a **0**, a **1** is
pushed; otherwise, a **0** is pushed.
This is a **non-portable extension**.
**(**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than the second, or **0** otherwise.
This is a **non-portable extension**.
**{**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than or equal to the second, or **0**
otherwise.
This is a **non-portable extension**.
**)**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than the second, or **0** otherwise.
This is a **non-portable extension**.
**}**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than or equal to the second, or
**0** otherwise.
This is a **non-portable extension**.
**M**
: The top two values are popped off of the stack. If they are both non-zero, a
**1** is pushed onto the stack. If either of them is zero, or both of them
are, then a **0** is pushed onto the stack.
This is like the **&&** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
**m**
: The top two values are popped off of the stack. If at least one of them is
non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
**0** is pushed onto the stack.
This is like the **||** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
## Pseudo-Random Number Generator
dc(1) has a built-in pseudo-random number generator. These commands query the
pseudo-random number generator. (See Parameters for more information about the
**seed** value that controls the pseudo-random number generator.)
The pseudo-random number generator is guaranteed to **NOT** be
cryptographically secure.
**'**
: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the
**LIMITS** section).
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
This is a **non-portable extension**.
**"**
: Pops a value off of the stack, which is used as an **exclusive** 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) while **seed** remains unchanged. If the bound is larger than
**DC_RAND_MAX**, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
**DC_RAND_MAX+1**, 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 **seed**, unless the operand is **0** or **1**. In that
case, **0** is pushed onto the stack, and **seed** is *not* changed.
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
This is a **non-portable extension**.
## Stack Control
These commands control the stack.
**c**
: Removes all items from ("clears") the stack.
**d**
: Copies the item on top of the stack ("duplicates") and pushes the copy onto
the stack.
**r**
: Swaps ("reverses") the two top items on the stack.
**R**
: Pops ("removes") the top value from the stack.
## Register Control
These commands control registers (see the **REGISTERS** section).
**s**_r_
: Pops the value off the top of the stack and stores it into register *r*.
**l**_r_
: Copies the value in register *r* and pushes it onto the stack. This does not
alter the contents of *r*.
**S**_r_
: Pops the value off the top of the (main) stack and pushes it onto the stack
of register *r*. The previous value of the register becomes inaccessible.
**L**_r_
: Pops the value off the top of the stack for register *r* and push it onto
the main stack. The previous value in the stack for register *r*, if any, is
now accessible via the **l**_r_ command.
## Parameters
These commands control the values of **ibase**, **obase**, **scale**, and
**seed**. Also see the **SYNTAX** section.
**i**
: Pops the value off of the top of the stack and uses it to set **ibase**,
which must be between **2** and **16**, inclusive.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**o**
: Pops the value off of the top of the stack and uses it to set **obase**,
which must be between **0** and **DC_BASE_MAX**, inclusive (see the
**LIMITS** section and the **NUMBERS** section).
If the value on top of the stack has any *scale*, the *scale* is ignored.
**k**
: Pops the value off of the top of the stack and uses it to set **scale**,
which must be non-negative.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**j**
: Pops the value off of the top of the stack and uses it to set **seed**. The
meaning of **seed** is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major versions.
The *scale* and sign of the value may be significant.
If a previously used **seed** 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 **seed** value was previously used.
The exact value assigned to **seed** is not guaranteed to be returned if the
**J** command is used. However, if **seed** *does* return a different value,
both values, when assigned to **seed**, are guaranteed to produce the same
sequence of pseudo-random numbers. This means that certain values assigned
to **seed** will not produce unique sequences of pseudo-random numbers.
There is no limit to the length (number of significant decimal digits) or
*scale* of the value that can be assigned to **seed**.
This is a **non-portable extension**.
**I**
: Pushes the current value of **ibase** onto the main stack.
**O**
: Pushes the current value of **obase** onto the main stack.
**K**
: Pushes the current value of **scale** onto the main stack.
**J**
: Pushes the current value of **seed** onto the main stack.
This is a **non-portable extension**.
**T**
: Pushes the maximum allowable value of **ibase** onto the main stack.
This is a **non-portable extension**.
**U**
: Pushes the maximum allowable value of **obase** onto the main stack.
This is a **non-portable extension**.
**V**
: Pushes the maximum allowable value of **scale** onto the main stack.
This is a **non-portable extension**.
**W**
: Pushes the maximum (inclusive) integer that can be generated with the **'**
pseudo-random number generator command.
This is a **non-portable extension**.
## Strings
The following commands control strings.
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.
While arithmetic operations have to have numbers, and will print an error if
given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string **[1pR]** is
executed as a macro, then the code **1pR** is executed, meaning that the **1**
will be printed with a newline after and then popped from the stack.
**\[**_characters_**\]**
: Makes a string containing *characters* and pushes it onto the stack.
If there are brackets (**\[** and **\]**) in the string, then they must be
balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
character.
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.
**a**
: The value on top of the stack is popped.
If it is a number, it is truncated and its absolute value is taken. The
result mod **256** is calculated. If that result is **0**, push an empty
string; otherwise, push a one-character string where the character is the
result of the mod interpreted as an ASCII character.
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.
This is a **non-portable extension**.
**x**
: Pops a value off of the top of the stack.
If it is a number, it is pushed back onto the stack.
If it is a string, it is executed as a macro.
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
**\>**_r_
: 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
*r* are executed.
For example, **0 1>a** will execute the contents of register **a**, and
**1 0>a** will not.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\>**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**\<**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\<**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**=**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!=**_r_
: 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
*r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**?**
: Reads a line from the **stdin** and executes it. This is to allow macros to
request input from users.
**q**
: 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.
**Q**
: 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.
**,**
: Pushes the depth of the execution stack onto the stack. The execution stack
is the stack of string executions. The number that is pushed onto the stack
is exactly as many as is needed to make dc(1) exit with the **Q** command,
so the sequence **,Q** will make dc(1) exit.
## Status
These commands query status of the stack or its top value.
**Z**
: Pops a value off of the stack.
If it is a number, calculates the number of significant decimal digits it
has and pushes the result. It will push **1** if the argument is **0** with
no decimal places.
If it is a string, pushes the number of characters the string has.
**X**
: Pops a value off of the stack.
If it is a number, pushes the *scale* of the value onto the stack.
If it is a string, pushes **0**.
**z**
: Pushes the current depth of the stack (before execution of this command)
onto the stack.
**y**_r_
: Pushes the current stack depth of the register *r* onto the main stack.
Because each register has a depth of **1** (with the value **0** in the top
item) when dc(1) starts, dc(1) requires that each register's stack must
always have at least one item; dc(1) will give an error and reset otherwise
(see the **RESET** section). This means that this command will never push
**0**.
This is a **non-portable extension**.
## Arrays
These commands manipulate arrays.
**:**_r_
: Pops the top two values off of the stack. The second value will be stored in
the array *r* (see the **REGISTERS** section), indexed by the first value.
**;**_r_
: Pops the value on top of the stack and uses it as an index into the array
*r*. The selected value is then pushed onto the stack.
**Y**_r_
: Pushes the length of the array *r* onto the stack.
This is a **non-portable extension**.
+## Global Settings
+
+These commands retrieve global settings. These are the only commands that
+require multiple specific characters, and all of them begin with the letter
+**g**. Only the characters below are allowed after the character **g**; any
+other character produces a parse error (see the **ERRORS** section).
+
+**gl**
+
+: Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT
+ VARIABLES** section) onto the stack.
+
+**gz**
+
+: Pushes **0** onto the stack if the leading zero setting has not been enabled
+ with the **-z** or **-\-leading-zeroes** options (see the **OPTIONS**
+ section), non-zero otherwise.
+
# REGISTERS
Registers are names that can store strings, numbers, and arrays. (Number/string
registers do not interfere with array registers.)
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
(**0**) in their stack, and it is a runtime error to attempt to pop that item
off of the register stack.
In non-extended register mode, a register name is just the single character that
follows any command that needs a register name. The only exceptions are: a
newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
newline or a left bracket to be used as a register name.
## Extended Register Mode
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
amounts of registers, if extended register mode is enabled.
If extended register mode is enabled (**-x** or **-\-extended-register**
command-line arguments are given), then normal single character registers are
used *unless* the character immediately following a command that needs a
register name is a space (according to **isspace()**) and not a newline
(**'\\n'**).
In that case, the register name is found according to the regex
**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
the next non-space characters do not match that regex.
# 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.
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
macros returned) is skipped.
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.
# PERFORMANCE
Most dc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This dc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**DC_BASE_DIGS**.
In addition, this dc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **DC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on dc(1):
**DC_LONG_BIT**
: The number of bits in the **long** 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).
**DC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **DC_LONG_BIT**.
**DC_BASE_POW**
: The max decimal number that each large integer can store (see
**DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
**DC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **DC_LONG_BIT**.
**DC_BASE_MAX**
: The maximum output base. Set at **DC_BASE_POW**.
**DC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**DC_SCALE_MAX**
: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
**DC_STRING_MAX**
: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
**DC_NAME_MAX**
: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
**DC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
**DC_RAND_MAX**
: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set
at **2\^DC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**DC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
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.
# ENVIRONMENT VARIABLES
dc(1) recognizes the following environment variables:
**DC_ENV_ARGS**
: 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 **DC_ENV_ARGS** 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 **-e** option to set **scale** to a value other than **0**.
The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
**"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'dc' file.dc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **DC_ENV_ARGS** 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.
**DC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
lines to that length, including the backslash newline combo. The default
line length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**DC_SIGINT_RESET**
: If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because dc(1) exits on
**SIGINT** when not in interactive mode.
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1) reset
on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
environment variable exists and is *not* an integer, then dc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use TTY
mode, and zero makes dc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a prompt,
and zero or a non-integer makes dc(1) not use a prompt. If this environment
variable does not exist and **DC_TTY_MODE** does, then the value of the
**DC_TTY_MODE** environment variable is used.
This environment variable and the **DC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
dc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, 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, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**), places (**\@**), left shift (**H**), and right shift (**h**)
operators.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, and using a token where it is
invalid.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors (including
attempting to execute a number), and attempting an operation when the stack
has too few elements.
**4**
: A fatal error occurred.
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.
The exit status **4** is special; when a fatal error occurs, dc(1) always exits
and returns **4**, no matter what mode dc(1) is in.
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
**-i** flag or **-\-interactive** option.
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 **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **DC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **DC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
mode on.
If the environment variable **DC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **DC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause dc(1) to do one of two things.
If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, dc(1) will
exit.
However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
default is an integer and non-zero, then dc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If dc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If dc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** 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.
**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
default handler for all other signals.
# LOCALES
This dc(1) ships with support for adding error messages for different locales
and thus, supports **LC_MESSAGES**.
# SEE ALSO
bc(1)
# STANDARDS
The dc(1) utility operators are compliant with the operators in the bc(1)
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHOR
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/manuals/dc/HN.1 b/manuals/dc/HN.1
index e7a76f01dc4a..eb35cb23ff7b 100644
--- a/manuals/dc/HN.1
+++ b/manuals/dc/HN.1
@@ -1,1474 +1,1519 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "DC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH Name
.PP
dc - arbitrary-precision decimal reverse-Polish notation calculator
.SH SYNOPSIS
.PP
\f[B]dc\f[R] [\f[B]-hiPRvVx\f[R]] [\f[B]--version\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]]
[\f[B]--no-read-prompt\f[R]] [\f[B]--extended-register\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
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.
.PP
If no files are given on the command-line, then dc(1) reads from
\f[B]stdin\f[R] (see the \f[B]STDIN\f[R] section).
Otherwise, those files are processed, and dc(1) will then exit.
.PP
If a user wants to set up a standard environment, they can use
\f[B]DC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
For example, if a user wants the \f[B]scale\f[R] always set to
\f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R],
and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R].
.SH OPTIONS
.PP
The following are the options that dc(1) accepts.
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]DC_ENV_ARGS\f[R].
.RS
.PP
These options override the \f[B]DC_PROMPT\f[R] and \f[B]DC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of dc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]?\f[R] command is used.
.PP
These options \f[I]do\f[R] override the \f[B]DC_PROMPT\f[R] and
\f[B]DC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-x\f[R] \f[B]--extended-register\f[R]
Enables extended register mode.
See the \f[I]Extended Register Mode\f[R] subsection of the
\f[B]REGISTERS\f[R] section for more information.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]DC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files are given on the command-line and no files or expressions
are given by the \f[B]-f\f[R], \f[B]--file\f[R], \f[B]-e\f[R], or
\f[B]--expression\f[R] options, then dc(1) read from \f[B]stdin\f[R].
.PP
However, there is a caveat to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if a string has been finished, but not
ended.
This means that, except for escaped brackets, all brackets must be
balanced before dc(1) parses and executes.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]dc >&-\f[R], it will quit with an error.
This is done so that dc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]dc 2>&-\f[R], it will quit with an error.
This is done so that dc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
Each item in the input source code, either a number (see the
\f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R]
section), is processed and executed, in order.
Input is processed immediately when entered.
.PP
\f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to interpret constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in dc(1)
programs with the \f[B]T\f[R] command.
.PP
\f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and
can be queried with the \f[B]U\f[R] command.
The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R].
If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific
notation, and if \f[B]obase\f[R] is \f[B]1\f[R], values are output in
engineering notation.
Otherwise, values are output in the specified base.
.PP
Outputting in scientific and engineering notations are \f[B]non-portable
extensions\f[R].
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a register (see the \f[B]REGISTERS\f[R] section) that sets the
precision of any operations (with exceptions).
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] can be queried in dc(1)
programs with the \f[B]V\f[R] command.
.PP
\f[B]seed\f[R] is a register containing the current seed for the
pseudo-random number generator.
If the current value of \f[B]seed\f[R] is queried and stored, then if it
is assigned to \f[B]seed\f[R] later, the pseudo-random number generator
is guaranteed to produce the same sequence of pseudo-random numbers that
were generated after the value of \f[B]seed\f[R] was first queried.
.PP
Multiple values assigned to \f[B]seed\f[R] can produce the same sequence
of pseudo-random numbers.
Likewise, when a value is assigned to \f[B]seed\f[R], it is not
guaranteed that querying \f[B]seed\f[R] immediately after will return
the same value.
In addition, the value of \f[B]seed\f[R] will change after any call to
the \f[B]\[cq]\f[R] command or the \f[B]\[lq]\f[R] command that does not
get receive a value of \f[B]0\f[R] or \f[B]1\f[R].
The maximum integer returned by the \f[B]\[cq]\f[R] command can be
queried with the \f[B]W\f[R] command.
.PP
\f[B]Note\f[R]: The values returned by the pseudo-random number
generator with the \f[B]\[cq]\f[R] and \f[B]\[lq]\f[R] commands are
guaranteed to \f[B]NOT\f[R] be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they \f[I]are\f[R] guaranteed to be reproducible with identical
\f[B]seed\f[R] values.
This means that the pseudo-random values from dc(1) should only be used
where a reproducible stream of pseudo-random numbers is
\f[I]ESSENTIAL\f[R].
In any other case, use a non-seeded pseudo-random number generator.
.PP
The pseudo-random number generator, \f[B]seed\f[R], and all associated
operations are \f[B]non-portable extensions\f[R].
.SS Comments
.PP
Comments go from \f[B]#\f[R] until, and not including, the next newline.
This is a \f[B]non-portable extension\f[R].
.SH NUMBERS
.PP
Numbers are strings made up of digits, uppercase letters up to
\f[B]F\f[R], and at most \f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]F\f[R] alone always equals decimal \f[B]15\f[R].
.PP
In addition, dc(1) accepts numbers in scientific notation.
These have the form \f[B]e\f[R].
The exponent (the portion after the \f[B]e\f[R]) must be an integer.
An example is \f[B]1.89237e9\f[R], which is equal to
\f[B]1892370000\f[R].
Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to
\f[B]0.0042890\f[R].
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if dc(1) is given the number string
\f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.PP
Accepting input as scientific notation is a \f[B]non-portable
extension\f[R].
.SH COMMANDS
.PP
The valid commands are listed below.
.SS Printing
.PP
These commands are used for printing.
.PP
Note that both scientific notation and engineering notation are
available for printing numbers.
Scientific notation is activated by assigning \f[B]0\f[R] to
\f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is
activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using
\f[B]1o\f[R].
To deactivate them, just assign a different value to \f[B]obase\f[R].
.PP
Printing numbers in scientific notation and/or engineering notation is a
\f[B]non-portable extension\f[R].
.TP
\f[B]p\f[R]
Prints the value on top of the stack, whether number or string, and
prints a newline after.
.RS
.PP
This does not alter the stack.
.RE
.TP
\f[B]n\f[R]
Prints the value on top of the stack, whether number or string, and pops
it off of the stack.
.TP
\f[B]P\f[R]
Pops a value off the stack.
.RS
.PP
If the value is a number, it is truncated and the absolute value of the
result is printed as though \f[B]obase\f[R] is \f[B]256\f[R] and each
digit is interpreted as an 8-bit ASCII character, making it a byte
stream.
.PP
If the value is a string, it is printed without a trailing newline.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]f\f[R]
Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
.RS
.PP
Users should use this command when they get lost.
.RE
.SS Arithmetic
.PP
These are the commands used for arithmetic.
.TP
\f[B]+\f[R]
The top two values are popped off the stack, added, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]-\f[R]
The top two values are popped off the stack, subtracted, and the result
is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]*\f[R]
The top two values are popped off the stack, multiplied, and the result
is pushed onto the stack.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The top two values are popped off the stack, divided, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]%\f[R]
The top two values are popped off the stack, remaindered, and the result
is pushed onto the stack.
.RS
.PP
Remaindering is equivalent to 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R], and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]\[ti]\f[R]
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 \f[B]x y / x y %\f[R] except that \f[B]x\f[R] and
\f[B]y\f[R] are only evaluated once.
.RS
.PP
The first value popped off of the stack must be non-zero.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
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.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
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.
.RE
.TP
\f[B]v\f[R]
The top value is popped off the stack, its square root is computed, and
the result is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The value popped off of the stack must be non-negative.
.RE
.TP
\f[B]_\f[R]
If this command \f[I]immediately\f[R] precedes a number (i.e., no spaces
or other commands), then that number is input as a negative number.
.RS
.PP
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 \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]b\f[R]
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.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]|\f[R]
The top three values are popped off the stack, a modular exponentiation
is computed, and the result is pushed onto the stack.
.RS
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]$\f[R]
The top value is popped off the stack and copied, and the copy is
truncated and pushed onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[at]\f[R]
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.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]H\f[R]
The top two values are popped off the stack, and the second is shifted
left (radix shifted right) to the value of the first.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]h\f[R]
The top two values are popped off the stack, and the second is shifted
right (radix shifted left) to the value of the first.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]G\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]N\f[R]
The top value is popped off of the stack, and if it a \f[B]0\f[R], a
\f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B](\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]{\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than or equal to the second,
or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B])\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]}\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than or equal to the
second, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]M\f[R]
The top two values are popped off of the stack.
If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack.
If either of them is zero, or both of them are, then a \f[B]0\f[R] is
pushed onto the stack.
.RS
.PP
This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]m\f[R]
The top two values are popped off of the stack.
If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the
stack.
If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack.
.RS
.PP
This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Pseudo-Random Number Generator
.PP
dc(1) has a built-in pseudo-random number generator.
These commands query the pseudo-random number generator.
(See Parameters for more information about the \f[B]seed\f[R] value that
controls the pseudo-random number generator.)
.PP
The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be
cryptographically secure.
.TP
\f[B]\[cq]\f[R]
Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see
the \f[B]LIMITS\f[R] section).
.RS
.PP
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[lq]\f[R]
Pops a value off of the stack, which is used as an \f[B]exclusive\f[R]
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 \f[B]RESET\f[R] section) while \f[B]seed\f[R]
remains unchanged.
If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is
honored by generating several pseudo-random integers, multiplying them
by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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 \f[B]seed\f[R], unless the
operand is \f[B]0\f[R] or \f[B]1\f[R].
In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R]
is \f[I]not\f[R] changed.
.RS
.PP
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Stack Control
.PP
These commands control the stack.
.TP
\f[B]c\f[R]
Removes all items from (\[lq]clears\[rq]) the stack.
.TP
\f[B]d\f[R]
Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes
the copy onto the stack.
.TP
\f[B]r\f[R]
Swaps (\[lq]reverses\[rq]) the two top items on the stack.
.TP
\f[B]R\f[R]
Pops (\[lq]removes\[rq]) the top value from the stack.
.SS Register Control
.PP
These commands control registers (see the \f[B]REGISTERS\f[R] section).
.TP
\f[B]s\f[R]\f[I]r\f[R]
Pops the value off the top of the stack and stores it into register
\f[I]r\f[R].
.TP
\f[B]l\f[R]\f[I]r\f[R]
Copies the value in register \f[I]r\f[R] and pushes it onto the stack.
This does not alter the contents of \f[I]r\f[R].
.TP
\f[B]S\f[R]\f[I]r\f[R]
Pops the value off the top of the (main) stack and pushes it onto the
stack of register \f[I]r\f[R].
The previous value of the register becomes inaccessible.
.TP
\f[B]L\f[R]\f[I]r\f[R]
Pops the value off the top of the stack for register \f[I]r\f[R] and
push it onto the main stack.
The previous value in the stack for register \f[I]r\f[R], if any, is now
accessible via the \f[B]l\f[R]\f[I]r\f[R] command.
.SS Parameters
.PP
These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R],
\f[B]scale\f[R], and \f[B]seed\f[R].
Also see the \f[B]SYNTAX\f[R] section.
.TP
\f[B]i\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R],
inclusive.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]o\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]obase\f[R], which must be between \f[B]0\f[R] and
\f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and
the \f[B]NUMBERS\f[R] section).
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]k\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]scale\f[R], which must be non-negative.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]j\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]seed\f[R].
The meaning of \f[B]seed\f[R] is dependent on the current pseudo-random
number generator but is guaranteed to not change except for new major
versions.
.RS
.PP
The \f[I]scale\f[R] and sign of the value may be significant.
.PP
If a previously used \f[B]seed\f[R] 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 \f[B]seed\f[R]
value was previously used.
.PP
The exact value assigned to \f[B]seed\f[R] is not guaranteed to be
returned if the \f[B]J\f[R] command is used.
However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both
values, when assigned to \f[B]seed\f[R], are guaranteed to produce the
same sequence of pseudo-random numbers.
This means that certain values assigned to \f[B]seed\f[R] will not
produce unique sequences of pseudo-random numbers.
.PP
There is no limit to the length (number of significant decimal digits)
or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]I\f[R]
Pushes the current value of \f[B]ibase\f[R] onto the main stack.
.TP
\f[B]O\f[R]
Pushes the current value of \f[B]obase\f[R] onto the main stack.
.TP
\f[B]K\f[R]
Pushes the current value of \f[B]scale\f[R] onto the main stack.
.TP
\f[B]J\f[R]
Pushes the current value of \f[B]seed\f[R] onto the main stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]T\f[R]
Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]U\f[R]
Pushes the maximum allowable value of \f[B]obase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]V\f[R]
Pushes the maximum allowable value of \f[B]scale\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]W\f[R]
Pushes the maximum (inclusive) integer that can be generated with the
\f[B]\[cq]\f[R] pseudo-random number generator command.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Strings
.PP
The following commands control strings.
.PP
dc(1) can work with both numbers and strings, and registers (see the
\f[B]REGISTERS\f[R] section) can hold both strings and numbers.
dc(1) always knows whether the contents of a register are a string or a
number.
.PP
While arithmetic operations have to have numbers, and will print an
error if given a string, other commands accept strings.
.PP
Strings can also be executed as macros.
For example, if the string \f[B][1pR]\f[R] is executed as a macro, then
the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be
printed with a newline after and then popped from the stack.
.TP
\f[B][\f[R]\f[I]characters\f[R]\f[B]]\f[R]
Makes a string containing \f[I]characters\f[R] and pushes it onto the
stack.
.RS
.PP
If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then
they must be balanced.
Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R])
character.
.PP
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.
.RE
.TP
\f[B]a\f[R]
The value on top of the stack is popped.
.RS
.PP
If it is a number, it is truncated and its absolute value is taken.
The result mod \f[B]256\f[R] is calculated.
If that result is \f[B]0\f[R], push an empty string; otherwise, push a
one-character string where the character is the result of the mod
interpreted as an ASCII character.
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]x\f[R]
Pops a value off of the top of the stack.
.RS
.PP
If it is a number, it is pushed back onto the stack.
.PP
If it is a string, it is executed as a macro.
.PP
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
For example, \f[B]0 1>a\f[R] will execute the contents of register
\f[B]a\f[R], and \f[B]1 0>a\f[R] will not.
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]
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
\f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]?\f[R]
Reads a line from the \f[B]stdin\f[R] and executes it.
This is to allow macros to request input from users.
.TP
\f[B]q\f[R]
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
\f[B]Q\f[R]
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.
.TP
\f[B],\f[R]
Pushes the depth of the execution stack onto the stack.
The execution stack is the stack of string executions.
The number that is pushed onto the stack is exactly as many as is needed
to make dc(1) exit with the \f[B]Q\f[R] command, so the sequence
\f[B],Q\f[R] will make dc(1) exit.
.SS Status
.PP
These commands query status of the stack or its top value.
.TP
\f[B]Z\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, calculates the number of significant decimal digits
it has and pushes the result.
It will push \f[B]1\f[R] if the argument is \f[B]0\f[R] with no decimal
places.
.PP
If it is a string, pushes the number of characters the string has.
.RE
.TP
\f[B]X\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, pushes the \f[I]scale\f[R] of the value onto the
stack.
.PP
If it is a string, pushes \f[B]0\f[R].
.RE
.TP
\f[B]z\f[R]
Pushes the current depth of the stack (before execution of this command)
onto the stack.
.TP
\f[B]y\f[R]\f[I]r\f[R]
Pushes the current stack depth of the register \f[I]r\f[R] onto the main
stack.
.RS
.PP
Because each register has a depth of \f[B]1\f[R] (with the value
\f[B]0\f[R] in the top item) when dc(1) starts, dc(1) requires that each
register\[cq]s stack must always have at least one item; dc(1) will give
an error and reset otherwise (see the \f[B]RESET\f[R] section).
This means that this command will never push \f[B]0\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Arrays
.PP
These commands manipulate arrays.
.TP
\f[B]:\f[R]\f[I]r\f[R]
Pops the top two values off of the stack.
The second value will be stored in the array \f[I]r\f[R] (see the
\f[B]REGISTERS\f[R] section), indexed by the first value.
.TP
\f[B];\f[R]\f[I]r\f[R]
Pops the value on top of the stack and uses it as an index into the
array \f[I]r\f[R].
The selected value is then pushed onto the stack.
.TP
\f[B]Y\f[R]\f[I]r\f[R]
Pushes the length of the array \f[I]r\f[R] onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
+.SS Global Settings
+.PP
+These commands retrieve global settings.
+These are the only commands that require multiple specific characters,
+and all of them begin with the letter \f[B]g\f[R].
+Only the characters below are allowed after the character \f[B]g\f[R];
+any other character produces a parse error (see the \f[B]ERRORS\f[R]
+section).
+.TP
+\f[B]gl\f[R]
+Pushes the line length set by \f[B]DC_LINE_LENGTH\f[R] (see the
+\f[B]ENVIRONMENT VARIABLES\f[R] section) onto the stack.
+.TP
+\f[B]gz\f[R]
+Pushes \f[B]0\f[R] onto the stack if the leading zero setting has not
+been enabled with the \f[B]-z\f[R] or \f[B]--leading-zeroes\f[R] options
+(see the \f[B]OPTIONS\f[R] section), non-zero otherwise.
.SH REGISTERS
.PP
Registers are names that can store strings, numbers, and arrays.
(Number/string registers do not interfere with array registers.)
.PP
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 (\f[B]0\f[R]) in
their stack, and it is a runtime error to attempt to pop that item off
of the register stack.
.PP
In non-extended register mode, a register name is just the single
character that follows any command that needs a register name.
The only exceptions are: a newline (\f[B]`\[rs]n'\f[R]) and a left
bracket (\f[B]`['\f[R]); it is a parse error for a newline or a left
bracket to be used as a register name.
.SS Extended Register Mode
.PP
Unlike most other dc(1) implentations, this dc(1) provides nearly
unlimited amounts of registers, if extended register mode is enabled.
.PP
If extended register mode is enabled (\f[B]-x\f[R] or
\f[B]--extended-register\f[R] command-line arguments are given), then
normal single character registers are used \f[I]unless\f[R] the
character immediately following a command that needs a register name is
a space (according to \f[B]isspace()\f[R]) and not a newline
(\f[B]`\[rs]n'\f[R]).
.PP
In that case, the register name is found according to the regex
\f[B][a-z][a-z0-9_]*\f[R] (like bc(1) identifiers), and it is a parse
error if the next non-space characters do not match that regex.
.SH RESET
.PP
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.
.PP
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 macros returned) is skipped.
.PP
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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.SH PERFORMANCE
.PP
Most dc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This dc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]DC_BASE_DIGS\f[R].
.PP
In addition, this dc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]DC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on dc(1):
.TP
\f[B]DC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] 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 \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]DC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]DC_BASE_DIGS\f[R].
.TP
\f[B]DC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]DC_BASE_POW\f[R].
.TP
\f[B]DC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]DC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command,
if dc(1).
Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]DC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
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
.PP
dc(1) recognizes the following environment variables:
.TP
\f[B]DC_ENV_ARGS\f[R]
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
\f[B]DC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 \f[B]-e\f[R] option to set
\f[B]scale\f[R] to a value other than \f[B]0\f[R].
.RS
.PP
The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`dc' file.dc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]DC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]DC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length,
including the backslash newline combo.
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]DC_SIGINT_RESET\f[R]
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because dc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes dc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then dc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use
TTY mode, and zero makes dc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a
prompt, and zero or a non-integer makes dc(1) not use a prompt.
If this environment variable does not exist and \f[B]DC_TTY_MODE\f[R]
does, then the value of the \f[B]DC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]DC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
dc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], 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, overflow when calculating the size of a number, and attempting
to use a non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift
(\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, and using a
token where it is invalid.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors (including attempting to execute
a number), and attempting an operation when the stack has too few
elements.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
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.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, dc(1)
always exits and returns \f[B]4\f[R], no matter what mode dc(1) is in.
.PP
The other statuses will only be returned when dc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
dc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, dc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
dc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]DC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, dc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]DC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, dc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]DC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then dc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]DC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]DC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]DC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]DC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]DC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause dc(1) to do one of two things.
.PP
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, dc(1) will exit.
.PP
However, if dc(1) is in interactive mode, and the
\f[B]DC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then dc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If dc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If dc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] 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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause dc(1) to clean up and
exit, and it uses the default handler for all other signals.
.SH SEE ALSO
.PP
bc(1)
.SH STANDARDS
.PP
The dc(1) utility operators are compliant with the operators in the
bc(1) IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHOR
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/dc/HN.1.md b/manuals/dc/HN.1.md
index caffefacce7d..70c962624833 100644
--- a/manuals/dc/HN.1.md
+++ b/manuals/dc/HN.1.md
@@ -1,1316 +1,1356 @@
# Name
dc - arbitrary-precision decimal reverse-Polish notation calculator
# SYNOPSIS
**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# 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.
If no files are given on the command-line, then dc(1) reads from **stdin** (see
the **STDIN** section). Otherwise, those files are processed, and dc(1) will
then exit.
If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
this dc(1) will always start with a **scale** of **10**.
# OPTIONS
The following are the options that dc(1) accepts.
**-h**, **-\-help**
: Prints a usage message and quits.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in dc(1). Most of those users
would want to put this option in **DC_ENV_ARGS**.
These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of dc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **?** command is used.
These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-x** **-\-extended-register**
: Enables extended register mode. See the *Extended Register Mode* subsection
of the **REGISTERS** section for more information.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files are given on the command-line and no files or expressions are given
by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
read from **stdin**.
However, there is a caveat to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
a string has been finished, but not ended. This means that, except for escaped
brackets, all brackets must be balanced before dc(1) parses and executes.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **dc >&-**, it will quit with an error. This
is done so that dc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This
is done so that dc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
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.
**ibase** is a register (see the **REGISTERS** section) that determines how to
interpret constant numbers. It is the "input" base, or the number base used for
interpreting input numbers. **ibase** is initially **10**. The max allowable
value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
The max allowable value for **ibase** can be queried in dc(1) programs with the
**T** command.
**obase** is a register (see the **REGISTERS** section) that determines how to
output results. It is the "output" base, or the number base used for outputting
numbers. **obase** is initially **10**. The max allowable value for **obase** is
**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
value for **obase** is **0**. If **obase** is **0**, values are output in
scientific notation, and if **obase** is **1**, values are output in engineering
notation. Otherwise, values are output in the specified base.
Outputting in scientific and engineering notations are **non-portable
extensions**.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a register (see the
**REGISTERS** section) that sets the precision of any operations (with
exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
allowable value for **scale** can be queried in dc(1) programs with the **V**
command.
**seed** is a register containing the current seed for the pseudo-random number
generator. If the current value of **seed** is queried and stored, then if it is
assigned to **seed** later, the pseudo-random number generator is guaranteed to
produce the same sequence of pseudo-random numbers that were generated after the
value of **seed** was first queried.
Multiple values assigned to **seed** can produce the same sequence of
pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not
guaranteed that querying **seed** immediately after will return the same value.
In addition, the value of **seed** will change after any call to the **'**
command or the **"** command that does not get receive a value of **0** or
**1**. The maximum integer returned by the **'** command can be queried with the
**W** command.
**Note**: The values returned by the pseudo-random number generator with the
**'** and **"** commands are guaranteed to **NOT** be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator. However,
they *are* guaranteed to be reproducible with identical **seed** values. This
means that the pseudo-random values from dc(1) should only be used where a
reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
use a non-seeded pseudo-random number generator.
The pseudo-random number generator, **seed**, and all associated operations are
**non-portable extensions**.
## Comments
Comments go from **#** until, and not including, the next newline. This is a
**non-portable extension**.
# NUMBERS
Numbers are strings made up of digits, uppercase letters up to **F**, and at
most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
current value of **ibase**, they are set to the value of the highest valid digit
in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **F** alone always equals decimal
**15**.
In addition, dc(1) accepts numbers in scientific notation. These have the form
**\e\**. The exponent (the portion after the **e**) must be
an integer. An example is **1.89237e9**, which is equal to **1892370000**.
Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For example,
if **ibase** is **16** and dc(1) is given the number string **FFeA**, the
resulting decimal number will be **2550000000000**, and if dc(1) is given the
number string **10e_4**, the resulting decimal number will be **0.0016**.
Accepting input as scientific notation is a **non-portable extension**.
# COMMANDS
The valid commands are listed below.
## Printing
These commands are used for printing.
Note that both scientific notation and engineering notation are available for
printing numbers. Scientific notation is activated by assigning **0** to
**obase** using **0o**, and engineering notation is activated by assigning **1**
to **obase** using **1o**. To deactivate them, just assign a different value to
**obase**.
Printing numbers in scientific notation and/or engineering notation is a
**non-portable extension**.
**p**
: Prints the value on top of the stack, whether number or string, and prints a
newline after.
This does not alter the stack.
**n**
: Prints the value on top of the stack, whether number or string, and pops it
off of the stack.
**P**
: Pops a value off the stack.
If the value is a number, it is truncated and the absolute value of the
result is printed as though **obase** is **256** and each digit is
interpreted as an 8-bit ASCII character, making it a byte stream.
If the value is a string, it is printed without a trailing newline.
This is a **non-portable extension**.
**f**
: Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
Users should use this command when they get lost.
## Arithmetic
These are the commands used for arithmetic.
**+**
: The top two values are popped off the stack, added, and the result is pushed
onto the stack. The *scale* of the result is equal to the max *scale* of
both operands.
**-**
: The top two values are popped off the stack, subtracted, and the result is
pushed onto the stack. The *scale* of the result is equal to the max
*scale* of both operands.
**\***
: The top two values are popped off the stack, multiplied, and the result is
pushed onto the stack. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result
is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The top two values are popped off the stack, divided, and the result is
pushed onto the stack. The *scale* of the result is equal to **scale**.
The first value popped off of the stack must be non-zero.
**%**
: The top two values are popped off the stack, remaindered, and the result is
pushed onto the stack.
Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The first value popped off of the stack must be non-zero.
**~**
: 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 **x y / x y %** except that **x** and **y** are only
evaluated once.
The first value popped off of the stack must be non-zero.
This is a **non-portable extension**.
**\^**
: 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. The *scale* of
the result is equal to **scale**.
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.
**v**
: The top value is popped off the stack, its square root is computed, and the
result is pushed onto the stack. The *scale* of the result is equal to
**scale**.
The value popped off of the stack must be non-negative.
**\_**
: If this command *immediately* precedes a number (i.e., no spaces or other
commands), then that number is input as a negative number.
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
**non-portable extension**.
**b**
: 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.
This is a **non-portable extension**.
**|**
: The top three values are popped off the stack, a modular exponentiation is
computed, and the result is pushed onto the stack.
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.
This is a **non-portable extension**.
**\$**
: The top value is popped off the stack and copied, and the copy is truncated
and pushed onto the stack.
This is a **non-portable extension**.
**\@**
: 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.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**H**
: The top two values are popped off the stack, and the second is shifted left
(radix shifted right) to the value of the first.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**h**
: The top two values are popped off the stack, and the second is shifted right
(radix shifted left) to the value of the first.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**G**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if they are equal, or **0** otherwise.
This is a **non-portable extension**.
**N**
: The top value is popped off of the stack, and if it a **0**, a **1** is
pushed; otherwise, a **0** is pushed.
This is a **non-portable extension**.
**(**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than the second, or **0** otherwise.
This is a **non-portable extension**.
**{**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than or equal to the second, or **0**
otherwise.
This is a **non-portable extension**.
**)**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than the second, or **0** otherwise.
This is a **non-portable extension**.
**}**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than or equal to the second, or
**0** otherwise.
This is a **non-portable extension**.
**M**
: The top two values are popped off of the stack. If they are both non-zero, a
**1** is pushed onto the stack. If either of them is zero, or both of them
are, then a **0** is pushed onto the stack.
This is like the **&&** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
**m**
: The top two values are popped off of the stack. If at least one of them is
non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
**0** is pushed onto the stack.
This is like the **||** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
## Pseudo-Random Number Generator
dc(1) has a built-in pseudo-random number generator. These commands query the
pseudo-random number generator. (See Parameters for more information about the
**seed** value that controls the pseudo-random number generator.)
The pseudo-random number generator is guaranteed to **NOT** be
cryptographically secure.
**'**
: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the
**LIMITS** section).
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
This is a **non-portable extension**.
**"**
: Pops a value off of the stack, which is used as an **exclusive** 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) while **seed** remains unchanged. If the bound is larger than
**DC_RAND_MAX**, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
**DC_RAND_MAX+1**, 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 **seed**, unless the operand is **0** or **1**. In that
case, **0** is pushed onto the stack, and **seed** is *not* changed.
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
This is a **non-portable extension**.
## Stack Control
These commands control the stack.
**c**
: Removes all items from ("clears") the stack.
**d**
: Copies the item on top of the stack ("duplicates") and pushes the copy onto
the stack.
**r**
: Swaps ("reverses") the two top items on the stack.
**R**
: Pops ("removes") the top value from the stack.
## Register Control
These commands control registers (see the **REGISTERS** section).
**s**_r_
: Pops the value off the top of the stack and stores it into register *r*.
**l**_r_
: Copies the value in register *r* and pushes it onto the stack. This does not
alter the contents of *r*.
**S**_r_
: Pops the value off the top of the (main) stack and pushes it onto the stack
of register *r*. The previous value of the register becomes inaccessible.
**L**_r_
: Pops the value off the top of the stack for register *r* and push it onto
the main stack. The previous value in the stack for register *r*, if any, is
now accessible via the **l**_r_ command.
## Parameters
These commands control the values of **ibase**, **obase**, **scale**, and
**seed**. Also see the **SYNTAX** section.
**i**
: Pops the value off of the top of the stack and uses it to set **ibase**,
which must be between **2** and **16**, inclusive.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**o**
: Pops the value off of the top of the stack and uses it to set **obase**,
which must be between **0** and **DC_BASE_MAX**, inclusive (see the
**LIMITS** section and the **NUMBERS** section).
If the value on top of the stack has any *scale*, the *scale* is ignored.
**k**
: Pops the value off of the top of the stack and uses it to set **scale**,
which must be non-negative.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**j**
: Pops the value off of the top of the stack and uses it to set **seed**. The
meaning of **seed** is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major versions.
The *scale* and sign of the value may be significant.
If a previously used **seed** 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 **seed** value was previously used.
The exact value assigned to **seed** is not guaranteed to be returned if the
**J** command is used. However, if **seed** *does* return a different value,
both values, when assigned to **seed**, are guaranteed to produce the same
sequence of pseudo-random numbers. This means that certain values assigned
to **seed** will not produce unique sequences of pseudo-random numbers.
There is no limit to the length (number of significant decimal digits) or
*scale* of the value that can be assigned to **seed**.
This is a **non-portable extension**.
**I**
: Pushes the current value of **ibase** onto the main stack.
**O**
: Pushes the current value of **obase** onto the main stack.
**K**
: Pushes the current value of **scale** onto the main stack.
**J**
: Pushes the current value of **seed** onto the main stack.
This is a **non-portable extension**.
**T**
: Pushes the maximum allowable value of **ibase** onto the main stack.
This is a **non-portable extension**.
**U**
: Pushes the maximum allowable value of **obase** onto the main stack.
This is a **non-portable extension**.
**V**
: Pushes the maximum allowable value of **scale** onto the main stack.
This is a **non-portable extension**.
**W**
: Pushes the maximum (inclusive) integer that can be generated with the **'**
pseudo-random number generator command.
This is a **non-portable extension**.
## Strings
The following commands control strings.
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.
While arithmetic operations have to have numbers, and will print an error if
given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string **[1pR]** is
executed as a macro, then the code **1pR** is executed, meaning that the **1**
will be printed with a newline after and then popped from the stack.
**\[**_characters_**\]**
: Makes a string containing *characters* and pushes it onto the stack.
If there are brackets (**\[** and **\]**) in the string, then they must be
balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
character.
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.
**a**
: The value on top of the stack is popped.
If it is a number, it is truncated and its absolute value is taken. The
result mod **256** is calculated. If that result is **0**, push an empty
string; otherwise, push a one-character string where the character is the
result of the mod interpreted as an ASCII character.
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.
This is a **non-portable extension**.
**x**
: Pops a value off of the top of the stack.
If it is a number, it is pushed back onto the stack.
If it is a string, it is executed as a macro.
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
**\>**_r_
: 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
*r* are executed.
For example, **0 1>a** will execute the contents of register **a**, and
**1 0>a** will not.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\>**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**\<**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\<**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**=**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!=**_r_
: 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
*r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**?**
: Reads a line from the **stdin** and executes it. This is to allow macros to
request input from users.
**q**
: 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.
**Q**
: 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.
**,**
: Pushes the depth of the execution stack onto the stack. The execution stack
is the stack of string executions. The number that is pushed onto the stack
is exactly as many as is needed to make dc(1) exit with the **Q** command,
so the sequence **,Q** will make dc(1) exit.
## Status
These commands query status of the stack or its top value.
**Z**
: Pops a value off of the stack.
If it is a number, calculates the number of significant decimal digits it
has and pushes the result. It will push **1** if the argument is **0** with
no decimal places.
If it is a string, pushes the number of characters the string has.
**X**
: Pops a value off of the stack.
If it is a number, pushes the *scale* of the value onto the stack.
If it is a string, pushes **0**.
**z**
: Pushes the current depth of the stack (before execution of this command)
onto the stack.
**y**_r_
: Pushes the current stack depth of the register *r* onto the main stack.
Because each register has a depth of **1** (with the value **0** in the top
item) when dc(1) starts, dc(1) requires that each register's stack must
always have at least one item; dc(1) will give an error and reset otherwise
(see the **RESET** section). This means that this command will never push
**0**.
This is a **non-portable extension**.
## Arrays
These commands manipulate arrays.
**:**_r_
: Pops the top two values off of the stack. The second value will be stored in
the array *r* (see the **REGISTERS** section), indexed by the first value.
**;**_r_
: Pops the value on top of the stack and uses it as an index into the array
*r*. The selected value is then pushed onto the stack.
**Y**_r_
: Pushes the length of the array *r* onto the stack.
This is a **non-portable extension**.
+## Global Settings
+
+These commands retrieve global settings. These are the only commands that
+require multiple specific characters, and all of them begin with the letter
+**g**. Only the characters below are allowed after the character **g**; any
+other character produces a parse error (see the **ERRORS** section).
+
+**gl**
+
+: Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT
+ VARIABLES** section) onto the stack.
+
+**gz**
+
+: Pushes **0** onto the stack if the leading zero setting has not been enabled
+ with the **-z** or **-\-leading-zeroes** options (see the **OPTIONS**
+ section), non-zero otherwise.
+
# REGISTERS
Registers are names that can store strings, numbers, and arrays. (Number/string
registers do not interfere with array registers.)
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
(**0**) in their stack, and it is a runtime error to attempt to pop that item
off of the register stack.
In non-extended register mode, a register name is just the single character that
follows any command that needs a register name. The only exceptions are: a
newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
newline or a left bracket to be used as a register name.
## Extended Register Mode
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
amounts of registers, if extended register mode is enabled.
If extended register mode is enabled (**-x** or **-\-extended-register**
command-line arguments are given), then normal single character registers are
used *unless* the character immediately following a command that needs a
register name is a space (according to **isspace()**) and not a newline
(**'\\n'**).
In that case, the register name is found according to the regex
**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
the next non-space characters do not match that regex.
# 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.
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
macros returned) is skipped.
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.
# PERFORMANCE
Most dc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This dc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**DC_BASE_DIGS**.
In addition, this dc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **DC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on dc(1):
**DC_LONG_BIT**
: The number of bits in the **long** 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).
**DC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **DC_LONG_BIT**.
**DC_BASE_POW**
: The max decimal number that each large integer can store (see
**DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
**DC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **DC_LONG_BIT**.
**DC_BASE_MAX**
: The maximum output base. Set at **DC_BASE_POW**.
**DC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**DC_SCALE_MAX**
: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
**DC_STRING_MAX**
: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
**DC_NAME_MAX**
: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
**DC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
**DC_RAND_MAX**
: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set
at **2\^DC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**DC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
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.
# ENVIRONMENT VARIABLES
dc(1) recognizes the following environment variables:
**DC_ENV_ARGS**
: 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 **DC_ENV_ARGS** 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 **-e** option to set **scale** to a value other than **0**.
The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
**"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'dc' file.dc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **DC_ENV_ARGS** 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.
**DC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
lines to that length, including the backslash newline combo. The default
line length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**DC_SIGINT_RESET**
: If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because dc(1) exits on
**SIGINT** when not in interactive mode.
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1) reset
on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
environment variable exists and is *not* an integer, then dc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use TTY
mode, and zero makes dc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a prompt,
and zero or a non-integer makes dc(1) not use a prompt. If this environment
variable does not exist and **DC_TTY_MODE** does, then the value of the
**DC_TTY_MODE** environment variable is used.
This environment variable and the **DC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
dc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, 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, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**), places (**\@**), left shift (**H**), and right shift (**h**)
operators.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, and using a token where it is
invalid.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors (including
attempting to execute a number), and attempting an operation when the stack
has too few elements.
**4**
: A fatal error occurred.
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.
The exit status **4** is special; when a fatal error occurs, dc(1) always exits
and returns **4**, no matter what mode dc(1) is in.
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
**-i** flag or **-\-interactive** option.
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 **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **DC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **DC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
mode on.
If the environment variable **DC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **DC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause dc(1) to do one of two things.
If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, dc(1) will
exit.
However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
default is an integer and non-zero, then dc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If dc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If dc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** 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.
**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
default handler for all other signals.
# SEE ALSO
bc(1)
# STANDARDS
The dc(1) utility operators are compliant with the operators in the bc(1)
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHOR
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/manuals/dc/N.1 b/manuals/dc/N.1
index 30cfcadc7a07..c5cc36ac9b10 100644
--- a/manuals/dc/N.1
+++ b/manuals/dc/N.1
@@ -1,1500 +1,1545 @@
.\"
.\" SPDX-License-Identifier: BSD-2-Clause
.\"
.\" Copyright (c) 2018-2021 Gavin D. Howard and contributors.
.\"
.\" 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.
.\"
.TH "DC" "1" "June 2021" "Gavin D. Howard" "General Commands Manual"
.SH Name
.PP
dc - arbitrary-precision decimal reverse-Polish notation calculator
.SH SYNOPSIS
.PP
\f[B]dc\f[R] [\f[B]-hiPRvVx\f[R]] [\f[B]--version\f[R]]
[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]]
[\f[B]--no-read-prompt\f[R]] [\f[B]--extended-register\f[R]]
[\f[B]-e\f[R] \f[I]expr\f[R]]
[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R]
\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...]
[\f[I]file\f[R]\&...]
.SH DESCRIPTION
.PP
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.
.PP
If no files are given on the command-line, then dc(1) reads from
\f[B]stdin\f[R] (see the \f[B]STDIN\f[R] section).
Otherwise, those files are processed, and dc(1) will then exit.
.PP
If a user wants to set up a standard environment, they can use
\f[B]DC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
For example, if a user wants the \f[B]scale\f[R] always set to
\f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R],
and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R].
.SH OPTIONS
.PP
The following are the options that dc(1) accepts.
.TP
\f[B]-h\f[R], \f[B]--help\f[R]
Prints a usage message and quits.
.TP
\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R]
Print the version information (copyright header) and exit.
.TP
\f[B]-i\f[R], \f[B]--interactive\f[R]
Forces interactive mode.
(See the \f[B]INTERACTIVE MODE\f[R] section.)
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-L\f[R], \f[B]--no-line-length\f[R]
+Disables line length checking and prints numbers without backslashes and
+newlines.
+In other words, this option sets \f[B]BC_LINE_LENGTH\f[R] to \f[B]0\f[R]
+(see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
+.RS
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-P\f[R], \f[B]--no-prompt\f[R]
Disables the prompt in TTY mode.
(The prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]DC_ENV_ARGS\f[R].
.RS
.PP
These options override the \f[B]DC_PROMPT\f[R] and \f[B]DC_TTY_MODE\f[R]
environment variables (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-R\f[R], \f[B]--no-read-prompt\f[R]
Disables the read prompt in TTY mode.
(The read prompt is only enabled in TTY mode.
See the \f[B]TTY MODE\f[R] section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1).
Most of those users would want to put this option in
\f[B]BC_ENV_ARGS\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
This option is also useful in hash bang lines of dc(1) scripts that
prompt for user input.
.RS
.PP
This option does not disable the regular prompt because the read prompt
is only used when the \f[B]?\f[R] command is used.
.PP
These options \f[I]do\f[R] override the \f[B]DC_PROMPT\f[R] and
\f[B]DC_TTY_MODE\f[R] environment variables (see the \f[B]ENVIRONMENT
VARIABLES\f[R] section), but only for the read prompt.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-x\f[R] \f[B]--extended-register\f[R]
Enables extended register mode.
See the \f[I]Extended Register Mode\f[R] subsection of the
\f[B]REGISTERS\f[R] section for more information.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
+\f[B]-z\f[R], \f[B]--leading-zeroes\f[R]
+Makes bc(1) print all numbers greater than \f[B]-1\f[R] and less than
+\f[B]1\f[R], and not equal to \f[B]0\f[R], with a leading zero.
+.RS
+.PP
+This can be set for individual numbers with the \f[B]plz(x)\f[R],
+plznl(x)**, \f[B]pnlz(x)\f[R], and \f[B]pnlznl(x)\f[R] functions in the
+extended math library (see the \f[B]LIBRARY\f[R] section).
+.PP
+This is a \f[B]non-portable extension\f[R].
+.RE
+.TP
\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R]
Evaluates \f[I]expr\f[R].
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.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in
\f[B]DC_ENV_ARGS\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R]
Reads in \f[I]file\f[R] and evaluates it, line by line, as though it
were read through \f[B]stdin\f[R].
If expressions are also given (see above), the expressions are evaluated
in the order given.
.RS
.PP
If this option is given on the command-line (i.e., not in
\f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section),
then after processing all expressions and files, dc(1) will exit, unless
\f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to
\f[B]-f\f[R] or \f[B]--file\f[R].
However, if any other \f[B]-e\f[R], \f[B]--expression\f[R],
\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after
\f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and
exit.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.PP
All long options are \f[B]non-portable extensions\f[R].
.SH STDIN
.PP
If no files are given on the command-line and no files or expressions
are given by the \f[B]-f\f[R], \f[B]--file\f[R], \f[B]-e\f[R], or
\f[B]--expression\f[R] options, then dc(1) read from \f[B]stdin\f[R].
.PP
However, there is a caveat to this.
.PP
First, \f[B]stdin\f[R] is evaluated a line at a time.
The only exception to this is if a string has been finished, but not
ended.
This means that, except for escaped brackets, all brackets must be
balanced before dc(1) parses and executes.
.SH STDOUT
.PP
Any non-error output is written to \f[B]stdout\f[R].
In addition, if history (see the \f[B]HISTORY\f[R] section) and the
prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output
to \f[B]stdout\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in
\f[B]dc >&-\f[R], it will quit with an error.
This is done so that dc(1) can report problems when \f[B]stdout\f[R] is
redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stdout\f[R] to \f[B]/dev/null\f[R].
.SH STDERR
.PP
Any error output is written to \f[B]stderr\f[R].
.PP
\f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will
issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot
write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in
\f[B]dc 2>&-\f[R], it will quit with an error.
This is done so that dc(1) can exit with an error code when
\f[B]stderr\f[R] is redirected to a file.
.PP
If there are scripts that depend on the behavior of other dc(1)
implementations, it is recommended that those scripts be changed to
redirect \f[B]stderr\f[R] to \f[B]/dev/null\f[R].
.SH SYNTAX
.PP
Each item in the input source code, either a number (see the
\f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R]
section), is processed and executed, in order.
Input is processed immediately when entered.
.PP
\f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to interpret constant numbers.
It is the \[lq]input\[rq] base, or the number base used for interpreting
input numbers.
\f[B]ibase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R].
The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R].
The max allowable value for \f[B]ibase\f[R] can be queried in dc(1)
programs with the \f[B]T\f[R] command.
.PP
\f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that
determines how to output results.
It is the \[lq]output\[rq] base, or the number base used for outputting
numbers.
\f[B]obase\f[R] is initially \f[B]10\f[R].
The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and
can be queried with the \f[B]U\f[R] command.
The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R].
If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific
notation, and if \f[B]obase\f[R] is \f[B]1\f[R], values are output in
engineering notation.
Otherwise, values are output in the specified base.
.PP
Outputting in scientific and engineering notations are \f[B]non-portable
extensions\f[R].
.PP
The \f[I]scale\f[R] of an expression is the number of digits in the
result of the expression right of the decimal point, and \f[B]scale\f[R]
is a register (see the \f[B]REGISTERS\f[R] section) that sets the
precision of any operations (with exceptions).
\f[B]scale\f[R] is initially \f[B]0\f[R].
\f[B]scale\f[R] cannot be negative.
The max allowable value for \f[B]scale\f[R] can be queried in dc(1)
programs with the \f[B]V\f[R] command.
.PP
\f[B]seed\f[R] is a register containing the current seed for the
pseudo-random number generator.
If the current value of \f[B]seed\f[R] is queried and stored, then if it
is assigned to \f[B]seed\f[R] later, the pseudo-random number generator
is guaranteed to produce the same sequence of pseudo-random numbers that
were generated after the value of \f[B]seed\f[R] was first queried.
.PP
Multiple values assigned to \f[B]seed\f[R] can produce the same sequence
of pseudo-random numbers.
Likewise, when a value is assigned to \f[B]seed\f[R], it is not
guaranteed that querying \f[B]seed\f[R] immediately after will return
the same value.
In addition, the value of \f[B]seed\f[R] will change after any call to
the \f[B]\[cq]\f[R] command or the \f[B]\[lq]\f[R] command that does not
get receive a value of \f[B]0\f[R] or \f[B]1\f[R].
The maximum integer returned by the \f[B]\[cq]\f[R] command can be
queried with the \f[B]W\f[R] command.
.PP
\f[B]Note\f[R]: The values returned by the pseudo-random number
generator with the \f[B]\[cq]\f[R] and \f[B]\[lq]\f[R] commands are
guaranteed to \f[B]NOT\f[R] be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator.
However, they \f[I]are\f[R] guaranteed to be reproducible with identical
\f[B]seed\f[R] values.
This means that the pseudo-random values from dc(1) should only be used
where a reproducible stream of pseudo-random numbers is
\f[I]ESSENTIAL\f[R].
In any other case, use a non-seeded pseudo-random number generator.
.PP
The pseudo-random number generator, \f[B]seed\f[R], and all associated
operations are \f[B]non-portable extensions\f[R].
.SS Comments
.PP
Comments go from \f[B]#\f[R] until, and not including, the next newline.
This is a \f[B]non-portable extension\f[R].
.SH NUMBERS
.PP
Numbers are strings made up of digits, uppercase letters up to
\f[B]F\f[R], and at most \f[B]1\f[R] period for a radix.
Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits.
Uppercase letters are equal to \f[B]9\f[R] + their position in the
alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]).
If a digit or letter makes no sense with the current value of
\f[B]ibase\f[R], they are set to the value of the highest valid digit in
\f[B]ibase\f[R].
.PP
Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that
they would have if they were valid digits, regardless of the value of
\f[B]ibase\f[R].
This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and
\f[B]F\f[R] alone always equals decimal \f[B]15\f[R].
.PP
In addition, dc(1) accepts numbers in scientific notation.
These have the form \f[B]e\f[R].
The exponent (the portion after the \f[B]e\f[R]) must be an integer.
An example is \f[B]1.89237e9\f[R], which is equal to
\f[B]1892370000\f[R].
Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to
\f[B]0.0042890\f[R].
.PP
\f[B]WARNING\f[R]: Both the number and the exponent in scientific
notation are interpreted according to the current \f[B]ibase\f[R], but
the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless
of the current \f[B]ibase\f[R].
For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the
number string \f[B]FFeA\f[R], the resulting decimal number will be
\f[B]2550000000000\f[R], and if dc(1) is given the number string
\f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R].
.PP
Accepting input as scientific notation is a \f[B]non-portable
extension\f[R].
.SH COMMANDS
.PP
The valid commands are listed below.
.SS Printing
.PP
These commands are used for printing.
.PP
Note that both scientific notation and engineering notation are
available for printing numbers.
Scientific notation is activated by assigning \f[B]0\f[R] to
\f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is
activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using
\f[B]1o\f[R].
To deactivate them, just assign a different value to \f[B]obase\f[R].
.PP
Printing numbers in scientific notation and/or engineering notation is a
\f[B]non-portable extension\f[R].
.TP
\f[B]p\f[R]
Prints the value on top of the stack, whether number or string, and
prints a newline after.
.RS
.PP
This does not alter the stack.
.RE
.TP
\f[B]n\f[R]
Prints the value on top of the stack, whether number or string, and pops
it off of the stack.
.TP
\f[B]P\f[R]
Pops a value off the stack.
.RS
.PP
If the value is a number, it is truncated and the absolute value of the
result is printed as though \f[B]obase\f[R] is \f[B]256\f[R] and each
digit is interpreted as an 8-bit ASCII character, making it a byte
stream.
.PP
If the value is a string, it is printed without a trailing newline.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]f\f[R]
Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
.RS
.PP
Users should use this command when they get lost.
.RE
.SS Arithmetic
.PP
These are the commands used for arithmetic.
.TP
\f[B]+\f[R]
The top two values are popped off the stack, added, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]-\f[R]
The top two values are popped off the stack, subtracted, and the result
is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of
both operands.
.TP
\f[B]*\f[R]
The top two values are popped off the stack, multiplied, and the result
is pushed onto the stack.
If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and
\f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the
\f[I]scale\f[R] of the result is equal to
\f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and
\f[B]max()\f[R] return the obvious values.
.TP
\f[B]/\f[R]
The top two values are popped off the stack, divided, and the result is
pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]%\f[R]
The top two values are popped off the stack, remaindered, and the result
is pushed onto the stack.
.RS
.PP
Remaindering is equivalent to 1) Computing \f[B]a/b\f[R] to current
\f[B]scale\f[R], and 2) Using the result of step 1 to calculate
\f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R]
\f[B]max(scale+scale(b),scale(a))\f[R].
.PP
The first value popped off of the stack must be non-zero.
.RE
.TP
\f[B]\[ti]\f[R]
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 \f[B]x y / x y %\f[R] except that \f[B]x\f[R] and
\f[B]y\f[R] are only evaluated once.
.RS
.PP
The first value popped off of the stack must be non-zero.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[ha]\f[R]
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.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
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.
.RE
.TP
\f[B]v\f[R]
The top value is popped off the stack, its square root is computed, and
the result is pushed onto the stack.
The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R].
.RS
.PP
The value popped off of the stack must be non-negative.
.RE
.TP
\f[B]_\f[R]
If this command \f[I]immediately\f[R] precedes a number (i.e., no spaces
or other commands), then that number is input as a negative number.
.RS
.PP
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 \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]b\f[R]
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.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]|\f[R]
The top three values are popped off the stack, a modular exponentiation
is computed, and the result is pushed onto the stack.
.RS
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]$\f[R]
The top value is popped off the stack and copied, and the copy is
truncated and pushed onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[at]\f[R]
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.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]H\f[R]
The top two values are popped off the stack, and the second is shifted
left (radix shifted right) to the value of the first.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]h\f[R]
The top two values are popped off the stack, and the second is shifted
right (radix shifted left) to the value of the first.
.RS
.PP
The first value popped off of the stack must be an integer and
non-negative.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]G\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]N\f[R]
The top value is popped off of the stack, and if it a \f[B]0\f[R], a
\f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B](\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]{\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is less than or equal to the second,
or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B])\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than the second, or
\f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]}\f[R]
The top two values are popped off of the stack, they are compared, and a
\f[B]1\f[R] is pushed if the first is greater than or equal to the
second, or \f[B]0\f[R] otherwise.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]M\f[R]
The top two values are popped off of the stack.
If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack.
If either of them is zero, or both of them are, then a \f[B]0\f[R] is
pushed onto the stack.
.RS
.PP
This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]m\f[R]
The top two values are popped off of the stack.
If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the
stack.
If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack.
.RS
.PP
This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R]
a short-circuit operator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Pseudo-Random Number Generator
.PP
dc(1) has a built-in pseudo-random number generator.
These commands query the pseudo-random number generator.
(See Parameters for more information about the \f[B]seed\f[R] value that
controls the pseudo-random number generator.)
.PP
The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be
cryptographically secure.
.TP
\f[B]\[cq]\f[R]
Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see
the \f[B]LIMITS\f[R] section).
.RS
.PP
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]\[lq]\f[R]
Pops a value off of the stack, which is used as an \f[B]exclusive\f[R]
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 \f[B]RESET\f[R] section) while \f[B]seed\f[R]
remains unchanged.
If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is
honored by generating several pseudo-random integers, multiplying them
by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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 \f[B]seed\f[R], unless the
operand is \f[B]0\f[R] or \f[B]1\f[R].
In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R]
is \f[I]not\f[R] changed.
.RS
.PP
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Stack Control
.PP
These commands control the stack.
.TP
\f[B]c\f[R]
Removes all items from (\[lq]clears\[rq]) the stack.
.TP
\f[B]d\f[R]
Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes
the copy onto the stack.
.TP
\f[B]r\f[R]
Swaps (\[lq]reverses\[rq]) the two top items on the stack.
.TP
\f[B]R\f[R]
Pops (\[lq]removes\[rq]) the top value from the stack.
.SS Register Control
.PP
These commands control registers (see the \f[B]REGISTERS\f[R] section).
.TP
\f[B]s\f[R]\f[I]r\f[R]
Pops the value off the top of the stack and stores it into register
\f[I]r\f[R].
.TP
\f[B]l\f[R]\f[I]r\f[R]
Copies the value in register \f[I]r\f[R] and pushes it onto the stack.
This does not alter the contents of \f[I]r\f[R].
.TP
\f[B]S\f[R]\f[I]r\f[R]
Pops the value off the top of the (main) stack and pushes it onto the
stack of register \f[I]r\f[R].
The previous value of the register becomes inaccessible.
.TP
\f[B]L\f[R]\f[I]r\f[R]
Pops the value off the top of the stack for register \f[I]r\f[R] and
push it onto the main stack.
The previous value in the stack for register \f[I]r\f[R], if any, is now
accessible via the \f[B]l\f[R]\f[I]r\f[R] command.
.SS Parameters
.PP
These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R],
\f[B]scale\f[R], and \f[B]seed\f[R].
Also see the \f[B]SYNTAX\f[R] section.
.TP
\f[B]i\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R],
inclusive.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]o\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]obase\f[R], which must be between \f[B]0\f[R] and
\f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and
the \f[B]NUMBERS\f[R] section).
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]k\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]scale\f[R], which must be non-negative.
.RS
.PP
If the value on top of the stack has any \f[I]scale\f[R], the
\f[I]scale\f[R] is ignored.
.RE
.TP
\f[B]j\f[R]
Pops the value off of the top of the stack and uses it to set
\f[B]seed\f[R].
The meaning of \f[B]seed\f[R] is dependent on the current pseudo-random
number generator but is guaranteed to not change except for new major
versions.
.RS
.PP
The \f[I]scale\f[R] and sign of the value may be significant.
.PP
If a previously used \f[B]seed\f[R] 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 \f[B]seed\f[R]
value was previously used.
.PP
The exact value assigned to \f[B]seed\f[R] is not guaranteed to be
returned if the \f[B]J\f[R] command is used.
However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both
values, when assigned to \f[B]seed\f[R], are guaranteed to produce the
same sequence of pseudo-random numbers.
This means that certain values assigned to \f[B]seed\f[R] will not
produce unique sequences of pseudo-random numbers.
.PP
There is no limit to the length (number of significant decimal digits)
or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]I\f[R]
Pushes the current value of \f[B]ibase\f[R] onto the main stack.
.TP
\f[B]O\f[R]
Pushes the current value of \f[B]obase\f[R] onto the main stack.
.TP
\f[B]K\f[R]
Pushes the current value of \f[B]scale\f[R] onto the main stack.
.TP
\f[B]J\f[R]
Pushes the current value of \f[B]seed\f[R] onto the main stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]T\f[R]
Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]U\f[R]
Pushes the maximum allowable value of \f[B]obase\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]V\f[R]
Pushes the maximum allowable value of \f[B]scale\f[R] onto the main
stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]W\f[R]
Pushes the maximum (inclusive) integer that can be generated with the
\f[B]\[cq]\f[R] pseudo-random number generator command.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Strings
.PP
The following commands control strings.
.PP
dc(1) can work with both numbers and strings, and registers (see the
\f[B]REGISTERS\f[R] section) can hold both strings and numbers.
dc(1) always knows whether the contents of a register are a string or a
number.
.PP
While arithmetic operations have to have numbers, and will print an
error if given a string, other commands accept strings.
.PP
Strings can also be executed as macros.
For example, if the string \f[B][1pR]\f[R] is executed as a macro, then
the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be
printed with a newline after and then popped from the stack.
.TP
\f[B][\f[R]\f[I]characters\f[R]\f[B]]\f[R]
Makes a string containing \f[I]characters\f[R] and pushes it onto the
stack.
.RS
.PP
If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then
they must be balanced.
Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R])
character.
.PP
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.
.RE
.TP
\f[B]a\f[R]
The value on top of the stack is popped.
.RS
.PP
If it is a number, it is truncated and its absolute value is taken.
The result mod \f[B]256\f[R] is calculated.
If that result is \f[B]0\f[R], push an empty string; otherwise, push a
one-character string where the character is the result of the mod
interpreted as an ASCII character.
.PP
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.
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]x\f[R]
Pops a value off of the top of the stack.
.RS
.PP
If it is a number, it is pushed back onto the stack.
.PP
If it is a string, it is executed as a macro.
.PP
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
For example, \f[B]0 1>a\f[R] will execute the contents of register
\f[B]a\f[R], and \f[B]1 0>a\f[R] will not.
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]
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
\f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]
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 \f[I]r\f[R] are executed.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.RE
.TP
\f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R]
Like the above, but will execute register \f[I]s\f[R] if the comparison
fails.
.RS
.PP
If either or both of the values are not numbers, dc(1) will raise an
error and reset (see the \f[B]RESET\f[R] section).
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.TP
\f[B]?\f[R]
Reads a line from the \f[B]stdin\f[R] and executes it.
This is to allow macros to request input from users.
.TP
\f[B]q\f[R]
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
\f[B]Q\f[R]
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.
.TP
\f[B],\f[R]
Pushes the depth of the execution stack onto the stack.
The execution stack is the stack of string executions.
The number that is pushed onto the stack is exactly as many as is needed
to make dc(1) exit with the \f[B]Q\f[R] command, so the sequence
\f[B],Q\f[R] will make dc(1) exit.
.SS Status
.PP
These commands query status of the stack or its top value.
.TP
\f[B]Z\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, calculates the number of significant decimal digits
it has and pushes the result.
It will push \f[B]1\f[R] if the argument is \f[B]0\f[R] with no decimal
places.
.PP
If it is a string, pushes the number of characters the string has.
.RE
.TP
\f[B]X\f[R]
Pops a value off of the stack.
.RS
.PP
If it is a number, pushes the \f[I]scale\f[R] of the value onto the
stack.
.PP
If it is a string, pushes \f[B]0\f[R].
.RE
.TP
\f[B]z\f[R]
Pushes the current depth of the stack (before execution of this command)
onto the stack.
.TP
\f[B]y\f[R]\f[I]r\f[R]
Pushes the current stack depth of the register \f[I]r\f[R] onto the main
stack.
.RS
.PP
Because each register has a depth of \f[B]1\f[R] (with the value
\f[B]0\f[R] in the top item) when dc(1) starts, dc(1) requires that each
register\[cq]s stack must always have at least one item; dc(1) will give
an error and reset otherwise (see the \f[B]RESET\f[R] section).
This means that this command will never push \f[B]0\f[R].
.PP
This is a \f[B]non-portable extension\f[R].
.RE
.SS Arrays
.PP
These commands manipulate arrays.
.TP
\f[B]:\f[R]\f[I]r\f[R]
Pops the top two values off of the stack.
The second value will be stored in the array \f[I]r\f[R] (see the
\f[B]REGISTERS\f[R] section), indexed by the first value.
.TP
\f[B];\f[R]\f[I]r\f[R]
Pops the value on top of the stack and uses it as an index into the
array \f[I]r\f[R].
The selected value is then pushed onto the stack.
.TP
\f[B]Y\f[R]\f[I]r\f[R]
Pushes the length of the array \f[I]r\f[R] onto the stack.
.RS
.PP
This is a \f[B]non-portable extension\f[R].
.RE
+.SS Global Settings
+.PP
+These commands retrieve global settings.
+These are the only commands that require multiple specific characters,
+and all of them begin with the letter \f[B]g\f[R].
+Only the characters below are allowed after the character \f[B]g\f[R];
+any other character produces a parse error (see the \f[B]ERRORS\f[R]
+section).
+.TP
+\f[B]gl\f[R]
+Pushes the line length set by \f[B]DC_LINE_LENGTH\f[R] (see the
+\f[B]ENVIRONMENT VARIABLES\f[R] section) onto the stack.
+.TP
+\f[B]gz\f[R]
+Pushes \f[B]0\f[R] onto the stack if the leading zero setting has not
+been enabled with the \f[B]-z\f[R] or \f[B]--leading-zeroes\f[R] options
+(see the \f[B]OPTIONS\f[R] section), non-zero otherwise.
.SH REGISTERS
.PP
Registers are names that can store strings, numbers, and arrays.
(Number/string registers do not interfere with array registers.)
.PP
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 (\f[B]0\f[R]) in
their stack, and it is a runtime error to attempt to pop that item off
of the register stack.
.PP
In non-extended register mode, a register name is just the single
character that follows any command that needs a register name.
The only exceptions are: a newline (\f[B]`\[rs]n'\f[R]) and a left
bracket (\f[B]`['\f[R]); it is a parse error for a newline or a left
bracket to be used as a register name.
.SS Extended Register Mode
.PP
Unlike most other dc(1) implentations, this dc(1) provides nearly
unlimited amounts of registers, if extended register mode is enabled.
.PP
If extended register mode is enabled (\f[B]-x\f[R] or
\f[B]--extended-register\f[R] command-line arguments are given), then
normal single character registers are used \f[I]unless\f[R] the
character immediately following a command that needs a register name is
a space (according to \f[B]isspace()\f[R]) and not a newline
(\f[B]`\[rs]n'\f[R]).
.PP
In that case, the register name is found according to the regex
\f[B][a-z][a-z0-9_]*\f[R] (like bc(1) identifiers), and it is a parse
error if the next non-space characters do not match that regex.
.SH RESET
.PP
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.
.PP
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 macros returned) is skipped.
.PP
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 \f[B]EXIT STATUS\f[R] section), it asks for more input;
otherwise, it exits with the appropriate return code.
.SH PERFORMANCE
.PP
Most dc(1) implementations use \f[B]char\f[R] types to calculate the
value of \f[B]1\f[R] decimal digit at a time, but that can be slow.
This dc(1) does something different.
.PP
It uses large integers to calculate more than \f[B]1\f[R] decimal digit
at a time.
If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the
\f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has
\f[B]9\f[R] decimal digits.
If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R]
then each integer has \f[B]4\f[R] decimal digits.
This value (the number of decimal digits per large integer) is called
\f[B]DC_BASE_DIGS\f[R].
.PP
In addition, this dc(1) uses an even larger integer for overflow
checking.
This integer type depends on the value of \f[B]DC_LONG_BIT\f[R], but is
always at least twice as large as the integer type used to store digits.
.SH LIMITS
.PP
The following are the limits on dc(1):
.TP
\f[B]DC_LONG_BIT\f[R]
The number of bits in the \f[B]long\f[R] 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 \f[B]PERFORMANCE\f[R] section).
.TP
\f[B]DC_BASE_DIGS\f[R]
The number of decimal digits per large integer (see the
\f[B]PERFORMANCE\f[R] section).
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_POW\f[R]
The max decimal number that each large integer can store (see
\f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R].
Depends on \f[B]DC_BASE_DIGS\f[R].
.TP
\f[B]DC_OVERFLOW_MAX\f[R]
The max number that the overflow type (see the \f[B]PERFORMANCE\f[R]
section) can hold.
Depends on \f[B]DC_LONG_BIT\f[R].
.TP
\f[B]DC_BASE_MAX\f[R]
The maximum output base.
Set at \f[B]DC_BASE_POW\f[R].
.TP
\f[B]DC_DIM_MAX\f[R]
The maximum size of arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.TP
\f[B]DC_SCALE_MAX\f[R]
The maximum \f[B]scale\f[R].
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_STRING_MAX\f[R]
The maximum length of strings.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NAME_MAX\f[R]
The maximum length of identifiers.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_NUM_MAX\f[R]
The maximum length of a number (in decimal digits), which includes
digits after the decimal point.
Set at \f[B]DC_OVERFLOW_MAX-1\f[R].
.TP
\f[B]DC_RAND_MAX\f[R]
The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command,
if dc(1).
Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R].
.TP
Exponent
The maximum allowable exponent (positive or negative).
Set at \f[B]DC_OVERFLOW_MAX\f[R].
.TP
Number of vars
The maximum number of vars/arrays.
Set at \f[B]SIZE_MAX-1\f[R].
.PP
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
.PP
dc(1) recognizes the following environment variables:
.TP
\f[B]DC_ENV_ARGS\f[R]
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
\f[B]DC_ENV_ARGS\f[R] will be processed before arguments and files given
on the command-line.
This gives the user the ability to set up \[lq]standard\[rq] 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 \f[B]-e\f[R] option to set
\f[B]scale\f[R] to a value other than \f[B]0\f[R].
.RS
.PP
The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted
arguments, but it does not understand escape sequences.
For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R]
will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some
\[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes.
.PP
The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or
\f[B]\[lq]\f[R].
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 \f[B]\[lq]some
`dc' file.dc\[rq]\f[R], and vice versa if you have a file with double
quotes.
However, handling a file with both kinds of quotes in
\f[B]DC_ENV_ARGS\f[R] 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.
.RE
.TP
\f[B]DC_LINE_LENGTH\f[R]
If this environment variable exists and contains an integer that is
greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R]
(\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length,
including the backslash newline combo.
The default line length is \f[B]70\f[R].
+.RS
+.PP
+The special value of \f[B]0\f[R] will disable line length checking and
+print numbers without regard to line length and without backslashes and
+newlines.
+.RE
.TP
\f[B]DC_SIGINT_RESET\f[R]
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), then this environment variable has no effect because dc(1)
exits on \f[B]SIGINT\f[R] when not in interactive mode.
.RS
.PP
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1)
reset on \f[B]SIGINT\f[R], rather than exit, and zero makes dc(1) exit.
If this environment variable exists and is \f[I]not\f[R] an integer,
then dc(1) will exit on \f[B]SIGINT\f[R].
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_TTY_MODE\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use
TTY mode, and zero makes dc(1) not use TTY mode.
.PP
This environment variable overrides the default, which can be queried
with the \f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.TP
\f[B]DC_PROMPT\f[R]
If TTY mode is \f[I]not\f[R] available (see the \f[B]TTY MODE\f[R]
section), then this environment variable has no effect.
.RS
.PP
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a
prompt, and zero or a non-integer makes dc(1) not use a prompt.
If this environment variable does not exist and \f[B]DC_TTY_MODE\f[R]
does, then the value of the \f[B]DC_TTY_MODE\f[R] environment variable
is used.
.PP
This environment variable and the \f[B]DC_TTY_MODE\f[R] environment
variable override the default, which can be queried with the
\f[B]-h\f[R] or \f[B]--help\f[R] options.
.RE
.SH EXIT STATUS
.PP
dc(1) returns the following exit statuses:
.TP
\f[B]0\f[R]
No error.
.TP
\f[B]1\f[R]
A math error occurred.
This follows standard practice of using \f[B]1\f[R] for expected errors,
since math errors will happen in the process of normal execution.
.RS
.PP
Math errors include divide by \f[B]0\f[R], 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, overflow when calculating the size of a number, and attempting
to use a non-integer where an integer is required.
.PP
Converting to a hardware integer happens for the second operand of the
power (\f[B]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift
(\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators.
.RE
.TP
\f[B]2\f[R]
A parse error occurred.
.RS
.PP
Parse errors include unexpected \f[B]EOF\f[R], using an invalid
character, failing to find the end of a string or comment, and using a
token where it is invalid.
.RE
.TP
\f[B]3\f[R]
A runtime error occurred.
.RS
.PP
Runtime errors include assigning an invalid number to any global
(\f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]), giving a bad
expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside
of a \f[B]read()\f[R] call, type errors (including attempting to execute
a number), and attempting an operation when the stack has too few
elements.
.RE
.TP
\f[B]4\f[R]
A fatal error occurred.
.RS
.PP
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.
.RE
.PP
The exit status \f[B]4\f[R] is special; when a fatal error occurs, dc(1)
always exits and returns \f[B]4\f[R], no matter what mode dc(1) is in.
.PP
The other statuses will only be returned when dc(1) is not in
interactive mode (see the \f[B]INTERACTIVE MODE\f[R] section), since
dc(1) resets its state (see the \f[B]RESET\f[R] 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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.PP
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
\f[B]-i\f[R] flag or \f[B]--interactive\f[R] option.
.SH INTERACTIVE MODE
.PP
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both \f[B]stdin\f[R]
and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag
and \f[B]--interactive\f[R] option can turn it on in other situations.
.PP
In interactive mode, dc(1) attempts to recover from errors (see the
\f[B]RESET\f[R] section), and in normal execution, flushes
\f[B]stdout\f[R] as soon as execution is done for the current input.
dc(1) may also reset on \f[B]SIGINT\f[R] instead of exit, depending on
the contents of, or default for, the \f[B]DC_SIGINT_RESET\f[R]
environment variable (see the \f[B]ENVIRONMENT VARIABLES\f[R] section).
.SH TTY MODE
.PP
If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY, then \[lq]TTY mode\[rq] is considered to be
available, and thus, dc(1) can turn on TTY mode, subject to some
settings.
.PP
If there is the environment variable \f[B]DC_TTY_MODE\f[R] in the
environment (see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then if
that environment variable contains a non-zero integer, dc(1) will turn
on TTY mode when \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R]
are all connected to a TTY.
If the \f[B]DC_TTY_MODE\f[R] environment variable exists but is
\f[I]not\f[R] a non-zero integer, then dc(1) will not turn TTY mode on.
.PP
If the environment variable \f[B]DC_TTY_MODE\f[R] does \f[I]not\f[R]
exist, the default setting is used.
The default setting can be queried with the \f[B]-h\f[R] or
\f[B]--help\f[R] options.
.PP
TTY mode is different from interactive mode because interactive mode is
required in the bc(1)
specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html),
and interactive mode requires only \f[B]stdin\f[R] and \f[B]stdout\f[R]
to be connected to a terminal.
.SS Command-Line History
.PP
Command-line history is only enabled if TTY mode is, i.e., that
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to
a TTY and the \f[B]DC_TTY_MODE\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section) and its default do not disable
TTY mode.
See the \f[B]COMMAND LINE HISTORY\f[R] section for more information.
.SS Prompt
.PP
If TTY mode is available, then a prompt can be enabled.
Like TTY mode itself, it can be turned on or off with an environment
variable: \f[B]DC_PROMPT\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
If the environment variable \f[B]DC_PROMPT\f[R] exists and is a non-zero
integer, then the prompt is turned on when \f[B]stdin\f[R],
\f[B]stdout\f[R], and \f[B]stderr\f[R] are connected to a TTY and the
\f[B]-P\f[R] and \f[B]--no-prompt\f[R] options were not used.
The read prompt will be turned on under the same conditions, except that
the \f[B]-R\f[R] and \f[B]--no-read-prompt\f[R] options must also not be
used.
.PP
However, if \f[B]DC_PROMPT\f[R] does not exist, the prompt can be
enabled or disabled with the \f[B]DC_TTY_MODE\f[R] environment variable,
the \f[B]-P\f[R] and \f[B]--no-prompt\f[R] options, and the \f[B]-R\f[R]
and \f[B]--no-read-prompt\f[R] options.
See the \f[B]ENVIRONMENT VARIABLES\f[R] and \f[B]OPTIONS\f[R] sections
for more details.
.SH SIGNAL HANDLING
.PP
Sending a \f[B]SIGINT\f[R] will cause dc(1) to do one of two things.
.PP
If dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[R]
section), or the \f[B]DC_SIGINT_RESET\f[R] environment variable (see the
\f[B]ENVIRONMENT VARIABLES\f[R] section), or its default, is either not
an integer or it is zero, dc(1) will exit.
.PP
However, if dc(1) is in interactive mode, and the
\f[B]DC_SIGINT_RESET\f[R] or its default is an integer and non-zero,
then dc(1) will stop executing the current input and reset (see the
\f[B]RESET\f[R] section) upon receiving a \f[B]SIGINT\f[R].
.PP
Note that \[lq]current input\[rq] can mean one of two things.
If dc(1) is processing input from \f[B]stdin\f[R] in interactive mode,
it will ask for more input.
If dc(1) is processing input from a file in interactive mode, it will
stop processing the file and start processing the next file, if one
exists, or ask for input from \f[B]stdin\f[R] if no other file exists.
.PP
This means that if a \f[B]SIGINT\f[R] 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.
.PP
\f[B]SIGTERM\f[R] and \f[B]SIGQUIT\f[R] cause dc(1) to clean up and
exit, and it uses the default handler for all other signals.
The one exception is \f[B]SIGHUP\f[R]; in that case, and only when dc(1)
is in TTY mode (see the \f[B]TTY MODE\f[R] section), a \f[B]SIGHUP\f[R]
will cause dc(1) to clean up and exit.
.SH COMMAND LINE HISTORY
.PP
dc(1) supports interactive command-line editing.
.PP
If dc(1) can be in TTY mode (see the \f[B]TTY MODE\f[R] section),
history can be enabled.
This means that command-line history can only be enabled when
\f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all
connected to a TTY.
.PP
Like TTY mode itself, it can be turned on or off with the environment
variable \f[B]DC_TTY_MODE\f[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R]
section).
.PP
\f[B]Note\f[R]: tabs are converted to 8 spaces.
.SH SEE ALSO
.PP
bc(1)
.SH STANDARDS
.PP
The dc(1) utility operators are compliant with the operators in the
bc(1) IEEE Std 1003.1-2017
(\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html)
specification.
.SH BUGS
.PP
None are known.
Report bugs at https://git.yzena.com/gavin/bc.
.SH AUTHOR
.PP
Gavin D.
Howard and contributors.
diff --git a/manuals/dc/N.1.md b/manuals/dc/N.1.md
index 078554a4fc58..fea23028e483 100644
--- a/manuals/dc/N.1.md
+++ b/manuals/dc/N.1.md
@@ -1,1339 +1,1379 @@
# Name
dc - arbitrary-precision decimal reverse-Polish notation calculator
# SYNOPSIS
**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
# 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.
If no files are given on the command-line, then dc(1) reads from **stdin** (see
the **STDIN** section). Otherwise, those files are processed, and dc(1) will
then exit.
If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
this dc(1) will always start with a **scale** of **10**.
# OPTIONS
The following are the options that dc(1) accepts.
**-h**, **-\-help**
: Prints a usage message and quits.
**-v**, **-V**, **-\-version**
: Print the version information (copyright header) and exit.
**-i**, **-\-interactive**
: Forces interactive mode. (See the **INTERACTIVE MODE** section.)
This is a **non-portable extension**.
+**-L**, **-\-no-line-length**
+
+: Disables line length checking and prints numbers without backslashes and
+ newlines. In other words, this option sets **BC_LINE_LENGTH** to **0** (see
+ the **ENVIRONMENT VARIABLES** section).
+
+ This is a **non-portable extension**.
+
**-P**, **-\-no-prompt**
: Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
See the **TTY MODE** section.) This is mostly for those users that do not
want a prompt or are not used to having them in dc(1). Most of those users
would want to put this option in **DC_ENV_ARGS**.
These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
variables (see the **ENVIRONMENT VARIABLES** section).
This is a **non-portable extension**.
**-R**, **-\-no-read-prompt**
: Disables the read prompt in TTY mode. (The read prompt is only enabled in
TTY mode. See the **TTY MODE** section.) This is mostly for those users that
do not want a read prompt or are not used to having them in dc(1). Most of
those users would want to put this option in **BC_ENV_ARGS** (see the
**ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
lines of dc(1) scripts that prompt for user input.
This option does not disable the regular prompt because the read prompt is
only used when the **?** command is used.
These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
environment variables (see the **ENVIRONMENT VARIABLES** section), but only
for the read prompt.
This is a **non-portable extension**.
**-x** **-\-extended-register**
: Enables extended register mode. See the *Extended Register Mode* subsection
of the **REGISTERS** section for more information.
This is a **non-portable extension**.
+**-z**, **-\-leading-zeroes**
+
+: Makes bc(1) print all numbers greater than **-1** and less than **1**, and
+ not equal to **0**, with a leading zero.
+
+ This can be set for individual numbers with the **plz(x)**, plznl(x)**,
+ **pnlz(x)**, and **pnlznl(x)** functions in the extended math library (see
+ the **LIBRARY** section).
+
+ This is a **non-portable extension**.
+
**-e** *expr*, **-\-expression**=*expr*
: Evaluates *expr*. 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.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**, whether on the
command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
**-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
**-f** *file*, **-\-file**=*file*
: Reads in *file* and evaluates it, line by line, as though it were read
through **stdin**. If expressions are also given (see above), the
expressions are evaluated in the order given.
If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
see the **ENVIRONMENT VARIABLES** section), then after processing all
expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
as an argument at least once to **-f** or **-\-file**. However, if any other
**-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
**-f-** or equivalent is given, dc(1) will give a fatal error and exit.
This is a **non-portable extension**.
All long options are **non-portable extensions**.
# STDIN
If no files are given on the command-line and no files or expressions are given
by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
read from **stdin**.
However, there is a caveat to this.
First, **stdin** is evaluated a line at a time. The only exception to this is if
a string has been finished, but not ended. This means that, except for escaped
brackets, all brackets must be balanced before dc(1) parses and executes.
# STDOUT
Any non-error output is written to **stdout**. In addition, if history (see the
**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
both are output to **stdout**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
**stdout** is closed, as in **dc >&-**, it will quit with an error. This
is done so that dc(1) can report problems when **stdout** is redirected to a
file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stdout** to
**/dev/null**.
# STDERR
Any error output is written to **stderr**.
**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
**stderr** is closed, as in **dc 2>&-**, it will quit with an error. This
is done so that dc(1) can exit with an error code when **stderr** is redirected
to a file.
If there are scripts that depend on the behavior of other dc(1) implementations,
it is recommended that those scripts be changed to redirect **stderr** to
**/dev/null**.
# SYNTAX
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.
**ibase** is a register (see the **REGISTERS** section) that determines how to
interpret constant numbers. It is the "input" base, or the number base used for
interpreting input numbers. **ibase** is initially **10**. The max allowable
value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
The max allowable value for **ibase** can be queried in dc(1) programs with the
**T** command.
**obase** is a register (see the **REGISTERS** section) that determines how to
output results. It is the "output" base, or the number base used for outputting
numbers. **obase** is initially **10**. The max allowable value for **obase** is
**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
value for **obase** is **0**. If **obase** is **0**, values are output in
scientific notation, and if **obase** is **1**, values are output in engineering
notation. Otherwise, values are output in the specified base.
Outputting in scientific and engineering notations are **non-portable
extensions**.
The *scale* of an expression is the number of digits in the result of the
expression right of the decimal point, and **scale** is a register (see the
**REGISTERS** section) that sets the precision of any operations (with
exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
allowable value for **scale** can be queried in dc(1) programs with the **V**
command.
**seed** is a register containing the current seed for the pseudo-random number
generator. If the current value of **seed** is queried and stored, then if it is
assigned to **seed** later, the pseudo-random number generator is guaranteed to
produce the same sequence of pseudo-random numbers that were generated after the
value of **seed** was first queried.
Multiple values assigned to **seed** can produce the same sequence of
pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not
guaranteed that querying **seed** immediately after will return the same value.
In addition, the value of **seed** will change after any call to the **'**
command or the **"** command that does not get receive a value of **0** or
**1**. The maximum integer returned by the **'** command can be queried with the
**W** command.
**Note**: The values returned by the pseudo-random number generator with the
**'** and **"** commands are guaranteed to **NOT** be cryptographically secure.
This is a consequence of using a seeded pseudo-random number generator. However,
they *are* guaranteed to be reproducible with identical **seed** values. This
means that the pseudo-random values from dc(1) should only be used where a
reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
use a non-seeded pseudo-random number generator.
The pseudo-random number generator, **seed**, and all associated operations are
**non-portable extensions**.
## Comments
Comments go from **#** until, and not including, the next newline. This is a
**non-portable extension**.
# NUMBERS
Numbers are strings made up of digits, uppercase letters up to **F**, and at
most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
current value of **ibase**, they are set to the value of the highest valid digit
in **ibase**.
Single-character numbers (i.e., **A** alone) take the value that they would have
if they were valid digits, regardless of the value of **ibase**. This means that
**A** alone always equals decimal **10** and **F** alone always equals decimal
**15**.
In addition, dc(1) accepts numbers in scientific notation. These have the form
**\e\**. The exponent (the portion after the **e**) must be
an integer. An example is **1.89237e9**, which is equal to **1892370000**.
Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**.
**WARNING**: Both the number and the exponent in scientific notation are
interpreted according to the current **ibase**, but the number is still
multiplied by **10\^exponent** regardless of the current **ibase**. For example,
if **ibase** is **16** and dc(1) is given the number string **FFeA**, the
resulting decimal number will be **2550000000000**, and if dc(1) is given the
number string **10e_4**, the resulting decimal number will be **0.0016**.
Accepting input as scientific notation is a **non-portable extension**.
# COMMANDS
The valid commands are listed below.
## Printing
These commands are used for printing.
Note that both scientific notation and engineering notation are available for
printing numbers. Scientific notation is activated by assigning **0** to
**obase** using **0o**, and engineering notation is activated by assigning **1**
to **obase** using **1o**. To deactivate them, just assign a different value to
**obase**.
Printing numbers in scientific notation and/or engineering notation is a
**non-portable extension**.
**p**
: Prints the value on top of the stack, whether number or string, and prints a
newline after.
This does not alter the stack.
**n**
: Prints the value on top of the stack, whether number or string, and pops it
off of the stack.
**P**
: Pops a value off the stack.
If the value is a number, it is truncated and the absolute value of the
result is printed as though **obase** is **256** and each digit is
interpreted as an 8-bit ASCII character, making it a byte stream.
If the value is a string, it is printed without a trailing newline.
This is a **non-portable extension**.
**f**
: Prints the entire contents of the stack, in order from newest to oldest,
without altering anything.
Users should use this command when they get lost.
## Arithmetic
These are the commands used for arithmetic.
**+**
: The top two values are popped off the stack, added, and the result is pushed
onto the stack. The *scale* of the result is equal to the max *scale* of
both operands.
**-**
: The top two values are popped off the stack, subtracted, and the result is
pushed onto the stack. The *scale* of the result is equal to the max
*scale* of both operands.
**\***
: The top two values are popped off the stack, multiplied, and the result is
pushed onto the stack. If **a** is the *scale* of the first expression and
**b** is the *scale* of the second expression, the *scale* of the result
is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
the obvious values.
**/**
: The top two values are popped off the stack, divided, and the result is
pushed onto the stack. The *scale* of the result is equal to **scale**.
The first value popped off of the stack must be non-zero.
**%**
: The top two values are popped off the stack, remaindered, and the result is
pushed onto the stack.
Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
**max(scale+scale(b),scale(a))**.
The first value popped off of the stack must be non-zero.
**~**
: 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 **x y / x y %** except that **x** and **y** are only
evaluated once.
The first value popped off of the stack must be non-zero.
This is a **non-portable extension**.
**\^**
: 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. The *scale* of
the result is equal to **scale**.
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.
**v**
: The top value is popped off the stack, its square root is computed, and the
result is pushed onto the stack. The *scale* of the result is equal to
**scale**.
The value popped off of the stack must be non-negative.
**\_**
: If this command *immediately* precedes a number (i.e., no spaces or other
commands), then that number is input as a negative number.
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
**non-portable extension**.
**b**
: 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.
This is a **non-portable extension**.
**|**
: The top three values are popped off the stack, a modular exponentiation is
computed, and the result is pushed onto the stack.
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.
This is a **non-portable extension**.
**\$**
: The top value is popped off the stack and copied, and the copy is truncated
and pushed onto the stack.
This is a **non-portable extension**.
**\@**
: 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.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**H**
: The top two values are popped off the stack, and the second is shifted left
(radix shifted right) to the value of the first.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**h**
: The top two values are popped off the stack, and the second is shifted right
(radix shifted left) to the value of the first.
The first value popped off of the stack must be an integer and non-negative.
This is a **non-portable extension**.
**G**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if they are equal, or **0** otherwise.
This is a **non-portable extension**.
**N**
: The top value is popped off of the stack, and if it a **0**, a **1** is
pushed; otherwise, a **0** is pushed.
This is a **non-portable extension**.
**(**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than the second, or **0** otherwise.
This is a **non-portable extension**.
**{**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is less than or equal to the second, or **0**
otherwise.
This is a **non-portable extension**.
**)**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than the second, or **0** otherwise.
This is a **non-portable extension**.
**}**
: The top two values are popped off of the stack, they are compared, and a
**1** is pushed if the first is greater than or equal to the second, or
**0** otherwise.
This is a **non-portable extension**.
**M**
: The top two values are popped off of the stack. If they are both non-zero, a
**1** is pushed onto the stack. If either of them is zero, or both of them
are, then a **0** is pushed onto the stack.
This is like the **&&** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
**m**
: The top two values are popped off of the stack. If at least one of them is
non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
**0** is pushed onto the stack.
This is like the **||** operator in bc(1), and it is *not* a short-circuit
operator.
This is a **non-portable extension**.
## Pseudo-Random Number Generator
dc(1) has a built-in pseudo-random number generator. These commands query the
pseudo-random number generator. (See Parameters for more information about the
**seed** value that controls the pseudo-random number generator.)
The pseudo-random number generator is guaranteed to **NOT** be
cryptographically secure.
**'**
: Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the
**LIMITS** section).
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
This is a **non-portable extension**.
**"**
: Pops a value off of the stack, which is used as an **exclusive** 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) while **seed** remains unchanged. If the bound is larger than
**DC_RAND_MAX**, the higher bound is honored by generating several
pseudo-random integers, multiplying them by appropriate powers of
**DC_RAND_MAX+1**, 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 **seed**, unless the operand is **0** or **1**. In that
case, **0** is pushed onto the stack, and **seed** is *not* changed.
The generated integer is made as unbiased as possible, subject to the
limitations of the pseudo-random number generator.
This is a **non-portable extension**.
## Stack Control
These commands control the stack.
**c**
: Removes all items from ("clears") the stack.
**d**
: Copies the item on top of the stack ("duplicates") and pushes the copy onto
the stack.
**r**
: Swaps ("reverses") the two top items on the stack.
**R**
: Pops ("removes") the top value from the stack.
## Register Control
These commands control registers (see the **REGISTERS** section).
**s**_r_
: Pops the value off the top of the stack and stores it into register *r*.
**l**_r_
: Copies the value in register *r* and pushes it onto the stack. This does not
alter the contents of *r*.
**S**_r_
: Pops the value off the top of the (main) stack and pushes it onto the stack
of register *r*. The previous value of the register becomes inaccessible.
**L**_r_
: Pops the value off the top of the stack for register *r* and push it onto
the main stack. The previous value in the stack for register *r*, if any, is
now accessible via the **l**_r_ command.
## Parameters
These commands control the values of **ibase**, **obase**, **scale**, and
**seed**. Also see the **SYNTAX** section.
**i**
: Pops the value off of the top of the stack and uses it to set **ibase**,
which must be between **2** and **16**, inclusive.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**o**
: Pops the value off of the top of the stack and uses it to set **obase**,
which must be between **0** and **DC_BASE_MAX**, inclusive (see the
**LIMITS** section and the **NUMBERS** section).
If the value on top of the stack has any *scale*, the *scale* is ignored.
**k**
: Pops the value off of the top of the stack and uses it to set **scale**,
which must be non-negative.
If the value on top of the stack has any *scale*, the *scale* is ignored.
**j**
: Pops the value off of the top of the stack and uses it to set **seed**. The
meaning of **seed** is dependent on the current pseudo-random number
generator but is guaranteed to not change except for new major versions.
The *scale* and sign of the value may be significant.
If a previously used **seed** 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 **seed** value was previously used.
The exact value assigned to **seed** is not guaranteed to be returned if the
**J** command is used. However, if **seed** *does* return a different value,
both values, when assigned to **seed**, are guaranteed to produce the same
sequence of pseudo-random numbers. This means that certain values assigned
to **seed** will not produce unique sequences of pseudo-random numbers.
There is no limit to the length (number of significant decimal digits) or
*scale* of the value that can be assigned to **seed**.
This is a **non-portable extension**.
**I**
: Pushes the current value of **ibase** onto the main stack.
**O**
: Pushes the current value of **obase** onto the main stack.
**K**
: Pushes the current value of **scale** onto the main stack.
**J**
: Pushes the current value of **seed** onto the main stack.
This is a **non-portable extension**.
**T**
: Pushes the maximum allowable value of **ibase** onto the main stack.
This is a **non-portable extension**.
**U**
: Pushes the maximum allowable value of **obase** onto the main stack.
This is a **non-portable extension**.
**V**
: Pushes the maximum allowable value of **scale** onto the main stack.
This is a **non-portable extension**.
**W**
: Pushes the maximum (inclusive) integer that can be generated with the **'**
pseudo-random number generator command.
This is a **non-portable extension**.
## Strings
The following commands control strings.
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.
While arithmetic operations have to have numbers, and will print an error if
given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string **[1pR]** is
executed as a macro, then the code **1pR** is executed, meaning that the **1**
will be printed with a newline after and then popped from the stack.
**\[**_characters_**\]**
: Makes a string containing *characters* and pushes it onto the stack.
If there are brackets (**\[** and **\]**) in the string, then they must be
balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
character.
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.
**a**
: The value on top of the stack is popped.
If it is a number, it is truncated and its absolute value is taken. The
result mod **256** is calculated. If that result is **0**, push an empty
string; otherwise, push a one-character string where the character is the
result of the mod interpreted as an ASCII character.
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.
This is a **non-portable extension**.
**x**
: Pops a value off of the top of the stack.
If it is a number, it is pushed back onto the stack.
If it is a string, it is executed as a macro.
This behavior is the norm whenever a macro is executed, whether by this
command or by the conditional execution commands below.
**\>**_r_
: 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
*r* are executed.
For example, **0 1>a** will execute the contents of register **a**, and
**1 0>a** will not.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\>**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\>**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**\<**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!\<**_r_
: 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 *r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!\<**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**=**_r_
: 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 *r*
are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**!=**_r_
: 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
*r* are executed.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
**!=**_r_**e**_s_
: Like the above, but will execute register *s* if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error
and reset (see the **RESET** section).
This is a **non-portable extension**.
**?**
: Reads a line from the **stdin** and executes it. This is to allow macros to
request input from users.
**q**
: 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.
**Q**
: 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.
**,**
: Pushes the depth of the execution stack onto the stack. The execution stack
is the stack of string executions. The number that is pushed onto the stack
is exactly as many as is needed to make dc(1) exit with the **Q** command,
so the sequence **,Q** will make dc(1) exit.
## Status
These commands query status of the stack or its top value.
**Z**
: Pops a value off of the stack.
If it is a number, calculates the number of significant decimal digits it
has and pushes the result. It will push **1** if the argument is **0** with
no decimal places.
If it is a string, pushes the number of characters the string has.
**X**
: Pops a value off of the stack.
If it is a number, pushes the *scale* of the value onto the stack.
If it is a string, pushes **0**.
**z**
: Pushes the current depth of the stack (before execution of this command)
onto the stack.
**y**_r_
: Pushes the current stack depth of the register *r* onto the main stack.
Because each register has a depth of **1** (with the value **0** in the top
item) when dc(1) starts, dc(1) requires that each register's stack must
always have at least one item; dc(1) will give an error and reset otherwise
(see the **RESET** section). This means that this command will never push
**0**.
This is a **non-portable extension**.
## Arrays
These commands manipulate arrays.
**:**_r_
: Pops the top two values off of the stack. The second value will be stored in
the array *r* (see the **REGISTERS** section), indexed by the first value.
**;**_r_
: Pops the value on top of the stack and uses it as an index into the array
*r*. The selected value is then pushed onto the stack.
**Y**_r_
: Pushes the length of the array *r* onto the stack.
This is a **non-portable extension**.
+## Global Settings
+
+These commands retrieve global settings. These are the only commands that
+require multiple specific characters, and all of them begin with the letter
+**g**. Only the characters below are allowed after the character **g**; any
+other character produces a parse error (see the **ERRORS** section).
+
+**gl**
+
+: Pushes the line length set by **DC_LINE_LENGTH** (see the **ENVIRONMENT
+ VARIABLES** section) onto the stack.
+
+**gz**
+
+: Pushes **0** onto the stack if the leading zero setting has not been enabled
+ with the **-z** or **-\-leading-zeroes** options (see the **OPTIONS**
+ section), non-zero otherwise.
+
# REGISTERS
Registers are names that can store strings, numbers, and arrays. (Number/string
registers do not interfere with array registers.)
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
(**0**) in their stack, and it is a runtime error to attempt to pop that item
off of the register stack.
In non-extended register mode, a register name is just the single character that
follows any command that needs a register name. The only exceptions are: a
newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
newline or a left bracket to be used as a register name.
## Extended Register Mode
Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
amounts of registers, if extended register mode is enabled.
If extended register mode is enabled (**-x** or **-\-extended-register**
command-line arguments are given), then normal single character registers are
used *unless* the character immediately following a command that needs a
register name is a space (according to **isspace()**) and not a newline
(**'\\n'**).
In that case, the register name is found according to the regex
**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
the next non-space characters do not match that regex.
# 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.
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
macros returned) is skipped.
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.
# PERFORMANCE
Most dc(1) implementations use **char** types to calculate the value of **1**
decimal digit at a time, but that can be slow. This dc(1) does something
different.
It uses large integers to calculate more than **1** decimal digit at a time. If
built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
**64**, then each integer has **9** decimal digits. If built in an environment
where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
value (the number of decimal digits per large integer) is called
**DC_BASE_DIGS**.
In addition, this dc(1) uses an even larger integer for overflow checking. This
integer type depends on the value of **DC_LONG_BIT**, but is always at least
twice as large as the integer type used to store digits.
# LIMITS
The following are the limits on dc(1):
**DC_LONG_BIT**
: The number of bits in the **long** 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).
**DC_BASE_DIGS**
: The number of decimal digits per large integer (see the **PERFORMANCE**
section). Depends on **DC_LONG_BIT**.
**DC_BASE_POW**
: The max decimal number that each large integer can store (see
**DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
**DC_OVERFLOW_MAX**
: The max number that the overflow type (see the **PERFORMANCE** section) can
hold. Depends on **DC_LONG_BIT**.
**DC_BASE_MAX**
: The maximum output base. Set at **DC_BASE_POW**.
**DC_DIM_MAX**
: The maximum size of arrays. Set at **SIZE_MAX-1**.
**DC_SCALE_MAX**
: The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
**DC_STRING_MAX**
: The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
**DC_NAME_MAX**
: The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
**DC_NUM_MAX**
: The maximum length of a number (in decimal digits), which includes digits
after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
**DC_RAND_MAX**
: The maximum integer (inclusive) returned by the **'** command, if dc(1). Set
at **2\^DC_LONG_BIT-1**.
Exponent
: The maximum allowable exponent (positive or negative). Set at
**DC_OVERFLOW_MAX**.
Number of vars
: The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
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.
# ENVIRONMENT VARIABLES
dc(1) recognizes the following environment variables:
**DC_ENV_ARGS**
: 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 **DC_ENV_ARGS** 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 **-e** option to set **scale** to a value other than **0**.
The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
but it does not understand escape sequences. For example, the string
**"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
**"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
The quote parsing will handle either kind of quotes, **'** or **"**. 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 **"some 'dc' file.dc"**, and vice
versa if you have a file with double quotes. However, handling a file with
both kinds of quotes in **DC_ENV_ARGS** 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.
**DC_LINE_LENGTH**
: If this environment variable exists and contains an integer that is greater
than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
lines to that length, including the backslash newline combo. The default
line length is **70**.
+ The special value of **0** will disable line length checking and print
+ numbers without regard to line length and without backslashes and newlines.
+
**DC_SIGINT_RESET**
: If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
then this environment variable has no effect because dc(1) exits on
**SIGINT** when not in interactive mode.
However, when dc(1) is in interactive mode, then if this environment
variable exists and contains an integer, a non-zero value makes dc(1) reset
on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
environment variable exists and is *not* an integer, then dc(1) will exit on
**SIGINT**.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_TTY_MODE**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, then a non-zero value makes dc(1) use TTY
mode, and zero makes dc(1) not use TTY mode.
This environment variable overrides the default, which can be queried with
the **-h** or **-\-help** options.
**DC_PROMPT**
: If TTY mode is *not* available (see the **TTY MODE** section), then this
environment variable has no effect.
However, when TTY mode is available, then if this environment variable
exists and contains an integer, a non-zero value makes dc(1) use a prompt,
and zero or a non-integer makes dc(1) not use a prompt. If this environment
variable does not exist and **DC_TTY_MODE** does, then the value of the
**DC_TTY_MODE** environment variable is used.
This environment variable and the **DC_TTY_MODE** environment variable
override the default, which can be queried with the **-h** or **-\-help**
options.
# EXIT STATUS
dc(1) returns the following exit statuses:
**0**
: No error.
**1**
: A math error occurred. This follows standard practice of using **1** for
expected errors, since math errors will happen in the process of normal
execution.
Math errors include divide by **0**, 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, overflow when
calculating the size of a number, and attempting to use a non-integer where
an integer is required.
Converting to a hardware integer happens for the second operand of the power
(**\^**), places (**\@**), left shift (**H**), and right shift (**h**)
operators.
**2**
: A parse error occurred.
Parse errors include unexpected **EOF**, using an invalid character, failing
to find the end of a string or comment, and using a token where it is
invalid.
**3**
: A runtime error occurred.
Runtime errors include assigning an invalid number to any global (**ibase**,
**obase**, or **scale**), giving a bad expression to a **read()** call,
calling **read()** inside of a **read()** call, type errors (including
attempting to execute a number), and attempting an operation when the stack
has too few elements.
**4**
: A fatal error occurred.
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.
The exit status **4** is special; when a fatal error occurs, dc(1) always exits
and returns **4**, no matter what mode dc(1) is in.
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
**-i** flag or **-\-interactive** option.
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 **-i** flag or
**-\-interactive** option.
# INTERACTIVE MODE
Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
Interactive mode is turned on automatically when both **stdin** and **stdout**
are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
turn it on in other situations.
In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
section), and in normal execution, flushes **stdout** as soon as execution is
done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
depending on the contents of, or default for, the **DC_SIGINT_RESET**
environment variable (see the **ENVIRONMENT VARIABLES** section).
# TTY MODE
If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
subject to some settings.
If there is the environment variable **DC_TTY_MODE** in the environment (see the
**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
mode on.
If the environment variable **DC_TTY_MODE** does *not* exist, the default
setting is used. The default setting can be queried with the **-h** or
**-\-help** options.
TTY mode is different from interactive mode because interactive mode is required
in the [bc(1) specification][1], and interactive mode requires only **stdin**
and **stdout** to be connected to a terminal.
## Command-Line History
Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
**stdout**, and **stderr** are connected to a TTY and the **DC_TTY_MODE**
environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
information.
## Prompt
If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
can be turned on or off with an environment variable: **DC_PROMPT** (see the
**ENVIRONMENT VARIABLES** section).
If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
prompt will be turned on under the same conditions, except that the **-R** and
**-\-no-read-prompt** options must also not be used.
However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
VARIABLES** and **OPTIONS** sections for more details.
# SIGNAL HANDLING
Sending a **SIGINT** will cause dc(1) to do one of two things.
If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
section), or its default, is either not an integer or it is zero, dc(1) will
exit.
However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
default is an integer and non-zero, then dc(1) will stop executing the current
input and reset (see the **RESET** section) upon receiving a **SIGINT**.
Note that "current input" can mean one of two things. If dc(1) is processing
input from **stdin** in interactive mode, it will ask for more input. If dc(1)
is processing input from a file in interactive mode, it will stop processing the
file and start processing the next file, if one exists, or ask for input from
**stdin** if no other file exists.
This means that if a **SIGINT** 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.
**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
default handler for all other signals. The one exception is **SIGHUP**; in that
case, and only when dc(1) is in TTY mode (see the **TTY MODE** section), a
**SIGHUP** will cause dc(1) to clean up and exit.
# COMMAND LINE HISTORY
dc(1) supports interactive command-line editing.
If dc(1) can be in TTY mode (see the **TTY MODE** section), history can be
enabled. This means that command-line history can only be enabled when
**stdin**, **stdout**, and **stderr** are all connected to a TTY.
Like TTY mode itself, it can be turned on or off with the environment variable
**DC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
**Note**: tabs are converted to 8 spaces.
# SEE ALSO
bc(1)
# STANDARDS
The dc(1) utility operators are compliant with the operators in the bc(1)
[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
# BUGS
None are known. Report bugs at https://git.yzena.com/gavin/bc.
# AUTHOR
Gavin D. Howard and contributors.
[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
diff --git a/scripts/functions.sh b/scripts/functions.sh
index e794d96fc707..65ec0a1167fe 100755
--- a/scripts/functions.sh
+++ b/scripts/functions.sh
@@ -1,330 +1,328 @@
#! /bin/sh
#
# SPDX-License-Identifier: BSD-2-Clause
#
# Copyright (c) 2018-2021 Gavin D. Howard and contributors.
#
# 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.
#
# This script is NOT meant to be run! It is meant to be sourced by other
# scripts.
# Reads and follows a link until it finds a real file. This is here because the
# readlink utility is not part of the POSIX standard. Sigh...
# @param f The link to find the original file for.
readlink() {
_readlink_f="$1"
shift
_readlink_arrow="-> "
_readlink_d=$(dirname "$_readlink_f")
_readlink_lsout=""
_readlink_link=""
_readlink_lsout=$(ls -dl "$_readlink_f")
_readlink_link=$(printf '%s' "${_readlink_lsout#*$_readlink_arrow}")
while [ -z "${_readlink_lsout##*$_readlink_arrow*}" ]; do
_readlink_f="$_readlink_d/$_readlink_link"
_readlink_d=$(dirname "$_readlink_f")
_readlink_lsout=$(ls -dl "$_readlink_f")
_readlink_link=$(printf '%s' "${_readlink_lsout#*$_readlink_arrow}")
done
printf '%s' "${_readlink_f##*$_readlink_d/}"
}
# Quick function for exiting with an error.
# @param 1 A message to print.
# @param 2 The exit code to use.
err_exit() {
if [ "$#" -ne 2 ]; then
printf 'Invalid number of args to err_exit\n'
exit 1
fi
printf '%s\n' "$1"
exit "$2"
}
# Check the return code on a test and exit with a fail if it's non-zero.
# @param d The calculator under test.
# @param err The return code.
# @param name The name of the test.
checktest_retcode() {
_checktest_retcode_d="$1"
shift
_checktest_retcode_err="$1"
shift
_checktest_retcode_name="$1"
shift
if [ "$_checktest_retcode_err" -ne 0 ]; then
printf 'FAIL!!!\n'
err_exit "$_checktest_retcode_d failed test '$_checktest_retcode_name' with error code $_checktest_retcode_err" 1
fi
}
# Check the result of a test. First, it checks the error code using
# checktest_retcode(). Then it checks the output against the expected output
# and fails if it doesn't match.
# @param d The calculator under test.
# @param err The error code.
# @param name The name of the test.
# @param test_path The path to the test.
# @param results_name The path to the file with the expected result.
checktest() {
_checktest_d="$1"
shift
_checktest_err="$1"
shift
_checktest_name="$1"
shift
_checktest_test_path="$1"
shift
_checktest_results_name="$1"
shift
checktest_retcode "$_checktest_d" "$_checktest_err" "$_checktest_name"
_checktest_diff=$(diff "$_checktest_test_path" "$_checktest_results_name")
_checktest_err="$?"
if [ "$_checktest_err" -ne 0 ]; then
printf 'FAIL!!!\n'
printf '%s\n' "$_checktest_diff"
err_exit "$_checktest_d failed test $_checktest_name" 1
fi
}
# Die. With a message.
# @param d The calculator under test.
# @param msg The message to print.
# @param name The name of the test.
# @param err The return code from the test.
die() {
_die_d="$1"
shift
_die_msg="$1"
shift
_die_name="$1"
shift
_die_err="$1"
shift
_die_str=$(printf '\n%s %s on test:\n\n %s\n' "$_die_d" "$_die_msg" "$_die_name")
err_exit "$_die_str" "$_die_err"
}
# Check that a test did not crash and die if it did.
# @param d The calculator under test.
# @param error The error code.
# @param name The name of the test.
checkcrash() {
_checkcrash_d="$1"
shift
_checkcrash_error="$1"
shift
_checkcrash_name="$1"
shift
if [ "$_checkcrash_error" -gt 127 ]; then
die "$_checkcrash_d" "crashed ($_checkcrash_error)" \
"$_checkcrash_name" "$_checkcrash_error"
fi
}
# Check that a test had an error or crash.
# @param d The calculator under test.
# @param error The error code.
# @param name The name of the test.
# @param out The file that the test results were output to.
# @param exebase The name of the executable.
checkerrtest()
{
_checkerrtest_d="$1"
shift
_checkerrtest_error="$1"
shift
_checkerrtest_name="$1"
shift
_checkerrtest_out="$1"
shift
_checkerrtest_exebase="$1"
shift
checkcrash "$_checkerrtest_d" "$_checkerrtest_error" "$_checkerrtest_name"
if [ "$_checkerrtest_error" -eq 0 ]; then
die "$_checkerrtest_d" "returned no error" "$_checkerrtest_name" 127
fi
# This is to check for memory errors with Valgrind, which is told to return
# 100 on memory errors.
if [ "$_checkerrtest_error" -eq 100 ]; then
_checkerrtest_output=$(cat "$_checkerrtest_out")
_checkerrtest_fatal_error="Fatal error"
if [ "${_checkerrtest_output##*$_checkerrtest_fatal_error*}" ]; then
printf "%s\n" "$_checkerrtest_output"
die "$_checkerrtest_d" "had memory errors on a non-fatal error" \
"$_checkerrtest_name" "$_checkerrtest_error"
fi
fi
if [ ! -s "$_checkerrtest_out" ]; then
die "$_checkerrtest_d" "produced no error message" "$_checkerrtest_name" "$_checkerrtest_error"
fi
- # Display the error messages if not directly running exe.
- # This allows the script to print valgrind output.
- if [ "$_checkerrtest_exebase" != "bc" ] && [ "$_checkerrtest_exebase" != "dc" ]; then
- cat "$_checkerrtest_out"
- fi
+ # To display error messages, uncomment this line. This is useful when
+ # debugging.
+ #cat "$_checkerrtest_out"
}
# Replace a substring in a string with another. This function is the *real*
# workhorse behind configure.sh's generation of a Makefile.
#
# This function uses a sed call that uses exclamation points `!` as delimiters.
# As a result, needle can never contain an exclamation point. Oh well.
#
# @param str The string that will have any of the needle replaced by
# replacement.
# @param needle The needle to replace in str with replacement.
# @param replacement The replacement for needle in str.
substring_replace() {
_substring_replace_str="$1"
shift
_substring_replace_needle="$1"
shift
_substring_replace_replacement="$1"
shift
_substring_replace_result=$(printf '%s\n' "$_substring_replace_str" | \
sed -e "s!$_substring_replace_needle!$_substring_replace_replacement!g")
printf '%s' "$_substring_replace_result"
}
# Generates an NLS path based on the locale and executable name.
#
# This is a monstrosity for a reason.
#
# @param nlspath The $NLSPATH
# @param locale The locale.
# @param execname The name of the executable.
gen_nlspath() {
_gen_nlspath_nlspath="$1"
shift
_gen_nlspath_locale="$1"
shift
_gen_nlspath_execname="$1"
shift
# Split the locale into its modifier and other parts.
_gen_nlspath_char="@"
_gen_nlspath_modifier="${_gen_nlspath_locale#*$_gen_nlspath_char}"
_gen_nlspath_tmplocale="${_gen_nlspath_locale%%$_gen_nlspath_char*}"
# Split the locale into charset and other parts.
_gen_nlspath_char="."
_gen_nlspath_charset="${_gen_nlspath_tmplocale#*$_gen_nlspath_char}"
_gen_nlspath_tmplocale="${_gen_nlspath_tmplocale%%$_gen_nlspath_char*}"
# Check for an empty charset.
if [ "$_gen_nlspath_charset" = "$_gen_nlspath_tmplocale" ]; then
_gen_nlspath_charset=""
fi
# Split the locale into territory and language.
_gen_nlspath_char="_"
_gen_nlspath_territory="${_gen_nlspath_tmplocale#*$_gen_nlspath_char}"
_gen_nlspath_language="${_gen_nlspath_tmplocale%%$_gen_nlspath_char*}"
# Check for empty territory and language.
if [ "$_gen_nlspath_territory" = "$_gen_nlspath_tmplocale" ]; then
_gen_nlspath_territory=""
fi
if [ "$_gen_nlspath_language" = "$_gen_nlspath_tmplocale" ]; then
_gen_nlspath_language=""
fi
# Prepare to replace the format specifiers. This is done by wrapping the in
# pipe characters. It just makes it easier to split them later.
_gen_nlspath_needles="%%:%L:%N:%l:%t:%c"
_gen_nlspath_needles=$(printf '%s' "$_gen_nlspath_needles" | tr ':' '\n')
for _gen_nlspath_i in $_gen_nlspath_needles; do
_gen_nlspath_nlspath=$(substring_replace "$_gen_nlspath_nlspath" "$_gen_nlspath_i" "|$_gen_nlspath_i|")
done
# Replace all the format specifiers.
_gen_nlspath_nlspath=$(substring_replace "$_gen_nlspath_nlspath" "%%" "%")
_gen_nlspath_nlspath=$(substring_replace "$_gen_nlspath_nlspath" "%L" "$_gen_nlspath_locale")
_gen_nlspath_nlspath=$(substring_replace "$_gen_nlspath_nlspath" "%N" "$_gen_nlspath_execname")
_gen_nlspath_nlspath=$(substring_replace "$_gen_nlspath_nlspath" "%l" "$_gen_nlspath_language")
_gen_nlspath_nlspath=$(substring_replace "$_gen_nlspath_nlspath" "%t" "$_gen_nlspath_territory")
_gen_nlspath_nlspath=$(substring_replace "$_gen_nlspath_nlspath" "%c" "$_gen_nlspath_charset")
# Get rid of pipe characters.
_gen_nlspath_nlspath=$(printf '%s' "$_gen_nlspath_nlspath" | tr -d '|')
# Return the result.
printf '%s' "$_gen_nlspath_nlspath"
}
diff --git a/src/args.c b/src/args.c
index ea1d0043a357..6601cfb2eeb6 100644
--- a/src/args.c
+++ b/src/args.c
@@ -1,276 +1,288 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
#include
#include
#include
#include
#ifndef _WIN32
#include
#endif // _WIN32
#include
#include
#include
#include
/**
* Adds @a str to the list of expressions to execute later.
* @param str The string to add to the list of expressions.
*/
static void bc_args_exprs(const char *str) {
BC_SIG_ASSERT_LOCKED;
if (vm.exprs.v == NULL) bc_vec_init(&vm.exprs, sizeof(uchar), BC_DTOR_NONE);
bc_vec_concat(&vm.exprs, str);
bc_vec_concat(&vm.exprs, "\n");
}
/**
* Adds the contents of @a file to the list of expressions to execute later.
* @param file The name of the file whose contents should be added to the list
* of expressions to execute.
*/
static void bc_args_file(const char *file) {
char *buf;
BC_SIG_ASSERT_LOCKED;
vm.file = file;
buf = bc_read_file(file);
assert(buf != NULL);
bc_args_exprs(buf);
free(buf);
}
#if BC_ENABLED
/**
* Redefines a keyword, if it exists and is not a POSIX keyword. Otherwise, it
* throws a fatal error.
* @param keyword The keyword to redefine.
*/
static void bc_args_redefine(const char *keyword) {
size_t i;
for (i = 0; i < bc_lex_kws_len; ++i) {
const BcLexKeyword *kw = bc_lex_kws + i;
if (!strcmp(keyword, kw->name)) {
if (BC_LEX_KW_POSIX(kw)) break;
vm.redefined_kws[i] = true;
return;
}
}
bc_error(BC_ERR_FATAL_ARG, 0, keyword);
}
#endif // BC_ENABLED
void bc_args(int argc, char *argv[], bool exit_exprs) {
int c;
size_t i;
bool do_exit = false, version = false;
BcOpt opts;
BC_SIG_ASSERT_LOCKED;
bc_opt_init(&opts, argv);
// This loop should look familiar to anyone who has used getopt() or
// getopt_long() in C.
while ((c = bc_opt_parse(&opts, bc_args_lopt)) != -1) {
switch (c) {
case 'e':
{
// Barf if not allowed.
if (vm.no_exprs)
bc_verr(BC_ERR_FATAL_OPTION, "-e (--expression)");
// Add the expressions and set exit.
bc_args_exprs(opts.optarg);
vm.exit_exprs = (exit_exprs || vm.exit_exprs);
break;
}
case 'f':
{
// Figure out if exiting on expressions is disabled.
if (!strcmp(opts.optarg, "-")) vm.no_exprs = true;
else {
// Barf if not allowed.
if (vm.no_exprs)
bc_verr(BC_ERR_FATAL_OPTION, "-f (--file)");
// Add the expressions and set exit.
bc_args_file(opts.optarg);
vm.exit_exprs = (exit_exprs || vm.exit_exprs);
}
break;
}
case 'h':
{
bc_vm_info(vm.help);
do_exit = true;
break;
}
case 'i':
{
vm.flags |= BC_FLAG_I;
break;
}
+ case 'z':
+ {
+ vm.flags |= BC_FLAG_Z;
+ break;
+ }
+
+ case 'L':
+ {
+ vm.line_len = 0;
+ break;
+ }
+
case 'P':
{
vm.flags &= ~(BC_FLAG_P);
break;
}
case 'R':
{
vm.flags &= ~(BC_FLAG_R);
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);
- // Do nothing.
+ vm.flags &= ~(BC_FLAG_Q);
break;
}
case 'r':
{
bc_args_redefine(opts.optarg);
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_DC);
vm.flags |= DC_FLAG_X;
break;
}
#endif // DC_ENABLED
#ifndef NDEBUG
// We shouldn't get here because bc_opt_error()/bc_error() should
// longjmp() out.
case '?':
case ':':
default:
{
BC_UNREACHABLE
abort();
}
#endif // NDEBUG
}
}
if (version) bc_vm_info(NULL);
if (do_exit) {
vm.status = (sig_atomic_t) BC_STATUS_QUIT;
BC_JMP;
}
// We do not print the banner if expressions are used or dc is used.
if (!BC_IS_BC || vm.exprs.len > 1) vm.flags &= ~(BC_FLAG_Q);
// We need to make sure the files list is initialized. We don't want to
// initialize it if there are no files because it's just a waste of memory.
if (opts.optind < (size_t) argc && vm.files.v == NULL)
bc_vec_init(&vm.files, sizeof(char*), BC_DTOR_NONE);
// Add all the files to the vector.
for (i = opts.optind; i < (size_t) argc; ++i)
bc_vec_push(&vm.files, argv + i);
}
diff --git a/src/bc_parse.c b/src/bc_parse.c
index d0635a3b56d0..c64121ec5da8 100644
--- a/src/bc_parse.c
+++ b/src/bc_parse.c
@@ -1,2266 +1,2278 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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 bc.
*
*/
#if BC_ENABLED
#include
#include
#include
#include
#include
#include
#include
#include
// Before you embark on trying to understand this code, have you read the
// Development manual (manuals/development.md) and the comment in include/bc.h
// yet? No? Do that first. I'm serious.
//
// The reason is because this file holds the most sensitive and finicky code in
// the entire codebase. Even getting history to work on Windows was nothing
// compared to this. This is where dreams go to die, where dragons live, and
// from which Ken Thompson himself would flee.
static void bc_parse_else(BcParse *p);
static void bc_parse_stmt(BcParse *p);
static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags,
BcParseNext next);
static void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next);
/**
* Returns true if an instruction could only have come from a "leaf" expression.
* For more on what leaf expressions are, read the comment for BC_PARSE_LEAF().
* @param t The instruction to test.
*/
static bool bc_parse_inst_isLeaf(BcInst t) {
return (t >= BC_INST_NUM && t <= BC_INST_MAXSCALE) ||
#if BC_ENABLE_EXTRA_MATH
t == BC_INST_TRUNC ||
#endif // BC_ENABLE_EXTRA_MATH
t <= BC_INST_DEC;
}
/**
* Returns true if the *previous* token was a delimiter. A delimiter is anything
* that can legally end a statement. In bc's case, it could be a newline, a
* semicolon, and a brace in certain cases.
* @param p The parser.
*/
static bool bc_parse_isDelimiter(const BcParse *p) {
BcLexType t = p->l.t;
bool good;
// If it's an obvious delimiter, say so.
if (BC_PARSE_DELIMITER(t)) return true;
good = false;
// If the current token is a keyword, then...beware. That means that we need
// to check for a "dangling" else, where there was no brace-delimited block
// on the previous if.
if (t == BC_LEX_KW_ELSE) {
size_t i;
uint16_t *fptr = NULL, flags = BC_PARSE_FLAG_ELSE;
// As long as going up the stack is valid for a dangling else, keep on.
for (i = 0; i < p->flags.len && BC_PARSE_BLOCK_STMT(flags); ++i) {
fptr = bc_vec_item_rev(&p->flags, i);
flags = *fptr;
// If we need a brace and don't have one, then we don't have a
// delimiter.
if ((flags & BC_PARSE_FLAG_BRACE) && p->l.last != BC_LEX_RBRACE)
return false;
}
// Oh, and we had also better have an if statement somewhere.
good = ((flags & BC_PARSE_FLAG_IF) != 0);
}
else if (t == BC_LEX_RBRACE) {
size_t i;
// Since we have a brace, we need to just check if a brace was needed.
for (i = 0; !good && i < p->flags.len; ++i) {
uint16_t *fptr = bc_vec_item_rev(&p->flags, i);
good = (((*fptr) & BC_PARSE_FLAG_BRACE) != 0);
}
}
return good;
}
/**
* Sets a previously defined exit label. What are labels? See the bc Parsing
* section of the Development manual (manuals/development.md).
* @param p The parser.
*/
static void bc_parse_setLabel(BcParse *p) {
BcFunc *func = p->func;
BcInstPtr *ip = bc_vec_top(&p->exits);
size_t *label;
assert(func == bc_vec_item(&p->prog->fns, p->fidx));
// Set the preallocated label to the correct index.
label = bc_vec_item(&func->labels, ip->idx);
*label = func->code.len;
// Now, we don't need the exit label; it is done.
bc_vec_pop(&p->exits);
}
/**
* Creates a label and sets it to idx. If this is an exit label, then idx is
* actually invalid, but it doesn't matter because it will be fixed by
* bc_parse_setLabel() later.
* @param p The parser.
* @param idx The index of the label.
*/
static void bc_parse_createLabel(BcParse *p, size_t idx) {
bc_vec_push(&p->func->labels, &idx);
}
/**
* Creates a conditional label. Unlike an exit label, this label is set at
* creation time because it comes *before* the code that will target it.
* @param p The parser.
* @param idx The index of the label.
*/
static void bc_parse_createCondLabel(BcParse *p, size_t idx) {
bc_parse_createLabel(p, p->func->code.len);
bc_vec_push(&p->conds, &idx);
}
/*
* Creates an exit label to be filled in later by bc_parse_setLabel(). Also, why
* create a label to be filled in later? Because exit labels are meant to be
* targeted by code that comes *before* the label. Since we have to parse that
* code first, and don't know how long it will be, we need to just make sure to
* reserve a slot to be filled in later when we know.
*
* By the way, this uses BcInstPtr because it was convenient. The field idx
* holds the index, and the field func holds the loop boolean.
*
* @param p The parser.
* @param idx The index of the label's position.
* @param loop True if the exit label is for a loop or not.
*/
static void bc_parse_createExitLabel(BcParse *p, size_t idx, bool loop) {
BcInstPtr ip;
assert(p->func == bc_vec_item(&p->prog->fns, p->fidx));
ip.func = loop;
ip.idx = idx;
ip.len = 0;
bc_vec_push(&p->exits, &ip);
bc_parse_createLabel(p, SIZE_MAX);
}
/**
* Pops the correct operators off of the operator stack based on the current
* operator. This is because of the Shunting-Yard algorithm. Lower prec means
* higher precedence.
* @param p The parser.
* @param type The operator.
* @param start The previous start of the operator stack. For more
* information, see the bc Parsing section of the Development
* manual (manuals/development.md).
* @param nexprs A pointer to the current number of expressions that have not
* been consumed yet. This is an IN and OUT parameter.
*/
static void bc_parse_operator(BcParse *p, BcLexType type,
size_t start, size_t *nexprs)
{
BcLexType t;
uchar l, r = BC_PARSE_OP_PREC(type);
uchar left = BC_PARSE_OP_LEFT(type);
// While we haven't hit the stop point yet.
while (p->ops.len > start) {
// Get the top operator.
t = BC_PARSE_TOP_OP(p);
// If it's a right paren, we have reached the end of whatever expression
// this is no matter what.
if (t == BC_LEX_LPAREN) break;
// Break for precedence. Precedence operates differently on left and
// right associativity, by the way. A left associative operator that
// matches the current precedence should take priority, but a right
// associative operator should not.
l = BC_PARSE_OP_PREC(t);
if (l >= r && (l != r || !left)) break;
// Do the housekeeping. In particular, make sure to note that one
// expression was consumed. (Two were, but another was added.)
bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
bc_vec_pop(&p->ops);
*nexprs -= !BC_PARSE_OP_PREFIX(t);
}
bc_vec_push(&p->ops, &type);
}
/**
* Parses a right paren. In the Shunting-Yard algorithm, it needs to be put on
* the operator stack. But before that, it needs to consume whatever operators
* there are until it hits a left paren.
* @param p The parser.
* @param nexprs A pointer to the current number of expressions that have not
* been consumed yet. This is an IN and OUT parameter.
*/
static void bc_parse_rightParen(BcParse *p, size_t *nexprs) {
BcLexType top;
// Consume operators until a left paren.
while ((top = BC_PARSE_TOP_OP(p)) != BC_LEX_LPAREN) {
bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
bc_vec_pop(&p->ops);
*nexprs -= !BC_PARSE_OP_PREFIX(top);
}
// We need to pop the left paren as well.
bc_vec_pop(&p->ops);
// Oh, and we also want the next token.
bc_lex_next(&p->l);
}
/**
* Parses function arguments.
* @param p The parser.
* @param flags Flags restricting what kind of expressions the arguments can
* be.
*/
static void bc_parse_args(BcParse *p, uint8_t flags) {
bool comma = false;
size_t nargs;
bc_lex_next(&p->l);
// Print and comparison operators not allowed. Well, comparison operators
// only for POSIX. But we do allow arrays, and we *must* get a value.
flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
flags |= (BC_PARSE_ARRAY | BC_PARSE_NEEDVAL);
// Count the arguments and parse them.
for (nargs = 0; p->l.t != BC_LEX_RPAREN; ++nargs) {
bc_parse_expr_status(p, flags, bc_parse_next_arg);
comma = (p->l.t == BC_LEX_COMMA);
if (comma) bc_lex_next(&p->l);
}
// An ending comma is FAIL.
if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Now do the call with the number of arguments.
bc_parse_push(p, BC_INST_CALL);
bc_parse_pushIndex(p, nargs);
}
/**
* Parses a function call.
* @param p The parser.
* @param flags Flags restricting what kind of expressions the arguments can
* be.
*/
static void bc_parse_call(BcParse *p, const char *name, uint8_t flags) {
size_t idx;
bc_parse_args(p, flags);
// We just assert this because bc_parse_args() should
// ensure that the next token is what it should be.
assert(p->l.t == BC_LEX_RPAREN);
// We cannot use bc_program_insertFunc() here
// because it will overwrite an existing function.
idx = bc_map_index(&p->prog->fn_map, name);
// The function does not exist yet. Create a space for it. If the user does
// not define it, it's a *runtime* error, not a parse error.
if (idx == BC_VEC_INVALID_IDX) {
BC_SIG_LOCK;
idx = bc_program_insertFunc(p->prog, name);
BC_SIG_UNLOCK;
assert(idx != BC_VEC_INVALID_IDX);
// Make sure that this pointer was not invalidated.
p->func = bc_vec_item(&p->prog->fns, p->fidx);
}
// The function exists, so set the right function index.
else idx = ((BcId*) bc_vec_item(&p->prog->fn_map, idx))->idx;
bc_parse_pushIndex(p, idx);
// Make sure to get the next token.
bc_lex_next(&p->l);
}
/**
* Parses a name/identifier-based expression. It could be a variable, an array
* element, an array itself (for function arguments), a function call, etc.
*
*/
static void bc_parse_name(BcParse *p, BcInst *type,
bool *can_assign, uint8_t flags)
{
char *name;
BC_SIG_LOCK;
// We want a copy of the name since the lexer might overwrite its copy.
name = bc_vm_strdup(p->l.str.v);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// We need the next token to see if it's just a variable or something more.
bc_lex_next(&p->l);
// Array element or array.
if (p->l.t == BC_LEX_LBRACKET) {
bc_lex_next(&p->l);
// Array only. This has to be a function parameter.
if (p->l.t == BC_LEX_RBRACKET) {
// Error if arrays are not allowed.
if (BC_ERR(!(flags & BC_PARSE_ARRAY)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
*type = BC_INST_ARRAY;
*can_assign = false;
}
else {
// If we are here, we have an array element. We need to set the
// expression parsing flags.
uint8_t flags2 = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) |
BC_PARSE_NEEDVAL;
bc_parse_expr_status(p, flags2, bc_parse_next_elem);
// The next token *must* be a right bracket.
if (BC_ERR(p->l.t != BC_LEX_RBRACKET))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
*type = BC_INST_ARRAY_ELEM;
*can_assign = true;
}
// Make sure to get the next token.
bc_lex_next(&p->l);
// Push the instruction and the name of the identifier.
bc_parse_push(p, *type);
bc_parse_pushName(p, name, false);
}
else if (p->l.t == BC_LEX_LPAREN) {
// We are parsing a function call; error if not allowed.
if (BC_ERR(flags & BC_PARSE_NOCALL))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
*type = BC_INST_CALL;
*can_assign = false;
bc_parse_call(p, name, flags);
}
else {
// Just a variable.
*type = BC_INST_VAR;
*can_assign = true;
bc_parse_push(p, BC_INST_VAR);
bc_parse_pushName(p, name, true);
}
err:
// Need to make sure to unallocate the name.
BC_SIG_MAYLOCK;
free(name);
BC_LONGJMP_CONT;
}
/**
* Parses a builtin function that takes no arguments. This includes read(),
* rand(), maxibase(), maxobase(), maxscale(), and maxrand().
* @param p The parser.
* @param inst The instruction corresponding to the builtin.
*/
static void bc_parse_noArgBuiltin(BcParse *p, BcInst inst) {
// Must have a left paren.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Must have a right paren.
bc_lex_next(&p->l);
if ((p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_parse_push(p, inst);
bc_lex_next(&p->l);
}
/**
* Parses a builtin function that takes 1 argument. This includes length(),
* sqrt(), abs(), scale(), and irand().
* @param p The parser.
* @param type The lex token.
* @param flags The expression parsing flags for parsing the argument.
* @param prev An out parameter; the previous instruction pointer.
*/
static void bc_parse_builtin(BcParse *p, BcLexType type,
uint8_t flags, BcInst *prev)
{
// Must have a left paren.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Change the flags as needed for parsing the argument.
flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
flags |= BC_PARSE_NEEDVAL;
// Since length can take arrays, we need to specially add that flag.
if (type == BC_LEX_KW_LENGTH) flags |= BC_PARSE_ARRAY;
bc_parse_expr_status(p, flags, bc_parse_next_rel);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Adjust previous based on the token and push it.
*prev = type - BC_LEX_KW_LENGTH + BC_INST_LENGTH;
bc_parse_push(p, *prev);
bc_lex_next(&p->l);
}
/**
* Parses a builtin function that takes 3 arguments. This includes modexp() and
* divmod().
*/
static void bc_parse_builtin3(BcParse *p, BcLexType type,
uint8_t flags, BcInst *prev)
{
assert(type == BC_LEX_KW_MODEXP || type == BC_LEX_KW_DIVMOD);
// Must have a left paren.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Change the flags as needed for parsing the argument.
flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
flags |= BC_PARSE_NEEDVAL;
bc_parse_expr_status(p, flags, bc_parse_next_builtin);
// Must have a comma.
if (BC_ERR(p->l.t != BC_LEX_COMMA))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
bc_parse_expr_status(p, flags, bc_parse_next_builtin);
// Must have a comma.
if (BC_ERR(p->l.t != BC_LEX_COMMA))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// If it is a divmod, parse an array name. Otherwise, just parse another
// expression.
if (type == BC_LEX_KW_DIVMOD) {
// Must have a name.
if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// This is safe because the next token should not overwrite the name.
bc_lex_next(&p->l);
// Must have a left bracket.
if (BC_ERR(p->l.t != BC_LEX_LBRACKET))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// This is safe because the next token should not overwrite the name.
bc_lex_next(&p->l);
// Must have a right bracket.
if (BC_ERR(p->l.t != BC_LEX_RBRACKET))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// This is safe because the next token should not overwrite the name.
bc_lex_next(&p->l);
}
else bc_parse_expr_status(p, flags, bc_parse_next_rel);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Adjust previous based on the token and push it.
*prev = type - BC_LEX_KW_MODEXP + BC_INST_MODEXP;
bc_parse_push(p, *prev);
// If we have divmod, we need to assign the modulus to the array element, so
// we need to push the instructions for doing so.
if (type == BC_LEX_KW_DIVMOD) {
// The zeroth element.
bc_parse_push(p, BC_INST_ZERO);
bc_parse_push(p, BC_INST_ARRAY_ELEM);
// Push the array.
bc_parse_pushName(p, p->l.str.v, false);
// Swap them and assign. After this, the top item on the stack should
// be the quotient.
bc_parse_push(p, BC_INST_SWAP);
bc_parse_push(p, BC_INST_ASSIGN_NO_VAL);
}
bc_lex_next(&p->l);
}
/**
* Parses the scale keyword. This is special because scale can be a value or a
* builtin function.
* @param p The parser.
* @param type An out parameter; the instruction for the parse.
* @param can_assign An out parameter; whether the expression can be assigned
* to.
* @param flags The expression parsing flags for parsing a scale() arg.
*/
static void bc_parse_scale(BcParse *p, BcInst *type,
bool *can_assign, uint8_t flags)
{
bc_lex_next(&p->l);
// Without the left paren, it's just the keyword.
if (p->l.t != BC_LEX_LPAREN) {
// Set, push, and return.
*type = BC_INST_SCALE;
*can_assign = true;
bc_parse_push(p, BC_INST_SCALE);
return;
}
// Handle the scale function.
*type = BC_INST_SCALE_FUNC;
*can_assign = false;
// Once again, adjust the flags.
flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
flags |= BC_PARSE_NEEDVAL;
bc_lex_next(&p->l);
bc_parse_expr_status(p, flags, bc_parse_next_rel);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_parse_push(p, BC_INST_SCALE_FUNC);
bc_lex_next(&p->l);
}
/**
* Parses and increment or decrement operator. This is a bit complex.
* @param p The parser.
* @param prev An out parameter; the previous instruction pointer.
* @param can_assign An out parameter; whether the expression can be assigned
* to.
* @param nexs An in/out parameter; the number of expressions in the
* parse tree that are not used.
* @param flags The expression parsing flags for parsing a scale() arg.
*/
static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign,
size_t *nexs, uint8_t flags)
{
BcLexType type;
uchar inst;
BcInst etype = *prev;
BcLexType last = p->l.last;
assert(prev != NULL && can_assign != NULL);
// If we can't assign to the previous token, then we have an error.
if (BC_ERR(last == BC_LEX_OP_INC || last == BC_LEX_OP_DEC ||
last == BC_LEX_RPAREN))
{
bc_parse_err(p, BC_ERR_PARSE_ASSIGN);
}
// Is the previous instruction for a variable?
if (BC_PARSE_INST_VAR(etype)) {
// If so, this is a postfix operator.
if (!*can_assign) bc_parse_err(p, BC_ERR_PARSE_ASSIGN);
// Only postfix uses BC_INST_INC and BC_INST_DEC.
*prev = inst = BC_INST_INC + (p->l.t != BC_LEX_OP_INC);
bc_parse_push(p, inst);
bc_lex_next(&p->l);
*can_assign = false;
}
else {
// This is a prefix operator. In that case, we just convert it to
// an assignment instruction.
*prev = inst = BC_INST_ASSIGN_PLUS + (p->l.t != BC_LEX_OP_INC);
bc_lex_next(&p->l);
type = p->l.t;
// Because we parse the next part of the expression
// right here, we need to increment this.
*nexs = *nexs + 1;
// Is the next token a normal identifier?
if (type == BC_LEX_NAME) {
// Parse the name.
uint8_t flags2 = flags & ~BC_PARSE_ARRAY;
bc_parse_name(p, prev, can_assign, flags2 | BC_PARSE_NOCALL);
}
// Is the next token a global?
else if (type >= BC_LEX_KW_LAST && type <= BC_LEX_KW_OBASE) {
bc_parse_push(p, type - BC_LEX_KW_LAST + BC_INST_LAST);
bc_lex_next(&p->l);
}
// Is the next token specifically scale, which needs special treatment?
else if (BC_NO_ERR(type == BC_LEX_KW_SCALE)) {
bc_lex_next(&p->l);
// Check that scale() was not used.
if (BC_ERR(p->l.t == BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
else bc_parse_push(p, BC_INST_SCALE);
}
// Now we know we have an error.
else bc_parse_err(p, BC_ERR_PARSE_TOKEN);
*can_assign = false;
bc_parse_push(p, BC_INST_ONE);
bc_parse_push(p, inst);
}
}
/**
* Parses the minus operator. This needs special treatment because it is either
* subtract or negation.
* @param p The parser.
* @param prev An in/out parameter; the previous instruction.
* @param ops_bgn The size of the operator stack.
* @param rparen True if the last token was a right paren.
* @param binlast True if the last token was a binary operator.
* @param nexprs An in/out parameter; the number of unused expressions.
*/
static void bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
bool rparen, bool binlast, size_t *nexprs)
{
BcLexType type;
bc_lex_next(&p->l);
// Figure out if it's a minus or a negation.
type = BC_PARSE_LEAF(*prev, binlast, rparen) ? BC_LEX_OP_MINUS : BC_LEX_NEG;
*prev = BC_PARSE_TOKEN_INST(type);
// We can just push onto the op stack because this is the largest
// precedence operator that gets pushed. Inc/dec does not.
if (type != BC_LEX_OP_MINUS) bc_vec_push(&p->ops, &type);
else bc_parse_operator(p, type, ops_bgn, nexprs);
}
/**
* Parses a string.
* @param p The parser.
* @param inst The instruction corresponding to how the string was found and
* how it should be printed.
*/
static void bc_parse_str(BcParse *p, BcInst inst) {
bc_parse_addString(p);
bc_parse_push(p, inst);
bc_lex_next(&p->l);
}
/**
* Parses a print statement.
* @param p The parser.
*/
static void bc_parse_print(BcParse *p, BcLexType type) {
BcLexType t;
bool comma = false;
BcInst inst = type == BC_LEX_KW_STREAM ?
BC_INST_PRINT_STREAM : BC_INST_PRINT_POP;
bc_lex_next(&p->l);
t = p->l.t;
// A print or stream statement has to have *something*.
if (bc_parse_isDelimiter(p)) bc_parse_err(p, BC_ERR_PARSE_PRINT);
do {
// If the token is a string, then print it with escapes.
// BC_INST_PRINT_POP plays that role for bc.
if (t == BC_LEX_STR) bc_parse_str(p, inst);
else {
// We have an actual number; parse and add a print instruction.
bc_parse_expr_status(p, BC_PARSE_NEEDVAL, bc_parse_next_print);
bc_parse_push(p, inst);
}
// Is the next token a comma?
comma = (p->l.t == BC_LEX_COMMA);
// Get the next token if we have a comma.
if (comma) bc_lex_next(&p->l);
else {
// If we don't have a comma, the statement needs to end.
if (!bc_parse_isDelimiter(p))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
else break;
}
t = p->l.t;
} while (true);
// If we have a comma but no token, that's bad.
if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
/**
* Parses a return statement.
* @param p The parser.
*/
static void bc_parse_return(BcParse *p) {
BcLexType t;
bool paren;
uchar inst = BC_INST_RET0;
// If we are not in a function, that's an error.
if (BC_ERR(!BC_PARSE_FUNC(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// If we are in a void function, make sure to return void.
if (p->func->voidfn) inst = BC_INST_RET_VOID;
bc_lex_next(&p->l);
t = p->l.t;
paren = (t == BC_LEX_LPAREN);
// An empty return statement just needs to push the selected instruction.
if (bc_parse_isDelimiter(p)) bc_parse_push(p, inst);
else {
BcParseStatus s;
// Need to parse the expression whose value will be returned.
s = bc_parse_expr_err(p, BC_PARSE_NEEDVAL, bc_parse_next_expr);
// If the expression was empty, just push the selected instruction.
if (s == BC_PARSE_STATUS_EMPTY_EXPR) {
bc_parse_push(p, inst);
bc_lex_next(&p->l);
}
// POSIX requires parentheses.
if (!paren || p->l.last != BC_LEX_RPAREN) {
bc_parse_err(p, BC_ERR_POSIX_RET);
}
// Void functions require an empty expression.
if (BC_ERR(p->func->voidfn)) {
if (s != BC_PARSE_STATUS_EMPTY_EXPR)
bc_parse_verr(p, BC_ERR_PARSE_RET_VOID, p->func->name);
}
// If we got here, we want to be sure to end the function with a real
// return instruction, just in case.
else bc_parse_push(p, BC_INST_RET);
}
}
/**
* Clears flags that indicate the end of an if statement and its block and sets
* the jump location.
* @param p The parser.
*/
static void bc_parse_noElse(BcParse *p) {
uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
*flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
bc_parse_setLabel(p);
}
/**
* Ends (finishes parsing) the body of a control statement or a function.
* @param p The parser.
* @param brace True if the body was ended by a brace, false otherwise.
*/
static void bc_parse_endBody(BcParse *p, bool brace) {
bool has_brace, new_else = false;
// We cannot be ending a body if there are no bodies to end.
if (BC_ERR(p->flags.len <= 1)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
if (brace) {
// The brace was already gotten; make sure that the caller did not lie.
// We check for the requirement of braces later.
assert(p->l.t == BC_LEX_RBRACE);
bc_lex_next(&p->l);
// If the next token is not a delimiter, that is a problem.
if (BC_ERR(!bc_parse_isDelimiter(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
// Do we have a brace flag?
has_brace = (BC_PARSE_BRACE(p) != 0);
do {
size_t len = p->flags.len;
bool loop;
// If we have a brace flag but not a brace, that's a problem.
if (has_brace && !brace) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Are we inside a loop?
loop = (BC_PARSE_LOOP_INNER(p) != 0);
// If we are ending a loop or an else...
if (loop || BC_PARSE_ELSE(p)) {
// Loops have condition labels that we have to take care of as well.
if (loop) {
size_t *label = bc_vec_top(&p->conds);
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, *label);
bc_vec_pop(&p->conds);
}
bc_parse_setLabel(p);
bc_vec_pop(&p->flags);
}
// If we are ending a function...
else if (BC_PARSE_FUNC_INNER(p)) {
BcInst inst = (p->func->voidfn ? BC_INST_RET_VOID : BC_INST_RET0);
bc_parse_push(p, inst);
bc_parse_updateFunc(p, BC_PROG_MAIN);
bc_vec_pop(&p->flags);
}
// If we have a brace flag and not an if statement, we can pop the top
// of the flags stack because they have been taken care of above.
else if (has_brace && !BC_PARSE_IF(p)) bc_vec_pop(&p->flags);
// This needs to be last to parse nested if's properly.
if (BC_PARSE_IF(p) && (len == p->flags.len || !BC_PARSE_BRACE(p))) {
// Eat newlines.
while (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l);
// *Now* we can pop the flags.
bc_vec_pop(&p->flags);
// If we are allowed non-POSIX stuff...
if (!BC_S) {
// Have we found yet another dangling else?
*(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_IF_END;
new_else = (p->l.t == BC_LEX_KW_ELSE);
// Parse the else or end the if statement body.
if (new_else) bc_parse_else(p);
else if (!has_brace && (!BC_PARSE_IF_END(p) || brace))
bc_parse_noElse(p);
}
// POSIX requires us to do the bare minimum only.
else bc_parse_noElse(p);
}
// If these are both true, we have "used" the braces that we found.
if (brace && has_brace) brace = false;
// This condition was perhaps the hardest single part of the parser. If the
// flags stack does not have enough, we should stop. If we have a new else
// statement, we should stop. If we do have the end of an if statement and
// we have eaten the brace, we should stop. If we do have a brace flag, we
// should stop.
} while (p->flags.len > 1 && !new_else && (!BC_PARSE_IF_END(p) || brace) &&
!(has_brace = (BC_PARSE_BRACE(p) != 0)));
// If we have a brace, yet no body for it, that's a problem.
if (BC_ERR(p->flags.len == 1 && brace))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
else if (brace && BC_PARSE_BRACE(p)) {
// If we make it here, we have a brace and a flag for it.
uint16_t flags = BC_PARSE_TOP_FLAG(p);
// This condition ensure that the *last* body is correctly finished by
// popping its flags.
if (!(flags & (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_LOOP_INNER)) &&
!(flags & (BC_PARSE_FLAG_IF | BC_PARSE_FLAG_ELSE)) &&
!(flags & (BC_PARSE_FLAG_IF_END)))
{
bc_vec_pop(&p->flags);
}
}
}
/**
* Starts the body of a control statement or function.
* @param p The parser.
* @param flags The current flags (will be edited).
*/
static void bc_parse_startBody(BcParse *p, uint16_t flags) {
assert(flags);
flags |= (BC_PARSE_TOP_FLAG(p) & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
flags |= BC_PARSE_FLAG_BODY;
bc_vec_push(&p->flags, &flags);
}
/**
* Parses an if statement.
* @param p The parser.
*/
static void bc_parse_if(BcParse *p) {
// We are allowed relational operators, and we must have a value.
size_t idx;
uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL);
// Get the left paren and barf if necessary.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Parse the condition.
bc_lex_next(&p->l);
bc_parse_expr_status(p, flags, bc_parse_next_rel);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Insert the conditional jump instruction.
bc_parse_push(p, BC_INST_JUMP_ZERO);
idx = p->func->labels.len;
// Push the index for the instruction and create an exit label for an else
// statement.
bc_parse_pushIndex(p, idx);
bc_parse_createExitLabel(p, idx, false);
bc_parse_startBody(p, BC_PARSE_FLAG_IF);
}
/**
* Parses an else statement.
* @param p The parser.
*/
static void bc_parse_else(BcParse *p) {
size_t idx = p->func->labels.len;
// We must be at the end of an if statement.
if (BC_ERR(!BC_PARSE_IF_END(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Push an unconditional jump to make bc jump over the else statement if it
// executed the original if statement.
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, idx);
// Clear the else stuff. Yes, that function is misnamed for its use here,
// but deal with it.
bc_parse_noElse(p);
// Create the exit label and parse the body.
bc_parse_createExitLabel(p, idx, false);
bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
bc_lex_next(&p->l);
}
/**
* Parse a while loop.
* @param p The parser.
*/
static void bc_parse_while(BcParse *p) {
// We are allowed relational operators, and we must have a value.
size_t idx;
uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL);
// Get the left paren and barf if necessary.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Create the labels. Loops need both.
bc_parse_createCondLabel(p, p->func->labels.len);
idx = p->func->labels.len;
bc_parse_createExitLabel(p, idx, true);
// Parse the actual condition and barf on non-right paren.
bc_parse_expr_status(p, flags, bc_parse_next_rel);
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Now we can push the conditional jump and start the body.
bc_parse_push(p, BC_INST_JUMP_ZERO);
bc_parse_pushIndex(p, idx);
bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
}
/**
* Parse a for loop.
* @param p The parser.
*/
static void bc_parse_for(BcParse *p) {
size_t cond_idx, exit_idx, body_idx, update_idx;
// Barf on the missing left paren.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// The first statement can be empty, but if it is, check for error in POSIX
// mode. Otherwise, parse it.
if (p->l.t != BC_LEX_SCOLON)
bc_parse_expr_status(p, 0, bc_parse_next_for);
else bc_parse_err(p, BC_ERR_POSIX_FOR);
// Must have a semicolon.
if (BC_ERR(p->l.t != BC_LEX_SCOLON)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// These are indices for labels. There are so many of them because the end
// of the loop must unconditionally jump to the update code. Then the update
// code must unconditionally jump to the condition code. Then the condition
// code must *conditionally* jump to the exit.
cond_idx = p->func->labels.len;
update_idx = cond_idx + 1;
body_idx = update_idx + 1;
exit_idx = body_idx + 1;
// This creates the condition label.
bc_parse_createLabel(p, p->func->code.len);
// Parse an expression if it exists.
if (p->l.t != BC_LEX_SCOLON) {
uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL);
bc_parse_expr_status(p, flags, bc_parse_next_for);
}
else {
// Set this for the next call to bc_parse_number because an empty
// condition means that it is an infinite loop, so the condition must be
// non-zero. This is safe to set because the current token is a
// semicolon, which has no string requirement.
bc_vec_string(&p->l.str, sizeof(bc_parse_one) - 1, bc_parse_one);
bc_parse_number(p);
// An empty condition makes POSIX mad.
bc_parse_err(p, BC_ERR_POSIX_FOR);
}
// Must have a semicolon.
if (BC_ERR(p->l.t != BC_LEX_SCOLON))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Now we can set up the conditional jump to the exit and an unconditional
// jump to the body right after. The unconditional jump to the body is
// because there is update code coming right after the condition, so we need
// to skip it to get to the body.
bc_parse_push(p, BC_INST_JUMP_ZERO);
bc_parse_pushIndex(p, exit_idx);
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, body_idx);
// Now create the label for the update code.
bc_parse_createCondLabel(p, update_idx);
// Parse if not empty, and if it is, let POSIX yell if necessary.
if (p->l.t != BC_LEX_RPAREN)
bc_parse_expr_status(p, 0, bc_parse_next_rel);
else bc_parse_err(p, BC_ERR_POSIX_FOR);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Set up a jump to the condition right after the update code.
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, cond_idx);
bc_parse_createLabel(p, p->func->code.len);
// Create an exit label for the body and start the body.
bc_parse_createExitLabel(p, exit_idx, true);
bc_lex_next(&p->l);
bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
}
/**
* Parse a statement or token that indicates a loop exit. This includes an
* actual loop exit, the break keyword, or the continue keyword.
* @param p The parser.
* @param type The type of exit.
*/
static void bc_parse_loopExit(BcParse *p, BcLexType type) {
size_t i;
BcInstPtr *ip;
// Must have a loop. If we don't, that's an error.
if (BC_ERR(!BC_PARSE_LOOP(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// If we have a break statement...
if (type == BC_LEX_KW_BREAK) {
// If there are no exits, something went wrong somewhere.
if (BC_ERR(!p->exits.len)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Get the exit.
i = p->exits.len - 1;
ip = bc_vec_item(&p->exits, i);
// The condition !ip->func is true if the exit is not for a loop, so we
// need to find the first actual loop exit.
while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
// Make sure everything is hunky dory.
assert(ip != NULL && (i < p->exits.len || ip->func));
// Set the index for the exit.
i = ip->idx;
}
// If we have a continue statement or just the loop end, jump to the
// condition (or update for a foor loop).
else i = *((size_t*) bc_vec_top(&p->conds));
// Add the unconditional jump.
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, i);
bc_lex_next(&p->l);
}
/**
* Parse a function (header).
* @param p The parser.
*/
static void bc_parse_func(BcParse *p) {
bool comma = false, voidfn;
uint16_t flags;
size_t idx;
bc_lex_next(&p->l);
// Must have a name.
if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERR_PARSE_FUNC);
// If the name is "void", and POSIX is not on, mark as void.
voidfn = (!BC_IS_POSIX && p->l.t == BC_LEX_NAME &&
!strcmp(p->l.str.v, "void"));
// We can safely do this because the expected token should not overwrite the
// function name.
bc_lex_next(&p->l);
// If we *don't* have another name, then void is the name of the function.
voidfn = (voidfn && p->l.t == BC_LEX_NAME);
// With a void function, allow POSIX to complain and get a new token.
if (voidfn) {
bc_parse_err(p, BC_ERR_POSIX_VOID);
// We can safely do this because the expected token should not overwrite
// the function name.
bc_lex_next(&p->l);
}
// Must have a left paren.
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_FUNC);
// Make sure the functions map and vector are synchronized.
assert(p->prog->fns.len == p->prog->fn_map.len);
// Must lock signals because vectors are changed, and the vector functions
// expect signals to be locked.
BC_SIG_LOCK;
// Insert the function by name into the map and vector.
idx = bc_program_insertFunc(p->prog, p->l.str.v);
BC_SIG_UNLOCK;
// Make sure the insert worked.
assert(idx);
// Update the function pointer and stuff in the parser and set its void.
bc_parse_updateFunc(p, idx);
p->func->voidfn = voidfn;
bc_lex_next(&p->l);
// While we do not have a right paren, we are still parsing arguments.
while (p->l.t != BC_LEX_RPAREN) {
BcType t = BC_TYPE_VAR;
// If we have an asterisk, we are parsing a reference argument.
if (p->l.t == BC_LEX_OP_MULTIPLY) {
t = BC_TYPE_REF;
bc_lex_next(&p->l);
// Let POSIX complain if necessary.
bc_parse_err(p, BC_ERR_POSIX_REF);
}
// If we don't have a name, the argument will not have a name. Barf.
if (BC_ERR(p->l.t != BC_LEX_NAME))
bc_parse_err(p, BC_ERR_PARSE_FUNC);
// Increment the number of parameters.
p->func->nparams += 1;
// Copy the string in the lexer so that we can use the lexer again.
bc_vec_string(&p->buf, p->l.str.len, p->l.str.v);
bc_lex_next(&p->l);
// We are parsing an array parameter if this is true.
if (p->l.t == BC_LEX_LBRACKET) {
// Set the array type, unless we are already parsing a reference.
if (t == BC_TYPE_VAR) t = BC_TYPE_ARRAY;
bc_lex_next(&p->l);
// The brackets *must* be empty.
if (BC_ERR(p->l.t != BC_LEX_RBRACKET))
bc_parse_err(p, BC_ERR_PARSE_FUNC);
bc_lex_next(&p->l);
}
// If we did *not* get a bracket, but we are expecting a reference, we
// have a problem.
else if (BC_ERR(t == BC_TYPE_REF))
bc_parse_verr(p, BC_ERR_PARSE_REF_VAR, p->buf.v);
// Test for comma and get the next token if it exists.
comma = (p->l.t == BC_LEX_COMMA);
if (comma) bc_lex_next(&p->l);
// Insert the parameter into the function.
bc_func_insert(p->func, p->prog, p->buf.v, t, p->l.line);
}
// If we have a comma, but no parameter, barf.
if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_FUNC);
// Start the body.
flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER;
bc_parse_startBody(p, flags);
bc_lex_next(&p->l);
// POSIX requires that a brace be on the same line as the function header.
// If we don't have a brace, let POSIX throw an error.
if (p->l.t != BC_LEX_LBRACE) bc_parse_err(p, BC_ERR_POSIX_BRACE);
}
/**
* Parse an auto list.
* @param p The parser.
*/
static void bc_parse_auto(BcParse *p) {
bool comma, one;
// Error if the auto keyword appeared in the wrong place.
if (BC_ERR(!p->auto_part)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
p->auto_part = comma = false;
// We need at least one variable or array.
one = (p->l.t == BC_LEX_NAME);
// While we have a variable or array.
while (p->l.t == BC_LEX_NAME) {
BcType t;
// Copy the name from the lexer, so we can use it again.
bc_vec_string(&p->buf, p->l.str.len - 1, p->l.str.v);
bc_lex_next(&p->l);
// If we are parsing an array...
if (p->l.t == BC_LEX_LBRACKET) {
t = BC_TYPE_ARRAY;
bc_lex_next(&p->l);
// The brackets *must* be empty.
if (BC_ERR(p->l.t != BC_LEX_RBRACKET))
bc_parse_err(p, BC_ERR_PARSE_FUNC);
bc_lex_next(&p->l);
}
else t = BC_TYPE_VAR;
// Test for comma and get the next token if it exists.
comma = (p->l.t == BC_LEX_COMMA);
if (comma) bc_lex_next(&p->l);
// Insert the auto into the function.
bc_func_insert(p->func, p->prog, p->buf.v, t, p->l.line);
}
// If we have a comma, but no auto, barf.
if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_FUNC);
// If we don't have any variables or arrays, barf.
if (BC_ERR(!one)) bc_parse_err(p, BC_ERR_PARSE_NO_AUTO);
// The auto statement should be all that's in the statement.
if (BC_ERR(!bc_parse_isDelimiter(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
/**
* Parses a body.
* @param p The parser.
* @param brace True if a brace was encountered, false otherwise.
*/
static void bc_parse_body(BcParse *p, bool brace) {
uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
assert(flag_ptr != NULL);
assert(p->flags.len >= 2);
// The body flag is for when we expect a body. We got a body, so clear the
// flag.
*flag_ptr &= ~(BC_PARSE_FLAG_BODY);
// If we are inside a function, that means we just barely entered it, and
// we can expect an auto list.
if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
// We *must* have a brace in this case.
if (BC_ERR(!brace)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
p->auto_part = (p->l.t != BC_LEX_KW_AUTO);
if (!p->auto_part) {
// Make sure this is true to not get a parse error.
p->auto_part = true;
// Since we already have the auto keyword, parse.
bc_parse_auto(p);
}
// Eat a newline.
if (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l);
}
else {
// This is the easy part.
size_t len = p->flags.len;
assert(*flag_ptr);
// Parse a statement.
bc_parse_stmt(p);
// This is a very important condition to get right. If there is no
// brace, and no body flag, and the flags len hasn't shrunk, then we
// have a body that was not delimited by braces, so we need to end it
// now, after just one statement.
if (!brace && !BC_PARSE_BODY(p) && len <= p->flags.len)
bc_parse_endBody(p, false);
}
}
/**
* Parses a statement. This is the entry point for just about everything, except
* function definitions.
* @param p The parser.
*/
static void bc_parse_stmt(BcParse *p) {
size_t len;
uint16_t flags;
BcLexType type = p->l.t;
// Eat newline.
if (type == BC_LEX_NLINE) {
bc_lex_next(&p->l);
return;
}
// Eat auto list.
if (type == BC_LEX_KW_AUTO) {
bc_parse_auto(p);
return;
}
// If we reach this point, no auto list is allowed.
p->auto_part = false;
// Everything but an else needs to be taken care of here, but else is
// special.
if (type != BC_LEX_KW_ELSE) {
// After an if, no else found.
if (BC_PARSE_IF_END(p)) {
// Clear the expectation for else, end body, and return. Returning
// gives us a clean slate for parsing again.
bc_parse_noElse(p);
if (p->flags.len > 1 && !BC_PARSE_BRACE(p))
bc_parse_endBody(p, false);
return;
}
// With a left brace, we are parsing a body.
else if (type == BC_LEX_LBRACE) {
// We need to start a body if we are not expecting one yet.
if (!BC_PARSE_BODY(p)) {
bc_parse_startBody(p, BC_PARSE_FLAG_BRACE);
bc_lex_next(&p->l);
}
// If we *are* expecting a body, that body should get a brace. This
// takes care of braces being on a different line than if and loop
// headers.
else {
*(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_BRACE;
bc_lex_next(&p->l);
bc_parse_body(p, true);
}
// If we have reached this point, we need to return for a clean
// slate.
return;
}
// This happens when we are expecting a body and get a single statement,
// i.e., a body with no braces surrounding it. Returns after for a clean
// slate.
else if (BC_PARSE_BODY(p) && !BC_PARSE_BRACE(p)) {
bc_parse_body(p, false);
return;
}
}
len = p->flags.len;
flags = BC_PARSE_TOP_FLAG(p);
switch (type) {
// All of these are valid for expressions.
case BC_LEX_OP_INC:
case BC_LEX_OP_DEC:
case BC_LEX_OP_MINUS:
case BC_LEX_OP_BOOL_NOT:
case BC_LEX_LPAREN:
case BC_LEX_NAME:
case BC_LEX_NUMBER:
case BC_LEX_KW_IBASE:
case BC_LEX_KW_LAST:
case BC_LEX_KW_LENGTH:
case BC_LEX_KW_OBASE:
case BC_LEX_KW_SCALE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_SEED:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_SQRT:
case BC_LEX_KW_ABS:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_IRAND:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_ASCIIFY:
case BC_LEX_KW_MODEXP:
case BC_LEX_KW_DIVMOD:
case BC_LEX_KW_READ:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_RAND:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_MAXIBASE:
case BC_LEX_KW_MAXOBASE:
case BC_LEX_KW_MAXSCALE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_MAXRAND:
#endif // BC_ENABLE_EXTRA_MATH
+ case BC_LEX_KW_LINE_LENGTH:
+ case BC_LEX_KW_GLOBAL_STACKS:
+ case BC_LEX_KW_LEADING_ZERO:
{
bc_parse_expr_status(p, BC_PARSE_PRINT, bc_parse_next_expr);
break;
}
case BC_LEX_KW_ELSE:
{
bc_parse_else(p);
break;
}
// Just eat.
case BC_LEX_SCOLON:
{
// Do nothing.
break;
}
case BC_LEX_RBRACE:
{
bc_parse_endBody(p, true);
break;
}
case BC_LEX_STR:
{
bc_parse_str(p, BC_INST_PRINT_STR);
break;
}
case BC_LEX_KW_BREAK:
case BC_LEX_KW_CONTINUE:
{
bc_parse_loopExit(p, p->l.t);
break;
}
case BC_LEX_KW_FOR:
{
bc_parse_for(p);
break;
}
case BC_LEX_KW_HALT:
{
bc_parse_push(p, BC_INST_HALT);
bc_lex_next(&p->l);
break;
}
case BC_LEX_KW_IF:
{
bc_parse_if(p);
break;
}
case BC_LEX_KW_LIMITS:
{
// `limits` is a compile-time command, so execute it right away.
bc_vm_printf("BC_LONG_BIT = %lu\n", (ulong) BC_LONG_BIT);
bc_vm_printf("BC_BASE_DIGS = %lu\n", (ulong) BC_BASE_DIGS);
bc_vm_printf("BC_BASE_POW = %lu\n", (ulong) BC_BASE_POW);
bc_vm_printf("BC_OVERFLOW_MAX = %lu\n", (ulong) BC_NUM_BIGDIG_MAX);
bc_vm_printf("\n");
bc_vm_printf("BC_BASE_MAX = %lu\n", BC_MAX_OBASE);
bc_vm_printf("BC_DIM_MAX = %lu\n", BC_MAX_DIM);
bc_vm_printf("BC_SCALE_MAX = %lu\n", BC_MAX_SCALE);
bc_vm_printf("BC_STRING_MAX = %lu\n", BC_MAX_STRING);
bc_vm_printf("BC_NAME_MAX = %lu\n", BC_MAX_NAME);
bc_vm_printf("BC_NUM_MAX = %lu\n", BC_MAX_NUM);
#if BC_ENABLE_EXTRA_MATH
bc_vm_printf("BC_RAND_MAX = %lu\n", BC_MAX_RAND);
#endif // BC_ENABLE_EXTRA_MATH
bc_vm_printf("MAX Exponent = %lu\n", BC_MAX_EXP);
bc_vm_printf("Number of vars = %lu\n", BC_MAX_VARS);
bc_lex_next(&p->l);
break;
}
case BC_LEX_KW_STREAM:
case BC_LEX_KW_PRINT:
{
bc_parse_print(p, type);
break;
}
case BC_LEX_KW_QUIT:
{
// Quit is a compile-time command. We don't exit directly, so the vm
// can clean up.
vm.status = BC_STATUS_QUIT;
BC_JMP;
break;
}
case BC_LEX_KW_RETURN:
{
bc_parse_return(p);
break;
}
case BC_LEX_KW_WHILE:
{
bc_parse_while(p);
break;
}
default:
{
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
}
// If the flags did not change, we expect a delimiter.
if (len == p->flags.len && flags == BC_PARSE_TOP_FLAG(p)) {
if (BC_ERR(!bc_parse_isDelimiter(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
// Make sure semicolons are eaten.
while (p->l.t == BC_LEX_SCOLON) bc_lex_next(&p->l);
}
void bc_parse_parse(BcParse *p) {
assert(p);
BC_SETJMP(exit);
// We should not let an EOF get here unless some partial parse was not
// completed, in which case, it's the user's fault.
if (BC_ERR(p->l.t == BC_LEX_EOF)) bc_parse_err(p, BC_ERR_PARSE_EOF);
// Functions need special parsing.
else if (p->l.t == BC_LEX_KW_DEFINE) {
- if (BC_ERR(BC_PARSE_NO_EXEC(p)))
- bc_parse_err(p, BC_ERR_PARSE_TOKEN);
+ if (BC_ERR(BC_PARSE_NO_EXEC(p))) {
+ if (p->flags.len == 1 &&
+ BC_PARSE_TOP_FLAG(p) == BC_PARSE_FLAG_IF_END)
+ {
+ bc_parse_noElse(p);
+ }
+ else bc_parse_err(p, BC_ERR_PARSE_TOKEN);
+ }
bc_parse_func(p);
}
// Otherwise, parse a normal statement.
else bc_parse_stmt(p);
exit:
BC_SIG_MAYLOCK;
// We need to reset on error.
if (BC_ERR(((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig)))
bc_parse_reset(p);
BC_LONGJMP_CONT;
}
/**
* Parse an expression. This is the actual implementation of the Shunting-Yard
* Algorithm.
* @param p The parser.
* @param flags The flags for what is valid in the expression.
* @param next A set of tokens for what is valid *after* the expression.
* @return A parse status. In some places, an empty expression is an
* error, and sometimes, it is required. This allows this function
* to tell the caller if the expression was empty and let the
* caller handle it.
*/
static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags,
BcParseNext next)
{
BcInst prev = BC_INST_PRINT;
uchar inst = BC_INST_INVALID;
BcLexType top, t;
size_t nexprs, ops_bgn;
uint32_t i, nparens, nrelops;
bool pfirst, rprn, done, get_token, assign, bin_last, incdec, can_assign;
// One of these *must* be true.
assert(!(flags & BC_PARSE_PRINT) || !(flags & BC_PARSE_NEEDVAL));
// These are set very carefully. In fact, controlling the values of these
// locals is the biggest part of making this work. ops_bgn especially is
// important because it marks where the operator stack begins for *this*
// invocation of this function. That's because bc_parse_expr_err() is
// recursive (the Shunting-Yard Algorithm is most easily expressed
// recursively when parsing subexpressions), and each invocation needs to
// know where to stop.
//
// - nparens is the number of left parens without matches.
// - nrelops is the number of relational operators that appear in the expr.
// - nexprs is the number of unused expressions.
// - rprn is a right paren encountered last.
// - done means the expression has been fully parsed.
// - get_token is true when a token is needed at the end of an iteration.
// - assign is true when an assignment statement was parsed last.
// - incdec is true when the previous operator was an inc or dec operator.
// - can_assign is true when an assignemnt is valid.
// - bin_last is true when the previous instruction was a binary operator.
t = p->l.t;
pfirst = (p->l.t == BC_LEX_LPAREN);
nparens = nrelops = 0;
nexprs = 0;
ops_bgn = p->ops.len;
rprn = done = get_token = assign = incdec = can_assign = false;
bin_last = true;
// We want to eat newlines if newlines are not a valid ending token.
// This is for spacing in things like for loop headers.
if (!(flags & BC_PARSE_NOREAD)) {
while ((t = p->l.t) == BC_LEX_NLINE) bc_lex_next(&p->l);
}
// This is the Shunting-Yard algorithm loop.
for (; !done && BC_PARSE_EXPR(t); t = p->l.t)
{
switch (t) {
case BC_LEX_OP_INC:
case BC_LEX_OP_DEC:
{
// These operators can only be used with items that can be
// assigned to.
if (BC_ERR(incdec)) bc_parse_err(p, BC_ERR_PARSE_ASSIGN);
bc_parse_incdec(p, &prev, &can_assign, &nexprs, flags);
rprn = get_token = bin_last = false;
incdec = true;
flags &= ~(BC_PARSE_ARRAY);
break;
}
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_TRUNC:
{
// The previous token must have been a leaf expression, or the
// operator is in the wrong place.
if (BC_ERR(!BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// I can just add the instruction because
// negative will already be taken care of.
bc_parse_push(p, BC_INST_TRUNC);
rprn = can_assign = incdec = false;
get_token = true;
flags &= ~(BC_PARSE_ARRAY);
break;
}
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_MINUS:
{
bc_parse_minus(p, &prev, ops_bgn, rprn, bin_last, &nexprs);
rprn = get_token = can_assign = false;
// This is true if it was a binary operator last.
bin_last = (prev == BC_INST_MINUS);
if (bin_last) incdec = false;
flags &= ~(BC_PARSE_ARRAY);
break;
}
// All of this group, including the fallthrough, is to parse binary
// operators.
case BC_LEX_OP_ASSIGN_POWER:
case BC_LEX_OP_ASSIGN_MULTIPLY:
case BC_LEX_OP_ASSIGN_DIVIDE:
case BC_LEX_OP_ASSIGN_MODULUS:
case BC_LEX_OP_ASSIGN_PLUS:
case BC_LEX_OP_ASSIGN_MINUS:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_ASSIGN_PLACES:
case BC_LEX_OP_ASSIGN_LSHIFT:
case BC_LEX_OP_ASSIGN_RSHIFT:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_ASSIGN:
{
// We need to make sure the assignment is valid.
if (!BC_PARSE_INST_VAR(prev))
bc_parse_err(p, BC_ERR_PARSE_ASSIGN);
}
// Fallthrough.
BC_FALLTHROUGH
case BC_LEX_OP_POWER:
case BC_LEX_OP_MULTIPLY:
case BC_LEX_OP_DIVIDE:
case BC_LEX_OP_MODULUS:
case BC_LEX_OP_PLUS:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_PLACES:
case BC_LEX_OP_LSHIFT:
case BC_LEX_OP_RSHIFT:
#endif // BC_ENABLE_EXTRA_MATH
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:
case BC_LEX_OP_BOOL_NOT:
case BC_LEX_OP_BOOL_OR:
case BC_LEX_OP_BOOL_AND:
{
// This is true if the operator if the token is a prefix
// operator. This is only for boolean not.
if (BC_PARSE_OP_PREFIX(t)) {
// Prefix operators are only allowed after binary operators
// or prefix operators.
if (BC_ERR(!bin_last && !BC_PARSE_OP_PREFIX(p->l.last)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
}
// If we execute the else, that means we have a binary operator.
// If the previous operator was a prefix or a binary operator,
// then a binary operator is not allowed.
else if (BC_ERR(BC_PARSE_PREV_PREFIX(prev) || bin_last))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
nrelops += (t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT);
prev = BC_PARSE_TOKEN_INST(t);
bc_parse_operator(p, t, ops_bgn, &nexprs);
rprn = incdec = can_assign = false;
get_token = true;
bin_last = !BC_PARSE_OP_PREFIX(t);
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_LPAREN:
{
// A left paren is *not* allowed right after a leaf expr.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
nparens += 1;
rprn = incdec = can_assign = false;
get_token = true;
// Push the paren onto the operator stack.
bc_vec_push(&p->ops, &t);
break;
}
case BC_LEX_RPAREN:
{
// This needs to be a status. The error is handled in
// bc_parse_expr_status().
if (BC_ERR(p->l.last == BC_LEX_LPAREN))
return BC_PARSE_STATUS_EMPTY_EXPR;
// The right paren must not come after a prefix or binary
// operator.
if (BC_ERR(bin_last || BC_PARSE_PREV_PREFIX(prev)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// If there are no parens left, we are done, but we need another
// token.
if (!nparens) {
done = true;
get_token = false;
break;
}
nparens -= 1;
rprn = true;
get_token = bin_last = incdec = false;
bc_parse_rightParen(p, &nexprs);
break;
}
case BC_LEX_STR:
{
// POSIX only allows strings alone.
if (BC_IS_POSIX) bc_parse_err(p, BC_ERR_POSIX_EXPR_STRING);
// A string is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
bc_parse_addString(p);
get_token = true;
bin_last = rprn = false;
nexprs += 1;
break;
}
case BC_LEX_NAME:
{
// A name is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
get_token = bin_last = false;
bc_parse_name(p, &prev, &can_assign, flags & ~BC_PARSE_NOCALL);
rprn = (prev == BC_INST_CALL);
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_NUMBER:
{
// A number is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// The number instruction is pushed in here.
bc_parse_number(p);
nexprs += 1;
prev = BC_INST_NUM;
get_token = true;
rprn = bin_last = can_assign = false;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_IBASE:
case BC_LEX_KW_LAST:
case BC_LEX_KW_OBASE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_SEED:
#endif // BC_ENABLE_EXTRA_MATH
{
// All of these are leaves and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
prev = t - BC_LEX_KW_LAST + BC_INST_LAST;
bc_parse_push(p, prev);
get_token = can_assign = true;
rprn = bin_last = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_LENGTH:
case BC_LEX_KW_SQRT:
case BC_LEX_KW_ABS:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_IRAND:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_ASCIIFY:
{
// All of these are leaves and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
bc_parse_builtin(p, t, flags, &prev);
rprn = get_token = bin_last = incdec = can_assign = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_READ:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_RAND:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_MAXIBASE:
case BC_LEX_KW_MAXOBASE:
case BC_LEX_KW_MAXSCALE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_MAXRAND:
#endif // BC_ENABLE_EXTRA_MATH
+ case BC_LEX_KW_LINE_LENGTH:
+ case BC_LEX_KW_GLOBAL_STACKS:
+ case BC_LEX_KW_LEADING_ZERO:
{
// All of these are leaves and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// Error if we have read and it's not allowed.
else if (t == BC_LEX_KW_READ && BC_ERR(flags & BC_PARSE_NOREAD))
bc_parse_err(p, BC_ERR_EXEC_REC_READ);
prev = t - BC_LEX_KW_READ + BC_INST_READ;
bc_parse_noArgBuiltin(p, prev);
rprn = get_token = bin_last = incdec = can_assign = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_SCALE:
{
// This is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// Scale needs special work because it can be a variable *or* a
// function.
bc_parse_scale(p, &prev, &can_assign, flags);
rprn = get_token = bin_last = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_MODEXP:
case BC_LEX_KW_DIVMOD:
{
// This is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
bc_parse_builtin3(p, t, flags, &prev);
rprn = get_token = bin_last = incdec = can_assign = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
default:
{
#ifndef NDEBUG
// We should never get here, even in debug builds.
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
break;
#endif // NDEBUG
}
}
if (get_token) bc_lex_next(&p->l);
}
// Now that we have parsed the expression, we need to empty the operator
// stack.
while (p->ops.len > ops_bgn) {
top = BC_PARSE_TOP_OP(p);
assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
// There should not be *any* parens on the stack anymore.
if (BC_ERR(top == BC_LEX_LPAREN || top == BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
// Adjust the number of unused expressions.
nexprs -= !BC_PARSE_OP_PREFIX(top);
bc_vec_pop(&p->ops);
incdec = false;
}
// There must be only one expression at the top.
if (BC_ERR(nexprs != 1)) bc_parse_err(p, BC_ERR_PARSE_EXPR);
// Check that the next token is correct.
for (i = 0; i < next.len && t != next.tokens[i]; ++i);
if (BC_ERR(i == next.len && !bc_parse_isDelimiter(p)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// Check that POSIX would be happy with the number of relational operators.
if (!(flags & BC_PARSE_REL) && nrelops)
bc_parse_err(p, BC_ERR_POSIX_REL_POS);
else if ((flags & BC_PARSE_REL) && nrelops > 1)
bc_parse_err(p, BC_ERR_POSIX_MULTIREL);
// If this is true, then we might be in a situation where we don't print.
// We would want to have the increment/decrement operator not make an extra
// copy if it's not necessary.
if (!(flags & BC_PARSE_NEEDVAL) && !pfirst) {
// We have the easy case if the last operator was an assignment
// operator.
if (assign) {
inst = *((uchar*) bc_vec_top(&p->func->code));
inst += (BC_INST_ASSIGN_POWER_NO_VAL - BC_INST_ASSIGN_POWER);
incdec = false;
}
// If we have an inc/dec operator and we are *not* printing, implement
// the optimization to get rid of the extra copy.
else if (incdec && !(flags & BC_PARSE_PRINT)) {
inst = *((uchar*) bc_vec_top(&p->func->code));
incdec = (inst <= BC_INST_DEC);
inst = BC_INST_ASSIGN_PLUS_NO_VAL + (inst != BC_INST_INC &&
inst != BC_INST_ASSIGN_PLUS);
}
// This condition allows us to change the previous assignment
// instruction (which does a copy) for a NO_VAL version, which does not.
// This condition is set if either of the above if statements ends up
// being true.
if (inst >= BC_INST_ASSIGN_POWER_NO_VAL &&
inst <= BC_INST_ASSIGN_NO_VAL)
{
// Pop the previous assignment instruction and push a new one.
// Inc/dec needs the extra instruction because it is now a binary
// operator and needs a second operand.
bc_vec_pop(&p->func->code);
if (incdec) bc_parse_push(p, BC_INST_ONE);
bc_parse_push(p, inst);
}
}
// If we might have to print...
if ((flags & BC_PARSE_PRINT)) {
// With a paren first or the last operator not being an assignment, we
// *do* want to print.
if (pfirst || !assign) bc_parse_push(p, BC_INST_PRINT);
}
// We need to make sure to push a pop instruction for assignment statements
// that will not print. The print will pop, but without it, we need to pop.
else if (!(flags & BC_PARSE_NEEDVAL) &&
(inst < BC_INST_ASSIGN_POWER_NO_VAL ||
inst > BC_INST_ASSIGN_NO_VAL))
{
bc_parse_push(p, BC_INST_POP);
}
// We want to eat newlines if newlines are not a valid ending token.
// This is for spacing in things like for loop headers.
//
// Yes, this is one case where I reuse a variable for a different purpose;
// in this case, incdec being true now means that newlines are not valid.
for (incdec = true, i = 0; i < next.len && incdec; ++i)
incdec = (next.tokens[i] != BC_LEX_NLINE);
if (incdec) {
while (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l);
}
return BC_PARSE_STATUS_SUCCESS;
}
/**
* Parses an expression with bc_parse_expr_err(), but throws an error if it gets
* an empty expression.
* @param p The parser.
* @param flags The flags for what is valid in the expression.
* @param next A set of tokens for what is valid *after* the expression.
*/
static void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next) {
BcParseStatus s = bc_parse_expr_err(p, flags, next);
if (BC_ERR(s == BC_PARSE_STATUS_EMPTY_EXPR))
bc_parse_err(p, BC_ERR_PARSE_EMPTY_EXPR);
}
void bc_parse_expr(BcParse *p, uint8_t flags) {
assert(p);
bc_parse_expr_status(p, flags, bc_parse_next_read);
}
#endif // BC_ENABLED
diff --git a/src/data.c b/src/data.c
index 0eaf7d699f7d..82475299ed78 100644
--- a/src/data.c
+++ b/src/data.c
@@ -1,1308 +1,1320 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#if !BC_ENABLE_LIBRARY
#if BC_ENABLED
/// The bc signal message and its length.
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
/// The dc signal message and its length.
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
/// The copyright banner.
const char bc_copyright[] =
"Copyright (c) 2018-2021 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";
#ifdef __OpenBSD__
#if BC_ENABLE_EXTRA_MATH
#if BC_ENABLE_HISTORY
/// The pledges for starting bc.
const char bc_pledge_start[] = "rpath stdio tty unveil";
/// The final pledges with history enabled.
const char bc_pledge_end_history[] = "rpath stdio tty";
#else // BC_ENABLE_HISTORY
/// The pledges for starting bc.
const char bc_pledge_start[] = "rpath stdio unveil";
#endif // BC_ENABLE_HISTORY
/// The final pledges with history history disabled.
const char bc_pledge_end[] = "rpath stdio";
#else // BC_ENABLE_EXTRA_MATH
#if BC_ENABLE_HISTORY
/// The pledges for starting bc.
const char bc_pledge_start[] = "rpath stdio tty";
/// The final pledges with history enabled.
const char bc_pledge_end_history[] = "stdio tty";
#else // BC_ENABLE_HISTORY
/// The pledges for starting bc.
const char bc_pledge_start[] = "rpath stdio";
#endif // BC_ENABLE_HISTORY
/// The final pledges with history history disabled.
const char bc_pledge_end[] = "stdio";
#endif // BC_ENABLE_EXTRA_MATH
#else // __OpenBSD__
/// The pledges for starting bc.
const char bc_pledge_start[] = "";
#if BC_ENABLE_HISTORY
/// The final pledges with history enabled.
const char bc_pledge_end_history[] = "";
#endif // BC_ENABLE_HISTORY
/// The final pledges with history history disabled.
const char bc_pledge_end[] = "";
#endif // __OpenBSD__
/// The list of long options. There is a zero set at the end for detecting the
/// end.
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' },
+ { "leading-zeroes", BC_OPT_NONE, 'z' },
+ { "no-line-length", BC_OPT_NONE, 'L' },
{ "no-prompt", BC_OPT_NONE, 'P' },
{ "no-read-prompt", BC_OPT_NONE, 'R' },
#if BC_ENABLED
{ "global-stacks", BC_OPT_BC_ONLY, 'g' },
{ "mathlib", BC_OPT_BC_ONLY, 'l' },
{ "quiet", BC_OPT_BC_ONLY, 'q' },
{ "redefine", BC_OPT_REQUIRED_BC_ONLY, 'r' },
{ "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 },
};
/// The function header for error messages.
const char* const bc_err_func_header = "Function:";
/// The line format string for error messages.
const char* const bc_err_line = ":%zu";
/// The default error category strings.
const char *bc_errs[] = {
"Math error:",
"Parse error:",
"Runtime error:",
"Fatal error:",
#if BC_ENABLED
"Warning:",
#endif // BC_ENABLED
};
/// The error category for each error.
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_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_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, BC_ERR_IDX_PARSE,
#endif // BC_ENABLED
};
/// The default error messages. There are NULL pointers because the positions
/// must be preserved for the locales.
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 text: %s",
"path is a directory: %s",
"bad command-line option: \"%s\"",
"option requires an argument: '%c' (\"%s\")",
"option takes no arguments: '%c' (\"%s\")",
"bad option argument: \"%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",
"stack for register \"%s\" has too few elements",
#else // DC_ENABLED
NULL, 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 or stream 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",
"POSIX does not allow strings to be assigned to variables or arrays",
#endif // BC_ENABLED
};
#endif // !BC_ENABLE_LIBRARY
/// The destructors corresponding to BcDtorType enum items.
const BcVecFree bc_vec_dtors[] = {
NULL,
bc_vec_free,
bc_num_free,
#if !BC_ENABLE_LIBRARY
#ifndef NDEBUG
bc_func_free,
#endif // NDEBUG
bc_slab_free,
bc_const_free,
bc_result_free,
#if BC_ENABLE_HISTORY
bc_history_string_free,
#endif // BC_ENABLE_HISTORY
#else // !BC_ENABLE_LIBRARY
bcl_num_destruct,
#endif // !BC_ENABLE_LIBRARY
};
#if !BC_ENABLE_LIBRARY
#if BC_ENABLE_HISTORY
/// A flush type for not clearing current extras but not saving new ones either.
const BcFlushType bc_flush_none = BC_FLUSH_NO_EXTRAS_NO_CLEAR;
/// A flush type for clearing extras and not saving new ones.
const BcFlushType bc_flush_err = BC_FLUSH_NO_EXTRAS_CLEAR;
/// A flush type for clearing previous extras and saving new ones.
const BcFlushType bc_flush_save = BC_FLUSH_SAVE_EXTRAS_CLEAR;
#endif // BC_ENABLE_HISTORY
#if BC_ENABLE_HISTORY
/// A list of known bad terminals.
const char *bc_history_bad_terms[] = { "dumb", "cons25", "emacs", NULL };
/// A constant for tabs and its length. My tab handling is dumb and always
/// outputs the entire thing.
const char bc_history_tab[] = " ";
const size_t bc_history_tab_len = sizeof(bc_history_tab) - 1;
/// A list of wide chars. 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 },
};
/// The length of the wide chars list.
const size_t bc_history_wchars_len =
sizeof(bc_history_wchars) / sizeof(bc_history_wchars[0]);
/// A list of combining characters in Unicode. 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,
};
/// The length of the combining characters list.
const size_t bc_history_combo_chars_len =
sizeof(bc_history_combo_chars) / sizeof(bc_history_combo_chars[0]);
#endif // BC_ENABLE_HISTORY
/// The human-readable name of the main function in bc source code.
const char bc_func_main[] = "(main)";
/// The human-readable name of the read function in bc source code.
const char bc_func_read[] = "(read)";
#if BC_DEBUG_CODE
/// A list of names of instructions for easy debugging output.
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",
"BC_INST_ARRAY",
"BC_INST_ZERO",
"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_ASCIIFY",
"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",
#if BC_ENABLED
"BC_INST_PRINT_STR",
"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",
"BC_INST_SWAP",
"BC_INST_MODEXP",
"BC_INST_DIVMOD",
"BC_INST_PRINT_STREAM",
#if DC_ENABLED
"BC_INST_POP_EXEC",
"BC_INST_EXECUTE",
"BC_INST_EXEC_COND",
"BC_INST_PRINT_STACK",
"BC_INST_CLEAR_STACK",
"BC_INST_REG_STACK_LEN",
"BC_INST_STACK_LEN",
"BC_INST_DUPLICATE",
"BC_INST_LOAD",
"BC_INST_PUSH_VAR",
"BC_INST_PUSH_TO_VAR",
"BC_INST_QUIT",
"BC_INST_NQUIT",
"BC_INST_EXEC_STACK_LEN",
#endif // DC_ENABLED
"BC_INST_INVALID",
};
#endif // BC_DEBUG_CODE
/// A constant string for 0.
const char bc_parse_zero[2] = "0";
/// A constant string for 1.
const char bc_parse_one[2] = "1";
#if BC_ENABLED
/// A list of keywords for bc. This needs to be updated if keywords change.
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("asciify", 7, false),
BC_LEX_KW_ENTRY("modexp", 6, false),
BC_LEX_KW_ENTRY("divmod", 6, false),
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("line_length", 11, false),
+ BC_LEX_KW_ENTRY("global_stacks", 13, false),
+ BC_LEX_KW_ENTRY("leading_zero", 12, false),
BC_LEX_KW_ENTRY("stream", 6, false),
BC_LEX_KW_ENTRY("else", 4, false),
};
/// The length of the list of bc keywords.
const size_t bc_lex_kws_len = sizeof(bc_lex_kws) / sizeof(BcLexKeyword);
#if BC_C11
// This is here to ensure that BC_LEX_NKWS, which is needed for the
// redefined_kws in BcVm, is correct. If it's correct under C11, it will be
// correct under C99, and I did not know any other way of ensuring they remained
// synchronized.
static_assert(sizeof(bc_lex_kws) / sizeof(BcLexKeyword) == BC_LEX_NKWS,
"BC_LEX_NKWS is wrong.");
#endif // BC_C11
/// An array of booleans that correspond to token types. An entry is true if the
/// token is valid in an expression, false otherwise. This will need to change
/// if tokens change.
const uint8_t bc_parse_exprs[] = {
// Starts with BC_LEX_EOF.
BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, true),
// Starts with BC_LEX_OP_MULTIPLY if extra math is enabled, BC_LEX_OP_DIVIDE
// otherwise.
BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true),
// Starts with BC_LEX_OP_REL_EQ if extra math is enabled, BC_LEX_OP_REL_LT
// otherwise.
BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true),
#if BC_ENABLE_EXTRA_MATH
// Starts with BC_LEX_OP_ASSIGN_POWER.
BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true),
// Starts with BC_LEX_OP_ASSIGN_RSHIFT.
BC_PARSE_EXPR_ENTRY(true, true, false, false, true, true, false, false),
// Starts with BC_LEX_RBRACKET.
BC_PARSE_EXPR_ENTRY(false, false, false, false, true, true, true, false),
// Starts with BC_LEX_KW_BREAK.
BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false),
// Starts with BC_LEX_KW_HALT.
BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, true, false),
// Starts with BC_LEX_KW_SQRT.
BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, false, true),
// Starts with BC_LEX_KW_MAXIBASE.
- BC_PARSE_EXPR_ENTRY(true, true, true, true, true, false, false, 0)
+ BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true),
+
+ // Starts with BC_LEX_KW_STREAM.
+ BC_PARSE_EXPR_ENTRY(false, false, 0, 0, 0, 0, 0, 0)
#else // BC_ENABLE_EXTRA_MATH
// Starts with BC_LEX_OP_ASSIGN_PLUS.
BC_PARSE_EXPR_ENTRY(true, true, true, false, false, true, true, false),
// Starts with BC_LEX_COMMA.
BC_PARSE_EXPR_ENTRY(false, false, false, false, false, true, true, true),
// Starts with BC_LEX_KW_AUTO.
BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false),
// Starts with BC_LEX_KW_WHILE.
BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, false),
// Starts with BC_LEX_KW_SQRT.
BC_PARSE_EXPR_ENTRY(true, true, true, true, true, false, true, true),
// Starts with BC_LEX_KW_MAXSCALE,
- BC_PARSE_EXPR_ENTRY(true, true, false, false, 0, 0, 0, 0)
+ BC_PARSE_EXPR_ENTRY(true, true, true, true, true, false, false, 0)
#endif // BC_ENABLE_EXTRA_MATH
};
/// 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.
/// The valid next tokens for normal expressions.
const BcParseNext bc_parse_next_expr =
BC_PARSE_NEXT(4, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF);
/// The valid next tokens for function argument expressions.
const BcParseNext bc_parse_next_arg =
BC_PARSE_NEXT(2, BC_LEX_RPAREN, BC_LEX_COMMA);
/// The valid next tokens for expressions in print statements.
const BcParseNext bc_parse_next_print =
BC_PARSE_NEXT(4, BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF);
/// The valid next tokens for if statement conditions or loop conditions. This
/// is used in for loops for the update expression and for builtin function.
///
/// The name is an artifact of history, and is related to @a BC_PARSE_REL (see
/// include/parse.h). It refers to how POSIX only allows some operators as part
/// of the conditional of for loops, while loops, and if statements.
const BcParseNext bc_parse_next_rel = BC_PARSE_NEXT(1, BC_LEX_RPAREN);
/// The valid next tokens for array element expressions.
const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET);
/// The valid next tokens for for loop initialization expressions and condition
/// expressions.
const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON);
/// The valid next tokens for read expressions.
const BcParseNext bc_parse_next_read =
BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF);
/// The valid next tokens for the arguments of a builtin function with multiple
/// arguments.
const BcParseNext bc_parse_next_builtin = BC_PARSE_NEXT(1, BC_LEX_COMMA);
#endif // BC_ENABLED
#if DC_ENABLED
/// A list of instructions that need register arguments in dc.
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, BC_LEX_REG_STACK_LEVEL, BC_LEX_ARRAY_LENGTH,
};
/// The length of the list of register instructions.
const size_t dc_lex_regs_len = sizeof(dc_lex_regs) / sizeof(uint8_t);
/// A list corresponding to characters starting at double quote ("). If an entry
/// is BC_LEX_INVALID, then that character needs extra lexing in dc. If it does
/// not, the character can trivially be replaced by the entry. Positions are
/// kept because it corresponds to the ASCII table. This may need to be changed
/// if tokens change.
const uchar dc_lex_tokens[] = {
#if BC_ENABLE_EXTRA_MATH
BC_LEX_KW_IRAND,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
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
BC_LEX_KW_RAND,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_LPAREN, BC_LEX_RPAREN, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS,
BC_LEX_EXEC_STACK_LENGTH, 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
BC_LEX_KW_SEED,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_KW_SCALE, BC_LEX_LOAD_POP, BC_LEX_OP_BOOL_AND, BC_LEX_OP_BOOL_NOT,
BC_LEX_KW_OBASE, BC_LEX_KW_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
BC_LEX_KW_MAXRAND,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
BC_LEX_SCALE_FACTOR, BC_LEX_ARRAY_LENGTH, 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_KW_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
BC_LEX_STORE_SEED,
#else // BC_ENABLE_EXTRA_MATH
BC_LEX_INVALID,
#endif // BC_ENABLE_EXTRA_MATH
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_REG_STACK_LEVEL, BC_LEX_STACK_LEVEL,
BC_LEX_LBRACE, BC_LEX_KW_MODEXP, BC_LEX_RBRACE, BC_LEX_KW_DIVMOD,
BC_LEX_INVALID
};
/// A list of instructions that correspond to lex tokens. If an entry is
/// BC_INST_INVALID, that lex token needs extra parsing in the dc parser.
/// Otherwise, the token can trivially be replaced by the entry. This needs to
/// be updated if the tokens change.
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_ASCIIFY, BC_INST_MODEXP, BC_INST_DIVMOD,
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_PRINT_STREAM, BC_INST_INVALID,
+ BC_INST_LINE_LENGTH,
+#if BC_ENABLED
+ BC_INST_INVALID,
+#endif // BC_ENABLED
+ BC_INST_LEADING_ZERO, BC_INST_PRINT_STREAM, BC_INST_INVALID,
BC_INST_REL_EQ, BC_INST_INVALID,
BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK,
BC_INST_INVALID, BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP,
BC_INST_POP,
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_EXEC_STACK_LEN,
BC_INST_SCALE_FUNC, BC_INST_INVALID,
};
#endif // DC_ENABLED
#endif // !BC_ENABLE_LIBRARY
#if BC_ENABLE_EXTRA_MATH
/// A constant for the rand multiplier.
const BcRandState bc_rand_multiplier = BC_RAND_MULTIPLIER;
#endif // BC_ENABLE_EXTRA_MATH
#if BC_LONG_BIT >= 64
/// A constant array for the max of a bigdig number as a BcDig array.
const BcDig bc_num_bigdigMax[] = {
709551616U,
446744073U,
18U,
};
/// A constant array for the max of 2 times a bigdig number as a BcDig array.
const BcDig bc_num_bigdigMax2[] = {
768211456U,
374607431U,
938463463U,
282366920U,
340U,
};
#else // BC_LONG_BIT >= 64
/// A constant array for the max of a bigdig number as a BcDig array.
const BcDig bc_num_bigdigMax[] = {
7296U,
9496U,
42U,
};
/// A constant array for the max of 2 times a bigdig number as a BcDig array.
const BcDig bc_num_bigdigMax2[] = {
1616U,
955U,
737U,
6744U,
1844U,
};
#endif // BC_LONG_BIT >= 64
/// The size of the bigdig max array.
const size_t bc_num_bigdigMax_size = sizeof(bc_num_bigdigMax) / sizeof(BcDig);
/// The size of the bigdig max times 2 array.
const size_t bc_num_bigdigMax2_size = sizeof(bc_num_bigdigMax2) / sizeof(BcDig);
/// A string of digits for easy conversion from characters to digits.
const char bc_num_hex_digits[] = "0123456789ABCDEF";
/// An array for easy conversion from exponent to power of 10.
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
};
#if !BC_ENABLE_LIBRARY
/// An array of functions for binary operators corresponding to the order of
/// the instructions for the operators.
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
};
/// An array of functions for binary operators allocation requests corresponding
/// to the order of the instructions for the operators.
const BcNumBinaryOpReq bc_program_opReqs[] = {
bc_num_powReq, bc_num_mulReq, bc_num_divReq, bc_num_divReq,
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
};
/// An array of unary operator functions corresponding to the order of the
/// instructions.
const BcProgramUnary bc_program_unarys[] = {
bc_program_negate, bc_program_not,
#if BC_ENABLE_EXTRA_MATH
bc_program_trunc,
#endif // BC_ENABLE_EXTRA_MATH
};
/// A filename for when parsing expressions.
const char bc_program_exprs_name[] = "";
/// A filename for when parsing stdin..
const char bc_program_stdin_name[] = "";
/// A ready message for SIGINT catching.
const char bc_program_ready_msg[] = "ready for more input\n";
/// The length of the ready message.
const size_t bc_program_ready_msg_len = sizeof(bc_program_ready_msg) - 1;
/// A list of escape characters that a print statement should treat specially.
const char bc_program_esc_chars[] = "ab\\efnqrt";
/// A list of characters corresponding to the escape characters above.
const char bc_program_esc_seqs[] = "\a\b\\\\\f\n\"\r\t";
#endif // !BC_ENABLE_LIBRARY
diff --git a/src/dc_lex.c b/src/dc_lex.c
index d0e93c28a431..5c6950ba9698 100644
--- a/src/dc_lex.c
+++ b/src/dc_lex.c
@@ -1,263 +1,276 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
#include
#include
bool dc_lex_negCommand(BcLex *l) {
char c = l->buf[l->i];
return !BC_LEX_NUM_CHAR(c, false, false);
}
/**
* Processes a dc command that needs a register. This is where the
* extended-register extension is implemented.
* @param l The lexer.
*/
static void dc_lex_register(BcLex *l) {
// If extended register is enabled and the character is whitespace...
if (DC_X && isspace(l->buf[l->i - 1])) {
char c;
// Eat the whitespace.
bc_lex_whitespace(l);
c = l->buf[l->i];
// Check for a letter or underscore.
if (BC_ERR(!isalpha(c) && c != '_'))
bc_lex_verr(l, BC_ERR_PARSE_CHAR, c);
// Parse a normal identifier.
l->i += 1;
bc_lex_name(l);
}
else {
// I don't allow newlines because newlines are used for controlling when
// execution happens, and allowing newlines would just be complex.
if (BC_ERR(l->buf[l->i - 1] == '\n'))
bc_lex_verr(l, BC_ERR_PARSE_CHAR, l->buf[l->i - 1]);
// Set the lexer string and token.
bc_vec_popAll(&l->str);
bc_vec_pushByte(&l->str, (uchar) l->buf[l->i - 1]);
bc_vec_pushByte(&l->str, '\0');
l->t = BC_LEX_NAME;
}
}
/**
* Parses a dc string. Since dc's strings need to check for balanced brackets,
* we can't just parse bc and dc strings with different start and end
* characters. Oh, and dc strings need to check for escaped brackets.
* @param l The lexer.
*/
static void dc_lex_string(BcLex *l) {
size_t depth, nls, i;
char c;
bool got_more;
// Set the token and clear the string.
l->t = BC_LEX_STR;
bc_vec_popAll(&l->str);
do {
depth = 1;
nls = 0;
got_more = false;
assert(!l->is_stdin || l->buf == vm.buffer.v);
// This is the meat. As long as we don't run into the NUL byte, and we
// have "depth", which means we haven't completely balanced brackets
// yet, we continue eating the string.
for (i = l->i; (c = l->buf[i]) && depth; ++i) {
// Check for escaped brackets and set the depths as appropriate.
if (c == '\\') {
c = l->buf[++i];
if (!c) break;
}
else {
depth += (c == '[');
depth -= (c == ']');
}
// We want to adjust the line in the lexer as necessary.
nls += (c == '\n');
if (depth) bc_vec_push(&l->str, &c);
}
if (BC_ERR(c == '\0' && depth)) {
if (!vm.eof && l->is_stdin) got_more = bc_lex_readLine(l);
if (got_more) bc_vec_popAll(&l->str);
}
} while (got_more && depth);
// Obviously, if we didn't balance, that's an error.
if (BC_ERR(c == '\0' && depth)) {
l->i = i;
bc_lex_err(l, BC_ERR_PARSE_STRING);
}
bc_vec_pushByte(&l->str, '\0');
l->i = i;
l->line += nls;
}
/**
* Lexes a dc token. This is the dc implementation of BcLexNext.
* @param l The lexer.
*/
void dc_lex_token(BcLex *l) {
char c = l->buf[l->i++], c2;
size_t i;
// If the last token was a command that needs a register, we need to parse a
// register, so do so.
for (i = 0; i < dc_lex_regs_len; ++i) {
// If the token is a register token, take care of it and return.
if (l->last == dc_lex_regs[i]) {
dc_lex_register(l);
return;
}
}
// These lines are for tokens that easily correspond to one character. We
// just set the token.
if (c >= '"' && c <= '~' &&
(l->t = dc_lex_tokens[(c - '"')]) != BC_LEX_INVALID)
{
return;
}
// This is the workhorse of the lexer when more complicated things are
// needed.
switch (c) {
case '\0':
case '\n':
case '\t':
case '\v':
case '\f':
case '\r':
case ' ':
{
bc_lex_commonTokens(l, c);
break;
}
// We don't have the ! command, so we always expect certain things
// after the exclamation point.
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 the character after is a number, this dot is part of a number.
// Otherwise, it's the BSD dot (equivalent to last).
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 'g':
+ {
+ c2 = l->buf[l->i];
+
+ if (c2 == 'l') l->t = BC_LEX_KW_LINE_LENGTH;
+ else if (c2 == 'z') l->t = BC_LEX_KW_LEADING_ZERO;
+ else bc_lex_invalidChar(l, c2);
+
+ l->i += 1;
+
+ break;
+ }
+
case '[':
{
dc_lex_string(l);
break;
}
default:
{
bc_lex_invalidChar(l, c);
}
}
}
#endif // DC_ENABLED
diff --git a/src/history.c b/src/history.c
index 44fe48acc1ad..b5ba0758075c 100644
--- a/src/history.c
+++ b/src/history.c
@@ -1,1740 +1,1765 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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
* Copyright (c) 2010-2013, Pieter Noordhuis
*
* 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.
*
* ------------------------------------------------------------------------
*
* Does a number of crazy assumptions that happen to be true in 99.9999% of
* the 2010 UNIX computers around.
*
* References:
* - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
*
* Todo list:
* - Filter bogus Ctrl+ combinations.
* - Win32 support
*
* Bloat:
* - History search like Ctrl+r in readline?
*
* List of escape sequences used by this program, we do everything just
* with three sequences. In order to be so cheap we may have some
* flickering effect with some slow terminal, but the lesser sequences
* the more compatible.
*
* EL (Erase Line)
* Sequence: ESC [ n K
* Effect: if n is 0 or missing, clear from cursor to end of line
* Effect: if n is 1, clear from beginning of line to cursor
* Effect: if n is 2, clear entire line
*
* CUF (CUrsor Forward)
* Sequence: ESC [ n C
* Effect: moves cursor forward n chars
*
* CUB (CUrsor Backward)
* Sequence: ESC [ n D
* Effect: moves cursor backward n chars
*
* The following is used to get the terminal width if getting
* the width with the TIOCGWINSZ ioctl fails
*
* DSR (Device Status Report)
* Sequence: ESC [ 6 n
* Effect: reports the current cusor position as ESC [ n ; m R
* where n is the row and m is the column
*
* When multi line mode is enabled, we also use two additional escape
* sequences. However multi line editing is disabled by default.
*
* CUU (CUrsor Up)
* Sequence: ESC [ n A
* Effect: moves cursor up of n chars.
*
* CUD (CUrsor Down)
* Sequence: ESC [ n B
* Effect: moves cursor down of n chars.
*
* When bc_history_clearScreen() is called, two additional escape sequences
* are used in order to clear the screen and position the cursor at home
* position.
*
* CUP (CUrsor Position)
* Sequence: ESC [ H
* Effect: moves the cursor to upper left corner
*
* ED (Erase Display)
* Sequence: ESC [ 2 J
* Effect: clear the whole screen
*
* *****************************************************************************
*
* Code for line history.
*
*/
#if BC_ENABLE_HISTORY
#include
#include
#include
#include
#include
#include
#include
#include
#ifndef _WIN32
#include
#include
#include
#include
#include
#endif // _WIN32
#include
#include
#include
#include
#include
#include
#if BC_DEBUG_CODE
/// A file for outputting to when debugging.
BcFile bc_history_debug_fp;
/// A buffer for the above file.
char *bc_history_debug_buf;
#endif // BC_DEBUG_CODE
/**
* Checks if the code is a wide character.
* @param cp The codepoint to check.
* @return True if @a cp is a wide character, false otherwise.
*/
static bool bc_history_wchar(uint32_t cp) {
size_t i;
for (i = 0; i < bc_history_wchars_len; ++i) {
// Ranges are listed in ascending order. Therefore, once the
// whole range is higher than the codepoint we're testing, the
// codepoint won't be found in any remaining range => bail early.
if (bc_history_wchars[i][0] > cp) return false;
// Test this range.
if (bc_history_wchars[i][0] <= cp && cp <= bc_history_wchars[i][1])
return true;
}
return false;
}
/**
* Checks if the code is a combining character.
* @param cp The codepoint to check.
* @return True if @a cp is a combining character, false otherwise.
*/
static bool bc_history_comboChar(uint32_t cp) {
size_t i;
for (i = 0; i < bc_history_combo_chars_len; ++i) {
// Combining chars are listed in ascending order, so once we pass
// the codepoint of interest, we know it's not a combining char.
if (bc_history_combo_chars[i] > cp) return false;
if (bc_history_combo_chars[i] == cp) return true;
}
return false;
}
/**
* Gets the length of previous UTF8 character.
* @param buf The buffer of characters.
* @param pos The index into the buffer.
*/
static size_t bc_history_prevCharLen(const char *buf, size_t pos) {
size_t end = pos;
for (pos -= 1; pos < end && (buf[pos] & 0xC0) == 0x80; --pos);
return end - (pos >= end ? 0 : pos);
}
/**
* Converts UTF-8 to a Unicode code point.
* @param s The string.
* @param len The length of the string.
* @param cp An out parameter for the codepoint.
* @return The number of bytes eaten by the codepoint.
*/
static size_t bc_history_codePoint(const char *s, size_t len, uint32_t *cp) {
if (len) {
uchar byte = (uchar) s[0];
// This is literally the UTF-8 decoding algorithm. Look that up if you
// don't understand this.
if ((byte & 0x80) == 0) {
*cp = byte;
return 1;
}
else if ((byte & 0xE0) == 0xC0) {
if (len >= 2) {
*cp = (((uint32_t) (s[0] & 0x1F)) << 6) |
((uint32_t) (s[1] & 0x3F));
return 2;
}
}
else if ((byte & 0xF0) == 0xE0) {
if (len >= 3) {
*cp = (((uint32_t) (s[0] & 0x0F)) << 12) |
(((uint32_t) (s[1] & 0x3F)) << 6) |
((uint32_t) (s[2] & 0x3F));
return 3;
}
}
else if ((byte & 0xF8) == 0xF0) {
if (len >= 4) {
*cp = (((uint32_t) (s[0] & 0x07)) << 18) |
(((uint32_t) (s[1] & 0x3F)) << 12) |
(((uint32_t) (s[2] & 0x3F)) << 6) |
((uint32_t) (s[3] & 0x3F));
return 4;
}
}
else {
*cp = 0xFFFD;
return 1;
}
}
*cp = 0;
return 1;
}
/**
* Gets the length of next grapheme.
* @param buf The buffer.
* @param buf_len The length of the buffer.
* @param pos The index into the buffer.
* @param col_len An out parameter for the length of the grapheme on screen.
* @return The number of bytes in the grapheme.
*/
static size_t bc_history_nextLen(const char *buf, size_t buf_len,
size_t pos, size_t *col_len)
{
uint32_t cp;
size_t beg = pos;
size_t len = bc_history_codePoint(buf + pos, buf_len - pos, &cp);
if (bc_history_comboChar(cp)) {
BC_UNREACHABLE
if (col_len != NULL) *col_len = 0;
return 0;
}
// Store the width of the character on screen.
if (col_len != NULL) *col_len = bc_history_wchar(cp) ? 2 : 1;
pos += len;
// Find the first non-combining character.
while (pos < buf_len) {
len = bc_history_codePoint(buf + pos, buf_len - pos, &cp);
if (!bc_history_comboChar(cp)) return pos - beg;
pos += len;
}
return pos - beg;
}
/**
* Gets the length of previous grapheme.
* @param buf The buffer.
* @param pos The index into the buffer.
* @return The number of bytes in the grapheme.
*/
static size_t bc_history_prevLen(const char *buf, size_t pos) {
size_t end = pos;
// Find the first non-combining character.
while (pos > 0) {
uint32_t cp;
size_t len = bc_history_prevCharLen(buf, pos);
pos -= len;
bc_history_codePoint(buf + pos, len, &cp);
// The original linenoise-mob had an extra parameter col_len, like
// bc_history_nextLen(), which, if not NULL, was set in this if
// statement. However, we always passed NULL, so just skip that.
if (!bc_history_comboChar(cp)) return end - pos;
}
BC_UNREACHABLE
return 0;
}
/**
* Reads @a n characters from stdin.
* @param buf The buffer to read into. The caller is responsible for making
* sure this is big enough for @a n.
* @param n The number of characters to read.
* @return The number of characters read or less than 0 on error.
*/
static ssize_t bc_history_read(char *buf, size_t n) {
ssize_t ret;
BC_SIG_LOCK;
#ifndef _WIN32
do {
// We don't care about being interrupted.
ret = read(STDIN_FILENO, buf, n);
} while (ret == EINTR);
#else // _WIN32
bool good;
DWORD read;
HANDLE hn = GetStdHandle(STD_INPUT_HANDLE);
good = ReadConsole(hn, buf, (DWORD) n, &read, NULL);
ret = (read != n) ? -1 : 1;
#endif // _WIN32
BC_SIG_UNLOCK;
return ret;
}
/**
* Reads a Unicode code point into a buffer.
* @param buf The buffer to read into.
* @param buf_len The length of the buffer.
* @param cp An out parameter for the codepoint.
* @param nread An out parameter for the number of bytes read.
* @return BC_STATUS_EOF or BC_STATUS_SUCCESS.
*/
static BcStatus bc_history_readCode(char *buf, size_t buf_len,
uint32_t *cp, size_t *nread)
{
ssize_t n;
assert(buf_len >= 1);
// Read a byte.
n = bc_history_read(buf, 1);
if (BC_ERR(n <= 0)) goto err;
// Get the byte.
uchar byte = ((uchar*) buf)[0];
// Once again, this is the UTF-8 decoding algorithm, but it has reads
// instead of actual decoding.
if ((byte & 0x80) != 0) {
if ((byte & 0xE0) == 0xC0) {
assert(buf_len >= 2);
n = bc_history_read(buf + 1, 1);
if (BC_ERR(n <= 0)) goto err;
}
else if ((byte & 0xF0) == 0xE0) {
assert(buf_len >= 3);
n = bc_history_read(buf + 1, 2);
if (BC_ERR(n <= 0)) goto err;
}
else if ((byte & 0xF8) == 0xF0) {
assert(buf_len >= 3);
n = bc_history_read(buf + 1, 3);
if (BC_ERR(n <= 0)) goto err;
}
else {
n = -1;
goto err;
}
}
// Convert to the codepoint.
*nread = bc_history_codePoint(buf, buf_len, cp);
return BC_STATUS_SUCCESS;
err:
// If we get here, we either had a fatal error of EOF.
if (BC_ERR(n < 0)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
else *nread = (size_t) n;
return BC_STATUS_EOF;
}
/**
* Gets the column length from beginning of buffer to current byte position.
* @param buf The buffer.
* @param buf_len The length of the buffer.
* @param pos The index into the buffer.
* @return The number of columns between the beginning of @a buffer to
* @a pos.
*/
static size_t bc_history_colPos(const char *buf, size_t buf_len, size_t pos) {
size_t ret = 0, off = 0;
// While we haven't reached the offset, get the length of the next grapheme.
while (off < pos && off < buf_len) {
size_t col_len, len;
len = bc_history_nextLen(buf, buf_len, off, &col_len);
off += len;
ret += col_len;
}
return ret;
}
/**
* Returns true if the terminal name is in the list of terminals we know are
* not able to understand basic escape sequences.
* @return True if the terminal is a bad terminal.
*/
static inline bool bc_history_isBadTerm(void) {
size_t i;
bool ret = false;
char *term = bc_vm_getenv("TERM");
if (term == NULL) return false;
for (i = 0; !ret && bc_history_bad_terms[i]; ++i)
ret = (!strcasecmp(term, bc_history_bad_terms[i]));
bc_vm_getenvFree(term);
return ret;
}
/**
* Enables raw mode (1960's black magic).
* @param h The history data.
*/
static void bc_history_enableRaw(BcHistory *h) {
// I don't do anything for Windows because in Windows, you set their
// equivalent of raw mode and leave it, so I do it in bc_history_init().
#ifndef _WIN32
struct termios raw;
int err;
assert(BC_TTYIN);
if (h->rawMode) return;
BC_SIG_LOCK;
if (BC_ERR(tcgetattr(STDIN_FILENO, &h->orig_termios) == -1))
bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
BC_SIG_UNLOCK;
// Modify the original mode.
raw = h->orig_termios;
// Input modes: no break, no CR to NL, no parity check, no strip char,
// no start/stop output control.
raw.c_iflag &= (unsigned int) (~(BRKINT | ICRNL | INPCK | ISTRIP | IXON));
// Control modes: set 8 bit chars.
raw.c_cflag |= (CS8);
// Local modes - choing off, canonical off, no extended functions,
// no signal chars (^Z,^C).
raw.c_lflag &= (unsigned int) (~(ECHO | ICANON | IEXTEN | ISIG));
// Control chars - set return condition: min number of bytes and timer.
// We want read to give every single byte, w/o timeout (1 byte, no timer).
raw.c_cc[VMIN] = 1;
raw.c_cc[VTIME] = 0;
BC_SIG_LOCK;
// Put terminal in raw mode after flushing.
do {
err = tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
} while (BC_ERR(err < 0) && errno == EINTR);
BC_SIG_UNLOCK;
if (BC_ERR(err < 0)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
#endif // _WIN32
h->rawMode = true;
}
/**
* Disables raw mode.
* @param h The history data.
*/
static void bc_history_disableRaw(BcHistory *h) {
sig_atomic_t lock;
if (!h->rawMode) return;
BC_SIG_TRYLOCK(lock);
#ifndef _WIN32
if (BC_ERR(tcsetattr(STDIN_FILENO, TCSAFLUSH, &h->orig_termios) != -1))
h->rawMode = false;
#endif // _WIN32
BC_SIG_TRYUNLOCK(lock);
}
/**
* Uses the ESC [6n escape sequence to query the horizontal cursor position
* and return it. On error -1 is returned, on success the position of the
* cursor.
* @return The horizontal cursor position.
*/
static size_t bc_history_cursorPos(void) {
char buf[BC_HIST_SEQ_SIZE];
char *ptr, *ptr2;
size_t cols, rows, i;
// Report cursor location.
bc_file_write(&vm.fout, bc_flush_none, "\x1b[6n", 4);
bc_file_flush(&vm.fout, bc_flush_none);
// Read the response: ESC [ rows ; cols R.
for (i = 0; i < sizeof(buf) - 1; ++i) {
if (bc_history_read(buf + i, 1) != 1 || buf[i] == 'R') break;
}
buf[i] = '\0';
// This is basically an error; we didn't get what we were expecting.
if (BC_ERR(buf[0] != BC_ACTION_ESC || buf[1] != '[')) return SIZE_MAX;
// Parse the rows.
ptr = buf + 2;
rows = strtoul(ptr, &ptr2, 10);
// Here we also didn't get what we were expecting.
if (BC_ERR(!rows || ptr2[0] != ';')) return SIZE_MAX;
// Parse the columns.
ptr = ptr2 + 1;
cols = strtoul(ptr, NULL, 10);
if (BC_ERR(!cols)) return SIZE_MAX;
return cols <= UINT16_MAX ? cols : 0;
}
/**
* Tries to get the number of columns in the current terminal, or assume 80
* if it fails.
* @return The number of columns in the terminal.
*/
static size_t bc_history_columns(void) {
#ifndef _WIN32
struct winsize ws;
int ret;
BC_SIG_LOCK;
ret = ioctl(vm.fout.fd, TIOCGWINSZ, &ws);
BC_SIG_UNLOCK;
if (BC_ERR(ret == -1 || !ws.ws_col)) {
// Calling ioctl() failed. Try to query the terminal itself.
size_t start, cols;
// Get the initial position so we can restore it later.
start = bc_history_cursorPos();
if (BC_ERR(start == SIZE_MAX)) return BC_HIST_DEF_COLS;
// Go to right margin and get position.
bc_file_write(&vm.fout, bc_flush_none, "\x1b[999C", 6);
bc_file_flush(&vm.fout, bc_flush_none);
cols = bc_history_cursorPos();
if (BC_ERR(cols == SIZE_MAX)) return BC_HIST_DEF_COLS;
// Restore position.
if (cols > start) {
bc_file_printf(&vm.fout, "\x1b[%zuD", cols - start);
bc_file_flush(&vm.fout, bc_flush_none);
}
return cols;
}
return ws.ws_col;
#else // _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
return 80;
return ((size_t) (csbi.srWindow.Right)) - csbi.srWindow.Left + 1;
#endif // _WIN32
}
/**
* Gets the column length of prompt text. This is probably unnecessary because
* the prompts that I use are ASCII, but I kept it just in case.
* @param prompt The prompt.
* @param plen The length of the prompt.
* @return The column length of the prompt.
*/
static size_t bc_history_promptColLen(const char *prompt, size_t plen) {
char buf[BC_HIST_MAX_LINE + 1];
size_t buf_len = 0, off = 0;
// The original linenoise-mob checked for ANSI escapes here on the prompt. I
// know the prompts do not have ANSI escapes. I deleted the code.
while (off < plen) buf[buf_len++] = prompt[off++];
return bc_history_colPos(buf, buf_len, buf_len);
}
/**
* Rewrites the currently edited line accordingly to the buffer content,
* cursor position, and number of columns of the terminal.
* @param h The history data.
*/
static void bc_history_refresh(BcHistory *h) {
char* buf = h->buf.v;
size_t colpos, len = BC_HIST_BUF_LEN(h), pos = h->pos, extras_len = 0;
bc_file_flush(&vm.fout, bc_flush_none);
// Get to the prompt column position from the left.
while(h->pcol + bc_history_colPos(buf, len, pos) >= h->cols) {
size_t chlen = bc_history_nextLen(buf, len, 0, NULL);
buf += chlen;
len -= chlen;
pos -= chlen;
}
// Get to the prompt column position from the right.
while (h->pcol + bc_history_colPos(buf, len, len) > h->cols)
len -= bc_history_prevLen(buf, len);
// Cursor to left edge.
bc_file_write(&vm.fout, bc_flush_none, "\r", 1);
// Take the extra stuff into account. This is where history makes sure to
// preserve stuff that was printed without a newline.
if (h->extras.len > 1) {
extras_len = h->extras.len - 1;
bc_vec_grow(&h->buf, extras_len);
len += extras_len;
pos += extras_len;
bc_file_write(&vm.fout, bc_flush_none, h->extras.v, extras_len);
}
// Write the prompt, if desired.
if (BC_PROMPT) bc_file_write(&vm.fout, bc_flush_none, h->prompt, h->plen);
bc_file_write(&vm.fout, bc_flush_none, h->buf.v, len - extras_len);
// Erase to right.
bc_file_write(&vm.fout, bc_flush_none, "\x1b[0K", 4);
// We need to be sure to grow this.
if (pos >= h->buf.len - extras_len)
bc_vec_grow(&h->buf, pos + extras_len);
// Move cursor to original position.
colpos = bc_history_colPos(h->buf.v, len - extras_len, pos) + h->pcol;
// Set the cursor position again.
if (colpos) bc_file_printf(&vm.fout, "\r\x1b[%zuC", colpos);
bc_file_flush(&vm.fout, bc_flush_none);
}
/**
* Inserts the character(s) 'c' at cursor current position.
* @param h The history data.
* @param cbuf The character buffer to copy from.
* @param clen The number of characters to copy.
*/
static void bc_history_edit_insert(BcHistory *h, const char *cbuf, size_t clen)
{
bc_vec_grow(&h->buf, clen);
// If we are at the end of the line...
if (h->pos == BC_HIST_BUF_LEN(h)) {
size_t colpos = 0, len;
// Copy into the buffer.
memcpy(bc_vec_item(&h->buf, h->pos), cbuf, clen);
// Adjust the buffer.
h->pos += clen;
h->buf.len += clen - 1;
bc_vec_pushByte(&h->buf, '\0');
// Set the length and column position.
len = BC_HIST_BUF_LEN(h) + h->extras.len - 1;
colpos = bc_history_promptColLen(h->prompt, h->plen);
colpos += bc_history_colPos(h->buf.v, len, len);
// Do we have the trivial case?
if (colpos < h->cols) {
// Avoid a full update of the line in the trivial case.
bc_file_write(&vm.fout, bc_flush_none, cbuf, clen);
bc_file_flush(&vm.fout, bc_flush_none);
}
else bc_history_refresh(h);
}
else {
// Amount that we need to move.
size_t amt = BC_HIST_BUF_LEN(h) - h->pos;
// Move the stuff.
memmove(h->buf.v + h->pos + clen, h->buf.v + h->pos, amt);
memcpy(h->buf.v + h->pos, cbuf, clen);
// Adjust the buffer.
h->pos += clen;
h->buf.len += clen;
h->buf.v[BC_HIST_BUF_LEN(h)] = '\0';
bc_history_refresh(h);
}
}
/**
* Moves the cursor to the left.
* @param h The history data.
*/
static void bc_history_edit_left(BcHistory *h) {
// Stop at the left end.
if (h->pos <= 0) return;
h->pos -= bc_history_prevLen(h->buf.v, h->pos);
bc_history_refresh(h);
}
/**
* Moves the cursor to the right.
* @param h The history data.
*/
static void bc_history_edit_right(BcHistory *h) {
// Stop at the right end.
if (h->pos == BC_HIST_BUF_LEN(h)) return;
h->pos += bc_history_nextLen(h->buf.v, BC_HIST_BUF_LEN(h), h->pos, NULL);
bc_history_refresh(h);
}
/**
* Moves the cursor to the end of the current word.
* @param h The history data.
*/
static void bc_history_edit_wordEnd(BcHistory *h) {
size_t len = BC_HIST_BUF_LEN(h);
// Don't overflow.
if (!len || h->pos >= len) return;
// Find the word, then find the end of it.
while (h->pos < len && isspace(h->buf.v[h->pos])) h->pos += 1;
while (h->pos < len && !isspace(h->buf.v[h->pos])) h->pos += 1;
bc_history_refresh(h);
}
/**
* Moves the cursor to the start of the current word.
* @param h The history data.
*/
static void bc_history_edit_wordStart(BcHistory *h) {
size_t len = BC_HIST_BUF_LEN(h);
// Stop with no data.
if (!len) return;
// Find the word, the find the beginning of the word.
while (h->pos > 0 && isspace(h->buf.v[h->pos - 1])) h->pos -= 1;
while (h->pos > 0 && !isspace(h->buf.v[h->pos - 1])) h->pos -= 1;
bc_history_refresh(h);
}
/**
* Moves the cursor to the start of the line.
* @param h The history data.
*/
static void bc_history_edit_home(BcHistory *h) {
// Stop at the beginning.
if (!h->pos) return;
h->pos = 0;
bc_history_refresh(h);
}
/**
* Moves the cursor to the end of the line.
* @param h The history data.
*/
static void bc_history_edit_end(BcHistory *h) {
// Stop at the end of the line.
if (h->pos == BC_HIST_BUF_LEN(h)) return;
h->pos = BC_HIST_BUF_LEN(h);
bc_history_refresh(h);
}
/**
* Substitutes the currently edited line with the next or previous history
* entry as specified by 'dir' (direction).
* @param h The history data.
* @param dir The direction to substitute; true means previous, false next.
*/
static void bc_history_edit_next(BcHistory *h, bool dir) {
const char *dup, *str;
// Stop if there is no history.
if (h->history.len <= 1) return;
BC_SIG_LOCK;
// Duplicate the buffer.
if (h->buf.v[0]) dup = bc_vm_strdup(h->buf.v);
else dup = "";
// Update the current history entry before overwriting it with the next one.
bc_vec_replaceAt(&h->history, h->history.len - 1 - h->idx, &dup);
BC_SIG_UNLOCK;
// Show the new entry.
h->idx += (dir == BC_HIST_PREV ? 1 : SIZE_MAX);
// Se the index appropriately at the ends.
if (h->idx == SIZE_MAX) {
h->idx = 0;
return;
}
else if (h->idx >= h->history.len) {
h->idx = h->history.len - 1;
return;
}
// Get the string.
str = *((char**) bc_vec_item(&h->history, h->history.len - 1 - h->idx));
bc_vec_string(&h->buf, strlen(str), str);
assert(h->buf.len > 0);
// Set the position at the end.
h->pos = BC_HIST_BUF_LEN(h);
bc_history_refresh(h);
}
/**
* Deletes the character at the right of the cursor without altering the cursor
* position. Basically, this is what happens with the "Delete" keyboard key.
* @param h The history data.
*/
static void bc_history_edit_delete(BcHistory *h) {
size_t chlen, len = BC_HIST_BUF_LEN(h);
// If there is no character, skip.
if (!len || h->pos >= len) return;
// Get the length of the character.
chlen = bc_history_nextLen(h->buf.v, len, h->pos, NULL);
// Move characters after it into its place.
memmove(h->buf.v + h->pos, h->buf.v + h->pos + chlen, len - h->pos - chlen);
// Make the buffer valid again.
h->buf.len -= chlen;
h->buf.v[BC_HIST_BUF_LEN(h)] = '\0';
bc_history_refresh(h);
}
/**
* Deletes the character to the left of the cursor and moves the cursor back one
* space. Basically, this is what happens with the "Backspace" keyboard key.
* @param h The history data.
*/
static void bc_history_edit_backspace(BcHistory *h) {
size_t chlen, len = BC_HIST_BUF_LEN(h);
// If there are no characters, skip.
if (!h->pos || !len) return;
// Get the length of the previous character.
chlen = bc_history_prevLen(h->buf.v, h->pos);
// Move everything back one.
memmove(h->buf.v + h->pos - chlen, h->buf.v + h->pos, len - h->pos);
// Make the buffer valid again.
h->pos -= chlen;
h->buf.len -= chlen;
h->buf.v[BC_HIST_BUF_LEN(h)] = '\0';
bc_history_refresh(h);
}
/**
* Deletes the previous word, maintaining the cursor at the start of the
* current word.
* @param h The history data.
*/
static void bc_history_edit_deletePrevWord(BcHistory *h) {
size_t diff, old_pos = h->pos;
// If at the beginning of the line, skip.
if (!old_pos) return;
// Find the word, then the beginning of the word.
while (h->pos > 0 && isspace(h->buf.v[h->pos - 1])) --h->pos;
while (h->pos > 0 && !isspace(h->buf.v[h->pos - 1])) --h->pos;
// Get the difference in position.
diff = old_pos - h->pos;
// Move the data back.
memmove(h->buf.v + h->pos, h->buf.v + old_pos,
BC_HIST_BUF_LEN(h) - old_pos + 1);
// Make the buffer valid again.
h->buf.len -= diff;
bc_history_refresh(h);
}
/**
* Deletes the next word, maintaining the cursor at the same position.
* @param h The history data.
*/
static void bc_history_edit_deleteNextWord(BcHistory *h) {
size_t next_end = h->pos, len = BC_HIST_BUF_LEN(h);
// If at the end of the line, skip.
if (next_end == len) return;
// Find the word, then the end of the word.
while (next_end < len && isspace(h->buf.v[next_end])) ++next_end;
while (next_end < len && !isspace(h->buf.v[next_end])) ++next_end;
// Move the stuff into position.
memmove(h->buf.v + h->pos, h->buf.v + next_end, len - next_end);
// Make the buffer valid again.
h->buf.len -= next_end - h->pos;
bc_history_refresh(h);
}
/**
* Swaps two characters, the one under the cursor and the one to the left.
* @param h The history data.
*/
static void bc_history_swap(BcHistory *h) {
size_t pcl, ncl;
char auxb[5];
// Get the length of the previous and next characters.
pcl = bc_history_prevLen(h->buf.v, h->pos);
ncl = bc_history_nextLen(h->buf.v, BC_HIST_BUF_LEN(h), h->pos, NULL);
// To perform a swap we need:
// * Nonzero char length to the left.
// * To not be at the end of the line.
if (pcl && h->pos != BC_HIST_BUF_LEN(h) && pcl < 5 && ncl < 5) {
// Swap.
memcpy(auxb, h->buf.v + h->pos - pcl, pcl);
memcpy(h->buf.v + h->pos - pcl, h->buf.v + h->pos, ncl);
memcpy(h->buf.v + h->pos - pcl + ncl, auxb, pcl);
// Reset the position.
h->pos += ((~pcl) + 1) + ncl;
bc_history_refresh(h);
}
}
/**
* Raises the specified signal. This is a convenience function.
* @param h The history data.
* @param sig The signal to raise.
*/
static void bc_history_raise(BcHistory *h, int sig) {
// We really don't want to be in raw mode when longjmp()'s are flying.
bc_history_disableRaw(h);
raise(sig);
}
/**
* Handles escape sequences. This function will make sense if you know VT100
* escape codes; otherwise, it will be confusing.
* @param h The history data.
*/
static void bc_history_escape(BcHistory *h) {
char c, seq[3];
// Read a character into seq.
if (BC_ERR(BC_HIST_READ(seq, 1))) return;
c = seq[0];
// ESC ? sequences.
if (c != '[' && c != 'O') {
if (c == 'f') bc_history_edit_wordEnd(h);
else if (c == 'b') bc_history_edit_wordStart(h);
else if (c == 'd') bc_history_edit_deleteNextWord(h);
}
else {
// Read a character into seq.
if (BC_ERR(BC_HIST_READ(seq + 1, 1)))
bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
// ESC [ sequences.
if (c == '[') {
c = seq[1];
if (c >= '0' && c <= '9') {
// Extended escape, read additional byte.
if (BC_ERR(BC_HIST_READ(seq + 2, 1)))
bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
if (seq[2] == '~' && c == '3') bc_history_edit_delete(h);
else if(seq[2] == ';') {
// Read two characters into seq.
if (BC_ERR(BC_HIST_READ(seq, 2)))
bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
if (seq[0] != '5') return;
else if (seq[1] == 'C') bc_history_edit_wordEnd(h);
else if (seq[1] == 'D') bc_history_edit_wordStart(h);
}
}
else {
switch(c) {
// Up.
case 'A':
{
bc_history_edit_next(h, BC_HIST_PREV);
break;
}
// Down.
case 'B':
{
bc_history_edit_next(h, BC_HIST_NEXT);
break;
}
// Right.
case 'C':
{
bc_history_edit_right(h);
break;
}
// Left.
case 'D':
{
bc_history_edit_left(h);
break;
}
// Home.
case 'H':
case '1':
{
bc_history_edit_home(h);
break;
}
// End.
case 'F':
case '4':
{
bc_history_edit_end(h);
break;
}
case 'd':
{
bc_history_edit_deleteNextWord(h);
break;
}
}
}
}
// ESC O sequences.
else {
switch (seq[1]) {
case 'A':
{
bc_history_edit_next(h, BC_HIST_PREV);
break;
}
case 'B':
{
bc_history_edit_next(h, BC_HIST_NEXT);
break;
}
case 'C':
{
bc_history_edit_right(h);
break;
}
case 'D':
{
bc_history_edit_left(h);
break;
}
case 'F':
{
bc_history_edit_end(h);
break;
}
case 'H':
{
bc_history_edit_home(h);
break;
}
}
}
}
}
/**
* Adds a line to the history.
* @param h The history data.
* @param line The line to add.
*/
static void bc_history_add(BcHistory *h, char *line) {
// If there is something already there...
if (h->history.len) {
// Get the previous.
char *s = *((char**) bc_vec_item_rev(&h->history, 0));
// Check for, and discard, duplicates.
if (!strcmp(s, line)) {
BC_SIG_LOCK;
free(line);
BC_SIG_UNLOCK;
return;
}
}
bc_vec_push(&h->history, &line);
}
/**
* Adds an empty line to the history. This is separate from bc_history_add()
* because we don't want it allocating.
* @param h The history data.
*/
static void bc_history_add_empty(BcHistory *h) {
const char *line = "";
// If there is something already there...
if (h->history.len) {
// Get the previous.
char *s = *((char**) bc_vec_item_rev(&h->history, 0));
// Check for, and discard, duplicates.
if (!s[0]) return;
}
bc_vec_push(&h->history, &line);
}
/**
* Resets the history state to nothing.
* @param h The history data.
*/
static void bc_history_reset(BcHistory *h) {
h->oldcolpos = h->pos = h->idx = 0;
h->cols = bc_history_columns();
// The latest history entry is always our current buffer, that
// initially is just an empty string.
bc_history_add_empty(h);
// Buffer starts empty.
bc_vec_empty(&h->buf);
}
/**
* Prints a control character.
* @param h The history data.
* @param c The control character to print.
*/
static void bc_history_printCtrl(BcHistory *h, unsigned int c) {
char str[3] = "^A";
const char newline[2] = "\n";
// Set the correct character.
str[1] = (char) (c + 'A' - BC_ACTION_CTRL_A);
// Concatenate the string.
bc_vec_concat(&h->buf, str);
bc_history_refresh(h);
// Pop the string.
bc_vec_npop(&h->buf, sizeof(str));
bc_vec_pushByte(&h->buf, '\0');
#ifndef _WIN32
if (c != BC_ACTION_CTRL_C && c != BC_ACTION_CTRL_D)
#endif // _WIN32
{
// We sometimes want to print a newline; for the times we don't; it's
// because newlines are taken care of elsewhere.
bc_file_write(&vm.fout, bc_flush_none, newline, sizeof(newline) - 1);
bc_history_refresh(h);
}
}
/**
* Edits a line of history. This function is the core of the line editing
* capability of bc history. It expects 'fd' to be already in "raw mode" so that
* every key pressed will be returned ASAP to read().
* @param h The history data.
* @param prompt The prompt.
* @return BC_STATUS_SUCCESS or BC_STATUS_EOF.
*/
static BcStatus bc_history_edit(BcHistory *h, const char *prompt) {
bc_history_reset(h);
// Don't write the saved output the first time. This is because it has
// already been written to output. In other words, don't uncomment the
// line below or add anything like it.
// bc_file_write(&vm.fout, bc_flush_none, h->extras.v, h->extras.len - 1);
// Write the prompt if desired.
if (BC_PROMPT) {
h->prompt = prompt;
h->plen = strlen(prompt);
h->pcol = bc_history_promptColLen(prompt, h->plen);
bc_file_write(&vm.fout, bc_flush_none, prompt, h->plen);
bc_file_flush(&vm.fout, bc_flush_none);
}
// This is the input loop.
for (;;) {
BcStatus s;
char cbuf[32];
unsigned int c = 0;
size_t nread = 0;
// Read a code.
s = bc_history_readCode(cbuf, sizeof(cbuf), &c, &nread);
if (BC_ERR(s)) return s;
switch (c) {
case BC_ACTION_LINE_FEED:
case BC_ACTION_ENTER:
{
// Return the line.
bc_vec_pop(&h->history);
return s;
}
case BC_ACTION_TAB:
{
// My tab handling is dumb; it just prints 8 spaces every time.
memcpy(cbuf, bc_history_tab, bc_history_tab_len + 1);
bc_history_edit_insert(h, cbuf, bc_history_tab_len);
break;
}
#ifndef _WIN32
case BC_ACTION_CTRL_C:
{
bc_history_printCtrl(h, c);
// Quit if the user wants it.
if (!BC_SIGINT) {
vm.status = BC_STATUS_QUIT;
BC_JMP;
}
// Print the ready message.
bc_file_write(&vm.fout, bc_flush_none, vm.sigmsg, vm.siglen);
bc_file_write(&vm.fout, bc_flush_none, bc_program_ready_msg,
bc_program_ready_msg_len);
bc_history_reset(h);
bc_history_refresh(h);
break;
}
#endif // _WIN32
case BC_ACTION_BACKSPACE:
case BC_ACTION_CTRL_H:
{
bc_history_edit_backspace(h);
break;
}
#ifndef _WIN32
// Act as end-of-file.
case BC_ACTION_CTRL_D:
{
bc_history_printCtrl(h, c);
return BC_STATUS_EOF;
}
#endif // _WIN32
// Swaps current character with previous.
case BC_ACTION_CTRL_T:
{
bc_history_swap(h);
break;
}
case BC_ACTION_CTRL_B:
{
bc_history_edit_left(h);
break;
}
case BC_ACTION_CTRL_F:
{
bc_history_edit_right(h);
break;
}
case BC_ACTION_CTRL_P:
{
bc_history_edit_next(h, BC_HIST_PREV);
break;
}
case BC_ACTION_CTRL_N:
{
bc_history_edit_next(h, BC_HIST_NEXT);
break;
}
case BC_ACTION_ESC:
{
bc_history_escape(h);
break;
}
// Delete the whole line.
case BC_ACTION_CTRL_U:
{
bc_vec_string(&h->buf, 0, "");
h->pos = 0;
bc_history_refresh(h);
break;
}
// Delete from current to end of line.
case BC_ACTION_CTRL_K:
{
bc_vec_npop(&h->buf, h->buf.len - h->pos);
bc_vec_pushByte(&h->buf, '\0');
bc_history_refresh(h);
break;
}
// Go to the start of the line.
case BC_ACTION_CTRL_A:
{
bc_history_edit_home(h);
break;
}
// Go to the end of the line.
case BC_ACTION_CTRL_E:
{
bc_history_edit_end(h);
break;
}
// Clear screen.
case BC_ACTION_CTRL_L:
{
bc_file_write(&vm.fout, bc_flush_none, "\x1b[H\x1b[2J", 7);
bc_history_refresh(h);
break;
}
// Delete previous word.
case BC_ACTION_CTRL_W:
{
bc_history_edit_deletePrevWord(h);
break;
}
default:
{
// If we have a control character, print it and raise signals as
// needed.
if ((c >= BC_ACTION_CTRL_A && c <= BC_ACTION_CTRL_Z) ||
c == BC_ACTION_CTRL_BSLASH)
{
bc_history_printCtrl(h, c);
#ifndef _WIN32
if (c == BC_ACTION_CTRL_Z) bc_history_raise(h, SIGTSTP);
if (c == BC_ACTION_CTRL_S) bc_history_raise(h, SIGSTOP);
if (c == BC_ACTION_CTRL_BSLASH)
bc_history_raise(h, SIGQUIT);
#else // _WIN32
vm.status = BC_STATUS_QUIT;
BC_JMP;
#endif // _WIN32
}
// Otherwise, just insert.
else bc_history_edit_insert(h, cbuf, nread);
break;
}
}
}
return BC_STATUS_SUCCESS;
}
/**
* Returns true if stdin has more data. This is for multi-line pasting, and it
* does not work on Windows.
* @param h The history data.
*/
static inline bool bc_history_stdinHasData(BcHistory *h) {
#ifndef _WIN32
int n;
return pselect(1, &h->rdset, NULL, NULL, &h->ts, &h->sigmask) > 0 ||
(ioctl(STDIN_FILENO, FIONREAD, &n) >= 0 && n > 0);
#else // _WIN32
return false;
#endif // _WIN32
}
BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt) {
BcStatus s;
char* line;
assert(vm.fout.len == 0);
bc_history_enableRaw(h);
do {
// Do the edit.
s = bc_history_edit(h, prompt);
// Print a newline and flush.
bc_file_write(&vm.fout, bc_flush_none, "\n", 1);
bc_file_flush(&vm.fout, bc_flush_none);
// If we actually have data...
if (h->buf.v[0]) {
BC_SIG_LOCK;
// Duplicate it.
line = bc_vm_strdup(h->buf.v);
BC_SIG_UNLOCK;
// Store it.
bc_history_add(h, line);
}
// Add an empty string.
else bc_history_add_empty(h);
// Concatenate the line to the return vector.
bc_vec_concat(vec, h->buf.v);
bc_vec_concat(vec, "\n");
} while (!s && bc_history_stdinHasData(h));
assert(!s || s == BC_STATUS_EOF);
bc_history_disableRaw(h);
return s;
}
void bc_history_string_free(void *str) {
char *s = *((char**) str);
BC_SIG_ASSERT_LOCKED;
if (s[0]) free(s);
}
void bc_history_init(BcHistory *h) {
+#ifdef _WIN32
+ HANDLE out, in;
+#endif // _WIN32
+
BC_SIG_ASSERT_LOCKED;
+ h->rawMode = false;
+ h->badTerm = bc_history_isBadTerm();
+
+#ifdef _WIN32
+
+ h->orig_in = 0;
+ h->orig_out = 0;
+
+ in = GetStdHandle(STD_INPUT_HANDLE);
+ out = GetStdHandle(STD_OUTPUT_HANDLE);
+
+ if (!h->badTerm) {
+ SetConsoleCP(CP_UTF8);
+ SetConsoleOutputCP(CP_UTF8);
+ if (!GetConsoleMode(in, &h->orig_in) ||
+ !GetConsoleMode(out, &h->orig_out))
+ {
+ h->badTerm = true;
+ return;
+ }
+ else {
+ DWORD reqOut = ENABLE_VIRTUAL_TERMINAL_PROCESSING |
+ DISABLE_NEWLINE_AUTO_RETURN;
+ DWORD reqIn = ENABLE_VIRTUAL_TERMINAL_INPUT;
+ if (!SetConsoleMode(in, h->orig_in | reqIn) ||
+ !SetConsoleMode(out, h->orig_out | reqOut))
+ {
+ h->badTerm = true;
+ }
+ }
+ }
+#endif // _WIN32
+
bc_vec_init(&h->buf, sizeof(char), BC_DTOR_NONE);
bc_vec_init(&h->history, sizeof(char*), BC_DTOR_HISTORY_STRING);
bc_vec_init(&h->extras, sizeof(char), BC_DTOR_NONE);
#ifndef _WIN32
FD_ZERO(&h->rdset);
FD_SET(STDIN_FILENO, &h->rdset);
h->ts.tv_sec = 0;
h->ts.tv_nsec = 0;
sigemptyset(&h->sigmask);
sigaddset(&h->sigmask, SIGINT);
#endif // _WIN32
-
- h->rawMode = false;
- h->badTerm = bc_history_isBadTerm();
-
-#ifdef _WIN32
- if (!h->badTerm) {
- SetConsoleCP(CP_UTF8);
- SetConsoleOutputCP(CP_UTF8);
- GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &h->orig_console_mode);
- SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),
- ENABLE_VIRTUAL_TERMINAL_INPUT);
- }
-#endif // _WIN32
}
void bc_history_free(BcHistory *h) {
BC_SIG_ASSERT_LOCKED;
#ifndef _WIN32
bc_history_disableRaw(h);
#else // _WIN32
- SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), h->orig_console_mode);
+ SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), h->orig_in);
+ SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), h->orig_out);
#endif // _WIN32
#ifndef NDEBUG
bc_vec_free(&h->buf);
bc_vec_free(&h->history);
bc_vec_free(&h->extras);
#endif // NDEBUG
}
#if BC_DEBUG_CODE
/**
* Prints scan codes. This special mode is used by bc history in order to print
* scan codes on screen for debugging / development purposes.
* @param h The history data.
*/
void bc_history_printKeyCodes(BcHistory *h) {
char quit[4];
bc_vm_printf("Linenoise key codes debugging mode.\n"
"Press keys to see scan codes. "
"Type 'quit' at any time to exit.\n");
bc_history_enableRaw(h);
memset(quit, ' ', 4);
while(true) {
char c;
ssize_t nread;
nread = bc_history_read(&c, 1);
if (nread <= 0) continue;
// Shift string to left.
memmove(quit, quit + 1, sizeof(quit) - 1);
// Insert current char on the right.
quit[sizeof(quit) - 1] = c;
if (!memcmp(quit, "quit", sizeof(quit))) break;
bc_vm_printf("'%c' %lu (type quit to exit)\n",
isprint(c) ? c : '?', (unsigned long) c);
// Go left edge manually, we are in raw mode.
bc_vm_putchar('\r', bc_flush_none);
bc_file_flush(&vm.fout, bc_flush_none);
}
bc_history_disableRaw(h);
}
#endif // BC_DEBUG_CODE
#endif // BC_ENABLE_HISTORY
diff --git a/src/library.c b/src/library.c
index dbc8355a6b8e..e0bd3ee98b85 100644
--- a/src/library.c
+++ b/src/library.c
@@ -1,1273 +1,1281 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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 public functions for libbc.
*
*/
#if BC_ENABLE_LIBRARY
#include
#include
#include
#include
#include
#include
#include
// The asserts in this file are important to testing; in many cases, the test
// would not work without the asserts, so don't remove them without reason.
//
// Also, there are many uses of bc_num_clear() here; that is because numbers are
// being reused, and a clean slate is required.
//
// Also, there are a bunch of BC_UNSETJMP and BC_SETJMP_LOCKED() between calls
// to bc_num_init(). That is because locals are being initialized, and unlike bc
// proper, this code cannot assume that allocation failures are fatal. So we
// have to reset the jumps every time to ensure that the locals will be correct
// after jumping.
void bcl_handleSignal(void) {
// Signal already in flight, or bc is not executing.
if (vm.sig || !vm.running) return;
vm.sig = 1;
assert(vm.jmp_bufs.len);
if (!vm.sig_lock) BC_JMP;
}
bool bcl_running(void) {
return vm.running != 0;
}
BclError bcl_init(void) {
BclError e = BCL_ERROR_NONE;
vm.refs += 1;
if (vm.refs > 1) return e;
// Setting these to NULL ensures that if an error occurs, we only free what
// is necessary.
vm.ctxts.v = NULL;
vm.jmp_bufs.v = NULL;
vm.out.v = NULL;
vm.abrt = false;
BC_SIG_LOCK;
// The jmp_bufs always has to be initialized first.
bc_vec_init(&vm.jmp_bufs, sizeof(sigjmp_buf), BC_DTOR_NONE);
BC_FUNC_HEADER_INIT(err);
bc_vm_init();
bc_vec_init(&vm.ctxts, sizeof(BclContext), BC_DTOR_NONE);
bc_vec_init(&vm.out, sizeof(uchar), BC_DTOR_NONE);
// We need to seed this in case /dev/random and /dev/urandm don't work.
srand((unsigned int) time(NULL));
bc_rand_init(&vm.rng);
err:
// This is why we had to set them to NULL.
if (BC_ERR(vm.err)) {
if (vm.out.v != NULL) bc_vec_free(&vm.out);
if (vm.jmp_bufs.v != NULL) bc_vec_free(&vm.jmp_bufs);
if (vm.ctxts.v != NULL) bc_vec_free(&vm.ctxts);
}
BC_FUNC_FOOTER_UNLOCK(e);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return e;
}
BclError bcl_pushContext(BclContext ctxt) {
BclError e = BCL_ERROR_NONE;
BC_FUNC_HEADER_LOCK(err);
bc_vec_push(&vm.ctxts, &ctxt);
err:
BC_FUNC_FOOTER_UNLOCK(e);
return e;
}
void bcl_popContext(void) {
if (vm.ctxts.len) bc_vec_pop(&vm.ctxts);
}
BclContext bcl_context(void) {
if (!vm.ctxts.len) return NULL;
return *((BclContext*) bc_vec_top(&vm.ctxts));
}
void bcl_free(void) {
size_t i;
vm.refs -= 1;
if (vm.refs) return;
BC_SIG_LOCK;
bc_rand_free(&vm.rng);
bc_vec_free(&vm.out);
for (i = 0; i < vm.ctxts.len; ++i) {
BclContext ctxt = *((BclContext*) bc_vec_item(&vm.ctxts, i));
bcl_ctxt_free(ctxt);
}
bc_vec_free(&vm.ctxts);
bc_vm_atexit();
BC_SIG_UNLOCK;
memset(&vm, 0, sizeof(BcVm));
assert(!vm.running && !vm.sig && !vm.sig_lock);
}
void bcl_gc(void) {
BC_SIG_LOCK;
bc_vm_freeTemps();
BC_SIG_UNLOCK;
}
bool bcl_abortOnFatalError(void) {
return vm.abrt;
}
void bcl_setAbortOnFatalError(bool abrt) {
vm.abrt = abrt;
}
+bool bcl_leadingZeroes(void) {
+ return vm.leading_zeroes;
+}
+
+void bcl_setLeadingZeroes(bool leadingZeroes) {
+ vm.leading_zeroes = leadingZeroes;
+}
+
BclContext bcl_ctxt_create(void) {
BclContext ctxt = NULL;
BC_FUNC_HEADER_LOCK(err);
// We want the context to be free of any interference of other parties, so
// malloc() is appropriate here.
ctxt = bc_vm_malloc(sizeof(BclCtxt));
bc_vec_init(&ctxt->nums, sizeof(BcNum), BC_DTOR_BCL_NUM);
bc_vec_init(&ctxt->free_nums, sizeof(BclNumber), BC_DTOR_NONE);
ctxt->scale = 0;
ctxt->ibase = 10;
ctxt->obase= 10;
err:
if (BC_ERR(vm.err && ctxt != NULL)) {
if (ctxt->nums.v != NULL) bc_vec_free(&ctxt->nums);
free(ctxt);
ctxt = NULL;
}
BC_FUNC_FOOTER_NO_ERR;
assert(!vm.running && !vm.sig && !vm.sig_lock);
return ctxt;
}
void bcl_ctxt_free(BclContext ctxt) {
BC_SIG_LOCK;
bc_vec_free(&ctxt->free_nums);
bc_vec_free(&ctxt->nums);
free(ctxt);
BC_SIG_UNLOCK;
}
void bcl_ctxt_freeNums(BclContext ctxt) {
bc_vec_popAll(&ctxt->nums);
bc_vec_popAll(&ctxt->free_nums);
}
size_t bcl_ctxt_scale(BclContext ctxt) {
return ctxt->scale;
}
void bcl_ctxt_setScale(BclContext ctxt, size_t scale) {
ctxt->scale = scale;
}
size_t bcl_ctxt_ibase(BclContext ctxt) {
return ctxt->ibase;
}
void bcl_ctxt_setIbase(BclContext ctxt, size_t ibase) {
if (ibase < BC_NUM_MIN_BASE) ibase = BC_NUM_MIN_BASE;
else if (ibase > BC_NUM_MAX_IBASE) ibase = BC_NUM_MAX_IBASE;
ctxt->ibase = ibase;
}
size_t bcl_ctxt_obase(BclContext ctxt) {
return ctxt->obase;
}
void bcl_ctxt_setObase(BclContext ctxt, size_t obase) {
ctxt->obase = obase;
}
BclError bcl_err(BclNumber n) {
BclContext ctxt;
BC_CHECK_CTXT_ERR(ctxt);
// Errors are encoded as (0 - error_code). If the index is in that range, it
// is an encoded error.
if (n.i >= ctxt->nums.len) {
if (n.i > 0 - (size_t) BCL_ERROR_NELEMS) return (BclError) (0 - n.i);
else return BCL_ERROR_INVALID_NUM;
}
else return BCL_ERROR_NONE;
}
/**
* Inserts a BcNum into a context's list of numbers.
* @param ctxt The context to insert into.
* @param n The BcNum to insert.
* @return The resulting BclNumber from the insert.
*/
static BclNumber bcl_num_insert(BclContext ctxt, BcNum *restrict n) {
BclNumber idx;
// If there is a free spot...
if (ctxt->free_nums.len) {
BcNum *ptr;
// Get the index of the free spot and remove it.
idx = *((BclNumber*) bc_vec_top(&ctxt->free_nums));
bc_vec_pop(&ctxt->free_nums);
// Copy the number into the spot.
ptr = bc_vec_item(&ctxt->nums, idx.i);
memcpy(ptr, n, sizeof(BcNum));
}
else {
// Just push the number onto the vector.
idx.i = ctxt->nums.len;
bc_vec_push(&ctxt->nums, n);
}
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
BclNumber bcl_num_create(void) {
BclError e = BCL_ERROR_NONE;
BcNum n;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
bc_num_init(&n, BC_NUM_DEF_SIZE);
err:
BC_FUNC_FOOTER_UNLOCK(e);
BC_MAYBE_SETUP(ctxt, e, n, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
/**
* Destructs a number and marks its spot as free.
* @param ctxt The context.
* @param n The index of the number.
* @param num The number to destroy.
*/
static void bcl_num_dtor(BclContext ctxt, BclNumber n, BcNum *restrict num) {
BC_SIG_ASSERT_LOCKED;
assert(num != NULL && num->num != NULL);
bcl_num_destruct(num);
bc_vec_push(&ctxt->free_nums, &n);
}
void bcl_num_free(BclNumber n) {
BcNum *num;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
BC_SIG_LOCK;
assert(n.i < ctxt->nums.len);
num = BC_NUM(ctxt, n);
bcl_num_dtor(ctxt, n, num);
BC_SIG_UNLOCK;
}
BclError bcl_copy(BclNumber d, BclNumber s) {
BclError e = BCL_ERROR_NONE;
BcNum *dest, *src;
BclContext ctxt;
BC_CHECK_CTXT_ERR(ctxt);
BC_FUNC_HEADER_LOCK(err);
assert(d.i < ctxt->nums.len && s.i < ctxt->nums.len);
dest = BC_NUM(ctxt, d);
src = BC_NUM(ctxt, s);
assert(dest != NULL && src != NULL);
assert(dest->num != NULL && src->num != NULL);
bc_num_copy(dest, src);
err:
BC_FUNC_FOOTER_UNLOCK(e);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return e;
}
BclNumber bcl_dup(BclNumber s) {
BclError e = BCL_ERROR_NONE;
BcNum *src, dest;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
assert(s.i < ctxt->nums.len);
src = BC_NUM(ctxt, s);
assert(src != NULL && src->num != NULL);
// Copy the number.
bc_num_clear(&dest);
bc_num_createCopy(&dest, src);
err:
BC_FUNC_FOOTER_UNLOCK(e);
BC_MAYBE_SETUP(ctxt, e, dest, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
void bcl_num_destruct(void *num) {
BcNum *n = (BcNum*) num;
assert(n != NULL);
if (n->num == NULL) return;
bc_num_free(num);
bc_num_clear(num);
}
bool bcl_num_neg(BclNumber n) {
BcNum *num;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
assert(n.i < ctxt->nums.len);
num = BC_NUM(ctxt, n);
assert(num != NULL && num->num != NULL);
return BC_NUM_NEG(num) != 0;
}
void bcl_num_setNeg(BclNumber n, bool neg) {
BcNum *num;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
assert(n.i < ctxt->nums.len);
num = BC_NUM(ctxt, n);
assert(num != NULL && num->num != NULL);
num->rdx = BC_NUM_NEG_VAL(num, neg);
}
size_t bcl_num_scale(BclNumber n) {
BcNum *num;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
assert(n.i < ctxt->nums.len);
num = BC_NUM(ctxt, n);
assert(num != NULL && num->num != NULL);
return bc_num_scale(num);
}
BclError bcl_num_setScale(BclNumber n, size_t scale) {
BclError e = BCL_ERROR_NONE;
BcNum *nptr;
BclContext ctxt;
BC_CHECK_CTXT_ERR(ctxt);
BC_CHECK_NUM_ERR(ctxt, n);
BC_FUNC_HEADER(err);
assert(n.i < ctxt->nums.len);
nptr = BC_NUM(ctxt, n);
assert(nptr != NULL && nptr->num != NULL);
if (scale > nptr->scale) bc_num_extend(nptr, scale - nptr->scale);
else if (scale < nptr->scale) bc_num_truncate(nptr, nptr->scale - scale);
err:
BC_SIG_MAYLOCK;
BC_FUNC_FOOTER(e);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return e;
}
size_t bcl_num_len(BclNumber n) {
BcNum *num;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
assert(n.i < ctxt->nums.len);
num = BC_NUM(ctxt, n);
assert(num != NULL && num->num != NULL);
return bc_num_len(num);
}
BclError bcl_bigdig(BclNumber n, BclBigDig *result) {
BclError e = BCL_ERROR_NONE;
BcNum *num;
BclContext ctxt;
BC_CHECK_CTXT_ERR(ctxt);
BC_FUNC_HEADER_LOCK(err);
assert(n.i < ctxt->nums.len);
assert(result != NULL);
num = BC_NUM(ctxt, n);
assert(num != NULL && num->num != NULL);
*result = bc_num_bigdig(num);
err:
bcl_num_dtor(ctxt, n, num);
BC_FUNC_FOOTER_UNLOCK(e);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return e;
}
BclNumber bcl_bigdig2num(BclBigDig val) {
BclError e = BCL_ERROR_NONE;
BcNum n;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
bc_num_createFromBigdig(&n, val);
err:
BC_FUNC_FOOTER_UNLOCK(e);
BC_MAYBE_SETUP(ctxt, e, n, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
/**
* Sets up and executes a binary operator operation.
* @param a The first operand.
* @param b The second operand.
* @param op The operation.
* @param req The function to get the size of the result for preallocation.
* @return The result of the operation.
*/
static BclNumber bcl_binary(BclNumber a, BclNumber b, const BcNumBinaryOp op,
const BcNumBinaryOpReq req)
{
BclError e = BCL_ERROR_NONE;
BcNum *aptr, *bptr;
BcNum c;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_CHECK_NUM(ctxt, a);
BC_CHECK_NUM(ctxt, b);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len);
aptr = BC_NUM(ctxt, a);
bptr = BC_NUM(ctxt, b);
assert(aptr != NULL && bptr != NULL);
assert(aptr->num != NULL && bptr->num != NULL);
// Clear and initialize the result.
bc_num_clear(&c);
bc_num_init(&c, req(aptr, bptr, ctxt->scale));
BC_SIG_UNLOCK;
op(aptr, bptr, &c, ctxt->scale);
err:
BC_SIG_MAYLOCK;
// Eat the operands.
bcl_num_dtor(ctxt, a, aptr);
if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr);
BC_FUNC_FOOTER(e);
BC_MAYBE_SETUP(ctxt, e, c, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
BclNumber bcl_add(BclNumber a, BclNumber b) {
return bcl_binary(a, b, bc_num_add, bc_num_addReq);
}
BclNumber bcl_sub(BclNumber a, BclNumber b) {
return bcl_binary(a, b, bc_num_sub, bc_num_addReq);
}
BclNumber bcl_mul(BclNumber a, BclNumber b) {
return bcl_binary(a, b, bc_num_mul, bc_num_mulReq);
}
BclNumber bcl_div(BclNumber a, BclNumber b) {
return bcl_binary(a, b, bc_num_div, bc_num_divReq);
}
BclNumber bcl_mod(BclNumber a, BclNumber b) {
return bcl_binary(a, b, bc_num_mod, bc_num_divReq);
}
BclNumber bcl_pow(BclNumber a, BclNumber b) {
return bcl_binary(a, b, bc_num_pow, bc_num_powReq);
}
BclNumber bcl_lshift(BclNumber a, BclNumber b) {
return bcl_binary(a, b, bc_num_lshift, bc_num_placesReq);
}
BclNumber bcl_rshift(BclNumber a, BclNumber b) {
return bcl_binary(a, b, bc_num_rshift, bc_num_placesReq);
}
BclNumber bcl_sqrt(BclNumber a) {
BclError e = BCL_ERROR_NONE;
BcNum *aptr;
BcNum b;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_CHECK_NUM(ctxt, a);
BC_FUNC_HEADER(err);
bc_vec_grow(&ctxt->nums, 1);
assert(a.i < ctxt->nums.len);
aptr = BC_NUM(ctxt, a);
bc_num_sqrt(aptr, &b, ctxt->scale);
err:
BC_SIG_MAYLOCK;
bcl_num_dtor(ctxt, a, aptr);
BC_FUNC_FOOTER(e);
BC_MAYBE_SETUP(ctxt, e, b, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
BclError bcl_divmod(BclNumber a, BclNumber b, BclNumber *c, BclNumber *d) {
BclError e = BCL_ERROR_NONE;
size_t req;
BcNum *aptr, *bptr;
BcNum cnum, dnum;
BclContext ctxt;
BC_CHECK_CTXT_ERR(ctxt);
BC_CHECK_NUM_ERR(ctxt, a);
BC_CHECK_NUM_ERR(ctxt, b);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 2);
assert(c != NULL && d != NULL);
aptr = BC_NUM(ctxt, a);
bptr = BC_NUM(ctxt, b);
assert(aptr != NULL && bptr != NULL);
assert(aptr->num != NULL && bptr->num != NULL);
bc_num_clear(&cnum);
bc_num_clear(&dnum);
req = bc_num_divReq(aptr, bptr, ctxt->scale);
// Initialize the numbers.
bc_num_init(&cnum, req);
BC_UNSETJMP;
BC_SETJMP_LOCKED(err);
bc_num_init(&dnum, req);
BC_SIG_UNLOCK;
bc_num_divmod(aptr, bptr, &cnum, &dnum, ctxt->scale);
err:
BC_SIG_MAYLOCK;
// Eat the operands.
bcl_num_dtor(ctxt, a, aptr);
if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr);
// If there was an error...
if (BC_ERR(vm.err)) {
// Free the results.
if (cnum.num != NULL) bc_num_free(&cnum);
if (dnum.num != NULL) bc_num_free(&dnum);
// Make sure the return values are invalid.
c->i = 0 - (size_t) BCL_ERROR_INVALID_NUM;
d->i = c->i;
BC_FUNC_FOOTER(e);
}
else {
BC_FUNC_FOOTER(e);
// Insert the results into the context.
*c = bcl_num_insert(ctxt, &cnum);
*d = bcl_num_insert(ctxt, &dnum);
}
assert(!vm.running && !vm.sig && !vm.sig_lock);
return e;
}
BclNumber bcl_modexp(BclNumber a, BclNumber b, BclNumber c) {
BclError e = BCL_ERROR_NONE;
size_t req;
BcNum *aptr, *bptr, *cptr;
BcNum d;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_CHECK_NUM(ctxt, a);
BC_CHECK_NUM(ctxt, b);
BC_CHECK_NUM(ctxt, c);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len);
assert(c.i < ctxt->nums.len);
aptr = BC_NUM(ctxt, a);
bptr = BC_NUM(ctxt, b);
cptr = BC_NUM(ctxt, c);
assert(aptr != NULL && bptr != NULL && cptr != NULL);
assert(aptr->num != NULL && bptr->num != NULL && cptr->num != NULL);
// Prepare the result.
bc_num_clear(&d);
req = bc_num_divReq(aptr, cptr, 0);
// Initialize the result.
bc_num_init(&d, req);
BC_SIG_UNLOCK;
bc_num_modexp(aptr, bptr, cptr, &d);
err:
BC_SIG_MAYLOCK;
// Eat the operands.
bcl_num_dtor(ctxt, a, aptr);
if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr);
if (c.i != a.i && c.i != b.i) bcl_num_dtor(ctxt, c, cptr);
BC_FUNC_FOOTER(e);
BC_MAYBE_SETUP(ctxt, e, d, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
ssize_t bcl_cmp(BclNumber a, BclNumber b) {
BcNum *aptr, *bptr;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len);
aptr = BC_NUM(ctxt, a);
bptr = BC_NUM(ctxt, b);
assert(aptr != NULL && bptr != NULL);
assert(aptr->num != NULL && bptr->num != NULL);
return bc_num_cmp(aptr, bptr);
}
void bcl_zero(BclNumber n) {
BcNum *nptr;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
assert(n.i < ctxt->nums.len);
nptr = BC_NUM(ctxt, n);
assert(nptr != NULL && nptr->num != NULL);
bc_num_zero(nptr);
}
void bcl_one(BclNumber n) {
BcNum *nptr;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
assert(n.i < ctxt->nums.len);
nptr = BC_NUM(ctxt, n);
assert(nptr != NULL && nptr->num != NULL);
bc_num_one(nptr);
}
BclNumber bcl_parse(const char *restrict val) {
BclError e = BCL_ERROR_NONE;
BcNum n;
BclNumber idx;
BclContext ctxt;
bool neg;
BC_CHECK_CTXT(ctxt);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
assert(val != NULL);
// We have to take care of negative here because bc's number parsing does
// not.
neg = (val[0] == '-');
if (neg) val += 1;
if (!bc_num_strValid(val)) {
vm.err = BCL_ERROR_PARSE_INVALID_STR;
goto err;
}
// Clear and initialize the number.
bc_num_clear(&n);
bc_num_init(&n, BC_NUM_DEF_SIZE);
BC_SIG_UNLOCK;
bc_num_parse(&n, val, (BcBigDig) ctxt->ibase);
// Set the negative.
n.rdx = BC_NUM_NEG_VAL_NP(n, neg);
err:
BC_SIG_MAYLOCK;
BC_FUNC_FOOTER(e);
BC_MAYBE_SETUP(ctxt, e, n, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
char* bcl_string(BclNumber n) {
BcNum *nptr;
char *str = NULL;
BclContext ctxt;
BC_CHECK_CTXT_ASSERT(ctxt);
if (BC_ERR(n.i >= ctxt->nums.len)) return str;
BC_FUNC_HEADER(err);
assert(n.i < ctxt->nums.len);
nptr = BC_NUM(ctxt, n);
assert(nptr != NULL && nptr->num != NULL);
// Clear the buffer.
bc_vec_popAll(&vm.out);
// Print to the buffer.
bc_num_print(nptr, (BcBigDig) ctxt->obase, false);
bc_vec_pushByte(&vm.out, '\0');
BC_SIG_LOCK;
// Just dup the string; the caller is responsible for it.
str = bc_vm_strdup(vm.out.v);
err:
// Eat the operand.
bcl_num_dtor(ctxt, n, nptr);
BC_FUNC_FOOTER_NO_ERR;
assert(!vm.running && !vm.sig && !vm.sig_lock);
return str;
}
BclNumber bcl_irand(BclNumber a) {
BclError e = BCL_ERROR_NONE;
BcNum *aptr;
BcNum b;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_CHECK_NUM(ctxt, a);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
assert(a.i < ctxt->nums.len);
aptr = BC_NUM(ctxt, a);
assert(aptr != NULL && aptr->num != NULL);
// Clear and initialize the result.
bc_num_clear(&b);
bc_num_init(&b, BC_NUM_DEF_SIZE);
BC_SIG_UNLOCK;
bc_num_irand(aptr, &b, &vm.rng);
err:
BC_SIG_MAYLOCK;
// Eat the operand.
bcl_num_dtor(ctxt, a, aptr);
BC_FUNC_FOOTER(e);
BC_MAYBE_SETUP(ctxt, e, b, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
/**
* Helps bcl_frand(). This is separate because the error handling is easier that
* way. It is also easier to do ifrand that way.
* @param b The return parameter.
* @param places The number of decimal places to generate.
*/
static void bcl_frandHelper(BcNum *restrict b, size_t places) {
BcNum exp, pow, ten;
BcDig exp_digs[BC_NUM_BIGDIG_LOG10];
BcDig ten_digs[BC_NUM_BIGDIG_LOG10];
// Set up temporaries.
bc_num_setup(&exp, exp_digs, BC_NUM_BIGDIG_LOG10);
bc_num_setup(&ten, ten_digs, BC_NUM_BIGDIG_LOG10);
ten.num[0] = 10;
ten.len = 1;
bc_num_bigdig2num(&exp, (BcBigDig) places);
// Clear the temporary that might need to grow.
bc_num_clear(&pow);
BC_SIG_LOCK;
// Initialize the temporary that might need to grow.
bc_num_init(&pow, bc_num_powReq(&ten, &exp, 0));
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// Generate the number.
bc_num_pow(&ten, &exp, &pow, 0);
bc_num_irand(&pow, b, &vm.rng);
// Make the number entirely fraction.
bc_num_shiftRight(b, places);
err:
BC_SIG_MAYLOCK;
bc_num_free(&pow);
BC_LONGJMP_CONT;
}
BclNumber bcl_frand(size_t places) {
BclError e = BCL_ERROR_NONE;
BcNum n;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
// Clear and initialize the number.
bc_num_clear(&n);
bc_num_init(&n, BC_NUM_DEF_SIZE);
BC_SIG_UNLOCK;
bcl_frandHelper(&n, places);
err:
BC_SIG_MAYLOCK;
BC_FUNC_FOOTER(e);
BC_MAYBE_SETUP(ctxt, e, n, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
/**
* Helps bc_ifrand(). This is separate because error handling is easier that
* way.
* @param a The limit for bc_num_irand().
* @param b The return parameter.
* @param places The number of decimal places to generate.
*/
static void bcl_ifrandHelper(BcNum *restrict a, BcNum *restrict b,
size_t places)
{
BcNum ir, fr;
// Clear the integer and fractional numbers.
bc_num_clear(&ir);
bc_num_clear(&fr);
BC_SIG_LOCK;
// Initialize the integer and fractional numbers.
bc_num_init(&ir, BC_NUM_DEF_SIZE);
bc_num_init(&fr, BC_NUM_DEF_SIZE);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
bc_num_irand(a, &ir, &vm.rng);
bcl_frandHelper(&fr, places);
bc_num_add(&ir, &fr, b, 0);
err:
BC_SIG_MAYLOCK;
bc_num_free(&fr);
bc_num_free(&ir);
BC_LONGJMP_CONT;
}
BclNumber bcl_ifrand(BclNumber a, size_t places) {
BclError e = BCL_ERROR_NONE;
BcNum *aptr;
BcNum b;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_CHECK_NUM(ctxt, a);
BC_FUNC_HEADER_LOCK(err);
bc_vec_grow(&ctxt->nums, 1);
assert(a.i < ctxt->nums.len);
aptr = BC_NUM(ctxt, a);
assert(aptr != NULL && aptr->num != NULL);
// Clear and initialize the number.
bc_num_clear(&b);
bc_num_init(&b, BC_NUM_DEF_SIZE);
BC_SIG_UNLOCK;
bcl_ifrandHelper(aptr, &b, places);
err:
BC_SIG_MAYLOCK;
// Eat the oprand.
bcl_num_dtor(ctxt, a, aptr);
BC_FUNC_FOOTER(e);
BC_MAYBE_SETUP(ctxt, e, b, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
BclError bcl_rand_seedWithNum(BclNumber n) {
BclError e = BCL_ERROR_NONE;
BcNum *nptr;
BclContext ctxt;
BC_CHECK_CTXT_ERR(ctxt);
BC_CHECK_NUM_ERR(ctxt, n);
BC_FUNC_HEADER(err);
assert(n.i < ctxt->nums.len);
nptr = BC_NUM(ctxt, n);
assert(nptr != NULL && nptr->num != NULL);
bc_num_rng(nptr, &vm.rng);
err:
BC_SIG_MAYLOCK;
BC_FUNC_FOOTER(e);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return e;
}
BclError bcl_rand_seed(unsigned char seed[BCL_SEED_SIZE]) {
BclError e = BCL_ERROR_NONE;
size_t i;
ulong vals[BCL_SEED_ULONGS];
BC_FUNC_HEADER(err);
// Fill the array.
for (i = 0; i < BCL_SEED_SIZE; ++i) {
ulong val = ((ulong) seed[i]) << (((ulong) CHAR_BIT) *
(i % sizeof(ulong)));
vals[i / sizeof(long)] |= val;
}
bc_rand_seed(&vm.rng, vals[0], vals[1], vals[2], vals[3]);
err:
BC_SIG_MAYLOCK;
BC_FUNC_FOOTER(e);
return e;
}
void bcl_rand_reseed(void) {
bc_rand_srand(bc_vec_top(&vm.rng.v));
}
BclNumber bcl_rand_seed2num(void) {
BclError e = BCL_ERROR_NONE;
BcNum n;
BclNumber idx;
BclContext ctxt;
BC_CHECK_CTXT(ctxt);
BC_FUNC_HEADER_LOCK(err);
// Clear and initialize the number.
bc_num_clear(&n);
bc_num_init(&n, BC_NUM_DEF_SIZE);
BC_SIG_UNLOCK;
bc_num_createFromRNG(&n, &vm.rng);
err:
BC_SIG_MAYLOCK;
BC_FUNC_FOOTER(e);
BC_MAYBE_SETUP(ctxt, e, n, idx);
assert(!vm.running && !vm.sig && !vm.sig_lock);
return idx;
}
BclRandInt bcl_rand_int(void) {
return (BclRandInt) bc_rand_int(&vm.rng);
}
BclRandInt bcl_rand_bounded(BclRandInt bound) {
if (bound <= 1) return 0;
return (BclRandInt) bc_rand_bounded(&vm.rng, (BcRand) bound);
}
#endif // BC_ENABLE_LIBRARY
diff --git a/src/num.c b/src/num.c
index 604328dca80d..dc3f63ab076e 100644
--- a/src/num.c
+++ b/src/num.c
@@ -1,3927 +1,3931 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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 the number type.
*
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
// Before you try to understand this code, see the development manual
// (manuals/development.md#numbers).
static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale);
/**
* Multiply two numbers and throw a math error if they overflow.
* @param a The first operand.
* @param b The second operand.
* @return The product of the two operands.
*/
static inline size_t bc_num_mulOverflow(size_t a, size_t b) {
size_t res = a * b;
if (BC_ERR(BC_VM_MUL_OVERFLOW(a, b, res))) bc_err(BC_ERR_MATH_OVERFLOW);
return res;
}
/**
* Conditionally negate @a n based on @a neg. Algorithm taken from
* https://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate .
* @param n The value to turn into a signed value and negate.
* @param neg The condition to negate or not.
*/
static inline ssize_t bc_num_neg(size_t n, bool neg) {
return (((ssize_t) n) ^ -((ssize_t) neg)) + neg;
}
/**
* Compare a BcNum against zero.
* @param n The number to compare.
* @return -1 if the number is less than 0, 1 if greater, and 0 if equal.
*/
ssize_t bc_num_cmpZero(const BcNum *n) {
return bc_num_neg((n)->len != 0, BC_NUM_NEG(n));
}
/**
* Return the number of integer limbs in a BcNum. This is the opposite of rdx.
* @param n The number to return the amount of integer limbs for.
* @return The amount of integer limbs in @a n.
*/
static inline size_t bc_num_int(const BcNum *n) {
return n->len ? n->len - BC_NUM_RDX_VAL(n) : 0;
}
/**
* Expand a number's allocation capacity to at least req limbs.
* @param n The number to expand.
* @param req The number limbs to expand the allocation capacity to.
*/
static void bc_num_expand(BcNum *restrict n, size_t req) {
assert(n != NULL);
req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
if (req > n->cap) {
BC_SIG_LOCK;
n->num = bc_vm_realloc(n->num, BC_NUM_SIZE(req));
n->cap = req;
BC_SIG_UNLOCK;
}
}
/**
* Set a number to 0 with the specified scale.
* @param n The number to set to zero.
* @param scale The scale to set the number to.
*/
static void bc_num_setToZero(BcNum *restrict n, size_t scale) {
assert(n != NULL);
n->scale = scale;
n->len = n->rdx = 0;
}
void bc_num_zero(BcNum *restrict n) {
bc_num_setToZero(n, 0);
}
void bc_num_one(BcNum *restrict n) {
bc_num_zero(n);
n->len = 1;
n->num[0] = 1;
}
/**
* "Cleans" a number, which means reducing the length if the most significant
* limbs are zero.
* @param n The number to clean.
*/
static void bc_num_clean(BcNum *restrict n) {
// Reduce the length.
while (BC_NUM_NONZERO(n) && !n->num[n->len - 1]) n->len -= 1;
// Special cases.
if (BC_NUM_ZERO(n)) n->rdx = 0;
else {
// len must be at least as much as rdx.
size_t rdx = BC_NUM_RDX_VAL(n);
if (n->len < rdx) n->len = rdx;
}
}
/**
* Returns the log base 10 of @a i. I could have done this with floating-point
* math, and in fact, I originally did. However, that was the only
* floating-point code in the entire codebase, and I decided I didn't want any.
* This is fast enough. Also, it might handle larger numbers better.
* @param i The number to return the log base 10 of.
* @return The log base 10 of @a i.
*/
static size_t bc_num_log10(size_t i) {
size_t len;
for (len = 1; i; i /= BC_BASE, ++len);
assert(len - 1 <= BC_BASE_DIGS + 1);
return len - 1;
}
/**
* Returns the number of decimal digits in a limb that are zero starting at the
* most significant digits. This basically returns how much of the limb is used.
* @param n The number.
* @return The number of decimal digits that are 0 starting at the most
* significant digits.
*/
static inline size_t bc_num_zeroDigits(const BcDig *n) {
assert(*n >= 0);
assert(((size_t) *n) < BC_BASE_POW);
return BC_BASE_DIGS - bc_num_log10((size_t) *n);
}
/**
* Return the total number of integer digits in a number. This is the opposite
* of scale, like bc_num_int() is the opposite of rdx.
* @param n The number.
* @return The number of integer digits in @a n.
*/
static size_t bc_num_intDigits(const BcNum *n) {
size_t digits = bc_num_int(n) * BC_BASE_DIGS;
if (digits > 0) digits -= bc_num_zeroDigits(n->num + n->len - 1);
return digits;
}
/**
* Returns the number of limbs of a number that are non-zero starting at the
* most significant limbs. This expects that there are *no* integer limbs in the
* number because it is specifically to figure out how many zero limbs after the
* decimal place to ignore. If there are zero limbs after non-zero limbs, they
* are counted as non-zero limbs.
* @param n The number.
* @return The number of non-zero limbs after the decimal point.
*/
static size_t bc_num_nonZeroLen(const BcNum *restrict n) {
size_t i, len = n->len;
assert(len == BC_NUM_RDX_VAL(n));
for (i = len - 1; i < len && !n->num[i]; --i);
assert(i + 1 > 0);
return i + 1;
}
/**
* Performs a one-limb add with a carry.
* @param a The first limb.
* @param b The second limb.
* @param carry An in/out parameter; the carry in from the previous add and the
* carry out from this add.
* @return The resulting limb sum.
*/
static BcDig bc_num_addDigits(BcDig a, BcDig b, bool *carry) {
assert(((BcBigDig) BC_BASE_POW) * 2 == ((BcDig) BC_BASE_POW) * 2);
assert(a < BC_BASE_POW);
assert(b < BC_BASE_POW);
a += b + *carry;
*carry = (a >= BC_BASE_POW);
if (*carry) a -= BC_BASE_POW;
assert(a >= 0);
assert(a < BC_BASE_POW);
return a;
}
/**
* Performs a one-limb subtract with a carry.
* @param a The first limb.
* @param b The second limb.
* @param carry An in/out parameter; the carry in from the previous subtract
* and the carry out from this subtract.
* @return The resulting limb difference.
*/
static BcDig bc_num_subDigits(BcDig a, BcDig b, bool *carry) {
assert(a < BC_BASE_POW);
assert(b < BC_BASE_POW);
b += *carry;
*carry = (a < b);
if (*carry) a += BC_BASE_POW;
assert(a - b >= 0);
assert(a - b < BC_BASE_POW);
return a - b;
}
/**
* Add two BcDig arrays and store the result in the first array.
* @param a The first operand and out array.
* @param b The second operand.
* @param len The length of @a b.
*/
static void bc_num_addArrays(BcDig *restrict a, const BcDig *restrict b,
size_t len)
{
size_t i;
bool carry = false;
for (i = 0; i < len; ++i) a[i] = bc_num_addDigits(a[i], b[i], &carry);
// Take care of the extra limbs in the bigger array.
for (; carry; ++i) a[i] = bc_num_addDigits(a[i], 0, &carry);
}
/**
* Subtract two BcDig arrays and store the result in the first array.
* @param a The first operand and out array.
* @param b The second operand.
* @param len The length of @a b.
*/
static void bc_num_subArrays(BcDig *restrict a, const BcDig *restrict b,
size_t len)
{
size_t i;
bool carry = false;
for (i = 0; i < len; ++i) a[i] = bc_num_subDigits(a[i], b[i], &carry);
// Take care of the extra limbs in the bigger array.
for (; carry; ++i) a[i] = bc_num_subDigits(a[i], 0, &carry);
}
/**
* Multiply a BcNum array by a one-limb number. This is a faster version of
* multiplication for when we can use it.
* @param a The BcNum to multiply by the one-limb number.
* @param b The one limb of the one-limb number.
* @param c The return parameter.
*/
static void bc_num_mulArray(const BcNum *restrict a, BcBigDig b,
BcNum *restrict c)
{
size_t i;
BcBigDig carry = 0;
assert(b <= BC_BASE_POW);
// Make sure the return parameter is big enough.
if (a->len + 1 > c->cap) bc_num_expand(c, a->len + 1);
// We want the entire return parameter to be zero for cleaning later.
memset(c->num, 0, BC_NUM_SIZE(c->cap));
// Actual multiplication loop.
for (i = 0; i < a->len; ++i) {
BcBigDig in = ((BcBigDig) a->num[i]) * b + carry;
c->num[i] = in % BC_BASE_POW;
carry = in / BC_BASE_POW;
}
assert(carry < BC_BASE_POW);
// Finishing touches.
c->num[i] = (BcDig) carry;
c->len = a->len;
c->len += (carry != 0);
bc_num_clean(c);
// Postconditions.
assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c));
assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len);
assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len);
}
/**
* Divide a BcNum array by a one-limb number. This is a faster version of divide
* for when we can use it.
* @param a The BcNum to multiply by the one-limb number.
* @param b The one limb of the one-limb number.
* @param c The return parameter for the quotient.
* @param rem The return parameter for the remainder.
*/
static void bc_num_divArray(const BcNum *restrict a, BcBigDig b,
BcNum *restrict c, BcBigDig *rem)
{
size_t i;
BcBigDig carry = 0;
assert(c->cap >= a->len);
// Actual division loop.
for (i = a->len - 1; i < a->len; --i) {
BcBigDig in = ((BcBigDig) a->num[i]) + carry * BC_BASE_POW;
assert(in / b < BC_BASE_POW);
c->num[i] = (BcDig) (in / b);
carry = in % b;
}
// Finishing touches.
c->len = a->len;
bc_num_clean(c);
*rem = carry;
// Postconditions.
assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c));
assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len);
assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len);
}
/**
* Compare two BcDig arrays and return >0 if @a b is greater, <0 if @a b is
* less, and 0 if equal. Both @a a and @a b must have the same length.
* @param a The first array.
* @param b The second array.
* @param len The minimum length of the arrays.
*/
static ssize_t bc_num_compare(const BcDig *restrict a, const BcDig *restrict b,
size_t len)
{
size_t i;
BcDig c = 0;
for (i = len - 1; i < len && !(c = a[i] - b[i]); --i);
return bc_num_neg(i + 1, c < 0);
}
ssize_t bc_num_cmp(const BcNum *a, const BcNum *b) {
size_t i, min, a_int, b_int, diff, ardx, brdx;
BcDig *max_num, *min_num;
bool a_max, neg = false;
ssize_t cmp;
assert(a != NULL && b != NULL);
// Same num? Equal.
if (a == b) return 0;
// Easy cases.
if (BC_NUM_ZERO(a)) return bc_num_neg(b->len != 0, !BC_NUM_NEG(b));
if (BC_NUM_ZERO(b)) return bc_num_cmpZero(a);
if (BC_NUM_NEG(a)) {
if (BC_NUM_NEG(b)) neg = true;
else return -1;
}
else if (BC_NUM_NEG(b)) return 1;
// Get the number of int limbs in each number and get the difference.
a_int = bc_num_int(a);
b_int = bc_num_int(b);
a_int -= b_int;
// If there's a difference, then just return the comparison.
if (a_int) return neg ? -((ssize_t) a_int) : (ssize_t) a_int;
// Get the rdx's and figure out the max.
ardx = BC_NUM_RDX_VAL(a);
brdx = BC_NUM_RDX_VAL(b);
a_max = (ardx > brdx);
// Set variables based on the above.
if (a_max) {
min = brdx;
diff = ardx - brdx;
max_num = a->num + diff;
min_num = b->num;
}
else {
min = ardx;
diff = brdx - ardx;
max_num = b->num + diff;
min_num = a->num;
}
// Do a full limb-by-limb comparison.
cmp = bc_num_compare(max_num, min_num, b_int + min);
// If we found a difference, return it based on state.
if (cmp) return bc_num_neg((size_t) cmp, !a_max == !neg);
// If there was no difference, then the final step is to check which number
// has greater or lesser limbs beyond the other's.
for (max_num -= diff, i = diff - 1; i < diff; --i) {
if (max_num[i]) return bc_num_neg(1, !a_max == !neg);
}
return 0;
}
void bc_num_truncate(BcNum *restrict n, size_t places) {
size_t nrdx, places_rdx;
if (!places) return;
// Grab these needed values; places_rdx is the rdx equivalent to places like
// rdx is to scale.
nrdx = BC_NUM_RDX_VAL(n);
places_rdx = nrdx ? nrdx - BC_NUM_RDX(n->scale - places) : 0;
// We cannot truncate more places than we have.
assert(places <= n->scale && (BC_NUM_ZERO(n) || places_rdx <= n->len));
n->scale -= places;
BC_NUM_RDX_SET(n, nrdx - places_rdx);
// Only when the number is nonzero do we need to do the hard stuff.
if (BC_NUM_NONZERO(n)) {
size_t pow;
// This calculates how many decimal digits are in the least significant
// limb.
pow = n->scale % BC_BASE_DIGS;
pow = pow ? BC_BASE_DIGS - pow : 0;
pow = bc_num_pow10[pow];
n->len -= places_rdx;
// We have to move limbs to maintain invariants. The limbs must begin at
// the beginning of the BcNum array.
memmove(n->num, n->num + places_rdx, BC_NUM_SIZE(n->len));
// Clear the lower part of the last digit.
if (BC_NUM_NONZERO(n)) n->num[0] -= n->num[0] % (BcDig) pow;
bc_num_clean(n);
}
}
void bc_num_extend(BcNum *restrict n, size_t places) {
size_t nrdx, places_rdx;
if (!places) return;
// Easy case with zero; set the scale.
if (BC_NUM_ZERO(n)) {
n->scale += places;
return;
}
// Grab these needed values; places_rdx is the rdx equivalent to places like
// rdx is to scale.
nrdx = BC_NUM_RDX_VAL(n);
places_rdx = BC_NUM_RDX(places + n->scale) - nrdx;
// This is the hard case. We need to expand the number, move the limbs, and
// set the limbs that were just cleared.
if (places_rdx) {
bc_num_expand(n, bc_vm_growSize(n->len, places_rdx));
memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len));
memset(n->num, 0, BC_NUM_SIZE(places_rdx));
}
// Finally, set scale and rdx.
BC_NUM_RDX_SET(n, nrdx + places_rdx);
n->scale += places;
n->len += places_rdx;
assert(BC_NUM_RDX_VAL(n) == BC_NUM_RDX(n->scale));
}
/**
* Retires (finishes) a multiplication or division operation.
*/
static void bc_num_retireMul(BcNum *restrict n, size_t scale,
bool neg1, bool neg2)
{
// Make sure scale is correct.
if (n->scale < scale) bc_num_extend(n, scale - n->scale);
else bc_num_truncate(n, n->scale - scale);
bc_num_clean(n);
// We need to ensure rdx is correct.
if (BC_NUM_NONZERO(n)) n->rdx = BC_NUM_NEG_VAL(n, !neg1 != !neg2);
}
/**
* Splits a number into two BcNum's. This is used in Karatsuba.
* @param n The number to split.
* @param idx The index to split at.
* @param a An out parameter; the low part of @a n.
* @param b An out parameter; the high part of @a n.
*/
static void bc_num_split(const BcNum *restrict n, size_t idx,
BcNum *restrict a, BcNum *restrict b)
{
// We want a and b to be clear.
assert(BC_NUM_ZERO(a));
assert(BC_NUM_ZERO(b));
// The usual case.
if (idx < n->len) {
// Set the fields first.
b->len = n->len - idx;
a->len = idx;
a->scale = b->scale = 0;
BC_NUM_RDX_SET(a, 0);
BC_NUM_RDX_SET(b, 0);
assert(a->cap >= a->len);
assert(b->cap >= b->len);
// Copy the arrays. This is not necessary for safety, but it is faster,
// for some reason.
memcpy(b->num, n->num + idx, BC_NUM_SIZE(b->len));
memcpy(a->num, n->num, BC_NUM_SIZE(idx));
bc_num_clean(b);
}
// If the index is weird, just skip the split.
else bc_num_copy(a, n);
bc_num_clean(a);
}
/**
* Copies a number into another, but shifts the rdx so that the result number
* only sees the integer part of the source number.
* @param n The number to copy.
* @param r The result number with a shifted rdx, len, and num.
*/
static void bc_num_shiftRdx(const BcNum *restrict n, BcNum *restrict r) {
size_t rdx = BC_NUM_RDX_VAL(n);
r->len = n->len - rdx;
r->cap = n->cap - rdx;
r->num = n->num + rdx;
BC_NUM_RDX_SET_NEG(r, 0, BC_NUM_NEG(n));
r->scale = 0;
}
/**
* Shifts a number so that all of the least significant limbs of the number are
* skipped. This must be undone by bc_num_unshiftZero().
* @param n The number to shift.
*/
static size_t bc_num_shiftZero(BcNum *restrict n) {
size_t i;
// If we don't have an integer, that is a problem, but it's also a bug
// because the caller should have set everything up right.
assert(!BC_NUM_RDX_VAL(n) || BC_NUM_ZERO(n));
for (i = 0; i < n->len && !n->num[i]; ++i);
n->len -= i;
n->num += i;
return i;
}
/**
* Undo the damage done by bc_num_unshiftZero(). This must be called like all
* cleanup functions: after a label used by setjmp() and longjmp().
* @param n The number to unshift.
* @param places_rdx The amount the number was originally shift.
*/
static void bc_num_unshiftZero(BcNum *restrict n, size_t places_rdx) {
n->len += places_rdx;
n->num -= places_rdx;
}
/**
* Shifts the digits right within a number by no more than BC_BASE_DIGS - 1.
* This is the final step on shifting numbers with the shift operators. It
* depends on the caller to shift the limbs properly because all it does is
* ensure that the rdx point is realigned to be between limbs.
* @param n The number to shift digits in.
* @param dig The number of places to shift right.
*/
static void bc_num_shift(BcNum *restrict n, BcBigDig dig) {
size_t i, len = n->len;
BcBigDig carry = 0, pow;
BcDig *ptr = n->num;
assert(dig < BC_BASE_DIGS);
// Figure out the parameters for division.
pow = bc_num_pow10[dig];
dig = bc_num_pow10[BC_BASE_DIGS - dig];
// Run a series of divisions and mods with carries across the entire number
// array. This effectively shifts everything over.
for (i = len - 1; i < len; --i) {
BcBigDig in, temp;
in = ((BcBigDig) ptr[i]);
temp = carry * dig;
carry = in % pow;
ptr[i] = ((BcDig) (in / pow)) + (BcDig) temp;
}
assert(!carry);
}
/**
* Shift a number left by a certain number of places. This is the workhorse of
* the left shift operator.
* @param n The number to shift left.
* @param places The amount of places to shift @a n left by.
*/
static void bc_num_shiftLeft(BcNum *restrict n, size_t places) {
BcBigDig dig;
size_t places_rdx;
bool shift;
if (!places) return;
// Make sure to grow the number if necessary.
if (places > n->scale) {
size_t size = bc_vm_growSize(BC_NUM_RDX(places - n->scale), n->len);
if (size > SIZE_MAX - 1) bc_err(BC_ERR_MATH_OVERFLOW);
}
// If zero, we can just set the scale and bail.
if (BC_NUM_ZERO(n)) {
if (n->scale >= places) n->scale -= places;
else n->scale = 0;
return;
}
// When I changed bc to have multiple digits per limb, this was the hardest
// code to change. This and shift right. Make sure you understand this
// before attempting anything.
// This is how many limbs we will shift.
dig = (BcBigDig) (places % BC_BASE_DIGS);
shift = (dig != 0);
// Convert places to a rdx value.
places_rdx = BC_NUM_RDX(places);
// If the number is not an integer, we need special care. The reason an
// integer doesn't is because left shift would only extend the integer,
// whereas a non-integer might have its fractional part eliminated or only
// partially eliminated.
if (n->scale) {
size_t nrdx = BC_NUM_RDX_VAL(n);
// If the number's rdx is bigger, that's the hard case.
if (nrdx >= places_rdx) {
size_t mod = n->scale % BC_BASE_DIGS, revdig;
// We want mod to be in the range [1, BC_BASE_DIGS], not
// [0, BC_BASE_DIGS).
mod = mod ? mod : BC_BASE_DIGS;
// We need to reverse dig to get the actual number of digits.
revdig = dig ? BC_BASE_DIGS - dig : 0;
// If the two overflow BC_BASE_DIGS, we need to move an extra place.
if (mod + revdig > BC_BASE_DIGS) places_rdx = 1;
else places_rdx = 0;
}
else places_rdx -= nrdx;
}
// If this is non-zero, we need an extra place, so expand, move, and set.
if (places_rdx) {
bc_num_expand(n, bc_vm_growSize(n->len, places_rdx));
memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len));
memset(n->num, 0, BC_NUM_SIZE(places_rdx));
n->len += places_rdx;
}
// Set the scale appropriately.
if (places > n->scale) {
n->scale = 0;
BC_NUM_RDX_SET(n, 0);
}
else {
n->scale -= places;
BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale));
}
// Finally, shift within limbs.
if (shift) bc_num_shift(n, BC_BASE_DIGS - dig);
bc_num_clean(n);
}
void bc_num_shiftRight(BcNum *restrict n, size_t places) {
BcBigDig dig;
size_t places_rdx, scale, scale_mod, int_len, expand;
bool shift;
if (!places) return;
// If zero, we can just set the scale and bail.
if (BC_NUM_ZERO(n)) {
n->scale += places;
bc_num_expand(n, BC_NUM_RDX(n->scale));
return;
}
// Amount within a limb we have to shift by.
dig = (BcBigDig) (places % BC_BASE_DIGS);
shift = (dig != 0);
scale = n->scale;
// Figure out how the scale is affected.
scale_mod = scale % BC_BASE_DIGS;
scale_mod = scale_mod ? scale_mod : BC_BASE_DIGS;
// We need to know the int length and rdx for places.
int_len = bc_num_int(n);
places_rdx = BC_NUM_RDX(places);
// If we are going to shift past a limb boundary or not, set accordingly.
if (scale_mod + dig > BC_BASE_DIGS) {
expand = places_rdx - 1;
places_rdx = 1;
}
else {
expand = places_rdx;
places_rdx = 0;
}
// Clamp expanding.
if (expand > int_len) expand -= int_len;
else expand = 0;
// Extend, expand, and zero.
bc_num_extend(n, places_rdx * BC_BASE_DIGS);
bc_num_expand(n, bc_vm_growSize(expand, n->len));
memset(n->num + n->len, 0, BC_NUM_SIZE(expand));
// Set the fields.
n->len += expand;
n->scale = 0;
BC_NUM_RDX_SET(n, 0);
// Finally, shift within limbs.
if (shift) bc_num_shift(n, dig);
n->scale = scale + places;
BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale));
bc_num_clean(n);
assert(BC_NUM_RDX_VAL(n) <= n->len && n->len <= n->cap);
assert(BC_NUM_RDX_VAL(n) == BC_NUM_RDX(n->scale));
}
/**
* Invert @a into @a b at the current scale.
* @param a The number to invert.
* @param b The return parameter. This must be preallocated.
* @param scale The current scale.
*/
static inline void bc_num_inv(BcNum *a, BcNum *b, size_t scale) {
assert(BC_NUM_NONZERO(a));
bc_num_div(&vm.one, a, b, scale);
}
/**
* Tests if a number is a integer with scale or not. Returns true if the number
* is not an integer. If it is, its integer shifted form is copied into the
* result parameter for use where only integers are allowed.
* @param n The integer to test and shift.
* @param r The number to store the shifted result into. This number should
* *not* be allocated.
* @return True if the number is a non-integer, false otherwise.
*/
static bool bc_num_nonInt(const BcNum *restrict n, BcNum *restrict r) {
bool zero;
size_t i, rdx = BC_NUM_RDX_VAL(n);
if (!rdx) {
memcpy(r, n, sizeof(BcNum));
return false;
}
zero = true;
for (i = 0; zero && i < rdx; ++i) zero = (n->num[i] == 0);
if (BC_ERR(!zero)) return true;
bc_num_shiftRdx(n, r);
return false;
}
#if BC_ENABLE_EXTRA_MATH
/**
* Execute common code for an operater that needs an integer for the second
* operand and return the integer operand as a BcBigDig.
* @param a The first operand.
* @param b The second operand.
* @param c The result operand.
* @return The second operand as a hardware integer.
*/
static BcBigDig bc_num_intop(const BcNum *a, const BcNum *b, BcNum *restrict c)
{
BcNum temp;
if (BC_ERR(bc_num_nonInt(b, &temp))) bc_err(BC_ERR_MATH_NON_INTEGER);
bc_num_copy(c, a);
return bc_num_bigdig(&temp);
}
#endif // BC_ENABLE_EXTRA_MATH
/**
* This is the actual implementation of add *and* subtract. Since this function
* doesn't need to use scale (per the bc spec), I am hijacking it to say whether
* it's doing an add or a subtract. And then I convert substraction to addition
* of negative second operand. This is a BcNumBinOp function.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
* @param sub Non-zero for a subtract, zero for an add.
*/
static void bc_num_as(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub) {
BcDig *ptr_c, *ptr_l, *ptr_r;
size_t i, min_rdx, max_rdx, diff, a_int, b_int, min_len, max_len, max_int;
size_t len_l, len_r, ardx, brdx;
bool b_neg, do_sub, do_rev_sub, carry, c_neg;
if (BC_NUM_ZERO(b)) {
bc_num_copy(c, a);
return;
}
if (BC_NUM_ZERO(a)) {
bc_num_copy(c, b);
c->rdx = BC_NUM_NEG_VAL(c, BC_NUM_NEG(b) != sub);
return;
}
// Invert sign of b if it is to be subtracted. This operation must
// precede the tests for any of the operands being zero.
b_neg = (BC_NUM_NEG(b) != sub);
// Figure out if we will actually add the numbers if their signs are equal
// or subtract.
do_sub = (BC_NUM_NEG(a) != b_neg);
a_int = bc_num_int(a);
b_int = bc_num_int(b);
max_int = BC_MAX(a_int, b_int);
// Figure out which number will have its last limbs copied (for addition) or
// subtracted (for subtraction).
ardx = BC_NUM_RDX_VAL(a);
brdx = BC_NUM_RDX_VAL(b);
min_rdx = BC_MIN(ardx, brdx);
max_rdx = BC_MAX(ardx, brdx);
diff = max_rdx - min_rdx;
max_len = max_int + max_rdx;
if (do_sub) {
// Check whether b has to be subtracted from a or a from b.
if (a_int != b_int) do_rev_sub = (a_int < b_int);
else if (ardx > brdx)
do_rev_sub = (bc_num_compare(a->num + diff, b->num, b->len) < 0);
else
do_rev_sub = (bc_num_compare(a->num, b->num + diff, a->len) <= 0);
}
else {
// The result array of the addition might come out one element
// longer than the bigger of the operand arrays.
max_len += 1;
do_rev_sub = (a_int < b_int);
}
assert(max_len <= c->cap);
// Cache values for simple code later.
if (do_rev_sub) {
ptr_l = b->num;
ptr_r = a->num;
len_l = b->len;
len_r = a->len;
}
else {
ptr_l = a->num;
ptr_r = b->num;
len_l = a->len;
len_r = b->len;
}
ptr_c = c->num;
carry = false;
// This is true if the numbers have a different number of limbs after the
// decimal point.
if (diff) {
// If the rdx values of the operands do not match, the result will
// have low end elements that are the positive or negative trailing
// elements of the operand with higher rdx value.
if ((ardx > brdx) != do_rev_sub) {
// !do_rev_sub && ardx > brdx || do_rev_sub && brdx > ardx
// The left operand has BcDig values that need to be copied,
// either from a or from b (in case of a reversed subtraction).
memcpy(ptr_c, ptr_l, BC_NUM_SIZE(diff));
ptr_l += diff;
len_l -= diff;
}
else {
// The right operand has BcDig values that need to be copied
// or subtracted from zero (in case of a subtraction).
if (do_sub) {
// do_sub (do_rev_sub && ardx > brdx ||
// !do_rev_sub && brdx > ardx)
for (i = 0; i < diff; i++)
ptr_c[i] = bc_num_subDigits(0, ptr_r[i], &carry);
}
else {
// !do_sub && brdx > ardx
memcpy(ptr_c, ptr_r, BC_NUM_SIZE(diff));
}
// Future code needs to ignore the limbs we just did.
ptr_r += diff;
len_r -= diff;
}
// The return value pointer needs to ignore what we just did.
ptr_c += diff;
}
// This is the length that can be directly added/subtracted.
min_len = BC_MIN(len_l, len_r);
// After dealing with possible low array elements that depend on only one
// operand above, the actual add or subtract can be performed as if the rdx
// of both operands was the same.
//
// Inlining takes care of eliminating constant zero arguments to
// addDigit/subDigit (checked in disassembly of resulting bc binary
// compiled with gcc and clang).
if (do_sub) {
// Actual subtraction.
for (i = 0; i < min_len; ++i)
ptr_c[i] = bc_num_subDigits(ptr_l[i], ptr_r[i], &carry);
// Finishing the limbs beyond the direct subtraction.
for (; i < len_l; ++i) ptr_c[i] = bc_num_subDigits(ptr_l[i], 0, &carry);
}
else {
// Actual addition.
for (i = 0; i < min_len; ++i)
ptr_c[i] = bc_num_addDigits(ptr_l[i], ptr_r[i], &carry);
// Finishing the limbs beyond the direct addition.
for (; i < len_l; ++i) ptr_c[i] = bc_num_addDigits(ptr_l[i], 0, &carry);
// Addition can create an extra limb. We take care of that here.
ptr_c[i] = bc_num_addDigits(0, 0, &carry);
}
assert(carry == false);
// The result has the same sign as a, unless the operation was a
// reverse subtraction (b - a).
c_neg = BC_NUM_NEG(a) != (do_sub && do_rev_sub);
BC_NUM_RDX_SET_NEG(c, max_rdx, c_neg);
c->len = max_len;
c->scale = BC_MAX(a->scale, b->scale);
bc_num_clean(c);
}
/**
* The simple multiplication that karatsuba dishes out to when the length of the
* numbers gets low enough. This doesn't use scale because it treats the
* operands as though they are integers.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
*/
static void bc_num_m_simp(const BcNum *a, const BcNum *b, BcNum *restrict c) {
size_t i, alen = a->len, blen = b->len, clen;
BcDig *ptr_a = a->num, *ptr_b = b->num, *ptr_c;
BcBigDig sum = 0, carry = 0;
assert(sizeof(sum) >= sizeof(BcDig) * 2);
assert(!BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b));
// Make sure c is big enough.
clen = bc_vm_growSize(alen, blen);
bc_num_expand(c, bc_vm_growSize(clen, 1));
// If we don't memset, then we might have uninitialized data use later.
ptr_c = c->num;
memset(ptr_c, 0, BC_NUM_SIZE(c->cap));
// This is the actual multiplication loop. It uses the lattice form of long
// multiplication (see the explanation on the web page at
// https://knilt.arcc.albany.edu/What_is_Lattice_Multiplication or the
// explanation at Wikipedia).
for (i = 0; i < clen; ++i) {
ssize_t sidx = (ssize_t) (i - blen + 1);
size_t j, k;
// These are the start indices.
j = (size_t) BC_MAX(0, sidx);
k = BC_MIN(i, blen - 1);
// On every iteration of this loop, a multiplication happens, then the
// sum is automatically calculated.
for (; j < alen && k < blen; ++j, --k) {
sum += ((BcBigDig) ptr_a[j]) * ((BcBigDig) ptr_b[k]);
if (sum >= ((BcBigDig) BC_BASE_POW) * BC_BASE_POW) {
carry += sum / BC_BASE_POW;
sum %= BC_BASE_POW;
}
}
// Calculate the carry.
if (sum >= BC_BASE_POW) {
carry += sum / BC_BASE_POW;
sum %= BC_BASE_POW;
}
// Store and set up for next iteration.
ptr_c[i] = (BcDig) sum;
assert(ptr_c[i] < BC_BASE_POW);
sum = carry;
carry = 0;
}
// This should always be true because there should be no carry on the last
// digit; multiplication never goes above the sum of both lengths.
assert(!sum);
c->len = clen;
}
/**
* Does a shifted add or subtract for Karatsuba below. This calls either
* bc_num_addArrays() or bc_num_subArrays().
* @param n An in/out parameter; the first operand and return parameter.
* @param a The second operand.
* @param shift The amount to shift @a n by when adding/subtracting.
* @param op The function to call, either bc_num_addArrays() or
* bc_num_subArrays().
*/
static void bc_num_shiftAddSub(BcNum *restrict n, const BcNum *restrict a,
size_t shift, BcNumShiftAddOp op)
{
assert(n->len >= shift + a->len);
assert(!BC_NUM_RDX_VAL(n) && !BC_NUM_RDX_VAL(a));
op(n->num + shift, a->num, a->len);
}
/**
* Implements the Karatsuba algorithm.
*/
static void bc_num_k(const BcNum *a, const BcNum *b, BcNum *restrict c) {
size_t max, max2, total;
BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp;
BcDig *digs, *dig_ptr;
BcNumShiftAddOp op;
bool aone = BC_NUM_ONE(a);
assert(BC_NUM_ZERO(c));
if (BC_NUM_ZERO(a) || BC_NUM_ZERO(b)) return;
if (aone || BC_NUM_ONE(b)) {
bc_num_copy(c, aone ? b : a);
if ((aone && BC_NUM_NEG(a)) || BC_NUM_NEG(b)) BC_NUM_NEG_TGL(c);
return;
}
// Shell out to the simple algorithm with certain conditions.
if (a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN) {
bc_num_m_simp(a, b, c);
return;
}
// We need to calculate the max size of the numbers that can result from the
// operations.
max = BC_MAX(a->len, b->len);
max = BC_MAX(max, BC_NUM_DEF_SIZE);
max2 = (max + 1) / 2;
// Calculate the space needed for all of the temporary allocations. We do
// this to just allocate once.
total = bc_vm_arraySize(BC_NUM_KARATSUBA_ALLOCS, max);
BC_SIG_LOCK;
// Allocate space for all of the temporaries.
digs = dig_ptr = bc_vm_malloc(BC_NUM_SIZE(total));
// Set up the temporaries.
bc_num_setup(&l1, dig_ptr, max);
dig_ptr += max;
bc_num_setup(&h1, dig_ptr, max);
dig_ptr += max;
bc_num_setup(&l2, dig_ptr, max);
dig_ptr += max;
bc_num_setup(&h2, dig_ptr, max);
dig_ptr += max;
bc_num_setup(&m1, dig_ptr, max);
dig_ptr += max;
bc_num_setup(&m2, dig_ptr, max);
// Some temporaries need the ability to grow, so we allocate them
// separately.
max = bc_vm_growSize(max, 1);
bc_num_init(&z0, max);
bc_num_init(&z1, max);
bc_num_init(&z2, max);
max = bc_vm_growSize(max, max) + 1;
bc_num_init(&temp, max);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// First, set up c.
bc_num_expand(c, max);
c->len = max;
memset(c->num, 0, BC_NUM_SIZE(c->len));
// Split the parameters.
bc_num_split(a, max2, &l1, &h1);
bc_num_split(b, max2, &l2, &h2);
// Do the subtraction.
bc_num_sub(&h1, &l1, &m1, 0);
bc_num_sub(&l2, &h2, &m2, 0);
// The if statements below are there for efficiency reasons. The best way to
// understand them is to understand the Karatsuba algorithm because now that
// the ollocations and splits are done, the algorithm is pretty
// straightforward.
if (BC_NUM_NONZERO(&h1) && BC_NUM_NONZERO(&h2)) {
assert(BC_NUM_RDX_VALID_NP(h1));
assert(BC_NUM_RDX_VALID_NP(h2));
bc_num_m(&h1, &h2, &z2, 0);
bc_num_clean(&z2);
bc_num_shiftAddSub(c, &z2, max2 * 2, bc_num_addArrays);
bc_num_shiftAddSub(c, &z2, max2, bc_num_addArrays);
}
if (BC_NUM_NONZERO(&l1) && BC_NUM_NONZERO(&l2)) {
assert(BC_NUM_RDX_VALID_NP(l1));
assert(BC_NUM_RDX_VALID_NP(l2));
bc_num_m(&l1, &l2, &z0, 0);
bc_num_clean(&z0);
bc_num_shiftAddSub(c, &z0, max2, bc_num_addArrays);
bc_num_shiftAddSub(c, &z0, 0, bc_num_addArrays);
}
if (BC_NUM_NONZERO(&m1) && BC_NUM_NONZERO(&m2)) {
assert(BC_NUM_RDX_VALID_NP(m1));
assert(BC_NUM_RDX_VALID_NP(m1));
bc_num_m(&m1, &m2, &z1, 0);
bc_num_clean(&z1);
op = (BC_NUM_NEG_NP(m1) != BC_NUM_NEG_NP(m2)) ?
bc_num_subArrays : bc_num_addArrays;
bc_num_shiftAddSub(c, &z1, max2, op);
}
err:
BC_SIG_MAYLOCK;
free(digs);
bc_num_free(&temp);
bc_num_free(&z2);
bc_num_free(&z1);
bc_num_free(&z0);
BC_LONGJMP_CONT;
}
/**
* Does checks for Karatsuba. It also changes things to ensure that the
* Karatsuba and simple multiplication can treat the numbers as integers. This
* is a BcNumBinOp function.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
* @param scale The current scale.
*/
static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) {
BcNum cpa, cpb;
size_t ascale, bscale, ardx, brdx, azero = 0, bzero = 0, zero, len, rscale;
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_zero(c);
ascale = a->scale;
bscale = b->scale;
// This sets the final scale according to the bc spec.
scale = BC_MAX(scale, ascale);
scale = BC_MAX(scale, bscale);
rscale = ascale + bscale;
scale = BC_MIN(rscale, scale);
// If this condition is true, we can use bc_num_mulArray(), which would be
// much faster.
if ((a->len == 1 || b->len == 1) && !a->rdx && !b->rdx) {
BcNum *operand;
BcBigDig dig;
// Set the correct operands.
if (a->len == 1) {
dig = (BcBigDig) a->num[0];
operand = b;
}
else {
dig = (BcBigDig) b->num[0];
operand = a;
}
bc_num_mulArray(operand, dig, c);
// Need to make sure the sign is correct.
if (BC_NUM_NONZERO(c))
c->rdx = BC_NUM_NEG_VAL(c, BC_NUM_NEG(a) != BC_NUM_NEG(b));
return;
}
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
BC_SIG_LOCK;
// We need copies because of all of the mutation needed to make Karatsuba
// think the numbers are integers.
bc_num_init(&cpa, a->len + BC_NUM_RDX_VAL(a));
bc_num_init(&cpb, b->len + BC_NUM_RDX_VAL(b));
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
bc_num_copy(&cpa, a);
bc_num_copy(&cpb, b);
assert(BC_NUM_RDX_VALID_NP(cpa));
assert(BC_NUM_RDX_VALID_NP(cpb));
BC_NUM_NEG_CLR_NP(cpa);
BC_NUM_NEG_CLR_NP(cpb);
assert(BC_NUM_RDX_VALID_NP(cpa));
assert(BC_NUM_RDX_VALID_NP(cpb));
// These are what makes them appear like integers.
ardx = BC_NUM_RDX_VAL_NP(cpa) * BC_BASE_DIGS;
bc_num_shiftLeft(&cpa, ardx);
brdx = BC_NUM_RDX_VAL_NP(cpb) * BC_BASE_DIGS;
bc_num_shiftLeft(&cpb, brdx);
// We need to reset the jump here because azero and bzero are used in the
// cleanup, and local variables are not guaranteed to be the same after a
// jump.
BC_SIG_LOCK;
BC_UNSETJMP;
// We want to ignore zero limbs.
azero = bc_num_shiftZero(&cpa);
bzero = bc_num_shiftZero(&cpb);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
bc_num_clean(&cpa);
bc_num_clean(&cpb);
bc_num_k(&cpa, &cpb, c);
// The return parameter needs to have its scale set. This is the start. It
// also needs to be shifted by the same amount as a and b have limbs after
// the decimal point.
zero = bc_vm_growSize(azero, bzero);
len = bc_vm_growSize(c->len, zero);
bc_num_expand(c, len);
// Shift c based on the limbs after the decimal point in a and b.
bc_num_shiftLeft(c, (len - c->len) * BC_BASE_DIGS);
bc_num_shiftRight(c, ardx + brdx);
bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b));
err:
BC_SIG_MAYLOCK;
bc_num_unshiftZero(&cpb, bzero);
bc_num_free(&cpb);
bc_num_unshiftZero(&cpa, azero);
bc_num_free(&cpa);
BC_LONGJMP_CONT;
}
/**
* Returns true if the BcDig array has non-zero limbs, false otherwise.
* @param a The array to test.
* @param len The length of the array.
* @return True if @a has any non-zero limbs, false otherwise.
*/
static bool bc_num_nonZeroDig(BcDig *restrict a, size_t len) {
size_t i;
bool nonzero = false;
for (i = len - 1; !nonzero && i < len; --i) nonzero = (a[i] != 0);
return nonzero;
}
/**
* Compares a BcDig array against a BcNum. This is especially suited for
* division. Returns >0 if @a a is greater than @a b, <0 if it is less, and =0
* if they are equal.
* @param a The array.
* @param b The number.
* @param len The length to assume the arrays are. This is always less than the
* actual length because of how this is implemented.
*/
static ssize_t bc_num_divCmp(const BcDig *a, const BcNum *b, size_t len) {
ssize_t cmp;
if (b->len > len && a[len]) cmp = bc_num_compare(a, b->num, len + 1);
else if (b->len <= len) {
if (a[len]) cmp = 1;
else cmp = bc_num_compare(a, b->num, len);
}
else cmp = -1;
return cmp;
}
/**
* Extends the two operands of a division by BC_BASE_DIGS minus the number of
* digits in the divisor estimate. In other words, it is shifting the numbers in
* order to force the divisor estimate to fill the limb.
* @param a The first operand.
* @param b The second operand.
* @param divisor The divisor estimate.
*/
static void bc_num_divExtend(BcNum *restrict a, BcNum *restrict b,
BcBigDig divisor)
{
size_t pow;
assert(divisor < BC_BASE_POW);
pow = BC_BASE_DIGS - bc_num_log10((size_t) divisor);
bc_num_shiftLeft(a, pow);
bc_num_shiftLeft(b, pow);
}
/**
* Actually does division. This is a rewrite of my original code by Stefan Esser
* from FreeBSD.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
* @param scale The current scale.
*/
static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b,
BcNum *restrict c, size_t scale)
{
BcBigDig divisor;
size_t len, end, i, rdx;
BcNum cpb;
bool nonzero = false;
assert(b->len < a->len);
len = b->len;
end = a->len - len;
assert(len >= 1);
// This is a final time to make sure c is big enough and that its array is
// properly zeroed.
bc_num_expand(c, a->len);
memset(c->num, 0, c->cap * sizeof(BcDig));
// Setup.
BC_NUM_RDX_SET(c, BC_NUM_RDX_VAL(a));
c->scale = a->scale;
c->len = a->len;
// This is pulling the most significant limb of b in order to establish a
// good "estimate" for the actual divisor.
divisor = (BcBigDig) b->num[len - 1];
// The entire bit of code in this if statement is to tighten the estimate of
// the divisor. The condition asks if b has any other non-zero limbs.
if (len > 1 && bc_num_nonZeroDig(b->num, len - 1)) {
// This takes a little bit of understanding. The "10*BC_BASE_DIGS/6+1"
// results in either 16 for 64-bit 9-digit limbs or 7 for 32-bit 4-digit
// limbs. Then it shifts a 1 by that many, which in both cases, puts the
// result above *half* of the max value a limb can store. Basically,
// this quickly calculates if the divisor is greater than half the max
// of a limb.
nonzero = (divisor > 1 << ((10 * BC_BASE_DIGS) / 6 + 1));
// If the divisor is *not* greater than half the limb...
if (!nonzero) {
// Extend the parameters by the number of missing digits in the
// divisor.
bc_num_divExtend(a, b, divisor);
// Check bc_num_d(). In there, we grow a again and again. We do it
// again here; we *always* want to be sure it is big enough.
len = BC_MAX(a->len, b->len);
bc_num_expand(a, len + 1);
// Make a have a zero most significant limb to match the len.
if (len + 1 > a->len) a->len = len + 1;
// Grab the new divisor estimate, new because the shift has made it
// different.
len = b->len;
end = a->len - len;
divisor = (BcBigDig) b->num[len - 1];
nonzero = bc_num_nonZeroDig(b->num, len - 1);
}
}
// If b has other nonzero limbs, we want the divisor to be one higher, so
// that it is an upper bound.
divisor += nonzero;
// Make sure c can fit the new length.
bc_num_expand(c, a->len);
memset(c->num, 0, BC_NUM_SIZE(c->cap));
assert(c->scale >= scale);
rdx = BC_NUM_RDX_VAL(c) - BC_NUM_RDX(scale);
BC_SIG_LOCK;
bc_num_init(&cpb, len + 1);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// This is the actual division loop.
for (i = end - 1; i < end && i >= rdx && BC_NUM_NONZERO(a); --i) {
ssize_t cmp;
BcDig *n;
BcBigDig result;
n = a->num + i;
assert(n >= a->num);
result = 0;
cmp = bc_num_divCmp(n, b, len);
// This is true if n is greater than b, which means that division can
// proceed, so this inner loop is the part that implements one instance
// of the division.
while (cmp >= 0) {
BcBigDig n1, dividend, quotient;
// These should be named obviously enough. Just imagine that it's a
// division of one limb. Because that's what it is.
n1 = (BcBigDig) n[len];
dividend = n1 * BC_BASE_POW + (BcBigDig) n[len - 1];
quotient = (dividend / divisor);
// If this is true, then we can just subtract. Remember: setting
// quotient to 1 is not bad because we already know that n is
// greater than b.
if (quotient <= 1) {
quotient = 1;
bc_num_subArrays(n, b->num, len);
}
else {
assert(quotient <= BC_BASE_POW);
// We need to multiply and subtract for a quotient above 1.
bc_num_mulArray(b, (BcBigDig) quotient, &cpb);
bc_num_subArrays(n, cpb.num, cpb.len);
}
// The result is the *real* quotient, by the way, but it might take
// multiple trips around this loop to get it.
result += quotient;
assert(result <= BC_BASE_POW);
// And here's why it might take multiple trips: n might *still* be
// greater than b. So we have to loop again. That's what this is
// setting up for: the condition of the while loop.
if (nonzero) cmp = bc_num_divCmp(n, b, len);
else cmp = -1;
}
assert(result < BC_BASE_POW);
// Store the actual limb quotient.
c->num[i] = (BcDig) result;
}
err:
BC_SIG_MAYLOCK;
bc_num_free(&cpb);
BC_LONGJMP_CONT;
}
/**
* Implements division. This is a BcNumBinOp function.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
* @param scale The current scale.
*/
static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) {
size_t len, cpardx;
BcNum cpa, cpb;
if (BC_NUM_ZERO(b)) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO);
if (BC_NUM_ZERO(a)) {
bc_num_setToZero(c, scale);
return;
}
if (BC_NUM_ONE(b)) {
bc_num_copy(c, a);
bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b));
return;
}
// If this is true, we can use bc_num_divArray(), which would be faster.
if (!BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b) && b->len == 1 && !scale) {
BcBigDig rem;
bc_num_divArray(a, (BcBigDig) b->num[0], c, &rem);
bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b));
return;
}
len = bc_num_divReq(a, b, scale);
BC_SIG_LOCK;
// Initialize copies of the parameters. We want the length of the first
// operand copy to be as big as the result because of the way the division
// is implemented.
bc_num_init(&cpa, len);
bc_num_copy(&cpa, a);
bc_num_createCopy(&cpb, b);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
len = b->len;
// Like the above comment, we want the copy of the first parameter to be
// larger than the second parameter.
if (len > cpa.len) {
bc_num_expand(&cpa, bc_vm_growSize(len, 2));
bc_num_extend(&cpa, (len - cpa.len) * BC_BASE_DIGS);
}
cpardx = BC_NUM_RDX_VAL_NP(cpa);
cpa.scale = cpardx * BC_BASE_DIGS;
// This is just setting up the scale in preparation for the division.
bc_num_extend(&cpa, b->scale);
cpardx = BC_NUM_RDX_VAL_NP(cpa) - BC_NUM_RDX(b->scale);
BC_NUM_RDX_SET_NP(cpa, cpardx);
cpa.scale = cpardx * BC_BASE_DIGS;
// Once again, just setting things up, this time to match scale.
if (scale > cpa.scale) {
bc_num_extend(&cpa, scale);
cpardx = BC_NUM_RDX_VAL_NP(cpa);
cpa.scale = cpardx * BC_BASE_DIGS;
}
// Grow if necessary.
if (cpa.cap == cpa.len) bc_num_expand(&cpa, bc_vm_growSize(cpa.len, 1));
// We want an extra zero in front to make things simpler.
cpa.num[cpa.len++] = 0;
// Still setting things up. Why all of these things are needed is not
// something that can be easily explained, but it has to do with making the
// actual algorithm easier to understand because it can assume a lot of
// things. Thus, you should view all of this setup code as establishing
// assumptions for bc_num_d_long(), where the actual division happens.
if (cpardx == cpa.len) cpa.len = bc_num_nonZeroLen(&cpa);
if (BC_NUM_RDX_VAL_NP(cpb) == cpb.len) cpb.len = bc_num_nonZeroLen(&cpb);
cpb.scale = 0;
BC_NUM_RDX_SET_NP(cpb, 0);
bc_num_d_long(&cpa, &cpb, c, scale);
bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b));
err:
BC_SIG_MAYLOCK;
bc_num_free(&cpb);
bc_num_free(&cpa);
BC_LONGJMP_CONT;
}
/**
* Implements divmod. This is the actual modulus function; since modulus
* requires a division anyway, this returns the quotient and modulus. Either can
* be thrown out as desired.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter for the quotient.
* @param d The return parameter for the modulus.
* @param scale The current scale.
* @param ts The scale that the operation should be done to. Yes, it's not
* necessarily the same as scale, per the bc spec.
*/
static void bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c,
BcNum *restrict d, size_t scale, size_t ts)
{
BcNum temp;
bool neg;
if (BC_NUM_ZERO(b)) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO);
if (BC_NUM_ZERO(a)) {
bc_num_setToZero(c, ts);
bc_num_setToZero(d, ts);
return;
}
BC_SIG_LOCK;
bc_num_init(&temp, d->cap);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// Division.
bc_num_d(a, b, c, scale);
// We want an extra digit so we can safely truncate.
if (scale) scale = ts + 1;
assert(BC_NUM_RDX_VALID(c));
assert(BC_NUM_RDX_VALID(b));
// Implement the rest of the (a - (a / b) * b) formula.
bc_num_m(c, b, &temp, scale);
bc_num_sub(a, &temp, d, scale);
// Extend if necessary.
if (ts > d->scale && BC_NUM_NONZERO(d)) bc_num_extend(d, ts - d->scale);
neg = BC_NUM_NEG(d);
bc_num_retireMul(d, ts, BC_NUM_NEG(a), BC_NUM_NEG(b));
d->rdx = BC_NUM_NEG_VAL(d, BC_NUM_NONZERO(d) ? neg : false);
err:
BC_SIG_MAYLOCK;
bc_num_free(&temp);
BC_LONGJMP_CONT;
}
/**
* Implements modulus/remainder. (Yes, I know they are different, but not in the
* context of bc.) This is a BcNumBinOp function.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
* @param scale The current scale.
*/
static void bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) {
BcNum c1;
size_t ts;
ts = bc_vm_growSize(scale, b->scale);
ts = BC_MAX(ts, a->scale);
BC_SIG_LOCK;
// Need a temp for the quotient.
bc_num_init(&c1, bc_num_mulReq(a, b, ts));
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
bc_num_r(a, b, &c1, c, scale, ts);
err:
BC_SIG_MAYLOCK;
bc_num_free(&c1);
BC_LONGJMP_CONT;
}
/**
* Implements power (exponentiation). This is a BcNumBinOp function.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
* @param scale The current scale.
*/
static void bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) {
BcNum copy, btemp;
BcBigDig exp;
size_t powrdx, resrdx;
bool neg;
if (BC_ERR(bc_num_nonInt(b, &btemp))) bc_err(BC_ERR_MATH_NON_INTEGER);
if (BC_NUM_ZERO(&btemp)) {
bc_num_one(c);
return;
}
if (BC_NUM_ZERO(a)) {
if (BC_NUM_NEG_NP(btemp)) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO);
bc_num_setToZero(c, scale);
return;
}
if (BC_NUM_ONE(&btemp)) {
if (!BC_NUM_NEG_NP(btemp)) bc_num_copy(c, a);
else bc_num_inv(a, c, scale);
return;
}
neg = BC_NUM_NEG_NP(btemp);
BC_NUM_NEG_CLR_NP(btemp);
exp = bc_num_bigdig(&btemp);
BC_SIG_LOCK;
bc_num_createCopy(©, a);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// If this is true, then we do not have to do a division, and we need to
// set scale accordingly.
if (!neg) {
size_t max = BC_MAX(scale, a->scale), scalepow;
scalepow = bc_num_mulOverflow(a->scale, exp);
scale = BC_MIN(scalepow, max);
}
// This is only implementing the first exponentiation by squaring, until it
// reaches the first time where the square is actually used.
for (powrdx = a->scale; !(exp & 1); exp >>= 1) {
powrdx <<= 1;
assert(BC_NUM_RDX_VALID_NP(copy));
bc_num_mul(©, ©, ©, powrdx);
}
// Make c a copy of copy for the purpose of saving the squares that should
// be saved.
bc_num_copy(c, ©);
resrdx = powrdx;
// Now finish the exponentiation by squaring, this time saving the squares
// as necessary.
while (exp >>= 1) {
powrdx <<= 1;
assert(BC_NUM_RDX_VALID_NP(copy));
bc_num_mul(©, ©, ©, powrdx);
// If this is true, we want to save that particular square. This does
// that by multiplying c with copy.
if (exp & 1) {
resrdx += powrdx;
assert(BC_NUM_RDX_VALID(c));
assert(BC_NUM_RDX_VALID_NP(copy));
bc_num_mul(c, ©, c, resrdx);
}
}
// Invert if necessary.
if (neg) bc_num_inv(c, c, scale);
// Truncate if necessary.
if (c->scale > scale) bc_num_truncate(c, c->scale - scale);
bc_num_clean(c);
err:
BC_SIG_MAYLOCK;
bc_num_free(©);
BC_LONGJMP_CONT;
}
#if BC_ENABLE_EXTRA_MATH
/**
* Implements the places operator. This is a BcNumBinOp function.
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
* @param scale The current scale.
*/
static void bc_num_place(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) {
BcBigDig val;
BC_UNUSED(scale);
val = bc_num_intop(a, b, c);
// Just truncate or extend as appropriate.
if (val < c->scale) bc_num_truncate(c, c->scale - val);
else if (val > c->scale) bc_num_extend(c, val - c->scale);
}
/**
* Implements the left shift operator. This is a BcNumBinOp function.
*/
static void bc_num_left(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) {
BcBigDig val;
BC_UNUSED(scale);
val = bc_num_intop(a, b, c);
bc_num_shiftLeft(c, (size_t) val);
}
/**
* Implements the right shift operator. This is a BcNumBinOp function.
*/
static void bc_num_right(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) {
BcBigDig val;
BC_UNUSED(scale);
val = bc_num_intop(a, b, c);
if (BC_NUM_ZERO(c)) return;
bc_num_shiftRight(c, (size_t) val);
}
#endif // BC_ENABLE_EXTRA_MATH
/**
* Prepares for, and calls, a binary operator function. This is probably the
* most important function in the entire file because it establishes assumptions
* that make the rest of the code so easy. Those assumptions include:
*
* - a is not the same pointer as c.
* - b is not the same pointer as c.
* - there is enough room in c for the result.
*
* Without these, this whole function would basically have to be duplicated for
* *all* binary operators.
*
* @param a The first operand.
* @param b The second operand.
* @param c The return parameter.
* @param scale The current scale.
* @param req The number of limbs needed to fit the result.
*/
static void bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale,
BcNumBinOp op, size_t req)
{
BcNum *ptr_a, *ptr_b, num2;
bool init = false;
assert(a != NULL && b != NULL && c != NULL && op != NULL);
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
BC_SIG_LOCK;
// Reallocate if c == a.
if (c == a) {
ptr_a = &num2;
memcpy(ptr_a, c, sizeof(BcNum));
init = true;
}
else {
ptr_a = a;
}
// Also reallocate if c == b.
if (c == b) {
ptr_b = &num2;
if (c != a) {
memcpy(ptr_b, c, sizeof(BcNum));
init = true;
}
}
else {
ptr_b = b;
}
// Actually reallocate. If we don't reallocate, we want to expand at the
// very least.
if (init) {
bc_num_init(c, req);
// Must prepare for cleanup. We want this here so that locals that got
// set stay set since a longjmp() is not guaranteed to preserve locals.
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
}
else {
BC_SIG_UNLOCK;
bc_num_expand(c, req);
}
// It is okay for a and b to be the same. If a binary operator function does
// need them to be different, the binary operator function is responsible
// for that.
// Call the actual binary operator function.
op(ptr_a, ptr_b, c, scale);
assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c));
assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len);
assert(BC_NUM_RDX_VALID(c));
assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len);
err:
// Cleanup only needed if we initialized c to a new number.
if (init) {
BC_SIG_MAYLOCK;
bc_num_free(&num2);
BC_LONGJMP_CONT;
}
}
#if !defined(NDEBUG) || BC_ENABLE_LIBRARY
/**
* Tests a number string for validity. This function has a history; I originally
* wrote it because I did not trust my parser. Over time, however, I came to
* trust it, so I was able to relegate this function to debug builds only, and I
* used it in assert()'s. But then I created the library, and well, I can't
* trust users, so I reused this for yelling at users.
* @param val The string to check to see if it's a valid number string.
* @return True if the string is a valid number string, false otherwise.
*/
bool bc_num_strValid(const char *restrict val) {
bool radix = false;
size_t i, len = strlen(val);
// Notice that I don't check if there is a negative sign. That is not part
// of a valid number, except in the library. The library-specific code takes
// care of that part.
// Nothing in the string is okay.
if (!len) return true;
// Loop through the characters.
for (i = 0; i < len; ++i) {
BcDig c = val[i];
// If we have found a radix point...
if (c == '.') {
// We don't allow two radices.
if (radix) return false;
radix = true;
continue;
}
// We only allow digits and uppercase letters.
if (!(isdigit(c) || isupper(c))) return false;
}
return true;
}
#endif // !defined(NDEBUG) || BC_ENABLE_LIBRARY
/**
* Parses one character and returns the digit that corresponds to that
* character according to the base.
* @param c The character to parse.
* @param base The base.
* @return The character as a digit.
*/
static BcBigDig bc_num_parseChar(char c, size_t base) {
assert(isupper(c) || isdigit(c));
// If a letter...
if (isupper(c)) {
// This returns the digit that directly corresponds with the letter.
c = BC_NUM_NUM_LETTER(c);
// If the digit is greater than the base, we clamp.
c = ((size_t) c) >= base ? (char) base - 1 : c;
}
// Straight convert the digit to a number.
else c -= '0';
return (BcBigDig) (uchar) c;
}
/**
* Parses a string as a decimal number. This is separate because it's going to
* be the most used, and it can be heavily optimized for decimal only.
* @param n The number to parse into and return. Must be preallocated.
* @param val The string to parse.
*/
static void bc_num_parseDecimal(BcNum *restrict n, const char *restrict val) {
size_t len, i, temp, mod;
const char *ptr;
bool zero = true, rdx;
// Eat leading zeroes.
for (i = 0; val[i] == '0'; ++i);
val += i;
assert(!val[0] || isalnum(val[0]) || val[0] == '.');
// All 0's. We can just return, since this procedure expects a virgin
// (already 0) BcNum.
if (!val[0]) return;
// The length of the string is the length of the number, except it might be
// one bigger because of a decimal point.
len = strlen(val);
// Find the location of the decimal point.
ptr = strchr(val, '.');
rdx = (ptr != NULL);
// We eat leading zeroes again. These leading zeroes are different because
// they will come after the decimal point if they exist, and since that's
// the case, they must be preserved.
for (i = 0; i < len && (zero = (val[i] == '0' || val[i] == '.')); ++i);
// Set the scale of the number based on the location of the decimal point.
// The casts to uintptr_t is to ensure that bc does not hit undefined
// behavior when doing math on the values.
n->scale = (size_t) (rdx * (((uintptr_t) (val + len)) -
(((uintptr_t) ptr) + 1)));
// Set rdx.
BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale));
// Calculate length. First, the length of the integer, then the number of
// digits in the last limb, then the length.
i = len - (ptr == val ? 0 : i) - rdx;
temp = BC_NUM_ROUND_POW(i);
mod = n->scale % BC_BASE_DIGS;
i = mod ? BC_BASE_DIGS - mod : 0;
n->len = ((temp + i) / BC_BASE_DIGS);
// Expand and zero.
bc_num_expand(n, n->len);
memset(n->num, 0, BC_NUM_SIZE(n->len));
if (zero) {
// I think I can set rdx directly to zero here because n should be a
// new number with sign set to false.
n->len = n->rdx = 0;
}
else {
// There is actually stuff to parse if we make it here. Yay...
BcBigDig exp, pow;
assert(i <= BC_NUM_BIGDIG_MAX);
// The exponent and power.
exp = (BcBigDig) i;
pow = bc_num_pow10[exp];
// Parse loop. We parse backwards because numbers are stored little
// endian.
for (i = len - 1; i < len; --i, ++exp) {
char c = val[i];
// Skip the decimal point.
if (c == '.') exp -= 1;
else {
// The index of the limb.
size_t idx = exp / BC_BASE_DIGS;
// Clamp for the base.
if (isupper(c)) c = '9';
// Add the digit to the limb.
n->num[idx] += (((BcBigDig) c) - '0') * pow;
// Adjust the power and exponent.
if ((exp + 1) % BC_BASE_DIGS == 0) pow = 1;
else pow *= BC_BASE;
}
}
}
}
/**
* Parse a number in any base (besides decimal).
* @param n The number to parse into and return. Must be preallocated.
* @param val The string to parse.
* @param base The base to parse as.
*/
static void bc_num_parseBase(BcNum *restrict n, const char *restrict val,
BcBigDig base)
{
BcNum temp, mult1, mult2, result1, result2, *m1, *m2, *ptr;
char c = 0;
bool zero = true;
BcBigDig v;
size_t i, digs, len = strlen(val);
// If zero, just return because the number should be virgin (already 0).
for (i = 0; zero && i < len; ++i) zero = (val[i] == '.' || val[i] == '0');
if (zero) return;
BC_SIG_LOCK;
bc_num_init(&temp, BC_NUM_BIGDIG_LOG10);
bc_num_init(&mult1, BC_NUM_BIGDIG_LOG10);
BC_SETJMP_LOCKED(int_err);
BC_SIG_UNLOCK;
// We split parsing into parsing the integer and parsing the fractional
// part.
// Parse the integer part. This is the easy part because we just multiply
// the number by the base, then add the digit.
for (i = 0; i < len && (c = val[i]) && c != '.'; ++i) {
// Convert the character to a digit.
v = bc_num_parseChar(c, base);
// Multiply the number.
bc_num_mulArray(n, base, &mult1);
// Convert the digit to a number and add.
bc_num_bigdig2num(&temp, v);
bc_num_add(&mult1, &temp, n, 0);
}
// If this condition is true, then we are done. We still need to do cleanup
// though.
if (i == len && !val[i]) goto int_err;
// If we get here, we *must* be at the radix point.
assert(val[i] == '.');
BC_SIG_LOCK;
// Unset the jump to reset in for these new initializations.
BC_UNSETJMP;
bc_num_init(&mult2, BC_NUM_BIGDIG_LOG10);
bc_num_init(&result1, BC_NUM_DEF_SIZE);
bc_num_init(&result2, BC_NUM_DEF_SIZE);
bc_num_one(&mult1);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// Pointers for easy switching.
m1 = &mult1;
m2 = &mult2;
// Parse the fractional part. This is the hard part.
for (i += 1, digs = 0; i < len && (c = val[i]); ++i, ++digs) {
size_t rdx;
// Convert the character to a digit.
v = bc_num_parseChar(c, base);
// We keep growing result2 according to the base because the more digits
// after the radix, the more significant the digits close to the radix
// should be.
bc_num_mulArray(&result1, base, &result2);
// Convert the digit to a number.
bc_num_bigdig2num(&temp, v);
// Add the digit into the fraction part.
bc_num_add(&result2, &temp, &result1, 0);
// Keep growing m1 and m2 for use after the loop.
bc_num_mulArray(m1, base, m2);
rdx = BC_NUM_RDX_VAL(m2);
if (m2->len < rdx) m2->len = rdx;
// Switch.
ptr = m1;
m1 = m2;
m2 = ptr;
}
// This one cannot be a divide by 0 because mult starts out at 1, then is
// multiplied by base, and base cannot be 0, so mult cannot be 0. And this
// is the reason we keep growing m1 and m2; this division is what converts
// the parsed fractional part from an integer to a fractional part.
bc_num_div(&result1, m1, &result2, digs * 2);
// Pretruncate.
bc_num_truncate(&result2, digs);
// The final add of the integer part to the fractional part.
bc_num_add(n, &result2, n, digs);
// Basic cleanup.
if (BC_NUM_NONZERO(n)) {
if (n->scale < digs) bc_num_extend(n, digs - n->scale);
}
else bc_num_zero(n);
err:
BC_SIG_MAYLOCK;
bc_num_free(&result2);
bc_num_free(&result1);
bc_num_free(&mult2);
int_err:
BC_SIG_MAYLOCK;
bc_num_free(&mult1);
bc_num_free(&temp);
BC_LONGJMP_CONT;
}
/**
* Prints a backslash+newline combo if the number of characters needs it. This
* is really a convenience function.
*/
static inline void bc_num_printNewline(void) {
#if !BC_ENABLE_LIBRARY
- if (vm.nchars >= vm.line_len - 1) {
+ if (vm.nchars >= vm.line_len - 1 && vm.line_len) {
bc_vm_putchar('\\', bc_flush_none);
bc_vm_putchar('\n', bc_flush_err);
}
#endif // !BC_ENABLE_LIBRARY
}
/**
* Prints a character after a backslash+newline, if needed.
* @param c The character to print.
* @param bslash Whether to print a backslash+newline.
*/
static void bc_num_putchar(int c, bool bslash) {
if (c != '\n' && bslash) bc_num_printNewline();
bc_vm_putchar(c, bc_flush_save);
}
#if !BC_ENABLE_LIBRARY
/**
* Prints a character for a number's digit. This is for printing for dc's P
* command. This function does not need to worry about radix points. This is a
* BcNumDigitOp.
* @param n The "digit" to print.
* @param len The "length" of the digit, or number of characters that will
* need to be printed for the digit.
* @param rdx True if a decimal (radix) point should be printed.
* @param bslash True if a backslash+newline should be printed if the character
* limit for the line is reached, false otherwise.
*/
static void bc_num_printChar(size_t n, size_t len, bool rdx, bool bslash) {
BC_UNUSED(rdx);
BC_UNUSED(len);
BC_UNUSED(bslash);
assert(len == 1);
bc_vm_putchar((uchar) n, bc_flush_save);
}
#endif // !BC_ENABLE_LIBRARY
/**
* Prints a series of characters for large bases. This is for printing in bases
* above hexadecimal. This is a BcNumDigitOp.
* @param n The "digit" to print.
* @param len The "length" of the digit, or number of characters that will
* need to be printed for the digit.
* @param rdx True if a decimal (radix) point should be printed.
* @param bslash True if a backslash+newline should be printed if the character
* limit for the line is reached, false otherwise.
*/
static void bc_num_printDigits(size_t n, size_t len, bool rdx, bool bslash) {
size_t exp, pow;
// If needed, print the radix; otherwise, print a space to separate digits.
bc_num_putchar(rdx ? '.' : ' ', true);
// Calculate the exponent and power.
for (exp = 0, pow = 1; exp < len - 1; ++exp, pow *= BC_BASE);
// Print each character individually.
for (exp = 0; exp < len; pow /= BC_BASE, ++exp) {
// The individual subdigit.
size_t dig = n / pow;
// Take the subdigit away.
n -= dig * pow;
// Print the subdigit.
bc_num_putchar(((uchar) dig) + '0', bslash || exp != len - 1);
}
}
/**
* Prints a character for a number's digit. This is for printing in bases for
* hexadecimal and below because they always print only one character at a time.
* This is a BcNumDigitOp.
* @param n The "digit" to print.
* @param len The "length" of the digit, or number of characters that will
* need to be printed for the digit.
* @param rdx True if a decimal (radix) point should be printed.
* @param bslash True if a backslash+newline should be printed if the character
* limit for the line is reached, false otherwise.
*/
static void bc_num_printHex(size_t n, size_t len, bool rdx, bool bslash) {
BC_UNUSED(len);
BC_UNUSED(bslash);
assert(len == 1);
if (rdx) bc_num_putchar('.', true);
bc_num_putchar(bc_num_hex_digits[n], bslash);
}
/**
* Prints a decimal number. This is specially written for optimization since
* this will be used the most and because bc's numbers are already in decimal.
* @param n The number to print.
* @param newline Whether to print backslash+newlines on long enough lines.
*/
static void bc_num_printDecimal(const BcNum *restrict n, bool newline) {
size_t i, j, rdx = BC_NUM_RDX_VAL(n);
bool zero = true;
size_t buffer[BC_BASE_DIGS];
- // Print the sign.
- if (BC_NUM_NEG(n)) bc_num_putchar('-', true);
-
// Print loop.
for (i = n->len - 1; i < n->len; --i) {
BcDig n9 = n->num[i];
size_t temp;
bool irdx = (i == rdx - 1);
// Calculate the number of digits in the limb.
zero = (zero & !irdx);
temp = n->scale % BC_BASE_DIGS;
temp = i || !temp ? 0 : BC_BASE_DIGS - temp;
memset(buffer, 0, BC_BASE_DIGS * sizeof(size_t));
// Fill the buffer with individual digits.
for (j = 0; n9 && j < BC_BASE_DIGS; ++j) {
buffer[j] = ((size_t) n9) % BC_BASE;
n9 /= BC_BASE;
}
// Print the digits in the buffer.
for (j = BC_BASE_DIGS - 1; j < BC_BASE_DIGS && j >= temp; --j) {
// Figure out whether to print the decimal point.
bool print_rdx = (irdx & (j == BC_BASE_DIGS - 1));
// The zero variable helps us skip leading zero digits in the limb.
zero = (zero && buffer[j] == 0);
if (!zero) {
// While the first three arguments should be self-explanatory,
// the last needs explaining. I don't want to print a newline
// when the last digit to be printed could take the place of the
// backslash rather than being pushed, as a single character, to
// the next line. That's what that last argument does for bc.
bc_num_printHex(buffer[j], 1, print_rdx,
!newline || (j > temp || i != 0));
}
}
}
}
#if BC_ENABLE_EXTRA_MATH
/**
* Prints a number in scientific or engineering format. When doing this, we are
* always printing in decimal.
* @param n The number to print.
* @param eng True if we are in engineering mode.
* @param newline Whether to print backslash+newlines on long enough lines.
*/
static void bc_num_printExponent(const BcNum *restrict n,
bool eng, bool newline)
{
size_t places, mod, nrdx = BC_NUM_RDX_VAL(n);
bool neg = (n->len <= nrdx);
BcNum temp, exp;
BcDig digs[BC_NUM_BIGDIG_LOG10];
BC_SIG_LOCK;
bc_num_createCopy(&temp, n);
BC_SETJMP_LOCKED(exit);
BC_SIG_UNLOCK;
// We need to calculate the exponents, and they change based on whether the
// number is all fractional or not, obviously.
if (neg) {
// Figure out how many limbs after the decimal point is zero.
size_t i, idx = bc_num_nonZeroLen(n) - 1;
places = 1;
// Figure out how much in the last limb is zero.
for (i = BC_BASE_DIGS - 1; i < BC_BASE_DIGS; --i) {
if (bc_num_pow10[i] > (BcBigDig) n->num[idx]) places += 1;
else break;
}
// Calculate the combination of zero limbs and zero digits in the last
// limb.
places += (nrdx - (idx + 1)) * BC_BASE_DIGS;
mod = places % 3;
// Calculate places if we are in engineering mode.
if (eng && mod != 0) places += 3 - mod;
// Shift the temp to the right place.
bc_num_shiftLeft(&temp, places);
}
else {
// This is the number of digits that we are supposed to put behind the
// decimal point.
places = bc_num_intDigits(n) - 1;
// Calculate the true number based on whether engineering mode is
// activated.
mod = places % 3;
if (eng && mod != 0) places -= 3 - (3 - mod);
// Shift the temp to the right place.
bc_num_shiftRight(&temp, places);
}
// Print the shifted number.
bc_num_printDecimal(&temp, newline);
// Print the e.
bc_num_putchar('e', !newline);
// Need to explicitly print a zero exponent.
if (!places) {
bc_num_printHex(0, 1, false, !newline);
goto exit;
}
// Need to print sign for the exponent.
if (neg) bc_num_putchar('-', true);
// Create a temporary for the exponent...
bc_num_setup(&exp, digs, BC_NUM_BIGDIG_LOG10);
bc_num_bigdig2num(&exp, (BcBigDig) places);
/// ..and print it.
bc_num_printDecimal(&exp, newline);
exit:
BC_SIG_MAYLOCK;
bc_num_free(&temp);
BC_LONGJMP_CONT;
}
#endif // BC_ENABLE_EXTRA_MATH
/**
* Converts a number from limbs with base BC_BASE_POW to base @a pow, where
* @a pow is obase^N.
* @param n The number to convert.
* @param rem BC_BASE_POW - @a pow.
* @param pow The power of obase we will convert the number to.
* @param idx The index of the number to start converting at. Doing the
* conversion is O(n^2); we have to sweep through starting at the
* least significant limb
*/
static void bc_num_printFixup(BcNum *restrict n, BcBigDig rem,
BcBigDig pow, size_t idx)
{
size_t i, len = n->len - idx;
BcBigDig acc;
BcDig *a = n->num + idx;
// Ignore if there's just one limb left. This is the part that requires the
// extra loop after the one calling this function in bc_num_printPrepare().
if (len < 2) return;
// Loop through the remaining limbs and convert. We start at the second limb
// because we pull the value from the previous one as well.
for (i = len - 1; i > 0; --i) {
// Get the limb and add it to the previous, along with multiplying by
// the remainder because that's the proper overflow. "acc" means
// "accumulator," by the way.
acc = ((BcBigDig) a[i]) * rem + ((BcBigDig) a[i - 1]);
// Store a value in base pow in the previous limb.
a[i - 1] = (BcDig) (acc % pow);
// Divide by the base and accumulate the remaining value in the limb.
acc /= pow;
acc += (BcBigDig) a[i];
// If the accumulator is greater than the base...
if (acc >= BC_BASE_POW) {
// Do we need to grow?
if (i == len - 1) {
// Grow.
len = bc_vm_growSize(len, 1);
bc_num_expand(n, bc_vm_growSize(len, idx));
// Update the pointer because it may have moved.
a = n->num + idx;
// Zero out the last limb.
a[len - 1] = 0;
}
// Overflow into the next limb since we are over the base.
a[i + 1] += acc / BC_BASE_POW;
acc %= BC_BASE_POW;
}
assert(acc < BC_BASE_POW);
// Set the limb.
a[i] = (BcDig) acc;
}
// We may have grown the number, so adjust the length.
n->len = len + idx;
}
/**
* Prepares a number for printing in a base that is not a divisor of
* BC_BASE_POW. This basically converts the number from having limbs of base
* BC_BASE_POW to limbs of pow, where pow is obase^N.
* @param n The number to prepare for printing.
* @param rem The remainder of BC_BASE_POW when divided by a power of the base.
* @param pow The power of the base.
*/
static void bc_num_printPrepare(BcNum *restrict n, BcBigDig rem, BcBigDig pow) {
size_t i;
// Loop from the least significant limb to the most significant limb and
// convert limbs in each pass.
for (i = 0; i < n->len; ++i) bc_num_printFixup(n, rem, pow, i);
// bc_num_printFixup() does not do everything it is supposed to, so we do
// the last bit of cleanup here. That cleanup is to ensure that each limb
// is less than pow and to expand the number to fit new limbs as necessary.
for (i = 0; i < n->len; ++i) {
assert(pow == ((BcBigDig) ((BcDig) pow)));
// If the limb needs fixing...
if (n->num[i] >= (BcDig) pow) {
// Do we need to grow?
if (i + 1 == n->len) {
// Grow the number.
n->len = bc_vm_growSize(n->len, 1);
bc_num_expand(n, n->len);
// Without this, we might use uninitialized data.
n->num[i + 1] = 0;
}
assert(pow < BC_BASE_POW);
// Overflow into the next limb.
n->num[i + 1] += n->num[i] / ((BcDig) pow);
n->num[i] %= (BcDig) pow;
}
}
}
static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len,
BcNumDigitOp print, bool newline)
{
BcVec stack;
BcNum intp, fracp1, fracp2, digit, flen1, flen2, *n1, *n2, *temp;
BcBigDig dig = 0, *ptr, acc, exp;
size_t i, j, nrdx, idigits;
bool radix;
BcDig digit_digs[BC_NUM_BIGDIG_LOG10 + 1];
assert(base > 1);
// Easy case. Even with scale, we just print this.
if (BC_NUM_ZERO(n)) {
print(0, len, false, !newline);
return;
}
// This function uses an algorithm that Stefan Esser came
// up with to print the integer part of a number. What it does is convert
// intp into a number of the specified base, but it does it directly,
// instead of just doing a series of divisions and printing the remainders
// in reverse order.
//
// Let me explain in a bit more detail:
//
// The algorithm takes the current least significant limb (after intp has
// been converted to an integer) and the next to least significant limb, and
// it converts the least significant limb into one of the specified base,
// putting any overflow into the next to least significant limb. It iterates
// through the whole number, from least significant to most significant,
// doing this conversion. At the end of that iteration, the least
// significant limb is converted, but the others are not, so it iterates
// again, starting at the next to least significant limb. It keeps doing
// that conversion, skipping one more limb than the last time, until all
// limbs have been converted. Then it prints them in reverse order.
//
// That is the gist of the algorithm. It leaves out several things, such as
// the fact that limbs are not always converted into the specified base, but
// into something close, basically a power of the specified base. In
// Stefan's words, "You could consider BcDigs to be of base 10^BC_BASE_DIGS
// in the normal case and obase^N for the largest value of N that satisfies
// obase^N <= 10^BC_BASE_DIGS. [This means that] the result is not in base
// "obase", but in base "obase^N", which happens to be printable as a number
// of base "obase" without consideration for neighbouring BcDigs." This fact
// is what necessitates the existence of the loop later in this function.
//
// The conversion happens in bc_num_printPrepare() where the outer loop
// happens and bc_num_printFixup() where the inner loop, or actual
// conversion, happens. In other words, bc_num_printPrepare() is where the
// loop that starts at the least significant limb and goes to the most
// significant limb. Then, on every iteration of its loop, it calls
// bc_num_printFixup(), which has the inner loop of actually converting
// the limbs it passes into limbs of base obase^N rather than base
// BC_BASE_POW.
nrdx = BC_NUM_RDX_VAL(n);
BC_SIG_LOCK;
// The stack is what allows us to reverse the digits for printing.
bc_vec_init(&stack, sizeof(BcBigDig), BC_DTOR_NONE);
bc_num_init(&fracp1, nrdx);
// intp will be the "integer part" of the number, so copy it.
bc_num_createCopy(&intp, n);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// Make intp an integer.
bc_num_truncate(&intp, intp.scale);
// Get the fractional part out.
bc_num_sub(n, &intp, &fracp1, 0);
// If the base is not the same as the last base used for printing, we need
// to update the cached exponent and power. Yes, we cache the values of the
// exponent and power. That is to prevent us from calculating them every
// time because printing will probably happen multiple times on the same
// base.
if (base != vm.last_base) {
vm.last_pow = 1;
vm.last_exp = 0;
// Calculate the exponent and power.
while (vm.last_pow * base <= BC_BASE_POW) {
vm.last_pow *= base;
vm.last_exp += 1;
}
// Also, the remainder and base itself.
vm.last_rem = BC_BASE_POW - vm.last_pow;
vm.last_base = base;
}
exp = vm.last_exp;
// If vm.last_rem is 0, then the base we are printing in is a divisor of
// BC_BASE_POW, which is the easy case because it means that BC_BASE_POW is
// a power of obase, and no conversion is needed. If it *is* 0, then we have
// the hard case, and we have to prepare the number for the base.
if (vm.last_rem != 0) bc_num_printPrepare(&intp, vm.last_rem, vm.last_pow);
// After the conversion comes the surprisingly easy part. From here on out,
// this is basically naive code that I wrote, adjusted for the larger bases.
// Fill the stack of digits for the integer part.
for (i = 0; i < intp.len; ++i) {
// Get the limb.
acc = (BcBigDig) intp.num[i];
// Turn the limb into digits of base obase.
for (j = 0; j < exp && (i < intp.len - 1 || acc != 0); ++j)
{
// This condition is true if we are not at the last digit.
if (j != exp - 1) {
dig = acc % base;
acc /= base;
}
else {
dig = acc;
acc = 0;
}
assert(dig < base);
// Push the digit onto the stack.
bc_vec_push(&stack, &dig);
}
assert(acc == 0);
}
// Go through the stack backwards and print each digit.
for (i = 0; i < stack.len; ++i) {
ptr = bc_vec_item_rev(&stack, i);
assert(ptr != NULL);
// While the first three arguments should be self-explanatory, the last
// needs explaining. I don't want to print a newline when the last digit
// to be printed could take the place of the backslash rather than being
// pushed, as a single character, to the next line. That's what that
// last argument does for bc.
print(*ptr, len, false, !newline ||
(n->scale != 0 || i == stack.len - 1));
}
// We are done if there is no fractional part.
if (!n->scale) goto err;
BC_SIG_LOCK;
// Reset the jump because some locals are changing.
BC_UNSETJMP;
bc_num_init(&fracp2, nrdx);
bc_num_setup(&digit, digit_digs, sizeof(digit_digs) / sizeof(BcDig));
bc_num_init(&flen1, BC_NUM_BIGDIG_LOG10);
bc_num_init(&flen2, BC_NUM_BIGDIG_LOG10);
BC_SETJMP_LOCKED(frac_err);
BC_SIG_UNLOCK;
bc_num_one(&flen1);
radix = true;
// Pointers for easy switching.
n1 = &flen1;
n2 = &flen2;
fracp2.scale = n->scale;
BC_NUM_RDX_SET_NP(fracp2, BC_NUM_RDX(fracp2.scale));
// As long as we have not reached the scale of the number, keep printing.
while ((idigits = bc_num_intDigits(n1)) <= n->scale) {
// These numbers will keep growing.
bc_num_expand(&fracp2, fracp1.len + 1);
bc_num_mulArray(&fracp1, base, &fracp2);
nrdx = BC_NUM_RDX_VAL_NP(fracp2);
// Ensure an invariant.
if (fracp2.len < nrdx) fracp2.len = nrdx;
// fracp is guaranteed to be non-negative and small enough.
dig = bc_num_bigdig2(&fracp2);
// Convert the digit to a number and subtract it from the number.
bc_num_bigdig2num(&digit, dig);
bc_num_sub(&fracp2, &digit, &fracp1, 0);
// While the first three arguments should be self-explanatory, the last
// needs explaining. I don't want to print a newline when the last digit
// to be printed could take the place of the backslash rather than being
// pushed, as a single character, to the next line. That's what that
// last argument does for bc.
print(dig, len, radix, !newline || idigits != n->scale);
// Update the multipliers.
bc_num_mulArray(n1, base, n2);
radix = false;
// Switch.
temp = n1;
n1 = n2;
n2 = temp;
}
frac_err:
BC_SIG_MAYLOCK;
bc_num_free(&flen2);
bc_num_free(&flen1);
bc_num_free(&fracp2);
err:
BC_SIG_MAYLOCK;
bc_num_free(&fracp1);
bc_num_free(&intp);
bc_vec_free(&stack);
BC_LONGJMP_CONT;
}
/**
* Prints a number in the specified base, or rather, figures out which function
* to call to print the number in the specified base and calls it.
* @param n The number to print.
* @param base The base to print in.
* @param newline Whether to print backslash+newlines on long enough lines.
*/
static void bc_num_printBase(BcNum *restrict n, BcBigDig base, bool newline) {
size_t width;
BcNumDigitOp print;
bool neg = BC_NUM_NEG(n);
- // Just take care of the sign right here.
- if (neg) bc_num_putchar('-', true);
-
// Clear the sign because it makes the actual printing easier when we have
// to do math.
BC_NUM_NEG_CLR(n);
// Bases at hexadecimal and below are printed as one character, larger bases
// are printed as a series of digits separated by spaces.
if (base <= BC_NUM_MAX_POSIX_IBASE) {
width = 1;
print = bc_num_printHex;
}
else {
assert(base <= BC_BASE_POW);
width = bc_num_log10(base - 1);
print = bc_num_printDigits;
}
// Print.
bc_num_printNum(n, base, width, print, newline);
// Reset the sign.
n->rdx = BC_NUM_NEG_VAL(n, neg);
}
#if !BC_ENABLE_LIBRARY
void bc_num_stream(BcNum *restrict n) {
bc_num_printNum(n, BC_NUM_STREAM_BASE, 1, bc_num_printChar, false);
}
#endif // !BC_ENABLE_LIBRARY
void bc_num_setup(BcNum *restrict n, BcDig *restrict num, size_t cap) {
assert(n != NULL);
n->num = num;
n->cap = cap;
bc_num_zero(n);
}
void bc_num_init(BcNum *restrict n, size_t req) {
BcDig *num;
BC_SIG_ASSERT_LOCKED;
assert(n != NULL);
// BC_NUM_DEF_SIZE is set to be about the smallest allocation size that
// malloc() returns in practice, so just use it.
req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE;
// If we can't use a temp, allocate.
if (req != BC_NUM_DEF_SIZE || (num = bc_vm_takeTemp()) == NULL)
num = bc_vm_malloc(BC_NUM_SIZE(req));
bc_num_setup(n, num, req);
}
void bc_num_clear(BcNum *restrict n) {
n->num = NULL;
n->cap = 0;
}
void bc_num_free(void *num) {
BcNum *n = (BcNum*) num;
BC_SIG_ASSERT_LOCKED;
assert(n != NULL);
if (n->cap == BC_NUM_DEF_SIZE) bc_vm_addTemp(n->num);
else free(n->num);
}
void bc_num_copy(BcNum *d, const BcNum *s) {
assert(d != NULL && s != NULL);
if (d == s) return;
bc_num_expand(d, s->len);
d->len = s->len;
// I can just copy directly here because the sign *and* rdx will be
// properly preserved.
d->rdx = s->rdx;
d->scale = s->scale;
memcpy(d->num, s->num, BC_NUM_SIZE(d->len));
}
void bc_num_createCopy(BcNum *d, const BcNum *s) {
BC_SIG_ASSERT_LOCKED;
bc_num_init(d, s->len);
bc_num_copy(d, s);
}
void bc_num_createFromBigdig(BcNum *restrict n, BcBigDig val) {
BC_SIG_ASSERT_LOCKED;
bc_num_init(n, BC_NUM_BIGDIG_LOG10);
bc_num_bigdig2num(n, val);
}
size_t bc_num_scale(const BcNum *restrict n) {
return n->scale;
}
size_t bc_num_len(const BcNum *restrict n) {
size_t len = n->len;
// Always return at least 1.
if (BC_NUM_ZERO(n)) return n->scale ? n->scale : 1;
// If this is true, there is no integer portion of the number.
if (BC_NUM_RDX_VAL(n) == len) {
// We have to take into account the fact that some of the digits right
// after the decimal could be zero. If that is the case, we need to
// ignore them until we hit the first non-zero digit.
size_t zero, scale;
// The number of limbs with non-zero digits.
len = bc_num_nonZeroLen(n);
// Get the number of digits in the last limb.
scale = n->scale % BC_BASE_DIGS;
scale = scale ? scale : BC_BASE_DIGS;
// Get the number of zero digits.
zero = bc_num_zeroDigits(n->num + len - 1);
// Calculate the true length.
len = len * BC_BASE_DIGS - zero - (BC_BASE_DIGS - scale);
}
// Otherwise, count the number of int digits and return that plus the scale.
else len = bc_num_intDigits(n) + n->scale;
return len;
}
void bc_num_parse(BcNum *restrict n, const char *restrict val, BcBigDig base) {
assert(n != NULL && val != NULL && base);
assert(base >= BC_NUM_MIN_BASE && base <= vm.maxes[BC_PROG_GLOBALS_IBASE]);
assert(bc_num_strValid(val));
// A one character number is *always* parsed as though the base was the
// maximum allowed ibase, per the bc spec.
if (!val[1]) {
BcBigDig dig = bc_num_parseChar(val[0], BC_NUM_MAX_LBASE);
bc_num_bigdig2num(n, dig);
}
else if (base == BC_BASE) bc_num_parseDecimal(n, val);
else bc_num_parseBase(n, val, base);
assert(BC_NUM_RDX_VALID(n));
}
void bc_num_print(BcNum *restrict n, BcBigDig base, bool newline) {
assert(n != NULL);
assert(BC_ENABLE_EXTRA_MATH || base >= BC_NUM_MIN_BASE);
// We may need a newline, just to start.
bc_num_printNewline();
+ if (BC_NUM_NONZERO(n)) {
+
+ // Print the sign.
+ if (BC_NUM_NEG(n)) bc_num_putchar('-', true);
+
+ // Print the leading zero if necessary.
+ if (BC_Z && BC_NUM_RDX_VAL(n) == n->len)
+ bc_num_printHex(0, 1, false, !newline);
+ }
+
// Short-circuit 0.
if (BC_NUM_ZERO(n)) bc_num_printHex(0, 1, false, !newline);
else if (base == BC_BASE) bc_num_printDecimal(n, newline);
#if BC_ENABLE_EXTRA_MATH
else if (base == 0 || base == 1)
bc_num_printExponent(n, base != 0, newline);
#endif // BC_ENABLE_EXTRA_MATH
else bc_num_printBase(n, base, newline);
if (newline) bc_num_putchar('\n', false);
}
BcBigDig bc_num_bigdig2(const BcNum *restrict n) {
// This function returns no errors because it's guaranteed to succeed if
// its preconditions are met. Those preconditions include both n needs to
// be non-NULL, n being non-negative, and n being less than vm.max. If all
// of that is true, then we can just convert without worrying about negative
// errors or overflow.
BcBigDig r = 0;
size_t nrdx = BC_NUM_RDX_VAL(n);
assert(n != NULL);
assert(!BC_NUM_NEG(n));
assert(bc_num_cmp(n, &vm.max) < 0);
assert(n->len - nrdx <= 3);
// There is a small speed win from unrolling the loop here, and since it
// only adds 53 bytes, I decided that it was worth it.
switch (n->len - nrdx) {
case 3:
{
r = (BcBigDig) n->num[nrdx + 2];
}
// Fallthrough.
BC_FALLTHROUGH
case 2:
{
r = r * BC_BASE_POW + (BcBigDig) n->num[nrdx + 1];
}
// Fallthrough.
BC_FALLTHROUGH
case 1:
{
r = r * BC_BASE_POW + (BcBigDig) n->num[nrdx];
}
}
return r;
}
BcBigDig bc_num_bigdig(const BcNum *restrict n) {
assert(n != NULL);
// This error checking is extremely important, and if you do not have a
// guarantee that converting a number will always succeed in a particular
// case, you *must* call this function to get these error checks. This
// includes all instances of numbers inputted by the user or calculated by
// the user. Otherwise, you can call the faster bc_num_bigdig2().
if (BC_ERR(BC_NUM_NEG(n))) bc_err(BC_ERR_MATH_NEGATIVE);
if (BC_ERR(bc_num_cmp(n, &vm.max) >= 0)) bc_err(BC_ERR_MATH_OVERFLOW);
return bc_num_bigdig2(n);
}
void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val) {
BcDig *ptr;
size_t i;
assert(n != NULL);
bc_num_zero(n);
// Already 0.
if (!val) return;
// Expand first. This is the only way this function can fail, and it's a
// fatal error.
bc_num_expand(n, BC_NUM_BIGDIG_LOG10);
// The conversion is easy because numbers are laid out in little-endian
// order.
for (ptr = n->num, i = 0; val; ++i, val /= BC_BASE_POW)
ptr[i] = val % BC_BASE_POW;
n->len = i;
}
#if BC_ENABLE_EXTRA_MATH
void bc_num_rng(const BcNum *restrict n, BcRNG *rng) {
BcNum temp, temp2, intn, frac;
BcRand state1, state2, inc1, inc2;
size_t nrdx = BC_NUM_RDX_VAL(n);
// This function holds the secret of how I interpret a seed number for the
// PRNG. Well, it's actually in the development manual
// (manuals/development.md#pseudo-random-number-generator), so look there
// before you try to understand this.
BC_SIG_LOCK;
bc_num_init(&temp, n->len);
bc_num_init(&temp2, n->len);
bc_num_init(&frac, nrdx);
bc_num_init(&intn, bc_num_int(n));
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
assert(BC_NUM_RDX_VALID_NP(vm.max));
memcpy(frac.num, n->num, BC_NUM_SIZE(nrdx));
frac.len = nrdx;
BC_NUM_RDX_SET_NP(frac, nrdx);
frac.scale = n->scale;
assert(BC_NUM_RDX_VALID_NP(frac));
assert(BC_NUM_RDX_VALID_NP(vm.max2));
// Multiply the fraction and truncate so that it's an integer. The
// truncation is what clamps it, by the way.
bc_num_mul(&frac, &vm.max2, &temp, 0);
bc_num_truncate(&temp, temp.scale);
bc_num_copy(&frac, &temp);
// Get the integer.
memcpy(intn.num, n->num + nrdx, BC_NUM_SIZE(bc_num_int(n)));
intn.len = bc_num_int(n);
// This assert is here because it has to be true. It is also here to justify
// some optimizations.
assert(BC_NUM_NONZERO(&vm.max));
// If there *was* a fractional part...
if (BC_NUM_NONZERO(&frac)) {
// This divmod splits frac into the two state parts.
bc_num_divmod(&frac, &vm.max, &temp, &temp2, 0);
// frac is guaranteed to be smaller than vm.max * vm.max (pow).
// This means that when dividing frac by vm.max, as above, the
// quotient and remainder are both guaranteed to be less than vm.max,
// which means we can use bc_num_bigdig2() here and not worry about
// overflow.
state1 = (BcRand) bc_num_bigdig2(&temp2);
state2 = (BcRand) bc_num_bigdig2(&temp);
}
else state1 = state2 = 0;
// If there *was* an integer part...
if (BC_NUM_NONZERO(&intn)) {
// This divmod splits intn into the two inc parts.
bc_num_divmod(&intn, &vm.max, &temp, &temp2, 0);
// Because temp2 is the mod of vm.max, from above, it is guaranteed
// to be small enough to use bc_num_bigdig2().
inc1 = (BcRand) bc_num_bigdig2(&temp2);
// Clamp the second inc part.
if (bc_num_cmp(&temp, &vm.max) >= 0) {
bc_num_copy(&temp2, &temp);
bc_num_mod(&temp2, &vm.max, &temp, 0);
}
// The if statement above ensures that temp is less than vm.max, which
// means that we can use bc_num_bigdig2() here.
inc2 = (BcRand) bc_num_bigdig2(&temp);
}
else inc1 = inc2 = 0;
bc_rand_seed(rng, state1, state2, inc1, inc2);
err:
BC_SIG_MAYLOCK;
bc_num_free(&intn);
bc_num_free(&frac);
bc_num_free(&temp2);
bc_num_free(&temp);
BC_LONGJMP_CONT;
}
void bc_num_createFromRNG(BcNum *restrict n, BcRNG *rng) {
BcRand s1, s2, i1, i2;
BcNum conv, temp1, temp2, temp3;
BcDig temp1_num[BC_RAND_NUM_SIZE], temp2_num[BC_RAND_NUM_SIZE];
BcDig conv_num[BC_NUM_BIGDIG_LOG10];
BC_SIG_LOCK;
bc_num_init(&temp3, 2 * BC_RAND_NUM_SIZE);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
bc_num_setup(&temp1, temp1_num, sizeof(temp1_num) / sizeof(BcDig));
bc_num_setup(&temp2, temp2_num, sizeof(temp2_num) / sizeof(BcDig));
bc_num_setup(&conv, conv_num, sizeof(conv_num) / sizeof(BcDig));
// This assert is here because it has to be true. It is also here to justify
// the assumption that vm.max is not zero.
assert(BC_NUM_NONZERO(&vm.max));
// Because this is true, we can just ignore math errors that would happen
// otherwise.
assert(BC_NUM_NONZERO(&vm.max2));
bc_rand_getRands(rng, &s1, &s2, &i1, &i2);
// Put the second piece of state into a number.
bc_num_bigdig2num(&conv, (BcBigDig) s2);
assert(BC_NUM_RDX_VALID_NP(conv));
// Multiply by max to make room for the first piece of state.
bc_num_mul(&conv, &vm.max, &temp1, 0);
// Add in the first piece of state.
bc_num_bigdig2num(&conv, (BcBigDig) s1);
bc_num_add(&conv, &temp1, &temp2, 0);
// Divide to make it an entirely fractional part.
bc_num_div(&temp2, &vm.max2, &temp3, BC_RAND_STATE_BITS);
// Now start on the increment parts. It's the same process without the
// divide, so put the second piece of increment into a number.
bc_num_bigdig2num(&conv, (BcBigDig) i2);
assert(BC_NUM_RDX_VALID_NP(conv));
// Multiply by max to make room for the first piece of increment.
bc_num_mul(&conv, &vm.max, &temp1, 0);
// Add in the first piece of increment.
bc_num_bigdig2num(&conv, (BcBigDig) i1);
bc_num_add(&conv, &temp1, &temp2, 0);
// Now add the two together.
bc_num_add(&temp2, &temp3, n, 0);
assert(BC_NUM_RDX_VALID(n));
err:
BC_SIG_MAYLOCK;
bc_num_free(&temp3);
BC_LONGJMP_CONT;
}
void bc_num_irand(BcNum *restrict a, BcNum *restrict b, BcRNG *restrict rng) {
BcNum atemp;
size_t i, len;
assert(a != b);
if (BC_ERR(BC_NUM_NEG(a))) bc_err(BC_ERR_MATH_NEGATIVE);
// If either of these are true, then the numbers are integers.
if (BC_NUM_ZERO(a) || BC_NUM_ONE(a)) return;
if (BC_ERR(bc_num_nonInt(a, &atemp))) bc_err(BC_ERR_MATH_NON_INTEGER);
assert(atemp.len);
len = atemp.len - 1;
// Just generate a random number for each limb.
for (i = 0; i < len; ++i)
b->num[i] = (BcDig) bc_rand_bounded(rng, BC_BASE_POW);
// Do the last digit explicitly because the bound must be right. But only
// do it if the limb does not equal 1. If it does, we have already hit the
// limit.
if (atemp.num[i] != 1) {
b->num[i] = (BcDig) bc_rand_bounded(rng, (BcRand) atemp.num[i]);
b->len = atemp.len;
}
// We want 1 less len in the case where we skip the last limb.
else b->len = len;
bc_num_clean(b);
assert(BC_NUM_RDX_VALID(b));
}
#endif // BC_ENABLE_EXTRA_MATH
size_t bc_num_addReq(const BcNum *a, const BcNum *b, size_t scale) {
size_t aint, bint, ardx, brdx;
// Addition and subtraction require the max of the length of the two numbers
// plus 1.
BC_UNUSED(scale);
ardx = BC_NUM_RDX_VAL(a);
aint = bc_num_int(a);
assert(aint <= a->len && ardx <= a->len);
brdx = BC_NUM_RDX_VAL(b);
bint = bc_num_int(b);
assert(bint <= b->len && brdx <= b->len);
ardx = BC_MAX(ardx, brdx);
aint = BC_MAX(aint, bint);
return bc_vm_growSize(bc_vm_growSize(ardx, aint), 1);
}
size_t bc_num_mulReq(const BcNum *a, const BcNum *b, size_t scale) {
size_t max, rdx;
// Multiplication requires the sum of the lengths of the numbers.
rdx = bc_vm_growSize(BC_NUM_RDX_VAL(a), BC_NUM_RDX_VAL(b));
max = BC_NUM_RDX(scale);
max = bc_vm_growSize(BC_MAX(max, rdx), 1);
rdx = bc_vm_growSize(bc_vm_growSize(bc_num_int(a), bc_num_int(b)), max);
return rdx;
}
size_t bc_num_divReq(const BcNum *a, const BcNum *b, size_t scale) {
size_t max, rdx;
// Division requires the length of the dividend plus the scale.
rdx = bc_vm_growSize(BC_NUM_RDX_VAL(a), BC_NUM_RDX_VAL(b));
max = BC_NUM_RDX(scale);
max = bc_vm_growSize(BC_MAX(max, rdx), 1);
rdx = bc_vm_growSize(bc_num_int(a), max);
return rdx;
}
size_t bc_num_powReq(const BcNum *a, const BcNum *b, size_t scale) {
BC_UNUSED(scale);
return bc_vm_growSize(bc_vm_growSize(a->len, b->len), 1);
}
#if BC_ENABLE_EXTRA_MATH
size_t bc_num_placesReq(const BcNum *a, const BcNum *b, size_t scale) {
BC_UNUSED(scale);
return a->len + b->len - BC_NUM_RDX_VAL(a) - BC_NUM_RDX_VAL(b);
}
#endif // BC_ENABLE_EXTRA_MATH
void bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, false, bc_num_as, bc_num_addReq(a, b, scale));
}
void bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, true, bc_num_as, bc_num_addReq(a, b, scale));
}
void bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, scale, bc_num_m, bc_num_mulReq(a, b, scale));
}
void bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, scale, bc_num_d, bc_num_divReq(a, b, scale));
}
void bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, scale, bc_num_rem, bc_num_divReq(a, b, scale));
}
void bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, scale, bc_num_p, bc_num_powReq(a, b, scale));
}
#if BC_ENABLE_EXTRA_MATH
void bc_num_places(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, scale, bc_num_place, bc_num_placesReq(a, b, scale));
}
void bc_num_lshift(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, scale, bc_num_left, bc_num_placesReq(a, b, scale));
}
void bc_num_rshift(BcNum *a, BcNum *b, BcNum *c, size_t scale) {
assert(BC_NUM_RDX_VALID(a));
assert(BC_NUM_RDX_VALID(b));
bc_num_binary(a, b, c, scale, bc_num_right, bc_num_placesReq(a, b, scale));
}
#endif // BC_ENABLE_EXTRA_MATH
void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) {
BcNum num1, num2, half, f, fprime, *x0, *x1, *temp;
size_t pow, len, rdx, req, resscale;
BcDig half_digs[1];
assert(a != NULL && b != NULL && a != b);
if (BC_ERR(BC_NUM_NEG(a))) bc_err(BC_ERR_MATH_NEGATIVE);
// We want to calculate to a's scale if it is bigger so that the result will
// truncate properly.
if (a->scale > scale) scale = a->scale;
// Set parameters for the result.
len = bc_vm_growSize(bc_num_intDigits(a), 1);
rdx = BC_NUM_RDX(scale);
// Square root needs half of the length of the parameter.
req = bc_vm_growSize(BC_MAX(rdx, BC_NUM_RDX_VAL(a)), len >> 1);
BC_SIG_LOCK;
// Unlike the binary operators, this function is the only single parameter
// function and is expected to initialize the result. This means that it
// expects that b is *NOT* preallocated. We allocate it here.
bc_num_init(b, bc_vm_growSize(req, 1));
BC_SIG_UNLOCK;
assert(a != NULL && b != NULL && a != b);
assert(a->num != NULL && b->num != NULL);
// Easy case.
if (BC_NUM_ZERO(a)) {
bc_num_setToZero(b, scale);
return;
}
// Another easy case.
if (BC_NUM_ONE(a)) {
bc_num_one(b);
bc_num_extend(b, scale);
return;
}
// Set the parameters again.
rdx = BC_NUM_RDX(scale);
rdx = BC_MAX(rdx, BC_NUM_RDX_VAL(a));
len = bc_vm_growSize(a->len, rdx);
BC_SIG_LOCK;
bc_num_init(&num1, len);
bc_num_init(&num2, len);
bc_num_setup(&half, half_digs, sizeof(half_digs) / sizeof(BcDig));
// There is a division by two in the formula. We setup a number that's 1/2
// so that we can use multiplication instead of heavy division.
bc_num_one(&half);
half.num[0] = BC_BASE_POW / 2;
half.len = 1;
BC_NUM_RDX_SET_NP(half, 1);
half.scale = 1;
bc_num_init(&f, len);
bc_num_init(&fprime, len);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// Pointers for easy switching.
x0 = &num1;
x1 = &num2;
// Start with 1.
bc_num_one(x0);
// The power of the operand is needed for the estimate.
pow = bc_num_intDigits(a);
// The code in this if statement calculates the initial estimate. First, if
// a is less than 0, then 0 is a good estimate. Otherwise, we want something
// in the same ballpark. That ballpark is pow.
if (pow) {
// An odd number is served by starting with 2^((pow-1)/2), and an even
// number is served by starting with 6^((pow-2)/2). Why? Because math.
if (pow & 1) x0->num[0] = 2;
else x0->num[0] = 6;
pow -= 2 - (pow & 1);
bc_num_shiftLeft(x0, pow / 2);
}
// I can set the rdx here directly because neg should be false.
x0->scale = x0->rdx = 0;
resscale = (scale + BC_BASE_DIGS) + 2;
// This is the calculation loop. This compare goes to 0 eventually as the
// difference between the two numbers gets smaller than resscale.
while (bc_num_cmp(x1, x0)) {
assert(BC_NUM_NONZERO(x0));
// This loop directly corresponds to the iteration in Newton's method.
// If you know the formula, this loop makes sense. Go study the formula.
bc_num_div(a, x0, &f, resscale);
bc_num_add(x0, &f, &fprime, resscale);
assert(BC_NUM_RDX_VALID_NP(fprime));
assert(BC_NUM_RDX_VALID_NP(half));
bc_num_mul(&fprime, &half, x1, resscale);
// Switch.
temp = x0;
x0 = x1;
x1 = temp;
}
// Copy to the result and truncate.
bc_num_copy(b, x0);
if (b->scale > scale) bc_num_truncate(b, b->scale - scale);
assert(!BC_NUM_NEG(b) || BC_NUM_NONZERO(b));
assert(BC_NUM_RDX_VALID(b));
assert(BC_NUM_RDX_VAL(b) <= b->len || !b->len);
assert(!b->len || b->num[b->len - 1] || BC_NUM_RDX_VAL(b) == b->len);
err:
BC_SIG_MAYLOCK;
bc_num_free(&fprime);
bc_num_free(&f);
bc_num_free(&num2);
bc_num_free(&num1);
BC_LONGJMP_CONT;
}
void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale) {
size_t ts, len;
BcNum *ptr_a, num2;
bool init = false;
// The bulk of this function is just doing what bc_num_binary() does for the
// binary operators. However, it assumes that only c and a can be equal.
// Set up the parameters.
ts = BC_MAX(scale + b->scale, a->scale);
len = bc_num_mulReq(a, b, ts);
assert(a != NULL && b != NULL && c != NULL && d != NULL);
assert(c != d && a != d && b != d && b != c);
// Initialize or expand as necessary.
if (c == a) {
memcpy(&num2, c, sizeof(BcNum));
ptr_a = &num2;
BC_SIG_LOCK;
bc_num_init(c, len);
init = true;
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
}
else {
ptr_a = a;
bc_num_expand(c, len);
}
// Do the quick version if possible.
if (BC_NUM_NONZERO(a) && !BC_NUM_RDX_VAL(a) &&
!BC_NUM_RDX_VAL(b) && b->len == 1 && !scale)
{
BcBigDig rem;
bc_num_divArray(ptr_a, (BcBigDig) b->num[0], c, &rem);
assert(rem < BC_BASE_POW);
d->num[0] = (BcDig) rem;
d->len = (rem != 0);
}
// Do the slow method.
else bc_num_r(ptr_a, b, c, d, scale, ts);
assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c));
assert(BC_NUM_RDX_VALID(c));
assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len);
assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len);
assert(!BC_NUM_NEG(d) || BC_NUM_NONZERO(d));
assert(BC_NUM_RDX_VALID(d));
assert(BC_NUM_RDX_VAL(d) <= d->len || !d->len);
assert(!d->len || d->num[d->len - 1] || BC_NUM_RDX_VAL(d) == d->len);
err:
// Only cleanup if we initialized.
if (init) {
BC_SIG_MAYLOCK;
bc_num_free(&num2);
BC_LONGJMP_CONT;
}
}
void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d) {
BcNum base, exp, two, temp, atemp, btemp, ctemp;
BcDig two_digs[2];
assert(a != NULL && b != NULL && c != NULL && d != NULL);
assert(a != d && b != d && c != d);
if (BC_ERR(BC_NUM_ZERO(c))) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO);
if (BC_ERR(BC_NUM_NEG(b))) bc_err(BC_ERR_MATH_NEGATIVE);
#ifndef NDEBUG
// This is entirely for quieting a useless scan-build error.
btemp.len = 0;
ctemp.len = 0;
#endif // NDEBUG
// Eliminate fractional parts that are zero or error if they are not zero.
if (BC_ERR(bc_num_nonInt(a, &atemp) || bc_num_nonInt(b, &btemp) ||
bc_num_nonInt(c, &ctemp)))
{
bc_err(BC_ERR_MATH_NON_INTEGER);
}
bc_num_expand(d, ctemp.len);
BC_SIG_LOCK;
bc_num_init(&base, ctemp.len);
bc_num_setup(&two, two_digs, sizeof(two_digs) / sizeof(BcDig));
bc_num_init(&temp, btemp.len + 1);
bc_num_createCopy(&exp, &btemp);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
bc_num_one(&two);
two.num[0] = 2;
bc_num_one(d);
// We already checked for 0.
bc_num_rem(&atemp, &ctemp, &base, 0);
// If you know the algorithm I used, the memory-efficient method, then this
// loop should be self-explanatory because it is the calculation loop.
while (BC_NUM_NONZERO(&exp)) {
// Num two cannot be 0, so no errors.
bc_num_divmod(&exp, &two, &exp, &temp, 0);
if (BC_NUM_ONE(&temp) && !BC_NUM_NEG_NP(temp)) {
assert(BC_NUM_RDX_VALID(d));
assert(BC_NUM_RDX_VALID_NP(base));
bc_num_mul(d, &base, &temp, 0);
// We already checked for 0.
bc_num_rem(&temp, &ctemp, d, 0);
}
assert(BC_NUM_RDX_VALID_NP(base));
bc_num_mul(&base, &base, &temp, 0);
// We already checked for 0.
bc_num_rem(&temp, &ctemp, &base, 0);
}
err:
BC_SIG_MAYLOCK;
bc_num_free(&exp);
bc_num_free(&temp);
bc_num_free(&base);
BC_LONGJMP_CONT;
assert(!BC_NUM_NEG(d) || d->len);
assert(BC_NUM_RDX_VALID(d));
assert(!d->len || d->num[d->len - 1] || BC_NUM_RDX_VAL(d) == d->len);
}
#if BC_DEBUG_CODE
void bc_num_printDebug(const BcNum *n, const char *name, bool emptyline) {
bc_file_puts(&vm.fout, bc_flush_none, name);
bc_file_puts(&vm.fout, bc_flush_none, ": ");
bc_num_printDecimal(n, true);
bc_file_putchar(&vm.fout, bc_flush_err, '\n');
if (emptyline) bc_file_putchar(&vm.fout, bc_flush_err, '\n');
vm.nchars = 0;
}
void bc_num_printDigs(const BcDig *n, size_t len, bool emptyline) {
size_t i;
for (i = len - 1; i < len; --i)
bc_file_printf(&vm.fout, " %lu", (unsigned long) n[i]);
bc_file_putchar(&vm.fout, bc_flush_err, '\n');
if (emptyline) bc_file_putchar(&vm.fout, bc_flush_err, '\n');
vm.nchars = 0;
}
void bc_num_printWithDigs(const BcNum *n, const char *name, bool emptyline) {
bc_file_puts(&vm.fout, bc_flush_none, name);
bc_file_printf(&vm.fout, " len: %zu, rdx: %zu, scale: %zu\n",
name, n->len, BC_NUM_RDX_VAL(n), n->scale);
bc_num_printDigs(n->num, n->len, emptyline);
}
void bc_num_dump(const char *varname, const BcNum *n) {
ulong i, scale = n->scale;
bc_file_printf(&vm.ferr, "\n%s = %s", varname,
n->len ? (BC_NUM_NEG(n) ? "-" : "+") : "0 ");
for (i = n->len - 1; i < n->len; --i) {
if (i + 1 == BC_NUM_RDX_VAL(n))
bc_file_puts(&vm.ferr, bc_flush_none, ". ");
if (scale / BC_BASE_DIGS != BC_NUM_RDX_VAL(n) - i - 1)
bc_file_printf(&vm.ferr, "%lu ", (unsigned long) n->num[i]);
else {
int mod = scale % BC_BASE_DIGS;
int d = BC_BASE_DIGS - mod;
BcDig div;
if (mod != 0) {
div = n->num[i] / ((BcDig) bc_num_pow10[(ulong) d]);
bc_file_printf(&vm.ferr, "%lu", (unsigned long) div);
}
div = n->num[i] % ((BcDig) bc_num_pow10[(ulong) d]);
bc_file_printf(&vm.ferr, " ' %lu ", (unsigned long) div);
}
}
bc_file_printf(&vm.ferr, "(%zu | %zu.%zu / %zu) %lu\n",
n->scale, n->len, BC_NUM_RDX_VAL(n), n->cap,
(unsigned long) (void*) n->num);
bc_file_flush(&vm.ferr, bc_flush_err);
}
#endif // BC_DEBUG_CODE
diff --git a/src/program.c b/src/program.c
index 1ba012e57a5e..1ff9c24f323b 100644
--- a/src/program.c
+++ b/src/program.c
@@ -1,3267 +1,3307 @@
/*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* 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 execute bc programs.
*
*/
#include
#include
#include
#include
#include
#include
#include